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
1019 changed files with 16922 additions and 11125 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: [ '1.21.11' ] branches: [ '1.21.8' ]
permissions: permissions:
contents: read contents: read
+2 -2
View File
@@ -7,8 +7,8 @@ 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.46,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.46,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 '2.1.0' id 'org.barfuin.gradle.taskinfo' version '2.1.0'
} }
+3 -4
View File
@@ -4,10 +4,9 @@ repositories {
} }
dependencies { dependencies {
implementation 'org.ow2.asm:asm:9.8' implementation 'org.ow2.asm:asm:9.9.1'
implementation 'org.ow2.asm:asm-tree:9.8' implementation 'org.ow2.asm:asm-tree:9.9.1'
implementation 'net.minecraftforge:srgutils:0.5.10' 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'
@@ -62,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 + ']';
}
}
}
}
@@ -289,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)
} }
+4 -17
View File
@@ -91,7 +91,7 @@ final String MAVEN_PATH = ext.MAVEN_PATH
final String BINPATCH_TOOL = 'net.minecraftforge:binarypatcher:1.2.0:fatjar' final String BINPATCH_TOOL = 'net.minecraftforge:binarypatcher:1.2.0:fatjar'
final String INSTALLER_TOOLS = 'net.minecraftforge:installertools:1.4.3' 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.
@@ -112,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
@@ -126,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'))
@@ -156,12 +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
}
patcher { patcher {
excs.from file("$rootDir/src/main/resources/forge.exc") excs.from file("$rootDir/src/main/resources/forge.exc")
@@ -306,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 {
@@ -427,7 +414,7 @@ tasks.register('extractInheritance', ExtractInheritance) {
} }
tasks.register("findFinalizeSpawnTargets", BytecodePredicateFinder) { tasks.register("findFinalizeSpawnTargets", BytecodePredicateFinder) {
jar = createClientOfficial.output jar = createClientOfficial.output
output = rootProject.file('forge-transformers/src/main/resources/coremods/finalize_spawn_targets.json') output = rootProject.file('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.
-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'
+2 -2
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=1.21.11-&query=$.promos["1.21.11-recommended"]&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=1.21.11-&query=$.promos["1.21.11-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!
@@ -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;
@@ -158,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
@@ -41,14 +41,14 @@ public class ModList {
private List<ModContainer> sortedContainers; private List<ModContainer> sortedContainers;
private ModList(final List<ModFile> modFiles, final List<ModInfo> sortedList) { private ModList(final List<ModFile> modFiles, final List<ModInfo> sortedList) {
var modFileInfos = this.modFiles = modFiles.stream().map(ModFile::getModFileInfo).toList(); this.modFiles = modFiles.stream().map(ModFile::getModFileInfo).toList();
this.sortedList = sortedList.stream().map(IModInfo.class::cast).toList(); this.sortedList = sortedList.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());
} }
this.fileById = Map.copyOf(byId); this.fileById = Collections.unmodifiableMap(byId);
CrashReportCallables.registerCrashCallable("Mod List", this::crashReport); CrashReportCallables.registerCrashCallable("Mod List", this::crashReport);
} }
@@ -67,7 +67,7 @@ public class ModList {
} }
private String crashReport() { private String crashReport() {
return "\n" + applyForEachModFile(this::fileToLine).collect(Collectors.joining("\n\t\t", "\t\t", "")); return "\n"+applyForEachModFile(this::fileToLine).collect(Collectors.joining("\n\t\t", "\t\t", ""));
} }
public static ModList of(List<ModFile> modFiles, List<ModInfo> sortedList) { public static ModList of(List<ModFile> modFiles, List<ModInfo> sortedList) {
@@ -126,9 +126,10 @@ public class ModList {
map(IModFileInfo::getFile). map(IModFileInfo::getFile).
distinct(). distinct().
map(IModFile::getScanResult). map(IModFile::getScanResult).
toList(); collect(Collectors.toList());
} }
return modFileScanData; return modFileScanData;
} }
public void forEachModFile(Consumer<IModFile> fileConsumer) { public void forEachModFile(Consumer<IModFile> fileConsumer) {
@@ -6,7 +6,6 @@
package net.minecraftforge.fml; package net.minecraftforge.fml;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.fml.event.IModBusEvent; import net.minecraftforge.fml.event.IModBusEvent;
import net.minecraftforge.fml.loading.FMLEnvironment; import net.minecraftforge.fml.loading.FMLEnvironment;
import net.minecraftforge.fml.loading.FMLLoader; import net.minecraftforge.fml.loading.FMLLoader;
@@ -85,20 +84,20 @@ public class ModLoader {
private ModList modList; private ModList modList;
private ModLoader() { private ModLoader() {
var loadingModList = this.loadingModList = FMLLoader.getLoadingModList(); this.loadingModList = FMLLoader.getLoadingModList();
var loadingExceptions = this.loadingExceptions = loadingModList.getErrors().stream() this.loadingExceptions = this.loadingModList.getErrors().stream()
.flatMap(ModLoadingException::fromEarlyException) .flatMap(ModLoadingException::fromEarlyException)
.collect(Collectors.toList()); .collect(Collectors.toList());
this.loadingWarnings = loadingModList.getBrokenFiles().stream() this.loadingWarnings = this.loadingModList.getBrokenFiles().stream()
.map(file -> new ModLoadingWarning(null, ModLoadingStage.VALIDATE, InvalidModIdentifier.identifyJarProblem(file.getFilePath()).orElse("fml.modloading.brokenfile"), file.getFileName())) .map(file -> new ModLoadingWarning(null, ModLoadingStage.VALIDATE, InvalidModIdentifier.identifyJarProblem(file.getFilePath()).orElse("fml.modloading.brokenfile"), file.getFileName()))
.collect(Collectors.toList()); .collect(Collectors.toList());
if (loadingExceptions.isEmpty()) { if (this.loadingExceptions.isEmpty()) {
this.erroredModInfos = Collections.emptySet(); this.erroredModInfos = Collections.emptySet();
} else { } else {
this.erroredModInfos = Collections.newSetFromMap(new IdentityHashMap<>()); this.erroredModInfos = Collections.newSetFromMap(new IdentityHashMap<>());
this.erroredModInfos.addAll(loadingExceptions.stream().map(ModLoadingException::getModInfo).toList()); this.erroredModInfos.addAll(this.loadingExceptions.stream().map(ModLoadingException::getModInfo).toList());
} }
loadingModList.getModFiles().stream() this.loadingModList.getModFiles().stream()
.filter(ModFileInfo::missingLicense) .filter(ModFileInfo::missingLicense)
.filter(modFileInfo -> modFileInfo.getMods().stream().noneMatch(this.erroredModInfos::contains)) //Ignore files where any other mod already encountered an error .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())) .map(modFileInfo -> new ModLoadingException(null, ModLoadingStage.VALIDATE, "fml.modloading.missinglicense", null, modFileInfo.getFile()))
@@ -113,16 +112,16 @@ public class ModLoader {
private static String computeLanguageList() { private static String computeLanguageList() {
return "\n" + FMLLoader.getLanguageLoadingProvider() 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",""));
} }
@@ -233,19 +232,7 @@ public class ModLoader {
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);
statusConsumer.accept("Mod loading complete - %d mods loaded".formatted(this.modList.size()));
progress.complete(); progress.complete();
} }
@@ -267,7 +254,7 @@ public class ModLoader {
} }
private void handleInlineTransition(final Consumer<ModList> 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.accept(this.modList); transition.accept(this.modList);
syncExecutor.drive(ticker); syncExecutor.drive(ticker);
@@ -366,18 +353,12 @@ public class ModLoader {
return loadingStateValid; return loadingStateValid;
} }
/** @deprecated Use {@link #hasCompletedState(IModLoadingState)} instead */
@Deprecated(forRemoval = true)
public boolean hasCompletedState(final String stateName) { public boolean hasCompletedState(final String stateName) {
IModLoadingState state = stateManager.findState(stateName); IModLoadingState state = stateManager.findState(stateName);
return completedStates.contains(state); return completedStates.contains(state);
} }
public boolean hasCompletedState(IModLoadingState state) { public <T extends IModBusEvent> void runEventGenerator(Function<ModContainer, T> generator) {
return completedStates.contains(state);
}
public static <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;
@@ -386,7 +367,8 @@ public class ModLoader {
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;
@@ -395,7 +377,7 @@ public class ModLoader {
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;
@@ -406,14 +388,14 @@ public class ModLoader {
} }
@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, e) -> ModLoadingContext.get().setActiveContainer(mc), (mc, e) -> ModLoadingContext.get().setActiveContainer(mc),
(mc, e) -> 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;
@@ -19,13 +19,7 @@ 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() {
@@ -7,7 +7,6 @@ package net.minecraftforge.fml;
import net.minecraftforge.fml.loading.progress.ProgressMeter; import net.minecraftforge.fml.loading.progress.ProgressMeter;
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.Executor; import java.util.concurrent.Executor;
@@ -60,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, ml -> "", ml -> 0, phase, Optional.empty(), Optional.empty()); return of(name, phase).after(previous).empty();
} }
/** /**
@@ -121,22 +120,6 @@ public record ModLoadingState(
return new Builder(name, phase); return new Builder(name, phase);
} }
@Override
public boolean equals(Object o) {
return o instanceof ModLoadingState that
&& this.phase == that.phase
&& this.name.equals(that.name)
&& Objects.equals(this.previous, that.previous);
}
@Override
public int hashCode() {
int result = phase.hashCode();
result = 31 * result + name.hashCode();
result = 31 * result + Objects.hashCode(previous);
return result;
}
public static class Builder { public static class Builder {
private final String name; private final String name;
private final ModLoadingPhase phase; private final ModLoadingPhase phase;
@@ -41,13 +41,11 @@ public class ModStateManager {
} }
public 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);
} }
} }
@@ -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() { }
} }
+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() {
@@ -56,10 +57,7 @@ public final class CapabilityTokenSubclass implements ILaunchPluginService {
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 YAY;
return internalName.contains("$") ? YAY : NAY; // Anonymous subclasses only
} }
@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;
@@ -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();
@@ -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;
@@ -33,6 +34,7 @@ import static net.minecraftforge.fml.loading.LogMarkers.SCAN;
public 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 LanguageLoadingProvider languageLoadingProvider;
private static Dist dist; private static Dist dist;
private static String naming; private static String naming;
@@ -55,6 +57,8 @@ public 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 {
@@ -92,7 +96,6 @@ public 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(); ) {
@@ -143,8 +146,9 @@ public 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);
} }
@@ -157,6 +161,10 @@ public class FMLLoader {
return List.of(modValidator.getModResources()); return List.of(modValidator.getModResources());
} }
public static ICoreModProvider getCoreModProvider() {
return coreModProvider;
}
public static LanguageLoadingProvider getLanguageLoadingProvider() { public static LanguageLoadingProvider getLanguageLoadingProvider() {
return languageLoadingProvider; return languageLoadingProvider;
} }
@@ -68,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());
} }
} }
@@ -5,12 +5,13 @@
package net.minecraftforge.fml.loading; package net.minecraftforge.fml.loading;
import net.minecraftforge.fml.loading.EarlyLoadingException.ExceptionData; import com.mojang.logging.LogUtils;
import net.minecraftforge.fml.loading.moddiscovery.BackgroundScanHandler; import net.minecraftforge.fml.loading.moddiscovery.BackgroundScanHandler;
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.fml.loading.moddiscovery.ModInfo;
import net.minecraftforge.forgespi.locating.IModFile; import net.minecraftforge.forgespi.locating.IModFile;
import org.slf4j.Logger;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
@@ -20,10 +21,6 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.stream.Collectors; 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 * Master list of all mods <em>in the loading context. This class cannot refer outside the
* loading package</em> * loading package</em>
@@ -42,7 +39,9 @@ public class LoadingModList {
.map(ModFile::getModFileInfo) .map(ModFile::getModFileInfo)
.map(ModFileInfo.class::cast) .map(ModFileInfo.class::cast)
.toList(); .toList();
this.sortedList = sortedList.stream().toList(); this.sortedList = sortedList.stream()
.map(ModInfo.class::cast)
.toList();
this.fileById = this.modFiles.stream() this.fileById = this.modFiles.stream()
.map(ModFileInfo::getMods) .map(ModFileInfo::getMods)
.flatMap(Collection::stream) .flatMap(Collection::stream)
@@ -62,23 +61,31 @@ public class LoadingModList {
return INSTANCE; return INSTANCE;
} }
public void addAccessTransformers() { public void addCoreMods() {
var errors = new ArrayList<ExceptionData>(); modFiles.stream()
.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) { for (ModFileInfo modFile : modFiles) {
ModFile mod = modFile.getFile(); ModFile mod = modFile.getFile();
for (var at : mod.getAccessTransformers()) { for (Path at : mod.getAccessTransformers()) {
if (!Files.exists(at)) { if (!Files.exists(at)) {
var message = "Invalid mod file: " + modFile.getFile().getFileName() + ". Missing Access Transformer: " + at; var message = "Invalid mod file: " + modFile.getFile().getFileName() + ". Missing Access Transformer: " + at;
errors.add(new ExceptionData(message)); errors.add(new EarlyLoadingException.ExceptionData(message));
LOGGER.error(message); LOGGER.error(message);
} else } else {
FMLLoader.addAccessTransformer(at, mod); FMLLoader.addAccessTransformer(at, mod);
}
} }
} }
if (!errors.isEmpty()) {
if (!errors.isEmpty())
preLoadErrors.add(new EarlyLoadingException("Invalid Access Transformers", null, errors)); preLoadErrors.add(new EarlyLoadingException("Invalid Access Transformers", null, errors));
}
} }
public void addForScanning(BackgroundScanHandler backgroundScanHandler) { public void addForScanning(BackgroundScanHandler backgroundScanHandler) {
@@ -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);
} }
@@ -46,7 +46,7 @@ public 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
@@ -45,7 +45,6 @@ public final class RuntimeDistCleaner implements ILaunchPluginService {
@Override @Override
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty) { public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty) {
// TODO: [FML][RuntimeDistCleaner] In 26.1, only return YAY for MC classes on mod dev server
if (isEmpty) if (isEmpty)
return NAY; return NAY;
@@ -54,7 +53,7 @@ public final class RuntimeDistCleaner implements ILaunchPluginService {
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; return YAY;
@@ -65,29 +64,15 @@ 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);
final class LazyInit {
private LazyInit() {}
private static final boolean CAN_EXPLODE = !FMLEnvironment.production && "21.6".equals(FMLLoader.versionInfo().mcVersion());
}
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 (!annotations.isEmpty()) { if (!FMLEnvironment.production && !annotations.isEmpty() && hasModAnnotation(classNode.visibleAnnotations)) {
if (isNonMinecraftClass) { LOGGER.error(DISTXFORM, "Attempted to load class {} with @Mod and @OnlyIn/@OnlyIns annotations", classNode.name);
if (LazyInit.CAN_EXPLODE) 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");
throw new UnsupportedOperationException("Mod class " + classNode.name + " is annotated with @OnlyIn, this is no longer supported as it slowed down startup times");
else
LOGGER.warn(DISTXFORM, "Class {} is annotated with @OnlyIn, this is deprecated and won't work in a future MC release.", classNode.name);
}
if (!FMLEnvironment.production && hasModAnnotation(classNode.visibleAnnotations)) {
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()) {
@@ -96,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;
} }
} }
@@ -120,13 +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) {
if (LazyInit.CAN_EXPLODE)
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");
else
LOGGER.warn(DISTXFORM, "Field {} in class {} is annotated with @OnlyIn, this is deprecated and won't work in a future MC release.", field.name, classNode.name);
}
} }
} }
@@ -138,13 +116,6 @@ public final class RuntimeDistCleaner implements ILaunchPluginService {
itr.remove(); itr.remove();
lambdaGatherer.accept(method); lambdaGatherer.accept(method);
changed = true; changed = true;
if (isNonMinecraftClass) {
if (LazyInit.CAN_EXPLODE)
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");
else
LOGGER.warn(DISTXFORM, "Method {} in class {} is annotated with @OnlyIn, this is deprecated and won't work in a future MC release.", method.name, classNode.name);
}
} }
} }
@@ -171,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]
@@ -237,10 +208,6 @@ public final class RuntimeDistCleaner implements ILaunchPluginService {
return false; return false;
} }
private static boolean isMinecraftClass(final String internalName) {
return internalName.startsWith("net/minecraft/") || internalName.startsWith("com/mojang/");
}
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public Consumer<Dist> getExtension() { public Consumer<Dist> getExtension() {
@@ -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,7 +122,7 @@ 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) {
@@ -119,7 +130,7 @@ public final class UniqueModListBuilder {
return mf.getJarVersion(); return mf.getJarVersion();
} }
return mf.getModInfos().getFirst().getVersion(); return mf.getModInfos().get(0).getVersion();
} }
private static String getModId(ModFile modFile) { private static String getModId(ModFile modFile) {
@@ -127,7 +138,7 @@ public final class UniqueModListBuilder {
return modFile.getSecureJar().name(); return modFile.getSecureJar().name();
} }
return modFile.getModFileInfo().getMods().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) {}
@@ -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();
@@ -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() + "}";
}
}
@@ -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, id -> 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);
}
}
} }
@@ -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,36 +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); Launcher.INSTANCE.environment().computePropertyIfAbsent(Environment.Keys.MODDIRECTORYFACTORY.get(), v->ModsFolderLocator::new);
Launcher.INSTANCE.environment().computePropertyIfAbsent(Environment.Keys.PROGRESSMESSAGE.get(), v-> StartupNotificationManager.locatorConsumer().orElseGet(()-> s->{})); Launcher.INSTANCE.environment().computePropertyIfAbsent(Environment.Keys.PROGRESSMESSAGE.get(), v-> StartupNotificationManager.locatorConsumer().orElseGet(()-> s->{}));
final var moduleLayerManager = Launcher.INSTANCE.environment().findModuleLayerManager().orElseThrow(); final var moduleLayerManager = Launcher.INSTANCE.environment().findModuleLayerManager().orElseThrow();
ServiceLoader<IModLocator> modLocators = ServiceLoader.load(moduleLayerManager.getLayer(IModuleLayerManager.Layer.SERVICE).orElseThrow(), IModLocator.class); modLocators = ServiceLoader.load(moduleLayerManager.getLayer(IModuleLayerManager.Layer.SERVICE).orElseThrow(), IModLocator.class);
ServiceLoader<IDependencyLocator> dependencyLocators = ServiceLoader.load(moduleLayerManager.getLayer(IModuleLayerManager.Layer.SERVICE).orElseThrow(), IDependencyLocator.class); 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(); modLocatorList = ServiceLoaderUtils.streamServiceLoader(()-> modLocators, sce->LOGGER.error("Failed to load mod locator list", sce)).collect(Collectors.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<>();
@@ -111,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);
@@ -125,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.
@@ -145,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);
@@ -158,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()
@@ -181,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);
} }
} }
@@ -21,13 +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.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;
@@ -48,6 +48,7 @@ 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<CoreModFile> coreMods;
private Path accessTransformer; private Path accessTransformer;
private List<Path> accessTransformers = Collections.emptyList(); private List<Path> accessTransformers = Collections.emptyList();
@@ -92,22 +93,33 @@ public class ModFile implements IModFile {
return modFileInfo.getMods(); return modFileInfo.getMods();
} }
@Deprecated(forRemoval = true, since = "1.21.11") /** @deprecated Use {@link #getAccessTransformers()} instead*/
@Deprecated(forRemoval=true, since="1.21.11")
public Optional<Path> getAccessTransformer() { public Optional<Path> getAccessTransformer() {
return Optional.ofNullable(accessTransformer); 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)) {
@@ -116,14 +128,18 @@ public class ModFile implements IModFile {
} }
} 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
*/ */
@@ -191,28 +207,12 @@ public class ModFile implements IModFile {
@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();
} }
} }
@@ -34,6 +34,7 @@ public class ModValidator {
private LoadingModList loadingModList; 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));
@@ -43,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) {
@@ -50,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() {
@@ -60,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
@@ -125,6 +125,7 @@ public class ModValidator {
allErrors.addAll(this.discoveryErrorData); allErrors.addAll(this.discoveryErrorData);
loadingModList = ModSorter.sort(candidateMods, allErrors); loadingModList = ModSorter.sort(candidateMods, allErrors);
loadingModList.addCoreMods();
loadingModList.addAccessTransformers(); loadingModList.addAccessTransformers();
loadingModList.setBrokenFiles(brokenFiles); loadingModList.setBrokenFiles(brokenFiles);
BackgroundScanHandler backgroundScanHandler = new BackgroundScanHandler(candidateMods); BackgroundScanHandler backgroundScanHandler = new BackgroundScanHandler(candidateMods);
@@ -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"
}; };
} }
@@ -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 " + 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),
insn -> 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/GameTestHelper",
"methods": [
"spawn(Lnet/minecraft/world/entity/EntityType;Lnet/minecraft/world/phys/Vec3;Lnet/minecraft/world/entity/EntitySpawnReason;)Lnet/minecraft/world/entity/Entity;"
]
},
{ {
"class": "net/minecraft/server/commands/RaidCommand", "class": "net/minecraft/server/commands/RaidCommand",
"methods": [ "methods": [
@@ -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/Villager;" "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"
] ]
}, },
{ {
+3 -3
View File
@@ -5,11 +5,11 @@ org.gradle.daemon=false
org.gradle.parallel=true org.gradle.parallel=true
JAVA_VERSION=21 JAVA_VERSION=21
MC_VERSION=1.21.11 MC_VERSION=1.21.8
MC_NEXT_VERSION=1.22 MC_NEXT_VERSION=1.22
MCP_VERSION=20251223.124241 MCP_VERSION=20250717.105350
MAPPING_CHANNEL=official MAPPING_CHANNEL=official
MAPPING_VERSION=1.21.11 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
@@ -48,7 +48,7 @@ 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);
@@ -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;
} }
@@ -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,6 +1,6 @@
--- 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
@@ -133,6 +_,9 @@ @@ -132,6 +_,9 @@
GlStateManager._colorMask(true, true, true, true); 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);
@@ -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
@@ -24,6 +_,14 @@ @@ -23,6 +_,14 @@
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public class GlDebug { public class GlDebug {
@@ -24,10 +24,10 @@
} }
public List<String> getLastOpenGlDebugMessages() { public List<String> getLastOpenGlDebugMessages() {
@@ -120,6 +_,7 @@ @@ -121,6 +_,7 @@
}
public static @Nullable GlDebug enableDebugCallback(int p_394351_, boolean p_393026_, Set<String> p_393339_) { @Nullable
public static GlDebug enableDebugCallback(int p_394351_, boolean p_393026_, Set<String> p_393339_) {
+ p_393026_ |= PRINT_STACKTRACE_ON_ERROR; + p_393026_ |= PRINT_STACKTRACE_ON_ERROR;
if (p_394351_ <= 0) { if (p_394351_ <= 0) {
return null; return null;
@@ -1,8 +1,8 @@
--- 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
@@ -124,8 +_,15 @@ @@ -89,8 +_,15 @@
int p_407582_, public GpuTexture createTexture(
int p_408928_ @Nullable Supplier<String> p_397830_, int p_394481_, TextureFormat p_394839_, int p_391831_, int p_395609_, int p_407582_, int p_408928_
) { ) {
+ return createTexture(p_397830_, p_394481_, p_394839_, p_391831_, p_395609_, p_407582_, p_408928_, false); + return createTexture(p_397830_, p_394481_, p_394839_, p_391831_, p_395609_, p_407582_, p_408928_, false);
+ } + }
@@ -17,23 +17,23 @@
); );
} }
@@ -133,6 +_,15 @@ @@ -98,6 +_,15 @@
public GpuTexture createTexture( public GpuTexture createTexture(
@Nullable String p_394142_, @GpuTexture.Usage int p_395535_, TextureFormat p_394951_, int p_393944_, int p_392329_, int p_408015_, int p_406483_ @Nullable String p_394142_, int p_395535_, TextureFormat p_394951_, int p_393944_, int p_392329_, int p_408015_, int p_406483_
) { ) {
+ return createTexture(p_394142_, p_395535_, p_394951_, p_393944_, p_392329_, p_408015_, p_406483_, false); + return createTexture(p_394142_, p_395535_, p_394951_, p_393944_, p_392329_, p_408015_, p_406483_, false);
+ } + }
+ +
+ @Override + @Override
+ public GpuTexture createTexture( + public GpuTexture createTexture(
+ @Nullable String p_394142_, @GpuTexture.Usage int p_395535_, TextureFormat p_394951_, int p_393944_, int p_392329_, int p_408015_, int p_406483_, boolean stencil + @Nullable String p_394142_, int p_395535_, TextureFormat p_394951_, int p_393944_, int p_392329_, int p_408015_, int p_406483_, boolean stencil
+ ) { + ) {
+ // Forge: stencil rendering is only for depth + // Forge: stencil rendering is only for depth
+ stencil &= p_394951_.hasDepthAspect(); + stencil &= p_394951_.hasDepthAspect();
if (p_406483_ < 1) { if (p_406483_ < 1) {
throw new IllegalArgumentException("mipLevels must be at least 1"); throw new IllegalArgumentException("mipLevels must be at least 1");
} else if (p_408015_ < 1) { } else if (p_408015_ < 1) {
@@ -183,11 +_,14 @@ @@ -148,11 +_,14 @@
GlStateManager._texImage2D( GlStateManager._texImage2D(
k, k,
l, l,
@@ -48,7 +48,7 @@
GlConst.toGlType(p_394951_), GlConst.toGlType(p_394951_),
null null
); );
@@ -198,11 +_,14 @@ @@ -163,11 +_,14 @@
GlStateManager._texImage2D( GlStateManager._texImage2D(
j, j,
i1, i1,
@@ -63,7 +63,7 @@
GlConst.toGlType(p_394951_), GlConst.toGlType(p_394951_),
null null
); );
@@ -215,7 +_,7 @@ @@ -180,7 +_,7 @@
} else if (j1 != 0) { } else if (j1 != 0) {
throw new IllegalStateException("OpenGL error " + j1); throw new IllegalStateException("OpenGL error " + j1);
} else { } else {
@@ -1,6 +1,6 @@
--- 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
@@ -86,6 +_,11 @@ @@ -89,6 +_,11 @@
} }
} }
@@ -12,7 +12,7 @@
public static void _disableBlend() { public static void _disableBlend() {
RenderSystem.assertOnRenderThread(); RenderSystem.assertOnRenderThread();
BLEND.mode.disable(); BLEND.mode.disable();
@@ -371,9 +_,17 @@ @@ -404,9 +_,17 @@
} }
} }
@@ -1,9 +1,9 @@
--- 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
@@ -21,8 +_,13 @@ @@ -19,8 +_,13 @@
protected GlTexture( private int views;
@GpuTexture.Usage int p_394590_, String p_393950_, TextureFormat p_392837_, int p_391379_, int p_391947_, int p_396659_, int p_408255_, int p_408889_
) { 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(p_394590_, p_393950_, p_392837_, p_391379_, p_391947_, p_396659_, p_408255_, p_408889_, false); + this(p_394590_, p_393950_, p_392837_, p_391379_, p_391947_, p_396659_, p_408255_, p_408889_, false);
+ } + }
+ +
@@ -14,16 +14,20 @@
} }
@Override @Override
@@ -89,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
@@ -80,7 +_,7 @@ @@ -92,7 +_,7 @@
this.width = p_83951_; this.width = p_83951_;
this.height = p_83952_; this.height = p_83952_;
if (this.useDepth) { if (this.useDepth) {
- this.depthTexture = gpudevice.createTexture(() -> this.label + " / Depth", 15, TextureFormat.DEPTH32, p_83951_, p_83952_, 1, 1); - this.depthTexture = gpudevice.createTexture(() -> this.label + " / Depth", 15, TextureFormat.DEPTH32, p_83951_, p_83952_, 1, 1);
+ this.depthTexture = gpudevice.createTexture(() -> this.label + " / Depth", 15, TextureFormat.DEPTH32, p_83951_, p_83952_, 1, 1, this.stencilEnabled); + this.depthTexture = gpudevice.createTexture(() -> this.label + " / Depth", 15, TextureFormat.DEPTH32, p_83951_, p_83952_, 1, 1, this.stencilEnabled);
this.depthTextureView = gpudevice.createTextureView(this.depthTexture); this.depthTextureView = gpudevice.createTextureView(this.depthTexture);
} this.depthTexture.setTextureFilter(FilterMode.NEAREST, false);
this.depthTexture.setAddressMode(AddressMode.CLAMP_TO_EDGE);
@@ -126,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);
+ } + }
+ +
+ /** + /**
@@ -1,16 +1,16 @@
--- a/com/mojang/blaze3d/platform/Window.java --- a/com/mojang/blaze3d/platform/Window.java
+++ b/com/mojang/blaze3d/platform/Window.java +++ b/com/mojang/blaze3d/platform/Window.java
@@ -91,7 +_,8 @@ @@ -88,7 +_,8 @@
GLFW.glfwWindowHint(139267, 3); GLFW.glfwWindowHint(139267, 2);
GLFW.glfwWindowHint(139272, 204801); GLFW.glfwWindowHint(139272, 204801);
GLFW.glfwWindowHint(139270, 1); GLFW.glfwWindowHint(139270, 1);
- this.handle = GLFW.glfwCreateWindow(this.width, this.height, p_85376_, this.fullscreen && monitor != null ? monitor.getMonitor() : 0L, 0L); - this.window = GLFW.glfwCreateWindow(this.width, this.height, p_85376_, this.fullscreen && monitor != null ? monitor.getMonitor() : 0L, 0L);
+ this.handle = net.minecraftforge.fml.loading.ImmediateWindowHandler.setupMinecraftWindow(()->this.width, ()->this.height, ()->p_85376_, ()->this.fullscreen && monitor != null ? monitor.getMonitor() : 0L); + this.window = net.minecraftforge.fml.loading.ImmediateWindowHandler.setupMinecraftWindow(()->this.width, ()->this.height, ()->p_85376_, ()->this.fullscreen && monitor != null ? monitor.getMonitor() : 0L);
+ if (!net.minecraftforge.fml.loading.ImmediateWindowHandler.positionWindow(Optional.ofNullable(monitor), w->this.width = this.windowedWidth = w, h->this.height = this.windowedHeight = h, x->this.x = this.windowedX = x, y->this.y = this.windowedY = y)) { + if (!net.minecraftforge.fml.loading.ImmediateWindowHandler.positionWindow(Optional.ofNullable(monitor), w->this.width = this.windowedWidth = w, h->this.height = this.windowedHeight = h, x->this.x = this.windowedX = x, y->this.y = this.windowedY = y)) {
if (monitor != null) { if (monitor != null) {
VideoMode videomode = monitor.getPreferredVidMode(this.fullscreen ? this.preferredFullscreenVideoMode : Optional.empty()); VideoMode videomode = monitor.getPreferredVidMode(this.fullscreen ? this.preferredFullscreenVideoMode : Optional.empty());
this.windowedX = this.x = monitor.getX() + videomode.getWidth() / 2 - this.width / 2; this.windowedX = this.x = monitor.getX() + videomode.getWidth() / 2 - this.width / 2;
@@ -103,6 +_,7 @@ @@ -100,6 +_,7 @@
this.windowedX = this.x = aint1[0]; this.windowedX = this.x = aint1[0];
this.windowedY = this.y = aint[0]; this.windowedY = this.y = aint[0];
} }
@@ -18,8 +18,8 @@
this.setMode(); this.setMode();
this.refreshFramebufferSize(); this.refreshFramebufferSize();
@@ -269,6 +_,9 @@ @@ -266,6 +_,9 @@
GLFW.glfwGetFramebufferSize(this.handle, aint, aint1); GLFW.glfwGetFramebufferSize(this.window, aint, aint1);
this.framebufferWidth = aint[0] > 0 ? aint[0] : 1; this.framebufferWidth = aint[0] > 0 ? aint[0] : 1;
this.framebufferHeight = aint1[0] > 0 ? aint1[0] : 1; this.framebufferHeight = aint1[0] > 0 ? aint1[0] : 1;
+ if (this.framebufferHeight == 0 || this.framebufferWidth == 0) { + if (this.framebufferHeight == 0 || this.framebufferWidth == 0) {
@@ -1,7 +1,7 @@
--- a/com/mojang/blaze3d/systems/GpuDevice.java --- a/com/mojang/blaze3d/systems/GpuDevice.java
+++ b/com/mojang/blaze3d/systems/GpuDevice.java +++ b/com/mojang/blaze3d/systems/GpuDevice.java
@@ -36,9 +_,19 @@ @@ -26,7 +_,17 @@
int p_407070_ @Nullable Supplier<String> p_394357_, int p_395623_, TextureFormat p_395807_, int p_395802_, int p_396157_, int p_408810_, int p_407070_
); );
+ /** Forge: same as {@link #createTexture(Supplier, int, TextureFormat, int, int, int)} but with stencil support */ + /** Forge: same as {@link #createTexture(Supplier, int, TextureFormat, int, int, int)} but with stencil support */
@@ -9,9 +9,7 @@
+ return this.createTexture(p_394357_, p_395623_, p_395807_, p_395802_, p_396157_, p_408810_, p_407070_); + return this.createTexture(p_394357_, p_395623_, p_395807_, p_395802_, p_396157_, p_408810_, p_407070_);
+ } + }
+ +
GpuTexture createTexture( GpuTexture createTexture(@Nullable String p_391798_, int p_391800_, TextureFormat p_393333_, int p_395600_, int p_394065_, int p_408732_, int p_407125_);
@Nullable String p_391798_, @GpuTexture.Usage int p_391800_, TextureFormat p_393333_, int p_395600_, int p_394065_, int p_408732_, int p_407125_
);
+ +
+ /** Forge: same as {@link #createTexture(String, int, TextureFormat, int, int, int)} but with stencil support */ + /** Forge: same as {@link #createTexture(String, int, TextureFormat, int, int, int)} but with stencil support */
+ default GpuTexture createTexture(@Nullable String p_391798_, int p_391800_, TextureFormat p_393333_, int p_395600_, int p_394065_, int p_408732_, int p_407125_, boolean stencil) { + default GpuTexture createTexture(@Nullable String p_391798_, int p_391800_, TextureFormat p_393333_, int p_395600_, int p_394065_, int p_408732_, int p_407125_, boolean stencil) {
@@ -1,6 +1,6 @@
--- a/com/mojang/blaze3d/textures/GpuTexture.java --- a/com/mojang/blaze3d/textures/GpuTexture.java
+++ b/com/mojang/blaze3d/textures/GpuTexture.java +++ b/com/mojang/blaze3d/textures/GpuTexture.java
@@ -10,7 +_,7 @@ @@ -6,7 +_,7 @@
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
@DontObfuscate @DontObfuscate
@@ -1,7 +1,7 @@
--- a/com/mojang/blaze3d/vertex/VertexConsumer.java --- a/com/mojang/blaze3d/vertex/VertexConsumer.java
+++ b/com/mojang/blaze3d/vertex/VertexConsumer.java +++ b/com/mojang/blaze3d/vertex/VertexConsumer.java
@@ -14,7 +_,7 @@ @@ -15,7 +_,7 @@
import org.joml.Vector3fc; import org.lwjgl.system.MemoryStack;
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
-public interface VertexConsumer { -public interface VertexConsumer {
@@ -9,3 +9,15 @@
VertexConsumer addVertex(float p_344294_, float p_342213_, float p_344859_); VertexConsumer addVertex(float p_344294_, float p_342213_, float p_344859_);
VertexConsumer setColor(int p_342749_, int p_344324_, int p_343336_, int p_342831_); VertexConsumer setColor(int p_342749_, int p_344324_, int p_343336_, int p_342831_);
@@ -135,9 +_,11 @@
int j1 = ARGB.color(k, (int)f3, (int)f4, (int)f5);
int k1 = LightTexture.lightCoordsWithEmission(p_331444_[i1], l);
+ k1 = applyBakedLighting(k1, bytebuffer);
float f10 = bytebuffer.getFloat(16);
float f9 = bytebuffer.getFloat(20);
Vector3f vector3f1 = matrix4f.transformPosition(f, f1, f2, new Vector3f());
+ applyBakedNormals(vector3f, bytebuffer, p_85988_.normal());
this.addVertex(vector3f1.x(), vector3f1.y(), vector3f1.z(), j1, f10, f9, p_85993_, k1, vector3f.x(), vector3f.y(), vector3f.z());
}
}
@@ -1,23 +1,23 @@
--- a/com/mojang/blaze3d/vertex/VertexFormat.java --- a/com/mojang/blaze3d/vertex/VertexFormat.java
+++ b/com/mojang/blaze3d/vertex/VertexFormat.java +++ b/com/mojang/blaze3d/vertex/VertexFormat.java
@@ -20,7 +_,7 @@ @@ -21,7 +_,7 @@
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
@DontObfuscate @DontObfuscate
-public class VertexFormat { -public class VertexFormat {
+public class VertexFormat implements net.minecraftforge.client.extensions.IForgeVertexFormat { +public class VertexFormat implements net.minecraftforge.client.extensions.IForgeVertexFormat {
public static final int UNKNOWN_ELEMENT = -1; public static final int UNKNOWN_ELEMENT = -1;
private final List<VertexFormatElement> elements; private static final boolean USE_STAGING_BUFFER_WORKAROUND = Util.getPlatform() == Util.OS.WINDOWS && Util.isAarch64();
private final List<String> names; @Nullable
@@ -29,6 +_,7 @@ @@ -35,6 +_,7 @@
private final int[] offsetsByElement = new int[32]; private GpuBuffer immediateDrawVertexBuffer;
private @Nullable GpuBuffer immediateDrawVertexBuffer; @Nullable
private @Nullable GpuBuffer immediateDrawIndexBuffer; private GpuBuffer immediateDrawIndexBuffer;
+ private final com.google.common.collect.ImmutableMap<String, VertexFormatElement> elementMapping; + private final com.google.common.collect.ImmutableMap<String, VertexFormatElement> elementMapping;
VertexFormat(List<VertexFormatElement> p_343616_, List<String> p_345241_, IntList p_345522_, int p_344162_) { VertexFormat(List<VertexFormatElement> p_343616_, List<String> p_345241_, IntList p_345522_, int p_344162_) {
this.elements = p_343616_; this.elements = p_343616_;
@@ -41,6 +_,11 @@ @@ -47,6 +_,11 @@
int j = vertexformatelement != null ? p_343616_.indexOf(vertexformatelement) : -1; int j = vertexformatelement != null ? p_343616_.indexOf(vertexformatelement) : -1;
this.offsetsByElement[i] = j != -1 ? p_345522_.getInt(j) : -1; this.offsetsByElement[i] = j != -1 ? p_345522_.getInt(j) : -1;
} }
@@ -29,8 +29,8 @@
} }
public static VertexFormat.Builder builder() { public static VertexFormat.Builder builder() {
@@ -139,6 +_,9 @@ @@ -169,6 +_,9 @@
this.immediateDrawIndexBuffer = uploadToBuffer(this.immediateDrawIndexBuffer, p_391835_, 72, () -> "Immediate index buffer for " + this); );
return this.immediateDrawIndexBuffer; return this.immediateDrawIndexBuffer;
} }
+ +
@@ -1,18 +1,18 @@
--- a/com/mojang/math/Transformation.java --- a/com/mojang/math/Transformation.java
+++ b/com/mojang/math/Transformation.java +++ b/com/mojang/math/Transformation.java
@@ -16,7 +_,7 @@ @@ -14,7 +_,7 @@
import org.joml.Vector3fc; import org.joml.Quaternionf;
import org.jspecify.annotations.Nullable; import org.joml.Vector3f;
-public final class Transformation { -public final class Transformation {
+public final class Transformation implements net.minecraftforge.common.extensions.IForgeTransformation { +public final class Transformation implements net.minecraftforge.common.extensions.IForgeTransformation {
private final Matrix4fc matrix; private final Matrix4fc matrix;
public static final Codec<Transformation> CODEC = RecordCodecBuilder.create( public static final Codec<Transformation> CODEC = RecordCodecBuilder.create(
p_269604_ -> p_269604_.group( p_269604_ -> p_269604_.group(
@@ -168,5 +_,19 @@ @@ -174,5 +_,19 @@
this.getScale().lerp(p_175938_.getScale(), p_175939_, new Vector3f()), vector3f1.lerp(p_175938_.getScale(), p_175939_);
this.getRightRotation().slerp(p_175938_.getRightRotation(), p_175939_, new Quaternionf()) quaternionf1.slerp(p_175938_.getRightRotation(), p_175939_);
); return new Transformation(vector3f, quaternionf, vector3f1, quaternionf1);
+ } + }
+ +
+ private Matrix3f normalTransform = null; + private Matrix3f normalTransform = null;
@@ -1,18 +1,18 @@
--- a/com/mojang/realmsclient/gui/screens/RealmsGenericErrorScreen.java --- a/com/mojang/realmsclient/gui/screens/RealmsGenericErrorScreen.java
+++ b/com/mojang/realmsclient/gui/screens/RealmsGenericErrorScreen.java +++ b/com/mojang/realmsclient/gui/screens/RealmsGenericErrorScreen.java
@@ -62,6 +_,15 @@ @@ -71,6 +_,15 @@
} }
@Override @Override
+ public boolean keyPressed(net.minecraft.client.input.KeyEvent event) { + public boolean keyPressed(int key, int scanCode, int modifiers) {
+ if (event.key() == org.lwjgl.glfw.GLFW.GLFW_KEY_ESCAPE) { + if (key == org.lwjgl.glfw.GLFW.GLFW_KEY_ESCAPE) {
+ minecraft.setScreen(this.nextScreen); + minecraft.setScreen(this.nextScreen);
+ return true; + return true;
+ } + }
+ return super.keyPressed(event); + return super.keyPressed(key, scanCode, modifiers);
+ } + }
+ +
+ @Override + @Override
public void render(GuiGraphics p_283497_, int p_88680_, int p_88681_, float p_88682_) { public void render(GuiGraphics p_283497_, int p_88680_, int p_88681_, float p_88682_) {
super.render(p_283497_, p_88680_, p_88681_, p_88682_); super.render(p_283497_, p_88680_, p_88681_, p_88682_);
p_283497_.drawCenteredString(this.font, this.title, this.width / 2, 80, -1); p_283497_.drawCenteredString(this.font, this.lines.title, this.width / 2, 80, -1);
@@ -1,11 +0,0 @@
--- a/com/mojang/realmsclient/gui/screens/RealmsResetWorldScreen.java
+++ b/com/mojang/realmsclient/gui/screens/RealmsResetWorldScreen.java
@@ -263,7 +_,7 @@
int k = this.getY();
p_282595_.blit(RenderPipelines.GUI_TEXTURED, this.image, j + 2, k + 2, 0.0F, 0.0F, 56, 56, 56, 56, 56, 56, i);
p_282595_.blitSprite(RenderPipelines.GUI_TEXTURED, SLOT_FRAME_SPRITE, j, k, 60, 60, i);
- int l = flag ? -6250336 : -1;
+ int l = getFGColor();
p_282595_.drawCenteredString(RealmsResetWorldScreen.this.font, this.getMessage(), j + 28, k - 14, l);
}
}
@@ -1,6 +1,6 @@
--- a/net/minecraft/CrashReportCategory.java --- a/net/minecraft/CrashReportCategory.java
+++ b/net/minecraft/CrashReportCategory.java +++ b/net/minecraft/CrashReportCategory.java
@@ -116,8 +_,10 @@ @@ -112,8 +_,10 @@
if (astacktraceelement.length <= 0) { if (astacktraceelement.length <= 0) {
return 0; return 0;
} else { } else {
@@ -13,7 +13,7 @@
return this.stackTrace.length; return this.stackTrace.length;
} }
} }
@@ -164,16 +_,16 @@ @@ -160,16 +_,16 @@
if (this.stackTrace != null && this.stackTrace.length > 0) { if (this.stackTrace != null && this.stackTrace.length > 0) {
p_128169_.append("\nStacktrace:"); p_128169_.append("\nStacktrace:");
@@ -1,10 +1,10 @@
--- a/net/minecraft/SharedConstants.java --- a/net/minecraft/SharedConstants.java
+++ b/net/minecraft/SharedConstants.java +++ b/net/minecraft/SharedConstants.java
@@ -216,6 +_,7 @@ @@ -175,6 +_,7 @@
} }
static { static {
+ if (System.getProperty("io.netty.leakDetection.level") == null) // Forge: allow level to be manually specified + if (System.getProperty("io.netty.leakDetection.level") == null) // Forge: allow level to be manually specified
ResourceLeakDetector.setLevel(NETTY_LEAK_DETECTION); ResourceLeakDetector.setLevel(NETTY_LEAK_DETECTION);
CommandSyntaxException.ENABLE_COMMAND_STACK_TRACES = COMMAND_STACK_TRACES; CommandSyntaxException.ENABLE_COMMAND_STACK_TRACES = false;
CommandSyntaxException.BUILT_IN_EXCEPTIONS = new BrigadierExceptions(); CommandSyntaxException.BUILT_IN_EXCEPTIONS = new BrigadierExceptions();
@@ -1,11 +1,11 @@
--- a/net/minecraft/util/Util.java --- a/net/minecraft/Util.java
+++ b/net/minecraft/util/Util.java +++ b/net/minecraft/Util.java
@@ -268,7 +_,7 @@ @@ -268,7 +_,7 @@
.getSchema(DataFixUtils.makeKey(SharedConstants.getCurrentVersion().dataVersion().version())) .getSchema(DataFixUtils.makeKey(SharedConstants.getCurrentVersion().dataVersion().version()))
.getChoiceType(p_457223_, p_460132_); .getChoiceType(p_137552_, p_137553_);
} catch (IllegalArgumentException illegalargumentexception) { } catch (IllegalArgumentException illegalargumentexception) {
- LOGGER.error("No data fixer registered for {}", p_460132_); - LOGGER.error("No data fixer registered for {}", p_137553_);
+ LOGGER.debug("No data fixer registered for {}", p_460132_); + LOGGER.debug("No data fixer registered for {}", p_137553_);
if (SharedConstants.IS_RUNNING_IN_IDE) { if (SharedConstants.IS_RUNNING_IN_IDE) {
throw illegalargumentexception; throw illegalargumentexception;
} }
@@ -1,14 +1,14 @@
--- a/net/minecraft/advancements/Advancement.java --- a/net/minecraft/advancements/Advancement.java
+++ b/net/minecraft/advancements/Advancement.java +++ b/net/minecraft/advancements/Advancement.java
@@ -231,7 +_,11 @@ @@ -226,7 +_,11 @@
} }
public AdvancementHolder save(Consumer<AdvancementHolder> p_138390_, String p_138391_) { public AdvancementHolder save(Consumer<AdvancementHolder> p_138390_, String p_138391_) {
- AdvancementHolder advancementholder = this.build(Identifier.parse(p_138391_)); - AdvancementHolder advancementholder = this.build(ResourceLocation.parse(p_138391_));
+ return save(p_138390_, Identifier.parse(p_138391_)); + return save(p_138390_, ResourceLocation.parse(p_138391_));
+ } + }
+ +
+ public AdvancementHolder save(Consumer<AdvancementHolder> p_138390_, Identifier id) { + public AdvancementHolder save(Consumer<AdvancementHolder> p_138390_, ResourceLocation id) {
+ AdvancementHolder advancementholder = this.build(id); + AdvancementHolder advancementholder = this.build(id);
p_138390_.accept(advancementholder); p_138390_.accept(advancementholder);
return advancementholder; return advancementholder;
@@ -1,6 +1,6 @@
--- a/net/minecraft/advancements/AdvancementRewards.java --- a/net/minecraft/advancements/AdvancementRewards.java
+++ b/net/minecraft/advancements/AdvancementRewards.java +++ b/net/minecraft/advancements/AdvancementRewards.java
@@ -44,6 +_,7 @@ @@ -43,6 +_,7 @@
LootParams lootparams = new LootParams.Builder(serverlevel) LootParams lootparams = new LootParams.Builder(serverlevel)
.withParameter(LootContextParams.THIS_ENTITY, p_9990_) .withParameter(LootContextParams.THIS_ENTITY, p_9990_)
.withParameter(LootContextParams.ORIGIN, p_9990_.position()) .withParameter(LootContextParams.ORIGIN, p_9990_.position())
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/Camera.java --- a/net/minecraft/client/Camera.java
+++ b/net/minecraft/client/Camera.java +++ b/net/minecraft/client/Camera.java
@@ -136,9 +_,13 @@ @@ -133,9 +_,13 @@
} }
protected void setRotation(float p_90573_, float p_90574_) { protected void setRotation(float p_90573_, float p_90574_) {
@@ -15,10 +15,10 @@
FORWARDS.rotate(this.rotation, this.forwards); FORWARDS.rotate(this.rotation, this.forwards);
UP.rotate(this.rotation, this.up); UP.rotate(this.rotation, this.up);
LEFT.rotate(this.rotation, this.left); LEFT.rotate(this.rotation, this.left);
@@ -168,6 +_,13 @@ @@ -251,6 +_,13 @@
public float yRot() { public float getPartialTickTime() {
return this.yRot; return this.partialTickTime;
+ } + }
+ +
+ public net.minecraft.world.level.block.state.BlockState getBlockAtCamera() { + public net.minecraft.world.level.block.state.BlockState getBlockAtCamera() {
@@ -1,27 +1,35 @@
--- a/net/minecraft/client/KeyMapping.java --- a/net/minecraft/client/KeyMapping.java
+++ b/net/minecraft/client/KeyMapping.java +++ b/net/minecraft/client/KeyMapping.java
@@ -19,9 +_,9 @@ @@ -15,9 +_,9 @@
import org.jspecify.annotations.Nullable; import net.minecraftforge.api.distmarker.OnlyIn;
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
-public class KeyMapping implements Comparable<KeyMapping> { -public class KeyMapping implements Comparable<KeyMapping> {
+public class KeyMapping implements Comparable<KeyMapping>, net.minecraftforge.client.extensions.IForgeKeyMapping { +public class KeyMapping implements Comparable<KeyMapping>, net.minecraftforge.client.extensions.IForgeKeyMapping {
private static final Map<String, KeyMapping> ALL = Maps.newHashMap(); private static final Map<String, KeyMapping> ALL = Maps.newHashMap();
- private static final Map<InputConstants.Key, List<KeyMapping>> MAP = Maps.newHashMap(); - private static final Map<InputConstants.Key, KeyMapping> MAP = Maps.newHashMap();
+ private static final net.minecraftforge.client.settings.KeyMappingLookup MAP = new net.minecraftforge.client.settings.KeyMappingLookup(); + private static final net.minecraftforge.client.settings.KeyMappingLookup MAP = new net.minecraftforge.client.settings.KeyMappingLookup();
private final String name; private static final Set<String> CATEGORIES = Sets.newHashSet();
private final InputConstants.Key defaultKey; public static final String CATEGORY_MOVEMENT = "key.categories.movement";
private final KeyMapping.Category category; public static final String CATEGORY_MISC = "key.categories.misc";
@@ -39,7 +_,7 @@ @@ -43,14 +_,14 @@
private int clickCount;
public static void click(InputConstants.Key p_90836_) {
- KeyMapping keymapping = MAP.get(p_90836_);
+ for (KeyMapping keymapping : MAP.getAll(p_90836_))
if (keymapping != null) {
keymapping.clickCount++;
}
} }
private static void forAllKeyMappings(InputConstants.Key p_424096_, Consumer<KeyMapping> p_427756_) { public static void set(InputConstants.Key p_90838_, boolean p_90839_) {
- List<KeyMapping> list = MAP.get(p_424096_); - KeyMapping keymapping = MAP.get(p_90838_);
+ List<KeyMapping> list = MAP.getAll(p_424096_); + for (KeyMapping keymapping : MAP.getAll(p_90838_))
if (list != null && !list.isEmpty()) { if (keymapping != null) {
for (KeyMapping keymapping : list) { keymapping.setDown(p_90839_);
p_427756_.accept(keymapping); }
@@ -106,7 +_,7 @@ @@ -101,7 +_,7 @@
} }
public boolean isDown() { public boolean isDown() {
@@ -29,27 +37,26 @@
+ return this.isDown && isConflictContextAndModifierActive(); + return this.isDown && isConflictContextAndModifierActive();
} }
public KeyMapping.Category getCategory() { public String getCategory() {
@@ -149,8 +_,17 @@ @@ -137,7 +_,16 @@
? I18n.get(this.name).compareTo(I18n.get(p_90841_.name)) public int compareTo(KeyMapping p_90841_) {
: Integer.compare(this.order, p_90841_.order); return this.category.equals(p_90841_.category)
} else { ? I18n.get(this.name).compareTo(I18n.get(p_90841_.name))
- return Integer.compare(KeyMapping.Category.SORT_ORDER.indexOf(this.category), KeyMapping.Category.SORT_ORDER.indexOf(p_90841_.category)); - : CATEGORY_SORT_ORDER.get(this.category).compareTo(CATEGORY_SORT_ORDER.get(p_90841_.category));
+ return compareSort(this.category, p_90841_.category); + : compareSort(this.category, p_90841_.category);
}
+ } + }
+ +
+ private static int compareSort(Category c1, Category c2) { + private static int compareSort(String c1, String c2) {
+ int o1 = KeyMapping.Category.SORT_ORDER.indexOf(c1); + Integer o1 = CATEGORY_SORT_ORDER.get(c1);
+ int o2 = KeyMapping.Category.SORT_ORDER.indexOf(c2); + Integer o2 = CATEGORY_SORT_ORDER.get(c2);
+ if (o1 == -1 && o2 != -1) return 1; + if (o1 == null && o2 != null) return 1;
+ if (o1 != -1 && o2 == -1) return -1; + if (o1 != null && o2 == null) return -1;
+ if (o1 == -1 && o2 == -1) return I18n.get(c1.id().toLanguageKey("key.category")).compareTo(I18n.get(c1.id().toLanguageKey("key.category"))); + if (o1 == null && o2 == null) return I18n.get(c1).compareTo(I18n.get(c2));
+ return o1 - o2; + return o1.compareTo(o2);
} }
public static Supplier<Component> createNameSupplier(String p_90843_) { public static Supplier<Component> createNameSupplier(String p_90843_) {
@@ -159,6 +_,20 @@ @@ -146,6 +_,20 @@
} }
public boolean same(KeyMapping p_90851_) { public boolean same(KeyMapping p_90851_) {
@@ -70,7 +77,7 @@
return this.key.equals(p_90851_.key); return this.key.equals(p_90851_.key);
} }
@@ -177,11 +_,13 @@ @@ -164,11 +_,13 @@
} }
public Component getTranslatedKeyMessage() { public Component getTranslatedKeyMessage() {
@@ -85,15 +92,9 @@
} }
public String saveString() { public String saveString() {
@@ -193,11 +_,94 @@ @@ -182,5 +_,88 @@
} @Nullable
public static KeyMapping get(String p_378660_) {
private void registerMapping(InputConstants.Key p_423386_) {
- MAP.computeIfAbsent(p_423386_, p_420623_ -> new ArrayList<>()).add(this);
+ MAP.put(p_423386_, this);
}
public static @Nullable KeyMapping get(String p_378660_) {
return ALL.get(p_378660_); return ALL.get(p_378660_);
+ } + }
+ +
@@ -104,28 +105,28 @@
+ /** + /**
+ * Convenience constructor for creating KeyBindings with keyConflictContext set. + * Convenience constructor for creating KeyBindings with keyConflictContext set.
+ */ + */
+ public KeyMapping(String description, net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext, final InputConstants.Type inputType, final int keyCode, Category category, int order) { + public KeyMapping(String description, net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext, final InputConstants.Type inputType, final int keyCode, String category) {
+ this(description, keyConflictContext, inputType.getOrCreate(keyCode), category, order); + this(description, keyConflictContext, inputType.getOrCreate(keyCode), category);
+ } + }
+ +
+ /** + /**
+ * Convenience constructor for creating KeyBindings with keyConflictContext set. + * Convenience constructor for creating KeyBindings with keyConflictContext set.
+ */ + */
+ public KeyMapping(String description, net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext, InputConstants.Key keyCode, Category category, int order) { + public KeyMapping(String description, net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext, InputConstants.Key keyCode, String category) {
+ this(description, keyConflictContext, net.minecraftforge.client.settings.KeyModifier.NONE, keyCode, category, order); + this(description, keyConflictContext, net.minecraftforge.client.settings.KeyModifier.NONE, keyCode, category);
+ } + }
+ +
+ /** + /**
+ * Convenience constructor for creating KeyBindings with keyConflictContext and keyModifier set. + * Convenience constructor for creating KeyBindings with keyConflictContext and keyModifier set.
+ */ + */
+ public KeyMapping(String description, net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext, net.minecraftforge.client.settings.KeyModifier keyModifier, final InputConstants.Type inputType, final int keyCode, Category category, int order) { + public KeyMapping(String description, net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext, net.minecraftforge.client.settings.KeyModifier keyModifier, final InputConstants.Type inputType, final int keyCode, String category) {
+ this(description, keyConflictContext, keyModifier, inputType.getOrCreate(keyCode), category, order); + this(description, keyConflictContext, keyModifier, inputType.getOrCreate(keyCode), category);
+ } + }
+ +
+ /** + /**
+ * Convenience constructor for creating KeyBindings with keyConflictContext and keyModifier set. + * Convenience constructor for creating KeyBindings with keyConflictContext and keyModifier set.
+ */ + */
+ public KeyMapping(String description, net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext, net.minecraftforge.client.settings.KeyModifier keyModifier, InputConstants.Key keyCode, Category category, int order) { + public KeyMapping(String description, net.minecraftforge.client.settings.IKeyConflictContext keyConflictContext, net.minecraftforge.client.settings.KeyModifier keyModifier, InputConstants.Key keyCode, String category) {
+ this.name = description; + this.name = description;
+ this.key = keyCode; + this.key = keyCode;
+ this.defaultKey = keyCode; + this.defaultKey = keyCode;
@@ -133,11 +134,11 @@
+ this.keyConflictContext = keyConflictContext; + this.keyConflictContext = keyConflictContext;
+ this.keyModifier = keyModifier; + this.keyModifier = keyModifier;
+ this.keyModifierDefault = keyModifier; + this.keyModifierDefault = keyModifier;
+ this.order = order;
+ if (this.keyModifier.matches(keyCode)) + if (this.keyModifier.matches(keyCode))
+ this.keyModifier = net.minecraftforge.client.settings.KeyModifier.NONE; + this.keyModifier = net.minecraftforge.client.settings.KeyModifier.NONE;
+ ALL.put(description, this); + ALL.put(description, this);
+ MAP.put(keyCode, this); + MAP.put(keyCode, this);
+ CATEGORIES.add(category);
+ } + }
+ +
+ @Override + @Override
@@ -179,5 +180,4 @@
+ +
+ MAP.put(keyCode, this); + MAP.put(keyCode, this);
} }
}
@OnlyIn(Dist.CLIENT)
@@ -1,37 +1,39 @@
--- a/net/minecraft/client/KeyboardHandler.java --- a/net/minecraft/client/KeyboardHandler.java
+++ b/net/minecraft/client/KeyboardHandler.java +++ b/net/minecraft/client/KeyboardHandler.java
@@ -497,7 +_,7 @@ @@ -440,12 +_,12 @@
if (screen != null) { if (screen != null) {
try { try {
if (p_90895_ != 1 && p_90895_ != 2) { if (p_90897_ != 1 && p_90897_ != 2) {
- if (p_90895_ == 0 && screen.keyReleased(p_423534_)) { - if (p_90897_ == 0 && screen.keyReleased(p_90895_, p_90896_, p_90898_)) {
+ if (p_90895_ == 0 && net.minecraftforge.client.ForgeHooksClient.onScreenKeyReleased(screen, p_423534_)) { + if (p_90897_ == 0 && net.minecraftforge.client.ForgeHooksClient.onScreenKeyReleased(screen, p_90895_, p_90896_, p_90898_)) {
if (options.keyDebugModifier.matches(p_423534_)) { return;
this.usedDebugKeyAsModifier = false;
}
@@ -506,7 +_,7 @@
} }
} else { } else {
screen.afterKeyboardAction(); screen.afterKeyboardAction();
- if (screen.keyPressed(p_423534_)) { - if (screen.keyPressed(p_90895_, p_90896_, p_90898_)) {
+ if (net.minecraftforge.client.ForgeHooksClient.onScreenKeyPressed(screen, p_423534_)) { + if (net.minecraftforge.client.ForgeHooksClient.onScreenKeyPressed(screen, p_90895_, p_90896_, p_90898_)) {
if (this.minecraft.screen == null) { return;
InputConstants.Key inputconstants$key = InputConstants.getKey(p_423534_); }
KeyMapping.set(inputconstants$key, false); }
@@ -582,6 +_,7 @@ @@ -504,6 +_,7 @@
} }
} }
} }
+ net.minecraftforge.client.ForgeHooksClient.onKeyInput(p_423534_, p_90895_); + net.minecraftforge.client.ForgeHooksClient.onKeyInput(p_90895_, p_90896_, p_90897_, p_90898_);
} }
} }
@@ -590,7 +_,7 @@ @@ -513,10 +_,10 @@
Screen screen = this.minecraft.screen;
if (screen != null && this.minecraft.getOverlay() == null) { if (screen != null && this.minecraft.getOverlay() == null) {
try { try {
- screen.charTyped(p_427531_); if (Character.isBmpCodePoint(p_90891_)) {
+ net.minecraftforge.client.ForgeHooksClient.onScreenCharTyped(screen, p_427531_); - screen.charTyped((char)p_90891_, p_90892_);
+ net.minecraftforge.client.ForgeHooksClient.onScreenCharTyped(screen, (char)p_90891_, p_90892_);
} else if (Character.isValidCodePoint(p_90891_)) {
- screen.charTyped(Character.highSurrogate(p_90891_), p_90892_);
- screen.charTyped(Character.lowSurrogate(p_90891_), p_90892_);
+ net.minecraftforge.client.ForgeHooksClient.onScreenCharTyped(screen, Character.highSurrogate(p_90891_), p_90892_);
+ net.minecraftforge.client.ForgeHooksClient.onScreenCharTyped(screen, Character.lowSurrogate(p_90891_), p_90892_);
}
} catch (Throwable throwable) { } catch (Throwable throwable) {
CrashReport crashreport = CrashReport.forThrowable(throwable, "charTyped event handler"); CrashReport crashreport = CrashReport.forThrowable(throwable, "charTyped event handler");
screen.fillCrashDetails(crashreport);
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/Minecraft.java --- a/net/minecraft/client/Minecraft.java
+++ b/net/minecraft/client/Minecraft.java +++ b/net/minecraft/client/Minecraft.java
@@ -265,7 +_,7 @@ @@ -256,7 +_,7 @@
import org.slf4j.Logger; import org.slf4j.Logger;
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
@@ -8,8 +8,8 @@
+public class Minecraft extends ReentrantBlockableEventLoop<Runnable> implements WindowEventHandler, net.minecraftforge.client.extensions.IForgeMinecraft { +public class Minecraft extends ReentrantBlockableEventLoop<Runnable> implements WindowEventHandler, net.minecraftforge.client.extensions.IForgeMinecraft {
static Minecraft instance; static Minecraft instance;
private static final Logger LOGGER = LogUtils.getLogger(); private static final Logger LOGGER = LogUtils.getLogger();
private static final int MAX_TICKS_PER_UPDATE = 10; public static final boolean ON_OSX = Util.getPlatform() == Util.OS.OSX;
@@ -431,7 +_,6 @@ @@ -435,7 +_,6 @@
} }
}, Util.nonCriticalIoPool()); }, Util.nonCriticalIoPool());
LOGGER.info("Setting user: {}", this.user.getName()); LOGGER.info("Setting user: {}", this.user.getName());
@@ -17,19 +17,19 @@
this.demo = p_91084_.game.demo; this.demo = p_91084_.game.demo;
this.allowsMultiplayer = !p_91084_.game.disableMultiplayer; this.allowsMultiplayer = !p_91084_.game.disableMultiplayer;
this.allowsChat = !p_91084_.game.disableChat; this.allowsChat = !p_91084_.game.disableChat;
@@ -483,10 +_,9 @@ @@ -486,10 +_,9 @@
LOGGER.error("Couldn't set icon", (Throwable)ioexception); LOGGER.error("Couldn't set icon", (Throwable)ioexception);
} }
+ // FORGE: Move mouse and keyboard handler setup further below + // FORGE: Move mouse and keyboard handler setup further below
this.mouseHandler = new MouseHandler(this); this.mouseHandler = new MouseHandler(this);
- this.mouseHandler.setup(this.window); - this.mouseHandler.setup(this.window.getWindow());
this.keyboardHandler = new KeyboardHandler(this); this.keyboardHandler = new KeyboardHandler(this);
- this.keyboardHandler.setup(this.window); - this.keyboardHandler.setup(this.window.getWindow());
RenderSystem.initRenderer( RenderSystem.initRenderer(
this.window.handle(), this.window.getWindow(),
this.options.glDebugVerbosity, this.options.glDebugVerbosity,
@@ -498,6 +_,7 @@ @@ -500,6 +_,7 @@
LOGGER.info("Using optional rendering extensions: {}", String.join(", ", RenderSystem.getDevice().getEnabledExtensions())); LOGGER.info("Using optional rendering extensions: {}", String.join(", ", RenderSystem.getDevice().getEnabledExtensions()));
this.mainRenderTarget = new MainTarget(this.window.getWidth(), this.window.getHeight()); this.mainRenderTarget = new MainTarget(this.window.getWidth(), this.window.getHeight());
this.resourceManager = new ReloadableResourceManager(PackType.CLIENT_RESOURCES); this.resourceManager = new ReloadableResourceManager(PackType.CLIENT_RESOURCES);
@@ -37,40 +37,40 @@
this.resourcePackRepository.reload(); this.resourcePackRepository.reload();
this.options.loadSelectedResourcePacks(this.resourcePackRepository); this.options.loadSelectedResourcePacks(this.resourcePackRepository);
this.languageManager = new LanguageManager(this.options.languageCode, p_340763_ -> { this.languageManager = new LanguageManager(this.options.languageCode, p_340763_ -> {
@@ -585,6 +_,7 @@ @@ -578,6 +_,7 @@
this.particleResources = new ParticleResources(); this.blockEntityRenderDispatcher = new BlockEntityRenderDispatcher(this.font, this.modelManager.entityModels(), this.blockRenderer, this.itemModelResolver, this.itemRenderer, this.entityRenderDispatcher);
this.resourceManager.registerReloadListener(this.particleResources); this.resourceManager.registerReloadListener(this.blockEntityRenderDispatcher);
this.particleEngine = new ParticleEngine(this.level, this.particleResources); this.particleEngine = new ParticleEngine(this.level, this.textureManager);
+ net.minecraftforge.client.ForgeHooksClient.onRegisterParticleProviders(this.particleResources); + net.minecraftforge.client.ForgeHooksClient.onRegisterParticleProviders(this.particleEngine);
this.particleResources.onReload(this.particleEngine::clearParticles); this.resourceManager.registerReloadListener(this.particleEngine);
this.waypointStyles = new WaypointStyleManager(); this.paintingTextures = new PaintingTextureManager(this.textureManager);
this.resourceManager.registerReloadListener(this.waypointStyles); this.resourceManager.registerReloadListener(this.paintingTextures);
@@ -596,6 +_,9 @@ @@ -593,6 +_,9 @@
this.resourceManager.registerReloadListener(this.gpuWarnlistManager); this.resourceManager.registerReloadListener(this.gpuWarnlistManager);
this.resourceManager.registerReloadListener(this.regionalCompliancies); this.resourceManager.registerReloadListener(this.regionalCompliancies);
this.gui = new Gui(this); this.gui = new Gui(this);
+ // FORGE: Moved keyboard and mouse handler setup below ingame gui creation to prevent NPEs in them. + // FORGE: Moved keyboard and mouse handler setup below ingame gui creation to prevent NPEs in them.
+ this.mouseHandler.setup(this.window); + this.mouseHandler.setup(this.window.getWindow());
+ this.keyboardHandler.setup(this.window); + this.keyboardHandler.setup(this.window.getWindow());
this.debugRenderer = new DebugRenderer(this);
RealmsClient realmsclient = RealmsClient.getOrCreate(this); RealmsClient realmsclient = RealmsClient.getOrCreate(this);
this.realmsDataFetcher = new RealmsDataFetcher(realmsclient); this.realmsDataFetcher = new RealmsDataFetcher(realmsclient);
RenderSystem.setErrorCallback(this::onFullscreenError); @@ -626,6 +_,7 @@
@@ -628,6 +_,7 @@
} }
} }
+ net.minecraftforge.client.ForgeHooksClient.initClientHooks(this, this.resourceManager); + net.minecraftforge.client.ForgeHooksClient.initClientHooks(this, this.resourceManager);
this.window.updateVsync(this.options.enableVsync().get()); this.window.updateVsync(this.options.enableVsync().get());
this.window.updateRawMouseInput(this.options.rawMouseInput().get()); this.window.updateRawMouseInput(this.options.rawMouseInput().get());
this.window.setAllowCursorChanges(this.options.allowCursorChanges().get()); this.window.setDefaultErrorCallback();
@@ -651,16 +_,17 @@ @@ -648,16 +_,17 @@
GameLoadTimesEvent.INSTANCE.beginStep(TelemetryProperty.LOAD_TIME_LOADING_OVERLAY_MS); GameLoadTimesEvent.INSTANCE.beginStep(TelemetryProperty.LOAD_TIME_LOADING_OVERLAY_MS);
Minecraft.GameLoadCookie minecraft$gameloadcookie = new Minecraft.GameLoadCookie(realmsclient, p_91084_.quickPlay); Minecraft.GameLoadCookie minecraft$gameloadcookie = new Minecraft.GameLoadCookie(realmsclient, p_91084_.quickPlay);
this.setOverlay( this.setOverlay(
- new LoadingOverlay( - new LoadingOverlay(
- this, reloadinstance, p_447796_ -> Util.ifElse(p_447796_, p_296162_ -> this.rollbackResourcePacks(p_296162_, minecraft$gameloadcookie), () -> { - this, reloadinstance, p_296164_ -> Util.ifElse(p_296164_, p_296162_ -> this.rollbackResourcePacks(p_296162_, minecraft$gameloadcookie), () -> {
+ net.minecraftforge.fml.loading.ImmediateWindowHandler.<LoadingOverlay>loadingOverlay( + net.minecraftforge.fml.loading.ImmediateWindowHandler.<LoadingOverlay>loadingOverlay(
+ () -> this, () -> reloadinstance, p_296164_ -> Util.ifElse(p_296164_, p_447796_ -> this.rollbackResourcePacks(p_447796_, minecraft$gameloadcookie), () -> { + () -> this, () -> reloadinstance, p_296164_ -> Util.ifElse(p_296164_, p_296162_ -> this.rollbackResourcePacks(p_296162_, minecraft$gameloadcookie), () -> {
if (SharedConstants.IS_RUNNING_IN_IDE) { if (SharedConstants.IS_RUNNING_IN_IDE) {
this.selfTest(); this.selfTest();
} }
@@ -84,7 +84,7 @@
); );
this.quickPlayLog = QuickPlayLog.of(p_91084_.quickPlay.logPath()); this.quickPlayLog = QuickPlayLog.of(p_91084_.quickPlay.logPath());
this.framerateLimitTracker = new FramerateLimitTracker(this.options, this); this.framerateLimitTracker = new FramerateLimitTracker(this.options, this);
@@ -779,6 +_,7 @@ @@ -759,6 +_,7 @@
StringBuilder stringbuilder = new StringBuilder("Minecraft"); StringBuilder stringbuilder = new StringBuilder("Minecraft");
if (checkModStatus().shouldReportAsModified()) { if (checkModStatus().shouldReportAsModified()) {
stringbuilder.append("*"); stringbuilder.append("*");
@@ -92,25 +92,25 @@
} }
stringbuilder.append(" "); stringbuilder.append(" ");
@@ -802,6 +_,8 @@ @@ -782,6 +_,8 @@
} }
private UserApiService createUserApiService(YggdrasilAuthenticationService p_193586_, GameConfig p_193587_) { private UserApiService createUserApiService(YggdrasilAuthenticationService p_193586_, GameConfig p_193587_) {
+ if ("0".equals(p_193587_.user.user.getAccessToken())) // Forge: We use "0" in dev. Short circuit to stop exception spam. + if ("0".equals(p_193587_.user.user.getAccessToken())) // Forge: We use "0" in dev. Short circuit to stop exception spam.
+ return UserApiService.OFFLINE; + return UserApiService.OFFLINE;
return p_193587_.game.offlineDeveloperMode ? UserApiService.OFFLINE : p_193586_.createUserApiService(p_193587_.user.user.getAccessToken()); return p_193587_.user.user.getType() != User.Type.MSA
? UserApiService.OFFLINE
: p_193586_.createUserApiService(p_193587_.user.user.getAccessToken());
@@ -792,7 +_,7 @@
} }
@@ -814,7 +_,7 @@ private void rollbackResourcePacks(Throwable p_91240_, @Nullable Minecraft.GameLoadCookie p_299515_) {
}
private void rollbackResourcePacks(Throwable p_91240_, Minecraft.@Nullable GameLoadCookie p_299515_) {
- if (this.resourcePackRepository.getSelectedIds().size() > 1) { - if (this.resourcePackRepository.getSelectedIds().size() > 1) {
+ if (this.resourcePackRepository.getSelectedPacks().stream().anyMatch(e -> !e.isRequired())) { //Forge: This caused infinite loop if any resource packs are forced. Such as mod resources. So check if we can disable any. + if (this.resourcePackRepository.getSelectedPacks().stream().anyMatch(e -> !e.isRequired())) { //Forge: This caused infinite loop if any resource packs are forced. Such as mod resources. So check if we can disable any.
this.clearResourcePacksOnError(p_91240_, null, p_299515_); this.clearResourcePacksOnError(p_91240_, null, p_299515_);
} else { } else {
Util.throwAsRuntime(p_91240_); Util.throwAsRuntime(p_91240_);
@@ -1100,12 +_,6 @@ @@ -1078,12 +_,6 @@
LOGGER.error("setScreen called from non-game thread"); LOGGER.error("setScreen called from non-game thread");
} }
@@ -120,55 +120,57 @@
- this.setLastInputType(InputType.NONE); - this.setLastInputType(InputType.NONE);
- } - }
- -
if (p_91153_ == null) { if (p_91153_ == null && this.clientLevelTeardownInProgress) {
if (this.clientLevelTeardownInProgress) { throw new IllegalStateException("Trying to return to in-game GUI during disconnection");
throw new IllegalStateException("Trying to return to in-game GUI during disconnection"); } else {
@@ -1124,6 +_,23 @@ @@ -1097,6 +_,23 @@
}
} }
}
+ net.minecraftforge.client.ForgeHooksClient.clearGuiLayers(this); + net.minecraftforge.client.ForgeHooksClient.clearGuiLayers(this);
+ Screen old = this.screen; + Screen old = this.screen;
+ if (p_91153_ != null) { + if (p_91153_ != null) {
+ var event = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenOpening(old, p_91153_); + var event = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenOpening(old, p_91153_);
+ if (event == null) return; + if (event == null) return;
+ p_91153_ = event; + p_91153_ = event;
+ }
+
+ if (p_91153_ != old) {
+ if (old != null) {
+ net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenClose(old);
+ old.removed();
+ } else {
+ this.setLastInputType(InputType.NONE);
+ } + }
+ }
+ +
this.screen = p_91153_; + if (p_91153_ != old) {
if (this.screen != null) { + if (old != null) {
this.screen.added(); + net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenClose(old);
@@ -1207,6 +_,7 @@ + old.removed();
+ } else {
+ this.setLastInputType(InputType.NONE);
+ }
+ }
+
this.screen = p_91153_;
if (this.screen != null) {
this.screen.added();
@@ -1180,6 +_,7 @@
FreeTypeUtil.destroy();
Util.shutdownExecutors(); Util.shutdownExecutors();
RenderSystem.getSamplerCache().close();
RenderSystem.getDevice().close(); RenderSystem.getDevice().close();
+ net.minecraftforge.fml.config.ConfigTracker.INSTANCE.forceUnload(); + net.minecraftforge.fml.config.ConfigTracker.INSTANCE.forceUnload();
} catch (Throwable throwable) { } catch (Throwable throwable) {
LOGGER.error("Shutdown failure!", throwable); LOGGER.error("Shutdown failure!", throwable);
throw throwable; throw throwable;
@@ -1289,7 +_,9 @@ @@ -1248,9 +_,11 @@
RenderSystem.getDevice().createCommandEncoder().clearColorAndDepthTextures(rendertarget.getColorTexture(), 0, rendertarget.getDepthTexture(), 1.0); this.mouseHandler.handleAccumulatedMovement();
profilerfiller.push("gameRenderer"); profilerfiller.pop();
if (!this.noRender) { if (!this.noRender) {
+ net.minecraftforge.client.event.ForgeEventFactoryClient.onRenderTickStart(this.deltaTracker); + net.minecraftforge.client.event.ForgeEventFactoryClient.onRenderTickStart(this.deltaTracker);
this.gameRenderer.render(this.deltaTracker, p_91384_); profilerfiller.popPush("gameRenderer");
+ net.minecraftforge.client.event.ForgeEventFactoryClient.onRenderTickEnd(this.deltaTracker); this.gameRenderer.render(this.deltaTracker, p_91384_);
} profilerfiller.pop();
+ net.minecraftforge.client.event.ForgeEventFactoryClient.onRenderTickEnd(this.deltaTracker);
}
profilerfiller.popPush("blit"); profilerfiller.push("blit");
@@ -1401,10 +_,12 @@ @@ -1379,10 +_,12 @@
this.window.setGuiScale(i); this.window.setGuiScale(i);
if (this.screen != null) { if (this.screen != null) {
this.screen.resize(this.window.getGuiScaledWidth(), this.window.getGuiScaledHeight()); this.screen.resize(this, this.window.getGuiScaledWidth(), this.window.getGuiScaledHeight());
+ net.minecraftforge.client.ForgeHooksClient.resizeGuiLayers(this, this.window.getGuiScaledWidth(), this.window.getGuiScaledHeight()); + net.minecraftforge.client.ForgeHooksClient.resizeGuiLayers(this, this.window.getGuiScaledWidth(), this.window.getGuiScaledHeight());
} }
@@ -178,7 +180,7 @@
this.gameRenderer.resize(this.window.getWidth(), this.window.getHeight()); this.gameRenderer.resize(this.window.getWidth(), this.window.getHeight());
this.mouseHandler.setIgnoreFirstMove(); this.mouseHandler.setIgnoreFirstMove();
} }
@@ -1542,6 +_,7 @@ @@ -1520,6 +_,7 @@
} }
public void stop() { public void stop() {
@@ -186,59 +188,58 @@
this.running = false; this.running = false;
} }
@@ -1571,10 +_,18 @@ @@ -1547,10 +_,18 @@
if (p_91387_ && this.hitResult != null && this.hitResult.getType() == HitResult.Type.BLOCK) { if (p_91387_ && this.hitResult != null && this.hitResult.getType() == HitResult.Type.BLOCK) {
BlockHitResult blockhitresult = (BlockHitResult)this.hitResult; BlockHitResult blockhitresult = (BlockHitResult)this.hitResult;
BlockPos blockpos = blockhitresult.getBlockPos(); BlockPos blockpos = blockhitresult.getBlockPos();
- if (!this.level.getBlockState(blockpos).isAir()) { - if (!this.level.getBlockState(blockpos).isAir()) {
+ if (!this.level.isEmptyBlock(blockpos)) { + if (!this.level.isEmptyBlock(blockpos)) {
+ var inputEvent = new net.minecraftforge.client.event.InputEvent.InteractionKeyMappingTriggered(0, this.options.keyAttack, InteractionHand.MAIN_HAND);
+ if (net.minecraftforge.client.event.InputEvent.InteractionKeyMappingTriggered.BUS.post(inputEvent)) {
+ if (inputEvent.shouldSwingHand()) {
+ this.level.addBreakingBlockEffect(blockpos, blockhitresult);
+ this.player.swing(InteractionHand.MAIN_HAND);
+ }
+ return;
+ }
Direction direction = blockhitresult.getDirection();
- if (this.gameMode.continueDestroyBlock(blockpos, direction)) {
- this.level.addBreakingBlockEffect(blockpos, direction);
+ if (this.gameMode.continueDestroyBlock(blockpos, direction) && inputEvent.shouldSwingHand()) {
+ this.level.addBreakingBlockEffect(blockpos, blockhitresult);
this.player.swing(InteractionHand.MAIN_HAND);
}
}
@@ -1611,6 +_,8 @@
this.player.swing(InteractionHand.MAIN_HAND);
return true;
} else {
+ var inputEvent = new net.minecraftforge.client.event.InputEvent.InteractionKeyMappingTriggered(0, this.options.keyAttack, InteractionHand.MAIN_HAND); + var inputEvent = new net.minecraftforge.client.event.InputEvent.InteractionKeyMappingTriggered(0, this.options.keyAttack, InteractionHand.MAIN_HAND);
+ if (!net.minecraftforge.client.event.InputEvent.InteractionKeyMappingTriggered.BUS.post(inputEvent)) + if (net.minecraftforge.client.event.InputEvent.InteractionKeyMappingTriggered.BUS.post(inputEvent)) {
switch (this.hitResult.getType()) { + if (inputEvent.shouldSwingHand()) {
case ENTITY: + this.particleEngine.addBlockHitEffects(blockpos, blockhitresult);
AttackRange attackrange = itemstack.get(DataComponents.ATTACK_RANGE); + this.player.swing(InteractionHand.MAIN_HAND);
@@ -1621,7 +_,7 @@ + }
case BLOCK: + return;
BlockHitResult blockhitresult = (BlockHitResult)this.hitResult; + }
BlockPos blockpos = blockhitresult.getBlockPos(); Direction direction = blockhitresult.getDirection();
- if (!this.level.getBlockState(blockpos).isAir()) { - if (this.gameMode.continueDestroyBlock(blockpos, direction)) {
+ if (!this.level.isEmptyBlock(blockpos)) { - this.particleEngine.crack(blockpos, direction);
this.gameMode.startDestroyBlock(blockpos, blockhitresult.getDirection()); + if (this.gameMode.continueDestroyBlock(blockpos, direction) && inputEvent.shouldSwingHand()) {
if (this.level.getBlockState(blockpos).isAir()) { + this.particleEngine.addBlockHitEffects(blockpos, blockhitresult);
flag = true;
@@ -1634,9 +_,10 @@
}
this.player.resetAttackStrengthTicker();
+ net.minecraftforge.event.ForgeEventFactory.onLeftClickEmpty(this.player);
}
- if (!this.player.isSpectator()) {
+ if (!this.player.isSpectator() && inputEvent.shouldSwingHand()) {
this.player.swing(InteractionHand.MAIN_HAND); this.player.swing(InteractionHand.MAIN_HAND);
} }
}
@@ -1578,6 +_,8 @@
return false;
} else {
boolean flag = false;
+ var inputEvent = new net.minecraftforge.client.event.InputEvent.InteractionKeyMappingTriggered(0, this.options.keyAttack, InteractionHand.MAIN_HAND);
+ if (!net.minecraftforge.client.event.InputEvent.InteractionKeyMappingTriggered.BUS.post(inputEvent))
switch (this.hitResult.getType()) {
case ENTITY:
this.gameMode.attack(this.player, ((EntityHitResult)this.hitResult).getEntity());
@@ -1585,7 +_,7 @@
case BLOCK:
BlockHitResult blockhitresult = (BlockHitResult)this.hitResult;
BlockPos blockpos = blockhitresult.getBlockPos();
- if (!this.level.getBlockState(blockpos).isAir()) {
+ if (!this.level.isEmptyBlock(blockpos)) {
this.gameMode.startDestroyBlock(blockpos, blockhitresult.getDirection());
if (this.level.getBlockState(blockpos).isAir()) {
flag = true;
@@ -1598,8 +_,10 @@
}
@@ -1655,6 +_,12 @@ this.player.resetAttackStrengthTicker();
+ net.minecraftforge.event.ForgeEventFactory.onLeftClickEmpty(this.player);
}
+ if (inputEvent.shouldSwingHand())
this.player.swing(InteractionHand.MAIN_HAND);
return flag;
}
@@ -1615,6 +_,12 @@
} }
for (InteractionHand interactionhand : InteractionHand.values()) { for (InteractionHand interactionhand : InteractionHand.values()) {
@@ -251,16 +252,16 @@
ItemStack itemstack = this.player.getItemInHand(interactionhand); ItemStack itemstack = this.player.getItemInHand(interactionhand);
if (!itemstack.isItemEnabled(this.level.enabledFeatures())) { if (!itemstack.isItemEnabled(this.level.enabledFeatures())) {
return; return;
@@ -1676,7 +_,7 @@ @@ -1635,7 +_,7 @@
}
if (interactionresult instanceof InteractionResult.Success interactionresult$success2) {
- if (interactionresult$success2.swingSource() == InteractionResult.SwingSource.CLIENT) {
+ if (interactionresult$success2.swingSource() == InteractionResult.SwingSource.CLIENT && inputEvent.shouldSwingHand()) {
this.player.swing(interactionhand);
} }
if (interactionresult instanceof InteractionResult.Success interactionresult$success2) { @@ -1647,7 +_,7 @@
- if (interactionresult$success2.swingSource() == InteractionResult.SwingSource.CLIENT) {
+ if (interactionresult$success2.swingSource() == InteractionResult.SwingSource.CLIENT && inputEvent.shouldSwingHand()) {
this.player.swing(interactionhand);
}
@@ -1689,7 +_,7 @@
int i = itemstack.getCount(); int i = itemstack.getCount();
InteractionResult interactionresult1 = this.gameMode.useItemOn(this.player, interactionhand, blockhitresult); InteractionResult interactionresult1 = this.gameMode.useItemOn(this.player, interactionhand, blockhitresult);
if (interactionresult1 instanceof InteractionResult.Success interactionresult$success) { if (interactionresult1 instanceof InteractionResult.Success interactionresult$success) {
@@ -269,7 +270,7 @@
this.player.swing(interactionhand); this.player.swing(interactionhand);
if (!itemstack.isEmpty() && (itemstack.getCount() != i || this.player.hasInfiniteMaterials())) { if (!itemstack.isEmpty() && (itemstack.getCount() != i || this.player.hasInfiniteMaterials())) {
this.gameRenderer.itemInHandRenderer.itemUsed(interactionhand); this.gameRenderer.itemInHandRenderer.itemUsed(interactionhand);
@@ -1705,6 +_,9 @@ @@ -1663,6 +_,9 @@
} }
} }
@@ -279,7 +280,7 @@
if (!itemstack.isEmpty() if (!itemstack.isEmpty()
&& this.gameMode.useItem(this.player, interactionhand) instanceof InteractionResult.Success interactionresult$success1) { && this.gameMode.useItem(this.player, interactionhand) instanceof InteractionResult.Success interactionresult$success1) {
if (interactionresult$success1.swingSource() == InteractionResult.SwingSource.CLIENT) { if (interactionresult$success1.swingSource() == InteractionResult.SwingSource.CLIENT) {
@@ -1734,6 +_,8 @@ @@ -1692,6 +_,8 @@
} }
ProfilerFiller profilerfiller = Profiler.get(); ProfilerFiller profilerfiller = Profiler.get();
@@ -288,7 +289,7 @@
profilerfiller.push("gui"); profilerfiller.push("gui");
this.chatListener.tick(); this.chatListener.tick();
this.gui.tick(this.pause); this.gui.tick(this.pause);
@@ -1815,6 +_,7 @@ @@ -1778,6 +_,7 @@
this.tutorial.tick(); this.tutorial.tick();
@@ -296,7 +297,7 @@
try { try {
this.level.tick(() -> true); this.level.tick(() -> true);
} catch (Throwable throwable1) { } catch (Throwable throwable1) {
@@ -1828,6 +_,7 @@ @@ -1791,6 +_,7 @@
throw new ReportedException(crashreport1); throw new ReportedException(crashreport1);
} }
@@ -304,7 +305,7 @@
} }
profilerfiller.popPush("animateTick"); profilerfiller.popPush("animateTick");
@@ -1852,6 +_,7 @@ @@ -1815,6 +_,7 @@
profilerfiller.popPush("keyboard"); profilerfiller.popPush("keyboard");
this.keyboardHandler.tick(); this.keyboardHandler.tick();
profilerfiller.pop(); profilerfiller.pop();
@@ -312,15 +313,15 @@
} }
private boolean isLevelRunningNormally() { private boolean isLevelRunningNormally() {
@@ -2070,6 +_,7 @@ @@ -2031,6 +_,7 @@
} }
public void setLevel(ClientLevel p_91157_) { public void setLevel(ClientLevel p_91157_, ReceivingLevelScreen.Reason p_335893_) {
+ if (this.level != null) net.minecraftforge.event.ForgeEventFactory.onLevelUnload(this.level); + if (this.level != null) net.minecraftforge.event.ForgeEventFactory.onLevelUnload(this.level);
this.updateScreenAndTick(new ReceivingLevelScreen(() -> false, p_335893_));
this.level = p_91157_; this.level = p_91157_;
this.updateLevelInEngines(p_91157_); this.updateLevelInEngines(p_91157_);
} @@ -2068,6 +_,7 @@
@@ -2131,6 +_,7 @@
IntegratedServer integratedserver = this.singleplayerServer; IntegratedServer integratedserver = this.singleplayerServer;
this.singleplayerServer = null; this.singleplayerServer = null;
this.gameRenderer.resetData(); this.gameRenderer.resetData();
@@ -328,27 +329,27 @@
this.gameMode = null; this.gameMode = null;
this.narrator.clear(); this.narrator.clear();
this.clientLevelTeardownInProgress = true; this.clientLevelTeardownInProgress = true;
@@ -2138,6 +_,7 @@ @@ -2075,6 +_,7 @@
try { try {
this.updateScreenAndTick(p_335030_);
if (this.level != null) { if (this.level != null) {
this.gui.onDisconnected();
+ net.minecraftforge.event.ForgeEventFactory.onLevelUnload(this.level); + net.minecraftforge.event.ForgeEventFactory.onLevelUnload(this.level);
} if (integratedserver != null) {
ProfilerFiller profilerfiller = Profiler.get();
profilerfiller.push("waitForServer");
@@ -2088,6 +_,7 @@
if (integratedserver != null) { this.gui.onDisconnected();
@@ -2150,6 +_,7 @@ this.isLocalServer = false;
}
profilerfiller.pop();
+ net.minecraftforge.client.ForgeHooksClient.handleClientLevelClosing(this.level); + net.minecraftforge.client.ForgeHooksClient.handleClientLevelClosing(this.level);
} }
this.setScreenAndShow(p_457642_); this.level = null;
@@ -2292,6 +_,7 @@ @@ -2236,6 +_,7 @@
private void pickBlock() { private void pickBlock() {
if (this.hitResult != null && this.hitResult.getType() != HitResult.Type.MISS) { if (this.hitResult != null && this.hitResult.getType() != HitResult.Type.MISS) {
+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onClickInputPickBlock(this.options.keyPickItem)) return; + if (net.minecraftforge.client.event.ForgeEventFactoryClient.onClickInputPickBlock(this.options.keyPickItem)) return;
boolean flag = this.hasControlDown(); boolean flag = Screen.hasControlDown();
switch (this.hitResult) { switch (this.hitResult) {
case BlockHitResult blockhitresult: case BlockHitResult blockhitresult:
@@ -1,40 +1,40 @@
--- a/net/minecraft/client/MouseHandler.java --- a/net/minecraft/client/MouseHandler.java
+++ b/net/minecraft/client/MouseHandler.java +++ b/net/minecraft/client/MouseHandler.java
@@ -87,6 +_,7 @@ @@ -90,6 +_,7 @@
this.activeButton = null; this.activeButton = -1;
} }
+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseButtonPre(mousebuttoninfo, p_423948_)) return; + if (net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseButtonPre(p_91532_, p_91533_, p_91534_)) return;
if (this.minecraft.getOverlay() == null) { if (this.minecraft.getOverlay() == null) {
if (this.minecraft.screen == null) { if (this.minecraft.screen == null) {
if (!this.mouseGrabbed && flag) { if (!this.mouseGrabbed && flag) {
@@ -106,7 +_,7 @@ @@ -103,7 +_,7 @@
&& i - this.lastClick.time() < 250L screen.afterMouseAction();
&& this.lastClick.screen() == screen
&& this.lastClickButton == mousebuttonevent.button(); try {
- if (screen.mouseClicked(mousebuttonevent, flag1)) { - if (screen.mouseClicked(d0, d1, i)) {
+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseClicked(screen, d0, d1, mousebuttonevent, flag1)) { + if (net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseClicked(screen, d0, d1, i)) {
this.lastClick = new MouseHandler.LastClick(i, screen);
this.lastClickButton = mousebuttoninfo.button();
return; return;
@@ -121,7 +_,7 @@ }
} catch (Throwable throwable1) {
@@ -116,7 +_,7 @@
} }
} else { } else {
try { try {
- if (screen.mouseReleased(mousebuttonevent)) { - if (screen.mouseReleased(d0, d1, i)) {
+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseReleased(screen, d0, d1, mousebuttonevent)) { + if (net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseReleased(screen, d0, d1, i)) {
return; return;
} }
} catch (Throwable throwable) { } catch (Throwable throwable) {
@@ -151,6 +_,7 @@ @@ -150,6 +_,7 @@
KeyMapping.click(inputconstants$key);
} }
} }
+ net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseButtonPost(mousebuttoninfo, p_423948_);
} }
+ net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseButtonPost(p_91532_, p_91533_, p_91534_);
} }
@@ -207,7 +_,9 @@ public void fillMousePositionDetails(CrashReportCategory p_398230_, Window p_398216_) {
@@ -189,7 +_,9 @@
if (this.minecraft.screen != null) { if (this.minecraft.screen != null) {
double d3 = this.getScaledXPos(this.minecraft.getWindow()); double d3 = this.getScaledXPos(this.minecraft.getWindow());
double d4 = this.getScaledYPos(this.minecraft.getWindow()); double d4 = this.getScaledYPos(this.minecraft.getWindow());
@@ -45,7 +45,7 @@
this.minecraft.screen.afterMouseAction(); this.minecraft.screen.afterMouseAction();
} else if (this.minecraft.player != null) { } else if (this.minecraft.player != null) {
Vector2i vector2i = this.scrollWheelHandler.onMouseScroll(d1, d2); Vector2i vector2i = this.scrollWheelHandler.onMouseScroll(d1, d2);
@@ -216,6 +_,7 @@ @@ -198,6 +_,7 @@
} }
int i = vector2i.y == 0 ? -vector2i.x : vector2i.y; int i = vector2i.y == 0 ? -vector2i.x : vector2i.y;
@@ -53,16 +53,16 @@
if (this.minecraft.player.isSpectator()) { if (this.minecraft.player.isSpectator()) {
if (this.minecraft.gui.getSpectatorGui().isMenuActive()) { if (this.minecraft.gui.getSpectatorGui().isMenuActive()) {
this.minecraft.gui.getSpectatorGui().onMouseScrolled(-i); this.minecraft.gui.getSpectatorGui().onMouseScrolled(-i);
@@ -324,7 +_,7 @@ @@ -303,7 +_,7 @@
double d5 = getScaledYPos(window, this.accumulatedDY); double d5 = getScaledYPos(window, this.accumulatedDY);
try { try {
- screen.mouseDragged(new MouseButtonEvent(d2, d3, this.activeButton), d4, d5); - screen.mouseDragged(d2, d3, this.activeButton, d4, d5);
+ net.minecraftforge.client.ForgeHooksClient.onScreenMouseDrag(screen, new MouseButtonEvent(d2, d3, this.activeButton), d4, d5); + net.minecraftforge.client.ForgeHooksClient.onScreenMouseDrag(screen, d2, d3, this.activeButton, d4, d5);
} catch (Throwable throwable) { } catch (Throwable throwable) {
CrashReport crashreport1 = CrashReport.forThrowable(throwable, "mouseDragged event handler"); CrashReport crashreport1 = CrashReport.forThrowable(throwable, "mouseDragged event handler");
screen.fillCrashDetails(crashreport1); screen.fillCrashDetails(crashreport1);
@@ -411,6 +_,14 @@ @@ -393,6 +_,14 @@
public double ypos() { public double ypos() {
return this.ypos; return this.ypos;
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/Options.java --- a/net/minecraft/client/Options.java
+++ b/net/minecraft/client/Options.java +++ b/net/minecraft/client/Options.java
@@ -816,7 +_,8 @@ @@ -671,7 +_,8 @@
}, },
new OptionInstance.LazyEnum<>( new OptionInstance.LazyEnum<>(
() -> Stream.concat(Stream.of(""), Minecraft.getInstance().getSoundManager().getAvailableSoundDevices().stream()).toList(), () -> Stream.concat(Stream.of(""), Minecraft.getInstance().getSoundManager().getAvailableSoundDevices().stream()).toList(),
@@ -10,15 +10,15 @@
? Optional.empty() ? Optional.empty()
: Optional.of(p_232011_), : Optional.of(p_232011_),
Codec.STRING Codec.STRING
@@ -848,6 +_,7 @@ @@ -705,6 +_,7 @@
); );
public boolean syncWrites; public boolean syncWrites;
public boolean startedCleanly = true; public boolean startedCleanly = true;
+ private final Map<String, String> unknownKeys = new java.util.HashMap<>(); + private final Map<String, String> unknownKeys = new java.util.HashMap<>();
private static void operateOnLevelRenderer(Consumer<LevelRenderer> p_457625_) { public OptionInstance<Boolean> darkMojangStudiosBackground() {
LevelRenderer levelrenderer = Minecraft.getInstance().levelRenderer; return this.darkMojangStudiosBackground;
@@ -1313,6 +_,7 @@ @@ -1088,6 +_,7 @@
} }
public Options(Minecraft p_92138_, File p_92139_) { public Options(Minecraft p_92138_, File p_92139_) {
@@ -26,9 +26,9 @@
this.minecraft = p_92138_; this.minecraft = p_92138_;
this.optionsFile = new File(p_92139_, "options.txt"); this.optionsFile = new File(p_92139_, "options.txt");
boolean flag = Runtime.getRuntime().maxMemory() >= 1000000000L; boolean flag = Runtime.getRuntime().maxMemory() >= 1000000000L;
@@ -1463,15 +_,28 @@ @@ -1222,15 +_,28 @@
this.startedCleanly = p_168428_.process("startedCleanly", this.startedCleanly); this.startedCleanly = p_168428_.process("startedCleanly", this.startedCleanly);
p_168428_.process("musicToast", this.musicToast); p_168428_.process("showNowPlayingToast", this.showNowPlayingToast);
p_168428_.process("musicFrequency", this.musicFrequency); p_168428_.process("musicFrequency", this.musicFrequency);
+ processOptionsKeysOnly(p_168428_); + processOptionsKeysOnly(p_168428_);
+ processOptionsEnd(p_168428_); + processOptionsEnd(p_168428_);
@@ -56,7 +56,7 @@
for (SoundSource soundsource : SoundSource.values()) { for (SoundSource soundsource : SoundSource.values()) {
p_168428_.process("soundCategory_" + soundsource.getName(), this.soundSourceVolumes.get(soundsource)); p_168428_.process("soundCategory_" + soundsource.getName(), this.soundSourceVolumes.get(soundsource));
} }
@@ -1486,6 +_,10 @@ @@ -1245,6 +_,10 @@
} }
public void load() { public void load() {
@@ -67,17 +67,17 @@
try { try {
if (!this.optionsFile.exists()) { if (!this.optionsFile.exists()) {
return; return;
@@ -1505,7 +_,8 @@ @@ -1269,7 +_,8 @@
this.graphicsMode.set(isTrue(optional.get()) ? GraphicsStatus.FANCY : GraphicsStatus.FAST);
} }
final CompoundTag compoundtag1 = this.dataFix(compoundtag);
- this.processOptions( - this.processOptions(
+ java.util.function.Consumer<FieldAccess> processor = limited ? this::processOptionsKeysOnly : this::processOptions; + java.util.function.Consumer<FieldAccess> processor = limited ? this::processOptionsKeysOnly : this::processOptions;
+ processor.accept( + processor.accept(
new Options.FieldAccess() { new Options.FieldAccess() {
private @Nullable String getValue(String p_394210_) { @Nullable
Tag tag = compoundtag1.get(p_394210_); private String getValue(String p_394210_) {
@@ -1585,6 +_,17 @@ @@ -1350,6 +_,17 @@
); );
compoundtag1.getString("fullscreenResolution").ifPresent(p_389133_ -> this.fullscreenVideoModeString = p_389133_); compoundtag1.getString("fullscreenResolution").ifPresent(p_389133_ -> this.fullscreenVideoModeString = p_389133_);
KeyMapping.resetMapping(); KeyMapping.resetMapping();
@@ -95,7 +95,7 @@
} catch (Exception exception) { } catch (Exception exception) {
LOGGER.error("Failed to load options", (Throwable)exception); LOGGER.error("Failed to load options", (Throwable)exception);
} }
@@ -1612,9 +_,11 @@ @@ -1377,9 +_,11 @@
public void save() { public void save() {
try (final PrintWriter printwriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(this.optionsFile), StandardCharsets.UTF_8))) { try (final PrintWriter printwriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(this.optionsFile), StandardCharsets.UTF_8))) {
printwriter.println("version:" + SharedConstants.getCurrentVersion().dataVersion().version()); printwriter.println("version:" + SharedConstants.getCurrentVersion().dataVersion().version());
@@ -107,7 +107,7 @@
printwriter.print(p_168491_); printwriter.print(p_168491_);
printwriter.print(':'); printwriter.print(':');
} }
@@ -1670,6 +_,12 @@ @@ -1435,6 +_,12 @@
if (s != null) { if (s != null) {
printwriter.println("fullscreenResolution:" + s); printwriter.println("fullscreenResolution:" + s);
} }
@@ -120,7 +120,7 @@
} catch (Exception exception) { } catch (Exception exception) {
LOGGER.error("Failed to save options", (Throwable)exception); LOGGER.error("Failed to save options", (Throwable)exception);
} }
@@ -1707,6 +_,7 @@ @@ -1473,6 +_,7 @@
} }
public void broadcastOptions() { public void broadcastOptions() {
@@ -128,7 +128,7 @@
if (this.minecraft.player != null) { if (this.minecraft.player != null) {
this.minecraft.player.connection.broadcastClientInformation(this.buildPlayerInformation()); this.minecraft.player.connection.broadcastClientInformation(this.buildPlayerInformation());
} }
@@ -1820,6 +_,23 @@ @@ -1586,6 +_,23 @@
public static Component genericValueLabel(Component p_231901_, int p_231902_) { public static Component genericValueLabel(Component p_231901_, int p_231902_) {
return genericValueLabel(p_231901_, Component.literal(Integer.toString(p_231902_))); return genericValueLabel(p_231901_, Component.literal(Integer.toString(p_231902_)));
@@ -4,7 +4,7 @@
file2 = new File(file1, p_92297_); file2 = new File(file1, p_92297_);
} }
+ var event = new net.minecraftforge.client.event.ScreenshotEvent(p_447863_, file2); + var event = new net.minecraftforge.client.event.ScreenshotEvent(p_389141_, file2);
+ if (net.minecraftforge.client.event.ScreenshotEvent.BUS.post(event)) { + if (net.minecraftforge.client.event.ScreenshotEvent.BUS.post(event)) {
+ p_92301_.accept(event.getCancelMessage()); + p_92301_.accept(event.getCancelMessage());
+ return; + return;
@@ -15,12 +15,12 @@
.execute( .execute(
() -> { () -> {
@@ -50,10 +_,13 @@ @@ -50,10 +_,13 @@
NativeImage $$4x = p_447863_; NativeImage $$4x = p_389141_;
try { try {
- p_447863_.writeToFile(file2); - p_389141_.writeToFile(file2);
- Component component = Component.literal(file2.getName()) - Component component = Component.literal(file2.getName())
+ p_447863_.writeToFile(target); + p_389141_.writeToFile(target);
+ Component component = Component.literal(target.getName()) + Component component = Component.literal(target.getName())
.withStyle(ChatFormatting.UNDERLINE) .withStyle(ChatFormatting.UNDERLINE)
.withStyle(p_389149_ -> p_389149_.withClickEvent(new ClickEvent.OpenFile(file2.getAbsoluteFile()))); .withStyle(p_389149_ -> p_389149_.withClickEvent(new ClickEvent.OpenFile(file2.getAbsoluteFile())));
@@ -29,4 +29,4 @@
+ else + else
p_92301_.accept(Component.translatable("screenshot.success", component)); p_92301_.accept(Component.translatable("screenshot.success", component));
} catch (Throwable throwable1) { } catch (Throwable throwable1) {
if (p_447863_ != null) { if (p_389141_ != null) {
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/ToggleKeyMapping.java --- a/net/minecraft/client/ToggleKeyMapping.java
+++ b/net/minecraft/client/ToggleKeyMapping.java +++ b/net/minecraft/client/ToggleKeyMapping.java
@@ -31,7 +_,7 @@ @@ -17,7 +_,7 @@
@Override @Override
public void setDown(boolean p_92534_) { public void setDown(boolean p_92534_) {
if (this.needsToggle.getAsBoolean()) { if (this.needsToggle.getAsBoolean()) {
@@ -9,7 +9,7 @@
super.setDown(!this.isDown()); super.setDown(!this.isDown());
} }
} else { } else {
@@ -56,5 +_,9 @@ @@ -27,5 +_,9 @@
protected void reset() { protected void reset() {
super.setDown(false); super.setDown(false);
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/data/Main.java --- a/net/minecraft/client/data/Main.java
+++ b/net/minecraft/client/data/Main.java +++ b/net/minecraft/client/data/Main.java
@@ -30,13 +_,18 @@ @@ -31,13 +_,18 @@
OptionSpec<Void> optionspec1 = optionparser.accepts("client", "Include client generators"); OptionSpec<Void> optionspec1 = optionparser.accepts("client", "Include client generators");
OptionSpec<Void> optionspec2 = optionparser.accepts("all", "Include all generators"); OptionSpec<Void> optionspec2 = optionparser.accepts("all", "Include all generators");
OptionSpec<String> optionspec3 = optionparser.accepts("output", "Output folder").withRequiredArg().defaultsTo("generated"); OptionSpec<String> optionspec3 = optionparser.accepts("output", "Output folder").withRequiredArg().defaultsTo("generated");
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/data/models/ItemModelGenerators.java --- a/net/minecraft/client/data/models/ItemModelGenerators.java
+++ b/net/minecraft/client/data/models/ItemModelGenerators.java +++ b/net/minecraft/client/data/models/ItemModelGenerators.java
@@ -912,6 +_,9 @@ @@ -871,6 +_,9 @@
this.declareCustomModelItem(Items.COD); this.declareCustomModelItem(Items.COD);
this.declareCustomModelItem(Items.FEATHER); this.declareCustomModelItem(Items.FEATHER);
this.declareCustomModelItem(Items.LEAD); this.declareCustomModelItem(Items.LEAD);
@@ -21,11 +21,11 @@
} }
+ protected Stream<Block> getKnownBlocks() { + protected Stream<Block> getKnownBlocks() {
+ return BuiltInRegistries.BLOCK.stream().filter(block -> "minecraft".equals(block.builtInRegistryHolder().key().identifier().getNamespace())); + return BuiltInRegistries.BLOCK.stream().filter(block -> "minecraft".equals(block.builtInRegistryHolder().key().location().getNamespace()));
+ } + }
+ +
+ protected Stream<Item> getKnownItems() { + protected Stream<Item> getKnownItems() {
+ return BuiltInRegistries.ITEM.stream().filter(item -> "minecraft".equals(item.builtInRegistryHolder().key().identifier().getNamespace())); + return BuiltInRegistries.ITEM.stream().filter(item -> "minecraft".equals(item.builtInRegistryHolder().key().location().getNamespace()));
+ } + }
+ +
+ protected BlockModelGenerators getBlockModelGenerators(BlockStateGeneratorCollector blocks, ItemInfoCollector items, SimpleModelCollector models) { + protected BlockModelGenerators getBlockModelGenerators(BlockStateGeneratorCollector blocks, ItemInfoCollector items, SimpleModelCollector models) {
@@ -46,7 +46,7 @@
+ private final Supplier<Stream<Block>> known; + private final Supplier<Stream<Block>> known;
+ +
+ public BlockStateGeneratorCollector() { + public BlockStateGeneratorCollector() {
+ this(() -> BuiltInRegistries.BLOCK.stream().filter(block -> "minecraft".equals(block.builtInRegistryHolder().key().identifier().getNamespace()))); + this(() -> BuiltInRegistries.BLOCK.stream().filter(block -> "minecraft".equals(block.builtInRegistryHolder().key().location().getNamespace())));
+ } + }
+ +
+ public BlockStateGeneratorCollector(Supplier<Stream<Block>> known) { + public BlockStateGeneratorCollector(Supplier<Stream<Block>> known) {
@@ -61,8 +61,8 @@
public void validate() { public void validate() {
- Stream<Holder.Reference<Block>> stream = BuiltInRegistries.BLOCK.listElements().filter(p_376480_ -> true); - Stream<Holder.Reference<Block>> stream = BuiltInRegistries.BLOCK.listElements().filter(p_376480_ -> true);
+ Stream<Holder.Reference<Block>> stream = known.get().map(Block::builtInRegistryHolder); + Stream<Holder.Reference<Block>> stream = known.get().map(Block::builtInRegistryHolder);
List<Identifier> list = stream.filter(p_378423_ -> !this.generators.containsKey(p_378423_.value())) List<ResourceLocation> list = stream.filter(p_378423_ -> !this.generators.containsKey(p_378423_.value()))
.map(p_447940_ -> p_447940_.key().identifier()) .map(p_378200_ -> p_378200_.key().location())
.toList(); .toList();
@@ -97,6 +_,15 @@ @@ -97,6 +_,15 @@
public static class ItemInfoCollector implements ItemModelOutput { public static class ItemInfoCollector implements ItemModelOutput {
@@ -71,7 +71,7 @@
+ private final Supplier<Stream<Item>> known; + private final Supplier<Stream<Item>> known;
+ +
+ public ItemInfoCollector() { + public ItemInfoCollector() {
+ this(() -> BuiltInRegistries.ITEM.stream().filter(item -> "minecraft".equals(item.builtInRegistryHolder().key().identifier().getNamespace()))); + this(() -> BuiltInRegistries.ITEM.stream().filter(item -> "minecraft".equals(item.builtInRegistryHolder().key().location().getNamespace())));
+ } + }
+ +
+ public ItemInfoCollector(Supplier<Stream<Item>> known) { + public ItemInfoCollector(Supplier<Stream<Item>> known) {
@@ -79,16 +79,16 @@
+ } + }
@Override @Override
public void accept(Item p_376450_, ItemModel.Unbaked p_378513_, ClientItem.Properties p_455809_) { public void accept(Item p_376450_, ItemModel.Unbaked p_378513_) {
@@ -115,7 +_,7 @@ @@ -115,7 +_,7 @@
this.copies.put(p_376965_, p_377438_); this.copies.put(p_376965_, p_377438_);
} }
- public void finalizeAndValidate() { - public void finalizeAndValidate() {
+ public void generateDefaultBlockModels() { + public void generateDefaultBlockModels() {
BuiltInRegistries.ITEM.forEach(p_447944_ -> { BuiltInRegistries.ITEM.forEach(p_378629_ -> {
if (!this.copies.containsKey(p_447944_)) { if (!this.copies.containsKey(p_378629_)) {
if (p_447944_ instanceof BlockItem blockitem && !this.itemInfos.containsKey(blockitem)) { if (p_378629_ instanceof BlockItem blockitem && !this.itemInfos.containsKey(blockitem)) {
@@ -124,6 +_,8 @@ @@ -124,6 +_,8 @@
} }
} }
@@ -102,10 +102,10 @@
this.register(p_376289_, clientitem); this.register(p_376289_, clientitem);
} }
}); });
- List<Identifier> list = BuiltInRegistries.ITEM - List<ResourceLocation> list = BuiltInRegistries.ITEM
- .listElements() - .listElements()
+ List<Identifier> list = known.get() + List<ResourceLocation> list = known.get()
+ .map(item -> item.builtInRegistryHolder()) + .map(item -> item.builtInRegistryHolder())
.filter(p_377225_ -> !this.itemInfos.containsKey(p_377225_.value())) .filter(p_377225_ -> !this.itemInfos.containsKey(p_377225_.value()))
.map(p_447943_ -> p_447943_.key().identifier()) .map(p_378591_ -> p_378591_.key().location())
.toList(); .toList();
@@ -1,7 +1,7 @@
--- a/net/minecraft/client/gui/Font.java --- a/net/minecraft/client/gui/Font.java
+++ b/net/minecraft/client/gui/Font.java +++ b/net/minecraft/client/gui/Font.java
@@ -32,7 +_,7 @@ @@ -32,7 +_,7 @@
import org.jspecify.annotations.Nullable; import org.joml.Matrix4f;
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
-public class Font { -public class Font {
@@ -9,7 +9,7 @@
private final SubtitleOverlay subtitleOverlay; private final SubtitleOverlay subtitleOverlay;
private final SpectatorGui spectatorGui; private final SpectatorGui spectatorGui;
private final PlayerTabOverlay tabList; private final PlayerTabOverlay tabList;
@@ -193,6 +_,7 @@ @@ -194,6 +_,7 @@
() -> new JumpableVehicleBarRenderer(p_330021_) () -> new JumpableVehicleBarRenderer(p_330021_)
); );
this.resetTitleTimes(); this.resetTitleTimes();
@@ -17,10 +17,10 @@
} }
public void resetTitleTimes() { public void resetTitleTimes() {
@@ -203,6 +_,10 @@ @@ -204,6 +_,10 @@
public void render(GuiGraphics p_282884_, DeltaTracker p_342095_) { public void render(GuiGraphics p_282884_, DeltaTracker p_342095_) {
if (!(this.minecraft.screen instanceof LevelLoadingScreen)) { if (this.minecraft.screen == null || !(this.minecraft.screen instanceof ReceivingLevelScreen)) {
+ if (Boolean.valueOf(true)) { + if (Boolean.valueOf(true)) {
+ net.minecraftforge.client.gui.overlay.ForgeLayeredDraw.beginRender(p_282884_, p_342095_); + net.minecraftforge.client.gui.overlay.ForgeLayeredDraw.beginRender(p_282884_, p_342095_);
+ return; + return;
@@ -28,16 +28,16 @@
if (!this.minecraft.options.hideGui) { if (!this.minecraft.options.hideGui) {
this.renderCameraOverlays(p_282884_, p_342095_); this.renderCameraOverlays(p_282884_, p_342095_);
this.renderCrosshair(p_282884_, p_342095_); this.renderCrosshair(p_282884_, p_342095_);
@@ -386,7 +_,7 @@ @@ -377,7 +_,7 @@
int i = Mth.floor(this.minecraft.mouseHandler.getScaledXPos(window)); int i = Mth.floor(this.minecraft.mouseHandler.getScaledXPos(window));
int j = Mth.floor(this.minecraft.mouseHandler.getScaledYPos(window)); int j = Mth.floor(this.minecraft.mouseHandler.getScaledYPos(window));
p_329202_.nextStratum(); p_329202_.nextStratum();
- this.chat.render(p_329202_, this.getFont(), this.tickCount, i, j, false, false); - this.chat.render(p_329202_, this.tickCount, i, j, false);
+ net.minecraftforge.client.ForgeHooksClient.onCustomizeChatEvent(p_329202_, this.chat, window, i, j, this.tickCount, this.getFont()); + net.minecraftforge.client.ForgeHooksClient.onCustomizeChatEvent(p_329202_, this.chat, window, i, j, this.tickCount);
} }
} }
@@ -476,6 +_,8 @@ @@ -472,6 +_,8 @@
for (MobEffectInstance mobeffectinstance : Ordering.natural().reverse().sortedCopy(collection)) { for (MobEffectInstance mobeffectinstance : Ordering.natural().reverse().sortedCopy(collection)) {
Holder<MobEffect> holder = mobeffectinstance.getEffect(); Holder<MobEffect> holder = mobeffectinstance.getEffect();
@@ -46,7 +46,7 @@
if (mobeffectinstance.showIcon()) { if (mobeffectinstance.showIcon()) {
int k = p_282812_.guiWidth(); int k = p_282812_.guiWidth();
int l = 1; int l = 1;
@@ -506,6 +_,7 @@ @@ -502,6 +_,7 @@
} }
} }
@@ -54,7 +54,7 @@
p_282812_.blitSprite(RenderPipelines.GUI_TEXTURED, getMobEffectSprite(holder), k + 3, l + 3, 18, 18, ARGB.white(f)); p_282812_.blitSprite(RenderPipelines.GUI_TEXTURED, getMobEffectSprite(holder), k + 3, l + 3, 18, 18, ARGB.white(f));
} }
} }
@@ -602,6 +_,10 @@ @@ -598,6 +_,10 @@
} }
public void renderSelectedItemName(GuiGraphics p_283501_) { public void renderSelectedItemName(GuiGraphics p_283501_) {
@@ -65,7 +65,7 @@
Profiler.get().push("selectedItemName"); Profiler.get().push("selectedItemName");
if (this.toolHighlightTimer > 0 && !this.lastToolHighlight.isEmpty()) { if (this.toolHighlightTimer > 0 && !this.lastToolHighlight.isEmpty()) {
MutableComponent mutablecomponent = Component.empty().append(this.lastToolHighlight.getHoverName()).withStyle(this.lastToolHighlight.getRarity().color()); MutableComponent mutablecomponent = Component.empty().append(this.lastToolHighlight.getHoverName()).withStyle(this.lastToolHighlight.getRarity().color());
@@ -609,9 +_,13 @@ @@ -605,9 +_,13 @@
mutablecomponent.withStyle(ChatFormatting.ITALIC); mutablecomponent.withStyle(ChatFormatting.ITALIC);
} }
@@ -81,16 +81,16 @@
if (!this.minecraft.gameMode.canHurtPlayer()) { if (!this.minecraft.gameMode.canHurtPlayer()) {
k += 14; k += 14;
} }
@@ -622,7 +_,7 @@ @@ -618,7 +_,7 @@
} }
if (l > 0) { if (l > 0) {
- p_283501_.drawStringWithBackdrop(this.getFont(), mutablecomponent, j, k, i, ARGB.white(l)); - p_283501_.drawStringWithBackdrop(this.getFont(), mutablecomponent, j, k, i, ARGB.color(l, -1));
+ p_283501_.drawStringWithBackdrop(font, highlightTip, j, k, i, ARGB.white(l)); + p_283501_.drawStringWithBackdrop(font, highlightTip, j, k, i, ARGB.color(l, -1));
} }
} }
@@ -1148,7 +_,7 @@ @@ -1146,7 +_,7 @@
ItemStack itemstack = this.minecraft.player.getInventory().getSelectedItem(); ItemStack itemstack = this.minecraft.player.getInventory().getSelectedItem();
if (itemstack.isEmpty()) { if (itemstack.isEmpty()) {
this.toolHighlightTimer = 0; this.toolHighlightTimer = 0;
@@ -1,15 +1,15 @@
--- a/net/minecraft/client/gui/GuiGraphics.java --- a/net/minecraft/client/gui/GuiGraphics.java
+++ b/net/minecraft/client/gui/GuiGraphics.java +++ b/net/minecraft/client/gui/GuiGraphics.java
@@ -86,7 +_,7 @@ @@ -72,7 +_,7 @@
import org.jspecify.annotations.Nullable; import org.joml.Vector3f;
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
-public class GuiGraphics { -public class GuiGraphics {
+public class GuiGraphics implements net.minecraftforge.client.extensions.IForgeGuiGraphics { +public class GuiGraphics implements net.minecraftforge.client.extensions.IForgeGuiGraphics {
private static final int EXTRA_SPACE_AFTER_FIRST_TOOLTIP_LINE = 2; private static final int EXTRA_SPACE_AFTER_FIRST_TOOLTIP_LINE = 2;
final Minecraft minecraft; private final Minecraft minecraft;
private final Matrix3x2fStack pose; private final Matrix3x2fStack pose;
@@ -972,6 +_,7 @@ @@ -875,6 +_,7 @@
CrashReport crashreport = CrashReport.forThrowable(throwable, "Rendering item"); CrashReport crashreport = CrashReport.forThrowable(throwable, "Rendering item");
CrashReportCategory crashreportcategory = crashreport.addCategory("Item being rendered"); CrashReportCategory crashreportcategory = crashreport.addCategory("Item being rendered");
crashreportcategory.setDetail("Item Type", () -> String.valueOf(p_283653_.getItem())); crashreportcategory.setDetail("Item Type", () -> String.valueOf(p_283653_.getItem()));
@@ -17,7 +17,7 @@
crashreportcategory.setDetail("Item Components", () -> String.valueOf(p_283653_.getComponents())); crashreportcategory.setDetail("Item Components", () -> String.valueOf(p_283653_.getComponents()));
crashreportcategory.setDetail("Item Foil", () -> String.valueOf(p_283653_.hasFoil())); crashreportcategory.setDetail("Item Foil", () -> String.valueOf(p_283653_.hasFoil()));
throw new ReportedException(crashreport); throw new ReportedException(crashreport);
@@ -990,6 +_,7 @@ @@ -893,6 +_,7 @@
this.renderItemCooldown(p_283349_, p_282641_, p_282146_); this.renderItemCooldown(p_283349_, p_282641_, p_282146_);
this.renderItemCount(p_282005_, p_283349_, p_282641_, p_282146_, p_282803_); this.renderItemCount(p_282005_, p_283349_, p_282641_, p_282146_, p_282803_);
this.pose.popMatrix(); this.pose.popMatrix();
@@ -25,7 +25,7 @@
} }
} }
@@ -1001,21 +_,30 @@ @@ -904,21 +_,30 @@
this.setTooltipForNextFrame(this.minecraft.font, p_407686_, DefaultTooltipPositioner.INSTANCE, p_410475_, p_407139_, false); this.setTooltipForNextFrame(this.minecraft.font, p_407686_, DefaultTooltipPositioner.INSTANCE, p_410475_, p_407139_, false);
} }
@@ -50,15 +50,15 @@
+ } + }
+ +
public void setTooltipForNextFrame( public void setTooltipForNextFrame(
Font p_408450_, List<Component> p_405939_, Optional<TooltipComponent> p_456997_, int p_409519_, int p_410392_, @Nullable Identifier p_460731_ Font p_407847_, List<Component> p_408847_, Optional<TooltipComponent> p_410489_, int p_409369_, int p_407472_, @Nullable ResourceLocation p_410303_
) { ) {
- List<ClientTooltipComponent> list = p_405939_.stream().map(Component::getVisualOrderText).map(ClientTooltipComponent::create).collect(Util.toMutableList()); - List<ClientTooltipComponent> list = p_408847_.stream().map(Component::getVisualOrderText).map(ClientTooltipComponent::create).collect(Util.toMutableList());
- p_456997_.ifPresent(p_325321_ -> list.add(list.isEmpty() ? 0 : 1, ClientTooltipComponent.create(p_325321_))); - p_410489_.ifPresent(p_325321_ -> list.add(list.isEmpty() ? 0 : 1, ClientTooltipComponent.create(p_325321_)));
+ List<ClientTooltipComponent> list = net.minecraftforge.client.ForgeHooksClient.gatherTooltipComponents(this.tooltipStack, p_405939_, p_456997_, p_409519_, guiWidth(), guiHeight(), p_408450_); + List<ClientTooltipComponent> list = net.minecraftforge.client.ForgeHooksClient.gatherTooltipComponents(this.tooltipStack, p_408847_, p_410489_, p_409369_, guiWidth(), guiHeight(), p_407847_);
this.setTooltipForNextFrameInternal(p_408450_, list, p_409519_, p_410392_, DefaultTooltipPositioner.INSTANCE, p_460731_, false); this.setTooltipForNextFrameInternal(p_407847_, list, p_409369_, p_407472_, DefaultTooltipPositioner.INSTANCE, p_410303_, false);
} }
@@ -1028,7 +_,22 @@ @@ -931,7 +_,22 @@
} }
public void setComponentTooltipForNextFrame(Font p_406239_, List<Component> p_410275_, int p_410594_, int p_409343_) { public void setComponentTooltipForNextFrame(Font p_406239_, List<Component> p_410275_, int p_410594_, int p_409343_) {
@@ -81,33 +81,32 @@
+ this.tooltipStack = ItemStack.EMPTY; + this.tooltipStack = ItemStack.EMPTY;
} }
public void setComponentTooltipForNextFrame(Font p_408650_, List<Component> p_407512_, int p_406019_, int p_408123_, @Nullable Identifier p_456486_) { public void setComponentTooltipForNextFrame(Font p_408650_, List<Component> p_407512_, int p_406019_, int p_408123_, @Nullable ResourceLocation p_409993_) {
@@ -1073,24 +_,31 @@ @@ -981,9 +_,14 @@
int p_407794_,
int p_408784_,
ClientTooltipPositioner p_408798_,
- @Nullable Identifier p_451079_,
+ @Nullable Identifier p_456486_,
boolean p_410618_
) { ) {
if (!p_409928_.isEmpty()) { if (!p_409928_.isEmpty()) {
if (this.deferredTooltip == null || p_410618_) { if (this.deferredTooltip == null || p_410618_) {
- this.deferredTooltip = () -> this.renderTooltip(p_406605_, p_409928_, p_407794_, p_408784_, p_408798_, p_451079_); - this.deferredTooltip = () -> this.renderTooltip(p_406605_, p_409928_, p_407794_, p_408784_, p_408798_, p_407676_);
+ final var stackContext = this.tooltipStack; + final var stackContext = this.tooltipStack;
+ this.deferredTooltip = () -> this.renderTooltip(p_406605_, p_409928_, p_407794_, p_408784_, p_408798_, p_456486_, stackContext); + this.deferredTooltip = () -> this.renderTooltip(p_406605_, p_409928_, p_407794_, p_408784_, p_408798_, p_407676_, stackContext);
} }
} }
+ } + }
+ +
+ public void renderTooltip(Font p_283128_, List<ClientTooltipComponent> p_282716_, int p_283678_, int p_281696_, ClientTooltipPositioner p_409451_, @Nullable Identifier p_456486_) { + public void renderTooltip(Font p_283128_, List<ClientTooltipComponent> p_282716_, int p_283678_, int p_281696_, ClientTooltipPositioner p_409451_, @Nullable ResourceLocation p_409298_) {
+ renderTooltip(p_283128_, p_282716_, p_283678_, p_281696_, p_409451_, p_456486_, ItemStack.EMPTY); + renderTooltip(p_283128_, p_282716_, p_283678_, p_281696_, p_409451_, p_409298_, ItemStack.EMPTY);
} }
public void renderTooltip( public void renderTooltip(
- Font p_283128_, List<ClientTooltipComponent> p_282716_, int p_283678_, int p_281696_, ClientTooltipPositioner p_409451_, @Nullable Identifier p_459396_ @@ -992,13 +_,16 @@
+ Font p_283128_, List<ClientTooltipComponent> p_282716_, int p_283678_, int p_281696_, ClientTooltipPositioner p_409451_, @Nullable Identifier p_459396_, ItemStack itemstack int p_283678_,
int p_281696_,
ClientTooltipPositioner p_409451_,
- @Nullable ResourceLocation p_409298_
+ @Nullable ResourceLocation p_409298_,
+ ItemStack itemStack
) { ) {
+ var preEvent = net.minecraftforge.client.ForgeHooksClient.onRenderTooltipPre(itemstack, this, p_283678_, p_281696_, guiWidth(), guiHeight(), p_282716_, p_283128_, p_409451_, p_459396_); + var preEvent = net.minecraftforge.client.ForgeHooksClient.onRenderTooltipPre(itemStack, this, p_283678_, p_281696_, guiWidth(), guiHeight(), p_282716_, p_283128_, p_409451_, p_409298_);
+ if (preEvent == null) return; + if (preEvent == null) return;
int i = 0; int i = 0;
int j = p_282716_.size() == 1 ? -2 : 0; int j = p_282716_.size() == 1 ? -2 : 0;
@@ -118,7 +117,7 @@
if (k > i) { if (k > i) {
i = k; i = k;
} }
@@ -1100,16 +_,16 @@ @@ -1008,16 +_,17 @@
int l1 = i; int l1 = i;
int i2 = j; int i2 = j;
@@ -127,8 +126,9 @@
int l = vector2ic.x(); int l = vector2ic.x();
int i1 = vector2ic.y(); int i1 = vector2ic.y();
this.pose.pushMatrix(); this.pose.pushMatrix();
- TooltipRenderUtil.renderTooltipBackground(this, l, i1, i, j, p_459396_); - TooltipRenderUtil.renderTooltipBackground(this, l, i1, i, j, p_409298_);
+ TooltipRenderUtil.renderTooltipBackground(this, l, i1, i, j, preEvent.getBackground()); + var background = net.minecraftforge.client.event.ForgeEventFactoryClient.onRenderTooltipBackground(this.tooltipStack, this, l, i1, preEvent.getFont(), p_282716_, preEvent.getBackground());
+ TooltipRenderUtil.renderTooltipBackground(this, l, i1, i, j, background.getBackground());
int j1 = i1; int j1 = i1;
for (int k1 = 0; k1 < p_282716_.size(); k1++) { for (int k1 = 0; k1 < p_282716_.size(); k1++) {
@@ -138,7 +138,7 @@
j1 += clienttooltipcomponent1.getHeight(p_283128_) + (k1 == 0 ? 2 : 0); j1 += clienttooltipcomponent1.getHeight(p_283128_) + (k1 == 0 ? 2 : 0);
} }
@@ -1117,7 +_,7 @@ @@ -1025,7 +_,7 @@
for (int j2 = 0; j2 < p_282716_.size(); j2++) { for (int j2 = 0; j2 < p_282716_.size(); j2++) {
ClientTooltipComponent clienttooltipcomponent2 = p_282716_.get(j2); ClientTooltipComponent clienttooltipcomponent2 = p_282716_.get(j2);
@@ -147,7 +147,7 @@
j1 += clienttooltipcomponent2.getHeight(p_283128_) + (j2 == 0 ? 2 : 0); j1 += clienttooltipcomponent2.getHeight(p_283128_) + (j2 == 0 ? 2 : 0);
} }
@@ -1328,6 +_,14 @@ @@ -1222,6 +_,14 @@
public void submitProfilerChartRenderState(List<ResultField> p_408565_, int p_410147_, int p_406156_, int p_407365_, int p_408180_) { public void submitProfilerChartRenderState(List<ResultField> p_408565_, int p_410147_, int p_406156_, int p_407365_, int p_408180_) {
this.guiRenderState.submitPicturesInPictureState(new GuiProfilerChartRenderState(p_408565_, p_410147_, p_406156_, p_407365_, p_408180_, this.scissorStack.peek())); this.guiRenderState.submitPicturesInPictureState(new GuiProfilerChartRenderState(p_408565_, p_410147_, p_406156_, p_407365_, p_408180_, this.scissorStack.peek()));
@@ -161,4 +161,4 @@
+ return this.scissorStack; + return this.scissorStack;
} }
public TextureAtlasSprite getSprite(Material p_430745_) { @OnlyIn(Dist.CLIENT)
@@ -0,0 +1,11 @@
--- a/net/minecraft/client/gui/components/AbstractButton.java
+++ b/net/minecraft/client/gui/components/AbstractButton.java
@@ -38,7 +_,7 @@
this.getHeight(),
ARGB.white(this.alpha)
);
- int i = ARGB.color(this.alpha, this.active ? -1 : -6250336);
+ int i = getFGColor();
this.renderString(p_281670_, minecraft.font, i);
}
@@ -1,16 +1,17 @@
--- a/net/minecraft/client/gui/components/AbstractWidget.java --- a/net/minecraft/client/gui/components/AbstractWidget.java
+++ b/net/minecraft/client/gui/components/AbstractWidget.java +++ b/net/minecraft/client/gui/components/AbstractWidget.java
@@ -221,6 +_,23 @@ @@ -236,6 +_,25 @@
this.focused = p_93693_; this.focused = p_93693_;
} }
+ // Forge start
+ public static final int UNSET_FG_COLOR = -1; + public static final int UNSET_FG_COLOR = -1;
+ +
+ protected int packedFGColor = UNSET_FG_COLOR; + protected int packedFGColor = UNSET_FG_COLOR;
+ +
+ public int getFGColor() { + public int getFGColor() {
+ if (packedFGColor != UNSET_FG_COLOR) return packedFGColor; + if (packedFGColor != UNSET_FG_COLOR) return packedFGColor;
+ return this.active ? net.minecraft.util.CommonColors.WHITE : net.minecraft.util.CommonColors.LIGHT_GRAY; + return net.minecraft.util.ARGB.color(this.alpha, this.active ? -1 : -6250336); // White : Light Grey
+ } + }
+ +
+ public void setFGColor(int color) { + public void setFGColor(int color) {
@@ -20,6 +21,7 @@
+ public void clearFGColor() { + public void clearFGColor() {
+ this.packedFGColor = UNSET_FG_COLOR; + this.packedFGColor = UNSET_FG_COLOR;
+ } + }
+ // Forge end
+ +
@Override @Override
public NarratableEntry.NarrationPriority narrationPriority() { public NarratableEntry.NarrationPriority narrationPriority() {
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/gui/components/Button.java --- a/net/minecraft/client/gui/components/Button.java
+++ b/net/minecraft/client/gui/components/Button.java +++ b/net/minecraft/client/gui/components/Button.java
@@ -33,6 +_,12 @@ @@ -31,6 +_,12 @@
this.createNarration = p_259552_; this.createNarration = p_259552_;
} }
@@ -11,16 +11,16 @@
+ } + }
+ +
@Override @Override
public void onPress(InputWithModifiers p_424878_) { public void onPress() {
this.onPress.onPress(this); this.onPress.onPress(this);
@@ -96,9 +_,12 @@ @@ -95,9 +_,12 @@
} }
public Button build() { public Button build() {
- Button button = new Button.Plain(this.x, this.y, this.width, this.height, this.message, this.onPress, this.createNarration); - Button button = new Button(this.x, this.y, this.width, this.height, this.message, this.onPress, this.createNarration);
- button.setTooltip(this.tooltip); - button.setTooltip(this.tooltip);
- return button; - return button;
+ return build(Button.Plain::new); + return build(Button::new);
+ } + }
+ +
+ // Forge (GH-9238) + // Forge (GH-9238)
@@ -29,14 +29,3 @@
} }
} }
@@ -118,6 +_,10 @@
int p_455297_, int p_455388_, int p_459653_, int p_452847_, Component p_459347_, Button.OnPress p_453378_, Button.CreateNarration p_456163_
) {
super(p_455297_, p_455388_, p_459653_, p_452847_, p_459347_, p_453378_, p_456163_);
+ }
+
+ protected Plain(Builder builder) {
+ super(builder);
}
@Override
@@ -0,0 +1,101 @@
--- a/net/minecraft/client/gui/components/DebugScreenOverlay.java
+++ b/net/minecraft/client/gui/components/DebugScreenOverlay.java
@@ -139,9 +_,9 @@
@Nullable
private CompletableFuture<LevelChunk> serverChunk;
private boolean renderDebug;
- private boolean renderProfilerChart;
- private boolean renderFpsCharts;
- private boolean renderNetworkCharts;
+ protected boolean renderProfilerChart;
+ protected boolean renderFpsCharts;
+ protected boolean renderNetworkCharts;
private final LocalSampleLogger frameTimeLogger = new LocalSampleLogger(1);
private final LocalSampleLogger tickTimeLogger = new LocalSampleLogger(TpsDebugDimensions.values().length);
private final LocalSampleLogger pingLogger = new LocalSampleLogger(1);
@@ -183,15 +_,19 @@
this.clientChunk = null;
}
- public void render(GuiGraphics p_281427_) {
- ProfilerFiller profilerfiller = Profiler.get();
- profilerfiller.push("debug");
+ protected void update() {
Entity entity = this.minecraft.getCameraEntity();
this.block = entity.pick(20.0, 0.0F, false);
this.liquid = entity.pick(20.0, 0.0F, true);
+ }
+
+ protected void drawText(ProfilerFiller profilerfiller, GuiGraphics p_281427_) {
this.drawGameInformation(p_281427_);
this.drawSystemInformation(p_281427_);
p_281427_.nextStratum();
+ }
+
+ protected void drawFPSCharts(ProfilerFiller profilerfiller, GuiGraphics p_281427_) {
this.profilerPieChart.setBottomOffset(10);
if (this.renderFpsCharts) {
int i = p_281427_.guiWidth();
@@ -204,7 +_,9 @@
this.profilerPieChart.setBottomOffset(this.tpsChart.getFullHeight());
}
+ }
+ protected void drawNetworkCharts(ProfilerFiller profilerfiller, GuiGraphics p_281427_) {
if (this.renderNetworkCharts) {
int l = p_281427_.guiWidth();
int i1 = l / 2;
@@ -220,12 +_,22 @@
try (Zone zone = profilerfiller.zone("profilerPie")) {
this.profilerPieChart.render(p_281427_);
}
+ }
+
+ public void render(GuiGraphics p_281427_) {
+ ProfilerFiller profilerfiller = Profiler.get();
+ profilerfiller.push("debug");
+ this.update();
+
+ this.drawText(profilerfiller, p_281427_);
+ this.drawFPSCharts(profilerfiller, p_281427_);
+ this.drawNetworkCharts(profilerfiller, p_281427_);
profilerfiller.pop();
}
- protected void drawGameInformation(GuiGraphics p_281525_) {
- List<String> list = this.getGameInformation();
+ protected List<String> getOverlayHelp() {
+ List<String> list = Lists.newArrayList();
list.add("");
boolean flag = this.minecraft.getSingleplayerServer() != null;
list.add(
@@ -239,11 +_,18 @@
+ (this.renderNetworkCharts ? " visible" : " hidden")
);
list.add("For help: press F3 + Q");
- this.renderLines(p_281525_, list, true);
+ return list;
+ }
+ protected void drawGameInformation(GuiGraphics p_281525_) {
+ List<String> list = this.getGameInformation();
+ list.addAll(this.getOverlayHelp());
+ net.minecraftforge.client.ForgeHooksClient.onCustomizeDebugEvent(p_281525_, minecraft.getWindow(), minecraft.getDeltaTracker().getRealtimeDeltaTicks(), list, true);
+ this.renderLines(p_281525_, list, true);
}
protected void drawSystemInformation(GuiGraphics p_281261_) {
List<String> list = this.getSystemInformation();
+ net.minecraftforge.client.ForgeHooksClient.onCustomizeDebugEvent(p_281261_, minecraft.getWindow(), minecraft.getDeltaTracker().getRealtimeDeltaTicks(), list, false);
this.renderLines(p_281261_, list, false);
}
@@ -597,6 +_,7 @@
list.add("");
list.add(ChatFormatting.UNDERLINE + "Targeted Entity");
list.add(String.valueOf(BuiltInRegistries.ENTITY_TYPE.getKey(entity.getType())));
+ entity.getType().builtInRegistryHolder().tags().forEach(t -> list.add("#" + t.location()));
}
return list;
@@ -1,10 +0,0 @@
--- a/net/minecraft/client/gui/components/debug/DebugEntryLookingAtEntity.java
+++ b/net/minecraft/client/gui/components/debug/DebugEntryLookingAtEntity.java
@@ -25,6 +_,7 @@
if (entity != null) {
list.add(ChatFormatting.UNDERLINE + "Targeted Entity");
list.add(String.valueOf(BuiltInRegistries.ENTITY_TYPE.getKey(entity.getType())));
+ entity.getType().builtInRegistryHolder().tags().forEach(t -> list.add("#" + t.location()));
}
p_426755_.addToGroup(GROUP, list);
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/gui/components/toasts/ToastManager.java --- a/net/minecraft/client/gui/components/toasts/ToastManager.java
+++ b/net/minecraft/client/gui/components/toasts/ToastManager.java +++ b/net/minecraft/client/gui/components/toasts/ToastManager.java
@@ -142,6 +_,7 @@ @@ -146,6 +_,7 @@
} }
public void addToast(Toast p_360768_) { public void addToast(Toast p_360768_) {
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/gui/render/GuiRenderer.java --- a/net/minecraft/client/gui/render/GuiRenderer.java
+++ b/net/minecraft/client/gui/render/GuiRenderer.java +++ b/net/minecraft/client/gui/render/GuiRenderer.java
@@ -138,6 +_,7 @@ @@ -134,6 +_,7 @@
builder.put((Class<? extends PictureInPictureRenderState>)pictureinpicturerenderer.getRenderStateClass(), pictureinpicturerenderer); builder.put((Class<? extends PictureInPictureRenderState>)pictureinpicturerenderer.getRenderStateClass(), pictureinpicturerenderer);
} }
@@ -1,10 +1,10 @@
--- a/net/minecraft/client/gui/screens/ChatScreen.java --- a/net/minecraft/client/gui/screens/ChatScreen.java
+++ b/net/minecraft/client/gui/screens/ChatScreen.java +++ b/net/minecraft/client/gui/screens/ChatScreen.java
@@ -115,6 +_,7 @@ @@ -89,6 +_,7 @@
} else if (p_426273_.isConfirmation()) { return true;
} else if (p_95591_ == 257 || p_95591_ == 335) {
this.handleChatInput(this.input.getValue(), true); this.handleChatInput(this.input.getValue(), true);
this.exitReason = ChatScreen.ExitReason.DONE;
+ if (this.minecraft.screen == this) // FORGE: Prevent closing the screen if another screen has been opened. + if (this.minecraft.screen == this) // FORGE: Prevent closing the screen if another screen has been opened.
this.minecraft.setScreen(null); this.minecraft.setScreen(null);
return true; return true;
} else { } else if (p_95591_ == 265) {
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/gui/screens/LoadingOverlay.java --- a/net/minecraft/client/gui/screens/LoadingOverlay.java
+++ b/net/minecraft/client/gui/screens/LoadingOverlay.java +++ b/net/minecraft/client/gui/screens/LoadingOverlay.java
@@ -63,6 +_,8 @@ @@ -61,6 +_,8 @@
return p_169325_ & 16777215 | p_169326_ << 24; return p_169325_ & 16777215 | p_169326_ << 24;
} }
@@ -9,7 +9,7 @@
@Override @Override
public void render(GuiGraphics p_281839_, int p_282704_, int p_283650_, float p_283394_) { public void render(GuiGraphics p_281839_, int p_282704_, int p_283650_, float p_283394_) {
int i = p_281839_.guiWidth(); int i = p_281839_.guiWidth();
@@ -103,6 +_,7 @@ @@ -97,6 +_,7 @@
f2 = 1.0F; f2 = 1.0F;
} }
@@ -17,7 +17,7 @@
int l2 = (int)(p_281839_.guiWidth() * 0.5); int l2 = (int)(p_281839_.guiWidth() * 0.5);
int i1 = (int)(p_281839_.guiHeight() * 0.5); int i1 = (int)(p_281839_.guiHeight() * 0.5);
double d0 = Math.min(p_281839_.guiWidth() * 0.75, (double)p_281839_.guiHeight()) * 0.25; double d0 = Math.min(p_281839_.guiWidth() * 0.75, (double)p_281839_.guiHeight()) * 0.25;
@@ -118,6 +_,7 @@ @@ -112,12 +_,14 @@
if (f < 1.0F) { if (f < 1.0F) {
this.drawProgressBar(p_281839_, i / 2 - k1, i2 - 5, i / 2 + k1, i2 + 5, 1.0F - Mth.clamp(f, 0.0F, 1.0F)); this.drawProgressBar(p_281839_, i / 2 - k1, i2 - 5, i / 2 + k1, i2 + 5, 1.0F - Mth.clamp(f, 0.0F, 1.0F));
} }
@@ -25,19 +25,18 @@
if (f >= 2.0F) { if (f >= 2.0F) {
this.minecraft.setOverlay(null); this.minecraft.setOverlay(null);
@@ -127,6 +_,7 @@ }
@Override
public void tick() { if (this.fadeOutStart == -1L && this.reload.isDone() && (!this.fadeIn || f1 >= 2.0F)) {
if (this.fadeOutStart == -1L && this.reload.isDone() && this.isReadyToFadeOut()) {
+ this.fadeOutStart = Util.getMillis(); // Forge: Moved up to guard against inf loops caused by callback + this.fadeOutStart = Util.getMillis(); // Forge: Moved up to guard against inf loops caused by callback
try { try {
this.reload.checkExceptions(); this.reload.checkExceptions();
this.onFinish.accept(Optional.empty()); this.onFinish.accept(Optional.empty());
@@ -134,7 +_,6 @@ @@ -125,7 +_,6 @@
this.onFinish.accept(Optional.of(throwable)); this.onFinish.accept(Optional.of(throwable));
} }
- this.fadeOutStart = Util.getMillis(); - this.fadeOutStart = Util.getMillis();
if (this.minecraft.screen != null) { if (this.minecraft.screen != null) {
Window window = this.minecraft.getWindow(); this.minecraft.screen.init(this.minecraft, p_281839_.guiWidth(), p_281839_.guiHeight());
this.minecraft.screen.init(window.getGuiScaledWidth(), window.getGuiScaledHeight()); }
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/gui/screens/PauseScreen.java --- a/net/minecraft/client/gui/screens/PauseScreen.java
+++ b/net/minecraft/client/gui/screens/PauseScreen.java +++ b/net/minecraft/client/gui/screens/PauseScreen.java
@@ -102,6 +_,7 @@ @@ -105,6 +_,7 @@
} else { } else {
gridlayout$rowhelper.addChild(this.openScreenButton(PLAYER_REPORTING, () -> new SocialInteractionsScreen(this))); gridlayout$rowhelper.addChild(this.openScreenButton(PLAYER_REPORTING, () -> new SocialInteractionsScreen(this)));
} }
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/gui/screens/Screen.java --- a/net/minecraft/client/gui/screens/Screen.java
+++ b/net/minecraft/client/gui/screens/Screen.java +++ b/net/minecraft/client/gui/screens/Screen.java
@@ -194,7 +_,7 @@ @@ -191,7 +_,7 @@
} }
public void onClose() { public void onClose() {
@@ -9,7 +9,7 @@
} }
protected <T extends GuiEventListener & Renderable & NarratableEntry> T addRenderableWidget(T p_169406_) { protected <T extends GuiEventListener & Renderable & NarratableEntry> T addRenderableWidget(T p_169406_) {
@@ -326,8 +_,10 @@ @@ -339,8 +_,10 @@
this.width = p_96608_; this.width = p_96608_;
this.height = p_96609_; this.height = p_96609_;
if (!this.initialized) { if (!this.initialized) {
@@ -20,7 +20,7 @@
} else { } else {
this.repositionElements(); this.repositionElements();
} }
@@ -344,8 +_,10 @@ @@ -353,8 +_,10 @@
protected void rebuildWidgets() { protected void rebuildWidgets() {
this.clearWidgets(); this.clearWidgets();
this.clearFocus(); this.clearFocus();
@@ -31,16 +31,15 @@
} }
protected void fadeWidgets(float p_409453_) { protected void fadeWidgets(float p_409453_) {
@@ -385,6 +_,8 @@ @@ -389,6 +_,7 @@
this.renderMenuBackground(p_283688_);
}
this.renderBlurredBackground(p_283688_);
this.renderMenuBackground(p_283688_);
+ net.minecraftforge.client.event.ForgeEventFactoryClient.onRenderScreenBackground(this, p_283688_); + net.minecraftforge.client.event.ForgeEventFactoryClient.onRenderScreenBackground(this, p_283688_);
+
this.minecraft.gui.renderDeferredSubtitles();
} }
@@ -467,6 +_,19 @@ protected void renderBlurredBackground(GuiGraphics p_407253_) {
@@ -492,6 +_,19 @@
} }
public void onFilesDrop(List<Path> p_96591_) { public void onFilesDrop(List<Path> p_96591_) {
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/gui/screens/TitleScreen.java --- a/net/minecraft/client/gui/screens/TitleScreen.java
+++ b/net/minecraft/client/gui/screens/TitleScreen.java +++ b/net/minecraft/client/gui/screens/TitleScreen.java
@@ -53,6 +_,7 @@ @@ -54,6 +_,7 @@
private boolean fading; private boolean fading;
private long fadeInStart; private long fadeInStart;
private final LogoRenderer logoRenderer; private final LogoRenderer logoRenderer;
@@ -8,7 +8,7 @@
public TitleScreen() { public TitleScreen() {
this(false); this(false);
@@ -105,11 +_,15 @@ @@ -106,11 +_,15 @@
int j = this.width - i - 2; int j = this.width - i - 2;
int k = 24; int k = 24;
int l = this.height / 4 + 48; int l = this.height / 4 + 48;
@@ -24,7 +24,7 @@
l = this.createTestWorldButton(l, 24); l = this.createTestWorldButton(l, 24);
SpriteIconButton spriteiconbutton = this.addRenderableWidget( SpriteIconButton spriteiconbutton = this.addRenderableWidget(
@@ -176,7 +_,7 @@ @@ -175,7 +_,7 @@
}).bounds(this.width / 2 - 100, i = p_96764_ + p_96765_, 200, 20).tooltip(tooltip).build()).active = flag; }).bounds(this.width / 2 - 100, i = p_96764_ + p_96765_, 200, 20).tooltip(tooltip).build()).active = flag;
this.addRenderableWidget( this.addRenderableWidget(
Button.builder(Component.translatable("menu.online"), p_325369_ -> this.minecraft.setScreen(new RealmsMainScreen(this))) Button.builder(Component.translatable("menu.online"), p_325369_ -> this.minecraft.setScreen(new RealmsMainScreen(this)))
@@ -37,7 +37,7 @@
s = s + I18n.get("menu.modded"); s = s + I18n.get("menu.modded");
} }
- p_282860_.drawString(this.font, s, 2, this.height - 10, ARGB.white(f)); - p_282860_.drawString(this.font, s, 2, this.height - 10, ARGB.color(f, -1));
+ final float f_f = f; + final float f_f = f;
+ net.minecraftforge.internal.BrandingControl.forEachLine(true, true, (brd, brdline) -> + net.minecraftforge.internal.BrandingControl.forEachLine(true, true, (brd, brdline) ->
+ p_282860_.drawString(this.font, brd, 2, this.height - ( 10 + brdline * (this.font.lineHeight + 1)), ARGB.color(f_f, -1)) + p_282860_.drawString(this.font, brd, 2, this.height - ( 10 + brdline * (this.font.lineHeight + 1)), ARGB.color(f_f, -1))
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/gui/screens/advancements/AdvancementTab.java --- a/net/minecraft/client/gui/screens/advancements/AdvancementTab.java
+++ b/net/minecraft/client/gui/screens/advancements/AdvancementTab.java +++ b/net/minecraft/client/gui/screens/advancements/AdvancementTab.java
@@ -40,6 +_,7 @@ @@ -39,6 +_,7 @@
private int maxY = Integer.MIN_VALUE; private int maxY = Integer.MIN_VALUE;
private float fade; private float fade;
private boolean centered; private boolean centered;
@@ -8,7 +8,7 @@
public AdvancementTab( public AdvancementTab(
Minecraft p_97145_, AdvancementsScreen p_97146_, AdvancementTabType p_97147_, int p_97148_, AdvancementNode p_297568_, DisplayInfo p_97150_ Minecraft p_97145_, AdvancementsScreen p_97146_, AdvancementTabType p_97147_, int p_97148_, AdvancementNode p_297568_, DisplayInfo p_97150_
@@ -56,6 +_,15 @@ @@ -55,6 +_,15 @@
this.addWidget(this.root, p_297568_.holder()); this.addWidget(this.root, p_297568_.holder());
} }
@@ -24,7 +24,7 @@
public AdvancementTabType getType() { public AdvancementTabType getType() {
return this.type; return this.type;
} }
@@ -150,8 +_,8 @@ @@ -145,8 +_,8 @@
return null; return null;
} else { } else {
for (AdvancementTabType advancementtabtype : AdvancementTabType.values()) { for (AdvancementTabType advancementtabtype : AdvancementTabType.values()) {
@@ -1,14 +1,14 @@
--- a/net/minecraft/client/gui/screens/advancements/AdvancementsScreen.java --- a/net/minecraft/client/gui/screens/advancements/AdvancementsScreen.java
+++ b/net/minecraft/client/gui/screens/advancements/AdvancementsScreen.java +++ b/net/minecraft/client/gui/screens/advancements/AdvancementsScreen.java
@@ -52,6 +_,7 @@ @@ -51,6 +_,7 @@
private final Map<AdvancementHolder, AdvancementTab> tabs = Maps.newLinkedHashMap(); @Nullable
private @Nullable AdvancementTab selectedTab; private AdvancementTab selectedTab;
private boolean isScrolling; private boolean isScrolling;
+ private static int tabPage, maxPages; + private static int tabPage, maxPages;
public AdvancementsScreen(ClientAdvancements p_97340_) { public AdvancementsScreen(ClientAdvancements p_97340_) {
this(p_97340_, null); this(p_97340_, null);
@@ -65,6 +_,19 @@ @@ -64,6 +_,19 @@
@Override @Override
protected void init() { protected void init() {
@@ -28,21 +28,21 @@
this.layout.addTitleHeader(TITLE, this.font); this.layout.addTitleHeader(TITLE, this.font);
this.tabs.clear(); this.tabs.clear();
this.selectedTab = null; this.selectedTab = null;
@@ -109,7 +_,7 @@ @@ -108,7 +_,7 @@
int j = (this.height - 140) / 2; int j = (this.height - 140) / 2;
for (AdvancementTab advancementtab : this.tabs.values()) { for (AdvancementTab advancementtab : this.tabs.values()) {
- if (advancementtab.isMouseOver(i, j, p_431395_.x(), p_431395_.y())) { - if (advancementtab.isMouseOver(i, j, p_97343_, p_97344_)) {
+ if (advancementtab.getPage() == tabPage && advancementtab.isMouseOver(i, j, p_431395_.x(), p_431395_.y())) { + if (advancementtab.getPage() == tabPage && advancementtab.isMouseOver(i, j, p_97343_, p_97344_)) {
this.advancements.setSelectedTab(advancementtab.getRootNode().holder(), true); this.advancements.setSelectedTab(advancementtab.getRootNode().holder(), true);
break; break;
} }
@@ -200,10 +_,12 @@ @@ -183,10 +_,12 @@
p_283395_.blit(RenderPipelines.GUI_TEXTURED, WINDOW_LOCATION, p_281890_, p_282532_, 0.0F, 0.0F, 252, 140, 256, 256); p_283395_.blit(RenderPipelines.GUI_TEXTURED, WINDOW_LOCATION, p_281890_, p_282532_, 0.0F, 0.0F, 252, 140, 256, 256);
if (this.tabs.size() > 1) { if (this.tabs.size() > 1) {
for (AdvancementTab advancementtab : this.tabs.values()) { for (AdvancementTab advancementtab : this.tabs.values()) {
+ if (advancementtab.getPage() == tabPage) + if (advancementtab.getPage() == tabPage)
advancementtab.drawTab(p_283395_, p_281890_, p_282532_, p_451461_, p_451545_, advancementtab == this.selectedTab); advancementtab.drawTab(p_283395_, p_281890_, p_282532_, advancementtab == this.selectedTab);
} }
for (AdvancementTab advancementtab1 : this.tabs.values()) { for (AdvancementTab advancementtab1 : this.tabs.values()) {
@@ -50,7 +50,7 @@
advancementtab1.drawIcon(p_283395_, p_281890_, p_282532_); advancementtab1.drawIcon(p_283395_, p_281890_, p_282532_);
} }
} }
@@ -222,6 +_,7 @@ @@ -205,6 +_,7 @@
if (this.tabs.size() > 1) { if (this.tabs.size() > 1) {
for (AdvancementTab advancementtab : this.tabs.values()) { for (AdvancementTab advancementtab : this.tabs.values()) {
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/gui/screens/inventory/AbstractContainerScreen.java --- a/net/minecraft/client/gui/screens/inventory/AbstractContainerScreen.java
+++ b/net/minecraft/client/gui/screens/inventory/AbstractContainerScreen.java +++ b/net/minecraft/client/gui/screens/inventory/AbstractContainerScreen.java
@@ -102,6 +_,7 @@ @@ -107,6 +_,7 @@
int i = this.leftPos; int i = this.leftPos;
int j = this.topPos; int j = this.topPos;
super.render(p_409971_, p_409213_, p_408205_, p_408282_); super.render(p_409971_, p_409213_, p_408205_, p_408282_);
@@ -8,7 +8,7 @@
p_409971_.pose().pushMatrix(); p_409971_.pose().pushMatrix();
p_409971_.pose().translate(i, j); p_409971_.pose().translate(i, j);
this.renderLabels(p_409971_, p_409213_, p_408205_); this.renderLabels(p_409971_, p_409213_, p_408205_);
@@ -114,6 +_,8 @@ @@ -119,6 +_,8 @@
this.onStopHovering(slot); this.onStopHovering(slot);
} }
@@ -17,7 +17,7 @@
p_409971_.pose().popMatrix(); p_409971_.pose().popMatrix();
} }
@@ -197,7 +_,7 @@ @@ -202,7 +_,7 @@
ItemStack itemstack = this.hoveredSlot.getItem(); ItemStack itemstack = this.hoveredSlot.getItem();
if (this.menu.getCarried().isEmpty() || this.showTooltipWithItemInHand(itemstack)) { if (this.menu.getCarried().isEmpty() || this.showTooltipWithItemInHand(itemstack)) {
p_283594_.setTooltipForNextFrame( p_283594_.setTooltipForNextFrame(
@@ -26,7 +26,7 @@
); );
} }
} }
@@ -213,7 +_,8 @@ @@ -218,7 +_,8 @@
private void renderFloatingItem(GuiGraphics p_282567_, ItemStack p_281330_, int p_281772_, int p_281689_, @Nullable String p_282568_) { private void renderFloatingItem(GuiGraphics p_282567_, ItemStack p_281330_, int p_281772_, int p_281689_, @Nullable String p_282568_) {
p_282567_.renderItem(p_281330_, p_281772_, p_281689_); p_282567_.renderItem(p_281330_, p_281772_, p_281689_);
@@ -36,84 +36,87 @@
} }
protected void renderLabels(GuiGraphics p_281635_, int p_282681_, int p_283686_) { protected void renderLabels(GuiGraphics p_281635_, int p_282681_, int p_283686_) {
@@ -313,7 +_,8 @@ @@ -319,7 +_,8 @@
if (super.mouseClicked(p_427253_, p_427622_)) { if (super.mouseClicked(p_97748_, p_97749_, p_97750_)) {
return true; return true;
} else { } else {
- boolean flag = this.minecraft.options.keyPickItem.matchesMouse(p_427253_) && this.minecraft.player.hasInfiniteMaterials(); - boolean flag = this.minecraft.options.keyPickItem.matchesMouse(p_97750_) && this.minecraft.player.hasInfiniteMaterials();
+ var mouseKey = com.mojang.blaze3d.platform.InputConstants.Type.MOUSE.getOrCreate(p_427253_.button()); + InputConstants.Key mouseKey = InputConstants.Type.MOUSE.getOrCreate(p_97750_);
+ boolean flag = this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey) && this.minecraft.player.hasInfiniteMaterials(); + boolean flag = this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey);
Slot slot = this.getHoveredSlot(p_427253_.x(), p_427253_.y()); Slot slot = this.getHoveredSlot(p_97748_, p_97749_);
this.doubleclick = this.lastClickSlot == slot && p_427622_; long i = Util.getMillis();
this.skipNextRelease = false; this.doubleclick = this.lastClickSlot == slot && i - this.lastClickTime < 250L && this.lastClickButton == p_97750_;
@@ -323,6 +_,7 @@ @@ -330,6 +_,7 @@
int i = this.leftPos; int j = this.leftPos;
int j = this.topPos; int k = this.topPos;
boolean flag1 = this.hasClickedOutside(p_427253_.x(), p_427253_.y(), i, j); boolean flag1 = this.hasClickedOutside(p_97748_, p_97749_, j, k, p_97750_);
+ if (slot != null) flag1 = false; // Forge, prevent dropping of items through slots outside of GUI boundaries + if (slot != null) flag1 = false; // Forge, prevent dropping of items through slots outside of GUI boundaries
int k = -1; int l = -1;
if (slot != null) { if (slot != null) {
k = slot.index; l = slot.index;
@@ -348,7 +_,7 @@ @@ -355,7 +_,7 @@
} }
} else if (!this.isQuickCrafting) { } else if (!this.isQuickCrafting) {
if (this.menu.getCarried().isEmpty()) { if (this.menu.getCarried().isEmpty()) {
- if (flag) { - if (flag) {
+ if (this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey)) { + if (this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey)) {
this.slotClicked(slot, k, p_427253_.button(), ClickType.CLONE); this.slotClicked(slot, l, p_97750_, ClickType.CLONE);
} else { } else {
boolean flag2 = k != -999 && p_427253_.hasShiftDown(); boolean flag2 = l != -999
@@ -372,7 +_,7 @@ @@ -383,7 +_,7 @@
this.quickCraftingType = 0; this.quickCraftingType = 0;
} else if (p_427253_.button() == 1) { } else if (p_97750_ == 1) {
this.quickCraftingType = 1; this.quickCraftingType = 1;
- } else if (flag) { - } else if (flag) {
+ } else if (this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey)) { + } else if (this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey)) {
this.quickCraftingType = 2; this.quickCraftingType = 2;
} }
} }
@@ -449,10 +_,13 @@ @@ -459,10 +_,13 @@
@Override @Override
public boolean mouseReleased(MouseButtonEvent p_430939_) { public boolean mouseReleased(double p_97812_, double p_97813_, int p_97814_) {
+ super.mouseReleased(p_430939_); //Forge, Call parent to release buttons + super.mouseReleased(p_97812_, p_97813_, p_97814_); //Forge, Call parent to release buttons
Slot slot = this.getHoveredSlot(p_430939_.x(), p_430939_.y()); Slot slot = this.getHoveredSlot(p_97812_, p_97813_);
int i = this.leftPos; int i = this.leftPos;
int j = this.topPos; int j = this.topPos;
boolean flag = this.hasClickedOutside(p_430939_.x(), p_430939_.y(), i, j); boolean flag = this.hasClickedOutside(p_97812_, p_97813_, i, j, p_97814_);
+ if (slot != null) flag = false; // Forge, prevent dropping of items through slots outside of GUI boundaries + if (slot != null) flag = false; // Forge, prevent dropping of items through slots outside of GUI boundaries
+ var mouseKey = com.mojang.blaze3d.platform.InputConstants.Type.MOUSE.getOrCreate(p_430939_.button()); + InputConstants.Key mouseKey = InputConstants.Type.MOUSE.getOrCreate(p_97814_);
int k = -1; int k = -1;
if (slot != null) { if (slot != null) {
k = slot.index; k = slot.index;
@@ -469,7 +_,7 @@ @@ -479,7 +_,7 @@
if (slot2 != null if (slot2 != null
&& slot2.mayPickup(this.minecraft.player) && slot2.mayPickup(this.minecraft.player)
&& slot2.hasItem() && slot2.hasItem()
- && slot2.container == slot.container - && slot2.container == slot.container
+ && slot2.isSameInventory(slot) + && slot2.isSameInventory(slot)
&& AbstractContainerMenu.canItemQuickReplace(slot2, this.lastQuickMoved, true)) { && AbstractContainerMenu.canItemQuickReplace(slot2, this.lastQuickMoved, true)) {
this.slotClicked(slot2, slot2.index, p_430939_.button(), ClickType.QUICK_MOVE); this.slotClicked(slot2, slot2.index, p_97814_, ClickType.QUICK_MOVE);
} }
@@ -534,7 +_,7 @@ @@ -545,7 +_,7 @@
this.slotClicked(null, -999, AbstractContainerMenu.getQuickcraftMask(2, this.quickCraftingType), ClickType.QUICK_CRAFT); this.slotClicked(null, -999, AbstractContainerMenu.getQuickcraftMask(2, this.quickCraftingType), ClickType.QUICK_CRAFT);
} else if (!this.menu.getCarried().isEmpty()) { } else if (!this.menu.getCarried().isEmpty()) {
- if (this.minecraft.options.keyPickItem.matchesMouse(p_430939_)) { - if (this.minecraft.options.keyPickItem.matchesMouse(p_97814_)) {
+ if (this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey)) { + if (this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey)) {
this.slotClicked(slot, k, p_430939_.button(), ClickType.CLONE); this.slotClicked(slot, k, p_97814_, ClickType.CLONE);
} else { } else {
boolean flag1 = k != -999 && p_430939_.hasShiftDown(); boolean flag1 = k != -999
@@ -605,7 +_,7 @@ @@ -622,9 +_,10 @@
public boolean keyPressed(KeyEvent p_424324_) {
if (super.keyPressed(p_424324_)) { @Override
public boolean keyPressed(int p_97765_, int p_97766_, int p_97767_) {
+ InputConstants.Key mouseKey = InputConstants.getKey(p_97765_, p_97766_);
if (super.keyPressed(p_97765_, p_97766_, p_97767_)) {
return true; return true;
- } else if (this.minecraft.options.keyInventory.matches(p_424324_)) { - } else if (this.minecraft.options.keyInventory.matches(p_97765_, p_97766_)) {
+ } else if (this.minecraft.options.keyInventory.isActiveAndMatches(com.mojang.blaze3d.platform.InputConstants.getKey(p_424324_))) { + } else if (this.minecraft.options.keyInventory.isActiveAndMatches(mouseKey)) {
this.onClose(); this.onClose();
return true; return true;
} else { } else {
@@ -684,6 +_,13 @@ @@ -698,6 +_,13 @@
super.onClose(); super.onClose();
} }
Loaded 100 of 1019 files, more files were not shown because too many files have changed in this diff. Show more