mirror of
https://github.com/MinecraftForge/MinecraftForge.git
synced 2026-11-17 19:15:32 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0bca349d64 | ||
|
|
7a44626d5e | ||
|
|
30ec79b19e | ||
|
|
0794e51f62 | ||
|
|
c86172db31 | ||
|
|
ee14c0c911 | ||
|
|
b3a4ac864f | ||
|
|
f9139a3002 | ||
|
|
784693b7e5 | ||
|
|
774048154f | ||
|
|
490e35ba8e | ||
|
|
667a164430 | ||
|
|
0434d67016 | ||
|
|
02229557ed | ||
|
|
79224a70e6 | ||
|
|
5c9c8ce539 | ||
|
|
c186c38113 | ||
|
|
1507717fae | ||
|
|
12c4233fac | ||
|
|
f331376d9d | ||
|
|
b5b5064a4f | ||
|
|
f4801960e7 | ||
|
|
68c60c17e5 | ||
|
|
4a5f977691 | ||
|
|
896cfb38a3 | ||
|
|
185273022c | ||
|
|
eb65e1db51 | ||
|
|
6a5c413a13 | ||
|
|
1b7b2b6ff1 | ||
|
|
cb290f23f5 | ||
|
|
6e8eaeeec9 | ||
|
|
56c41f3ca8 | ||
|
|
0084b8cf48 | ||
|
|
eb6c564ce4 | ||
|
|
618da273dc | ||
|
|
074c0cdfd6 | ||
|
|
c22589b5b3 | ||
|
|
e0fbab3c49 | ||
|
|
7cfed38194 | ||
|
|
b8105ca5a6 | ||
|
|
c3ee633897 | ||
|
|
23b41ce9b3 | ||
|
|
2c6156be25 | ||
|
|
eeb3eb3689 | ||
|
|
44a158a714 | ||
|
|
770298b1d5 | ||
|
|
7bd50903a6 | ||
|
|
64295d04ff | ||
|
|
f168ce4499 | ||
|
|
419c349a1f | ||
|
|
26d0f7282f | ||
|
|
93c72d2d92 | ||
|
|
f252871322 | ||
|
|
32c8597305 | ||
|
|
9714512c31 | ||
|
|
f106ff0c21 | ||
|
|
9c85a6bb64 | ||
|
|
dc594f196a | ||
|
|
db4d8a4729 | ||
|
|
0ca1d0ebd0 | ||
|
|
4995902bc0 | ||
|
|
28e55b2843 | ||
|
|
decaace84a | ||
|
|
72f98dc4a3 | ||
|
|
2951c1dac8 | ||
|
|
40a0a16db0 | ||
|
|
520680b037 | ||
|
|
2844bead6e | ||
|
|
d498ec4a45 | ||
|
|
e2d1ca7d0e | ||
|
|
a547327c61 | ||
|
|
e9a7ce9544 | ||
|
|
511be6415c | ||
|
|
4d85053a4d | ||
|
|
4fcf1877c1 | ||
|
|
41fd15fc57 | ||
|
|
8e0845d032 | ||
|
|
c04e533a61 | ||
|
|
54f4997f71 | ||
|
|
3272e995ab | ||
|
|
8edb551571 | ||
|
|
4bf0de4763 | ||
|
|
f6a54436b9 | ||
|
|
7a497cdbd6 | ||
|
|
06336a40d8 | ||
|
|
842c95cfb9 | ||
|
|
aa2f471e87 | ||
|
|
4209d1fc12 | ||
|
|
583f363b6b | ||
|
|
1c633b4624 | ||
|
|
2677511da6 | ||
|
|
387441c045 | ||
|
|
4a2db246e0 | ||
|
|
3d9e12a71d | ||
|
|
cdeb786877 | ||
|
|
ff7085b95b | ||
|
|
16dde4d551 | ||
|
|
60661350c6 | ||
|
|
7ee4a44c75 | ||
|
|
f22894cf70 | ||
|
|
a3fce36942 | ||
|
|
549dbe7df4 | ||
|
|
5505e472aa | ||
|
|
c2c7f9b656 | ||
|
|
fd8a0f9c8b | ||
|
|
0ac873e296 | ||
|
|
38b5b678cb | ||
|
|
9a2bc1e7c2 | ||
|
|
95b49bedbc | ||
|
|
7c36115e3d | ||
|
|
c037e6aca1 | ||
|
|
e8f1b7ed6d | ||
|
|
5da16e6719 | ||
|
|
f0a82d79a6 | ||
|
|
2b3a4137e1 | ||
|
|
640c206117 | ||
|
|
59a7bbdb57 | ||
|
|
be7ad14b4b | ||
|
|
c700b4ea9d | ||
|
|
dffa3dd4c9 | ||
|
|
4b934809c4 | ||
|
|
ddf76db9b3 | ||
|
|
64d6b4f76a | ||
|
|
58012bfb17 | ||
|
|
0cad6b14d9 | ||
|
|
8848294210 | ||
|
|
0e28336fc0 | ||
|
|
968fa9eeb5 | ||
|
|
43768ea328 | ||
|
|
0e829630da | ||
|
|
0467d71466 | ||
|
|
115eb5e4c8 | ||
|
|
a7345372fd | ||
|
|
bd714b2f76 | ||
|
|
7b782e5b05 |
No files matched your search
Vendored
+3
-3
@@ -36,9 +36,9 @@ project {
|
|||||||
buildType(PullRequestCompatibility)
|
buildType(PullRequestCompatibility)
|
||||||
|
|
||||||
params {
|
params {
|
||||||
text("docker_jdk_version", "17", label = "Gradle version", description = "The version of the JDK to use during execution of tasks in a JDK.", display = ParameterDisplay.HIDDEN, allowEmpty = false)
|
text("docker_jdk_version", "21", label = "Gradle version", description = "The version of the JDK to use during execution of tasks in a JDK.", display = ParameterDisplay.HIDDEN, allowEmpty = false)
|
||||||
text("docker_gradle_version", "7.5.1", label = "Gradle version", description = "The version of Gradle to use during execution of Gradle tasks.", display = ParameterDisplay.HIDDEN, allowEmpty = false)
|
text("docker_gradle_version", "8.7", label = "Gradle version", description = "The version of Gradle to use during execution of Gradle tasks.", display = ParameterDisplay.HIDDEN, allowEmpty = false)
|
||||||
text("git_main_branch", "1.20.x", label = "Git Main Branch", description = "The git main or default branch to use in VCS operations.", display = ParameterDisplay.HIDDEN, allowEmpty = false)
|
text("git_main_branch", "1.21.x", label = "Git Main Branch", description = "The git main or default branch to use in VCS operations.", display = ParameterDisplay.HIDDEN, allowEmpty = false)
|
||||||
text("git_branch_spec", """
|
text("git_branch_spec", """
|
||||||
+:refs/heads/(main*)
|
+:refs/heads/(main*)
|
||||||
+:refs/heads/(master*)
|
+:refs/heads/(master*)
|
||||||
|
|||||||
+2
-2
@@ -7,8 +7,8 @@ plugins {
|
|||||||
id 'net.minecraftforge.gradleutils' version '[2.3.0,2.4.0)'
|
id 'net.minecraftforge.gradleutils' version '[2.3.0,2.4.0)'
|
||||||
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.16,6.2)' apply false
|
id 'net.minecraftforge.gradle.patcher' version '[6.0.22,6.2)' apply false
|
||||||
id 'net.minecraftforge.gradle.mcp' version '[6.0.16,6.2)' apply false
|
id 'net.minecraftforge.gradle.mcp' version '[6.0.22,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'
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,10 +4,10 @@ repositories {
|
|||||||
}
|
}
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation 'org.ow2.asm:asm:9.6'
|
implementation 'org.ow2.asm:asm:9.7'
|
||||||
implementation 'org.ow2.asm:asm-tree:9.6'
|
implementation 'org.ow2.asm:asm-tree:9.7'
|
||||||
implementation 'net.minecraftforge:srgutils:0.5.+'
|
implementation 'net.minecraftforge:srgutils:0.5.10'
|
||||||
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.5.0.202303070854-r'
|
implementation 'org.eclipse.jgit:org.eclipse.jgit:6.7.0.202309050840-r'
|
||||||
}
|
}
|
||||||
@@ -10,11 +10,13 @@ import java.util.zip.ZipFile
|
|||||||
|
|
||||||
abstract class BundleList extends DefaultTask {
|
abstract class BundleList extends DefaultTask {
|
||||||
@InputFiles abstract ConfigurableFileCollection getConfig()
|
@InputFiles abstract ConfigurableFileCollection getConfig()
|
||||||
|
@InputFiles abstract ConfigurableFileCollection getConfigExtra()
|
||||||
@InputFile abstract RegularFileProperty getServerBundle()
|
@InputFile abstract RegularFileProperty getServerBundle()
|
||||||
@OutputFile abstract RegularFileProperty getOutput()
|
@OutputFile abstract RegularFileProperty getOutput()
|
||||||
|
|
||||||
BundleList() {
|
BundleList() {
|
||||||
config.setFrom(project.configurations.installer)
|
config.setFrom(project.configurations.installer)
|
||||||
|
configExtra.setFrom(project.configurations.installerextra)
|
||||||
output.convention(project.layout.buildDirectory.file("$name/output.list"))
|
output.convention(project.layout.buildDirectory.file("$name/output.list"))
|
||||||
configure {
|
configure {
|
||||||
dependsOn(project.tasks.universalJar)
|
dependsOn(project.tasks.universalJar)
|
||||||
@@ -32,6 +34,13 @@ abstract class BundleList extends DefaultTask {
|
|||||||
entries.put("$info.art.group:$info.art.name", "$dep.file.sha256\t$info.name\t$info.path")
|
entries.put("$info.art.group:$info.art.name", "$dep.file.sha256\t$info.name\t$info.path")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
resolved = project.configurations.installerextra.resolvedConfiguration.resolvedArtifacts
|
||||||
|
for (def dep : resolved) {
|
||||||
|
def info = Util.getMavenInfoFromDep(dep)
|
||||||
|
//println("$dep.file.sha1\t$info.name\t$info.path")
|
||||||
|
entries.put("$info.art.group:$info.art.name", "$dep.file.sha256\t$info.name\t$info.path")
|
||||||
|
}
|
||||||
|
|
||||||
var packed = (AbstractArchiveTask) project.tasks.universalJar
|
var packed = (AbstractArchiveTask) project.tasks.universalJar
|
||||||
var info = Util.getMavenInfoFromTask(packed)
|
var info = Util.getMavenInfoFromTask(packed)
|
||||||
def file = packed.archiveFile.get().asFile
|
def file = packed.archiveFile.get().asFile
|
||||||
|
|||||||
+1
-1
@@ -27,6 +27,6 @@ abstract class BytecodePredicateFinder extends BytecodeFinder {
|
|||||||
@Internal
|
@Internal
|
||||||
@Override
|
@Override
|
||||||
protected Object getData() {
|
protected Object getData() {
|
||||||
return matches.toSorted(Comparator.naturalOrder()) ?: {throw new RuntimeException('Failed to find any targets, please ensure that method names and descriptors are correct.')}()
|
return matches.toSorted(Comparator.<String>naturalOrder()) ?: {throw new RuntimeException('Failed to find any targets, please ensure that method names and descriptors are correct.')}()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -24,6 +24,7 @@ abstract class LauncherJson extends DefaultTask {
|
|||||||
dependsOn(project.tasks.universalJar)
|
dependsOn(project.tasks.universalJar)
|
||||||
input.from(project.tasks.universalJar.archiveFile)
|
input.from(project.tasks.universalJar.archiveFile)
|
||||||
input.from(project.configurations.installer)
|
input.from(project.configurations.installer)
|
||||||
|
input.from(project.configurations.installerextra)
|
||||||
configure {
|
configure {
|
||||||
def mc = project.rootProject.ext.MC_VERSION
|
def mc = project.rootProject.ext.MC_VERSION
|
||||||
def forge = project.rootProject.ext.FORGE_VERSION
|
def forge = project.rootProject.ext.FORGE_VERSION
|
||||||
@@ -88,6 +89,7 @@ abstract class LauncherJson extends DefaultTask {
|
|||||||
]
|
]
|
||||||
])
|
])
|
||||||
|
|
||||||
|
json.libraries.addAll(getArtifacts(project.configurations.installerextra).values())
|
||||||
json.libraries.addAll(getArtifacts(project.configurations.installer).values())
|
json.libraries.addAll(getArtifacts(project.configurations.installer).values())
|
||||||
Files.writeString(output.get().asFile.toPath(), new JsonBuilder(json).toPrettyString())
|
Files.writeString(output.get().asFile.toPath(), new JsonBuilder(json).toPrettyString())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -140,7 +140,7 @@ abstract class CheckPatches extends CheckTask {
|
|||||||
final nextLineChange = i + 1 < lines.size() && lines[i + 1].startsWithAny('+','-')
|
final nextLineChange = i + 1 < lines.size() && lines[i + 1].startsWithAny('+','-')
|
||||||
|
|
||||||
if (!prevLineChange && !nextLineChange) {
|
if (!prevLineChange && !nextLineChange) {
|
||||||
reporter.report("Patch contains white space change in valid hunk at line ${i + 1}, file: $patchPath", false)
|
reporter.report("Patch contains white space change in valid hunk at line ${i + 1}, file: $patchPath \n$prevLine\n$line\n${lines[i+1]}", false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -61,4 +61,13 @@ eclipse.classpath.file.whenMerged {
|
|||||||
def src = entries.find { it.path == 'src/main/java' }
|
def src = entries.find { it.path == 'src/main/java' }
|
||||||
if (src == null) throw new IllegalStateException("You must run `setup` task before importing")
|
if (src == null) throw new IllegalStateException("You must run `setup` task before importing")
|
||||||
src.entryAttributes['ignore_optional_problems'] = 'true'
|
src.entryAttributes['ignore_optional_problems'] = 'true'
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.named('genPatches').configure {
|
||||||
|
onlyIf { false }
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.named('extractRangeMap').configure {
|
||||||
|
onlyIf { false }
|
||||||
|
tool = 'net.minecraftforge:Srg2Source:8.1.0:fatjar'
|
||||||
}
|
}
|
||||||
+107
-135
@@ -12,9 +12,9 @@ import net.minecraftforge.gradle.common.tasks.ApplyBinPatches
|
|||||||
import net.minecraftforge.gradle.common.tasks.CheckJarCompatibility
|
import net.minecraftforge.gradle.common.tasks.CheckJarCompatibility
|
||||||
import net.minecraftforge.gradle.common.tasks.DownloadMavenArtifact
|
import net.minecraftforge.gradle.common.tasks.DownloadMavenArtifact
|
||||||
import net.minecraftforge.gradle.common.tasks.ExtractInheritance
|
import net.minecraftforge.gradle.common.tasks.ExtractInheritance
|
||||||
|
import net.minecraftforge.gradle.patcher.tasks.FilterNewJar
|
||||||
import net.minecraftforge.gradle.patcher.tasks.GeneratePatches
|
import net.minecraftforge.gradle.patcher.tasks.GeneratePatches
|
||||||
import net.minecraftforge.gradle.userdev.tasks.RenameJar
|
import net.minecraftforge.gradle.userdev.tasks.RenameJar
|
||||||
import net.minecraftforge.gradleutils.PomUtils
|
|
||||||
import org.apache.tools.ant.filters.ReplaceTokens
|
import org.apache.tools.ant.filters.ReplaceTokens
|
||||||
import org.objectweb.asm.Opcodes
|
import org.objectweb.asm.Opcodes
|
||||||
|
|
||||||
@@ -46,6 +46,7 @@ jarSigner.autoDetect('forge')
|
|||||||
|
|
||||||
applyPatches {
|
applyPatches {
|
||||||
level 'WARNING'
|
level 'WARNING'
|
||||||
|
failOnError = UPDATING != 'true'
|
||||||
}
|
}
|
||||||
|
|
||||||
sourceSets {
|
sourceSets {
|
||||||
@@ -88,16 +89,21 @@ ext {
|
|||||||
final String MAVEN_PATH = ext.MAVEN_PATH
|
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.0'
|
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.1.0: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.
|
||||||
bootstrap { transitive = false }
|
bootstrap { transitive = false }
|
||||||
installer {
|
installer {
|
||||||
extendsFrom(bootstrap)
|
extendsFrom(bootstrap)
|
||||||
transitive = false
|
transitive = false
|
||||||
}
|
}
|
||||||
|
installerextra {
|
||||||
|
extendsFrom(bootstrap)
|
||||||
|
transitive = false
|
||||||
|
}
|
||||||
api.extendsFrom(installer)
|
api.extendsFrom(installer)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -111,10 +117,11 @@ dependencies {
|
|||||||
bootstrap(libs.unsafe) // Needed by securemodules
|
bootstrap(libs.unsafe) // Needed by securemodules
|
||||||
bootstrap(libs.bundles.asm) // Needed by securemodules
|
bootstrap(libs.bundles.asm) // Needed by securemodules
|
||||||
|
|
||||||
|
implementation(libs.jopt.simple)
|
||||||
|
|
||||||
installer(libs.bootstrap)
|
installer(libs.bootstrap)
|
||||||
installer(libs.bootstrap.api) // Needed by securemodules
|
installer(libs.bootstrap.api) // Needed by securemodules
|
||||||
installer(libs.accesstransformers)
|
installer(libs.accesstransformers)
|
||||||
installer(libs.antlr.runtime) // Dep of AccessTransformer
|
|
||||||
installer(libs.eventbus)
|
installer(libs.eventbus)
|
||||||
installer(libs.typetools) // Dep of EventBus
|
installer(libs.typetools) // Dep of EventBus
|
||||||
installer(libs.forgespi)
|
installer(libs.forgespi)
|
||||||
@@ -135,10 +142,16 @@ dependencies {
|
|||||||
installer(project(':lowcodelanguage'))
|
installer(project(':lowcodelanguage'))
|
||||||
installer(project(':mclanguage'))
|
installer(project(':mclanguage'))
|
||||||
|
|
||||||
|
installerextra("${MCP_ARTIFACT.group}:${MCP_ARTIFACT.name}:${MCP_ARTIFACT.version}:srg2off")
|
||||||
|
|
||||||
runtimeOnly(libs.bootstrap)
|
runtimeOnly(libs.bootstrap)
|
||||||
runtimeOnly(libs.bootstrap.dev)
|
runtimeOnly(libs.bootstrap.dev)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
tasks.named('extractRangeMap').configure {
|
||||||
|
tool = S2S_TOOL
|
||||||
|
}
|
||||||
|
|
||||||
patcher {
|
patcher {
|
||||||
excs.from file("$rootDir/src/main/resources/forge.exc")
|
excs.from file("$rootDir/src/main/resources/forge.exc")
|
||||||
parent = project(':mcp')
|
parent = project(':mcp')
|
||||||
@@ -167,6 +180,7 @@ patcher {
|
|||||||
|
|
||||||
forge_client_test {
|
forge_client_test {
|
||||||
parent runs.forge_client
|
parent runs.forge_client
|
||||||
|
source sourceSets.test
|
||||||
}
|
}
|
||||||
|
|
||||||
forge_server {
|
forge_server {
|
||||||
@@ -175,14 +189,17 @@ patcher {
|
|||||||
|
|
||||||
forge_server_test {
|
forge_server_test {
|
||||||
parent runs.forge_server
|
parent runs.forge_server
|
||||||
|
source sourceSets.test
|
||||||
}
|
}
|
||||||
|
|
||||||
forge_server_gametest {
|
forge_server_gametest {
|
||||||
args '--launchTarget', 'forge_dev_server_gametest'
|
args '--launchTarget', 'forge_dev_server_gametest'
|
||||||
|
args '--uniqueWorld' // Unique world is used so that the world regenerates, as well as the world config isn't influenced by other runs
|
||||||
}
|
}
|
||||||
|
|
||||||
forge_server_gametest_test {
|
forge_server_gametest_test {
|
||||||
parent runs.forge_server_gametest
|
parent runs.forge_server_gametest
|
||||||
|
source sourceSets.test
|
||||||
}
|
}
|
||||||
|
|
||||||
forge_data {
|
forge_data {
|
||||||
@@ -198,6 +215,7 @@ patcher {
|
|||||||
}
|
}
|
||||||
|
|
||||||
forge_data_test {
|
forge_data_test {
|
||||||
|
source sourceSets.test
|
||||||
args '--launchTarget', 'forge_dev_data',
|
args '--launchTarget', 'forge_dev_data',
|
||||||
'--mod', '.+',
|
'--mod', '.+',
|
||||||
'--all',
|
'--all',
|
||||||
@@ -208,7 +226,6 @@ patcher {
|
|||||||
'--assetsDir', downloadAssets.output,
|
'--assetsDir', downloadAssets.output,
|
||||||
'--assetIndex', "{asset_index}"
|
'--assetIndex', "{asset_index}"
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -362,33 +379,15 @@ tasks.register('extractInheritance', ExtractInheritance) {
|
|||||||
Files.readAllLines(rf.asFile.toPath()).stream().map(File::new).toList()
|
Files.readAllLines(rf.asFile.toPath()).stream().map(File::new).toList()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
tasks.register("findFieldInstanceChecks", FieldCompareFinder) {
|
|
||||||
jar = createJoinedSRG.output
|
|
||||||
output = rootProject.file('src/main/resources/coremods/field_to_instanceof.json')
|
|
||||||
fields {
|
|
||||||
/* 1.17 changed most things to use Tags. So this isn't nessasary anymore so just make an empty list
|
|
||||||
bows {
|
|
||||||
cls = 'net/minecraft/world/item/Items'
|
|
||||||
name = 'f_42411_'
|
|
||||||
replacement = 'net/minecraft/world/item/BowItem'
|
|
||||||
}
|
|
||||||
crossbows {
|
|
||||||
cls = 'net/minecraft/world/item/Items'
|
|
||||||
name = 'f_42717_'
|
|
||||||
replacement = 'net/minecraft/world/item/CrossbowItem'
|
|
||||||
}
|
|
||||||
*/
|
|
||||||
}
|
|
||||||
}
|
|
||||||
tasks.register("findFinalizeSpawnTargets", BytecodePredicateFinder) {
|
tasks.register("findFinalizeSpawnTargets", BytecodePredicateFinder) {
|
||||||
jar = createJoinedSRG.output
|
jar = createJoinedSRG.output
|
||||||
output = rootProject.file('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 ->
|
||||||
'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.
|
||||||
&& insn.getOpcode() === Opcodes.INVOKEVIRTUAL
|
&& insn.getOpcode().equals(Opcodes.INVOKEVIRTUAL)
|
||||||
&& insn.name == 'm_6518_'
|
&& insn.name == 'm_6518_'
|
||||||
&& insn.desc == '(Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/world/DifficultyInstance;Lnet/minecraft/world/entity/MobSpawnType;Lnet/minecraft/world/entity/SpawnGroupData;Lnet/minecraft/nbt/CompoundTag;)Lnet/minecraft/world/entity/SpawnGroupData;'
|
&& insn.desc == '(Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/world/DifficultyInstance;Lnet/minecraft/world/entity/MobSpawnType;Lnet/minecraft/world/entity/SpawnGroupData;)Lnet/minecraft/world/entity/SpawnGroupData;';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
tasks.register('validateDeprecations', ValidateDeprecations) {
|
tasks.register('validateDeprecations', ValidateDeprecations) {
|
||||||
@@ -406,16 +405,6 @@ tasks.register("downloadServerShim", DownloadMavenArtifact) {
|
|||||||
artifact = libs.bootstrap.shim.get().toString()
|
artifact = libs.bootstrap.shim.get().toString()
|
||||||
changing = true
|
changing = true
|
||||||
}
|
}
|
||||||
tasks.register("downloadMCPConfig", DownloadMavenArtifact) {
|
|
||||||
artifact = MCP_ARTIFACT
|
|
||||||
}
|
|
||||||
tasks.register('extractMCPConfigMappings', net.minecraftforge.gradle.common.tasks.JarExec) {
|
|
||||||
ext.output = file('build/mcp_mappings.tsrg')
|
|
||||||
tool = INSTALLER_TOOLS + ':fatjar'
|
|
||||||
args = ['--task', 'MCP_DATA', '--key', 'mappings', '--input', downloadMCPConfig.output.get().asFile.absolutePath, '--output', output.absolutePath]
|
|
||||||
outputs.file(output)
|
|
||||||
inputs.file(downloadMCPConfig.output)
|
|
||||||
}
|
|
||||||
tasks.register('downloadClientMappings', net.minecraftforge.gradle.common.tasks.JarExec) {
|
tasks.register('downloadClientMappings', net.minecraftforge.gradle.common.tasks.JarExec) {
|
||||||
ext.output = file('build/client_mappings.tsrg')
|
ext.output = file('build/client_mappings.tsrg')
|
||||||
tool = INSTALLER_TOOLS + ':fatjar'
|
tool = INSTALLER_TOOLS + ':fatjar'
|
||||||
@@ -428,43 +417,34 @@ tasks.register('downloadServerMappings', net.minecraftforge.gradle.common.tasks.
|
|||||||
args = ['--task', 'DOWNLOAD_MOJMAPS', '--sanitize', '--version', MC_VERSION, '--side', 'server', '--output', output.absolutePath]
|
args = ['--task', 'DOWNLOAD_MOJMAPS', '--sanitize', '--version', MC_VERSION, '--side', 'server', '--output', output.absolutePath]
|
||||||
outputs.file(output)
|
outputs.file(output)
|
||||||
}
|
}
|
||||||
tasks.register('mergeClientMappings', net.minecraftforge.gradle.common.tasks.JarExec) {
|
|
||||||
ext.output = file('build/client_mappings_merged.tsrg')
|
|
||||||
tool = INSTALLER_TOOLS + ':fatjar'
|
|
||||||
args = ['--task', 'MERGE_MAPPING', '--classes', '--reverse-right', '--left', extractMCPConfigMappings.output.absolutePath, '--right', downloadClientMappings.output.absolutePath, '--output', output.absolutePath]
|
|
||||||
outputs.file(output)
|
|
||||||
}
|
|
||||||
tasks.register('mergeServerMappings', net.minecraftforge.gradle.common.tasks.JarExec) {
|
|
||||||
ext.output = file('build/server_mappings_merged.tsrg')
|
|
||||||
tool = INSTALLER_TOOLS + ':fatjar'
|
|
||||||
args = ['--task', 'MERGE_MAPPING', '--classes', '--reverse-right', '--left', extractMCPConfigMappings.output.absolutePath, '--right', downloadServerMappings.output.absolutePath, '--output', output.absolutePath]
|
|
||||||
outputs.file(output)
|
|
||||||
}
|
|
||||||
tasks.register("createJoinedSRG", DownloadMavenArtifact) {
|
tasks.register("createJoinedSRG", DownloadMavenArtifact) {
|
||||||
artifact = "net.minecraft:joined:${MC_VERSION}-${MCP_VERSION}:srg"
|
artifact = "net.minecraft:joined:${MC_VERSION}-${MCP_VERSION}:srg"
|
||||||
}
|
}
|
||||||
tasks.register("createClientSRG", RenameJar) {
|
tasks.register("createClientOfficial", RenameJar) {
|
||||||
tool = FART + ':all'
|
tool = FART + ':all'
|
||||||
args = ['--input', '{input}', '--output', '{output}', '--names', '{mappings}', '--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs']
|
args = ['--input', '{input}', '--output', '{output}', '--names', '{mappings}', '--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs', '--reverse']
|
||||||
mappings = createMcp2Srg.srg
|
mappings = downloadClientMappings.output
|
||||||
dependsOn(downloadClientRaw)
|
dependsOn(downloadClientRaw, downloadClientMappings)
|
||||||
input = downloadClientRaw.dest
|
input = downloadClientRaw.dest
|
||||||
output = file("build/createClientSRG/output.jar")
|
output = file("build/createClientOfficial/output.jar")
|
||||||
}
|
}
|
||||||
tasks.register("createServerSRG", RenameJar) {
|
tasks.register("createServerOfficial", RenameJar) {
|
||||||
tool = FART + ':all'
|
tool = FART + ':all'
|
||||||
args = ['--input', '{input}', '--output', '{output}', '--names', '{mappings}', '--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs']
|
args = ['--input', '{input}', '--output', '{output}', '--names', '{mappings}', '--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs', '--reverse']
|
||||||
mappings = createMcp2Srg.srg
|
mappings = downloadServerMappings.output
|
||||||
|
dependsOn(downloadServerMappings)
|
||||||
input = extractServer.output
|
input = extractServer.output
|
||||||
output = file("build/createServerSRG/output.jar")
|
output = file("build/createServerOfficial/output.jar")
|
||||||
}
|
}
|
||||||
tasks.named('genClientBinPatches').configure {
|
tasks.named('genClientBinPatches').configure {
|
||||||
tool = BINPATCH_TOOL
|
tool = BINPATCH_TOOL
|
||||||
cleanJar = createClientSRG.output
|
cleanJar = createClientOfficial.output
|
||||||
|
dirtyJar = jar.archiveFile
|
||||||
}
|
}
|
||||||
tasks.named('genServerBinPatches').configure {
|
tasks.named('genServerBinPatches').configure {
|
||||||
tool = BINPATCH_TOOL
|
tool = BINPATCH_TOOL
|
||||||
cleanJar = createServerSRG.output
|
cleanJar = createServerOfficial.output
|
||||||
|
dirtyJar = jar.archiveFile
|
||||||
}
|
}
|
||||||
tasks.named('genJoinedBinPatches').configure {
|
tasks.named('genJoinedBinPatches').configure {
|
||||||
tool = BINPATCH_TOOL
|
tool = BINPATCH_TOOL
|
||||||
@@ -472,13 +452,13 @@ tasks.named('genJoinedBinPatches').configure {
|
|||||||
}
|
}
|
||||||
tasks.register('applyClientBinPatches', ApplyBinPatches) {
|
tasks.register('applyClientBinPatches', ApplyBinPatches) {
|
||||||
tool = BINPATCH_TOOL
|
tool = BINPATCH_TOOL
|
||||||
clean = createClientSRG.output
|
clean = createClientOfficial.output
|
||||||
patch = genClientBinPatches.output
|
patch = genClientBinPatches.output
|
||||||
args.addAll(['--data', '--unpatched'])
|
args.addAll(['--data', '--unpatched'])
|
||||||
}
|
}
|
||||||
tasks.register('applyServerBinPatches', ApplyBinPatches) {
|
tasks.register('applyServerBinPatches', ApplyBinPatches) {
|
||||||
tool = BINPATCH_TOOL
|
tool = BINPATCH_TOOL
|
||||||
clean = createServerSRG.output
|
clean = createServerOfficial.output
|
||||||
patch = genServerBinPatches.output
|
patch = genServerBinPatches.output
|
||||||
args.addAll(['--data', '--unpatched'])
|
args.addAll(['--data', '--unpatched'])
|
||||||
}
|
}
|
||||||
@@ -494,10 +474,10 @@ tasks.register('createServerShimClasspath', BundleList) {
|
|||||||
tasks.register('createServerShimConfig') {
|
tasks.register('createServerShimConfig') {
|
||||||
ext.output = file('build/libs/bootstrap-shim.properties')
|
ext.output = file('build/libs/bootstrap-shim.properties')
|
||||||
doLast {
|
doLast {
|
||||||
def cfg = new CleanProperties()
|
var cfg = new CleanProperties()
|
||||||
cfg."Main-Class" = 'net.minecraftforge.bootstrap.ForgeBootstrap'
|
cfg['Main-Class'] = 'net.minecraftforge.bootstrap.ForgeBootstrap'
|
||||||
cfg."Java-Version" = '17'
|
cfg['Java-Version'] = '21'
|
||||||
cfg."Arguments" = "--launchTarget forge_server"
|
cfg['Arguments'] = '--launchTarget forge_server'
|
||||||
cfg.store(output)
|
cfg.store(output)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -523,7 +503,7 @@ tasks.register('checkAll') {
|
|||||||
group = 'checks'
|
group = 'checks'
|
||||||
}
|
}
|
||||||
tasks.register('checkAllAndFix') {
|
tasks.register('checkAllAndFix') {
|
||||||
dependsOn 'findFinalizeSpawnTargets', 'findFieldInstanceChecks', 'checkLicenses'
|
dependsOn 'findFinalizeSpawnTargets', 'checkLicenses'
|
||||||
group = 'checks'
|
group = 'checks'
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -631,21 +611,15 @@ tasks.register('installerJson', InstallerJson) {
|
|||||||
dependsOn(launcherJson)
|
dependsOn(launcherJson)
|
||||||
input.from(launcherJson.output)
|
input.from(launcherJson.output)
|
||||||
|
|
||||||
// Extract MCP Mappings
|
|
||||||
dependsOn(extractMCPConfigMappings)
|
|
||||||
input.from(extractMCPConfigMappings.output)
|
|
||||||
// Download Official Mappings
|
// Download Official Mappings
|
||||||
dependsOn(downloadClientMappings, downloadServerMappings)
|
dependsOn(downloadClientMappings, downloadServerMappings)
|
||||||
input.from(downloadClientMappings.output, downloadServerMappings.output)
|
input.from(downloadClientMappings.output, downloadServerMappings.output)
|
||||||
// Merge MCP and Official Mappings
|
|
||||||
dependsOn(mergeClientMappings, mergeServerMappings)
|
|
||||||
input.from(mergeClientMappings.output, mergeServerMappings.output)
|
|
||||||
// Get 'base' MC jar, Client is straight download, server is extracted from the bundle
|
// Get 'base' MC jar, Client is straight download, server is extracted from the bundle
|
||||||
dependsOn(downloadClientRaw, extractServer)
|
dependsOn(downloadClientRaw, extractServer)
|
||||||
input.from(downloadClientRaw.dest, extractServer.output)
|
input.from(downloadClientRaw.dest, extractServer.output)
|
||||||
// Rename MC Jar
|
// Rename MC Jar
|
||||||
dependsOn(createClientSRG, createServerSRG)
|
dependsOn(createClientOfficial, createServerOfficial)
|
||||||
input.from(createClientSRG.output, createServerSRG.output)
|
input.from(createClientOfficial.output, createServerOfficial.output)
|
||||||
// Apply Binary patches to vanilla jar
|
// Apply Binary patches to vanilla jar
|
||||||
dependsOn(applyClientBinPatches, applyServerBinPatches)
|
dependsOn(applyClientBinPatches, applyServerBinPatches)
|
||||||
input.from(applyClientBinPatches.output, applyServerBinPatches.output, genClientBinPatches.toolJar)
|
input.from(applyClientBinPatches.output, applyServerBinPatches.output, genClientBinPatches.toolJar)
|
||||||
@@ -663,30 +637,14 @@ tasks.register('installerJson', InstallerJson) {
|
|||||||
minecraft: MC_VERSION,
|
minecraft: MC_VERSION,
|
||||||
serverJarPath: '{LIBRARY_DIR}/net/minecraft/server/{MINECRAFT_VERSION}/server-{MINECRAFT_VERSION}-bundled.jar',
|
serverJarPath: '{LIBRARY_DIR}/net/minecraft/server/{MINECRAFT_VERSION}/server-{MINECRAFT_VERSION}-bundled.jar',
|
||||||
data: [
|
data: [
|
||||||
MAPPINGS: [
|
|
||||||
client: "[${MCP_ARTIFACT.group}:${MCP_ARTIFACT.name}:${MCP_ARTIFACT.version}:mappings@tsrg]",
|
|
||||||
server: "[${MCP_ARTIFACT.group}:${MCP_ARTIFACT.name}:${MCP_ARTIFACT.version}:mappings@tsrg]"
|
|
||||||
],
|
|
||||||
MAPPINGS_SHA: [
|
|
||||||
client: "'${extractMCPConfigMappings.output.sha1}'",
|
|
||||||
server: "'${extractMCPConfigMappings.output.sha1}'"
|
|
||||||
],
|
|
||||||
MOJMAPS: [
|
MOJMAPS: [
|
||||||
client: "[net.minecraft:client:${MC_VERSION}-${MCP_VERSION}:mappings@tsrg]",
|
client: "[net.minecraft:client:${MC_VERSION}:mappings@tsrg]",
|
||||||
server: "[net.minecraft:server:${MC_VERSION}-${MCP_VERSION}:mappings@tsrg]"
|
server: "[net.minecraft:server:${MC_VERSION}:mappings@tsrg]"
|
||||||
],
|
],
|
||||||
MOJMAPS_SHA: [
|
MOJMAPS_SHA: [
|
||||||
client: "'${downloadClientMappings.output.sha1}'",
|
client: "'${downloadClientMappings.output.sha1}'",
|
||||||
server: "'${downloadServerMappings.output.sha1}'"
|
server: "'${downloadServerMappings.output.sha1}'"
|
||||||
],
|
],
|
||||||
MERGED_MAPPINGS: [
|
|
||||||
client: "[${MCP_ARTIFACT.group}:${MCP_ARTIFACT.name}:${MCP_ARTIFACT.version}:mappings-merged@tsrg]",
|
|
||||||
server: "[${MCP_ARTIFACT.group}:${MCP_ARTIFACT.name}:${MCP_ARTIFACT.version}:mappings-merged@tsrg]"
|
|
||||||
],
|
|
||||||
MERGED_MAPPINGS_SHA: [
|
|
||||||
client: "'${mergeClientMappings.output.sha1}'",
|
|
||||||
server: "'${mergeServerMappings.output.sha1}'"
|
|
||||||
],
|
|
||||||
MC_UNPACKED: [
|
MC_UNPACKED: [
|
||||||
client: "[net.minecraft:client:${MC_VERSION}]",
|
client: "[net.minecraft:client:${MC_VERSION}]",
|
||||||
server: "[net.minecraft:server:${MC_VERSION}:unpacked]"
|
server: "[net.minecraft:server:${MC_VERSION}:unpacked]"
|
||||||
@@ -695,13 +653,13 @@ tasks.register('installerJson', InstallerJson) {
|
|||||||
client: "'${downloadClientRaw.dest.sha1}'",
|
client: "'${downloadClientRaw.dest.sha1}'",
|
||||||
server: "'${extractServer.output.get().asFile.sha1}'"
|
server: "'${extractServer.output.get().asFile.sha1}'"
|
||||||
],
|
],
|
||||||
MC_SRG: [
|
MC_OFF: [
|
||||||
client: "[net.minecraft:client:${MC_VERSION}-${MCP_VERSION}:srg]",
|
client: "[net.minecraft:client:${MC_VERSION}:official]",
|
||||||
server: "[net.minecraft:server:${MC_VERSION}-${MCP_VERSION}:srg]"
|
server: "[net.minecraft:server:${MC_VERSION}:official]"
|
||||||
],
|
],
|
||||||
MC_SRG_SHA: [
|
MC_OFF_SHA: [
|
||||||
client: "'${createClientSRG.output.get().asFile.sha1}'",
|
client: "'${createClientOfficial.output.get().asFile.sha1}'",
|
||||||
server: "'${createServerSRG.output.get().asFile.sha1}'"
|
server: "'${createServerOfficial.output.get().asFile.sha1}'"
|
||||||
],
|
],
|
||||||
BINPATCH: [
|
BINPATCH: [
|
||||||
client: '/data/client.lzma',
|
client: '/data/client.lzma',
|
||||||
@@ -768,18 +726,6 @@ tasks.register('installerJson', InstallerJson) {
|
|||||||
outputs: [
|
outputs: [
|
||||||
'{MC_UNPACKED}': '{MC_UNPACKED_SHA}'
|
'{MC_UNPACKED}': '{MC_UNPACKED_SHA}'
|
||||||
]
|
]
|
||||||
], [
|
|
||||||
jar: INSTALLER_TOOLS,
|
|
||||||
classpath: INSTALLER_TOOLS_CLASSPATH,
|
|
||||||
args: [
|
|
||||||
'--task', 'MCP_DATA',
|
|
||||||
'--input', "[${MCP_ARTIFACT.descriptor}]",
|
|
||||||
'--output', '{MAPPINGS}',
|
|
||||||
'--key', 'mappings'
|
|
||||||
],
|
|
||||||
outputs: [
|
|
||||||
'{MAPPINGS}': '{MAPPINGS_SHA}'
|
|
||||||
]
|
|
||||||
], [
|
], [
|
||||||
jar: INSTALLER_TOOLS,
|
jar: INSTALLER_TOOLS,
|
||||||
classpath: INSTALLER_TOOLS_CLASSPATH,
|
classpath: INSTALLER_TOOLS_CLASSPATH,
|
||||||
@@ -793,31 +739,18 @@ tasks.register('installerJson', InstallerJson) {
|
|||||||
outputs: [
|
outputs: [
|
||||||
'{MOJMAPS}': '{MOJMAPS_SHA}'
|
'{MOJMAPS}': '{MOJMAPS_SHA}'
|
||||||
]
|
]
|
||||||
], [
|
|
||||||
jar: INSTALLER_TOOLS,
|
|
||||||
classpath: INSTALLER_TOOLS_CLASSPATH,
|
|
||||||
args: [
|
|
||||||
'--task', 'MERGE_MAPPING',
|
|
||||||
'--left', '{MAPPINGS}',
|
|
||||||
'--right', '{MOJMAPS}',
|
|
||||||
'--output', '{MERGED_MAPPINGS}',
|
|
||||||
'--classes', '--reverse-right'
|
|
||||||
],
|
|
||||||
outputs: [
|
|
||||||
'{MERGED_MAPPINGS}': '{MERGED_MAPPINGS_SHA}'
|
|
||||||
]
|
|
||||||
], [
|
], [
|
||||||
sides: ['server'],
|
sides: ['server'],
|
||||||
jar: FART,
|
jar: FART,
|
||||||
classpath: getClasspath(project, libs, FART),
|
classpath: getClasspath(project, libs, FART),
|
||||||
args: [
|
args: [
|
||||||
'--input', '{MC_UNPACKED}',
|
'--input', '{MC_UNPACKED}',
|
||||||
'--output', '{MC_SRG}',
|
'--output', '{MC_OFF}',
|
||||||
'--names', '{MERGED_MAPPINGS}',
|
'--names', '{MOJMAPS}',
|
||||||
'--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs'
|
'--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs', '--reverse'
|
||||||
],
|
],
|
||||||
outputs: [
|
outputs: [
|
||||||
'{MC_SRG}': '{MC_SRG_SHA}'
|
'{MC_OFF}': '{MC_OFF_SHA}'
|
||||||
]
|
]
|
||||||
], [
|
], [
|
||||||
sides: ['client'],
|
sides: ['client'],
|
||||||
@@ -825,18 +758,18 @@ tasks.register('installerJson', InstallerJson) {
|
|||||||
classpath: getClasspath(project, libs, FART),
|
classpath: getClasspath(project, libs, FART),
|
||||||
args: [
|
args: [
|
||||||
'--input', '{MINECRAFT_JAR}',
|
'--input', '{MINECRAFT_JAR}',
|
||||||
'--output', '{MC_SRG}',
|
'--output', '{MC_OFF}',
|
||||||
'--names', '{MERGED_MAPPINGS}',
|
'--names', '{MOJMAPS}',
|
||||||
'--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs'
|
'--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs', '--reverse'
|
||||||
],
|
],
|
||||||
outputs: [
|
outputs: [
|
||||||
'{MC_SRG}': '{MC_SRG_SHA}'
|
'{MC_OFF}': '{MC_OFF_SHA}'
|
||||||
]
|
]
|
||||||
], [
|
], [
|
||||||
jar: BINPATCH_TOOL.rsplit(':', 1)[0], // remove :fatjar
|
jar: BINPATCH_TOOL.rsplit(':', 1)[0], // remove :fatjar
|
||||||
classpath: getClasspath(project, libs, BINPATCH_TOOL.rsplit(':', 1)[0]),
|
classpath: getClasspath(project, libs, BINPATCH_TOOL.rsplit(':', 1)[0]),
|
||||||
args: [
|
args: [
|
||||||
'--clean', '{MC_SRG}',
|
'--clean', '{MC_OFF}',
|
||||||
'--output', '{PATCHED}',
|
'--output', '{PATCHED}',
|
||||||
'--apply', '{BINPATCH}',
|
'--apply', '{BINPATCH}',
|
||||||
'--data', '--unpatched'
|
'--data', '--unpatched'
|
||||||
@@ -851,6 +784,27 @@ tasks.register('installerJson', InstallerJson) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
tasks.register('officialClassesOnly', Zip).configure {
|
||||||
|
dependsOn(jar)
|
||||||
|
destinationDirectory = file('build/libs')
|
||||||
|
archiveClassifier = 'official-classes'
|
||||||
|
from zipTree(jar.archiveFile).matching {
|
||||||
|
include '**/*.class'
|
||||||
|
exclude 'mcp/**'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.named('filterJarNew').configure {
|
||||||
|
dependsOn('officialClassesOnly')
|
||||||
|
input = officialClassesOnly.archiveFile
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.register('filterJarNewSRG', FilterNewJar).configure {
|
||||||
|
input = reobfJar.output
|
||||||
|
srg = filterJarNew.srg
|
||||||
|
blacklist = filterJarNew.blacklist
|
||||||
|
}
|
||||||
|
|
||||||
tasks.named('universalJar').configure {
|
tasks.named('universalJar').configure {
|
||||||
dependsOn downloadCrowdin
|
dependsOn downloadCrowdin
|
||||||
from zipTree(downloadCrowdin.dest).matching {
|
from zipTree(downloadCrowdin.dest).matching {
|
||||||
@@ -862,6 +816,9 @@ tasks.named('universalJar').configure {
|
|||||||
exclude '.cache'
|
exclude '.cache'
|
||||||
|
|
||||||
manifest {
|
manifest {
|
||||||
|
attributes([
|
||||||
|
'Automatic-Module-Name': 'net.minecraftforge.forge'
|
||||||
|
] as LinkedHashMap)
|
||||||
attributes([
|
attributes([
|
||||||
'Specification-Title': 'Forge',
|
'Specification-Title': 'Forge',
|
||||||
'Specification-Vendor': 'Forge Development LLC',
|
'Specification-Vendor': 'Forge Development LLC',
|
||||||
@@ -882,6 +839,20 @@ tasks.named('universalJar').configure {
|
|||||||
jarSigner.sign(it)
|
jarSigner.sign(it)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
tasks.register('universalJarSrg', Jar).configure {
|
||||||
|
from zipTree(filterJarNewSRG.output)
|
||||||
|
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
|
||||||
|
from zipTree(universalJar.archiveFile)
|
||||||
|
destinationDirectory = file('build/libs')
|
||||||
|
archiveClassifier = 'universal-srg'
|
||||||
|
manifest.from(universalJar.manifest)
|
||||||
|
jarSigner.sign(it)
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.named('userdevConfig').configure {
|
||||||
|
universal = "$project.group:$project.name:$project.version:universal-srg@jar"
|
||||||
|
}
|
||||||
|
|
||||||
tasks.register('installerJar', InstallerJar) {
|
tasks.register('installerJar', InstallerJar) {
|
||||||
fat = !System.env.TEAMCITY_VERSION
|
fat = !System.env.TEAMCITY_VERSION
|
||||||
//offline = true
|
//offline = true
|
||||||
@@ -1068,6 +1039,7 @@ tasks.named('javadoc', Javadoc).configure {
|
|||||||
publishing {
|
publishing {
|
||||||
publications.register('mavenJava', MavenPublication).configure {
|
publications.register('mavenJava', MavenPublication).configure {
|
||||||
artifact universalJar
|
artifact universalJar
|
||||||
|
artifact universalJarSrg
|
||||||
artifact installerJar
|
artifact installerJar
|
||||||
artifact mdkZip
|
artifact mdkZip
|
||||||
artifact userdevJar
|
artifact userdevJar
|
||||||
@@ -1079,8 +1051,8 @@ publishing {
|
|||||||
name = project.name
|
name = project.name
|
||||||
description = 'Modifactions to Minecraft to enable mod developers.'
|
description = 'Modifactions to Minecraft to enable mod developers.'
|
||||||
url = 'https://github.com/MinecraftForge/MinecraftForge'
|
url = 'https://github.com/MinecraftForge/MinecraftForge'
|
||||||
PomUtils.setGitHubDetails(pom, 'MinecraftForge')
|
gradleutils.pom.setGitHubDetails(pom, 'MinecraftForge')
|
||||||
license PomUtils.Licenses.LGPLv2_1
|
license gradleutils.pom.Licenses.LGPLv2_1
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1090,5 +1062,5 @@ publishing {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Make sure we run bin compat checking during local testing.
|
// Make sure we run bin compat checking during local testing.
|
||||||
if (!System.env.MAVEN_USER || !System.env.MAVEN_PASSWORD)
|
if ((!System.env.MAVEN_USER || !System.env.MAVEN_PASSWORD) && CHECK_COMPATIBILITY == "true")
|
||||||
tasks.named('publish').configure { dependsOn(':forge:checkJarCompatibility') }
|
tasks.named('publish').configure { dependsOn(':forge:checkJarCompatibility') }
|
||||||
@@ -44,6 +44,7 @@ tasks.withType(JavaCompile).configureEach {
|
|||||||
dependsOn 'processResources' // Needed because we merge the output of this with the output of the compile task. And gradle detects downstream tasks using the output without a hard dep
|
dependsOn 'processResources' // Needed because we merge the output of this with the output of the compile task. And gradle detects downstream tasks using the output without a hard dep
|
||||||
options.encoding = 'UTF-8' // Use the UTF-8 charset for Java compilation
|
options.encoding = 'UTF-8' // Use the UTF-8 charset for Java compilation
|
||||||
options.warnings = false // Shutup deprecated for removal warnings
|
options.warnings = false // Shutup deprecated for removal warnings
|
||||||
|
options.forkOptions.jvmArgs += '-Xmx3G' // Needed to make compiling faster, and not run out of heap space in some cases.
|
||||||
}
|
}
|
||||||
|
|
||||||
// Merge the resources and classes into the same directory. We'll need to split them at runtime because
|
// Merge the resources and classes into the same directory. We'll need to split them at runtime because
|
||||||
@@ -74,3 +75,11 @@ eclipse {
|
|||||||
// Run when importing the project
|
// Run when importing the project
|
||||||
synchronizationTasks generateResources, copyEclipseSettings, eclipseClasspath, eclipseProject
|
synchronizationTasks generateResources, copyEclipseSettings, eclipseClasspath, eclipseProject
|
||||||
}
|
}
|
||||||
|
|
||||||
|
idea {
|
||||||
|
module {
|
||||||
|
// IntelliJ IDEA does not do this by itself anymore...
|
||||||
|
downloadJavadoc = true
|
||||||
|
downloadSources = true
|
||||||
|
}
|
||||||
|
}
|
||||||
+25
-6
@@ -2,16 +2,15 @@
|
|||||||
|
|
||||||
MinecraftForge
|
MinecraftForge
|
||||||
=============
|
=============
|
||||||
[][Download]
|
[][Download]
|
||||||
[][Download] [][Discord] [][Patreon]
|
)][Download] [][Discord] [][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!
|
||||||
|
|
||||||
| Version | Support |
|
| Version | Support |
|
||||||
|---------| ------------- |
|
|--------------|-----------------------------|
|
||||||
| 1.20.x | Active |
|
| All versions | [Supported][Support-Policy] |
|
||||||
| 1.19.x | Legacy |
|
|
||||||
|
|
||||||
* [Download]
|
* [Download]
|
||||||
* [Forum]
|
* [Forum]
|
||||||
@@ -31,6 +30,19 @@ You can download the installer for the *Recommended Build* or the
|
|||||||
|
|
||||||
For support and questions, visit [the Support Forum][Support-Forum] or [the Forge Discord server][Discord].
|
For support and questions, visit [the Support Forum][Support-Forum] or [the Forge Discord server][Discord].
|
||||||
|
|
||||||
|
## Required Java Versions
|
||||||
|
|
||||||
|
We require the version of Java that Minecraft requires, which is currently:
|
||||||
|
|
||||||
|
| Minecraft | Java |
|
||||||
|
|---------------|-------------------|
|
||||||
|
| 1.20.6+ | [21][Adoptium-21] |
|
||||||
|
| 1.18 - 1.20.4 | [17][Adoptium-17] |
|
||||||
|
| 1.17.1 | [16][Adoptium-16] |
|
||||||
|
| 1.16.5- | [8][Adoptium-8] |
|
||||||
|
|
||||||
|
**If you are on Windows and have difficulty using Java to launch JAR files, consider using [Jarfix by Johann Löfflmann][Jarfix].**
|
||||||
|
|
||||||
# Creating Mods
|
# Creating Mods
|
||||||
|
|
||||||
[See the "Getting Started" section in the Forge Documentation][Getting-Started].
|
[See the "Getting Started" section in the Forge Documentation][Getting-Started].
|
||||||
@@ -63,8 +75,15 @@ Please ensure you have a valid email address associated with your GitHub account
|
|||||||
|
|
||||||
[Download]: https://files.minecraftforge.net/
|
[Download]: https://files.minecraftforge.net/
|
||||||
|
|
||||||
|
[Adoptium-21]: https://adoptium.net/temurin/releases/?version=21
|
||||||
|
[Adoptium-17]: https://adoptium.net/temurin/releases/?version=17
|
||||||
|
[Adoptium-16]: https://adoptium.net/temurin/releases/?version=16
|
||||||
|
[Adoptium-8]: https://adoptium.net/temurin/releases/?version=8
|
||||||
|
[Jarfix]: https://johann.loefflmann.net/en/software/jarfix/index.html
|
||||||
|
|
||||||
[Forum]: https://forums.minecraftforge.net/
|
[Forum]: https://forums.minecraftforge.net/
|
||||||
[Support-Forum]: https://forums.minecraftforge.net/forum/18-support-bug-reports/
|
[Support-Forum]: https://forums.minecraftforge.net/forum/18-support-bug-reports/
|
||||||
|
[Support-Policy]: https://forums.minecraftforge.net/topic/144690-new-tiered-support-policy
|
||||||
|
|
||||||
[Discord]: https://discord.minecraftforge.net/
|
[Discord]: https://discord.minecraftforge.net/
|
||||||
|
|
||||||
|
|||||||
@@ -9,41 +9,35 @@ import net.minecraftforge.eventbus.api.IEventBus;
|
|||||||
import net.minecraftforge.fml.config.IConfigEvent;
|
import net.minecraftforge.fml.config.IConfigEvent;
|
||||||
import net.minecraftforge.fml.loading.FMLLoader;
|
import net.minecraftforge.fml.loading.FMLLoader;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.ServiceConfigurationError;
|
import java.util.ServiceConfigurationError;
|
||||||
import java.util.ServiceLoader;
|
import java.util.ServiceLoader;
|
||||||
import java.util.function.Supplier;
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Used to allow access to certain things from the game layer
|
||||||
|
*/
|
||||||
public class Bindings {
|
public class Bindings {
|
||||||
private static final Bindings INSTANCE = new Bindings();
|
private Bindings() {}
|
||||||
|
|
||||||
private final IBindingsProvider provider;
|
/**
|
||||||
|
* The provider of the bindings
|
||||||
private Bindings() {
|
* @implNote May also throw a {@link ServiceConfigurationError}
|
||||||
var providers = new ArrayList<IBindingsProvider>(1);
|
*/
|
||||||
for (var itr = ServiceLoader.load(FMLLoader.getGameLayer(), IBindingsProvider.class).iterator(); itr.hasNext(); ) {
|
private static final IBindingsProvider PROVIDER = ServiceLoader.load(FMLLoader.getGameLayer(), IBindingsProvider.class)
|
||||||
try {
|
.findFirst().orElseThrow(() -> new IllegalStateException("Could not find bindings provider"));
|
||||||
providers.add(itr.next());
|
|
||||||
} catch (ServiceConfigurationError sce) {
|
|
||||||
sce.printStackTrace();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (providers.size() != 1)
|
|
||||||
throw new IllegalStateException("Could not find bindings provider: " + providers);
|
|
||||||
|
|
||||||
this.provider = providers.get(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return A supplier of net.minecraftforge.common.MinecraftForge#EVENT_BUS
|
||||||
|
*/
|
||||||
public static Supplier<IEventBus> getForgeBus() {
|
public static Supplier<IEventBus> getForgeBus() {
|
||||||
return INSTANCE.provider.getForgeBusSupplier();
|
return PROVIDER.getForgeBusSupplier();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Supplier<I18NParser> getMessageParser() {
|
public static Supplier<I18NParser> getMessageParser() {
|
||||||
return INSTANCE.provider.getMessageParser();
|
return PROVIDER.getMessageParser();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Supplier<IConfigEvent.ConfigConfig> getConfigConfiguration() {
|
public static Supplier<IConfigEvent.ConfigConfig> getConfigConfiguration() {
|
||||||
return INSTANCE.provider.getConfigConfiguration();
|
return PROVIDER.getConfigConfiguration();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -57,7 +57,9 @@ public class DeferredWorkQueue
|
|||||||
LOGGER.debug(LOADING, "Dispatching synchronous work for work queue {}: {} jobs", modLoadingStage, tasks.size());
|
LOGGER.debug(LOADING, "Dispatching synchronous work for work queue {}: {} jobs", modLoadingStage, tasks.size());
|
||||||
RuntimeException aggregate = new RuntimeException();
|
RuntimeException aggregate = new RuntimeException();
|
||||||
Stopwatch timer = Stopwatch.createStarted();
|
Stopwatch timer = Stopwatch.createStarted();
|
||||||
tasks.forEach(t -> makeRunnable(t, Runnable::run, aggregate));
|
for (TaskInfo t : tasks) {
|
||||||
|
makeRunnable(t, Runnable::run, aggregate);
|
||||||
|
}
|
||||||
timer.stop();
|
timer.stop();
|
||||||
if (aggregate.getSuppressed().length > 0) {
|
if (aggregate.getSuppressed().length > 0) {
|
||||||
LOGGER.fatal(
|
LOGGER.fatal(
|
||||||
@@ -114,7 +116,7 @@ public class DeferredWorkQueue
|
|||||||
return future;
|
return future;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static class TaskInfo {
|
private static final class TaskInfo {
|
||||||
private final ModContainer owner;
|
private final ModContainer owner;
|
||||||
private Runnable task;
|
private Runnable task;
|
||||||
private CompletableFuture<?> future;
|
private CompletableFuture<?> future;
|
||||||
|
|||||||
@@ -61,7 +61,7 @@ public class InterModComms
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static ConcurrentMap<String, ConcurrentLinkedQueue<IMCMessage>> containerQueues = new ConcurrentHashMap<>();
|
private static final ConcurrentMap<String, ConcurrentLinkedQueue<IMCMessage>> containerQueues = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Send IMC to remote. Sender will default to the active modcontainer, or minecraft if not.
|
* Send IMC to remote. Sender will default to the active modcontainer, or minecraft if not.
|
||||||
@@ -115,16 +115,14 @@ public class InterModComms
|
|||||||
return getMessages(modId, s->Boolean.TRUE);
|
return getMessages(modId, s->Boolean.TRUE);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static class QueueFilteringSpliterator implements Spliterator<IMCMessage>
|
private record QueueFilteringSpliterator(
|
||||||
{
|
ConcurrentLinkedQueue<IMCMessage> queue,
|
||||||
private final ConcurrentLinkedQueue<IMCMessage> queue;
|
Predicate<String> methodFilter,
|
||||||
private final Predicate<String> methodFilter;
|
Iterator<IMCMessage> iterator
|
||||||
private final Iterator<IMCMessage> iterator;
|
) implements Spliterator<IMCMessage> {
|
||||||
|
|
||||||
public QueueFilteringSpliterator(final ConcurrentLinkedQueue<IMCMessage> queue, final Predicate<String> methodFilter) {
|
public QueueFilteringSpliterator(final ConcurrentLinkedQueue<IMCMessage> queue, final Predicate<String> methodFilter) {
|
||||||
this.queue = queue;
|
this(queue, methodFilter, queue.iterator());
|
||||||
this.iterator = queue.iterator();
|
|
||||||
this.methodFilter = methodFilter;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -16,8 +16,7 @@ import net.minecraftforge.api.distmarker.Dist;
|
|||||||
*
|
*
|
||||||
* @see Dist
|
* @see Dist
|
||||||
*/
|
*/
|
||||||
public enum LogicalSide
|
public enum LogicalSide {
|
||||||
{
|
|
||||||
/**
|
/**
|
||||||
* The logical client of the Minecraft game, which interfaces with the player's inputs and renders the player's
|
* The logical client of the Minecraft game, which interfaces with the player's inputs and renders the player's
|
||||||
* viewpoint.
|
* viewpoint.
|
||||||
@@ -27,6 +26,7 @@ public enum LogicalSide
|
|||||||
* @see Dist#CLIENT
|
* @see Dist#CLIENT
|
||||||
*/
|
*/
|
||||||
CLIENT,
|
CLIENT,
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The logical server of the Minecraft game, responsible for connecting to clients and running the simulation logic
|
* The logical server of the Minecraft game, responsible for connecting to clients and running the simulation logic
|
||||||
* on the level.
|
* on the level.
|
||||||
@@ -41,16 +41,14 @@ public enum LogicalSide
|
|||||||
/**
|
/**
|
||||||
* {@return if this logical side is the server}
|
* {@return if this logical side is the server}
|
||||||
*/
|
*/
|
||||||
public boolean isServer()
|
public boolean isServer() {
|
||||||
{
|
|
||||||
return !isClient();
|
return !isClient();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* {@return if the logical side is the client}
|
* {@return if the logical side is the client}
|
||||||
*/
|
*/
|
||||||
public boolean isClient()
|
public boolean isClient() {
|
||||||
{
|
|
||||||
return this == CLIENT;
|
return this == CLIENT;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -45,7 +45,7 @@ public abstract class ModContainer
|
|||||||
protected final IModInfo modInfo;
|
protected final IModInfo modInfo;
|
||||||
protected ModLoadingStage modLoadingStage;
|
protected ModLoadingStage modLoadingStage;
|
||||||
protected Supplier<?> contextExtension;
|
protected Supplier<?> contextExtension;
|
||||||
protected final Map<ModLoadingStage, Runnable> activityMap = new HashMap<>();
|
protected final Map<ModLoadingStage, Runnable> activityMap = new EnumMap<>(ModLoadingStage.class);
|
||||||
protected final Map<Class<? extends IExtensionPoint<?>>, Supplier<?>> extensionPoints = new IdentityHashMap<>();
|
protected final Map<Class<? extends IExtensionPoint<?>>, Supplier<?>> extensionPoints = new IdentityHashMap<>();
|
||||||
protected final EnumMap<ModConfig.Type, ModConfig> configs = new EnumMap<>(ModConfig.Type.class);
|
protected final EnumMap<ModConfig.Type, ModConfig> configs = new EnumMap<>(ModConfig.Type.class);
|
||||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||||
@@ -168,7 +168,10 @@ public abstract class ModContainer
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void dispatchConfigEvent(IConfigEvent event) {
|
public void dispatchConfigEvent(IConfigEvent event) {
|
||||||
configHandler.ifPresent(configHandler->configHandler.accept(event));
|
var handler = configHandler.orElse(null);
|
||||||
|
if (handler != null) {
|
||||||
|
handler.accept(event);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -74,11 +74,12 @@ public class ModList
|
|||||||
}
|
}
|
||||||
|
|
||||||
private String fileToLine(IModFile mf) {
|
private String fileToLine(IModFile mf) {
|
||||||
|
var mainMod = mf.getModInfos().getFirst();
|
||||||
return String.format(Locale.ENGLISH, "%-50.50s|%-30.30s|%-30.30s|%-20.20s|%-10.10s|Manifest: %s", mf.getFileName(),
|
return String.format(Locale.ENGLISH, "%-50.50s|%-30.30s|%-30.30s|%-20.20s|%-10.10s|Manifest: %s", mf.getFileName(),
|
||||||
mf.getModInfos().get(0).getDisplayName(),
|
mainMod.getDisplayName(),
|
||||||
mf.getModInfos().get(0).getModId(),
|
mainMod.getModId(),
|
||||||
mf.getModInfos().get(0).getVersion(),
|
mainMod.getVersion(),
|
||||||
getModContainerState(mf.getModInfos().get(0).getModId()),
|
getModContainerState(mainMod.getModId()),
|
||||||
((ModFileInfo)mf.getModFileInfo()).getCodeSigningFingerprint().orElse("NOSIGNATURE"));
|
((ModFileInfo)mf.getModFileInfo()).getCodeSigningFingerprint().orElse("NOSIGNATURE"));
|
||||||
}
|
}
|
||||||
private String crashReport() {
|
private String crashReport() {
|
||||||
@@ -95,14 +96,6 @@ public class ModList
|
|||||||
return INSTANCE;
|
return INSTANCE;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static ForkJoinWorkerThread newForkJoinWorkerThread(ForkJoinPool pool) {
|
|
||||||
ForkJoinWorkerThread thread = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool);
|
|
||||||
thread.setName("modloading-worker-" + thread.getPoolIndex());
|
|
||||||
// The default sets it to the SystemClassloader, so copy the current one.
|
|
||||||
thread.setContextClassLoader(Thread.currentThread().getContextClassLoader());
|
|
||||||
return thread;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<IModFileInfo> getModFiles()
|
public List<IModFileInfo> getModFiles()
|
||||||
{
|
{
|
||||||
return modFiles;
|
return modFiles;
|
||||||
@@ -131,16 +124,18 @@ public class ModList
|
|||||||
CompletableFuture<Void> cf = new CompletableFuture<>();
|
CompletableFuture<Void> cf = new CompletableFuture<>();
|
||||||
final RuntimeException accumulator = new RuntimeException();
|
final RuntimeException accumulator = new RuntimeException();
|
||||||
cf.completeExceptionally(accumulator);
|
cf.completeExceptionally(accumulator);
|
||||||
throwables.forEach(exception -> {
|
for (Throwable exception : throwables) {
|
||||||
if (exception instanceof CompletionException) {
|
if (exception instanceof CompletionException) {
|
||||||
exception = exception.getCause();
|
exception = exception.getCause();
|
||||||
}
|
}
|
||||||
if (exception.getSuppressed().length!=0) {
|
if (exception.getSuppressed().length != 0) {
|
||||||
Arrays.stream(exception.getSuppressed()).forEach(accumulator::addSuppressed);
|
for (Throwable throwable : exception.getSuppressed()) {
|
||||||
|
accumulator.addSuppressed(throwable);
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
accumulator.addSuppressed(exception);
|
accumulator.addSuppressed(exception);
|
||||||
}
|
}
|
||||||
});
|
}
|
||||||
return cf;
|
return cf;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -148,11 +143,11 @@ public class ModList
|
|||||||
static <V> CompletableFuture<List<Map.Entry<V, Throwable>>> gather(List<? extends CompletableFuture<? extends V>> futures) {
|
static <V> CompletableFuture<List<Map.Entry<V, Throwable>>> gather(List<? extends CompletableFuture<? extends V>> futures) {
|
||||||
List<Map.Entry<V, Throwable>> list = new ArrayList<>(futures.size());
|
List<Map.Entry<V, Throwable>> list = new ArrayList<>(futures.size());
|
||||||
CompletableFuture<?>[] results = new CompletableFuture[futures.size()];
|
CompletableFuture<?>[] results = new CompletableFuture[futures.size()];
|
||||||
futures.forEach(future -> {
|
for (var future : futures) {
|
||||||
int i = list.size();
|
int i = list.size();
|
||||||
list.add(null);
|
list.add(null);
|
||||||
results[i] = future.whenComplete((result, exception) -> list.set(i, new AbstractMap.SimpleImmutableEntry<>(result, exception)));
|
results[i] = future.whenComplete((result, exception) -> list.set(i, new AbstractMap.SimpleImmutableEntry<>(result, exception)));
|
||||||
});
|
}
|
||||||
return CompletableFuture.allOf(results).handle((r, th)->null).thenApply(res -> list);
|
return CompletableFuture.allOf(results).handle((r, th)->null).thenApply(res -> list);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -77,13 +77,13 @@ import static net.minecraftforge.fml.Logging.LOADING;
|
|||||||
public class ModLoader
|
public class ModLoader
|
||||||
{
|
{
|
||||||
private static final Logger LOGGER = LogManager.getLogger();
|
private static final Logger LOGGER = LogManager.getLogger();
|
||||||
private static ModLoader INSTANCE;
|
|
||||||
private final LoadingModList loadingModList;
|
private final LoadingModList loadingModList;
|
||||||
|
|
||||||
private final List<ModLoadingException> loadingExceptions;
|
private final List<ModLoadingException> loadingExceptions;
|
||||||
|
private final Set<IModInfo> erroredModInfos;
|
||||||
private final List<ModLoadingWarning> loadingWarnings;
|
private final List<ModLoadingWarning> loadingWarnings;
|
||||||
private final ModStateManager stateManager;
|
private final ModStateManager stateManager;
|
||||||
private boolean loadingStateValid;
|
private static boolean loadingStateValid;
|
||||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||||
private final Optional<Consumer<String>> statusConsumer = StartupNotificationManager.modLoaderConsumer();
|
private final Optional<Consumer<String>> statusConsumer = StartupNotificationManager.modLoaderConsumer();
|
||||||
private final Set<IModLoadingState> completedStates = new HashSet<>();
|
private final Set<IModLoadingState> completedStates = new HashSet<>();
|
||||||
@@ -91,7 +91,6 @@ public class ModLoader
|
|||||||
|
|
||||||
private ModLoader()
|
private ModLoader()
|
||||||
{
|
{
|
||||||
INSTANCE = this;
|
|
||||||
this.loadingModList = FMLLoader.getLoadingModList();
|
this.loadingModList = FMLLoader.getLoadingModList();
|
||||||
this.loadingExceptions = this.loadingModList.getErrors().stream()
|
this.loadingExceptions = this.loadingModList.getErrors().stream()
|
||||||
.flatMap(ModLoadingException::fromEarlyException)
|
.flatMap(ModLoadingException::fromEarlyException)
|
||||||
@@ -99,24 +98,32 @@ public class ModLoader
|
|||||||
this.loadingWarnings = this.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 (this.loadingExceptions.isEmpty()) {
|
||||||
|
this.erroredModInfos = Collections.emptySet();
|
||||||
|
} else {
|
||||||
|
this.erroredModInfos = Collections.newSetFromMap(new IdentityHashMap<>());
|
||||||
|
this.erroredModInfos.addAll(this.loadingExceptions.stream().map(ModLoadingException::getModInfo).toList());
|
||||||
|
}
|
||||||
this.loadingModList.getModFiles().stream()
|
this.loadingModList.getModFiles().stream()
|
||||||
.filter(ModFileInfo::missingLicense)
|
.filter(ModFileInfo::missingLicense)
|
||||||
.filter(modFileInfo -> modFileInfo.getMods().stream().noneMatch(thisModInfo -> this.loadingExceptions.stream().map(ModLoadingException::getModInfo).anyMatch(otherInfo -> otherInfo == thisModInfo))) //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()))
|
||||||
.forEach(this.loadingExceptions::add);
|
.forEach(this.loadingExceptions::add);
|
||||||
this.stateManager = new ModStateManager();
|
this.stateManager = new ModStateManager();
|
||||||
CrashReportCallables.registerCrashCallable("ModLauncher", FMLLoader::getLauncherInfo);
|
CrashReportCallables.registerCrashCallable("ModLauncher", FMLLoader::getLauncherInfo);
|
||||||
CrashReportCallables.registerCrashCallable("ModLauncher launch target", FMLLoader::launcherHandlerName);
|
CrashReportCallables.registerCrashCallable("ModLauncher launch target", FMLLoader::launcherHandlerName);
|
||||||
CrashReportCallables.registerCrashCallable("ModLauncher naming", FMLLoader::getNaming);
|
CrashReportCallables.registerCrashCallable("ModLauncher naming", FMLLoader::getNaming);
|
||||||
CrashReportCallables.registerCrashCallable("ModLauncher services", this::computeModLauncherServiceList);
|
CrashReportCallables.registerCrashCallable("ModLauncher services", ModLoader::computeModLauncherServiceList);
|
||||||
CrashReportCallables.registerCrashCallable("FML Language Providers", this::computeLanguageList);
|
CrashReportCallables.registerCrashCallable("FML Language Providers", ModLoader::computeLanguageList);
|
||||||
}
|
}
|
||||||
|
|
||||||
private String computeLanguageList() {
|
private static String computeLanguageList() {
|
||||||
return "\n"+FMLLoader.getLanguageLoadingProvider().applyForEach(lp->lp.name() +"@"+ lp.getClass().getPackage().getImplementationVersion()).collect(Collectors.joining("\n\t\t", "\t\t", ""));
|
return "\n" + FMLLoader.getLanguageLoadingProvider()
|
||||||
|
.applyForEach(lp -> lp.name() + "@" + lp.getClass().getPackage().getImplementationVersion())
|
||||||
|
.collect(Collectors.joining("\n\t\t", "\t\t", ""));
|
||||||
}
|
}
|
||||||
|
|
||||||
private 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")+
|
||||||
@@ -125,9 +132,13 @@ public class ModLoader
|
|||||||
collect(Collectors.joining("\n\t\t","\t\t",""));
|
collect(Collectors.joining("\n\t\t","\t\t",""));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static ModLoader get()
|
public static ModLoader get() {
|
||||||
{
|
return LazyInit.INSTANCE;
|
||||||
return INSTANCE == null ? INSTANCE = new ModLoader() : INSTANCE;
|
}
|
||||||
|
|
||||||
|
private static final class LazyInit {
|
||||||
|
private static final ModLoader INSTANCE = new ModLoader();
|
||||||
|
private LazyInit() {}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -144,7 +155,7 @@ public class ModLoader
|
|||||||
final ModList modList = ModList.of(loadingModList.getModFiles().stream().map(ModFileInfo::getFile).toList(),
|
final ModList modList = ModList.of(loadingModList.getModFiles().stream().map(ModFileInfo::getFile).toList(),
|
||||||
loadingModList.getMods());
|
loadingModList.getMods());
|
||||||
if (!this.loadingExceptions.isEmpty()) {
|
if (!this.loadingExceptions.isEmpty()) {
|
||||||
LOGGER.fatal(CORE, "Error during pre-loading phase", loadingExceptions.get(0));
|
LOGGER.fatal(CORE, "Error during pre-loading phase", loadingExceptions.getFirst());
|
||||||
statusConsumer.ifPresent(c->c.accept("ERROR DURING MOD LOADING"));
|
statusConsumer.ifPresent(c->c.accept("ERROR DURING MOD LOADING"));
|
||||||
modList.setLoadedMods(Collections.emptyList());
|
modList.setLoadedMods(Collections.emptyList());
|
||||||
loadingStateValid = false;
|
loadingStateValid = false;
|
||||||
@@ -152,7 +163,7 @@ public class ModLoader
|
|||||||
}
|
}
|
||||||
List<? extends ForgeFeature.Bound> failedBounds = loadingModList.getMods().stream()
|
List<? extends ForgeFeature.Bound> failedBounds = loadingModList.getMods().stream()
|
||||||
.map(ModInfo::getForgeFeatures)
|
.map(ModInfo::getForgeFeatures)
|
||||||
.flatMap(Collection::stream)
|
.flatMap(List::stream)
|
||||||
.filter(bound -> !ForgeFeature.testFeature(FMLEnvironment.dist, bound))
|
.filter(bound -> !ForgeFeature.testFeature(FMLEnvironment.dist, bound))
|
||||||
.toList();
|
.toList();
|
||||||
|
|
||||||
@@ -169,10 +180,10 @@ public class ModLoader
|
|||||||
final List<ModContainer> modContainers = loadingModList.getModFiles().stream()
|
final List<ModContainer> modContainers = loadingModList.getModFiles().stream()
|
||||||
.map(ModFileInfo::getFile)
|
.map(ModFileInfo::getFile)
|
||||||
.map(this::buildMods)
|
.map(this::buildMods)
|
||||||
.<ModContainer>mapMulti(Iterable::forEach)
|
.flatMap(List::stream)
|
||||||
.toList();
|
.toList();
|
||||||
if (!loadingExceptions.isEmpty()) {
|
if (!loadingExceptions.isEmpty()) {
|
||||||
LOGGER.fatal(CORE, "Failed to initialize mod containers", loadingExceptions.get(0));
|
LOGGER.fatal(CORE, "Failed to initialize mod containers", loadingExceptions.getFirst());
|
||||||
statusConsumer.ifPresent(c->c.accept("ERROR DURING MOD LOADING"));
|
statusConsumer.ifPresent(c->c.accept("ERROR DURING MOD LOADING"));
|
||||||
modList.setLoadedMods(Collections.emptyList());
|
modList.setLoadedMods(Collections.emptyList());
|
||||||
loadingStateValid = false;
|
loadingStateValid = false;
|
||||||
@@ -181,22 +192,28 @@ public class ModLoader
|
|||||||
modList.setLoadedMods(modContainers);
|
modList.setLoadedMods(modContainers);
|
||||||
this.modList = modList;
|
this.modList = modList;
|
||||||
var stateList = stateManager.getStates(ModLoadingPhase.GATHER);
|
var stateList = stateManager.getStates(ModLoadingPhase.GATHER);
|
||||||
var progress = StartupMessageManager.addProgressBar("Mod Gather", stateList.stream().mapToInt(mls -> mls.size().applyAsInt(modList)).sum());
|
var progress = StartupMessageManager.addProgressBar("Mod Gather", stateList.stream().mapToInt(mls -> mls.size().applyAsInt(this.modList)).sum());
|
||||||
stateList.forEach(mls->dispatchAndHandleError(mls, syncExecutor, parallelExecutor, periodicTask, progress));
|
for (IModLoadingState mls : stateList) {
|
||||||
|
dispatchAndHandleError(mls, syncExecutor, parallelExecutor, periodicTask, progress);
|
||||||
|
}
|
||||||
progress.complete();
|
progress.complete();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void loadMods(final ModWorkManager.DrivenExecutor syncExecutor, final Executor parallelExecutor, final Runnable periodicTask) {
|
public void loadMods(final ModWorkManager.DrivenExecutor syncExecutor, final Executor parallelExecutor, final Runnable periodicTask) {
|
||||||
var stateList = stateManager.getStates(ModLoadingPhase.LOAD);
|
var stateList = stateManager.getStates(ModLoadingPhase.LOAD);
|
||||||
var progress = StartupMessageManager.addProgressBar("Mod Loading", stateList.stream().mapToInt(mls -> mls.size().applyAsInt(modList)).sum());
|
var progress = StartupMessageManager.addProgressBar("Mod Loading", stateList.stream().mapToInt(mls -> mls.size().applyAsInt(modList)).sum());
|
||||||
stateList.forEach(mls->dispatchAndHandleError(mls, syncExecutor, parallelExecutor, periodicTask, progress));
|
for (IModLoadingState mls : stateList) {
|
||||||
|
dispatchAndHandleError(mls, syncExecutor, parallelExecutor, periodicTask, progress);
|
||||||
|
}
|
||||||
progress.complete();
|
progress.complete();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void finishMods(final ModWorkManager.DrivenExecutor syncExecutor, final Executor parallelExecutor, final Runnable periodicTask) {
|
public void finishMods(final ModWorkManager.DrivenExecutor syncExecutor, final Executor parallelExecutor, final Runnable periodicTask) {
|
||||||
var stateList = stateManager.getStates(ModLoadingPhase.COMPLETE);
|
var stateList = stateManager.getStates(ModLoadingPhase.COMPLETE);
|
||||||
var progress = StartupMessageManager.addProgressBar("Mod Complete", stateList.stream().mapToInt(mls -> mls.size().applyAsInt(modList)).sum());
|
var progress = StartupMessageManager.addProgressBar("Mod Complete", stateList.stream().mapToInt(mls -> mls.size().applyAsInt(modList)).sum());
|
||||||
stateList.forEach(mls->dispatchAndHandleError(mls, syncExecutor, parallelExecutor, periodicTask, progress));
|
for (IModLoadingState mls : stateList) {
|
||||||
|
dispatchAndHandleError(mls, syncExecutor, parallelExecutor, periodicTask, progress);
|
||||||
|
}
|
||||||
statusConsumer.ifPresent(c->c.accept(String.format("Mod loading complete - %d mods loaded", this.modList.size())));
|
statusConsumer.ifPresent(c->c.accept(String.format("Mod loading complete - %d mods loaded", this.modList.size())));
|
||||||
progress.complete();
|
progress.complete();
|
||||||
}
|
}
|
||||||
@@ -206,10 +223,15 @@ public class ModLoader
|
|||||||
LOGGER.error("Cowardly refusing to process mod state change request from {}", state);
|
LOGGER.error("Cowardly refusing to process mod state change request from {}", state);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
progressBar.label(progressBar.name()+ " working");
|
progressBar.label(progressBar.name() + " working");
|
||||||
syncExecutor.drive(ticker);
|
syncExecutor.drive(ticker);
|
||||||
state.inlineRunnable().ifPresent(a->this.handleInlineTransition(a, state, syncExecutor, ticker));
|
|
||||||
state.buildTransition(syncExecutor, parallelExecutor, progressBar).ifPresent(t->waitForTransition(state, syncExecutor, ticker, t));
|
var inlineRunnable = state.inlineRunnable().orElse(null);
|
||||||
|
if (inlineRunnable != null) handleInlineTransition(inlineRunnable, state, syncExecutor, ticker);
|
||||||
|
|
||||||
|
var transition = state.buildTransition(syncExecutor, parallelExecutor, progressBar).orElse(null);
|
||||||
|
if (transition != null) waitForTransition(state, syncExecutor, ticker, transition);
|
||||||
|
|
||||||
completedStates.add(state);
|
completedStates.add(state);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -286,9 +308,12 @@ public class ModLoader
|
|||||||
try {
|
try {
|
||||||
final String modId = idToProviderEntry.getKey();
|
final String modId = idToProviderEntry.getKey();
|
||||||
final IModLanguageProvider.IModLanguageLoader languageLoader = idToProviderEntry.getValue();
|
final IModLanguageProvider.IModLanguageLoader languageLoader = idToProviderEntry.getValue();
|
||||||
IModInfo info = Optional.ofNullable(modInfoMap.get(modId)).
|
|
||||||
// throw a missing metadata error if there is no matching modid in the modInfoMap from the mods.toml file
|
IModInfo info = modInfoMap.get(modId);
|
||||||
orElseThrow(()->new ModLoadingException(null, ModLoadingStage.CONSTRUCT, "fml.modloading.missingmetadata", null, modId));
|
// throw a missing metadata error if there is no matching modid in the modInfoMap from the mods.toml file
|
||||||
|
if (info == null)
|
||||||
|
throw new ModLoadingException(null, ModLoadingStage.CONSTRUCT, "fml.modloading.missingmetadata", null, modId);
|
||||||
|
|
||||||
return languageLoader.loadMod(info, modFile.getScanResult(), FMLLoader.getGameLayer());
|
return languageLoader.loadMod(info, modFile.getScanResult(), FMLLoader.getGameLayer());
|
||||||
} catch (ModLoadingException mle) {
|
} catch (ModLoadingException mle) {
|
||||||
// exceptions are caught and added to the error list for later handling
|
// exceptions are caught and added to the error list for later handling
|
||||||
@@ -303,7 +328,7 @@ public class ModLoader
|
|||||||
* and don't want to cause extraneous crashes due to trying to do things that aren't possible in a "broken load"
|
* and don't want to cause extraneous crashes due to trying to do things that aren't possible in a "broken load"
|
||||||
*/
|
*/
|
||||||
public static boolean isLoadingStateValid() {
|
public static boolean isLoadingStateValid() {
|
||||||
return get().loadingStateValid;
|
return loadingStateValid;
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean hasCompletedState(final String stateName) {
|
public boolean hasCompletedState(final String stateName) {
|
||||||
|
|||||||
@@ -19,28 +19,51 @@ public class ModLoadingContext
|
|||||||
{
|
{
|
||||||
private static final Logger LOGGER = LogUtils.getLogger();
|
private static final Logger LOGGER = LogUtils.getLogger();
|
||||||
private static final ThreadLocal<ModLoadingContext> context = ThreadLocal.withInitial(ModLoadingContext::new);
|
private static final ThreadLocal<ModLoadingContext> context = ThreadLocal.withInitial(ModLoadingContext::new);
|
||||||
|
private ModContainer activeContainer;
|
||||||
private Object languageExtension;
|
private Object languageExtension;
|
||||||
private ModLoadingStage stage;
|
private ModLoadingStage stage;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @deprecated Use the context provided by your language loader in your mod's constructor
|
||||||
|
*/
|
||||||
|
@Deprecated(forRemoval = true, since="1.21.1")
|
||||||
public static ModLoadingContext get() {
|
public static ModLoadingContext get() {
|
||||||
return context.get();
|
return context.get();
|
||||||
}
|
}
|
||||||
|
|
||||||
private ModContainer activeContainer;
|
/**
|
||||||
|
* @deprecated Going to be moved to ForgeHooks for Internal use.
|
||||||
|
*/
|
||||||
|
@Deprecated(forRemoval = true, since="1.21.1")
|
||||||
public void setActiveContainer(final ModContainer container) {
|
public void setActiveContainer(final ModContainer container) {
|
||||||
this.activeContainer = container;
|
this.activeContainer = container;
|
||||||
this.languageExtension = container == null ? null : container.contextExtension.get();
|
this.languageExtension = container == null ? null : container.contextExtension.get();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Going to be moved to ForgeHooks for Internal use.
|
||||||
|
* @deprecated Override/Use {@link ModLoadingContext#getContainer()}
|
||||||
|
*/
|
||||||
|
@Deprecated(forRemoval = true, since="1.21.1")
|
||||||
public ModContainer getActiveContainer() {
|
public ModContainer getActiveContainer() {
|
||||||
return activeContainer == null ? ModList.get().getModContainerById("minecraft").orElseThrow(()->new RuntimeException("Where is minecraft???!")) : activeContainer;
|
return activeContainer == null ? ModList.get().getModContainerById("minecraft").orElseThrow(()->new RuntimeException("Where is minecraft???!")) : activeContainer;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @deprecated Going to be moved to ForgeHooks for Internal use.
|
||||||
|
*/
|
||||||
|
@Deprecated(forRemoval = true, since="1.21.1")
|
||||||
public String getActiveNamespace() {
|
public String getActiveNamespace() {
|
||||||
return activeContainer == null ? "minecraft" : activeContainer.getNamespace();
|
return activeContainer == null ? "minecraft" : activeContainer.getNamespace();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return {@link ModLoadingContext#getActiveContainer()} by default.
|
||||||
|
*/
|
||||||
|
public ModContainer getContainer() {
|
||||||
|
return getActiveContainer();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register an {@link IExtensionPoint} with the mod container.
|
* Register an {@link IExtensionPoint} with the mod container.
|
||||||
* @param point The extension point to register
|
* @param point The extension point to register
|
||||||
@@ -48,7 +71,7 @@ public class ModLoadingContext
|
|||||||
* @param <T> The type signature of the extension operator
|
* @param <T> The type signature of the extension operator
|
||||||
*/
|
*/
|
||||||
public <T extends Record & IExtensionPoint<T>> void registerExtensionPoint(Class<? extends IExtensionPoint<T>> point, Supplier<T> extension) {
|
public <T extends Record & IExtensionPoint<T>> void registerExtensionPoint(Class<? extends IExtensionPoint<T>> point, Supplier<T> extension) {
|
||||||
getActiveContainer().registerExtensionPoint(point, extension);
|
getContainer().registerExtensionPoint(point, extension);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -57,7 +80,7 @@ public class ModLoadingContext
|
|||||||
* @param displayTest The {@link IExtensionPoint.DisplayTest} to register
|
* @param displayTest The {@link IExtensionPoint.DisplayTest} to register
|
||||||
*/
|
*/
|
||||||
public void registerDisplayTest(IExtensionPoint.DisplayTest displayTest) {
|
public void registerDisplayTest(IExtensionPoint.DisplayTest displayTest) {
|
||||||
getActiveContainer().registerDisplayTest(() -> displayTest);
|
getContainer().registerDisplayTest(() -> displayTest);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -66,7 +89,7 @@ public class ModLoadingContext
|
|||||||
* @param displayTest The {@link Supplier<IExtensionPoint.DisplayTest>} to register
|
* @param displayTest The {@link Supplier<IExtensionPoint.DisplayTest>} to register
|
||||||
*/
|
*/
|
||||||
public void registerDisplayTest(Supplier<IExtensionPoint.DisplayTest> displayTest) {
|
public void registerDisplayTest(Supplier<IExtensionPoint.DisplayTest> displayTest) {
|
||||||
getActiveContainer().registerDisplayTest(displayTest);
|
getContainer().registerDisplayTest(displayTest);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -76,7 +99,7 @@ public class ModLoadingContext
|
|||||||
* @see IExtensionPoint.DisplayTest#DisplayTest(String, BiPredicate)
|
* @see IExtensionPoint.DisplayTest#DisplayTest(String, BiPredicate)
|
||||||
*/
|
*/
|
||||||
public void registerDisplayTest(String version, BiPredicate<String, Boolean> remoteVersionTest) {
|
public void registerDisplayTest(String version, BiPredicate<String, Boolean> remoteVersionTest) {
|
||||||
getActiveContainer().registerDisplayTest(new IExtensionPoint.DisplayTest(version, remoteVersionTest));
|
getContainer().registerDisplayTest(new IExtensionPoint.DisplayTest(version, remoteVersionTest));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -86,29 +109,29 @@ public class ModLoadingContext
|
|||||||
* @see IExtensionPoint.DisplayTest#DisplayTest(Supplier, BiPredicate)
|
* @see IExtensionPoint.DisplayTest#DisplayTest(Supplier, BiPredicate)
|
||||||
*/
|
*/
|
||||||
public void registerDisplayTest(Supplier<String> suppliedVersion, BiPredicate<String, Boolean> remoteVersionTest) {
|
public void registerDisplayTest(Supplier<String> suppliedVersion, BiPredicate<String, Boolean> remoteVersionTest) {
|
||||||
getActiveContainer().registerDisplayTest(new IExtensionPoint.DisplayTest(suppliedVersion, remoteVersionTest));
|
getContainer().registerDisplayTest(new IExtensionPoint.DisplayTest(suppliedVersion, remoteVersionTest));
|
||||||
}
|
}
|
||||||
|
|
||||||
public void registerConfig(ModConfig.Type type, IConfigSpec<?> spec) {
|
public void registerConfig(ModConfig.Type type, IConfigSpec<?> spec) {
|
||||||
if (spec.isEmpty())
|
if (spec.isEmpty())
|
||||||
{
|
{
|
||||||
// This handles the case where a mod tries to register a config, without any options configured inside it.
|
// This handles the case where a mod tries to register a config, without any options configured inside it.
|
||||||
LOGGER.debug("Attempted to register an empty config for type {} on mod {}", type, getActiveContainer().getModId());
|
LOGGER.debug("Attempted to register an empty config for type {} on mod {}", type, getContainer().getModId());
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
getActiveContainer().addConfig(new ModConfig(type, spec, getActiveContainer()));
|
getContainer().addConfig(new ModConfig(type, spec, getContainer()));
|
||||||
}
|
}
|
||||||
|
|
||||||
public void registerConfig(ModConfig.Type type, IConfigSpec<?> spec, String fileName) {
|
public void registerConfig(ModConfig.Type type, IConfigSpec<?> spec, String fileName) {
|
||||||
if (spec.isEmpty())
|
if (spec.isEmpty())
|
||||||
{
|
{
|
||||||
// This handles the case where a mod tries to register a config, without any options configured inside it.
|
// This handles the case where a mod tries to register a config, without any options configured inside it.
|
||||||
LOGGER.debug("Attempted to register an empty config for type {} on mod {} using file name {}", type, getActiveContainer().getModId(), fileName);
|
LOGGER.debug("Attempted to register an empty config for type {} on mod {} using file name {}", type, getContainer().getModId(), fileName);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
getActiveContainer().addConfig(new ModConfig(type, spec, getActiveContainer(), fileName));
|
getContainer().addConfig(new ModConfig(type, spec, getContainer(), fileName));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -39,7 +39,10 @@ public record ModLoadingState(String name, String previous,
|
|||||||
final ProgressMeter progressBar,
|
final ProgressMeter progressBar,
|
||||||
final Function<Executor, CompletableFuture<Void>> preSyncTask,
|
final Function<Executor, CompletableFuture<Void>> preSyncTask,
|
||||||
final Function<Executor, CompletableFuture<Void>> postSyncTask) {
|
final Function<Executor, CompletableFuture<Void>> postSyncTask) {
|
||||||
return transition.map(t -> t.build(name, syncExecutor, parallelExecutor, progressBar, preSyncTask, postSyncTask));
|
var transition = this.transition.orElse(null);
|
||||||
|
return transition == null
|
||||||
|
? Optional.empty()
|
||||||
|
: Optional.ofNullable(transition.build(name, syncExecutor, parallelExecutor, progressBar, preSyncTask, postSyncTask));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -16,15 +16,13 @@ import java.util.stream.Collectors;
|
|||||||
|
|
||||||
@SuppressWarnings("UnstableApiUsage")
|
@SuppressWarnings("UnstableApiUsage")
|
||||||
public class ModStateManager {
|
public class ModStateManager {
|
||||||
static ModStateManager INSTANCE;
|
|
||||||
private final EnumMap<ModLoadingPhase, List<IModLoadingState>> stateMap;
|
private final EnumMap<ModLoadingPhase, List<IModLoadingState>> stateMap;
|
||||||
|
|
||||||
public ModStateManager() {
|
public ModStateManager() {
|
||||||
INSTANCE = this;
|
|
||||||
final var sp = ServiceLoader.load(FMLLoader.getGameLayer(), IModStateProvider.class);
|
final var sp = ServiceLoader.load(FMLLoader.getGameLayer(), IModStateProvider.class);
|
||||||
this.stateMap = ServiceLoaderUtils.streamWithErrorHandling(sp, sce->{})
|
this.stateMap = ServiceLoaderUtils.streamWithErrorHandling(sp, sce->{})
|
||||||
.map(IModStateProvider::getAllStates)
|
.map(IModStateProvider::getAllStates)
|
||||||
.<IModLoadingState>mapMulti(Iterable::forEach)
|
.flatMap(List::stream)
|
||||||
.collect(Collectors.groupingBy(IModLoadingState::phase, ()->new EnumMap<>(ModLoadingPhase.class), Collectors.toUnmodifiableList()));
|
.collect(Collectors.groupingBy(IModLoadingState::phase, ()->new EnumMap<>(ModLoadingPhase.class), Collectors.toUnmodifiableList()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -36,14 +34,16 @@ public class ModStateManager {
|
|||||||
var dummy = ModLoadingState.empty("", "", phase);
|
var dummy = ModLoadingState.empty("", "", phase);
|
||||||
nodes.forEach(graph::addNode);
|
nodes.forEach(graph::addNode);
|
||||||
graph.addNode(dummy);
|
graph.addNode(dummy);
|
||||||
nodes.forEach(n->graph.putEdge(lookup.getOrDefault(n.previous(), dummy), n));
|
for (IModLoadingState node : nodes) {
|
||||||
|
graph.putEdge(lookup.getOrDefault(node.previous(), dummy), node);
|
||||||
|
}
|
||||||
return TopologicalSort.topologicalSort(graph, Comparator.comparingInt(nodes::indexOf)).stream().filter(st->st!=dummy).toList();
|
return TopologicalSort.topologicalSort(graph, Comparator.comparingInt(nodes::indexOf)).stream().filter(st->st!=dummy).toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
public IModLoadingState findState(final String stateName) {
|
public IModLoadingState findState(final String stateName) {
|
||||||
return stateMap.values()
|
return stateMap.values()
|
||||||
.stream()
|
.stream()
|
||||||
.flatMap(Collection::stream)
|
.flatMap(List::stream)
|
||||||
.filter(mls -> mls.name().equals(stateName))
|
.filter(mls -> mls.name().equals(stateName))
|
||||||
.findFirst()
|
.findFirst()
|
||||||
.orElseThrow(() -> new IllegalArgumentException("Unknown IModLoadingState: " + stateName));
|
.orElseThrow(() -> new IllegalArgumentException("Unknown IModLoadingState: " + stateName));
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import static net.minecraftforge.fml.Logging.LOADING;
|
|||||||
public class ModWorkManager {
|
public class ModWorkManager {
|
||||||
private static final Logger LOGGER = LogManager.getLogger();
|
private static final Logger LOGGER = LogManager.getLogger();
|
||||||
private static final long PARK_TIME = TimeUnit.MILLISECONDS.toNanos(1);
|
private static final long PARK_TIME = TimeUnit.MILLISECONDS.toNanos(1);
|
||||||
|
|
||||||
public interface DrivenExecutor extends Executor {
|
public interface DrivenExecutor extends Executor {
|
||||||
boolean selfDriven();
|
boolean selfDriven();
|
||||||
boolean driveOne();
|
boolean driveOne();
|
||||||
@@ -33,8 +34,11 @@ public class ModWorkManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
private static class SyncExecutor implements DrivenExecutor {
|
|
||||||
private ConcurrentLinkedDeque<Runnable> tasks = new ConcurrentLinkedDeque<>();
|
private record SyncExecutor(ConcurrentLinkedDeque<Runnable> tasks) implements DrivenExecutor {
|
||||||
|
public SyncExecutor() {
|
||||||
|
this(new ConcurrentLinkedDeque<>());
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean driveOne() {
|
public boolean driveOne() {
|
||||||
@@ -56,13 +60,7 @@ public class ModWorkManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static class WrappingExecutor implements DrivenExecutor {
|
private record WrappingExecutor(Executor wrapped) implements DrivenExecutor {
|
||||||
private final Executor wrapped;
|
|
||||||
|
|
||||||
public WrappingExecutor(final Executor executor) {
|
|
||||||
this.wrapped = executor;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean selfDriven() {
|
public boolean selfDriven() {
|
||||||
return true;
|
return true;
|
||||||
@@ -79,11 +77,9 @@ public class ModWorkManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static SyncExecutor syncExecutor;
|
private static final SyncExecutor syncExecutor = new SyncExecutor();
|
||||||
|
|
||||||
public static DrivenExecutor syncExecutor() {
|
public static DrivenExecutor syncExecutor() {
|
||||||
if (syncExecutor == null)
|
|
||||||
syncExecutor = new SyncExecutor();
|
|
||||||
return syncExecutor;
|
return syncExecutor;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -91,14 +87,8 @@ public class ModWorkManager {
|
|||||||
return new WrappingExecutor(executor);
|
return new WrappingExecutor(executor);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static ForkJoinPool parallelThreadPool;
|
|
||||||
public static Executor parallelExecutor() {
|
public static Executor parallelExecutor() {
|
||||||
if (parallelThreadPool == null) {
|
return LazyInit.PARALLEL_EXECUTOR;
|
||||||
final int loadingThreadCount = FMLConfig.getIntConfigValue(FMLConfig.ConfigValue.MAX_THREADS);
|
|
||||||
LOGGER.debug(LOADING, "Using {} threads for parallel mod-loading", loadingThreadCount);
|
|
||||||
parallelThreadPool = new ForkJoinPool(loadingThreadCount, ModWorkManager::newForkJoinWorkerThread, null, false);
|
|
||||||
}
|
|
||||||
return parallelThreadPool;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static ForkJoinWorkerThread newForkJoinWorkerThread(ForkJoinPool pool) {
|
private static ForkJoinWorkerThread newForkJoinWorkerThread(ForkJoinPool pool) {
|
||||||
@@ -109,4 +99,14 @@ public class ModWorkManager {
|
|||||||
return thread;
|
return thread;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static final class LazyInit {
|
||||||
|
private LazyInit() {}
|
||||||
|
private static final ForkJoinPool PARALLEL_EXECUTOR;
|
||||||
|
|
||||||
|
static {
|
||||||
|
final int loadingThreadCount = FMLConfig.getIntConfigValue(FMLConfig.ConfigValue.MAX_THREADS);
|
||||||
|
LOGGER.debug(LOADING, "Using {} threads for parallel mod-loading", loadingThreadCount);
|
||||||
|
PARALLEL_EXECUTOR = new ForkJoinPool(loadingThreadCount, ModWorkManager::newForkJoinWorkerThread, null, false);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -23,7 +23,7 @@ public final class OptionalMod<T>
|
|||||||
return new OptionalMod<>(modId);
|
return new OptionalMod<>(modId);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static OptionalMod<?> EMPTY = new OptionalMod<>(true);
|
private static final OptionalMod<?> EMPTY = new OptionalMod<>(true);
|
||||||
private static <T> OptionalMod<T> empty() {
|
private static <T> OptionalMod<T> empty() {
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
OptionalMod<T> t = (OptionalMod<T>) EMPTY;
|
OptionalMod<T> t = (OptionalMod<T>) EMPTY;
|
||||||
@@ -213,8 +213,8 @@ public final class OptionalMod<T>
|
|||||||
public boolean equals(Object obj)
|
public boolean equals(Object obj)
|
||||||
{
|
{
|
||||||
if (this == obj) return true;
|
if (this == obj) return true;
|
||||||
if (obj instanceof OptionalMod) {
|
if (obj instanceof OptionalMod<?> optionalMod) {
|
||||||
return Objects.equals(((OptionalMod)obj).modId, modId);
|
return Objects.equals(optionalMod.modId, modId);
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -48,8 +48,8 @@ public class VersionChecker {
|
|||||||
BETA(),
|
BETA(),
|
||||||
BETA_OUTDATED(6, true, true);
|
BETA_OUTDATED(6, true, true);
|
||||||
|
|
||||||
final int sheetOffset;
|
private final int sheetOffset;
|
||||||
final boolean draw, animated;
|
private final boolean draw, animated;
|
||||||
|
|
||||||
Status() {
|
Status() {
|
||||||
this(0, false, false);
|
this(0, false, false);
|
||||||
@@ -72,6 +72,10 @@ public class VersionChecker {
|
|||||||
public boolean isAnimated() {
|
public boolean isAnimated() {
|
||||||
return animated;
|
return animated;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public boolean isOutdated() {
|
||||||
|
return this == OUTDATED || this == BETA_OUTDATED;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public record CheckResult(VersionChecker.Status status, ComparableVersion target, Map<ComparableVersion, String> changes, String url) {}
|
public record CheckResult(VersionChecker.Status status, ComparableVersion target, Map<ComparableVersion, String> changes, String url) {}
|
||||||
@@ -211,7 +215,7 @@ public class VersionChecker {
|
|||||||
LOGGER.warn("Failed to process update information", e);
|
LOGGER.warn("Failed to process update information", e);
|
||||||
status = FAILED;
|
status = FAILED;
|
||||||
}
|
}
|
||||||
results.put(mod, new CheckResult(status, target, changes, display_url));
|
RESULTS.put(mod, new CheckResult(status, target, changes, display_url));
|
||||||
}
|
}
|
||||||
}.start();
|
}.start();
|
||||||
}
|
}
|
||||||
@@ -226,10 +230,10 @@ public class VersionChecker {
|
|||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static Map<IModInfo, CheckResult> results = new ConcurrentHashMap<>();
|
private static final Map<IModInfo, CheckResult> RESULTS = new ConcurrentHashMap<>();
|
||||||
private static final CheckResult PENDING_CHECK = new CheckResult(PENDING, null, null, null);
|
private static final CheckResult PENDING_CHECK = new CheckResult(PENDING, null, null, null);
|
||||||
|
|
||||||
public static CheckResult getResult(IModInfo mod) {
|
public static CheckResult getResult(IModInfo mod) {
|
||||||
return results.getOrDefault(mod, PENDING_CHECK);
|
return RESULTS.getOrDefault(mod, PENDING_CHECK);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -14,6 +14,7 @@ import com.mojang.logging.LogUtils;
|
|||||||
import net.minecraftforge.fml.loading.FMLConfig;
|
import net.minecraftforge.fml.loading.FMLConfig;
|
||||||
import net.minecraftforge.fml.loading.FMLPaths;
|
import net.minecraftforge.fml.loading.FMLPaths;
|
||||||
import org.apache.commons.io.FilenameUtils;
|
import org.apache.commons.io.FilenameUtils;
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
@@ -25,9 +26,66 @@ import static net.minecraftforge.fml.config.ConfigTracker.CONFIG;
|
|||||||
|
|
||||||
public class ConfigFileTypeHandler {
|
public class ConfigFileTypeHandler {
|
||||||
private static final Logger LOGGER = LogUtils.getLogger();
|
private static final Logger LOGGER = LogUtils.getLogger();
|
||||||
static ConfigFileTypeHandler TOML = new ConfigFileTypeHandler();
|
|
||||||
private static final Path defaultConfigPath = FMLPaths.GAMEDIR.get().resolve(FMLConfig.getConfigValue(FMLConfig.ConfigValue.DEFAULT_CONFIG_PATH));
|
private static final Path defaultConfigPath = FMLPaths.GAMEDIR.get().resolve(FMLConfig.getConfigValue(FMLConfig.ConfigValue.DEFAULT_CONFIG_PATH));
|
||||||
|
|
||||||
|
private static final ConfigFileTypeHandler CLIENT = new ConfigFileTypeHandler(ModConfig.Type.CLIENT);
|
||||||
|
private static final ConfigFileTypeHandler COMMON = new ConfigFileTypeHandler(ModConfig.Type.COMMON);
|
||||||
|
private static final ConfigFileTypeHandler SERVER = new ConfigFileTypeHandler(ModConfig.Type.SERVER);
|
||||||
|
|
||||||
|
private final @Nullable ModConfig.Type type;
|
||||||
|
private @Nullable FileWatcher watcher;
|
||||||
|
|
||||||
|
// exists for bin compat
|
||||||
|
public ConfigFileTypeHandler() {
|
||||||
|
this(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private ConfigFileTypeHandler(@Nullable ModConfig.Type type) {
|
||||||
|
this.type = type;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the handler for the given {@link ModConfig.Type}.
|
||||||
|
*
|
||||||
|
* @param type The type to get the handler for
|
||||||
|
* @return The handler
|
||||||
|
*/
|
||||||
|
static ConfigFileTypeHandler get(ModConfig.Type type) {
|
||||||
|
return switch (type) {
|
||||||
|
case CLIENT -> CLIENT;
|
||||||
|
case COMMON -> COMMON;
|
||||||
|
case SERVER -> SERVER;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the {@link FileWatcher} for this handler, creating it if it doesn't exist and/or has been stopped.
|
||||||
|
*
|
||||||
|
* @return The watcher
|
||||||
|
*
|
||||||
|
* @apiNote This is package-private so modders can't just call {@link FileWatcher#stop()} and fuck up everything.
|
||||||
|
*/
|
||||||
|
FileWatcher getWatcher() {
|
||||||
|
if (this.watcher == null) {
|
||||||
|
LOGGER.debug(CONFIG, "Starting watcher for handler: {}", this);
|
||||||
|
this.watcher = new FileWatcher();
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.watcher;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stops the {@link FileWatcher} for this handler, and sets it to null afterward. Use this instead of
|
||||||
|
* {@link FileWatcher#stop()}.
|
||||||
|
*/
|
||||||
|
void stopWatcher() {
|
||||||
|
if (this.watcher == null) return;
|
||||||
|
|
||||||
|
LOGGER.debug(CONFIG, "Stopping watcher for hander: {}", this);
|
||||||
|
this.watcher.stop();
|
||||||
|
this.watcher = null;
|
||||||
|
}
|
||||||
|
|
||||||
public Function<ModConfig, CommentedFileConfig> reader(Path configBasePath) {
|
public Function<ModConfig, CommentedFileConfig> reader(Path configBasePath) {
|
||||||
return (c) -> {
|
return (c) -> {
|
||||||
final Path configPath = configBasePath.resolve(c.getFileName());
|
final Path configPath = configBasePath.resolve(c.getFileName());
|
||||||
@@ -37,7 +95,7 @@ public class ConfigFileTypeHandler {
|
|||||||
onFileNotFound((newfile, configFormat)-> setupConfigFile(c, newfile, configFormat)).
|
onFileNotFound((newfile, configFormat)-> setupConfigFile(c, newfile, configFormat)).
|
||||||
writingMode(WritingMode.REPLACE).
|
writingMode(WritingMode.REPLACE).
|
||||||
build();
|
build();
|
||||||
LOGGER.debug(CONFIG, "Built TOML config for {}", configPath.toString());
|
LOGGER.debug(CONFIG, "Built TOML config for {}", configPath);
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
configData.load();
|
configData.load();
|
||||||
@@ -46,13 +104,9 @@ public class ConfigFileTypeHandler {
|
|||||||
{
|
{
|
||||||
throw new ConfigLoadingException(c, ex);
|
throw new ConfigLoadingException(c, ex);
|
||||||
}
|
}
|
||||||
LOGGER.debug(CONFIG, "Loaded TOML config file {}", configPath.toString());
|
LOGGER.debug(CONFIG, "Loaded TOML config file {}", configPath);
|
||||||
try {
|
this.getWatcher().addWatch(configPath, new ConfigWatcher(c, configData, Thread.currentThread().getContextClassLoader()));
|
||||||
FileWatcher.defaultInstance().addWatch(configPath, new ConfigWatcher(c, configData, Thread.currentThread().getContextClassLoader()));
|
LOGGER.debug(CONFIG, "Watching TOML config file {} for changes", configPath);
|
||||||
LOGGER.debug(CONFIG, "Watching TOML config file {} for changes", configPath.toString());
|
|
||||||
} catch (IOException e) {
|
|
||||||
throw new RuntimeException("Couldn't watch config file", e);
|
|
||||||
}
|
|
||||||
return configData;
|
return configData;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -60,14 +114,16 @@ public class ConfigFileTypeHandler {
|
|||||||
public void unload(Path configBasePath, ModConfig config) {
|
public void unload(Path configBasePath, ModConfig config) {
|
||||||
Path configPath = configBasePath.resolve(config.getFileName());
|
Path configPath = configBasePath.resolve(config.getFileName());
|
||||||
try {
|
try {
|
||||||
FileWatcher.defaultInstance().removeWatch(configBasePath.resolve(config.getFileName()));
|
this.getWatcher().removeWatch(configPath);
|
||||||
} catch (RuntimeException e) {
|
} catch (RuntimeException e) {
|
||||||
LOGGER.error("Failed to remove config {} from tracker!", configPath.toString(), e);
|
LOGGER.error("Failed to remove config {} from tracker!", configPath, e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean setupConfigFile(final ModConfig modConfig, final Path file, final ConfigFormat<?> conf) throws IOException {
|
private static boolean setupConfigFile(final ModConfig modConfig, final Path file, final ConfigFormat<?> conf) throws IOException {
|
||||||
Files.createDirectories(file.getParent());
|
if (!Files.isDirectory(file.getParent())) {
|
||||||
|
Files.createDirectories(file.getParent());
|
||||||
|
}
|
||||||
Path p = defaultConfigPath.resolve(modConfig.getFileName());
|
Path p = defaultConfigPath.resolve(modConfig.getFileName());
|
||||||
if (Files.exists(p)) {
|
if (Files.exists(p)) {
|
||||||
LOGGER.info(CONFIG, "Loading default config file from path {}", p);
|
LOGGER.info(CONFIG, "Loading default config file from path {}", p);
|
||||||
@@ -111,17 +167,16 @@ public class ConfigFileTypeHandler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static class ConfigWatcher implements Runnable {
|
@Override
|
||||||
private final ModConfig modConfig;
|
public String toString() {
|
||||||
private final CommentedFileConfig commentedFileConfig;
|
return "ConfigFileTypeHandler[" + (type != null ? type : "UNKNOWN") + "]";
|
||||||
private final ClassLoader realClassLoader;
|
}
|
||||||
|
|
||||||
ConfigWatcher(final ModConfig modConfig, final CommentedFileConfig commentedFileConfig, final ClassLoader classLoader) {
|
|
||||||
this.modConfig = modConfig;
|
|
||||||
this.commentedFileConfig = commentedFileConfig;
|
|
||||||
this.realClassLoader = classLoader;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
private record ConfigWatcher(
|
||||||
|
ModConfig modConfig,
|
||||||
|
CommentedFileConfig commentedFileConfig,
|
||||||
|
ClassLoader realClassLoader
|
||||||
|
) implements Runnable {
|
||||||
@Override
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
// Force the regular classloader onto the special thread
|
// Force the regular classloader onto the special thread
|
||||||
|
|||||||
@@ -8,6 +8,9 @@ package net.minecraftforge.fml.config;
|
|||||||
import com.electronwill.nightconfig.core.CommentedConfig;
|
import com.electronwill.nightconfig.core.CommentedConfig;
|
||||||
import com.electronwill.nightconfig.core.file.CommentedFileConfig;
|
import com.electronwill.nightconfig.core.file.CommentedFileConfig;
|
||||||
import com.mojang.logging.LogUtils;
|
import com.mojang.logging.LogUtils;
|
||||||
|
import net.minecraftforge.api.distmarker.Dist;
|
||||||
|
import net.minecraftforge.fml.DistExecutor;
|
||||||
|
import net.minecraftforge.fml.loading.FMLPaths;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.Marker;
|
import org.slf4j.Marker;
|
||||||
import org.slf4j.MarkerFactory;
|
import org.slf4j.MarkerFactory;
|
||||||
@@ -47,15 +50,32 @@ public class ConfigTracker {
|
|||||||
|
|
||||||
public void loadConfigs(ModConfig.Type type, Path configBasePath) {
|
public void loadConfigs(ModConfig.Type type, Path configBasePath) {
|
||||||
LOGGER.debug(CONFIG, "Loading configs type {}", type);
|
LOGGER.debug(CONFIG, "Loading configs type {}", type);
|
||||||
this.configSets.get(type).forEach(config -> openConfig(config, configBasePath));
|
for (ModConfig config : this.configSets.get(type)) {
|
||||||
|
openConfig(config, configBasePath);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO: [FML] This is only called for the server (outside of forceUnload)
|
||||||
|
// rethink config implementation for eventual FML rewrite
|
||||||
public void unloadConfigs(ModConfig.Type type, Path configBasePath) {
|
public void unloadConfigs(ModConfig.Type type, Path configBasePath) {
|
||||||
LOGGER.debug(CONFIG, "Unloading configs type {}", type);
|
LOGGER.debug(CONFIG, "Unloading configs type {}", type);
|
||||||
this.configSets.get(type).forEach(config -> closeConfig(config, configBasePath));
|
for (ModConfig config : this.configSets.get(type)) {
|
||||||
|
closeConfig(config, configBasePath);
|
||||||
|
}
|
||||||
|
ConfigFileTypeHandler.get(type).stopWatcher();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void openConfig(final ModConfig config, final Path configBasePath) {
|
// If there is a better way to do this, please tell me. Because this is FUCKED
|
||||||
|
public void forceUnload() {
|
||||||
|
// This is how ModStateProvider handles loading configs. So we're doing the same but with unloadConfigs instead
|
||||||
|
DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> this.unloadConfigs(ModConfig.Type.CLIENT, FMLPaths.CONFIGDIR.get()));
|
||||||
|
this.unloadConfigs(ModConfig.Type.COMMON, FMLPaths.CONFIGDIR.get());
|
||||||
|
|
||||||
|
// just in case server watcher is still alive somehow...
|
||||||
|
ConfigFileTypeHandler.get(ModConfig.Type.SERVER).stopWatcher();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void openConfig(final ModConfig config, final Path configBasePath) {
|
||||||
LOGGER.trace(CONFIG, "Loading config file type {} at {} for {}", config.getType(), config.getFileName(), config.getModId());
|
LOGGER.trace(CONFIG, "Loading config file type {} at {} for {}", config.getType(), config.getFileName(), config.getModId());
|
||||||
final CommentedFileConfig configData = config.getHandler().reader(configBasePath).apply(config);
|
final CommentedFileConfig configData = config.getHandler().reader(configBasePath).apply(config);
|
||||||
config.setConfigData(configData);
|
config.setConfigData(configData);
|
||||||
@@ -63,7 +83,7 @@ public class ConfigTracker {
|
|||||||
config.save();
|
config.save();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void closeConfig(final ModConfig config, final Path configBasePath) {
|
private static void closeConfig(final ModConfig config, final Path configBasePath) {
|
||||||
if (config.getConfigData() != null) {
|
if (config.getConfigData() != null) {
|
||||||
LOGGER.trace(CONFIG, "Closing config file type {} at {} for {}", config.getType(), config.getFileName(), config.getModId());
|
LOGGER.trace(CONFIG, "Closing config file type {} at {} for {}", config.getType(), config.getFileName(), config.getModId());
|
||||||
// stop the filewatcher before we save the file and close it, so reload doesn't fire
|
// stop the filewatcher before we save the file and close it, so reload doesn't fire
|
||||||
|
|||||||
@@ -24,14 +24,13 @@ public class ModConfig
|
|||||||
private final ModContainer container;
|
private final ModContainer container;
|
||||||
private final ConfigFileTypeHandler configHandler;
|
private final ConfigFileTypeHandler configHandler;
|
||||||
private CommentedConfig configData;
|
private CommentedConfig configData;
|
||||||
private Callable<Void> saveHandler;
|
|
||||||
|
|
||||||
public ModConfig(final Type type, final IConfigSpec<?> spec, final ModContainer container, final String fileName) {
|
public ModConfig(final Type type, final IConfigSpec<?> spec, final ModContainer container, final String fileName) {
|
||||||
this.type = type;
|
this.type = type;
|
||||||
this.spec = spec;
|
this.spec = spec;
|
||||||
this.fileName = fileName;
|
this.fileName = fileName;
|
||||||
this.container = container;
|
this.container = container;
|
||||||
this.configHandler = ConfigFileTypeHandler.TOML;
|
this.configHandler = ConfigFileTypeHandler.get(type);
|
||||||
ConfigTracker.INSTANCE.trackConfig(this);
|
ConfigTracker.INSTANCE.trackConfig(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+21
-15
@@ -22,9 +22,7 @@ import org.slf4j.Logger;
|
|||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import java.awt.Desktop;
|
import java.awt.Desktop;
|
||||||
import java.io.BufferedReader;
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.InputStreamReader;
|
|
||||||
import java.lang.reflect.Method;
|
import java.lang.reflect.Method;
|
||||||
import java.lang.reflect.Modifier;
|
import java.lang.reflect.Modifier;
|
||||||
import java.net.URI;
|
import java.net.URI;
|
||||||
@@ -302,13 +300,6 @@ public class DisplayWindow implements ImmediateWindowProvider {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void crashElegantly(String errorDetails) {
|
private void crashElegantly(String errorDetails) {
|
||||||
String qrText;
|
|
||||||
try (var is = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/glfailure.txt")))) {
|
|
||||||
qrText = is.lines().collect(Collectors.joining("\n"));
|
|
||||||
} catch (IOException ioe) {
|
|
||||||
qrText = "";
|
|
||||||
}
|
|
||||||
|
|
||||||
StringBuilder msgBuilder = new StringBuilder(2000);
|
StringBuilder msgBuilder = new StringBuilder(2000);
|
||||||
msgBuilder.append("Failed to initialize graphics window with current settings.\n");
|
msgBuilder.append("Failed to initialize graphics window with current settings.\n");
|
||||||
msgBuilder.append("\n\n");
|
msgBuilder.append("\n\n");
|
||||||
@@ -407,13 +398,13 @@ public class DisplayWindow implements ImmediateWindowProvider {
|
|||||||
if (showHelpLog && versidx == 0) {
|
if (showHelpLog && versidx == 0) {
|
||||||
LOGGER.info("""
|
LOGGER.info("""
|
||||||
If this message is the only thing at the bottom of your log before a crash, you probably have a driver issue.
|
If this message is the only thing at the bottom of your log before a crash, you probably have a driver issue.
|
||||||
|
|
||||||
Possible solutions:
|
Possible solutions:
|
||||||
A) Make sure Minecraft is set to prefer high performance graphics in the OS and/or driver control panel
|
A) Make sure Minecraft is set to prefer high performance graphics in the OS and/or driver control panel
|
||||||
B) Check for driver updates on the graphics brand's website
|
B) Check for driver updates on the graphics brand's website
|
||||||
C) Try reinstalling your graphics drivers
|
C) Try reinstalling your graphics drivers
|
||||||
D) If still not working after trying all of the above, ask for further help on the Forge forums or Discord
|
D) If still not working after trying all of the above, ask for further help on the Forge forums or Discord
|
||||||
|
|
||||||
You can safely ignore this message if the game starts up successfully.""");
|
You can safely ignore this message if the game starts up successfully.""");
|
||||||
}
|
}
|
||||||
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, GL_VERSIONS[versidx][0]); // we try our versions one at a time
|
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, GL_VERSIONS[versidx][0]); // we try our versions one at a time
|
||||||
@@ -612,10 +603,25 @@ public class DisplayWindow implements ImmediateWindowProvider {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void updateModuleReads(final ModuleLayer layer) {
|
public void updateModuleReads(final ModuleLayer layer) {
|
||||||
var fm = layer.findModule("forge").orElseThrow();
|
final var FORGE_MODULE = "net.minecraftforge.forge";
|
||||||
getClass().getModule().addReads(fm);
|
var forge_module = layer.findModule(FORGE_MODULE).orElse(null);
|
||||||
var clz = FMLLoader.getGameLayer().findModule("forge").map(l->Class.forName(l, "net.minecraftforge.client.loading.ForgeLoadingOverlay")).orElseThrow();
|
if (forge_module == null)
|
||||||
loadingOverlay = Arrays.stream(clz.getDeclaredMethods()).filter(m-> Modifier.isStatic(m.getModifiers()) && m.getName().equals("newInstance")).findFirst().orElseThrow();
|
throw new IllegalStateException("Could not find " + FORGE_MODULE + " in " + layer);
|
||||||
|
|
||||||
|
getClass().getModule().addReads(forge_module);
|
||||||
|
|
||||||
|
|
||||||
|
var clz = Class.forName(forge_module, "net.minecraftforge.client.loading.ForgeLoadingOverlay");
|
||||||
|
|
||||||
|
for (var mtd : clz.getDeclaredMethods()) {
|
||||||
|
if (Modifier.isStatic(mtd.getModifiers()) && "newInstance".equals(mtd.getName())) {
|
||||||
|
this.loadingOverlay = mtd;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loadingOverlay == null)
|
||||||
|
throw new IllegalStateException("Could not find static newInstace method in " + clz.getName());
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getFramebufferTextureId() {
|
public int getFramebufferTextureId() {
|
||||||
|
|||||||
+4
-5
@@ -13,10 +13,10 @@ import java.lang.management.MemoryMXBean;
|
|||||||
import java.lang.management.MemoryUsage;
|
import java.lang.management.MemoryUsage;
|
||||||
|
|
||||||
public class PerformanceInfo {
|
public class PerformanceInfo {
|
||||||
|
private static final MemoryMXBean MEMORY_BEAN = ManagementFactory.getMemoryMXBean();
|
||||||
|
|
||||||
private final boolean showCPUUsage;
|
private final boolean showCPUUsage;
|
||||||
private final OperatingSystemMXBean osBean;
|
private final OperatingSystemMXBean osBean;
|
||||||
private final MemoryMXBean memoryBean;
|
|
||||||
|
|
||||||
private float memory;
|
private float memory;
|
||||||
private String text;
|
private String text;
|
||||||
@@ -24,15 +24,14 @@ public class PerformanceInfo {
|
|||||||
PerformanceInfo() {
|
PerformanceInfo() {
|
||||||
showCPUUsage = FMLConfig.getBoolConfigValue(FMLConfig.ConfigValue.EARLY_WINDOW_SHOW_CPU);
|
showCPUUsage = FMLConfig.getBoolConfigValue(FMLConfig.ConfigValue.EARLY_WINDOW_SHOW_CPU);
|
||||||
osBean = showCPUUsage ? ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class) : null;
|
osBean = showCPUUsage ? ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class) : null;
|
||||||
memoryBean = ManagementFactory.getMemoryMXBean();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void update() {
|
void update() {
|
||||||
final MemoryUsage heapusage = memoryBean.getHeapMemoryUsage();
|
final MemoryUsage heapusage = MEMORY_BEAN.getHeapMemoryUsage();
|
||||||
memory = (float) heapusage.getUsed() / heapusage.getMax();
|
memory = (float) heapusage.getUsed() / heapusage.getMax();
|
||||||
|
|
||||||
if (!showCPUUsage) {
|
if (!showCPUUsage) {
|
||||||
text = "Heap: %d/%d MB (%.1f%%) OffHeap: %d MB".formatted(heapusage.getUsed() >> 20, heapusage.getMax() >> 20, memory * 100.0, memoryBean.getNonHeapMemoryUsage().getUsed() >> 20);
|
text = "Memory: %d/%dMB (%.1f%%)".formatted(heapusage.getUsed() >>> 20, heapusage.getMax() >>> 20, memory * 100f);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -44,7 +43,7 @@ public class PerformanceInfo {
|
|||||||
cpuText = "CPU: %.1f%%".formatted(cpuLoad * 100f);
|
cpuText = "CPU: %.1f%%".formatted(cpuLoad * 100f);
|
||||||
}
|
}
|
||||||
|
|
||||||
text = "Heap: %d/%d MB (%.1f%%) OffHeap: %d MB %s".formatted(heapusage.getUsed() >> 20, heapusage.getMax() >> 20, memory * 100.0, memoryBean.getNonHeapMemoryUsage().getUsed() >> 20, cpuText);
|
text = "Memory: %d/%dMB (%.1f%%) %s".formatted(heapusage.getUsed() >>> 20, heapusage.getMax() >>> 20, memory * 100f, cpuText);
|
||||||
}
|
}
|
||||||
|
|
||||||
String text() {
|
String text() {
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ public class SimpleFont {
|
|||||||
private final int lineSpacing;
|
private final int lineSpacing;
|
||||||
private final int descent;
|
private final int descent;
|
||||||
private final int GLYPH_COUNT = 127-32;
|
private final int GLYPH_COUNT = 127-32;
|
||||||
private Glyph[] glyphs;
|
private final Glyph[] glyphs;
|
||||||
|
|
||||||
private record Glyph(char c, int charwidth, int[] pos, float[] uv) {
|
private record Glyph(char c, int charwidth, int[] pos, float[] uv) {
|
||||||
Pos loadQuad(Pos pos, int colour, SimpleBufferBuilder bb) {
|
Pos loadQuad(Pos pos, int colour, SimpleBufferBuilder bb) {
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ dependencies {
|
|||||||
implementation(libs.jimfs)
|
implementation(libs.jimfs)
|
||||||
|
|
||||||
implementation(libs.log4j.core)
|
implementation(libs.log4j.core)
|
||||||
annotationProcessor(libs.log4j.core)
|
annotationProcessor(libs.bundles.log4j)
|
||||||
|
|
||||||
testCompileOnly(libs.nulls)
|
testCompileOnly(libs.nulls)
|
||||||
testRuntimeOnly(libs.bootstrap)
|
testRuntimeOnly(libs.bootstrap)
|
||||||
|
|||||||
+24
-31
@@ -36,9 +36,9 @@ import cpw.mods.modlauncher.serviceapi.ILaunchPluginService;
|
|||||||
*/
|
*/
|
||||||
public class CapabilityTokenSubclass implements ILaunchPluginService {
|
public class CapabilityTokenSubclass implements ILaunchPluginService {
|
||||||
|
|
||||||
private final String FUNC_NAME = "getType";
|
private static final String FUNC_NAME = "getType";
|
||||||
private final String FUNC_DESC = "()Ljava/lang/String;";
|
private static final String FUNC_DESC = "()Ljava/lang/String;";
|
||||||
private 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() {
|
||||||
@@ -49,49 +49,45 @@ public class CapabilityTokenSubclass implements ILaunchPluginService {
|
|||||||
private static final EnumSet<Phase> NAY = EnumSet.noneOf(Phase.class);
|
private static final EnumSet<Phase> NAY = EnumSet.noneOf(Phase.class);
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty)
|
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty) {
|
||||||
{
|
if (isEmpty)
|
||||||
return isEmpty ? NAY : YAY;
|
return NAY;
|
||||||
|
|
||||||
|
String internalName = classType.getInternalName();
|
||||||
|
if (internalName.startsWith("net/minecraft/") || internalName.startsWith("com/mojang/"))
|
||||||
|
return NAY;
|
||||||
|
|
||||||
|
return YAY;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int processClassWithFlags(final Phase phase, final ClassNode classNode, final Type classType, final String reason)
|
public int processClassWithFlags(final Phase phase, final ClassNode classNode, final Type classType, final String reason) {
|
||||||
{
|
if (CAP_INJECT.equals(classNode.name)) {
|
||||||
if (CAP_INJECT.equals(classNode.name))
|
for (MethodNode mtd : classNode.methods) {
|
||||||
{
|
if (FUNC_NAME.equals(mtd.name) && FUNC_DESC.equals(mtd.desc)) {
|
||||||
for (MethodNode mtd : classNode.methods)
|
|
||||||
{
|
|
||||||
if (FUNC_NAME.equals(mtd.name) && FUNC_DESC.equals(mtd.desc))
|
|
||||||
{
|
|
||||||
mtd.access &= ~Opcodes.ACC_FINAL; // We have it final in code so people don't override it, cuz that'd be stupid, and make our transformer more complicated.
|
mtd.access &= ~Opcodes.ACC_FINAL; // We have it final in code so people don't override it, cuz that'd be stupid, and make our transformer more complicated.
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return ComputeFlags.SIMPLE_REWRITE;
|
return ComputeFlags.SIMPLE_REWRITE;
|
||||||
}
|
} else if (CAP_INJECT.equals(classNode.superName)) {
|
||||||
else if (CAP_INJECT.equals(classNode.superName))
|
|
||||||
{
|
|
||||||
Holder cls = new Holder();
|
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) {
|
||||||
{
|
final Deque<String> stack = new ArrayDeque<>();
|
||||||
Deque<String> stack = new ArrayDeque<>();
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void visitClassType(final String name)
|
public void visitClassType(final String name) {
|
||||||
{
|
|
||||||
stack.push(name);
|
stack.push(name);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void visitInnerClassType(final String name)
|
public void visitInnerClassType(final String name) {
|
||||||
{
|
|
||||||
stack.push(stack.pop() + '$' + name);
|
stack.push(stack.pop() + '$' + name);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void visitEnd()
|
public void visitEnd() {
|
||||||
{
|
|
||||||
var val = stack.pop();
|
var val = stack.pop();
|
||||||
if (!stack.isEmpty() && CAP_INJECT.equals(stack.peek()))
|
if (!stack.isEmpty() && CAP_INJECT.equals(stack.peek()))
|
||||||
cls.value = val;
|
cls.value = val;
|
||||||
@@ -106,15 +102,12 @@ public class CapabilityTokenSubclass implements ILaunchPluginService {
|
|||||||
mtd.visitInsn(Opcodes.ARETURN);
|
mtd.visitInsn(Opcodes.ARETURN);
|
||||||
mtd.visitEnd();
|
mtd.visitEnd();
|
||||||
return ComputeFlags.COMPUTE_MAXS;
|
return ComputeFlags.COMPUTE_MAXS;
|
||||||
}
|
} else {
|
||||||
else
|
|
||||||
{
|
|
||||||
return ComputeFlags.NO_REWRITE;
|
return ComputeFlags.NO_REWRITE;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static class Holder {
|
private static final class Holder {
|
||||||
String value;
|
String value;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
+30
-10
@@ -8,6 +8,7 @@ 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.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
import java.util.concurrent.atomic.AtomicBoolean;
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
import java.util.function.Function;
|
import java.util.function.Function;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
@@ -34,8 +35,12 @@ public class ObjectHolderDefinalize implements ILaunchPluginService {
|
|||||||
new VanillaObjectHolderData("net.minecraft.world.effect.MobEffects", "mob_effect", "net.minecraft.world.effect.MobEffect"),
|
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.core.particles.ParticleTypes", "particle_type", "net.minecraft.core.particles.ParticleType"),
|
||||||
new VanillaObjectHolderData("net.minecraft.sounds.SoundEvents", "sound_event", "net.minecraft.sounds.SoundEvent")
|
new VanillaObjectHolderData("net.minecraft.sounds.SoundEvents", "sound_event", "net.minecraft.sounds.SoundEvent")
|
||||||
).collect(Collectors.toMap(VanillaObjectHolderData::holderClass, Function.identity()));
|
).collect(Collectors.toUnmodifiableMap(VanillaObjectHolderData::holderClass, Function.identity()));
|
||||||
private final String OBJECT_HOLDER = "Lnet/minecraftforge/registries/ObjectHolder;"; //Don't directly reference this to prevent class loading.
|
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
|
@Override
|
||||||
public String name() {
|
public String name() {
|
||||||
@@ -46,13 +51,29 @@ public class ObjectHolderDefinalize implements ILaunchPluginService {
|
|||||||
private static final EnumSet<Phase> NAY = EnumSet.noneOf(Phase.class);
|
private static final EnumSet<Phase> NAY = EnumSet.noneOf(Phase.class);
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty)
|
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty) {
|
||||||
{
|
if (isEmpty)
|
||||||
return isEmpty ? NAY : YAY;
|
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 boolean hasHolder(List<AnnotationNode> lst)
|
private static boolean hasHolder(List<AnnotationNode> lst) {
|
||||||
{
|
|
||||||
return lst != null && lst.stream().anyMatch(n -> n.desc.equals(OBJECT_HOLDER));
|
return lst != null && lst.stream().anyMatch(n -> n.desc.equals(OBJECT_HOLDER));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,10 +97,9 @@ public class ObjectHolderDefinalize implements ILaunchPluginService {
|
|||||||
{
|
{
|
||||||
final AtomicBoolean changes = new AtomicBoolean();
|
final AtomicBoolean changes = new AtomicBoolean();
|
||||||
//Must be public static finals, and non-array objects
|
//Must be public static finals, and non-array objects
|
||||||
final int flags = Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL;
|
|
||||||
|
|
||||||
//Fix Annotated Fields before injecting from class level
|
//Fix Annotated Fields before injecting from class level
|
||||||
classNode.fields.stream().filter(f -> ((f.access & flags) == flags) && f.desc.startsWith("L") && hasHolder(f.visibleAnnotations)).forEach(f ->
|
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;
|
int prev = f.access;
|
||||||
f.access &= ~Opcodes.ACC_FINAL; //Strip final
|
f.access &= ~Opcodes.ACC_FINAL; //Strip final
|
||||||
@@ -89,7 +109,7 @@ public class ObjectHolderDefinalize implements ILaunchPluginService {
|
|||||||
|
|
||||||
if (VANILLA_OBJECT_HOLDERS.containsKey(classType.getClassName())) //Class level, de-finalize all fields and add @ObjectHolder to them!
|
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 & flags) == flags) && f.desc.startsWith("L")).forEach(f ->
|
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;
|
int prev = f.access;
|
||||||
f.access &= ~Opcodes.ACC_FINAL;
|
f.access &= ~Opcodes.ACC_FINAL;
|
||||||
|
|||||||
+29
-24
@@ -28,15 +28,16 @@ import org.slf4j.Logger;
|
|||||||
public class RuntimeEnumExtender implements ILaunchPluginService {
|
public class RuntimeEnumExtender implements ILaunchPluginService {
|
||||||
|
|
||||||
private static final Logger LOGGER = LogUtils.getLogger();
|
private static final Logger LOGGER = LogUtils.getLogger();
|
||||||
private final Type STRING = Type.getType(String.class);
|
private static final Type STRING = Type.getType(String.class);
|
||||||
private final Type ENUM = Type.getType(Enum.class);
|
private static final Type ENUM = Type.getType(Enum.class);
|
||||||
private final Type MARKER_IFACE = Type.getType("Lnet/minecraftforge/common/IExtensibleEnum;");
|
private static final Type MARKER_IFACE = Type.getType("Lnet/minecraftforge/common/IExtensibleEnum;");
|
||||||
private final Type ARRAY_UTILS = Type.getType("Lorg/apache/commons/lang3/ArrayUtils;"); //Don't directly reference this to prevent class loading.
|
private static final Type ARRAY_UTILS = Type.getType("Lorg/apache/commons/lang3/ArrayUtils;"); //Don't directly reference this to prevent class loading.
|
||||||
private final String ADD_DESC = Type.getMethodDescriptor(Type.getType(Object[].class), Type.getType(Object[].class), Type.getType(Object.class));
|
private static final String ADD_DESC = Type.getMethodDescriptor(Type.getType(Object[].class), Type.getType(Object[].class), Type.getType(Object.class));
|
||||||
private final Type UNSAFE_HACKS = Type.getType("Lnet/minecraftforge/fml/unsafe/UnsafeHacks;"); //Again, not direct reference to prevent class loading.
|
private static final Type UNSAFE_HACKS = Type.getType("Lnet/minecraftforge/fml/unsafe/UnsafeHacks;"); //Again, not direct reference to prevent class loading.
|
||||||
private final String CLEAN_DESC = Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(Class.class));
|
private static final String CLEAN_DESC = Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(Class.class));
|
||||||
private final String NAME_DESC = Type.getMethodDescriptor(STRING);
|
private static final String NAME_DESC = Type.getMethodDescriptor(STRING);
|
||||||
private final String EQUALS_DESC = Type.getMethodDescriptor(Type.BOOLEAN_TYPE, STRING);
|
private static final String EQUALS_DESC = Type.getMethodDescriptor(Type.BOOLEAN_TYPE, STRING);
|
||||||
|
private static final int FLAGS = Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL | Opcodes.ACC_SYNTHETIC;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String name() {
|
public String name() {
|
||||||
@@ -47,9 +48,15 @@ public class RuntimeEnumExtender implements ILaunchPluginService {
|
|||||||
private static final EnumSet<Phase> NAY = EnumSet.noneOf(Phase.class);
|
private static final EnumSet<Phase> NAY = EnumSet.noneOf(Phase.class);
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty)
|
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty) {
|
||||||
{
|
if (isEmpty)
|
||||||
return isEmpty ? NAY : YAY;
|
return NAY;
|
||||||
|
|
||||||
|
String internalName = classType.getInternalName();
|
||||||
|
if (internalName.startsWith("net/minecraftforge/") || internalName.startsWith("com/mojang/"))
|
||||||
|
return NAY;
|
||||||
|
|
||||||
|
return YAY;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -58,25 +65,24 @@ public class RuntimeEnumExtender implements ILaunchPluginService {
|
|||||||
if ((classNode.access & Opcodes.ACC_ENUM) == 0)
|
if ((classNode.access & Opcodes.ACC_ENUM) == 0)
|
||||||
return ComputeFlags.NO_REWRITE;
|
return ComputeFlags.NO_REWRITE;
|
||||||
|
|
||||||
Type array = Type.getType("[" + classType.getDescriptor());
|
if (!classNode.interfaces.contains(MARKER_IFACE.getInternalName()))
|
||||||
final int flags = Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL | Opcodes.ACC_SYNTHETIC;
|
|
||||||
|
|
||||||
FieldNode values = classNode.fields.stream().filter(f -> f.desc.contentEquals(array.getDescriptor()) && ((f.access & flags) == flags)).findFirst().orElse(null);
|
|
||||||
|
|
||||||
if (!classNode.interfaces.contains(MARKER_IFACE.getInternalName())) {
|
|
||||||
return ComputeFlags.NO_REWRITE;
|
return ComputeFlags.NO_REWRITE;
|
||||||
}
|
|
||||||
|
Type array = Type.getType("[" + classType.getDescriptor());
|
||||||
|
String arrayDesc = array.getDescriptor();
|
||||||
|
|
||||||
|
FieldNode values = classNode.fields.stream().filter(f -> f.desc.equals(arrayDesc) && ((f.access & FLAGS) == FLAGS)).findFirst().orElse(null);
|
||||||
|
|
||||||
//Static methods named "create" with first argument as a string
|
//Static methods named "create" with first argument as a string
|
||||||
List<MethodNode> candidates = classNode.methods.stream()
|
List<MethodNode> candidates = classNode.methods.stream()
|
||||||
.filter(m -> ((m.access & Opcodes.ACC_STATIC) != 0) && m.name.equals("create"))
|
.filter(m -> ((m.access & Opcodes.ACC_STATIC) != 0) && m.name.equals("create"))
|
||||||
.collect(Collectors.toList());
|
.toList();
|
||||||
|
|
||||||
if (candidates.isEmpty()) {
|
if (candidates.isEmpty()) {
|
||||||
throw new IllegalStateException("IExtensibleEnum has no candidate factory methods: " + classType.getClassName());
|
throw new IllegalStateException("IExtensibleEnum has no candidate factory methods: " + classType.getClassName());
|
||||||
}
|
}
|
||||||
|
|
||||||
candidates.forEach(mtd ->
|
for (var mtd : candidates)
|
||||||
{
|
{
|
||||||
Type[] args = Type.getArgumentTypes(mtd.desc);
|
Type[] args = Type.getArgumentTypes(mtd.desc);
|
||||||
if (args.length == 0 || !args[0].equals(STRING)) {
|
if (args.length == 0 || !args[0].equals(STRING)) {
|
||||||
@@ -108,8 +114,7 @@ public class RuntimeEnumExtender implements ILaunchPluginService {
|
|||||||
Type[] ctrArgs = new Type[args.length + 1];
|
Type[] ctrArgs = new Type[args.length + 1];
|
||||||
ctrArgs[0] = STRING;
|
ctrArgs[0] = STRING;
|
||||||
ctrArgs[1] = Type.INT_TYPE;
|
ctrArgs[1] = Type.INT_TYPE;
|
||||||
for (int x = 1; x < args.length; x++)
|
System.arraycopy(args, 1, ctrArgs, 2, args.length - 1);
|
||||||
ctrArgs[1 + x] = args[x];
|
|
||||||
|
|
||||||
String desc = Type.getMethodDescriptor(Type.VOID_TYPE, ctrArgs);
|
String desc = Type.getMethodDescriptor(Type.VOID_TYPE, ctrArgs);
|
||||||
|
|
||||||
@@ -231,7 +236,7 @@ public class RuntimeEnumExtender implements ILaunchPluginService {
|
|||||||
ins.load(vars, classType);
|
ins.load(vars, classType);
|
||||||
ins.areturn(classType);
|
ins.areturn(classType);
|
||||||
}
|
}
|
||||||
});
|
}
|
||||||
return ComputeFlags.COMPUTE_FRAMES;
|
return ComputeFlags.COMPUTE_FRAMES;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -17,11 +17,9 @@ 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 net.minecraftforge.forgespi.coremod.ICoreModProvider;
|
||||||
import org.apache.commons.lang3.tuple.Pair;
|
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
|
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.nio.file.Paths;
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
@@ -36,7 +34,6 @@ 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 ModDiscoverer modDiscoverer;
|
|
||||||
private static ICoreModProvider coreModProvider;
|
private static ICoreModProvider coreModProvider;
|
||||||
private static LanguageLoadingProvider languageLoadingProvider;
|
private static LanguageLoadingProvider languageLoadingProvider;
|
||||||
private static Dist dist;
|
private static Dist dist;
|
||||||
@@ -57,12 +54,15 @@ public class FMLLoader {
|
|||||||
LOGGER.debug(CORE, "Detected version data : {}", versionInfo);
|
LOGGER.debug(CORE, "Detected version data : {}", versionInfo);
|
||||||
LOGGER.debug(CORE, "FML {} loading", LauncherVersion.getVersion());
|
LOGGER.debug(CORE, "FML {} loading", LauncherVersion.getVersion());
|
||||||
|
|
||||||
|
// Allows us to communicate properties with other services through ModLauncher
|
||||||
|
setupBlackboardKeys();
|
||||||
|
|
||||||
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");
|
||||||
/*eventBus =*/ getPlugin(env, "eventbus", "1.0", "EventBus");
|
/*eventBus =*/ getPlugin(env, "eventbus", "1.0", "EventBus");
|
||||||
runtimeDistCleaner = getPlugin(env, "runtimedistcleaner", "1.0", "RuntimeDistCleaner");
|
runtimeDistCleaner = getPlugin(env, "runtimedistcleaner", "1.0", "RuntimeDistCleaner");
|
||||||
coreModProvider = getSingleService(ICoreModProvider.class, "CoreMod");
|
coreModProvider = getSingleService(ICoreModProvider.class, "CoreMod");
|
||||||
LOGGER.debug(CORE,"FML found CoreMod version : {}", JarVersionLookupHandler.getInfo(coreModProvider.getClass()).impl().version().orElse("MISSING"));
|
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 {
|
||||||
@@ -74,14 +74,15 @@ public class FMLLoader {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
private static <T> T getPlugin(IEnvironment env, String id, String version, String name) throws IncompatibleEnvironmentException {
|
private static <T> T getPlugin(IEnvironment env, String id, String version, String name) throws IncompatibleEnvironmentException {
|
||||||
@SuppressWarnings("unchecked")
|
var plugin = env.findLaunchPlugin(id).orElse(null);
|
||||||
var plugin = (T)env.findLaunchPlugin(id).orElseThrow(() -> {
|
if (plugin == null) {
|
||||||
LOGGER.error(CORE, "{} library is missing, we need this to run", name);
|
LOGGER.error(CORE, "{} library is missing, we need this to run", name);
|
||||||
return new IncompatibleEnvironmentException("Missing " + name + ", cannot run");
|
throw new IncompatibleEnvironmentException("Missing " + name + ", cannot run");
|
||||||
});
|
}
|
||||||
checkPackage(plugin.getClass(), version, name);
|
checkPackage(plugin.getClass(), version, name);
|
||||||
return plugin;
|
return (T) plugin;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void checkPackage(Class<?> cls, String version, String name) throws IncompatibleEnvironmentException {
|
private static void checkPackage(Class<?> cls, String version, String name) throws IncompatibleEnvironmentException {
|
||||||
@@ -120,6 +121,12 @@ public class FMLLoader {
|
|||||||
return providers.get(0);
|
return providers.get(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static void setupBlackboardKeys() {
|
||||||
|
LOGGER.debug(CORE, "Requesting CoreMods to not apply the fix for ASMAPI.findFirstInstructionBefore by default");
|
||||||
|
var blackboardKey = TypesafeMap.Key.getOrCreate(Launcher.INSTANCE.blackboard(), "coremods.use_old_findFirstInstructionBefore", Boolean.class);
|
||||||
|
Launcher.INSTANCE.blackboard().<Boolean>computeIfAbsent(blackboardKey, k -> true);
|
||||||
|
}
|
||||||
|
|
||||||
static void setupLaunchHandler(final IEnvironment environment, final Map<String, Object> arguments) {
|
static void setupLaunchHandler(final IEnvironment environment, final Map<String, Object> arguments) {
|
||||||
final String launchTarget = environment.getProperty(IEnvironment.Keys.LAUNCHTARGET.get()).orElse("MISSING");
|
final String launchTarget = environment.getProperty(IEnvironment.Keys.LAUNCHTARGET.get()).orElse("MISSING");
|
||||||
arguments.put("launchTarget", launchTarget);
|
arguments.put("launchTarget", launchTarget);
|
||||||
@@ -137,20 +144,20 @@ public class FMLLoader {
|
|||||||
}
|
}
|
||||||
commonLaunchHandler = (CommonLaunchHandler)launchHandler.get();
|
commonLaunchHandler = (CommonLaunchHandler)launchHandler.get();
|
||||||
launchHandlerName = launchHandler.get().name();
|
launchHandlerName = launchHandler.get().name();
|
||||||
gamePath = environment.getProperty(IEnvironment.Keys.GAMEDIR.get()).orElse(Paths.get(".").toAbsolutePath());
|
gamePath = environment.getProperty(IEnvironment.Keys.GAMEDIR.get()).orElse(Path.of(".").toAbsolutePath());
|
||||||
|
|
||||||
naming = commonLaunchHandler.getNaming();
|
naming = commonLaunchHandler.getNaming();
|
||||||
dist = commonLaunchHandler.getDist();
|
dist = commonLaunchHandler.getDist();
|
||||||
production = commonLaunchHandler.isProduction();
|
production = commonLaunchHandler.isProduction();
|
||||||
|
|
||||||
accessTransformer.getExtension().accept(Pair.of(naming, "srg"));
|
accessTransformer.getExtension().accept(Map.entry(naming, "srg"));
|
||||||
|
|
||||||
runtimeDistCleaner.getExtension().accept(dist);
|
runtimeDistCleaner.getExtension().accept(dist);
|
||||||
}
|
}
|
||||||
|
|
||||||
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");
|
||||||
modDiscoverer = new ModDiscoverer(arguments);
|
var modDiscoverer = new ModDiscoverer(arguments);
|
||||||
modValidator = modDiscoverer.discoverMods();
|
modValidator = modDiscoverer.discoverMods();
|
||||||
var pluginResources = modValidator.getPluginResources();
|
var pluginResources = modValidator.getPluginResources();
|
||||||
return List.of(pluginResources);
|
return List.of(pluginResources);
|
||||||
@@ -172,10 +179,6 @@ public class FMLLoader {
|
|||||||
return languageLoadingProvider;
|
return languageLoadingProvider;
|
||||||
}
|
}
|
||||||
|
|
||||||
static ModDiscoverer getModDiscoverer() {
|
|
||||||
return modDiscoverer;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static CommonLaunchHandler getLaunchHandler() {
|
public static CommonLaunchHandler getLaunchHandler() {
|
||||||
return commonLaunchHandler;
|
return commonLaunchHandler;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ import static net.minecraftforge.fml.loading.LogMarkers.CORE;
|
|||||||
|
|
||||||
public class FMLServiceProvider implements ITransformationService {
|
public class FMLServiceProvider implements ITransformationService {
|
||||||
private static final Logger LOGGER = LogUtils.getLogger();
|
private static final Logger LOGGER = LogUtils.getLogger();
|
||||||
private Map<String, Object> arguments;
|
private final Map<String, Object> arguments = new HashMap<>();
|
||||||
|
|
||||||
public FMLServiceProvider() {
|
public FMLServiceProvider() {
|
||||||
var markers = System.getProperty("forge.logging.markers", "").split(",");
|
var markers = System.getProperty("forge.logging.markers", "").split(",");
|
||||||
@@ -45,7 +45,6 @@ public class FMLServiceProvider implements ITransformationService {
|
|||||||
FMLConfig.load();
|
FMLConfig.load();
|
||||||
LOGGER.debug(CORE, "Preparing ModFile");
|
LOGGER.debug(CORE, "Preparing ModFile");
|
||||||
environment.computePropertyIfAbsent(Environment.Keys.MODFILEFACTORY.get(), k->ModFile::new);
|
environment.computePropertyIfAbsent(Environment.Keys.MODFILEFACTORY.get(), k->ModFile::new);
|
||||||
arguments = new HashMap<>();
|
|
||||||
LOGGER.debug(CORE, "Preparing launch handler");
|
LOGGER.debug(CORE, "Preparing launch handler");
|
||||||
FMLLoader.setupLaunchHandler(environment, arguments);
|
FMLLoader.setupLaunchHandler(environment, arguments);
|
||||||
FMLEnvironment.setupInteropEnvironment(environment);
|
FMLEnvironment.setupInteropEnvironment(environment);
|
||||||
@@ -68,14 +67,6 @@ public class FMLServiceProvider implements ITransformationService {
|
|||||||
FMLLoader.onInitialLoad(environment, otherServices);
|
FMLLoader.onInitialLoad(environment, otherServices);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public void arguments(BiFunction<String, String, OptionSpecBuilder> argumentBuilder) {
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void argumentValues(OptionResult option) {
|
|
||||||
}
|
|
||||||
|
|
||||||
@SuppressWarnings("rawtypes")
|
@SuppressWarnings("rawtypes")
|
||||||
@Override
|
@Override
|
||||||
public @NotNull List<ITransformer> transformers() {
|
public @NotNull List<ITransformer> transformers() {
|
||||||
|
|||||||
@@ -140,7 +140,7 @@ public class ImmediateWindowHandler {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void updateModuleReads(final ModuleLayer layer) {
|
public void updateModuleReads(final ModuleLayer layer) {
|
||||||
var fm = layer.findModule("forge");
|
var fm = layer.findModule("net.minecraftforge.forge");
|
||||||
if (fm.isPresent()) {
|
if (fm.isPresent()) {
|
||||||
getClass().getModule().addReads(fm.get());
|
getClass().getModule().addReads(fm.get());
|
||||||
var clz = fm.map(l -> Class.forName(l, "net.minecraftforge.client.loading.NoVizFallback")).orElseThrow();
|
var clz = fm.map(l -> Class.forName(l, "net.minecraftforge.client.loading.NoVizFallback")).orElseThrow();
|
||||||
|
|||||||
@@ -78,9 +78,13 @@ public class LoadingModList
|
|||||||
|
|
||||||
public void addAccessTransformers()
|
public void addAccessTransformers()
|
||||||
{
|
{
|
||||||
modFiles.stream()
|
for (ModFileInfo modFile : modFiles) {
|
||||||
.map(ModFileInfo::getFile)
|
ModFile mod = modFile.getFile();
|
||||||
.forEach(mod -> mod.getAccessTransformer().ifPresent(path -> FMLLoader.addAccessTransformer(path, mod)));
|
var at = mod.getAccessTransformer().orElse(null);
|
||||||
|
if (at != null) {
|
||||||
|
FMLLoader.addAccessTransformer(at, mod);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void addForScanning(BackgroundScanHandler backgroundScanHandler)
|
public void addForScanning(BackgroundScanHandler backgroundScanHandler)
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ public class MCPNamingService implements INameMappingService {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Map.Entry<String, String> understanding() {
|
public Map.Entry<String, String> understanding() {
|
||||||
return Pair.of("srg", "mcp");
|
return Map.entry("srg", "mcp");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -77,7 +77,7 @@ public class MCPNamingService implements INameMappingService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static void loadMappings(final String mappingFileName, BiConsumer<String, String> mapStore) {
|
private static void loadMappings(final String mappingFileName, BiConsumer<String, String> mapStore) {
|
||||||
URL path = ClassLoader.getSystemResource(mappingFileName); //We EXPLICITLY go through the SystemClassLoader here because this is dev-time only. And will be on the root classpath.
|
URL path = MCPNamingService.class.getClassLoader().getResource(mappingFileName);
|
||||||
if (path == null)
|
if (path == null)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ public class MavenCoordinateResolver {
|
|||||||
(!extension.isEmpty() ? "." + extension : ".jar");
|
(!extension.isEmpty() ? "." + extension : ".jar");
|
||||||
|
|
||||||
String[] groups = groupId.split("\\.");
|
String[] groups = groupId.split("\\.");
|
||||||
Path result = Paths.get(groups[0]);
|
Path result = Path.of(groups[0]);
|
||||||
for (int i = 1; i < groups.length; i++) {
|
for (int i = 1; i < groups.length; i++) {
|
||||||
result = result.resolve(groups[i]);
|
result = result.resolve(groups[i]);
|
||||||
}
|
}
|
||||||
|
|||||||
+14
@@ -10,6 +10,8 @@ import cpw.mods.jarhandling.SecureJar;
|
|||||||
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.serviceapi.ITransformerDiscoveryService;
|
import cpw.mods.modlauncher.serviceapi.ITransformerDiscoveryService;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.ApiStatus;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
@@ -20,6 +22,7 @@ import java.util.ArrayList;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
|
@ApiStatus.Internal
|
||||||
public class ModDirTransformerDiscoverer implements ITransformerDiscoveryService {
|
public class ModDirTransformerDiscoverer implements ITransformerDiscoveryService {
|
||||||
private static final Logger LOGGER = LogUtils.getLogger();
|
private static final Logger LOGGER = LogUtils.getLogger();
|
||||||
private static final Set<String> SERVICES = Set.of(
|
private static final Set<String> SERVICES = Set.of(
|
||||||
@@ -76,4 +79,15 @@ public class ModDirTransformerDiscoverer implements ITransformerDiscoveryService
|
|||||||
.filter(SERVICES::contains)
|
.filter(SERVICES::contains)
|
||||||
.forEach(s -> found.add(new NamedPath(s, path)));
|
.forEach(s -> found.add(new NamedPath(s, path)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static boolean isServiceProvider(Path path) {
|
||||||
|
var jar = SecureJar.from(path);
|
||||||
|
|
||||||
|
for (var providers : jar.moduleDataProvider().descriptor().provides()) {
|
||||||
|
if (SERVICES.contains(providers.service()))
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -57,13 +57,13 @@ public class ModSorter
|
|||||||
// Note this will never actually throw an error because the duplicate checks are done in ModDiscovererer before we get to this phase
|
// Note this will never actually throw an error because the duplicate checks are done in ModDiscovererer before we get to this phase
|
||||||
// So all this is really doing is wasting time.
|
// So all this is really doing is wasting time.
|
||||||
// But i'm leaving it here until I rewrite all of cpw's mod loading code because its such a clusterfuck.
|
// But i'm leaving it here until I rewrite all of cpw's mod loading code because its such a clusterfuck.
|
||||||
return LoadingModList.of(ms.systemMods, ms.systemMods.stream().map(mf->(ModInfo)mf.getModInfos().get(0)).collect(toList()), e);
|
return LoadingModList.of(ms.systemMods, ms.systemMods.stream().map(mf->(ModInfo)mf.getModInfos().get(0)).toList(), e);
|
||||||
}
|
}
|
||||||
// try and validate dependencies
|
// try and validate dependencies
|
||||||
final List<ExceptionData> failedList = Stream.concat(ms.verifyDependencyVersions().stream(), errors.stream()).toList();
|
final List<ExceptionData> failedList = Stream.concat(ms.verifyDependencyVersions().stream(), errors.stream()).toList();
|
||||||
// if we miss one or the other, we abort now
|
// if we miss one or the other, we abort now
|
||||||
if (!failedList.isEmpty()) {
|
if (!failedList.isEmpty()) {
|
||||||
return LoadingModList.of(ms.systemMods, ms.systemMods.stream().map(mf->(ModInfo)mf.getModInfos().get(0)).collect(toList()), new EarlyLoadingException("failure to validate mod list", null, failedList));
|
return LoadingModList.of(ms.systemMods, ms.systemMods.stream().map(mf->(ModInfo)mf.getModInfos().get(0)).toList(), new EarlyLoadingException("failure to validate mod list", null, failedList));
|
||||||
} else {
|
} else {
|
||||||
// Otherwise, lets try and sort the modlist and proceed
|
// Otherwise, lets try and sort the modlist and proceed
|
||||||
EarlyLoadingException earlyLoadingException = null;
|
EarlyLoadingException earlyLoadingException = null;
|
||||||
@@ -89,9 +89,9 @@ public class ModSorter
|
|||||||
infos.keySet().forEach(graph::addNode);
|
infos.keySet().forEach(graph::addNode);
|
||||||
modFiles.stream()
|
modFiles.stream()
|
||||||
.map(ModFile::getModInfos)
|
.map(ModFile::getModInfos)
|
||||||
.<IModInfo>mapMulti(Iterable::forEach)
|
.flatMap(List::stream)
|
||||||
.map(IModInfo::getDependencies)
|
.map(IModInfo::getDependencies)
|
||||||
.<IModInfo.ModVersion>mapMulti(Iterable::forEach)
|
.<IModInfo.ModVersion>flatMap(List::stream)
|
||||||
.forEach(dep -> addDependency(graph, dep));
|
.forEach(dep -> addDependency(graph, dep));
|
||||||
|
|
||||||
final List<ModFileInfo> sorted;
|
final List<ModFileInfo> sorted;
|
||||||
@@ -107,7 +107,7 @@ public class ModSorter
|
|||||||
LOGGER.error(LOADING, "Mod Sorting failed.\nDetected Cycles: {}\n", cycles);
|
LOGGER.error(LOADING, "Mod Sorting failed.\nDetected Cycles: {}\n", cycles);
|
||||||
}
|
}
|
||||||
var dataList = cycles.stream()
|
var dataList = cycles.stream()
|
||||||
.<ModFileInfo>mapMulti(Iterable::forEach)
|
.flatMap(Set::stream)
|
||||||
.<IModInfo>mapMulti((mf,c)->mf.getMods().forEach(c))
|
.<IModInfo>mapMulti((mf,c)->mf.getMods().forEach(c))
|
||||||
.map(IModInfo::getModId)
|
.map(IModInfo::getModId)
|
||||||
.map(list -> new ExceptionData("fml.modloading.cycle", list))
|
.map(list -> new ExceptionData("fml.modloading.cycle", list))
|
||||||
@@ -116,7 +116,7 @@ public class ModSorter
|
|||||||
}
|
}
|
||||||
this.sortedList = sorted.stream()
|
this.sortedList = sorted.stream()
|
||||||
.map(ModFileInfo::getMods)
|
.map(ModFileInfo::getMods)
|
||||||
.<IModInfo>mapMulti(Iterable::forEach)
|
.flatMap(List::stream)
|
||||||
.map(ModInfo.class::cast)
|
.map(ModInfo.class::cast)
|
||||||
.collect(toList());
|
.collect(toList());
|
||||||
this.modFiles = sorted.stream()
|
this.modFiles = sorted.stream()
|
||||||
@@ -126,12 +126,14 @@ public class ModSorter
|
|||||||
|
|
||||||
private void addDependency(MutableGraph<ModFileInfo> topoGraph, IModInfo.ModVersion dep)
|
private void addDependency(MutableGraph<ModFileInfo> topoGraph, IModInfo.ModVersion dep)
|
||||||
{
|
{
|
||||||
final ModFileInfo self = (ModFileInfo)dep.getOwner().getOwningFile();
|
|
||||||
final IModInfo targetModInfo = modIdNameLookup.get(dep.getModId());
|
final IModInfo targetModInfo = modIdNameLookup.get(dep.getModId());
|
||||||
// soft dep that doesn't exist. Just return. No edge required.
|
// soft dep that doesn't exist. Just return. No edge required.
|
||||||
if (targetModInfo == null || !(targetModInfo.getOwningFile() instanceof final ModFileInfo target)) return;
|
if (targetModInfo == null || !(targetModInfo.getOwningFile() instanceof final ModFileInfo target)) return;
|
||||||
|
|
||||||
|
final ModFileInfo self = (ModFileInfo)dep.getOwner().getOwningFile();
|
||||||
if (self == target)
|
if (self == target)
|
||||||
return; // in case a jar has two mods that have dependencies between
|
return; // in case a jar has two mods that have dependencies between
|
||||||
|
|
||||||
switch (dep.getOrdering()) {
|
switch (dep.getOrdering()) {
|
||||||
case BEFORE -> topoGraph.putEdge(self, target);
|
case BEFORE -> topoGraph.putEdge(self, target);
|
||||||
case AFTER -> topoGraph.putEdge(target, self);
|
case AFTER -> topoGraph.putEdge(target, self);
|
||||||
@@ -165,7 +167,7 @@ public class ModSorter
|
|||||||
var container = modFilesByFirstId.get(systemMod);
|
var container = modFilesByFirstId.get(systemMod);
|
||||||
if (container != null && !container.isEmpty()) {
|
if (container != null && !container.isEmpty()) {
|
||||||
LOGGER.debug("Found system mod: {}", systemMod);
|
LOGGER.debug("Found system mod: {}", systemMod);
|
||||||
this.systemMods.add((ModFile) container.get(0));
|
this.systemMods.add(container.getFirst());
|
||||||
} else {
|
} else {
|
||||||
throw new IllegalStateException("Failed to find system mod: " + systemMod);
|
throw new IllegalStateException("Failed to find system mod: " + systemMod);
|
||||||
}
|
}
|
||||||
@@ -176,23 +178,23 @@ public class ModSorter
|
|||||||
{
|
{
|
||||||
final var modVersions = modFiles.stream()
|
final var modVersions = modFiles.stream()
|
||||||
.map(ModFile::getModInfos)
|
.map(ModFile::getModInfos)
|
||||||
.<IModInfo>mapMulti(Iterable::forEach)
|
.flatMap(List::stream)
|
||||||
.collect(toMap(IModInfo::getModId, IModInfo::getVersion));
|
.collect(toMap(IModInfo::getModId, IModInfo::getVersion));
|
||||||
|
|
||||||
final var modVersionDependencies = modFiles.stream()
|
final var modVersionDependencies = modFiles.stream()
|
||||||
.map(ModFile::getModInfos)
|
.map(ModFile::getModInfos)
|
||||||
.<IModInfo>mapMulti(Iterable::forEach)
|
.flatMap(List::stream)
|
||||||
.collect(groupingBy(Function.identity(), flatMapping(e -> e.getDependencies().stream(), toList())));
|
.collect(groupingBy(Function.identity(), flatMapping(e -> e.getDependencies().stream(), toList())));
|
||||||
|
|
||||||
final var modRequirements = modVersionDependencies.values().stream()
|
final var modRequirements = modVersionDependencies.values().stream()
|
||||||
.<IModInfo.ModVersion>mapMulti(Iterable::forEach)
|
.<IModInfo.ModVersion>flatMap(List::stream)
|
||||||
.filter(mv -> mv.getSide().isCorrectSide())
|
.filter(mv -> mv.getSide().isCorrectSide())
|
||||||
.collect(toSet());
|
.collect(toSet());
|
||||||
|
|
||||||
final long mandatoryRequired = modRequirements.stream().filter(IModInfo.ModVersion::isMandatory).count();
|
final long mandatoryRequired = modRequirements.stream().filter(IModInfo.ModVersion::isMandatory).count();
|
||||||
LOGGER.debug(LOADING, "Found {} mod requirements ({} mandatory, {} optional)", modRequirements.size(), mandatoryRequired, modRequirements.size() - mandatoryRequired);
|
LOGGER.debug(LOADING, "Found {} mod requirements ({} mandatory, {} optional)", modRequirements.size(), mandatoryRequired, modRequirements.size() - mandatoryRequired);
|
||||||
final var missingVersions = modRequirements.stream()
|
final var missingVersions = modRequirements.stream()
|
||||||
.filter(mv -> (mv.isMandatory() || modVersions.containsKey(mv.getModId())) && this.modVersionNotContained(mv, modVersions))
|
.filter(mv -> (mv.isMandatory() || modVersions.containsKey(mv.getModId())) && !modVersionContained(mv, modVersions))
|
||||||
.collect(toSet());
|
.collect(toSet());
|
||||||
final long mandatoryMissing = missingVersions.stream().filter(IModInfo.ModVersion::isMandatory).count();
|
final long mandatoryMissing = missingVersions.stream().filter(IModInfo.ModVersion::isMandatory).count();
|
||||||
LOGGER.debug(LOADING, "Found {} mod requirements missing ({} mandatory, {} optional)", missingVersions.size(), mandatoryMissing, missingVersions.size() - mandatoryMissing);
|
LOGGER.debug(LOADING, "Found {} mod requirements missing ({} mandatory, {} optional)", missingVersions.size(), mandatoryMissing, missingVersions.size() - mandatoryMissing);
|
||||||
@@ -240,9 +242,13 @@ public class ModSorter
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean modVersionNotContained(final IModInfo.ModVersion mv, final Map<String, ArtifactVersion> modVersions)
|
private static boolean modVersionContained(IModInfo.ModVersion mv, Map<String, ArtifactVersion> modVersions) {
|
||||||
{
|
var modId = mv.getModId();
|
||||||
return !(VersionSupportMatrix.testVersionSupportMatrix(mv.getVersionRange(), mv.getModId(), "mod", (modId, range) -> modVersions.containsKey(modId) &&
|
var range = mv.getVersionRange();
|
||||||
(range.containsVersion(modVersions.get(modId)) || modVersions.get(modId).toString().equals("0.0NONE"))));
|
if (modVersions.containsKey(modId)
|
||||||
|
&& (range.containsVersion(modVersions.get(modId)) || modVersions.get(modId).toString().equals("0.0NONE")))
|
||||||
|
return true;
|
||||||
|
|
||||||
|
return VersionSupportMatrix.testVersionSupportMatrix(mv.getVersionRange(), mv.getModId(), "mod");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -8,14 +8,8 @@ package net.minecraftforge.fml.loading;
|
|||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
import java.util.EnumSet;
|
import java.util.EnumSet;
|
||||||
import java.util.Iterator;
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Objects;
|
|
||||||
import java.util.concurrent.atomic.AtomicBoolean;
|
|
||||||
import java.util.function.Consumer;
|
import java.util.function.Consumer;
|
||||||
import java.util.stream.Collectors;
|
|
||||||
|
|
||||||
import com.google.common.collect.Streams;
|
|
||||||
import com.mojang.logging.LogUtils;
|
import com.mojang.logging.LogUtils;
|
||||||
import cpw.mods.modlauncher.serviceapi.ILaunchPluginService;
|
import cpw.mods.modlauncher.serviceapi.ILaunchPluginService;
|
||||||
import net.minecraftforge.api.distmarker.Dist;
|
import net.minecraftforge.api.distmarker.Dist;
|
||||||
@@ -28,138 +22,177 @@ import org.objectweb.asm.Type;
|
|||||||
import org.objectweb.asm.tree.AbstractInsnNode;
|
import org.objectweb.asm.tree.AbstractInsnNode;
|
||||||
import org.objectweb.asm.tree.AnnotationNode;
|
import org.objectweb.asm.tree.AnnotationNode;
|
||||||
import org.objectweb.asm.tree.ClassNode;
|
import org.objectweb.asm.tree.ClassNode;
|
||||||
import org.objectweb.asm.tree.FieldNode;
|
|
||||||
import org.objectweb.asm.tree.MethodNode;
|
import org.objectweb.asm.tree.MethodNode;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.Marker;
|
import org.slf4j.Marker;
|
||||||
import org.slf4j.MarkerFactory;
|
import org.slf4j.MarkerFactory;
|
||||||
|
|
||||||
public class RuntimeDistCleaner implements ILaunchPluginService
|
public class RuntimeDistCleaner implements ILaunchPluginService {
|
||||||
{
|
|
||||||
private static final Logger LOGGER = LogUtils.getLogger();
|
private static final Logger LOGGER = LogUtils.getLogger();
|
||||||
private static final Marker DISTXFORM = MarkerFactory.getMarker("DISTXFORM");
|
private static final Marker DISTXFORM = MarkerFactory.getMarker("DISTXFORM");
|
||||||
private static String DIST;
|
private static String DIST;
|
||||||
private static final String ONLYIN = Type.getDescriptor(OnlyIn.class);
|
private static final String ONLYIN = Type.getDescriptor(OnlyIn.class);
|
||||||
private static final String ONLYINS = Type.getDescriptor(OnlyIns.class);
|
private static final String ONLYINS = Type.getDescriptor(OnlyIns.class);
|
||||||
|
private static final String MOD = "Lnet/minecraftforge/fml/common/Mod;";
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String name()
|
public String name() {
|
||||||
{
|
|
||||||
return "runtimedistcleaner";
|
return "runtimedistcleaner";
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int processClassWithFlags(final Phase phase, final ClassNode classNode, final Type classType, final String reason)
|
public int processClassWithFlags(final Phase phase, final ClassNode classNode, final Type classType, final String reason) {
|
||||||
{
|
var changed = false;
|
||||||
AtomicBoolean changes = new AtomicBoolean();
|
|
||||||
if (remove(classNode.visibleAnnotations, DIST))
|
var annotations = unpack(classNode.visibleAnnotations);
|
||||||
{
|
|
||||||
|
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 (classNode.interfaces != null )
|
if (!FMLEnvironment.production && !annotations.isEmpty() && hasModAnnotation(classNode.visibleAnnotations)) {
|
||||||
{
|
LOGGER.error(DISTXFORM, "Attempted to load class {} with @Mod and @OnlyIn/@OnlyIns annotations", classNode.name);
|
||||||
unpack(classNode.visibleAnnotations).stream()
|
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");
|
||||||
.filter(ann->Objects.equals(ann.desc, ONLYIN))
|
}
|
||||||
.filter(ann->ann.values.indexOf("_interface") != -1)
|
|
||||||
.filter(ann->!Objects.equals(((String[])ann.values.get(ann.values.indexOf("value") + 1))[1], DIST))
|
if (classNode.interfaces != null && !classNode.interfaces.isEmpty()) {
|
||||||
.map(ann -> ((Type)ann.values.get(ann.values.indexOf("_interface") + 1)).getInternalName())
|
for (var ann : annotations) {
|
||||||
.forEach(intf -> {
|
if (ann.intf == null || DIST.equals(ann.side))
|
||||||
if (classNode.interfaces.remove(intf)) {
|
continue;
|
||||||
LOGGER.debug(DISTXFORM,"Removing Interface: {} implements {}", classNode.name, intf);
|
|
||||||
changes.compareAndSet(false, true);
|
if (classNode.interfaces.remove(ann.intf)) {
|
||||||
}
|
LOGGER.debug(DISTXFORM,"Removing Interface: {} implements {}", classNode.name, ann.intf);
|
||||||
});
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
//Remove Class level @OnlyIn/@OnlyIns annotations, this is important if anyone gets ambitious and tries to reflect an annotation with _interface set.
|
//Remove Class level @OnlyIn/@OnlyIns annotations, this is important if anyone gets ambitious and tries to reflect an annotation with _interface set.
|
||||||
if (classNode.visibleAnnotations != null) {
|
if (classNode.visibleAnnotations != null) {
|
||||||
Iterator<AnnotationNode> itr = classNode.visibleAnnotations.iterator();
|
for (var itr = classNode.visibleAnnotations.iterator(); itr.hasNext(); ) {
|
||||||
while (itr.hasNext()) {
|
var ann = itr.next();
|
||||||
AnnotationNode ann = itr.next();
|
if (ONLYIN.equals(ann.desc) || ONLYINS.equals(ann.desc)) {
|
||||||
if (Objects.equals(ann.desc, ONLYIN) || Objects.equals(ann.desc, ONLYINS)) {
|
LOGGER.debug(DISTXFORM, "Removing Class Annotation: {} @{}", classNode.name, ann.desc);
|
||||||
LOGGER.debug(DISTXFORM,"Removing Class Annotation: {} @{}", classNode.name, ann.desc);
|
|
||||||
itr.remove();
|
itr.remove();
|
||||||
changes.compareAndSet(false, true);
|
changed = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Iterator<FieldNode> fields = classNode.fields.iterator();
|
for (var itr = classNode.fields.iterator(); itr.hasNext(); ) {
|
||||||
while(fields.hasNext())
|
var field = itr.next();
|
||||||
{
|
if (remove(unpack(field.visibleAnnotations), DIST)) {
|
||||||
FieldNode field = fields.next();
|
LOGGER.debug(DISTXFORM, "Removing field: {}.{}", classNode.name, field.name);
|
||||||
if (remove(field.visibleAnnotations, DIST))
|
itr.remove();
|
||||||
{
|
changed = true;
|
||||||
LOGGER.debug(DISTXFORM,"Removing field: {}.{}", classNode.name, field.name);
|
|
||||||
fields.remove();
|
|
||||||
changes.compareAndSet(false, true);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
LambdaGatherer lambdaGatherer = new LambdaGatherer();
|
var lambdaGatherer = new LambdaGatherer();
|
||||||
Iterator<MethodNode> methods = classNode.methods.iterator();
|
for (var itr = classNode.methods.iterator(); itr.hasNext(); ) {
|
||||||
while(methods.hasNext())
|
var method = itr.next();
|
||||||
{
|
if (remove(unpack(method.visibleAnnotations), DIST)) {
|
||||||
MethodNode method = methods.next();
|
LOGGER.debug(DISTXFORM, "Removing method: {}.{}{}", classNode.name, method.name, method.desc);
|
||||||
if (remove(method.visibleAnnotations, DIST))
|
itr.remove();
|
||||||
{
|
|
||||||
LOGGER.debug(DISTXFORM,"Removing method: {}.{}{}", classNode.name, method.name, method.desc);
|
|
||||||
methods.remove();
|
|
||||||
lambdaGatherer.accept(method);
|
lambdaGatherer.accept(method);
|
||||||
changes.compareAndSet(false, true);
|
changed = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// remove dynamic synthetic lambda methods that are inside of removed methods
|
// remove dynamic synthetic lambda methods that are inside of removed methods
|
||||||
for (List<Handle> dynamicLambdaHandles = lambdaGatherer.getDynamicLambdaHandles();
|
for (List<Handle> handles = lambdaGatherer.getDynamicLambdaHandles();
|
||||||
!dynamicLambdaHandles.isEmpty(); dynamicLambdaHandles = lambdaGatherer.getDynamicLambdaHandles())
|
!handles.isEmpty(); handles = lambdaGatherer.getDynamicLambdaHandles()) {
|
||||||
{
|
|
||||||
lambdaGatherer = new LambdaGatherer();
|
lambdaGatherer = new LambdaGatherer();
|
||||||
methods = classNode.methods.iterator();
|
for (var itr = classNode.methods.iterator(); itr.hasNext(); ) {
|
||||||
while (methods.hasNext())
|
MethodNode method = itr.next();
|
||||||
{
|
if ((method.access & Opcodes.ACC_SYNTHETIC) == 0)
|
||||||
MethodNode method = methods.next();
|
continue;
|
||||||
if ((method.access & Opcodes.ACC_SYNTHETIC) == 0) continue;
|
|
||||||
for (Handle dynamicLambdaHandle : dynamicLambdaHandles)
|
for (var handle : handles) {
|
||||||
{
|
if (method.name.equals(handle.getName()) && method.desc.equals(handle.getDesc())) {
|
||||||
if (method.name.equals(dynamicLambdaHandle.getName()) && method.desc.equals(dynamicLambdaHandle.getDesc()))
|
LOGGER.debug(DISTXFORM, "Removing lambda method: {}.{}{}", classNode.name, method.name, method.desc);
|
||||||
{
|
itr.remove();
|
||||||
LOGGER.debug(DISTXFORM,"Removing lambda method: {}.{}{}", classNode.name, method.name, method.desc);
|
|
||||||
methods.remove();
|
|
||||||
lambdaGatherer.accept(method);
|
lambdaGatherer.accept(method);
|
||||||
changes.compareAndSet(false, true);
|
changed = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return changes.get() ? ComputeFlags.SIMPLE_REWRITE : ComputeFlags.NO_REWRITE;
|
|
||||||
|
return changed ? ComputeFlags.SIMPLE_REWRITE : ComputeFlags.NO_REWRITE;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static record Target(String side, String intf) {
|
||||||
|
static Target from(final AnnotationNode node) {
|
||||||
|
var idx = node.values.indexOf("value");
|
||||||
|
var value = (String[])node.values.get(idx + 1); // Enums are stored as [Type, Value]
|
||||||
|
|
||||||
|
idx = node.values.indexOf("_interface");
|
||||||
|
if (idx == -1)
|
||||||
|
return new Target(value[1], null);
|
||||||
|
|
||||||
|
var intf = (Type)node.values.get(idx + 1);
|
||||||
|
return new Target(value[1], intf.getInternalName());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unpack any OnlyIn or OnlyIns annotations to Target objects.
|
||||||
|
*/
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
private static List<AnnotationNode> unpack(final List<AnnotationNode> anns) {
|
private static List<Target> unpack(final List<AnnotationNode> anns) {
|
||||||
if (anns == null) return Collections.emptyList();
|
if (anns == null || anns.isEmpty())
|
||||||
List<AnnotationNode> ret = anns.stream().filter(ann->Objects.equals(ann.desc, ONLYIN)).collect(Collectors.toList());
|
return Collections.emptyList();
|
||||||
anns.stream().filter(ann->Objects.equals(ann.desc, ONLYINS) && ann.values != null)
|
|
||||||
.map( ann -> (List<AnnotationNode>)ann.values.get(ann.values.indexOf("value") + 1))
|
var ret = new ArrayList<Target>();
|
||||||
.filter(v -> v != null)
|
for (var node : anns) {
|
||||||
.forEach(v -> v.forEach(ret::add));
|
if (ONLYIN.equals(node.desc))
|
||||||
|
ret.add(Target.from(node));
|
||||||
|
else if (ONLYINS.equals(node.desc)) {
|
||||||
|
if (node.values == null || node.values.isEmpty())
|
||||||
|
continue;
|
||||||
|
|
||||||
|
int idx = node.values.indexOf("value");
|
||||||
|
if (idx == -1)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
var subNodes = (List<AnnotationNode>)node.values.get(idx + 1);
|
||||||
|
if (subNodes != null) {
|
||||||
|
for (var sub : subNodes)
|
||||||
|
ret.add(Target.from(sub));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean remove(final List<AnnotationNode> anns, final String side)
|
private static boolean remove(final List<Target> targets, final String side) {
|
||||||
{
|
for (var target : targets) {
|
||||||
return unpack(anns).stream().
|
if (target.intf == null && !side.equals(target.side))
|
||||||
filter(ann->Objects.equals(ann.desc, ONLYIN)).
|
return true;
|
||||||
filter(ann->ann.values.indexOf("_interface") == -1).
|
}
|
||||||
anyMatch(ann -> !Objects.equals(((String[])ann.values.get(ann.values.indexOf("value")+1))[1], side));
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean hasModAnnotation(final List<AnnotationNode> anns) {
|
||||||
|
if (anns == null || anns.isEmpty())
|
||||||
|
return false;
|
||||||
|
|
||||||
|
for (var ann : anns) {
|
||||||
|
if (ann.desc.equals(MOD))
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
@Override
|
@Override
|
||||||
public Consumer<Dist> getExtension()
|
public Consumer<Dist> getExtension() {
|
||||||
{
|
return s -> {
|
||||||
return (s)-> {
|
|
||||||
DIST = s.name();
|
DIST = s.name();
|
||||||
LOGGER.debug(DISTXFORM, "Configuring for Dist {}", DIST);
|
LOGGER.debug(DISTXFORM, "Configuring for Dist {}", DIST);
|
||||||
};
|
};
|
||||||
@@ -169,9 +202,15 @@ public class RuntimeDistCleaner implements ILaunchPluginService
|
|||||||
private static final EnumSet<Phase> NAY = EnumSet.noneOf(Phase.class);
|
private static final EnumSet<Phase> NAY = EnumSet.noneOf(Phase.class);
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty)
|
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty) {
|
||||||
{
|
if (isEmpty)
|
||||||
return isEmpty ? NAY : YAY;
|
return NAY;
|
||||||
|
|
||||||
|
String internalName = classType.getInternalName();
|
||||||
|
if (internalName.startsWith("net/minecraftforge/"))
|
||||||
|
return NAY;
|
||||||
|
|
||||||
|
return YAY;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static class LambdaGatherer extends MethodVisitor {
|
private static class LambdaGatherer extends MethodVisitor {
|
||||||
@@ -186,23 +225,21 @@ public class RuntimeDistCleaner implements ILaunchPluginService
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void accept(MethodNode method) {
|
public void accept(MethodNode method) {
|
||||||
Streams.stream(method.instructions.iterator()).
|
for (var insn : method.instructions) {
|
||||||
filter(insnNode->insnNode.getType() == AbstractInsnNode.INVOKE_DYNAMIC_INSN).
|
if (insn.getType() == AbstractInsnNode.INVOKE_DYNAMIC_INSN)
|
||||||
forEach(insnNode->insnNode.accept(this));
|
insn.accept(this);
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void visitInvokeDynamicInsn(String name, String desc, Handle bsm, Object... bsmArgs)
|
|
||||||
{
|
|
||||||
if (META_FACTORY.equals(bsm))
|
|
||||||
{
|
|
||||||
Handle dynamicLambdaHandle = (Handle) bsmArgs[1];
|
|
||||||
dynamicLambdaHandles.add(dynamicLambdaHandle);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<Handle> getDynamicLambdaHandles()
|
@Override
|
||||||
{
|
public void visitInvokeDynamicInsn(String name, String desc, Handle bsm, Object... bsmArgs) {
|
||||||
|
if (META_FACTORY.equals(bsm)) {
|
||||||
|
var handle = (Handle)bsmArgs[1];
|
||||||
|
dynamicLambdaHandles.add(handle);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Handle> getDynamicLambdaHandles() {
|
||||||
return dynamicLambdaHandles;
|
return dynamicLambdaHandles;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,16 +14,17 @@ import org.apache.commons.lang3.text.StrSubstitutor;
|
|||||||
|
|
||||||
@SuppressWarnings("deprecation")
|
@SuppressWarnings("deprecation")
|
||||||
public class StringSubstitutor {
|
public class StringSubstitutor {
|
||||||
|
private static final Map<String, String> GLOBALS = Map.of(
|
||||||
|
"mcVersion", FMLLoader.versionInfo().mcVersion(),
|
||||||
|
"forgeVersion", FMLLoader.versionInfo().forgeVersion()
|
||||||
|
);
|
||||||
|
|
||||||
public static String replace(final String in, final ModFile file) {
|
public static String replace(final String in, final ModFile file) {
|
||||||
return new StrSubstitutor(getStringLookup(file)).replace(in);
|
return new StrSubstitutor(getStringLookup(file)).replace(in);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static StrLookup<String> getStringLookup(final ModFile file) {
|
private static StrLookup<String> getStringLookup(final ModFile file) {
|
||||||
var globals = Map.of(
|
return new StrLookup<>() {
|
||||||
"mcVersion", FMLLoader.versionInfo().mcVersion(),
|
|
||||||
"forgeVersion", FMLLoader.versionInfo().forgeVersion()
|
|
||||||
);
|
|
||||||
return new StrLookup<String>() {
|
|
||||||
@Override
|
@Override
|
||||||
public String lookup(String key) {
|
public String lookup(String key) {
|
||||||
var parts = key.split("\\.");
|
var parts = key.split("\\.");
|
||||||
@@ -32,7 +33,7 @@ public class StringSubstitutor {
|
|||||||
var pfx = parts[0];
|
var pfx = parts[0];
|
||||||
|
|
||||||
if ("global".equals(pfx))
|
if ("global".equals(pfx))
|
||||||
return globals.get(parts[1]);
|
return GLOBALS.get(parts[1]);
|
||||||
else if ("file".equals(pfx) && file != null)
|
else if ("file".equals(pfx) && file != null)
|
||||||
return String.valueOf(file.getSubstitutionMap().get().get(parts[1]));
|
return String.valueOf(file.getSubstitutionMap().get().get(parts[1]));
|
||||||
|
|
||||||
|
|||||||
@@ -47,12 +47,12 @@ public class UniqueModListBuilder
|
|||||||
|
|
||||||
// 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
|
||||||
uniqueModList = modFilesByFirstId.entrySet().stream()
|
uniqueModList = modFilesByFirstId.entrySet().stream()
|
||||||
.map(this::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
|
||||||
uniqueLibListWithVersion = libFilesWithVersionByModuleName.entrySet().stream()
|
uniqueLibListWithVersion = libFilesWithVersionByModuleName.entrySet().stream()
|
||||||
.map(this::selectNewestModInfo)
|
.map(UniqueModListBuilder::selectNewestModInfo)
|
||||||
.toList();
|
.toList();
|
||||||
|
|
||||||
// Transform to the full mod id list
|
// Transform to the full mod id list
|
||||||
@@ -75,7 +75,7 @@ public class UniqueModListBuilder
|
|||||||
final List<String> dupedModErrors = modIds.values().stream()
|
final List<String> dupedModErrors = modIds.values().stream()
|
||||||
.filter(modInfos -> modInfos.size() > 1)
|
.filter(modInfos -> modInfos.size() > 1)
|
||||||
.map(mods -> String.format("\tMod ID: '%s' from mod files: %s",
|
.map(mods -> String.format("\tMod ID: '%s' from mod files: %s",
|
||||||
mods.get(0).getModId(),
|
mods.getFirst().getModId(),
|
||||||
mods.stream()
|
mods.stream()
|
||||||
.map(modInfo -> modInfo.getOwningFile().getFile().getFileName()).collect(joining(", "))
|
.map(modInfo -> modInfo.getOwningFile().getFile().getFileName()).collect(joining(", "))
|
||||||
)).toList();
|
)).toList();
|
||||||
@@ -91,9 +91,8 @@ public class UniqueModListBuilder
|
|||||||
final List<String> dupedLibErrors = versionedLibIds.values().stream()
|
final List<String> dupedLibErrors = versionedLibIds.values().stream()
|
||||||
.filter(modFiles -> modFiles.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.get(0)),
|
getModId(mods.getFirst()),
|
||||||
mods.stream()
|
mods.stream().map(ModFile::getFileName).collect(joining(", "))
|
||||||
.map(modFile -> modFile.getFileName()).collect(joining(", "))
|
|
||||||
)).toList();
|
)).toList();
|
||||||
|
|
||||||
if (!dupedLibErrors.isEmpty()) {
|
if (!dupedLibErrors.isEmpty()) {
|
||||||
@@ -107,25 +106,23 @@ public class UniqueModListBuilder
|
|||||||
final Map<String, List<ModFile>> uniqueModFilesByFirstId = uniqueModList.stream()
|
final Map<String, List<ModFile>> uniqueModFilesByFirstId = uniqueModList.stream()
|
||||||
.collect(groupingBy(UniqueModListBuilder::getModId));
|
.collect(groupingBy(UniqueModListBuilder::getModId));
|
||||||
|
|
||||||
final List<ModFile> loadedList = new ArrayList<>();
|
final List<ModFile> loadedList = new ArrayList<>(uniqueModList);
|
||||||
loadedList.addAll(uniqueModList);
|
|
||||||
loadedList.addAll(uniqueLibListWithVersion);
|
loadedList.addAll(uniqueLibListWithVersion);
|
||||||
|
|
||||||
return new UniqueModListData(loadedList, uniqueModFilesByFirstId);
|
return new UniqueModListData(loadedList, uniqueModFilesByFirstId);
|
||||||
}
|
}
|
||||||
|
|
||||||
private ModFile selectNewestModInfo(Map.Entry<String, List<ModFile>> fullList) {
|
private static ModFile selectNewestModInfo(Map.Entry<String, List<ModFile>> fullList) {
|
||||||
List<ModFile> modInfoList = fullList.getValue();
|
List<ModFile> modInfoList = fullList.getValue();
|
||||||
if (modInfoList.size() > 1) {
|
if (modInfoList.size() > 1) {
|
||||||
LOGGER.debug("Found {} mods for first modid {}, selecting most recent based on version data", modInfoList.size(), fullList.getKey());
|
LOGGER.debug("Found {} mods for first modid {}, selecting most recent based on version data", modInfoList.size(), fullList.getKey());
|
||||||
modInfoList.sort(Comparator.comparing(this::getVersion).reversed());
|
modInfoList.sort(Comparator.comparing(UniqueModListBuilder::getVersion).reversed());
|
||||||
LOGGER.debug("Selected file {} for modid {} with version {}", modInfoList.get(0).getFileName(), fullList.getKey(), this.getVersion(modInfoList.get(0)));
|
LOGGER.debug("Selected file {} for modid {} with version {}", modInfoList.getFirst().getFileName(), fullList.getKey(), getVersion(modInfoList.getFirst()));
|
||||||
}
|
}
|
||||||
return modInfoList.get(0);
|
return modInfoList.get(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
private ArtifactVersion getVersion(final ModFile mf)
|
private static ArtifactVersion getVersion(final ModFile mf) {
|
||||||
{
|
|
||||||
if (mf.getModFileInfo() == null || mf.getModInfos() == null || mf.getModInfos().isEmpty()) {
|
if (mf.getModFileInfo() == null || mf.getModInfos() == null || mf.getModInfos().isEmpty()) {
|
||||||
return mf.getJarVersion();
|
return mf.getJarVersion();
|
||||||
}
|
}
|
||||||
@@ -138,7 +135,7 @@ public class UniqueModListBuilder
|
|||||||
return modFile.getSecureJar().name();
|
return modFile.getSecureJar().name();
|
||||||
}
|
}
|
||||||
|
|
||||||
return modFile.getModFileInfo().moduleName();
|
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) {}
|
||||||
|
|||||||
@@ -5,33 +5,53 @@
|
|||||||
|
|
||||||
package net.minecraftforge.fml.loading;
|
package net.minecraftforge.fml.loading;
|
||||||
|
|
||||||
import net.minecraftforge.forgespi.language.MavenVersionAdapter;
|
|
||||||
import org.apache.maven.artifact.versioning.ArtifactVersion;
|
import org.apache.maven.artifact.versioning.ArtifactVersion;
|
||||||
import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
|
import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
|
||||||
import org.apache.maven.artifact.versioning.VersionRange;
|
import org.apache.maven.artifact.versioning.VersionRange;
|
||||||
|
import org.jetbrains.annotations.ApiStatus;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.Collections;
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
import java.util.function.BiPredicate;
|
import java.util.function.BiPredicate;
|
||||||
|
|
||||||
|
@ApiStatus.Internal // since 1.21.1, will be made non-public in a later MC version
|
||||||
public class VersionSupportMatrix {
|
public class VersionSupportMatrix {
|
||||||
private static final HashMap<String, List<ArtifactVersion>> overrideVersions = new HashMap<>();
|
private static final Map<String, List<ArtifactVersion>> OVERRIDE_VERSIONS;
|
||||||
|
|
||||||
static {
|
static {
|
||||||
final ArtifactVersion version = new DefaultArtifactVersion(FMLLoader.versionInfo().mcVersion());
|
if ("1.21.1".equals(FMLLoader.versionInfo().mcVersion())) {
|
||||||
if (MavenVersionAdapter.createFromVersionSpec("[1.19.2]").containsVersion(version)) {
|
OVERRIDE_VERSIONS = Map.ofEntries(
|
||||||
// 1.19.2 is Compatible with 1.19.1
|
// 1.21.1 is compatible with 1.21
|
||||||
add("languageloader.javafml", "42");
|
entry("languageloader.javafml", "51"),
|
||||||
add("mod.minecraft", "1.19.1");
|
entry("mod.minecraft", "1.21"),
|
||||||
add("mod.forge", "42.0.9");
|
entry("mod.forge", "51.0.33")
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
OVERRIDE_VERSIONS = Collections.emptyMap();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
private static void add(String key, String value) {
|
|
||||||
overrideVersions.computeIfAbsent(key, k -> new ArrayList<>()).add(new DefaultArtifactVersion(value));
|
/**
|
||||||
}
|
* @deprecated Use {@link #testVersionSupportMatrix(VersionRange, String, String)} instead, unwrapping your BiPredicate.
|
||||||
public static <T> boolean testVersionSupportMatrix(VersionRange declaredRange, String lookupId, String type, BiPredicate<String, VersionRange> standardLookup) {
|
*/
|
||||||
|
@Deprecated(forRemoval = true, since = "1.21.1")
|
||||||
|
public static boolean testVersionSupportMatrix(VersionRange declaredRange, String lookupId, String type, BiPredicate<String, VersionRange> standardLookup) {
|
||||||
if (standardLookup.test(lookupId, declaredRange)) return true;
|
if (standardLookup.test(lookupId, declaredRange)) return true;
|
||||||
List<ArtifactVersion> custom = overrideVersions.get(type + "." + lookupId);
|
return testVersionSupportMatrix(declaredRange, lookupId, type);
|
||||||
return custom == null ? false : custom.stream().anyMatch(declaredRange::containsVersion);
|
}
|
||||||
|
|
||||||
|
public static boolean testVersionSupportMatrix(VersionRange declaredRange, String lookupId, String type) {
|
||||||
|
if (OVERRIDE_VERSIONS.isEmpty()) return false;
|
||||||
|
List<ArtifactVersion> custom = OVERRIDE_VERSIONS.get(type + "." + lookupId);
|
||||||
|
return custom != null && custom.stream().anyMatch(declaredRange::containsVersion);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Map.Entry<String, List<ArtifactVersion>> entry(String typeAndLookupId, String declaredRange) {
|
||||||
|
return Map.entry(typeAndLookupId, List.of(new DefaultArtifactVersion(declaredRange)));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Map.Entry<String, List<ArtifactVersion>> entry(String typeAndLookupId, List<String> declaredRanges) {
|
||||||
|
return Map.entry(typeAndLookupId, declaredRanges.stream().map(DefaultArtifactVersion::new).map(it -> (ArtifactVersion) it).toList());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -49,10 +49,7 @@ public class ForgeHighlight {
|
|||||||
LOGGER.warn("Failed to invoke initializeTerminal on TCA", e);
|
LOGGER.warn("Failed to invoke initializeTerminal on TCA", e);
|
||||||
}
|
}
|
||||||
if (!TerminalConsoleAppender.isAnsiSupported() && Arrays.stream(options).noneMatch(s -> s.equals("disableAnsi=true"))) {
|
if (!TerminalConsoleAppender.isAnsiSupported() && Arrays.stream(options).noneMatch(s -> s.equals("disableAnsi=true"))) {
|
||||||
List<String> optionList = new ArrayList<>();
|
options = new String[] { options[0], "disableAnsi=true" };
|
||||||
optionList.add(options[0]);
|
|
||||||
optionList.add("disableAnsi=true");
|
|
||||||
options = optionList.toArray(new String[0]);
|
|
||||||
}
|
}
|
||||||
return HighlightConverter.newInstance(config, options);
|
return HighlightConverter.newInstance(config, options);
|
||||||
}
|
}
|
||||||
|
|||||||
+83
-10
@@ -6,9 +6,9 @@
|
|||||||
package net.minecraftforge.fml.loading.moddiscovery;
|
package net.minecraftforge.fml.loading.moddiscovery;
|
||||||
|
|
||||||
import com.mojang.logging.LogUtils;
|
import com.mojang.logging.LogUtils;
|
||||||
|
|
||||||
import cpw.mods.jarhandling.JarMetadata;
|
import cpw.mods.jarhandling.JarMetadata;
|
||||||
import cpw.mods.jarhandling.SecureJar;
|
import cpw.mods.jarhandling.SecureJar;
|
||||||
import net.minecraftforge.fml.loading.EarlyLoadingException;
|
|
||||||
import net.minecraftforge.fml.loading.LogMarkers;
|
import net.minecraftforge.fml.loading.LogMarkers;
|
||||||
import net.minecraftforge.forgespi.language.IConfigurable;
|
import net.minecraftforge.forgespi.language.IConfigurable;
|
||||||
import net.minecraftforge.forgespi.language.IModFileInfo;
|
import net.minecraftforge.forgespi.language.IModFileInfo;
|
||||||
@@ -19,38 +19,59 @@ import net.minecraftforge.forgespi.locating.IModProvider;
|
|||||||
import net.minecraftforge.forgespi.locating.ModFileLoadingException;
|
import net.minecraftforge.forgespi.locating.ModFileLoadingException;
|
||||||
|
|
||||||
import org.jetbrains.annotations.ApiStatus;
|
import org.jetbrains.annotations.ApiStatus;
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.lang.module.InvalidModuleDescriptorException;
|
||||||
|
import java.lang.module.ModuleDescriptor;
|
||||||
|
import java.lang.module.ModuleDescriptor.Version;
|
||||||
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.Collections;
|
||||||
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import java.util.function.Consumer;
|
import java.util.function.Consumer;
|
||||||
import java.util.jar.JarFile;
|
import java.util.jar.JarFile;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
@ApiStatus.Internal
|
@ApiStatus.Internal
|
||||||
public abstract class AbstractModProvider implements IModProvider {
|
public abstract class AbstractModProvider implements IModProvider {
|
||||||
private static final Logger LOGGER = LogUtils.getLogger();
|
private static final Logger LOGGER = LogUtils.getLogger();
|
||||||
protected static final String MODS_TOML = "META-INF/mods.toml";
|
protected static final String MODS_TOML = "META-INF/mods.toml";
|
||||||
|
protected static final String MODULE_INFO = "module-info.class";
|
||||||
|
|
||||||
protected IModLocator.ModFileOrException createMod(Path path) {
|
protected IModLocator.ModFileOrException createMod(Path path) {
|
||||||
|
return createMod(path, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nullable
|
||||||
|
protected IModLocator.ModFileOrException createMod(Path path, boolean ignoreUnknown) {
|
||||||
|
return createMod(path, ignoreUnknown, getDefaultJarModType());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nullable
|
||||||
|
protected IModLocator.ModFileOrException createMod(Path path, boolean ignoreUnknown, String defaultType) {
|
||||||
var mjm = new ModJarMetadata();
|
var mjm = new ModJarMetadata();
|
||||||
var sj = SecureJar.from(
|
SecureJar sj = null;
|
||||||
jar -> jar.moduleDataProvider().findFile(MODS_TOML).isPresent() ? mjm : JarMetadata.from(jar, path),
|
try {
|
||||||
path
|
sj = SecureJar.from(jar -> loadMetaFromJar(jar, mjm), path);
|
||||||
);
|
} catch (Throwable t) {
|
||||||
|
return new IModLocator.ModFileOrException(null, new ModFileLoadingException("Failed to create secure jar for \"" + path + "\" - " + t.getMessage()));
|
||||||
|
}
|
||||||
|
|
||||||
IModFile mod;
|
IModFile mod;
|
||||||
var type = sj.moduleDataProvider().getManifest().getMainAttributes().getValue(ModFile.TYPE);
|
var type = sj.moduleDataProvider().getManifest().getMainAttributes().getValue(ModFile.TYPE);
|
||||||
if (type == null)
|
if (type == null)
|
||||||
type = getDefaultJarModType();
|
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, path);
|
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
|
||||||
|
mjm.setModFile(mod);
|
||||||
if (mod.getModFileInfo().getFileProperties().containsKey(ModFileInfo.NOT_A_FORGE_MOD_PROP)) {
|
if (mod.getModFileInfo().getFileProperties().containsKey(ModFileInfo.NOT_A_FORGE_MOD_PROP)) {
|
||||||
LOGGER.error(LogMarkers.SCAN, "Unable to load file \"{}\" because its mods.toml is requesting an invalid javafml loaderVersion (use \"*\" if you want to allow all versions) and is missing a forge modId dependency declaration (see the sample mods.toml in the MDK).", path);
|
LOGGER.error(LogMarkers.SCAN, "Unable to load file \"{}\" because its mods.toml is requesting an invalid javafml loaderVersion (use \"*\" if you want to allow all versions) and is missing a forge modId dependency declaration (see the sample mods.toml in the MDK).", path);
|
||||||
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())));
|
||||||
@@ -58,17 +79,68 @@ public abstract class AbstractModProvider implements IModProvider {
|
|||||||
} else if (type != null) {
|
} else if (type != null) {
|
||||||
LOGGER.debug(LogMarkers.SCAN, "Found {} mod of type {}: {}", JarFile.MANIFEST_NAME, type, path);
|
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) {
|
||||||
|
return null;
|
||||||
} else
|
} else
|
||||||
return new IModLocator.ModFileOrException(null, new ModFileLoadingException("Invalid mod file found " + path));
|
return new IModLocator.ModFileOrException(null, new ModFileLoadingException("Invalid mod file found " + path));
|
||||||
|
|
||||||
mjm.setModFile(mod);
|
|
||||||
return new IModLocator.ModFileOrException(mod, null);
|
return new IModLocator.ModFileOrException(mod, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static JarMetadata loadMetaFromJar(SecureJar jar, ModJarMetadata mjm) {
|
||||||
|
var info = jar.moduleDataProvider().open(MODULE_INFO).orElse(null);
|
||||||
|
if (info != null) {
|
||||||
|
try {
|
||||||
|
var desc = ModuleDescriptor.read(info, jar::getPackages);
|
||||||
|
var all = new HashSet<>(jar.getPackages());
|
||||||
|
all.removeAll(desc.packages());
|
||||||
|
if (!all.isEmpty()) {
|
||||||
|
var missing = all.stream().sorted().collect(Collectors.joining(", "));
|
||||||
|
LOGGER.error("Invalid module-info, missing packages " + missing);
|
||||||
|
throw new ModFileLoadingException("Invalid module-info, missing packages " + missing);
|
||||||
|
} else {
|
||||||
|
return new JarMetadata() {
|
||||||
|
@Override
|
||||||
|
public String name() {
|
||||||
|
return desc.name();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String version() {
|
||||||
|
return desc.version().map(Version::toString).or(desc::rawVersion).orElse(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ModuleDescriptor descriptor() {
|
||||||
|
return desc;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
} catch (InvalidModuleDescriptorException | IOException e) {
|
||||||
|
LOGGER.error("Failed to parse " + jar.getPrimaryPath() + " module-info", e);
|
||||||
|
throw new ModFileLoadingException("Invalid module-info: " + e.getMessage());
|
||||||
|
} finally {
|
||||||
|
try {
|
||||||
|
info.close();
|
||||||
|
} catch (IOException e) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (jar.moduleDataProvider().findFile(MODS_TOML).isEmpty())
|
||||||
|
return JarMetadata.from(jar, jar.getPrimaryPath());
|
||||||
|
|
||||||
|
return mjm;
|
||||||
|
}
|
||||||
|
|
||||||
protected IModFileInfo manifestParser(final IModFile mod) {
|
protected IModFileInfo manifestParser(final IModFile mod) {
|
||||||
var mf = mod.getSecureJar().moduleDataProvider().getManifest().getMainAttributes();
|
var mf = mod.getSecureJar().moduleDataProvider().getManifest().getMainAttributes();
|
||||||
var license = mf.getValue("LICENSE");
|
var license = mf.getValue("LICENSE");
|
||||||
var dummy = new IConfigurable() {
|
var dummy = new IConfigurable() {
|
||||||
|
@Override
|
||||||
|
public <T> Optional<T> getConfigElement(String key) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public <T> Optional<T> getConfigElement(String... key) {
|
public <T> Optional<T> getConfigElement(String... key) {
|
||||||
return Optional.empty();
|
return Optional.empty();
|
||||||
@@ -128,10 +200,11 @@ public abstract class AbstractModProvider implements IModProvider {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static final class Holder<T> {
|
private static final class Holder<T> {
|
||||||
T value;
|
private T value;
|
||||||
}
|
}
|
||||||
|
|
||||||
private record DefaultModFileInfo(IModFile mod, String license, IConfigurable configurable) implements IModFileInfo, IConfigurable {
|
private record DefaultModFileInfo(IModFile mod, String license, IConfigurable configurable) implements IModFileInfo, IConfigurable {
|
||||||
|
@Override public <T> Optional<T> getConfigElement(final String string) { return Optional.empty(); }
|
||||||
@Override public <T> Optional<T> getConfigElement(final String... strings) { return Optional.empty(); }
|
@Override public <T> Optional<T> getConfigElement(final String... strings) { return Optional.empty(); }
|
||||||
@Override public List<? extends IConfigurable> getConfigList(final String... strings) { return null; }
|
@Override public List<? extends IConfigurable> getConfigList(final String... strings) { return null; }
|
||||||
@Override public List<IModInfo> getMods() { return Collections.emptyList(); }
|
@Override public List<IModInfo> getMods() { return Collections.emptyList(); }
|
||||||
|
|||||||
+6
-5
@@ -29,6 +29,7 @@ public class BackgroundScanHandler
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static final Logger LOGGER = LogUtils.getLogger();
|
private static final Logger LOGGER = LogUtils.getLogger();
|
||||||
|
private static final boolean DEBUG = LOGGER.isErrorEnabled(LogMarkers.SCAN);
|
||||||
private final ExecutorService modContentScanner;
|
private final ExecutorService modContentScanner;
|
||||||
private final List<ModFile> modFiles;
|
private final List<ModFile> modFiles;
|
||||||
private ScanStatus status;
|
private ScanStatus status;
|
||||||
@@ -55,16 +56,16 @@ public class BackgroundScanHandler
|
|||||||
}
|
}
|
||||||
status = ScanStatus.RUNNING;
|
status = ScanStatus.RUNNING;
|
||||||
ImmediateWindowHandler.updateProgress("Scanning mod candidates");
|
ImmediateWindowHandler.updateProgress("Scanning mod candidates");
|
||||||
final CompletableFuture<ModFileScanData> future = CompletableFuture.supplyAsync(file::compileContent, modContentScanner)
|
CompletableFuture<ModFileScanData> future = CompletableFuture.supplyAsync(file::compileContent, modContentScanner)
|
||||||
.whenComplete(file::setScanResult)
|
.whenComplete(file::setScanResult);
|
||||||
.whenComplete((r,t)-> this.addCompletedFile(file,r,t));
|
if (DEBUG) future = future.whenComplete((r, t) -> addCompletedFile(file, t));
|
||||||
file.setFutureScanResult(future);
|
file.setFutureScanResult(future);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void addCompletedFile(final ModFile file, final ModFileScanData modFileScanData, final Throwable throwable) {
|
private void addCompletedFile(final ModFile file, final Throwable throwable) {
|
||||||
if (throwable != null) {
|
if (throwable != null) {
|
||||||
status = ScanStatus.ERRORED;
|
status = ScanStatus.ERRORED;
|
||||||
LOGGER.error(LogMarkers.SCAN,"An error occurred scanning file {}", file, throwable);
|
LOGGER.error(LogMarkers.SCAN, "An error occurred scanning file {}", file, throwable);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+11
-8
@@ -8,6 +8,7 @@ package net.minecraftforge.fml.loading.moddiscovery;
|
|||||||
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.fml.loading.ModDirTransformerDiscoverer;
|
||||||
import net.minecraftforge.forgespi.locating.IModLocator;
|
import net.minecraftforge.forgespi.locating.IModLocator;
|
||||||
|
|
||||||
import org.jetbrains.annotations.ApiStatus;
|
import org.jetbrains.annotations.ApiStatus;
|
||||||
@@ -17,9 +18,9 @@ import java.io.IOException;
|
|||||||
import java.net.URI;
|
import java.net.URI;
|
||||||
import java.net.URL;
|
import java.net.URL;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.nio.file.Paths;
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
|
import java.util.Comparator;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.jar.Attributes;
|
import java.util.jar.Attributes;
|
||||||
@@ -27,7 +28,7 @@ import java.util.jar.JarFile;
|
|||||||
import java.util.jar.Manifest;
|
import java.util.jar.Manifest;
|
||||||
|
|
||||||
@ApiStatus.Internal
|
@ApiStatus.Internal
|
||||||
public class ClasspathLocator extends AbstractModProvider implements IModLocator {
|
public final class ClasspathLocator extends AbstractModProvider implements IModLocator {
|
||||||
private static final Logger LOGGER = LogUtils.getLogger();
|
private static final Logger LOGGER = LogUtils.getLogger();
|
||||||
private static final Attributes.Name MOD_TYPE = new Attributes.Name("FMLModType");
|
private static final Attributes.Name MOD_TYPE = new Attributes.Name("FMLModType");
|
||||||
|
|
||||||
@@ -71,16 +72,19 @@ public class ClasspathLocator extends AbstractModProvider implements IModLocator
|
|||||||
}
|
}
|
||||||
|
|
||||||
var ret = new ArrayList<ModFileOrException>();
|
var ret = new ArrayList<ModFileOrException>();
|
||||||
for (var path : claimed)
|
for (var path : claimed) {
|
||||||
ret.add(createMod(path));
|
// Filter out anything found by the ServiceLoader
|
||||||
|
if (!ModDirTransformerDiscoverer.isServiceProvider(path))
|
||||||
|
ret.add(createMod(path));
|
||||||
|
}
|
||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<URL> getUrls(ClassLoader cl, String resource) {
|
private static List<URL> getUrls(ClassLoader cl, String resource) {
|
||||||
try {
|
try {
|
||||||
var lst = Collections.list(cl.getResources(resource));
|
var lst = Collections.list(cl.getResources(resource));
|
||||||
if (LOGGER.isDebugEnabled(LogMarkers.SCAN)) {
|
if (LOGGER.isDebugEnabled(LogMarkers.SCAN)) {
|
||||||
Collections.sort(lst, (a, b) -> a.toString().compareTo(b.toString()));
|
lst.sort(Comparator.comparing(URL::toString));
|
||||||
LOGGER.debug(LogMarkers.SCAN, "Scanning Classloader: {} for {}", cl, resource);
|
LOGGER.debug(LogMarkers.SCAN, "Scanning Classloader: {} for {}", cl, resource);
|
||||||
for (var url : lst)
|
for (var url : lst)
|
||||||
LOGGER.debug(LogMarkers.SCAN, "\t{}", url);
|
LOGGER.debug(LogMarkers.SCAN, "\t{}", url);
|
||||||
@@ -100,8 +104,7 @@ public class ClasspathLocator extends AbstractModProvider implements IModLocator
|
|||||||
len += 2;
|
len += 2;
|
||||||
}
|
}
|
||||||
str = str.substring(0, str.length() - len);
|
str = str.substring(0, str.length() - len);
|
||||||
var path = Paths.get(URI.create(str));
|
return Path.of(URI.create(str));
|
||||||
return path;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static Path getPathFromResource(ClassLoader cl, String resource) {
|
private static Path getPathFromResource(ClassLoader cl, String resource) {
|
||||||
|
|||||||
+1
-1
@@ -15,7 +15,7 @@ import java.nio.file.Path;
|
|||||||
import org.jetbrains.annotations.ApiStatus;
|
import org.jetbrains.annotations.ApiStatus;
|
||||||
|
|
||||||
@ApiStatus.Internal
|
@ApiStatus.Internal
|
||||||
public class CoreModFile implements ICoreModFile {
|
public final class CoreModFile implements ICoreModFile {
|
||||||
private final Path internalPath;
|
private final Path internalPath;
|
||||||
private final ModFile file;
|
private final ModFile file;
|
||||||
private final String name;
|
private final String name;
|
||||||
|
|||||||
+17
-10
@@ -6,7 +6,6 @@
|
|||||||
package net.minecraftforge.fml.loading.moddiscovery;
|
package net.minecraftforge.fml.loading.moddiscovery;
|
||||||
|
|
||||||
import com.google.common.collect.ImmutableMap;
|
import com.google.common.collect.ImmutableMap;
|
||||||
import com.google.common.collect.Lists;
|
|
||||||
import com.mojang.logging.LogUtils;
|
import com.mojang.logging.LogUtils;
|
||||||
import net.minecraftforge.fml.loading.EarlyLoadingException;
|
import net.minecraftforge.fml.loading.EarlyLoadingException;
|
||||||
import net.minecraftforge.forgespi.language.IModInfo;
|
import net.minecraftforge.forgespi.language.IModInfo;
|
||||||
@@ -26,6 +25,7 @@ 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;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@@ -51,7 +51,7 @@ public class JarInJarDependencyLocator extends AbstractModProvider implements ID
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<IModFile> scanMods(Iterable<IModFile> loadedMods) {
|
public List<IModFile> scanMods(Iterable<IModFile> loadedMods) {
|
||||||
final List<IModFile> sources = Lists.newArrayList();
|
final List<IModFile> sources = new ArrayList<>();
|
||||||
loadedMods.forEach(sources::add);
|
loadedMods.forEach(sources::add);
|
||||||
|
|
||||||
var dependenciesToLoad = JarSelector.detectAndSelect(
|
var dependenciesToLoad = JarSelector.detectAndSelect(
|
||||||
@@ -83,7 +83,14 @@ public class JarInJarDependencyLocator extends AbstractModProvider implements ID
|
|||||||
final Map<String, ?> outerFsArgs = ImmutableMap.of("packagePath", pathInModFile);
|
final Map<String, ?> outerFsArgs = ImmutableMap.of("packagePath", pathInModFile);
|
||||||
final FileSystem zipFS = FileSystems.newFileSystem(filePathUri, outerFsArgs);
|
final FileSystem zipFS = FileSystems.newFileSystem(filePathUri, outerFsArgs);
|
||||||
final Path pathInFS = zipFS.getPath("/");
|
final Path pathInFS = zipFS.getPath("/");
|
||||||
return Optional.of(createMod(pathInFS).file());
|
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) {
|
} catch (Exception e) {
|
||||||
LOGGER.error("Failed to load mod file {} from {}", path, file.getFileName());
|
LOGGER.error("Failed to load mod file {} from {}", path, file.getFileName());
|
||||||
final RuntimeException exception = new ModFileLoadingException("Failed to load mod file " + file.getFileName());
|
final RuntimeException exception = new ModFileLoadingException("Failed to load mod file " + file.getFileName());
|
||||||
@@ -95,34 +102,34 @@ public class JarInJarDependencyLocator extends AbstractModProvider implements ID
|
|||||||
protected EarlyLoadingException exception(Collection<JarSelector.ResolutionFailureInformation<IModFile>> failedDependencies) {
|
protected EarlyLoadingException exception(Collection<JarSelector.ResolutionFailureInformation<IModFile>> failedDependencies) {
|
||||||
final List<EarlyLoadingException.ExceptionData> errors = failedDependencies.stream()
|
final List<EarlyLoadingException.ExceptionData> errors = failedDependencies.stream()
|
||||||
.filter(entry -> !entry.sources().isEmpty()) //Should never be the case, but just to be sure
|
.filter(entry -> !entry.sources().isEmpty()) //Should never be the case, but just to be sure
|
||||||
.map(this::buildExceptionData)
|
.map(JarInJarDependencyLocator::buildExceptionData)
|
||||||
.toList();
|
.toList();
|
||||||
|
|
||||||
return new EarlyLoadingException(failedDependencies.size() + " Dependency restrictions were not met.", null, errors);
|
return new EarlyLoadingException(failedDependencies.size() + " Dependency restrictions were not met.", null, errors);
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
private EarlyLoadingException.ExceptionData buildExceptionData(JarSelector.ResolutionFailureInformation<IModFile> entry) {
|
private static EarlyLoadingException.ExceptionData buildExceptionData(JarSelector.ResolutionFailureInformation<IModFile> entry) {
|
||||||
return new EarlyLoadingException.ExceptionData(
|
return new EarlyLoadingException.ExceptionData(
|
||||||
getErrorTranslationKey(entry),
|
getErrorTranslationKey(entry),
|
||||||
entry.identifier().group() + ":" + entry.identifier().artifact(),
|
entry.identifier().group() + ":" + entry.identifier().artifact(),
|
||||||
entry.sources()
|
entry.sources()
|
||||||
.stream()
|
.stream()
|
||||||
.flatMap(this::getModWithVersionRangeStream)
|
.flatMap(JarInJarDependencyLocator::getModWithVersionRangeStream)
|
||||||
.map(this::formatError)
|
.map(JarInJarDependencyLocator::formatError)
|
||||||
.collect(Collectors.joining(", "))
|
.collect(Collectors.joining(", "))
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
private String getErrorTranslationKey(JarSelector.ResolutionFailureInformation<IModFile> entry) {
|
private static String getErrorTranslationKey(JarSelector.ResolutionFailureInformation<IModFile> entry) {
|
||||||
return entry.failureReason() == JarSelector.FailureReason.VERSION_RESOLUTION_FAILED ?
|
return entry.failureReason() == JarSelector.FailureReason.VERSION_RESOLUTION_FAILED ?
|
||||||
"fml.dependencyloading.conflictingdependencies" :
|
"fml.dependencyloading.conflictingdependencies" :
|
||||||
"fml.dependencyloading.mismatchedcontaineddependencies";
|
"fml.dependencyloading.mismatchedcontaineddependencies";
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
private Stream<ModWithVersionRange> getModWithVersionRangeStream(JarSelector.SourceWithRequestedVersionRange<IModFile> file) {
|
private static Stream<ModWithVersionRange> getModWithVersionRangeStream(JarSelector.SourceWithRequestedVersionRange<IModFile> file) {
|
||||||
return file.sources()
|
return file.sources()
|
||||||
.stream()
|
.stream()
|
||||||
.map(IModFile::getModFileInfo)
|
.map(IModFile::getModFileInfo)
|
||||||
@@ -145,7 +152,7 @@ public class JarInJarDependencyLocator extends AbstractModProvider implements ID
|
|||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
private String formatError(ModWithVersionRange modWithVersionRange){
|
private static String formatError(ModWithVersionRange modWithVersionRange){
|
||||||
return YELLOW + modWithVersionRange.modInfo().getModId() + RESET + " - " +
|
return YELLOW + modWithVersionRange.modInfo().getModId() + RESET + " - " +
|
||||||
RED + modWithVersionRange.versionRange().toString() + RESET + " - " +
|
RED + modWithVersionRange.versionRange().toString() + RESET + " - " +
|
||||||
GREEN + modWithVersionRange.artifactVersion().toString() + RESET;
|
GREEN + modWithVersionRange.artifactVersion().toString() + RESET;
|
||||||
|
|||||||
+6
-8
@@ -18,24 +18,22 @@ import java.util.List;
|
|||||||
import org.jetbrains.annotations.ApiStatus;
|
import org.jetbrains.annotations.ApiStatus;
|
||||||
|
|
||||||
@ApiStatus.Internal
|
@ApiStatus.Internal
|
||||||
public class MinecraftLocator extends AbstractModProvider implements IModLocator {
|
public final class MinecraftLocator extends AbstractModProvider implements IModLocator {
|
||||||
@Override
|
@Override
|
||||||
public List<IModLocator.ModFileOrException> scanMods() {
|
public List<IModLocator.ModFileOrException> scanMods() {
|
||||||
var minecraft = FMLLoader.getLaunchHandler().getMinecraftPaths();
|
var minecraft = FMLLoader.getLaunchHandler().getMinecraftPaths();
|
||||||
|
var paths = minecraft.toArray(Path[]::new);
|
||||||
|
|
||||||
// Minecraft itself.
|
// Minecraft itself.
|
||||||
var meta = new ModJarMetadata();
|
var meta = new ModJarMetadata();
|
||||||
var mcjar = SecureJar.from(
|
var mcjar = SecureJar.from(jar -> meta, paths);
|
||||||
jar -> meta,
|
var mc = ModFileFactory.FACTORY.build(mcjar, this, MinecraftLocator::buildMinecraftTOML);
|
||||||
minecraft.toArray(Path[]::new)
|
|
||||||
);
|
|
||||||
var mc = ModFileFactory.FACTORY.build(mcjar, this, this::buildMinecraftTOML);
|
|
||||||
meta.setModFile(mc);
|
meta.setModFile(mc);
|
||||||
|
|
||||||
return List.of(new ModFileOrException(mc, null));
|
return List.of(new ModFileOrException(mc, null));
|
||||||
}
|
}
|
||||||
|
|
||||||
private IModFileInfo buildMinecraftTOML(final IModFile iModFile) {
|
private static IModFileInfo buildMinecraftTOML(final IModFile iModFile) {
|
||||||
// We haven't changed this in years, and I can't be asked right now to special case this one file in the path.
|
// We haven't changed this in years, and I can't be asked right now to special case this one file in the path.
|
||||||
final var conf = Config.inMemory();
|
final var conf = Config.inMemory();
|
||||||
conf.set("modLoader", "minecraft");
|
conf.set("modLoader", "minecraft");
|
||||||
@@ -52,7 +50,7 @@ public class MinecraftLocator extends AbstractModProvider implements IModLocator
|
|||||||
conf.set("mods", List.of(mods));
|
conf.set("mods", List.of(mods));
|
||||||
|
|
||||||
var configWrapper = new NightConfigWrapper(conf);
|
var configWrapper = new NightConfigWrapper(conf);
|
||||||
return new ModFileInfo((ModFile)iModFile, configWrapper, configWrapper::setFile, List.of());
|
return new ModFileInfo((ModFile) iModFile, configWrapper, configWrapper::setFile);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
+13
-12
@@ -6,7 +6,6 @@
|
|||||||
package net.minecraftforge.fml.loading.moddiscovery;
|
package net.minecraftforge.fml.loading.moddiscovery;
|
||||||
|
|
||||||
import com.google.common.collect.ImmutableList;
|
import com.google.common.collect.ImmutableList;
|
||||||
import com.google.common.collect.Maps;
|
|
||||||
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;
|
||||||
@@ -28,6 +27,7 @@ import org.jetbrains.annotations.ApiStatus;
|
|||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.EnumMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
@@ -49,17 +49,19 @@ public class ModDiscoverer {
|
|||||||
modLocators = ServiceLoader.load(moduleLayerManager.getLayer(IModuleLayerManager.Layer.SERVICE).orElseThrow(), IModLocator.class);
|
modLocators = ServiceLoader.load(moduleLayerManager.getLayer(IModuleLayerManager.Layer.SERVICE).orElseThrow(), IModLocator.class);
|
||||||
dependencyLocators = ServiceLoader.load(moduleLayerManager.getLayer(IModuleLayerManager.Layer.SERVICE).orElseThrow(), IDependencyLocator.class);
|
dependencyLocators = ServiceLoader.load(moduleLayerManager.getLayer(IModuleLayerManager.Layer.SERVICE).orElseThrow(), IDependencyLocator.class);
|
||||||
modLocatorList = ServiceLoaderUtils.streamServiceLoader(()-> modLocators, sce->LOGGER.error("Failed to load mod locator list", sce)).collect(Collectors.toList());
|
modLocatorList = ServiceLoaderUtils.streamServiceLoader(()-> modLocators, sce->LOGGER.error("Failed to load mod locator list", sce)).collect(Collectors.toList());
|
||||||
modLocatorList.forEach(l->l.initArguments(arguments));
|
for (IModLocator iModLocator : modLocatorList) {
|
||||||
|
iModLocator.initArguments(arguments);
|
||||||
|
}
|
||||||
dependencyLocatorList = ServiceLoaderUtils.streamServiceLoader(()-> dependencyLocators, sce->LOGGER.error("Failed to load dependency locator list", sce)).collect(Collectors.toList());
|
dependencyLocatorList = ServiceLoaderUtils.streamServiceLoader(()-> dependencyLocators, sce->LOGGER.error("Failed to load dependency locator list", sce)).collect(Collectors.toList());
|
||||||
dependencyLocatorList.forEach(l->l.initArguments(arguments));
|
for (IDependencyLocator l : dependencyLocatorList) {
|
||||||
|
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(",")));
|
||||||
}
|
|
||||||
if (LOGGER.isDebugEnabled(LogMarkers.CORE))
|
|
||||||
{
|
|
||||||
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(",")));
|
||||||
@@ -126,7 +128,7 @@ public 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 = Maps.newHashMap();
|
Map<IModFile.Type, List<ModFile>> modFilesMap = new EnumMap<>(IModFile.Type.class);
|
||||||
try {
|
try {
|
||||||
final UniqueModListBuilder modsUniqueListBuilder = new UniqueModListBuilder(loadedFiles);
|
final UniqueModListBuilder modsUniqueListBuilder = new UniqueModListBuilder(loadedFiles);
|
||||||
final UniqueModListBuilder.UniqueModListData uniqueModsData = modsUniqueListBuilder.buildUniqueList();
|
final UniqueModListBuilder.UniqueModListData uniqueModsData = modsUniqueListBuilder.buildUniqueList();
|
||||||
@@ -134,7 +136,7 @@ public class ModDiscoverer {
|
|||||||
//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.
|
||||||
modFilesMap = uniqueModsData.modFiles().stream()
|
modFilesMap = uniqueModsData.modFiles().stream()
|
||||||
.collect(Collectors.groupingBy(IModFile::getType));
|
.collect(Collectors.groupingBy(IModFile::getType, () -> new EnumMap<>(IModFile.Type.class), Collectors.toList()));
|
||||||
loadedFiles = uniqueModsData.modFiles();
|
loadedFiles = uniqueModsData.modFiles();
|
||||||
}
|
}
|
||||||
catch (EarlyLoadingException exception) {
|
catch (EarlyLoadingException exception) {
|
||||||
@@ -171,11 +173,11 @@ public class ModDiscoverer {
|
|||||||
|
|
||||||
//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()
|
||||||
.collect(Collectors.groupingBy(IModFile::getType));
|
.collect(Collectors.groupingBy(IModFile::getType, () -> new EnumMap<>(IModFile.Type.class), Collectors.toList()));
|
||||||
} catch (EarlyLoadingException exception) {
|
} catch (EarlyLoadingException exception) {
|
||||||
LOGGER.error(LogMarkers.SCAN, "Failed to build unique mod list after dependency discovery.", exception);
|
LOGGER.error(LogMarkers.SCAN, "Failed to build unique mod list after dependency discovery.", exception);
|
||||||
discoveryErrorData.addAll(exception.getAllData());
|
discoveryErrorData.addAll(exception.getAllData());
|
||||||
modFilesMap = loadedFiles.stream().collect(Collectors.groupingBy(IModFile::getType));
|
modFilesMap = loadedFiles.stream().collect(Collectors.groupingBy(IModFile::getType, () -> new EnumMap<>(IModFile.Type.class), Collectors.toList()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
@@ -190,8 +192,7 @@ public class ModDiscoverer {
|
|||||||
return validator;
|
return validator;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void handleLocatedFiles(final List<ModFile> loadedFiles, final List<IModFile> locatedFiles)
|
private static void handleLocatedFiles(final List<ModFile> loadedFiles, final List<IModFile> locatedFiles) {
|
||||||
{
|
|
||||||
var locatedModFiles = locatedFiles.stream().filter(ModFile.class::isInstance).map(ModFile.class::cast).toList();
|
var locatedModFiles = locatedFiles.stream().filter(ModFile.class::isInstance).map(ModFile.class::cast).toList();
|
||||||
for (IModFile mf : locatedModFiles) {
|
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());
|
||||||
|
|||||||
@@ -45,7 +45,6 @@ public class ModFile implements IModFile {
|
|||||||
private Throwable scanError;
|
private Throwable scanError;
|
||||||
private final SecureJar jar;
|
private final SecureJar jar;
|
||||||
private final Type modFileType;
|
private final Type modFileType;
|
||||||
private final Manifest manifest;
|
|
||||||
private final IModProvider provider;
|
private final IModProvider provider;
|
||||||
private IModFileInfo modFileInfo;
|
private IModFileInfo modFileInfo;
|
||||||
private ModFileScanData fileModFileScanData;
|
private ModFileScanData fileModFileScanData;
|
||||||
@@ -65,7 +64,7 @@ public class ModFile implements IModFile {
|
|||||||
this.jar = jar;
|
this.jar = jar;
|
||||||
this.parser = parser;
|
this.parser = parser;
|
||||||
|
|
||||||
manifest = this.jar.moduleDataProvider().getManifest();
|
var manifest = this.jar.moduleDataProvider().getManifest();
|
||||||
modFileType = Type.valueOf(type);
|
modFileType = Type.valueOf(type);
|
||||||
jarVersion = Optional.ofNullable(manifest.getMainAttributes().getValue(Attributes.Name.IMPLEMENTATION_VERSION)).orElse("0.0NONE");
|
jarVersion = Optional.ofNullable(manifest.getMainAttributes().getValue(Attributes.Name.IMPLEMENTATION_VERSION)).orElse("0.0NONE");
|
||||||
this.modFileInfo = ModFileParser.readModList(this, this.parser);
|
this.modFileInfo = ModFileParser.readModList(this, this.parser);
|
||||||
|
|||||||
+92
-69
@@ -7,7 +7,6 @@ package net.minecraftforge.fml.loading.moddiscovery;
|
|||||||
|
|
||||||
import com.google.common.base.Strings;
|
import com.google.common.base.Strings;
|
||||||
import com.mojang.logging.LogUtils;
|
import com.mojang.logging.LogUtils;
|
||||||
import cpw.mods.modlauncher.api.LamdbaExceptionUtils;
|
|
||||||
import net.minecraftforge.fml.loading.LogMarkers;
|
import net.minecraftforge.fml.loading.LogMarkers;
|
||||||
import net.minecraftforge.fml.loading.StringUtils;
|
import net.minecraftforge.fml.loading.StringUtils;
|
||||||
import net.minecraftforge.forgespi.language.IConfigurable;
|
import net.minecraftforge.forgespi.language.IConfigurable;
|
||||||
@@ -18,17 +17,15 @@ import org.jetbrains.annotations.ApiStatus;
|
|||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import javax.security.auth.x500.X500Principal;
|
import javax.security.auth.x500.X500Principal;
|
||||||
import java.net.URL;
|
import java.net.URL;
|
||||||
import java.security.CodeSigner;
|
|
||||||
import java.security.InvalidKeyException;
|
import java.security.InvalidKeyException;
|
||||||
import java.security.MessageDigest;
|
import java.security.MessageDigest;
|
||||||
import java.security.NoSuchAlgorithmException;
|
import java.security.NoSuchAlgorithmException;
|
||||||
import java.security.NoSuchProviderException;
|
import java.security.NoSuchProviderException;
|
||||||
import java.security.SignatureException;
|
import java.security.SignatureException;
|
||||||
import java.security.cert.Certificate;
|
import java.security.cert.CertificateEncodingException;
|
||||||
import java.security.cert.CertificateException;
|
import java.security.cert.CertificateException;
|
||||||
import java.security.cert.X509Certificate;
|
import java.security.cert.X509Certificate;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@@ -37,10 +34,8 @@ import java.util.Objects;
|
|||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import java.util.function.Consumer;
|
import java.util.function.Consumer;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
import java.util.stream.Stream;
|
|
||||||
|
|
||||||
public class ModFileInfo implements IModFileInfo, IConfigurable
|
public class ModFileInfo implements IModFileInfo, IConfigurable {
|
||||||
{
|
|
||||||
private static final Logger LOGGER = LogUtils.getLogger();
|
private static final Logger LOGGER = LogUtils.getLogger();
|
||||||
private static final String MAYBE_NOT_JAVAFML_VER = "[2,)";
|
private static final String MAYBE_NOT_JAVAFML_VER = "[2,)";
|
||||||
private static final String JAVAFML = "javafml";
|
private static final String JAVAFML = "javafml";
|
||||||
@@ -60,8 +55,7 @@ public class ModFileInfo implements IModFileInfo, IConfigurable
|
|||||||
private final String license;
|
private final String license;
|
||||||
private final List<String> usesServices;
|
private final List<String> usesServices;
|
||||||
|
|
||||||
ModFileInfo(final ModFile modFile, final IConfigurable config, Consumer<IModFileInfo> configFileConsumer)
|
ModFileInfo(final ModFile modFile, final IConfigurable config, Consumer<IModFileInfo> configFileConsumer) {
|
||||||
{
|
|
||||||
this.modFile = modFile;
|
this.modFile = modFile;
|
||||||
this.config = config;
|
this.config = config;
|
||||||
configFileConsumer.accept(this);
|
configFileConsumer.accept(this);
|
||||||
@@ -86,10 +80,6 @@ public class ModFileInfo implements IModFileInfo, IConfigurable
|
|||||||
.orElse(false);
|
.orElse(false);
|
||||||
this.clientSideOnly = config.<Boolean>getConfigElement("clientSideOnly")
|
this.clientSideOnly = config.<Boolean>getConfigElement("clientSideOnly")
|
||||||
.orElse(false);
|
.orElse(false);
|
||||||
if (this.clientSideOnly) {
|
|
||||||
// if clientSideOnly, then this is definitely a Forge mod
|
|
||||||
maybeNotAForgeMod = false;
|
|
||||||
}
|
|
||||||
this.showAsDataPack = config.<Boolean>getConfigElement("showAsDataPack")
|
this.showAsDataPack = config.<Boolean>getConfigElement("showAsDataPack")
|
||||||
.orElse(false);
|
.orElse(false);
|
||||||
this.usesServices = config.<List<String>>getConfigElement("services")
|
this.usesServices = config.<List<String>>getConfigElement("services")
|
||||||
@@ -98,6 +88,10 @@ public class ModFileInfo implements IModFileInfo, IConfigurable
|
|||||||
.map(StringUtils::toURL)
|
.map(StringUtils::toURL)
|
||||||
.orElse(null);
|
.orElse(null);
|
||||||
|
|
||||||
|
// if clientSideOnly, then this is definitely a Forge mod
|
||||||
|
if (this.clientSideOnly)
|
||||||
|
maybeNotAForgeMod = false;
|
||||||
|
|
||||||
if (maybeNotAForgeMod) {
|
if (maybeNotAForgeMod) {
|
||||||
// mark this file as not a Forge mod. Note: this marker may be removed later based on the mod dependencies
|
// mark this file as not a Forge mod. Note: this marker may be removed later based on the mod dependencies
|
||||||
this.properties = config.<Map<String, Object>>getConfigElement("properties")
|
this.properties = config.<Map<String, Object>>getConfigElement("properties")
|
||||||
@@ -110,15 +104,14 @@ public class ModFileInfo implements IModFileInfo, IConfigurable
|
|||||||
this.modFile.setFileProperties(this.properties);
|
this.modFile.setFileProperties(this.properties);
|
||||||
|
|
||||||
final List<? extends IConfigurable> modConfigs = config.getConfigList("mods");
|
final List<? extends IConfigurable> modConfigs = config.getConfigList("mods");
|
||||||
if (modConfigs.isEmpty())
|
if (modConfigs == null || modConfigs.isEmpty())
|
||||||
{
|
|
||||||
throw new InvalidModFileException("Missing mods list", this);
|
throw new InvalidModFileException("Missing mods list", this);
|
||||||
}
|
|
||||||
this.mods = modConfigs.stream()
|
this.mods = modConfigs.stream()
|
||||||
.map(mi-> (IModInfo)new ModInfo(this, mi))
|
.map(mi -> (IModInfo) ModInfo.of(this, mi))
|
||||||
.toList();
|
.toList();
|
||||||
if (LOGGER.isDebugEnabled(LogMarkers.LOADING))
|
|
||||||
{
|
if (LOGGER.isDebugEnabled(LogMarkers.LOADING)) {
|
||||||
LOGGER.debug(LogMarkers.LOADING, "Found valid mod file {} with {} mods - versions {}",
|
LOGGER.debug(LogMarkers.LOADING, "Found valid mod file {} with {} mods - versions {}",
|
||||||
this.modFile.getFileName(),
|
this.modFile.getFileName(),
|
||||||
this.mods.stream().map(IModInfo::getModId).collect(Collectors.joining(",", "{", "}")),
|
this.mods.stream().map(IModInfo::getModId).collect(Collectors.joining(",", "{", "}")),
|
||||||
@@ -132,13 +125,11 @@ public class ModFileInfo implements IModFileInfo, IConfigurable
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<IModInfo> getMods()
|
public List<IModInfo> getMods() {
|
||||||
{
|
|
||||||
return mods;
|
return mods;
|
||||||
}
|
}
|
||||||
|
|
||||||
public ModFile getFile()
|
public ModFile getFile() {
|
||||||
{
|
|
||||||
return this.modFile;
|
return this.modFile;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -148,44 +139,42 @@ public class ModFileInfo implements IModFileInfo, IConfigurable
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Map<String, Object> getFileProperties()
|
public Map<String, Object> getFileProperties() {
|
||||||
{
|
|
||||||
return this.properties;
|
return this.properties;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean showAsResourcePack()
|
public boolean showAsResourcePack() {
|
||||||
{
|
|
||||||
return this.showAsResourcePack;
|
return this.showAsResourcePack;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean isClientSideOnly()
|
public boolean isClientSideOnly() {
|
||||||
{
|
|
||||||
return this.clientSideOnly;
|
return this.clientSideOnly;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean showAsDataPack()
|
public boolean showAsDataPack() {
|
||||||
{
|
|
||||||
return this.showAsDataPack;
|
return this.showAsDataPack;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public <T> Optional<T> getConfigElement(final String... key)
|
public <T> Optional<T> getConfigElement(final String key) {
|
||||||
{
|
|
||||||
return this.config.getConfigElement(key);
|
return this.config.getConfigElement(key);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<? extends IConfigurable> getConfigList(final String... key)
|
public <T> Optional<T> getConfigElement(final String... key) {
|
||||||
{
|
return this.config.getConfigElement(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<? extends IConfigurable> getConfigList(final String... key) {
|
||||||
return this.config.getConfigList(key);
|
return this.config.getConfigList(key);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getLicense()
|
public String getLicense() {
|
||||||
{
|
|
||||||
return license;
|
return license;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -194,54 +183,83 @@ public class ModFileInfo implements IModFileInfo, IConfigurable
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public URL getIssueURL()
|
public URL getIssueURL() {
|
||||||
{
|
|
||||||
return issueURL;
|
return issueURL;
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean missingLicense()
|
public boolean missingLicense() {
|
||||||
{
|
|
||||||
return Strings.isNullOrEmpty(license);
|
return Strings.isNullOrEmpty(license);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static final char[] HEX = "0123456789ABCDEF".toCharArray();
|
||||||
public Optional<String> getCodeSigningFingerprint() {
|
public Optional<String> getCodeSigningFingerprint() {
|
||||||
var signers = this.modFile.getSecureJar().getManifestSigners();
|
var signers = this.modFile.getSecureJar().getManifestSigners();
|
||||||
return (signers == null ? Stream.<CodeSigner>of() : Arrays.stream(signers))
|
if (signers == null)
|
||||||
.flatMap(csa->csa.getSignerCertPath().getCertificates().stream())
|
return Optional.empty();
|
||||||
.findFirst()
|
|
||||||
.map(LamdbaExceptionUtils.rethrowFunction(Certificate::getEncoded))
|
for (var signer : signers) {
|
||||||
.map(bytes->LamdbaExceptionUtils.uncheck(()->MessageDigest.getInstance("SHA-256")).digest(bytes))
|
for (var cert : signer.getSignerCertPath().getCertificates()) {
|
||||||
.map(StringUtils::binToHex)
|
try {
|
||||||
.map(str-> String.join(":", str.split("(?<=\\G.{2})")));
|
var encoded = cert.getEncoded();
|
||||||
|
var sha256 = MessageDigest.getInstance("SHA-256");
|
||||||
|
var digest = sha256.digest(encoded);
|
||||||
|
var buf = new StringBuilder(digest.length * 3);
|
||||||
|
for (int x = 0; x < digest.length - 1; x++) {
|
||||||
|
buf.append(HEX[(digest[x] & 0xF0) >> 4]);
|
||||||
|
buf.append(HEX[(digest[x] & 0x0F) ]);
|
||||||
|
buf.append(':');
|
||||||
|
}
|
||||||
|
buf.append(HEX[(digest[digest.length - 1] & 0xF0) >> 4]);
|
||||||
|
buf.append(HEX[(digest[digest.length - 1] & 0x0F) ]);
|
||||||
|
|
||||||
|
// We only care about the first. Should we list them all?
|
||||||
|
return Optional.of(buf.toString());
|
||||||
|
} catch (CertificateEncodingException | NoSuchAlgorithmException e) {
|
||||||
|
sneak(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return Optional.empty();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public Optional<String> getTrustData() {
|
public Optional<String> getTrustData() {
|
||||||
return Arrays.stream(this.modFile.getSecureJar().getManifestSigners())
|
var signers = this.modFile.getSecureJar().getManifestSigners();
|
||||||
.flatMap(csa->csa.getSignerCertPath().getCertificates().stream())
|
if (signers == null)
|
||||||
.findFirst()
|
return Optional.empty();
|
||||||
.map(X509Certificate.class::cast)
|
|
||||||
.map(c->{
|
for (var signer : signers) {
|
||||||
StringBuffer sb = new StringBuffer();
|
for (var cert : signer.getSignerCertPath().getCertificates()) {
|
||||||
sb.append(c.getSubjectX500Principal().getName(X500Principal.RFC2253).split(",")[0]);
|
if (!(cert instanceof X509Certificate x509))
|
||||||
boolean selfSigned = false;
|
continue;
|
||||||
try {
|
|
||||||
c.verify(c.getPublicKey());
|
var sb = new StringBuilder();
|
||||||
selfSigned = true;
|
sb.append(x509.getSubjectX500Principal().getName(X500Principal.RFC2253).split(",")[0]);
|
||||||
} catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException | SignatureException | NoSuchProviderException e) {
|
|
||||||
// not self signed
|
var selfSigned = false;
|
||||||
}
|
try {
|
||||||
if (selfSigned) {
|
x509.verify(x509.getPublicKey());
|
||||||
|
selfSigned = true;
|
||||||
|
} catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException | SignatureException | NoSuchProviderException e) {
|
||||||
|
// not self signed
|
||||||
|
}
|
||||||
|
|
||||||
|
if (selfSigned)
|
||||||
sb.append(" self-signed");
|
sb.append(" self-signed");
|
||||||
} else {
|
else
|
||||||
sb.append(" signed by ").append(c.getIssuerX500Principal().getName(X500Principal.RFC2253).split(",")[0]);
|
sb.append(" signed by ").append(x509.getIssuerX500Principal().getName(X500Principal.RFC2253).split(",")[0]);
|
||||||
};
|
|
||||||
return sb.toString();
|
return Optional.of(sb.toString());
|
||||||
});
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return Optional.empty();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String moduleName() {
|
public String moduleName() {
|
||||||
return getMods().get(0).getModId();
|
return this.modFile.getSecureJar().name();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -253,4 +271,9 @@ public class ModFileInfo implements IModFileInfo, IConfigurable
|
|||||||
public List<String> usesServices() {
|
public List<String> usesServices() {
|
||||||
return usesServices;
|
return usesServices;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private static <E extends Throwable, R> R sneak(Throwable e) throws E {
|
||||||
|
throw (E)e;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+153
-198
@@ -19,202 +19,189 @@ import org.jetbrains.annotations.ApiStatus;
|
|||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
|
|
||||||
import java.net.URL;
|
import java.net.URL;
|
||||||
|
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.Optional;
|
import java.util.Optional;
|
||||||
import java.util.function.Supplier;
|
|
||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
@ApiStatus.Internal
|
@ApiStatus.Internal
|
||||||
public class ModInfo implements IModInfo, IConfigurable {
|
public record ModInfo(
|
||||||
|
ModFileInfo getOwningFile,
|
||||||
|
IConfigurable getConfig,
|
||||||
|
|
||||||
|
String getModId,
|
||||||
|
String getNamespace,
|
||||||
|
ArtifactVersion getVersion,
|
||||||
|
|
||||||
|
String getDisplayName,
|
||||||
|
String getDescription,
|
||||||
|
Optional<String> getLogoFile,
|
||||||
|
boolean getLogoBlur,
|
||||||
|
Optional<URL> getUpdateURL,
|
||||||
|
Optional<URL> getModURL,
|
||||||
|
|
||||||
|
Holder<List<? extends ModVersion>> dependencies,
|
||||||
|
Holder<List<ForgeFeature.Bound>> forgeFeatures,
|
||||||
|
Map<String, Object> getModProperties
|
||||||
|
) implements IModInfo, IConfigurable {
|
||||||
private static final Logger LOGGER = LogUtils.getLogger();
|
private static final Logger LOGGER = LogUtils.getLogger();
|
||||||
private static final DefaultArtifactVersion DEFAULT_VERSION = new DefaultArtifactVersion("1");
|
private static final DefaultArtifactVersion DEFAULT_VERSION = new DefaultArtifactVersion("1");
|
||||||
private static final Pattern VALID_MODID = Pattern.compile("^[a-z][a-z0-9_]{1,63}$");
|
private static final Pattern VALID_MODID = Pattern.compile("^[a-z][a-z0-9_]{1,63}$");
|
||||||
private static final Pattern VALID_NAMESPACE = Pattern.compile("^[a-z][a-z0-9_.-]{1,63}$");
|
private static final Pattern VALID_NAMESPACE = Pattern.compile("^[a-z][a-z0-9_.-]{1,63}$");
|
||||||
private static final Pattern VALID_VERSION = Pattern.compile("^\\d+.*");
|
private static final Pattern VALID_VERSION = Pattern.compile("^\\d+.*");
|
||||||
|
|
||||||
private final ModFileInfo owningFile;
|
public static ModInfo of(ModFileInfo owningFile, IConfigurable config) {
|
||||||
private final String modId;
|
|
||||||
private final String namespace;
|
|
||||||
private final ArtifactVersion version;
|
|
||||||
private final String displayName;
|
|
||||||
private final String description;
|
|
||||||
private final Optional<String> logoFile;
|
|
||||||
private final boolean logoBlur;
|
|
||||||
private final Optional<URL> updateJSONURL;
|
|
||||||
private final List<? extends IModInfo.ModVersion> dependencies;
|
|
||||||
|
|
||||||
private final List<ForgeFeature.Bound> features;
|
|
||||||
private final Map<String,Object> properties;
|
|
||||||
private final IConfigurable config;
|
|
||||||
private final Optional<URL> modUrl;
|
|
||||||
|
|
||||||
public ModInfo(final ModFileInfo owningFile, final IConfigurable config)
|
|
||||||
{
|
|
||||||
Optional<ModFileInfo> ownFile = Optional.ofNullable(owningFile);
|
|
||||||
this.owningFile = owningFile;
|
|
||||||
this.config = config;
|
|
||||||
// These are sourced from the mod specific [[mod]] entry
|
// These are sourced from the mod specific [[mod]] entry
|
||||||
this.modId = config.<String>getConfigElement("modId")
|
String modId = config.<String>getConfigElement("modId").orElse(null);
|
||||||
.orElseThrow(() -> new InvalidModFileException("Missing modId", owningFile));
|
if (modId == null)
|
||||||
|
throw new InvalidModFileException("Missing modId", owningFile);
|
||||||
|
|
||||||
// verify we have a valid modid
|
// verify we have a valid modid
|
||||||
if (!VALID_MODID.matcher(this.modId).matches()) {
|
if (!VALID_MODID.matcher(modId).matches()) {
|
||||||
LOGGER.error(LogUtils.FATAL_MARKER, "Invalid modId found in file {} - {} does not match the standard: {}", this.owningFile.getFile().getFilePath(), this.modId, VALID_MODID.pattern());
|
LOGGER.error(LogUtils.FATAL_MARKER, "Invalid modId found in file {} - {} does not match the standard: {}", owningFile.getFile().getFilePath(), modId, VALID_MODID.pattern());
|
||||||
throw new InvalidModFileException("Invalid modId found : " + this.modId, owningFile);
|
throw new InvalidModFileException("Invalid modId found : " + modId, owningFile);
|
||||||
}
|
}
|
||||||
this.namespace = config.<String>getConfigElement("namespace")
|
|
||||||
.orElse(this.modId);
|
String namespace = config.<String>getConfigElement("namespace")
|
||||||
|
.orElse(modId);
|
||||||
|
|
||||||
// verify our namespace is valid
|
// verify our namespace is valid
|
||||||
if (!VALID_NAMESPACE.matcher(this.namespace).matches()) {
|
if (!VALID_NAMESPACE.matcher(namespace).matches()) {
|
||||||
LOGGER.error(LogUtils.FATAL_MARKER, "Invalid override namespace found in file {} - {} does not match the standard: {}", this.owningFile.getFile().getFilePath(), this.namespace, VALID_NAMESPACE.pattern());
|
LOGGER.error(LogUtils.FATAL_MARKER, "Invalid override namespace found in file {} - {} does not match the standard: {}", owningFile.getFile().getFilePath(), namespace, VALID_NAMESPACE.pattern());
|
||||||
throw new InvalidModFileException("Invalid override namespace found : " + this.namespace, owningFile);
|
throw new InvalidModFileException("Invalid override namespace found : " + namespace, owningFile);
|
||||||
}
|
}
|
||||||
this.version = config.<String>getConfigElement("version")
|
|
||||||
.map(s -> StringSubstitutor.replace(s, ownFile.map(ModFileInfo::getFile).orElse(null)))
|
ArtifactVersion version = config.<String>getConfigElement("version")
|
||||||
|
.map(s -> StringSubstitutor.replace(s, owningFile.getFile()))
|
||||||
.map(DefaultArtifactVersion::new)
|
.map(DefaultArtifactVersion::new)
|
||||||
.orElse(DEFAULT_VERSION);
|
.orElse(DEFAULT_VERSION);
|
||||||
|
|
||||||
// verify we have a valid mod version
|
// verify we have a valid mod version
|
||||||
if (!VALID_VERSION.matcher(this.version.toString()).matches()) {
|
if (!VALID_VERSION.matcher(version.toString()).matches())
|
||||||
throw new InvalidModFileException("Illegal version number specified "+this.version, this.getOwningFile());
|
throw new InvalidModFileException("Illegal version number specified " + version, owningFile);
|
||||||
}
|
|
||||||
// The remaining properties all default to sensible values and are not essential
|
// The remaining properties all default to sensible values and are not essential
|
||||||
this.displayName = config.<String>getConfigElement("displayName")
|
String displayName = config.<String>getConfigElement("displayName")
|
||||||
.orElse(this.modId);
|
.orElse(modId);
|
||||||
this.description = config.<String>getConfigElement("description")
|
|
||||||
|
String description = config.<String>getConfigElement("description")
|
||||||
.orElse("MISSING DESCRIPTION")
|
.orElse("MISSING DESCRIPTION")
|
||||||
.replace("\r\n", "\n").stripIndent();
|
.replace("\r\n", "\n").stripIndent();
|
||||||
this.logoFile = Optional.ofNullable(config.<String>getConfigElement("logoFile")
|
|
||||||
.orElseGet(() -> ownFile.flatMap(mf -> mf.<String>getConfigElement("logoFile"))
|
Optional<String> logoFile = Optional.ofNullable(
|
||||||
.orElse(null)));
|
config.<String>getConfigElement("logoFile")
|
||||||
this.logoBlur = config.<Boolean>getConfigElement("logoBlur")
|
.orElseGet(() -> owningFile.<String>getConfigElement("logoFile").orElse(null))
|
||||||
.orElseGet(() -> ownFile.flatMap(f -> f.<Boolean>getConfigElement("logoBlur"))
|
);
|
||||||
.orElse(true));
|
|
||||||
this.updateJSONURL = config.<String>getConfigElement("updateJSONURL")
|
Boolean logoBlur = config.<Boolean>getConfigElement("logoBlur").orElse(null);
|
||||||
|
if (logoBlur == null)
|
||||||
|
logoBlur = owningFile.<Boolean>getConfigElement("logoBlur").orElse(true);
|
||||||
|
|
||||||
|
Optional<URL> updateJSONURL = config.<String>getConfigElement("updateJSONURL")
|
||||||
.map(StringUtils::toURL);
|
.map(StringUtils::toURL);
|
||||||
this.modUrl = config.<String>getConfigElement("modUrl")
|
|
||||||
|
Optional<URL> modUrl = config.<String>getConfigElement("modUrl")
|
||||||
.map(StringUtils::toURL);
|
.map(StringUtils::toURL);
|
||||||
// These are sourced from the file rather than the mod-specific block, but with a modid tag
|
|
||||||
this.dependencies = ownFile.map(mfi -> mfi.getConfigList("dependencies", this.modId))
|
// dependencies and features are done after the constructor as they need to reference the ModInfo we are creating
|
||||||
.orElse(Collections.emptyList())
|
List<? extends ModVersion> dependencies = Collections.emptyList();
|
||||||
.stream()
|
List<ForgeFeature.Bound> forgeFeatures = Collections.emptyList();
|
||||||
.map(dep -> new ModVersion(this, dep))
|
|
||||||
.toList();
|
Map<String, Object> modProperties = owningFile.<Map<String, Object>>getConfigElement("modproperties", modId)
|
||||||
this.features = ownFile.flatMap(mfi -> mfi.<Map<String, Object>>getConfigElement("features", this.modId))
|
.map(Collections::unmodifiableMap)
|
||||||
.stream()
|
|
||||||
.flatMap(m->m.entrySet().stream())
|
|
||||||
.map(this::makeBound)
|
|
||||||
.toList();
|
|
||||||
this.properties = ownFile.flatMap(mfi -> mfi.<Map<String, Object>>getConfigElement("modproperties", this.modId))
|
|
||||||
.orElse(Collections.emptyMap());
|
.orElse(Collections.emptyMap());
|
||||||
|
|
||||||
|
return new ModInfo(
|
||||||
|
owningFile, config,
|
||||||
|
modId, namespace, version,
|
||||||
|
displayName, description, logoFile, logoBlur, updateJSONURL, modUrl,
|
||||||
|
new Holder<>(dependencies), new Holder<>(forgeFeatures), modProperties
|
||||||
|
).setupDependencies().setupForgeFeatures();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
private ModInfo setupDependencies() {
|
||||||
public ModFileInfo getOwningFile() {
|
var deps = getOwningFile.getConfigList("dependencies", getModId);
|
||||||
return owningFile;
|
if (deps == null || deps.isEmpty()) {
|
||||||
|
dependencies.value = Collections.emptyList();
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
var tmp = new ModVersion[deps.size()];
|
||||||
|
for (int i = 0; i < deps.size(); i++) {
|
||||||
|
tmp[i] = ModVersion.of(this, deps.get(i));
|
||||||
|
}
|
||||||
|
dependencies.value = List.of(tmp);
|
||||||
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
private ModInfo setupForgeFeatures() {
|
||||||
public String getModId() {
|
var feats = getOwningFile.<Map<String, Object>>getConfigElement("features", getModId).orElse(null);
|
||||||
return modId;
|
if (feats == null) {
|
||||||
}
|
forgeFeatures.value = Collections.emptyList();
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
var tmp = new ArrayList<ForgeFeature.Bound>();
|
||||||
public String getDisplayName()
|
for (var entry : feats.entrySet()) {
|
||||||
{
|
if (!(entry.getValue() instanceof String val))
|
||||||
return this.displayName;
|
throw new InvalidModFileException("Invalid feature bound {" + entry.getValue() + "} for key {" + entry.getKey() + "} only strings are accepted", getOwningFile);
|
||||||
}
|
tmp.add(new ForgeFeature.Bound(entry.getKey(), val, this));
|
||||||
|
}
|
||||||
@Override
|
forgeFeatures.value = List.copyOf(tmp);
|
||||||
public String getDescription()
|
|
||||||
{
|
|
||||||
return this.description;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public ArtifactVersion getVersion() {
|
|
||||||
return version;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public List<? extends IModInfo.ModVersion> getDependencies() {
|
|
||||||
return this.dependencies;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getNamespace() {
|
|
||||||
return this.namespace;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Map<String, Object> getModProperties() {
|
|
||||||
return this.properties;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Optional<URL> getUpdateURL() {
|
|
||||||
return this.updateJSONURL;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Optional<String> getLogoFile()
|
|
||||||
{
|
|
||||||
return this.logoFile;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean getLogoBlur()
|
|
||||||
{
|
|
||||||
return this.logoBlur;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public IConfigurable getConfig() {
|
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<? extends ForgeFeature.Bound> getForgeFeatures() {
|
public <T> Optional<T> getConfigElement(String key) {
|
||||||
return this.features;
|
return getConfig.getConfigElement(key);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public <T> Optional<T> getConfigElement(final String... key) {
|
public <T> Optional<T> getConfigElement(String... key) {
|
||||||
return this.config.getConfigElement(key);
|
return getConfig.getConfigElement(key);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<? extends IConfigurable> getConfigList(final String... key) {
|
public List<? extends IConfigurable> getConfigList(String... key) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Optional<URL> getModURL() {
|
public List<? extends IModInfo.ModVersion> getDependencies() {
|
||||||
return modUrl;
|
return dependencies.value;
|
||||||
}
|
}
|
||||||
|
|
||||||
private ForgeFeature.Bound makeBound(Map.Entry<String, Object> e) {
|
@Override
|
||||||
if (e.getValue() instanceof String val) {
|
public List<? extends ForgeFeature.Bound> getForgeFeatures() {
|
||||||
return new ForgeFeature.Bound(e.getKey(), val, this);
|
return forgeFeatures.value;
|
||||||
} else {
|
}
|
||||||
throw new InvalidModFileException("Invalid feature bound {" + e.getValue() + "} for key {" + e.getKey() + "} only strings are accepted", this.owningFile);
|
|
||||||
|
private static final class Holder<T> {
|
||||||
|
private T value;
|
||||||
|
|
||||||
|
public Holder(T value) {
|
||||||
|
this.value = value;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class ModVersion implements net.minecraftforge.forgespi.language.IModInfo.ModVersion {
|
private record ModVersion(
|
||||||
private IModInfo owner;
|
Holder<IModInfo> owner,
|
||||||
private final String modId;
|
|
||||||
private final VersionRange versionRange;
|
|
||||||
private final boolean mandatory;
|
|
||||||
private final Ordering ordering;
|
|
||||||
private final DependencySide side;
|
|
||||||
private final Optional<URL> referralUrl;
|
|
||||||
|
|
||||||
public ModVersion(final IModInfo owner, final IConfigurable config) {
|
String getModId,
|
||||||
this.owner = owner;
|
VersionRange getVersionRange,
|
||||||
this.modId = config.<String>getConfigElement("modId")
|
boolean isMandatory,
|
||||||
.orElseThrow(()->new InvalidModFileException("Missing required field modid in dependency", getOwningFile()));
|
Ordering getOrdering,
|
||||||
if (this.modId.equals("forge")) {
|
DependencySide getSide,
|
||||||
|
Optional<URL> getReferralURL
|
||||||
|
) implements IModInfo.ModVersion {
|
||||||
|
public static ModVersion of(IModInfo owner, IConfigurable config) {
|
||||||
|
var modId = config.<String>getConfigElement("modId").orElse(null);
|
||||||
|
if (modId == null)
|
||||||
|
throw new InvalidModFileException("Missing required field modid in dependency", owner.getOwningFile());
|
||||||
|
|
||||||
|
if (modId.equals("forge")) {
|
||||||
var fileProps = owner.getOwningFile().getFileProperties();
|
var fileProps = owner.getOwningFile().getFileProperties();
|
||||||
// Checking containsKey to avoid a possible exception if the property is not present (due to Collections.emptyMap())
|
// Checking containsKey to avoid a possible exception if the property is not present (due to Collections.emptyMap())
|
||||||
if (!fileProps.isEmpty() && fileProps.containsKey(ModFileInfo.NOT_A_FORGE_MOD_PROP)) {
|
if (!fileProps.isEmpty() && fileProps.containsKey(ModFileInfo.NOT_A_FORGE_MOD_PROP)) {
|
||||||
@@ -223,74 +210,42 @@ public class ModInfo implements IModInfo, IConfigurable {
|
|||||||
fileProps.remove(ModFileInfo.NOT_A_FORGE_MOD_PROP);
|
fileProps.remove(ModFileInfo.NOT_A_FORGE_MOD_PROP);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
var mandatory = config.<Boolean>getConfigElement("mandatory");
|
|
||||||
if (mandatory.isPresent()) {
|
boolean mandatory;
|
||||||
this.mandatory = mandatory.get();
|
var mandatoryValue = config.<Boolean>getConfigElement("mandatory");
|
||||||
} else if (owner.getOwningFile().getFileProperties().containsKey(ModFileInfo.NOT_A_FORGE_MOD_PROP)) {
|
if (mandatoryValue.isPresent())
|
||||||
this.mandatory = true;
|
mandatory = mandatoryValue.get();
|
||||||
} else {
|
else if (owner.getOwningFile().getFileProperties().containsKey(ModFileInfo.NOT_A_FORGE_MOD_PROP))
|
||||||
throw new InvalidModFileException("Missing required field mandatory in dependency", getOwningFile());
|
mandatory = true;
|
||||||
}
|
else
|
||||||
this.versionRange = config.<String>getConfigElement("versionRange")
|
throw new InvalidModFileException("Missing required field mandatory in dependency", owner.getOwningFile());
|
||||||
|
|
||||||
|
var versionRange = config.<String>getConfigElement("versionRange")
|
||||||
.map(MavenVersionAdapter::createFromVersionSpec)
|
.map(MavenVersionAdapter::createFromVersionSpec)
|
||||||
.orElse(UNBOUNDED);
|
.orElse(UNBOUNDED);
|
||||||
this.ordering = config.<String>getConfigElement("ordering")
|
var ordering = config.<String>getConfigElement("ordering")
|
||||||
.map(Ordering::valueOf)
|
.map(Ordering::valueOf)
|
||||||
.orElse(Ordering.NONE);
|
.orElse(Ordering.NONE);
|
||||||
this.side = config.<String>getConfigElement("side")
|
var side = config.<String>getConfigElement("side")
|
||||||
.map(DependencySide::valueOf)
|
.map(DependencySide::valueOf)
|
||||||
.orElse(DependencySide.BOTH);
|
.orElse(DependencySide.BOTH);
|
||||||
this.referralUrl = config.<String>getConfigElement("referralUrl")
|
var referralUrl = config.<String>getConfigElement("referralUrl")
|
||||||
.map(StringUtils::toURL);
|
.map(StringUtils::toURL);
|
||||||
}
|
|
||||||
|
|
||||||
|
return new ModVersion(
|
||||||
@Override
|
new Holder<>(owner),
|
||||||
public String getModId()
|
modId, versionRange, mandatory, ordering, side, referralUrl
|
||||||
{
|
);
|
||||||
return modId;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public VersionRange getVersionRange()
|
public IModInfo getOwner() {
|
||||||
{
|
return owner.value;
|
||||||
return versionRange;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean isMandatory()
|
public void setOwner(IModInfo newOwner) {
|
||||||
{
|
owner.value = newOwner;
|
||||||
return mandatory;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Ordering getOrdering()
|
|
||||||
{
|
|
||||||
return ordering;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public DependencySide getSide()
|
|
||||||
{
|
|
||||||
return side;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setOwner(final IModInfo owner)
|
|
||||||
{
|
|
||||||
this.owner = owner;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public IModInfo getOwner()
|
|
||||||
{
|
|
||||||
return owner;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Optional<URL> getReferralURL() {
|
|
||||||
return referralUrl;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
+31
-16
@@ -9,49 +9,64 @@ import cpw.mods.jarhandling.JarMetadata;
|
|||||||
import net.minecraftforge.forgespi.locating.IModFile;
|
import net.minecraftforge.forgespi.locating.IModFile;
|
||||||
import java.lang.module.ModuleDescriptor;
|
import java.lang.module.ModuleDescriptor;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
|
|
||||||
import org.jetbrains.annotations.ApiStatus;
|
import org.jetbrains.annotations.ApiStatus;
|
||||||
|
|
||||||
@ApiStatus.Internal
|
@ApiStatus.Internal
|
||||||
public final class ModJarMetadata implements JarMetadata {
|
public final class ModJarMetadata implements JarMetadata {
|
||||||
|
private static final String AUTOMATIC_MODULE_NAME = "Automatic-Module-Name";
|
||||||
private IModFile modFile;
|
private IModFile modFile;
|
||||||
|
private String name;
|
||||||
|
private String version;
|
||||||
private ModuleDescriptor descriptor;
|
private ModuleDescriptor descriptor;
|
||||||
|
|
||||||
ModJarMetadata() {
|
ModJarMetadata() { }
|
||||||
}
|
|
||||||
|
|
||||||
public void setModFile(IModFile file) {
|
public void setModFile(IModFile file) {
|
||||||
this.modFile = file;
|
this.modFile = file;
|
||||||
|
var mods = this.modFile.getModFileInfo().getMods();
|
||||||
|
|
||||||
|
if (!mods.isEmpty()) {
|
||||||
|
var main = mods.get(0);
|
||||||
|
this.name = main.getModId();
|
||||||
|
this.version = main.getVersion().toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
var jar = file.getSecureJar();
|
||||||
|
var aname = jar.moduleDataProvider().getManifest().getMainAttributes().getValue(AUTOMATIC_MODULE_NAME);
|
||||||
|
if (aname != null)
|
||||||
|
this.name = aname;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String name() {
|
public String name() {
|
||||||
return modFile.getModFileInfo().moduleName();
|
return this.name;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String version() {
|
public String version() {
|
||||||
return modFile.getModFileInfo().versionString();
|
return this.version;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public ModuleDescriptor descriptor() {
|
public ModuleDescriptor descriptor() {
|
||||||
if (descriptor != null) return descriptor;
|
if (descriptor != null)
|
||||||
|
return descriptor;
|
||||||
|
|
||||||
var bld = ModuleDescriptor.newAutomaticModule(name())
|
var bld = ModuleDescriptor.newAutomaticModule(name())
|
||||||
.version(version())
|
.version(version())
|
||||||
.packages(modFile.getSecureJar().getPackages());
|
.packages(modFile.getSecureJar().getPackages());
|
||||||
modFile.getSecureJar().getProviders().stream()
|
|
||||||
.filter(p -> !p.providers().isEmpty())
|
for (var provider : modFile.getSecureJar().getProviders()) {
|
||||||
.forEach(p -> bld.provides(p.serviceName(), p.providers()));
|
if (provider.providers().isEmpty())
|
||||||
modFile.getModFileInfo().usesServices().forEach(bld::uses);
|
continue;
|
||||||
|
|
||||||
|
bld.provides(provider.serviceName(), provider.providers());
|
||||||
|
}
|
||||||
|
|
||||||
descriptor = bld.build();
|
descriptor = bld.build();
|
||||||
return descriptor;
|
return descriptor;
|
||||||
}
|
}
|
||||||
|
|
||||||
public IModFile modFile() {
|
|
||||||
return modFile;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean equals(Object obj) {
|
public boolean equals(Object obj) {
|
||||||
if (obj == this) return true;
|
if (obj == this) return true;
|
||||||
|
|||||||
+3
-3
@@ -64,7 +64,7 @@ public class ModValidator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
private List<ModFile> validateFiles(final List<ModFile> mods) {
|
private static List<ModFile> validateFiles(final List<ModFile> mods) {
|
||||||
final List<ModFile> brokenFiles = new ArrayList<>();
|
final List<ModFile> brokenFiles = new ArrayList<>();
|
||||||
for (Iterator<ModFile> iterator = mods.iterator(); iterator.hasNext();) {
|
for (Iterator<ModFile> iterator = mods.iterator(); iterator.hasNext();) {
|
||||||
ModFile modFile = iterator.next();
|
ModFile modFile = iterator.next();
|
||||||
@@ -106,8 +106,8 @@ public class ModValidator {
|
|||||||
|
|
||||||
private List<EarlyLoadingException.ExceptionData> validateLanguages() {
|
private List<EarlyLoadingException.ExceptionData> validateLanguages() {
|
||||||
List<EarlyLoadingException.ExceptionData> errorData = new ArrayList<>();
|
List<EarlyLoadingException.ExceptionData> errorData = new ArrayList<>();
|
||||||
for (Iterator<ModFile> iterator = this.candidateMods.iterator(); iterator.hasNext(); ) {
|
for (Iterator<ModFile> iterator = this.candidateMods.iterator(); iterator.hasNext();) {
|
||||||
final ModFile modFile = iterator.next();
|
var modFile = iterator.next();
|
||||||
try {
|
try {
|
||||||
modFile.identifyLanguage();
|
modFile.identifyLanguage();
|
||||||
} catch (EarlyLoadingException e) {
|
} catch (EarlyLoadingException e) {
|
||||||
|
|||||||
+16
-5
@@ -16,6 +16,7 @@ import org.slf4j.Logger;
|
|||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
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.Comparator;
|
import java.util.Comparator;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
@@ -42,11 +43,21 @@ public class ModsFolderLocator extends AbstractModProvider implements IModLocato
|
|||||||
public List<IModLocator.ModFileOrException> scanMods() {
|
public List<IModLocator.ModFileOrException> scanMods() {
|
||||||
LOGGER.debug(LogMarkers.SCAN, "Scanning mods dir {} for mods", this.modFolder);
|
LOGGER.debug(LogMarkers.SCAN, "Scanning mods dir {} for mods", this.modFolder);
|
||||||
var excluded = ModDirTransformerDiscoverer.allExcluded();
|
var excluded = ModDirTransformerDiscoverer.allExcluded();
|
||||||
try (var stream = Files.list(this.modFolder)) {
|
try {
|
||||||
return stream.filter(path -> !excluded.contains(path) && path.getFileName().toString().toLowerCase(Locale.ROOT).endsWith(SUFFIX))
|
var ret = new ArrayList<IModLocator.ModFileOrException>();
|
||||||
.sorted(Comparator.comparing(path -> path.getFileName().toString().toLowerCase(Locale.ROOT)))
|
var files = Files.list(this.modFolder).toList();
|
||||||
.map(this::createMod)
|
for (var file : files) {
|
||||||
.toList();
|
var name = file.getFileName().toString().toLowerCase(Locale.ROOT);
|
||||||
|
if (excluded.contains(file) || !name.endsWith(SUFFIX))
|
||||||
|
continue;
|
||||||
|
var mod = this.createMod(file, true);
|
||||||
|
if (mod == null) {
|
||||||
|
LOGGER.debug(LogMarkers.SCAN, "Found unknown jar file {} ignoring", file);
|
||||||
|
} else {
|
||||||
|
ret.add(mod);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ret;
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
return sneak(e);
|
return sneak(e);
|
||||||
}
|
}
|
||||||
|
|||||||
+34
-15
@@ -6,6 +6,8 @@
|
|||||||
package net.minecraftforge.fml.loading.moddiscovery;
|
package net.minecraftforge.fml.loading.moddiscovery;
|
||||||
|
|
||||||
import com.electronwill.nightconfig.core.UnmodifiableConfig;
|
import com.electronwill.nightconfig.core.UnmodifiableConfig;
|
||||||
|
import com.google.common.collect.ImmutableMap;
|
||||||
|
|
||||||
import net.minecraftforge.forgespi.language.IConfigurable;
|
import net.minecraftforge.forgespi.language.IConfigurable;
|
||||||
import net.minecraftforge.forgespi.language.IModFileInfo;
|
import net.minecraftforge.forgespi.language.IModFileInfo;
|
||||||
|
|
||||||
@@ -16,11 +18,12 @@ import java.util.Optional;
|
|||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
import org.jetbrains.annotations.ApiStatus;
|
import org.jetbrains.annotations.ApiStatus;
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
import static java.util.Arrays.asList;
|
import static java.util.Arrays.asList;
|
||||||
|
|
||||||
@ApiStatus.Internal
|
@ApiStatus.Internal
|
||||||
class NightConfigWrapper implements IConfigurable {
|
final class NightConfigWrapper implements IConfigurable {
|
||||||
private final UnmodifiableConfig config;
|
private final UnmodifiableConfig config;
|
||||||
private IModFileInfo file;
|
private IModFileInfo file;
|
||||||
|
|
||||||
@@ -28,35 +31,51 @@ class NightConfigWrapper implements IConfigurable {
|
|||||||
this.config = config;
|
this.config = config;
|
||||||
}
|
}
|
||||||
|
|
||||||
NightConfigWrapper setFile(IModFileInfo file) {
|
private NightConfigWrapper(UnmodifiableConfig config, IModFileInfo file) {
|
||||||
|
this.config = config;
|
||||||
|
this.file = file;
|
||||||
|
}
|
||||||
|
|
||||||
|
void setFile(IModFileInfo file) {
|
||||||
this.file = file;
|
this.file = file;
|
||||||
return this;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@SuppressWarnings("unchecked")
|
public <T> Optional<T> getConfigElement(String key) {
|
||||||
|
var path = List.of(key);
|
||||||
|
return Optional.ofNullable(validate(this.config.get(path), path));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
public <T> Optional<T> getConfigElement(final String... key) {
|
public <T> Optional<T> getConfigElement(final String... key) {
|
||||||
var path = asList(key);
|
var path = asList(key);
|
||||||
return this.config.getOptional(path).map(value -> {
|
return Optional.ofNullable(validate(this.config.get(path), path));
|
||||||
if (value instanceof UnmodifiableConfig) {
|
}
|
||||||
return (T) ((UnmodifiableConfig) value).valueMap();
|
|
||||||
} else if (value instanceof ArrayList<?> al && al.size() > 0 && al.get(0) instanceof UnmodifiableConfig) {
|
@SuppressWarnings("unchecked")
|
||||||
throw new InvalidModFileException("The configuration path " + path + " is invalid. I wasn't expecting a multi-object list - remove one of the [[ ]]", file);
|
private <T> T validate(@Nullable T value, List<String> path) {
|
||||||
}
|
if (value instanceof UnmodifiableConfig cfg) {
|
||||||
return (T) value;
|
// New Night config doesn't implement valueMap(), so do a copy.
|
||||||
});
|
var entries = cfg.entrySet();
|
||||||
|
var builder = ImmutableMap.builderWithExpectedSize(entries.size());
|
||||||
|
for (var e : entries)
|
||||||
|
builder.put(e.getKey(), e.getValue());
|
||||||
|
return (T) builder.build();
|
||||||
|
} else if (value instanceof ArrayList<?> al && !al.isEmpty() && al.getFirst() instanceof UnmodifiableConfig) {
|
||||||
|
throw new InvalidModFileException("The configuration path " + path + " is invalid. I wasn't expecting a multi-object list - remove one of the [[ ]]", file);
|
||||||
|
}
|
||||||
|
return value;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<? extends IConfigurable> getConfigList(final String... key) {
|
public List<? extends IConfigurable> getConfigList(final String... key) {
|
||||||
final List<String> path = asList(key);
|
final List<String> path = asList(key);
|
||||||
if (this.config.contains(path) && !(this.config.get(path) instanceof Collection)) {
|
if (this.config.contains(path) && !(this.config.get(path) instanceof Collection)) {
|
||||||
throw new InvalidModFileException("The configuration path "+path+" is invalid. Expecting a collection!", file);
|
throw new InvalidModFileException("The configuration path " + path + " is invalid. Expecting a collection!", file);
|
||||||
}
|
}
|
||||||
final Collection<UnmodifiableConfig> nestedConfigs = this.config.getOrElse(path, ArrayList::new);
|
final Collection<UnmodifiableConfig> nestedConfigs = this.config.getOrElse(path, ArrayList::new);
|
||||||
return nestedConfigs.stream()
|
return nestedConfigs.stream()
|
||||||
.map(NightConfigWrapper::new)
|
.map(conf -> new NightConfigWrapper(conf, file))
|
||||||
.map(cw->cw.setFile(file))
|
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -21,37 +21,36 @@ import java.nio.file.Path;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
@ApiStatus.Internal
|
@ApiStatus.Internal
|
||||||
class Scanner {
|
record Scanner(ModFile fileToScan, ModFileScanData result) {
|
||||||
private static final Logger LOGGER = LogUtils.getLogger();
|
private static final Logger LOGGER = LogUtils.getLogger();
|
||||||
private final ModFile fileToScan;
|
private static final boolean DEBUG = LOGGER.isDebugEnabled(LogMarkers.SCAN);
|
||||||
|
|
||||||
public Scanner(final ModFile fileToScan) {
|
public Scanner(ModFile fileToScan) {
|
||||||
this.fileToScan = fileToScan;
|
this(fileToScan, new ModFileScanData());
|
||||||
}
|
}
|
||||||
|
|
||||||
public ModFileScanData scan() {
|
public ModFileScanData scan() {
|
||||||
ModFileScanData result = new ModFileScanData();
|
|
||||||
result.addModFileInfo(fileToScan.getModFileInfo());
|
result.addModFileInfo(fileToScan.getModFileInfo());
|
||||||
fileToScan.scanFile(p -> fileVisitor(p, result));
|
fileToScan.scanFile(this::fileVisitor);
|
||||||
final List<IModLanguageProvider> loaders = fileToScan.getLoaders();
|
final List<IModLanguageProvider> loaders = fileToScan.getLoaders();
|
||||||
if (loaders != null) {
|
if (loaders != null) {
|
||||||
loaders.forEach(loader -> {
|
for (IModLanguageProvider loader : loaders) {
|
||||||
LOGGER.debug(LogMarkers.SCAN, "Scanning {} with language loader {}", fileToScan.getFilePath(), loader.name());
|
if (DEBUG) LOGGER.debug("Scanning {} with language loader {}", fileToScan.getFilePath(), loader.name());
|
||||||
loader.getFileVisitor().accept(result);
|
loader.getFileVisitor().accept(result);
|
||||||
});
|
}
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void fileVisitor(final Path path, final ModFileScanData result) {
|
private void fileVisitor(final Path path) {
|
||||||
LOGGER.debug(LogMarkers.SCAN,"Scanning {} path {}", fileToScan, path);
|
try (InputStream in = Files.newInputStream(path)) {
|
||||||
try (InputStream in = Files.newInputStream(path)){
|
|
||||||
ModClassVisitor mcv = new ModClassVisitor();
|
ModClassVisitor mcv = new ModClassVisitor();
|
||||||
ClassReader cr = new ClassReader(in);
|
ClassReader cr = new ClassReader(in);
|
||||||
cr.accept(mcv, 0);
|
cr.accept(mcv, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
|
||||||
mcv.buildData(result.getClasses(), result.getAnnotations());
|
mcv.buildData(result.getClasses(), result.getAnnotations());
|
||||||
} catch (IOException | IllegalArgumentException e) {
|
} catch (IOException | IllegalArgumentException e) {
|
||||||
// mark path bad
|
// mark path bad
|
||||||
|
if (DEBUG) LOGGER.warn("Failed scanning {} path {}", fileToScan, path);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -24,8 +24,8 @@ import java.util.function.Supplier;
|
|||||||
@ApiStatus.Internal
|
@ApiStatus.Internal
|
||||||
class ArgumentList {
|
class ArgumentList {
|
||||||
private static final Logger LOGGER = LogUtils.getLogger();
|
private static final Logger LOGGER = LogUtils.getLogger();
|
||||||
private List<Supplier<String[]>> entries = new ArrayList<>();
|
private final List<Supplier<String[]>> entries = new ArrayList<>();
|
||||||
private Map<String, EntryValue> values = new HashMap<>();
|
private final Map<String, EntryValue> values = new HashMap<>();
|
||||||
|
|
||||||
public static ArgumentList from(String... args) {
|
public static ArgumentList from(String... args) {
|
||||||
ArgumentList ret = new ArgumentList();
|
ArgumentList ret = new ArgumentList();
|
||||||
@@ -77,8 +77,8 @@ class ArgumentList {
|
|||||||
|
|
||||||
public String[] getArguments() {
|
public String[] getArguments() {
|
||||||
return entries.stream()
|
return entries.stream()
|
||||||
.flatMap(e -> Arrays.asList(e.get()).stream())
|
.flatMap(e -> Arrays.stream(e.get()))
|
||||||
.toArray(size -> new String[size]);
|
.toArray(String[]::new);
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean hasValue(String key) {
|
public boolean hasValue(String key) {
|
||||||
@@ -122,7 +122,7 @@ class ArgumentList {
|
|||||||
return ent.getValue();
|
return ent.getValue();
|
||||||
}
|
}
|
||||||
|
|
||||||
private class EntryValue implements Supplier<String[]> {
|
private static final class EntryValue implements Supplier<String[]> {
|
||||||
private final String prefix;
|
private final String prefix;
|
||||||
private final String key;
|
private final String key;
|
||||||
private final boolean split;
|
private final boolean split;
|
||||||
|
|||||||
+1
-1
@@ -40,7 +40,7 @@ abstract class CommonDevLaunchHandler extends CommonLaunchHandler {
|
|||||||
String username = args.get("username");
|
String username = args.get("username");
|
||||||
if (username != null) { // Replace '#' placeholders with random numbers
|
if (username != null) { // Replace '#' placeholders with random numbers
|
||||||
Matcher m = Pattern.compile("#+").matcher(username);
|
Matcher m = Pattern.compile("#+").matcher(username);
|
||||||
StringBuffer replaced = new StringBuffer();
|
StringBuilder replaced = new StringBuilder();
|
||||||
while (m.find()) {
|
while (m.find()) {
|
||||||
m.appendReplacement(replaced, getRandomNumbers(m.group().length()));
|
m.appendReplacement(replaced, getRandomNumbers(m.group().length()));
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-8
@@ -7,7 +7,6 @@ package net.minecraftforge.fml.loading.targets;
|
|||||||
|
|
||||||
import com.mojang.logging.LogUtils;
|
import com.mojang.logging.LogUtils;
|
||||||
import cpw.mods.modlauncher.api.ILaunchHandlerService;
|
import cpw.mods.modlauncher.api.ILaunchHandlerService;
|
||||||
import cpw.mods.modlauncher.api.ITransformingClassLoaderBuilder;
|
|
||||||
import cpw.mods.modlauncher.api.ServiceRunner;
|
import cpw.mods.modlauncher.api.ServiceRunner;
|
||||||
import net.minecraftforge.fml.loading.FMLLoader;
|
import net.minecraftforge.fml.loading.FMLLoader;
|
||||||
import net.minecraftforge.api.distmarker.Dist;
|
import net.minecraftforge.api.distmarker.Dist;
|
||||||
@@ -19,7 +18,6 @@ import org.slf4j.Logger;
|
|||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.net.URI;
|
import java.net.URI;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.nio.file.Paths;
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -47,10 +45,6 @@ public abstract class CommonLaunchHandler implements ILaunchHandlerService {
|
|||||||
|
|
||||||
public abstract List<Path> getMinecraftPaths();
|
public abstract List<Path> getMinecraftPaths();
|
||||||
|
|
||||||
@Override
|
|
||||||
public void configureTransformationClassLoader(final ITransformingClassLoaderBuilder builder) {
|
|
||||||
}
|
|
||||||
|
|
||||||
protected String[] preLaunch(String[] arguments, ModuleLayer layer) {
|
protected String[] preLaunch(String[] arguments, ModuleLayer layer) {
|
||||||
URI uri;
|
URI uri;
|
||||||
try (var reader = layer.configuration().findModule("net.minecraftforge.fmlloader").orElseThrow().reference().open()) {
|
try (var reader = layer.configuration().findModule("net.minecraftforge.fmlloader").orElseThrow().reference().open()) {
|
||||||
@@ -79,7 +73,7 @@ public abstract class CommonLaunchHandler implements ILaunchHandlerService {
|
|||||||
protected static final LaunchType CLIENT = new LaunchType("client", "minecraft", "net.minecraft.client.main.Main", Dist.CLIENT, false);
|
protected static final LaunchType CLIENT = new LaunchType("client", "minecraft", "net.minecraft.client.main.Main", Dist.CLIENT, false);
|
||||||
protected static final LaunchType DATA = new LaunchType("data", "minecraft", "net.minecraft.data.Main", Dist.CLIENT, true);
|
protected static final LaunchType DATA = new LaunchType("data", "minecraft", "net.minecraft.data.Main", Dist.CLIENT, true);
|
||||||
protected static final LaunchType SERVER = new LaunchType("server", "minecraft", "net.minecraft.server.Main", Dist.DEDICATED_SERVER, false);
|
protected static final LaunchType SERVER = new LaunchType("server", "minecraft", "net.minecraft.server.Main", Dist.DEDICATED_SERVER, false);
|
||||||
protected static final LaunchType SERVER_GAMETEST = new LaunchType("server_gametest", "forge", "net.minecraftforge.gametest.GameTestMain", Dist.DEDICATED_SERVER, false);
|
protected static final LaunchType SERVER_GAMETEST = new LaunchType("server_gametest", "net.minecraftforge.forge", "net.minecraftforge.gametest.GameTestMain", Dist.DEDICATED_SERVER, false);
|
||||||
|
|
||||||
protected void runTarget(String module, String target, final String[] arguments, final ModuleLayer layer) throws Throwable {
|
protected void runTarget(String module, String target, final String[] arguments, final ModuleLayer layer) throws Throwable {
|
||||||
var mod = layer.findModule(module).orElse(null);
|
var mod = layer.findModule(module).orElse(null);
|
||||||
@@ -107,7 +101,7 @@ public abstract class CommonLaunchHandler implements ILaunchHandlerService {
|
|||||||
len += 2;
|
len += 2;
|
||||||
}
|
}
|
||||||
str = str.substring(0, str.length() - len);
|
str = str.substring(0, str.length() - len);
|
||||||
var path = Paths.get(URI.create(str));
|
var path = Path.of(URI.create(str));
|
||||||
return path;
|
return path;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+5
-5
@@ -9,7 +9,7 @@ import java.util.List;
|
|||||||
import org.jetbrains.annotations.ApiStatus;
|
import org.jetbrains.annotations.ApiStatus;
|
||||||
|
|
||||||
@ApiStatus.Internal
|
@ApiStatus.Internal
|
||||||
abstract class ForgeDevLaunchHandler extends CommonDevLaunchHandler {
|
sealed abstract class ForgeDevLaunchHandler extends CommonDevLaunchHandler {
|
||||||
private ForgeDevLaunchHandler(LaunchType type) {
|
private ForgeDevLaunchHandler(LaunchType type) {
|
||||||
super(type, "forge_dev_");
|
super(type, "forge_dev_");
|
||||||
}
|
}
|
||||||
@@ -33,25 +33,25 @@ abstract class ForgeDevLaunchHandler extends CommonDevLaunchHandler {
|
|||||||
return List.of(filtered);
|
return List.of(filtered);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class Client extends ForgeDevLaunchHandler {
|
public static final class Client extends ForgeDevLaunchHandler {
|
||||||
public Client() {
|
public Client() {
|
||||||
super(CLIENT);
|
super(CLIENT);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class Data extends ForgeDevLaunchHandler {
|
public static final class Data extends ForgeDevLaunchHandler {
|
||||||
public Data() {
|
public Data() {
|
||||||
super(DATA);
|
super(DATA);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class Server extends ForgeDevLaunchHandler {
|
public static final class Server extends ForgeDevLaunchHandler {
|
||||||
public Server() {
|
public Server() {
|
||||||
super(SERVER);
|
super(SERVER);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class ServerGameTest extends ForgeDevLaunchHandler {
|
public static final class ServerGameTest extends ForgeDevLaunchHandler {
|
||||||
public ServerGameTest() {
|
public ServerGameTest() {
|
||||||
super(SERVER_GAMETEST);
|
super(SERVER_GAMETEST);
|
||||||
}
|
}
|
||||||
|
|||||||
+35
-19
@@ -35,7 +35,7 @@ import net.minecraftforge.fml.loading.moddiscovery.AbstractModProvider;
|
|||||||
import net.minecraftforge.forgespi.locating.IModLocator;
|
import net.minecraftforge.forgespi.locating.IModLocator;
|
||||||
|
|
||||||
@ApiStatus.Internal
|
@ApiStatus.Internal
|
||||||
public class ForgeDevLocator extends AbstractModProvider implements IModLocator {
|
public final class ForgeDevLocator extends AbstractModProvider implements IModLocator {
|
||||||
private static final String PACK_META = "pack.mcmeta";
|
private static final String PACK_META = "pack.mcmeta";
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -60,7 +60,7 @@ public class ForgeDevLocator extends AbstractModProvider implements IModLocator
|
|||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<Path> getMods() {
|
private static List<Path> getMods() {
|
||||||
// Forge is an exploded directory as well
|
// Forge is an exploded directory as well
|
||||||
var minecraft = ForgeDevLaunchHandler.getPathFromResource("net/minecraft/client/Minecraft.class");
|
var minecraft = ForgeDevLaunchHandler.getPathFromResource("net/minecraft/client/Minecraft.class");
|
||||||
var forge = ForgeDevLaunchHandler.getPathFromResource("net/minecraftforge/common/MinecraftForge.class");
|
var forge = ForgeDevLaunchHandler.getPathFromResource("net/minecraftforge/common/MinecraftForge.class");
|
||||||
@@ -84,30 +84,31 @@ public class ForgeDevLocator extends AbstractModProvider implements IModLocator
|
|||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<Path> explodeTestMods(Path path) {
|
private static List<Path> explodeTestMods(Path path) {
|
||||||
var mod = new ArrayList<Path>();
|
var mod = new ArrayList<Path>();
|
||||||
var memory = Jimfs.newFileSystem();
|
var memory = Jimfs.newFileSystem();
|
||||||
|
|
||||||
// First lets find all class files, that have the @Mod annotation and map packages to modids.
|
// First lets find all class files, that have the @Mod annotation and map packages to modids.
|
||||||
var packages = findTestModPackages(path);
|
var packages = findTestModPackages(path);
|
||||||
for (var entry : packages.entrySet()) {
|
for (var entry : packages.entrySet()) {
|
||||||
var pkg = entry.getKey();
|
var pkg = entry.getKey() + '/';
|
||||||
var modids = entry.getValue();
|
var modids = entry.getValue();
|
||||||
|
|
||||||
// Find resource directories for every mod in this group
|
// Find resource directories for every mod in this group
|
||||||
var resourcePaths = new LinkedHashSet<Path>();
|
var paths = new LinkedHashSet<Path>();
|
||||||
for (var modid : modids) {
|
for (var modid : modids) {
|
||||||
var rsc = path.resolve(modid);
|
var rsc = path.resolve(modid);
|
||||||
if (Files.exists(rsc))
|
if (Files.exists(rsc))
|
||||||
resourcePaths.add(rsc);
|
paths.add(rsc);
|
||||||
}
|
}
|
||||||
|
|
||||||
var root = memory.getPath(modids.iterator().next()); // use the first modid as our root
|
var root = memory.getPath(modids.iterator().next()); // use the first modid as our root
|
||||||
buildModsToml(resourcePaths, modids, root);
|
buildModsToml(paths, modids, root);
|
||||||
buildPackMeta(resourcePaths, root);
|
buildPackMeta(paths, root);
|
||||||
|
moveModuleInfo(paths, root);
|
||||||
|
|
||||||
if (Files.exists(root))
|
if (Files.exists(root))
|
||||||
resourcePaths.add(root);
|
paths.add(root);
|
||||||
|
|
||||||
// We want just the class files from the root of the input paths. So make a new union with a filter.
|
// We want just the class files from the root of the input paths. So make a new union with a filter.
|
||||||
var classes = UnionHelper.newFileSystem(
|
var classes = UnionHelper.newFileSystem(
|
||||||
@@ -121,14 +122,10 @@ public class ForgeDevLocator extends AbstractModProvider implements IModLocator
|
|||||||
}, new Path[] { path }
|
}, new Path[] { path }
|
||||||
);
|
);
|
||||||
|
|
||||||
// And we want the resources, and none of the classes, just in case things get kinda fucky and somehow a package overlaps a sub package {shading?}
|
paths.addFirst(classes.getRootDirectories().iterator().next());
|
||||||
var resources = UnionHelper.newFileSystem((name, base) -> !name.endsWith(".class"), resourcePaths.toArray(Path[]::new));
|
|
||||||
|
|
||||||
// Union of unions, Yay!
|
// Union of unions, Yay!
|
||||||
var union = UnionHelper.newFileSystem(null, new Path[] {
|
var union = UnionHelper.newFileSystem(null, paths.stream().toArray(Path[]::new));
|
||||||
classes.getRootDirectories().iterator().next(),
|
|
||||||
resources.getRootDirectories().iterator().next()
|
|
||||||
});
|
|
||||||
mod.add(union.getRootDirectories().iterator().next());
|
mod.add(union.getRootDirectories().iterator().next());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -137,7 +134,7 @@ public class ForgeDevLocator extends AbstractModProvider implements IModLocator
|
|||||||
|
|
||||||
// Find all the @Mods so we can generate tomls, and so we can pick packages. Right now it doesn't allow mods in parent directories,
|
// Find all the @Mods so we can generate tomls, and so we can pick packages. Right now it doesn't allow mods in parent directories,
|
||||||
// I could make it merge all the way up, but I think this would be fine.
|
// I could make it merge all the way up, but I think this would be fine.
|
||||||
private Map<String, Set<String>> findTestModPackages(Path path) {
|
private static Map<String, Set<String>> findTestModPackages(Path path) {
|
||||||
var mods = new HashMap<String, Set<String>>();
|
var mods = new HashMap<String, Set<String>>();
|
||||||
try (var files = Files.walk(path)) {
|
try (var files = Files.walk(path)) {
|
||||||
var classes = files
|
var classes = files
|
||||||
@@ -190,7 +187,7 @@ public class ForgeDevLocator extends AbstractModProvider implements IModLocator
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Builds or update the mods.toml file for all @Mods in this package
|
// Builds or update the mods.toml file for all @Mods in this package
|
||||||
private void buildModsToml(Set<Path> resources, Set<String> modids, Path root) {
|
private static void buildModsToml(Set<Path> resources, Set<String> modids, Path root) {
|
||||||
var toml = resources.stream()
|
var toml = resources.stream()
|
||||||
.map(p -> p.resolve(MODS_TOML))
|
.map(p -> p.resolve(MODS_TOML))
|
||||||
.filter(Files::exists)
|
.filter(Files::exists)
|
||||||
@@ -226,7 +223,7 @@ public class ForgeDevLocator extends AbstractModProvider implements IModLocator
|
|||||||
}
|
}
|
||||||
|
|
||||||
for (var modid : modids) {
|
for (var modid : modids) {
|
||||||
if (!modlist.stream().anyMatch(c -> modid.equals(c.get("modId")))) {
|
if (modlist.stream().noneMatch(c -> modid.equals(c.get("modId")))) {
|
||||||
modified = true;
|
modified = true;
|
||||||
var tmp = Config.inMemory();
|
var tmp = Config.inMemory();
|
||||||
tmp.set("modId", modid);
|
tmp.set("modId", modid);
|
||||||
@@ -248,7 +245,7 @@ public class ForgeDevLocator extends AbstractModProvider implements IModLocator
|
|||||||
}
|
}
|
||||||
|
|
||||||
// This is optional, it just hides a warning screen when starting up. I should probably remove this once I restructure how data gen for test mods work and make it generate there.
|
// This is optional, it just hides a warning screen when starting up. I should probably remove this once I restructure how data gen for test mods work and make it generate there.
|
||||||
private void buildPackMeta(Set<Path> paths, Path root) {
|
private static void buildPackMeta(Set<Path> paths, Path root) {
|
||||||
var existing = paths.stream()
|
var existing = paths.stream()
|
||||||
.map(p -> p.resolve(PACK_META))
|
.map(p -> p.resolve(PACK_META))
|
||||||
.filter(Files::exists)
|
.filter(Files::exists)
|
||||||
@@ -274,6 +271,25 @@ public class ForgeDevLocator extends AbstractModProvider implements IModLocator
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static void moveModuleInfo(Set<Path> paths, Path root) {
|
||||||
|
var existing = paths.stream()
|
||||||
|
.map(p -> p.resolve("module-info.dat"))
|
||||||
|
.filter(Files::exists)
|
||||||
|
.findFirst()
|
||||||
|
.orElse(null);
|
||||||
|
|
||||||
|
if (existing == null)
|
||||||
|
return;
|
||||||
|
|
||||||
|
var target = root.resolve("module-info.class");
|
||||||
|
try {
|
||||||
|
Files.createDirectories(target.getParent());
|
||||||
|
Files.copy(existing, target);
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new IllegalStateException("Failed to copy module-info.dat to memory: " + target, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
private static <E extends Throwable, R> R sneak(Throwable e) throws E {
|
private static <E extends Throwable, R> R sneak(Throwable e) throws E {
|
||||||
throw (E)e;
|
throw (E)e;
|
||||||
|
|||||||
+4
-4
@@ -10,15 +10,15 @@ import java.util.List;
|
|||||||
import org.jetbrains.annotations.ApiStatus;
|
import org.jetbrains.annotations.ApiStatus;
|
||||||
|
|
||||||
@ApiStatus.Internal
|
@ApiStatus.Internal
|
||||||
abstract class ForgeProdLaunchHandler extends CommonLaunchHandler {
|
sealed abstract class ForgeProdLaunchHandler extends CommonLaunchHandler {
|
||||||
protected ForgeProdLaunchHandler(LaunchType type) {
|
protected ForgeProdLaunchHandler(LaunchType type) {
|
||||||
super(type, "forge_");
|
super(type, "forge_");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override public String getNaming() { return "srg"; }
|
@Override public String getNaming() { return "mcp"; }
|
||||||
@Override public boolean isProduction() { return true; }
|
@Override public boolean isProduction() { return true; }
|
||||||
|
|
||||||
public static class Client extends ForgeProdLaunchHandler {
|
public static final class Client extends ForgeProdLaunchHandler {
|
||||||
public Client() {
|
public Client() {
|
||||||
super(CLIENT);
|
super(CLIENT);
|
||||||
}
|
}
|
||||||
@@ -29,7 +29,7 @@ abstract class ForgeProdLaunchHandler extends CommonLaunchHandler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class Server extends ForgeProdLaunchHandler {
|
public static final class Server extends ForgeProdLaunchHandler {
|
||||||
public Server() {
|
public Server() {
|
||||||
super(SERVER);
|
super(SERVER);
|
||||||
}
|
}
|
||||||
|
|||||||
+5
-5
@@ -14,7 +14,7 @@ import org.jetbrains.annotations.ApiStatus;
|
|||||||
import cpw.mods.jarhandling.SecureJar;
|
import cpw.mods.jarhandling.SecureJar;
|
||||||
|
|
||||||
@ApiStatus.Internal
|
@ApiStatus.Internal
|
||||||
abstract class ForgeUserdevLaunchHandler extends CommonDevLaunchHandler {
|
sealed abstract class ForgeUserdevLaunchHandler extends CommonDevLaunchHandler {
|
||||||
private ForgeUserdevLaunchHandler(LaunchType type) {
|
private ForgeUserdevLaunchHandler(LaunchType type) {
|
||||||
super(type, "forge_userdev_");
|
super(type, "forge_userdev_");
|
||||||
}
|
}
|
||||||
@@ -33,25 +33,25 @@ abstract class ForgeUserdevLaunchHandler extends CommonDevLaunchHandler {
|
|||||||
return List.of(minecraft);
|
return List.of(minecraft);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class Client extends ForgeUserdevLaunchHandler {
|
public static final class Client extends ForgeUserdevLaunchHandler {
|
||||||
public Client() {
|
public Client() {
|
||||||
super(CLIENT);
|
super(CLIENT);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class Data extends ForgeUserdevLaunchHandler {
|
public static final class Data extends ForgeUserdevLaunchHandler {
|
||||||
public Data() {
|
public Data() {
|
||||||
super(DATA);
|
super(DATA);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class Server extends ForgeUserdevLaunchHandler {
|
public static final class Server extends ForgeUserdevLaunchHandler {
|
||||||
public Server() {
|
public Server() {
|
||||||
super(SERVER);
|
super(SERVER);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class ServerGameTest extends ForgeUserdevLaunchHandler {
|
public static final class ServerGameTest extends ForgeUserdevLaunchHandler {
|
||||||
public ServerGameTest() {
|
public ServerGameTest() {
|
||||||
super(SERVER_GAMETEST);
|
super(SERVER_GAMETEST);
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -12,7 +12,7 @@ import net.minecraftforge.fml.loading.moddiscovery.AbstractModProvider;
|
|||||||
import net.minecraftforge.forgespi.locating.IModLocator;
|
import net.minecraftforge.forgespi.locating.IModLocator;
|
||||||
|
|
||||||
@ApiStatus.Internal
|
@ApiStatus.Internal
|
||||||
public class ForgeUserdevLocator extends AbstractModProvider implements IModLocator {
|
public final class ForgeUserdevLocator extends AbstractModProvider implements IModLocator {
|
||||||
@Override
|
@Override
|
||||||
public String name() {
|
public String name() {
|
||||||
return "forge_userdev_locator";
|
return "forge_userdev_locator";
|
||||||
|
|||||||
+1
-2
@@ -25,7 +25,7 @@ import java.util.Set;
|
|||||||
*/
|
*/
|
||||||
public class StronglyConnectedComponentDetector<T> {
|
public class StronglyConnectedComponentDetector<T> {
|
||||||
private final Graph<T> graph;
|
private final Graph<T> graph;
|
||||||
private Map<T, Integer> ids;
|
private final Map<T, Integer> ids = new HashMap<>();
|
||||||
private T[] elements;
|
private T[] elements;
|
||||||
private int[] dfn;
|
private int[] dfn;
|
||||||
private int[] low;
|
private int[] low;
|
||||||
@@ -49,7 +49,6 @@ public class StronglyConnectedComponentDetector<T> {
|
|||||||
private void calculate() {
|
private void calculate() {
|
||||||
components = new HashSet<>();
|
components = new HashSet<>();
|
||||||
int t = 0;
|
int t = 0;
|
||||||
ids = new HashMap<>();
|
|
||||||
Set<T> nodes = graph.nodes();
|
Set<T> nodes = graph.nodes();
|
||||||
elements = (T[]) new Object[nodes.size()];
|
elements = (T[]) new Object[nodes.size()];
|
||||||
for (T node : nodes) {
|
for (T node : nodes) {
|
||||||
|
|||||||
+10
-5
@@ -4,9 +4,14 @@ org.gradle.jvmargs=-Xmx3G
|
|||||||
org.gradle.daemon=false
|
org.gradle.daemon=false
|
||||||
org.gradle.parallel=true
|
org.gradle.parallel=true
|
||||||
|
|
||||||
JAVA_VERSION=17
|
JAVA_VERSION=21
|
||||||
MC_VERSION=1.20.4
|
MC_VERSION=1.21.1
|
||||||
MC_NEXT_VERSION=1.21
|
MC_NEXT_VERSION=1.22
|
||||||
MCP_VERSION=20231207.112700
|
MCP_VERSION=20240808.132146
|
||||||
MAPPING_CHANNEL=official
|
MAPPING_CHANNEL=official
|
||||||
MAPPING_VERSION=1.20.4
|
MAPPING_VERSION=1.21.1
|
||||||
|
|
||||||
|
// Set to true before the first build of a new MC version, so we don't do compatibility checks
|
||||||
|
CHECK_COMPATIBILITY=false
|
||||||
|
// Set to true to allow for fuzzy patching. Useful during updateing
|
||||||
|
UPDATING=false
|
||||||
Vendored
BIN
Binary file not shown.
+2
-1
@@ -1,6 +1,7 @@
|
|||||||
distributionBase=GRADLE_USER_HOME
|
distributionBase=GRADLE_USER_HOME
|
||||||
distributionPath=wrapper/dists
|
distributionPath=wrapper/dists
|
||||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-all.zip
|
distributionUrl=https\://services.gradle.org/distributions/gradle-8.12.1-bin.zip
|
||||||
networkTimeout=10000
|
networkTimeout=10000
|
||||||
|
validateDistributionUrl=true
|
||||||
zipStoreBase=GRADLE_USER_HOME
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
zipStorePath=wrapper/dists
|
zipStorePath=wrapper/dists
|
||||||
@@ -83,7 +83,8 @@ done
|
|||||||
# This is normally unused
|
# This is normally unused
|
||||||
# shellcheck disable=SC2034
|
# shellcheck disable=SC2034
|
||||||
APP_BASE_NAME=${0##*/}
|
APP_BASE_NAME=${0##*/}
|
||||||
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
|
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||||
|
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
|
||||||
|
|
||||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||||
MAX_FD=maximum
|
MAX_FD=maximum
|
||||||
@@ -130,10 +131,13 @@ location of your Java installation."
|
|||||||
fi
|
fi
|
||||||
else
|
else
|
||||||
JAVACMD=java
|
JAVACMD=java
|
||||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
if ! command -v java >/dev/null 2>&1
|
||||||
|
then
|
||||||
|
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||||
|
|
||||||
Please set the JAVA_HOME variable in your environment to match the
|
Please set the JAVA_HOME variable in your environment to match the
|
||||||
location of your Java installation."
|
location of your Java installation."
|
||||||
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Increase the maximum file descriptors if we can.
|
# Increase the maximum file descriptors if we can.
|
||||||
@@ -141,7 +145,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
|||||||
case $MAX_FD in #(
|
case $MAX_FD in #(
|
||||||
max*)
|
max*)
|
||||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||||
# shellcheck disable=SC3045
|
# shellcheck disable=SC2039,SC3045
|
||||||
MAX_FD=$( ulimit -H -n ) ||
|
MAX_FD=$( ulimit -H -n ) ||
|
||||||
warn "Could not query maximum file descriptor limit"
|
warn "Could not query maximum file descriptor limit"
|
||||||
esac
|
esac
|
||||||
@@ -149,7 +153,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
|||||||
'' | soft) :;; #(
|
'' | soft) :;; #(
|
||||||
*)
|
*)
|
||||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||||
# shellcheck disable=SC3045
|
# shellcheck disable=SC2039,SC3045
|
||||||
ulimit -n "$MAX_FD" ||
|
ulimit -n "$MAX_FD" ||
|
||||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||||
esac
|
esac
|
||||||
@@ -198,11 +202,11 @@ fi
|
|||||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||||
|
|
||||||
# Collect all arguments for the java command;
|
# Collect all arguments for the java command:
|
||||||
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
|
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||||
# shell script including quotes and variable substitutions, so put them in
|
# and any embedded shellness will be escaped.
|
||||||
# double quotes to make sure that they get re-expanded; and
|
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||||
# * put everything else in single quotes, so that it's not re-expanded.
|
# treated as '${Hostname}' itself on the command line.
|
||||||
|
|
||||||
set -- \
|
set -- \
|
||||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||||
|
|||||||
Vendored
+10
-10
@@ -43,11 +43,11 @@ set JAVA_EXE=java.exe
|
|||||||
%JAVA_EXE% -version >NUL 2>&1
|
%JAVA_EXE% -version >NUL 2>&1
|
||||||
if %ERRORLEVEL% equ 0 goto execute
|
if %ERRORLEVEL% equ 0 goto execute
|
||||||
|
|
||||||
echo.
|
echo. 1>&2
|
||||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||||
echo.
|
echo. 1>&2
|
||||||
echo Please set the JAVA_HOME variable in your environment to match the
|
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||||
echo location of your Java installation.
|
echo location of your Java installation. 1>&2
|
||||||
|
|
||||||
goto fail
|
goto fail
|
||||||
|
|
||||||
@@ -57,11 +57,11 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
|||||||
|
|
||||||
if exist "%JAVA_EXE%" goto execute
|
if exist "%JAVA_EXE%" goto execute
|
||||||
|
|
||||||
echo.
|
echo. 1>&2
|
||||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||||
echo.
|
echo. 1>&2
|
||||||
echo Please set the JAVA_HOME variable in your environment to match the
|
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||||
echo location of your Java installation.
|
echo location of your Java installation. 1>&2
|
||||||
|
|
||||||
goto fail
|
goto fail
|
||||||
|
|
||||||
|
|||||||
@@ -13,6 +13,8 @@ dependencies {
|
|||||||
compileOnly(libs.nulls)
|
compileOnly(libs.nulls)
|
||||||
implementation(project(':fmlloader'))
|
implementation(project(':fmlloader'))
|
||||||
implementation(project(':fmlcore'))
|
implementation(project(':fmlcore'))
|
||||||
|
implementation(libs.unsafe)
|
||||||
|
implementation(libs.securemodules)
|
||||||
}
|
}
|
||||||
|
|
||||||
java {
|
java {
|
||||||
@@ -57,7 +59,7 @@ publishing {
|
|||||||
license PomUtils.Licenses.LGPLv2_1
|
license PomUtils.Licenses.LGPLv2_1
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
repositories {
|
repositories {
|
||||||
maven gradleutils.publishingForgeMaven
|
maven gradleutils.publishingForgeMaven
|
||||||
}
|
}
|
||||||
|
|||||||
+13
-1
@@ -6,6 +6,7 @@
|
|||||||
package net.minecraftforge.fml.javafmlmod;
|
package net.minecraftforge.fml.javafmlmod;
|
||||||
|
|
||||||
import net.minecraftforge.api.distmarker.Dist;
|
import net.minecraftforge.api.distmarker.Dist;
|
||||||
|
import net.minecraftforge.api.distmarker.OnlyIn;
|
||||||
import net.minecraftforge.fml.Logging;
|
import net.minecraftforge.fml.Logging;
|
||||||
import net.minecraftforge.fml.ModContainer;
|
import net.minecraftforge.fml.ModContainer;
|
||||||
import net.minecraftforge.fml.common.Mod;
|
import net.minecraftforge.fml.common.Mod;
|
||||||
@@ -19,19 +20,21 @@ import org.apache.logging.log4j.LogManager;
|
|||||||
import org.apache.logging.log4j.Logger;
|
import org.apache.logging.log4j.Logger;
|
||||||
import org.objectweb.asm.Type;
|
import org.objectweb.asm.Type;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Automatic eventbus subscriber - reads {@link EventBusSubscriber}
|
* Automatic eventbus subscriber - reads {@link EventBusSubscriber}
|
||||||
* annotations and passes the class instances to the {@link nBus}
|
* 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 class AutomaticEventSubscriber {
|
public class AutomaticEventSubscriber {
|
||||||
private static final Logger LOGGER = LogManager.getLogger();
|
private static final Logger LOGGER = LogManager.getLogger();
|
||||||
private static final Type AUTO_SUBSCRIBER = Type.getType(EventBusSubscriber.class);
|
private static final Type AUTO_SUBSCRIBER = Type.getType(EventBusSubscriber.class);
|
||||||
private static final Type MOD_TYPE = Type.getType(Mod.class);
|
private static final Type MOD_TYPE = Type.getType(Mod.class);
|
||||||
|
private static final Type ONLY_IN_TYPE = Type.getType(OnlyIn.class);
|
||||||
|
|
||||||
public static void inject(ModContainer mod, ModFileScanData scanData, ClassLoader loader) {
|
public static void inject(ModContainer mod, ModFileScanData scanData, ClassLoader loader) {
|
||||||
if (scanData == null) return;
|
if (scanData == null) return;
|
||||||
@@ -41,6 +44,11 @@ public class AutomaticEventSubscriber {
|
|||||||
.filter(data -> AUTO_SUBSCRIBER.equals(data.annotationType()))
|
.filter(data -> AUTO_SUBSCRIBER.equals(data.annotationType()))
|
||||||
.toList();
|
.toList();
|
||||||
|
|
||||||
|
var onlyIns = FMLEnvironment.production ? Collections.emptySet() : scanData.getAnnotations().stream()
|
||||||
|
.filter(data -> ONLY_IN_TYPE.equals(data.annotationType()))
|
||||||
|
.map(data -> data.clazz().getClassName())
|
||||||
|
.collect(Collectors.toSet());
|
||||||
|
|
||||||
var modids = scanData.getAnnotations().stream()
|
var modids = scanData.getAnnotations().stream()
|
||||||
.filter(data -> MOD_TYPE.equals(data.annotationType()))
|
.filter(data -> MOD_TYPE.equals(data.annotationType()))
|
||||||
.collect(Collectors.toMap(a -> a.clazz().getClassName(), a -> (String)a.annotationData().get("value")));
|
.collect(Collectors.toMap(a -> a.clazz().getClassName(), a -> (String)a.annotationData().get("value")));
|
||||||
@@ -49,6 +57,10 @@ public class AutomaticEventSubscriber {
|
|||||||
var defaultBus = new EnumData(null, "FORGE");
|
var defaultBus = new EnumData(null, "FORGE");
|
||||||
|
|
||||||
for (var data : targets) {
|
for (var data : targets) {
|
||||||
|
if (!FMLEnvironment.production && onlyIns.contains(data.clazz().getClassName())) {
|
||||||
|
throw new RuntimeException("Found @OnlyIn on @EventBusSubscriber class " + data.clazz().getClassName() + " - this is not allowed as it causes crashes. Remove the OnlyIn and set value=Dist.CLIENT in the EventBusSubscriber annotation instead");
|
||||||
|
}
|
||||||
|
|
||||||
var modId = modids.getOrDefault(data.clazz().getClassName(), mod.getModId());
|
var modId = modids.getOrDefault(data.clazz().getClassName(), mod.getModId());
|
||||||
modId = value(data, "modid", modId);
|
modId = value(data, "modid", modId);
|
||||||
|
|
||||||
|
|||||||
+2
-15
@@ -31,21 +31,8 @@ public class FMLJavaModLanguageProvider implements IModLanguageProvider
|
|||||||
{
|
{
|
||||||
private static final Logger LOGGER = LogManager.getLogger();
|
private static final Logger LOGGER = LogManager.getLogger();
|
||||||
|
|
||||||
private static class FMLModTarget implements IModLanguageProvider.IModLanguageLoader {
|
private record FMLModTarget(String className, String modId) implements IModLanguageProvider.IModLanguageLoader {
|
||||||
private static final Logger LOGGER = FMLJavaModLanguageProvider.LOGGER;
|
private static final Logger LOGGER = FMLJavaModLanguageProvider.LOGGER;
|
||||||
private final String className;
|
|
||||||
private final String modId;
|
|
||||||
|
|
||||||
private FMLModTarget(String className, String modId)
|
|
||||||
{
|
|
||||||
this.className = className;
|
|
||||||
this.modId = modId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getModId()
|
|
||||||
{
|
|
||||||
return modId;
|
|
||||||
}
|
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
@Override
|
@Override
|
||||||
@@ -94,7 +81,7 @@ public class FMLJavaModLanguageProvider implements IModLanguageProvider
|
|||||||
.filter(ad -> ad.annotationType().equals(MODANNOTATION))
|
.filter(ad -> ad.annotationType().equals(MODANNOTATION))
|
||||||
.peek(ad -> LOGGER.debug(SCAN, "Found @Mod class {} with id {}", ad.clazz().getClassName(), ad.annotationData().get("value")))
|
.peek(ad -> LOGGER.debug(SCAN, "Found @Mod class {} with id {}", ad.clazz().getClassName(), ad.annotationData().get("value")))
|
||||||
.map(ad -> new FMLModTarget(ad.clazz().getClassName(), (String)ad.annotationData().get("value")))
|
.map(ad -> new FMLModTarget(ad.clazz().getClassName(), (String)ad.annotationData().get("value")))
|
||||||
.collect(Collectors.toMap(FMLModTarget::getModId, Function.identity(), (a,b)->a));
|
.collect(Collectors.toMap(FMLModTarget::modId, Function.identity(), (a,b)->a));
|
||||||
scanResult.addLanguageLoader(modTargetMap);
|
scanResult.addLanguageLoader(modTargetMap);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
+14
-1
@@ -8,7 +8,10 @@ package net.minecraftforge.fml.javafmlmod;
|
|||||||
import net.minecraftforge.eventbus.api.IEventBus;
|
import net.minecraftforge.eventbus.api.IEventBus;
|
||||||
import net.minecraftforge.fml.ModLoadingContext;
|
import net.minecraftforge.fml.ModLoadingContext;
|
||||||
|
|
||||||
public class FMLJavaModLoadingContext
|
/**
|
||||||
|
* Use the context provided by your language loader in your mod's constructor
|
||||||
|
*/
|
||||||
|
public class FMLJavaModLoadingContext extends ModLoadingContext
|
||||||
{
|
{
|
||||||
private final FMLModContainer container;
|
private final FMLModContainer container;
|
||||||
|
|
||||||
@@ -24,11 +27,21 @@ public class FMLJavaModLoadingContext
|
|||||||
return container.getEventBus();
|
return container.getEventBus();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return {@link FMLModContainer} by default.
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public FMLModContainer getContainer() {
|
||||||
|
return container;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Helper to get the right instance from the {@link ModLoadingContext} correctly.
|
* Helper to get the right instance from the {@link ModLoadingContext} correctly.
|
||||||
* @return The FMLJavaMod language specific extension from the ModLoadingContext
|
* @return The FMLJavaMod language specific extension from the ModLoadingContext
|
||||||
|
*
|
||||||
|
* @deprecated use {@link FMLJavaModLoadingContext} in your mod constructor
|
||||||
*/
|
*/
|
||||||
|
@Deprecated(forRemoval = true, since="1.21.1")
|
||||||
public static FMLJavaModLoadingContext get() {
|
public static FMLJavaModLoadingContext get() {
|
||||||
return ModLoadingContext.get().extension();
|
return ModLoadingContext.get().extension();
|
||||||
}
|
}
|
||||||
|
|||||||
+87
-8
@@ -16,14 +16,21 @@ import net.minecraftforge.fml.ModLoadingStage;
|
|||||||
import net.minecraftforge.fml.event.IModBusEvent;
|
import net.minecraftforge.fml.event.IModBusEvent;
|
||||||
import net.minecraftforge.forgespi.language.IModInfo;
|
import net.minecraftforge.forgespi.language.IModInfo;
|
||||||
import net.minecraftforge.forgespi.language.ModFileScanData;
|
import net.minecraftforge.forgespi.language.ModFileScanData;
|
||||||
|
import net.minecraftforge.unsafe.UnsafeHacks;
|
||||||
|
|
||||||
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.apache.logging.log4j.Marker;
|
import org.apache.logging.log4j.Marker;
|
||||||
import org.apache.logging.log4j.MarkerManager;
|
import org.apache.logging.log4j.MarkerManager;
|
||||||
|
|
||||||
|
import cpw.mods.jarhandling.SecureJar;
|
||||||
|
|
||||||
|
import java.lang.reflect.Constructor;
|
||||||
import java.lang.reflect.InvocationTargetException;
|
import java.lang.reflect.InvocationTargetException;
|
||||||
|
import java.lang.reflect.Method;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
import java.util.jar.Attributes;
|
||||||
|
|
||||||
public class FMLModContainer extends ModContainer {
|
public class FMLModContainer extends ModContainer {
|
||||||
private static final Logger LOGGER = LogManager.getLogger();
|
private static final Logger LOGGER = LogManager.getLogger();
|
||||||
@@ -32,38 +39,110 @@ public class FMLModContainer extends ModContainer {
|
|||||||
private final IEventBus eventBus;
|
private final IEventBus eventBus;
|
||||||
private Object modInstance;
|
private Object modInstance;
|
||||||
private final Class<?> modClass;
|
private final Class<?> modClass;
|
||||||
|
private final FMLJavaModLoadingContext context = new FMLJavaModLoadingContext(this);
|
||||||
|
|
||||||
public FMLModContainer(IModInfo info, String className, ModFileScanData modFileScanResults, ModuleLayer gameLayer) {
|
public FMLModContainer(IModInfo info, String className, ModFileScanData modFileScanResults, ModuleLayer gameLayer) {
|
||||||
super(info);
|
super(info);
|
||||||
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.eventBus = BusBuilder.builder().setExceptionHandler(this::onEventFailed).setTrackPhases(false).markerType(IModBusEvent.class).useModLauncher().build();
|
this.eventBus = BusBuilder.builder().setExceptionHandler(FMLModContainer::onEventFailed).setTrackPhases(false).markerType(IModBusEvent.class).useModLauncher().build();
|
||||||
this.configHandler = Optional.of(ce->this.eventBus.post(ce.self()));
|
this.configHandler = Optional.of(ce->this.eventBus.post(ce.self()));
|
||||||
final FMLJavaModLoadingContext contextExtension = new FMLJavaModLoadingContext(this);
|
this.contextExtension = () -> context;
|
||||||
this.contextExtension = () -> contextExtension;
|
|
||||||
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
var moduleName = info.getOwningFile().moduleName();
|
var moduleName = info.getOwningFile().moduleName();
|
||||||
var module = gameLayer.findModule(moduleName)
|
var module = gameLayer.findModule(moduleName)
|
||||||
.orElseThrow(() -> new IllegalStateException("Failed to find " + moduleName + " in " + gameLayer));
|
.orElseThrow(() -> new IllegalStateException("Failed to find " + moduleName + " in " + gameLayer));
|
||||||
|
|
||||||
|
openModules(gameLayer, module, info.getOwningFile().getFile().getSecureJar());
|
||||||
|
|
||||||
modClass = Class.forName(module, className);
|
modClass = Class.forName(module, className);
|
||||||
LOGGER.trace(LOADING,"Loaded modclass {} with {}", modClass.getName(), modClass.getClassLoader());
|
LOGGER.debug(LOADING,"Loaded modclass {}/{} with {}", modClass.getModule().getName(), modClass.getName(), modClass.getClassLoader());
|
||||||
} catch (Throwable e) {
|
} catch (Throwable e) {
|
||||||
LOGGER.error(LOADING, "Failed to load class {}", className, e);
|
LOGGER.error(LOADING, "Failed to load class {}", className, e);
|
||||||
throw new ModLoadingException(info, ModLoadingStage.CONSTRUCT, "fml.modloading.failedtoloadmodclass", e);
|
throw new ModLoadingException(info, ModLoadingStage.CONSTRUCT, "fml.modloading.failedtoloadmodclass", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void onEventFailed(IEventBus iEventBus, Event event, IEventListener[] iEventListeners, int i, Throwable throwable) {
|
/**
|
||||||
|
* <pre>
|
||||||
|
* Reads the Add-Exports and Add-Opens attributes (see note) from a mod file and
|
||||||
|
* attempts to apply them. This differers from the JEP in two significant ways:
|
||||||
|
* 1) Instead of opening things to ALL-UNNAMED it instead only opens to the
|
||||||
|
* mod's module itself. Because I don't want other mods accidently relying
|
||||||
|
* on transitive behavior
|
||||||
|
* 2) It is read from all mods not just the executable jars.
|
||||||
|
*
|
||||||
|
* From <a href = "https://openjdk.org/jeps/261">JEP 261: Module System</a>
|
||||||
|
*
|
||||||
|
* Two new JDK-specific JAR-file manifest attributes are defined to correspond
|
||||||
|
* to the --add-exports and --add-opens command-line options:
|
||||||
|
* Add-Exports: <module>/<package>( <module>/<package>)*
|
||||||
|
* Add-Opens: <module>/<package>( <module>/<package>)*
|
||||||
|
*
|
||||||
|
* The value of each attribute is a space-separated list of slash-separated
|
||||||
|
* module-name/package-name pairs. A >module</>package< pair in
|
||||||
|
* the value of an Add-Exports attribute has the same meaning as the
|
||||||
|
* command-line option --add-exports >module</>package<=ALL-UNNAMED.
|
||||||
|
*
|
||||||
|
* A >module</>package< pair in the value of an Add-Opens attribute has the
|
||||||
|
* same meaning as the command-line option --add-opens >module</>package<=ALL-UNNAMED.
|
||||||
|
*
|
||||||
|
* Each attribute can occur at most once, in the main section of a MANIFEST.MF file.
|
||||||
|
* A particular pair can be listed more than once. If a specified module was not
|
||||||
|
* resolved, or if a specified package does not exist, then the corresponding pair
|
||||||
|
* is ignored.
|
||||||
|
*/
|
||||||
|
private static void openModules(ModuleLayer layer, Module self, SecureJar jar) throws NoSuchMethodException, SecurityException, IllegalAccessException, InvocationTargetException {
|
||||||
|
var manifest = jar.moduleDataProvider().getManifest().getMainAttributes();
|
||||||
|
addOpenOrExports(layer, self, true, manifest);
|
||||||
|
addOpenOrExports(layer, self, false, manifest);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void addOpenOrExports(ModuleLayer layer, Module self, boolean open, Attributes attrs) throws NoSuchMethodException, SecurityException, IllegalAccessException, InvocationTargetException {
|
||||||
|
var key = open ? "Add-Opens" : "Add-Exports";
|
||||||
|
var entry = attrs.getValue(key);
|
||||||
|
if (entry == null)
|
||||||
|
return;
|
||||||
|
|
||||||
|
for (var pair : entry.split(" ")) {
|
||||||
|
var pts = pair.trim().split("/");
|
||||||
|
if (pts.length == 2) {
|
||||||
|
var target = layer.findModule(pts[0]).orElse(null);
|
||||||
|
if (target == null || !target.getDescriptor().packages().contains(pts[1]))
|
||||||
|
continue;
|
||||||
|
addOpenOrExport(target, pts[1], self, open);
|
||||||
|
} else {
|
||||||
|
LOGGER.warn(LOADING, "Invalid {} entry in {}: {}", key, self.getName(), pair);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Method implAddExportsOrOpens;
|
||||||
|
private static void addOpenOrExport(Module target, String pkg, Module reader, boolean open) throws NoSuchMethodException, SecurityException, IllegalAccessException, InvocationTargetException {
|
||||||
|
if (implAddExportsOrOpens == null) {
|
||||||
|
implAddExportsOrOpens = Module.class.getDeclaredMethod("implAddExportsOrOpens", String.class, Module.class, boolean.class, boolean.class);
|
||||||
|
UnsafeHacks.setAccessible(implAddExportsOrOpens);
|
||||||
|
}
|
||||||
|
|
||||||
|
LOGGER.info(LOADING, "{} {}/{} to {}", open ? "Opening" : "Exporting", target.getName(), pkg, reader.getName());
|
||||||
|
implAddExportsOrOpens.invoke(target, pkg, reader, open, /*syncVM*/true);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void onEventFailed(IEventBus iEventBus, Event event, IEventListener[] iEventListeners, int i, Throwable throwable) {
|
||||||
LOGGER.error(new EventBusErrorMessage(event, i, iEventListeners, throwable));
|
LOGGER.error(new EventBusErrorMessage(event, i, iEventListeners, throwable));
|
||||||
}
|
}
|
||||||
|
|
||||||
private void constructMod() {
|
private void constructMod() {
|
||||||
try {
|
try {
|
||||||
LOGGER.trace(LOADING, "Loading mod instance {} of type {}", getModId(), modClass.getName());
|
LOGGER.trace(LOADING, "Loading mod instance {} of type {}", getModId(), modClass.getName());
|
||||||
this.modInstance = modClass.getDeclaredConstructor().newInstance();
|
Constructor<?> constructor;
|
||||||
|
try {
|
||||||
|
constructor = modClass.getDeclaredConstructor(context.getClass());
|
||||||
|
} catch (NoSuchMethodException | SecurityException exception) {
|
||||||
|
constructor = modClass.getDeclaredConstructor();
|
||||||
|
}
|
||||||
|
this.modInstance = constructor.getParameterCount() == 0 ? constructor.newInstance() : constructor.newInstance(context);
|
||||||
LOGGER.trace(LOADING, "Loaded mod instance {} of type {}", getModId(), modClass.getName());
|
LOGGER.trace(LOADING, "Loaded mod instance {} of type {}", getModId(), modClass.getName());
|
||||||
} catch (Throwable e) {
|
} catch (Throwable e) {
|
||||||
// When a mod constructor throws an exception, it's wrapped in an InvocationTargetException which hides the
|
// When a mod constructor throws an exception, it's wrapped in an InvocationTargetException which hides the
|
||||||
|
|||||||
+1
-8
@@ -21,14 +21,12 @@ import static net.minecraftforge.fml.loading.LogMarkers.LOADING;
|
|||||||
public class LowCodeModContainer extends ModContainer
|
public class LowCodeModContainer extends ModContainer
|
||||||
{
|
{
|
||||||
private static final Logger LOGGER = LogUtils.getLogger();
|
private static final Logger LOGGER = LogUtils.getLogger();
|
||||||
private final ModFileScanData scanResults;
|
private final Object modInstance;
|
||||||
private Object modInstance;
|
|
||||||
|
|
||||||
public LowCodeModContainer(IModInfo info, ModFileScanData modFileScanResults, ModuleLayer gameLayer)
|
public LowCodeModContainer(IModInfo info, ModFileScanData modFileScanResults, ModuleLayer gameLayer)
|
||||||
{
|
{
|
||||||
super(info);
|
super(info);
|
||||||
LOGGER.debug(LOADING, "Creating LowCodeModContainer for {}", info.getModId());
|
LOGGER.debug(LOADING, "Creating LowCodeModContainer for {}", info.getModId());
|
||||||
this.scanResults = modFileScanResults;
|
|
||||||
this.modInstance = new Object();
|
this.modInstance = new Object();
|
||||||
this.contextExtension = () -> null;
|
this.contextExtension = () -> null;
|
||||||
this.extensionPoints.remove(IExtensionPoint.DisplayTest.class);
|
this.extensionPoints.remove(IExtensionPoint.DisplayTest.class);
|
||||||
@@ -45,9 +43,4 @@ public class LowCodeModContainer extends ModContainer
|
|||||||
{
|
{
|
||||||
return modInstance;
|
return modInstance;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
protected <T extends Event & IModBusEvent> void acceptEvent(final T e)
|
|
||||||
{
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
-4
@@ -5,7 +5,6 @@
|
|||||||
|
|
||||||
package net.minecraftforge.fml.mclanguageprovider;
|
package net.minecraftforge.fml.mclanguageprovider;
|
||||||
|
|
||||||
import net.minecraftforge.fml.ModContainer;
|
|
||||||
import net.minecraftforge.forgespi.language.ILifecycleEvent;
|
import net.minecraftforge.forgespi.language.ILifecycleEvent;
|
||||||
import net.minecraftforge.forgespi.language.IModInfo;
|
import net.minecraftforge.forgespi.language.IModInfo;
|
||||||
import net.minecraftforge.forgespi.language.IModLanguageProvider;
|
import net.minecraftforge.forgespi.language.IModLanguageProvider;
|
||||||
@@ -15,14 +14,11 @@ import org.apache.logging.log4j.Logger;
|
|||||||
|
|
||||||
import java.lang.reflect.InvocationTargetException;
|
import java.lang.reflect.InvocationTargetException;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Objects;
|
|
||||||
import java.util.function.Consumer;
|
import java.util.function.Consumer;
|
||||||
import java.util.function.Supplier;
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
import static net.minecraftforge.fml.Logging.LOADING;
|
import static net.minecraftforge.fml.Logging.LOADING;
|
||||||
|
|
||||||
import net.minecraftforge.forgespi.language.IModLanguageProvider.IModLanguageLoader;
|
|
||||||
|
|
||||||
public class MinecraftModLanguageProvider implements IModLanguageProvider {
|
public class MinecraftModLanguageProvider implements IModLanguageProvider {
|
||||||
private static final Logger LOGGER = LogManager.getLogger();
|
private static final Logger LOGGER = LogManager.getLogger();
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
+14
-15
@@ -2,7 +2,7 @@ plugins {
|
|||||||
id 'eclipse'
|
id 'eclipse'
|
||||||
id 'idea'
|
id 'idea'
|
||||||
id 'maven-publish'
|
id 'maven-publish'
|
||||||
id 'net.minecraftforge.gradle' version '[6.0.16,6.2)'
|
id 'net.minecraftforge.gradle' version '[6.0.24,6.2)'
|
||||||
}
|
}
|
||||||
|
|
||||||
version = mod_version
|
version = mod_version
|
||||||
@@ -12,8 +12,8 @@ base {
|
|||||||
archivesName = mod_id
|
archivesName = mod_id
|
||||||
}
|
}
|
||||||
|
|
||||||
// Mojang ships Java 17 to end users in 1.18+, so your mod should target Java 17.
|
// Mojang ships Java 21 to end users in 1.20.5+, so your mod should target Java 21.
|
||||||
java.toolchain.languageVersion = JavaLanguageVersion.of(17)
|
java.toolchain.languageVersion = JavaLanguageVersion.of(21)
|
||||||
|
|
||||||
println "Java: ${System.getProperty 'java.version'}, JVM: ${System.getProperty 'java.vm.version'} (${System.getProperty 'java.vendor'}), Arch: ${System.getProperty 'os.arch'}"
|
println "Java: ${System.getProperty 'java.version'}, JVM: ${System.getProperty 'java.vm.version'} (${System.getProperty 'java.vendor'}), Arch: ${System.getProperty 'os.arch'}"
|
||||||
minecraft {
|
minecraft {
|
||||||
@@ -31,6 +31,9 @@ minecraft {
|
|||||||
// Use non-default mappings at your own risk. They may not always work.
|
// Use non-default mappings at your own risk. They may not always work.
|
||||||
// Simply re-run your setup task after changing the mappings to update your workspace.
|
// Simply re-run your setup task after changing the mappings to update your workspace.
|
||||||
mappings channel: mapping_channel, version: mapping_version
|
mappings channel: mapping_channel, version: mapping_version
|
||||||
|
|
||||||
|
// Tell FG to not automtically create the reobf tasks, as we now use Official mappings at runtime, If you don't use them at dev time then you'll have to fix your reobf yourself.
|
||||||
|
reobf = false
|
||||||
|
|
||||||
// When true, this property will have all Eclipse/IntelliJ IDEA run configurations run the "prepareX" task for the given run configuration before launching the game.
|
// When true, this property will have all Eclipse/IntelliJ IDEA run configurations run the "prepareX" task for the given run configuration before launching the game.
|
||||||
// In most cases, it is not necessary to enable.
|
// In most cases, it is not necessary to enable.
|
||||||
@@ -124,11 +127,11 @@ dependencies {
|
|||||||
// then special handling is done to allow a setup of a vanilla dependency without the use of an external repository.
|
// then special handling is done to allow a setup of a vanilla dependency without the use of an external repository.
|
||||||
minecraft "net.minecraftforge:forge:${minecraft_version}-${forge_version}"
|
minecraft "net.minecraftforge:forge:${minecraft_version}-${forge_version}"
|
||||||
|
|
||||||
// Example mod dependency with JEI - using fg.deobf() ensures the dependency is remapped to your development mappings
|
// Example mod dependency with JEI
|
||||||
// The JEI API is declared for compile time use, while the full JEI artifact is used at runtime
|
// The JEI API is declared for compile time use, while the full JEI artifact is used at runtime
|
||||||
// compileOnly fg.deobf("mezz.jei:jei-${mc_version}-common-api:${jei_version}")
|
// compileOnly "mezz.jei:jei-${mc_version}-common-api:${jei_version}"
|
||||||
// compileOnly fg.deobf("mezz.jei:jei-${mc_version}-forge-api:${jei_version}")
|
// compileOnly "mezz.jei:jei-${mc_version}-forge-api:${jei_version}"
|
||||||
// runtimeOnly fg.deobf("mezz.jei:jei-${mc_version}-forge:${jei_version}")
|
// runtimeOnly "mezz.jei:jei-${mc_version}-forge:${jei_version}"
|
||||||
|
|
||||||
// Example mod dependency using a mod jar from ./libs with a flat dir repository
|
// Example mod dependency using a mod jar from ./libs with a flat dir repository
|
||||||
// This maps to ./libs/coolmod-${mc_version}-${coolmod_version}.jar
|
// This maps to ./libs/coolmod-${mc_version}-${coolmod_version}.jar
|
||||||
@@ -171,16 +174,8 @@ tasks.named('jar', Jar).configure {
|
|||||||
'Implementation-Vendor' : mod_authors
|
'Implementation-Vendor' : mod_authors
|
||||||
])
|
])
|
||||||
}
|
}
|
||||||
|
|
||||||
// This is the preferred method to reobfuscate your jar file
|
|
||||||
finalizedBy 'reobfJar'
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// However if you are in a multi-project build, dev time needs unobfed jar files, so you can delay the obfuscation until publishing by doing:
|
|
||||||
// tasks.named('publish').configure {
|
|
||||||
// dependsOn 'reobfJar'
|
|
||||||
// }
|
|
||||||
|
|
||||||
// Example configuration to allow publishing using the maven-publish plugin
|
// Example configuration to allow publishing using the maven-publish plugin
|
||||||
publishing {
|
publishing {
|
||||||
publications {
|
publications {
|
||||||
@@ -199,6 +194,10 @@ tasks.withType(JavaCompile).configureEach {
|
|||||||
options.encoding = 'UTF-8' // Use the UTF-8 charset for Java compilation
|
options.encoding = 'UTF-8' // Use the UTF-8 charset for Java compilation
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// IntelliJ no longer downloads javadocs and sources by default.
|
||||||
|
// This tells Gradle to force IDEA to do it.
|
||||||
|
idea.module { downloadJavadoc = downloadSources = true }
|
||||||
|
|
||||||
eclipse {
|
eclipse {
|
||||||
// Run everytime eclipse builds the code
|
// Run everytime eclipse builds the code
|
||||||
//autoBuildTasks genEclipseRuns
|
//autoBuildTasks genEclipseRuns
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ public class Config
|
|||||||
|
|
||||||
private static boolean validateItemName(final Object obj)
|
private static boolean validateItemName(final Object obj)
|
||||||
{
|
{
|
||||||
return obj instanceof final String itemName && ForgeRegistries.ITEMS.containsKey(new ResourceLocation(itemName));
|
return obj instanceof final String itemName && ForgeRegistries.ITEMS.containsKey(ResourceLocation.tryParse(itemName));
|
||||||
}
|
}
|
||||||
|
|
||||||
@SubscribeEvent
|
@SubscribeEvent
|
||||||
@@ -58,7 +58,7 @@ public class Config
|
|||||||
|
|
||||||
// convert the list of strings into a set of items
|
// convert the list of strings into a set of items
|
||||||
items = ITEM_STRINGS.get().stream()
|
items = ITEM_STRINGS.get().stream()
|
||||||
.map(itemName -> ForgeRegistries.ITEMS.getValue(new ResourceLocation(itemName)))
|
.map(itemName -> ForgeRegistries.ITEMS.getValue(ResourceLocation.tryParse(itemName)))
|
||||||
.collect(Collectors.toSet());
|
.collect(Collectors.toSet());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -18,7 +18,6 @@ import net.minecraftforge.event.BuildCreativeModeTabContentsEvent;
|
|||||||
import net.minecraftforge.event.server.ServerStartingEvent;
|
import net.minecraftforge.event.server.ServerStartingEvent;
|
||||||
import net.minecraftforge.eventbus.api.IEventBus;
|
import net.minecraftforge.eventbus.api.IEventBus;
|
||||||
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
import net.minecraftforge.eventbus.api.SubscribeEvent;
|
||||||
import net.minecraftforge.fml.ModLoadingContext;
|
|
||||||
import net.minecraftforge.fml.common.Mod;
|
import net.minecraftforge.fml.common.Mod;
|
||||||
import net.minecraftforge.fml.config.ModConfig;
|
import net.minecraftforge.fml.config.ModConfig;
|
||||||
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
|
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
|
||||||
@@ -51,7 +50,7 @@ public class ExampleMod
|
|||||||
|
|
||||||
// Creates a new food item with the id "examplemod:example_id", nutrition 1 and saturation 2
|
// Creates a new food item with the id "examplemod:example_id", nutrition 1 and saturation 2
|
||||||
public static final RegistryObject<Item> EXAMPLE_ITEM = ITEMS.register("example_item", () -> new Item(new Item.Properties().food(new FoodProperties.Builder()
|
public static final RegistryObject<Item> EXAMPLE_ITEM = ITEMS.register("example_item", () -> new Item(new Item.Properties().food(new FoodProperties.Builder()
|
||||||
.alwaysEat().nutrition(1).saturationMod(2f).build())));
|
.alwaysEdible().nutrition(1).saturationModifier(2f).build())));
|
||||||
|
|
||||||
// Creates a creative tab with the id "examplemod:example_tab" for the example item, that is placed after the combat tab
|
// Creates a creative tab with the id "examplemod:example_tab" for the example item, that is placed after the combat tab
|
||||||
public static final RegistryObject<CreativeModeTab> EXAMPLE_TAB = CREATIVE_MODE_TABS.register("example_tab", () -> CreativeModeTab.builder()
|
public static final RegistryObject<CreativeModeTab> EXAMPLE_TAB = CREATIVE_MODE_TABS.register("example_tab", () -> CreativeModeTab.builder()
|
||||||
@@ -61,9 +60,9 @@ public class ExampleMod
|
|||||||
output.accept(EXAMPLE_ITEM.get()); // Add the example item to the tab. For your own tabs, this method is preferred over the event
|
output.accept(EXAMPLE_ITEM.get()); // Add the example item to the tab. For your own tabs, this method is preferred over the event
|
||||||
}).build());
|
}).build());
|
||||||
|
|
||||||
public ExampleMod()
|
public ExampleMod(FMLJavaModLoadingContext context)
|
||||||
{
|
{
|
||||||
IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();
|
IEventBus modEventBus = context.getModEventBus();
|
||||||
|
|
||||||
// Register the commonSetup method for modloading
|
// Register the commonSetup method for modloading
|
||||||
modEventBus.addListener(this::commonSetup);
|
modEventBus.addListener(this::commonSetup);
|
||||||
@@ -82,7 +81,7 @@ public class ExampleMod
|
|||||||
modEventBus.addListener(this::addCreative);
|
modEventBus.addListener(this::addCreative);
|
||||||
|
|
||||||
// Register our mod's ForgeConfigSpec so that Forge can create and load the config file for us
|
// Register our mod's ForgeConfigSpec so that Forge can create and load the config file for us
|
||||||
ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, Config.SPEC);
|
context.registerConfig(ModConfig.Type.COMMON, Config.SPEC);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void commonSetup(final FMLCommonSetupEvent event)
|
private void commonSetup(final FMLCommonSetupEvent event)
|
||||||
|
|||||||
@@ -1,56 +1,55 @@
|
|||||||
--- 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
|
||||||
@@ -113,7 +_,10 @@
|
@@ -104,7 +_,10 @@
|
||||||
GlStateManager._texParameter(3553, 34892, 0);
|
GlStateManager._texParameter(3553, 34892, 0);
|
||||||
GlStateManager._texParameter(3553, 10242, 33071);
|
GlStateManager._texParameter(3553, 10242, 33071);
|
||||||
GlStateManager._texParameter(3553, 10243, 33071);
|
GlStateManager._texParameter(3553, 10243, 33071);
|
||||||
+ if (!stencilEnabled)
|
+ if (!stencilEnabled)
|
||||||
GlStateManager._texImage2D(3553, 0, 6402, this.width, this.height, 0, 6402, 5126, (IntBuffer)null);
|
GlStateManager._texImage2D(3553, 0, 6402, this.width, this.height, 0, 6402, 5126, null);
|
||||||
+ else
|
+ else
|
||||||
+ GlStateManager._texImage2D(3553, 0, org.lwjgl.opengl.GL30.GL_DEPTH32F_STENCIL8, this.width, this.height, 0, org.lwjgl.opengl.GL30.GL_DEPTH_STENCIL, org.lwjgl.opengl.GL30.GL_FLOAT_32_UNSIGNED_INT_24_8_REV, null);
|
+ GlStateManager._texImage2D(3553, 0, org.lwjgl.opengl.GL30.GL_DEPTH32F_STENCIL8, this.width, this.height, 0, org.lwjgl.opengl.GL30.GL_DEPTH_STENCIL, org.lwjgl.opengl.GL30.GL_FLOAT_32_UNSIGNED_INT_24_8_REV, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
this.setFilterMode(9728);
|
this.setFilterMode(9728, true);
|
||||||
@@ -124,7 +_,14 @@
|
@@ -114,8 +_,13 @@
|
||||||
GlStateManager._glBindFramebuffer(36160, this.frameBufferId);
|
GlStateManager._texImage2D(3553, 0, 32856, this.width, this.height, 0, 6408, 5121, null);
|
||||||
GlStateManager._glFramebufferTexture2D(36160, 36064, 3553, this.colorTextureId, 0);
|
GlStateManager._glBindFramebuffer(36160, this.frameBufferId);
|
||||||
if (this.useDepth) {
|
GlStateManager._glFramebufferTexture2D(36160, 36064, 3553, this.colorTextureId, 0);
|
||||||
+ if(!stencilEnabled)
|
- if (this.useDepth) {
|
||||||
GlStateManager._glFramebufferTexture2D(36160, 36096, 3553, this.depthBufferId, 0);
|
+ if (this.useDepth && !stencilEnabled) {
|
||||||
+ else if(net.minecraftforge.common.ForgeConfig.CLIENT.useCombinedDepthStencilAttachment.get()) {
|
GlStateManager._glFramebufferTexture2D(36160, 36096, 3553, this.depthBufferId, 0);
|
||||||
+ GlStateManager._glFramebufferTexture2D(org.lwjgl.opengl.GL30.GL_FRAMEBUFFER, org.lwjgl.opengl.GL30.GL_DEPTH_STENCIL_ATTACHMENT, 3553, this.depthBufferId, 0);
|
+ } else if(this.useDepth && net.minecraftforge.common.ForgeConfig.CLIENT.useCombinedDepthStencilAttachment.get()) {
|
||||||
+ } else {
|
+ GlStateManager._glFramebufferTexture2D(org.lwjgl.opengl.GL30.GL_FRAMEBUFFER, org.lwjgl.opengl.GL30.GL_DEPTH_STENCIL_ATTACHMENT, 3553, this.depthBufferId, 0);
|
||||||
+ GlStateManager._glFramebufferTexture2D(org.lwjgl.opengl.GL30.GL_FRAMEBUFFER, org.lwjgl.opengl.GL30.GL_DEPTH_ATTACHMENT, 3553, this.depthBufferId, 0);
|
+ } else if (this.useDepth) {
|
||||||
+ GlStateManager._glFramebufferTexture2D(org.lwjgl.opengl.GL30.GL_FRAMEBUFFER, org.lwjgl.opengl.GL30.GL_STENCIL_ATTACHMENT, 3553, this.depthBufferId, 0);
|
+ GlStateManager._glFramebufferTexture2D(org.lwjgl.opengl.GL30.GL_FRAMEBUFFER, org.lwjgl.opengl.GL30.GL_DEPTH_ATTACHMENT, 3553, this.depthBufferId, 0);
|
||||||
+ }
|
+ GlStateManager._glFramebufferTexture2D(org.lwjgl.opengl.GL30.GL_FRAMEBUFFER, org.lwjgl.opengl.GL30.GL_STENCIL_ATTACHMENT, 3553, this.depthBufferId, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
this.checkStatus();
|
this.checkStatus();
|
||||||
@@ -292,4 +_,27 @@
|
@@ -257,5 +_,26 @@
|
||||||
public int getDepthTextureId() {
|
|
||||||
return this.depthBufferId;
|
public int getDepthTextureId() {
|
||||||
}
|
return this.depthBufferId;
|
||||||
|
+ }
|
||||||
+
|
+
|
||||||
+ /*================================ FORGE START ================================================*/
|
+ private boolean stencilEnabled = false;
|
||||||
+ private boolean stencilEnabled = false;
|
+ /**
|
||||||
+ /**
|
+ * Attempts to enable 8 bits of stencil buffer on this FrameBuffer.
|
||||||
+ * Attempts to enable 8 bits of stencil buffer on this FrameBuffer.
|
+ * Modders must call this directly to set things up.
|
||||||
+ * Modders must call this directly to set things up.
|
+ * This is to prevent the default cause where graphics cards do not support stencil bits.
|
||||||
+ * This is to prevent the default cause where graphics cards do not support stencil bits.
|
+ * <b>Make sure to call this on the main render thread!</b>
|
||||||
+ * <b>Make sure to call this on the main render thread!</b>
|
+ */
|
||||||
+ */
|
+ public void enableStencil() {
|
||||||
+ public void enableStencil() {
|
+ if (stencilEnabled) return;
|
||||||
+ if(stencilEnabled) return;
|
+ stencilEnabled = true;
|
||||||
+ stencilEnabled = true;
|
+ this.resize(viewWidth, viewHeight, net.minecraft.client.Minecraft.ON_OSX);
|
||||||
+ this.resize(viewWidth, viewHeight, net.minecraft.client.Minecraft.ON_OSX);
|
+ }
|
||||||
+ }
|
|
||||||
+
|
+
|
||||||
+ /**
|
+ /**
|
||||||
+ * Returns wither or not this FBO has been successfully initialized with stencil bits.
|
+ * Returns wither or not this FBO has been successfully initialized with stencil bits.
|
||||||
+ * If not, and a modder wishes it to be, they must call enableStencil.
|
+ * If not, and a modder wishes it to be, they must call enableStencil.
|
||||||
+ */
|
+ */
|
||||||
+ public boolean isStencilEnabled() {
|
+ public boolean isStencilEnabled() {
|
||||||
+ return this.stencilEnabled;
|
+ return this.stencilEnabled;
|
||||||
+ }
|
}
|
||||||
+ /*================================ FORGE END ================================================*/
|
|
||||||
}
|
}
|
||||||
@@ -1,19 +1,20 @@
|
|||||||
--- a/com/mojang/blaze3d/platform/GlStateManager.java
|
--- a/com/mojang/blaze3d/platform/GlStateManager.java
|
||||||
+++ b/com/mojang/blaze3d/platform/GlStateManager.java
|
+++ b/com/mojang/blaze3d/platform/GlStateManager.java
|
||||||
@@ -501,9 +_,16 @@
|
@@ -493,9 +_,17 @@
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
}
|
+ /* Stores the last values sent into glMultiTexCoord2f */
|
||||||
|
+ public static float lastBrightnessX = 0.0f;
|
||||||
|
+ public static float lastBrightnessY = 0.0f;
|
||||||
|
+
|
||||||
|
public static void _texParameter(int p_84161_, int p_84162_, float p_84163_) {
|
||||||
|
RenderSystem.assertOnRenderThreadOrInit();
|
||||||
|
GL11.glTexParameterf(p_84161_, p_84162_, p_84163_);
|
||||||
|
+ if (p_84161_ == GL13.GL_TEXTURE1) {
|
||||||
|
+ lastBrightnessX = p_84162_;
|
||||||
|
+ lastBrightnessY = p_84163_;
|
||||||
|
+ }
|
||||||
|
}
|
||||||
|
|
||||||
+ /* Stores the last values sent into glMultiTexCoord2f */
|
public static void _texParameter(int p_84332_, int p_84333_, int p_84334_) {
|
||||||
+ public static float lastBrightnessX = 0.0f;
|
|
||||||
+ public static float lastBrightnessY = 0.0f;
|
|
||||||
public static void _texParameter(int p_84161_, int p_84162_, float p_84163_) {
|
|
||||||
RenderSystem.assertOnRenderThreadOrInit();
|
|
||||||
GL11.glTexParameterf(p_84161_, p_84162_, p_84163_);
|
|
||||||
+ if (p_84161_ == GL13.GL_TEXTURE1) {
|
|
||||||
+ lastBrightnessX = p_84162_;
|
|
||||||
+ lastBrightnessY = p_84163_;
|
|
||||||
+ }
|
|
||||||
}
|
|
||||||
|
|
||||||
public static void _texParameter(int p_84332_, int p_84333_, int p_84334_) {
|
|
||||||
@@ -1,28 +1,30 @@
|
|||||||
--- 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
|
||||||
@@ -81,7 +_,8 @@
|
@@ -84,7 +_,8 @@
|
||||||
GLFW.glfwWindowHint(139267, 2);
|
GLFW.glfwWindowHint(139267, 2);
|
||||||
GLFW.glfwWindowHint(139272, 204801);
|
GLFW.glfwWindowHint(139272, 204801);
|
||||||
GLFW.glfwWindowHint(139270, 1);
|
GLFW.glfwWindowHint(139270, 1);
|
||||||
- this.window = 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.window = 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;
|
||||||
@@ -93,6 +_,7 @@
|
@@ -96,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];
|
||||||
}
|
}
|
||||||
+ }
|
+ }
|
||||||
|
|
||||||
GLFW.glfwMakeContextCurrent(this.window);
|
GLFW.glfwMakeContextCurrent(this.window);
|
||||||
GL.createCapabilities();
|
GL.createCapabilities();
|
||||||
@@ -242,6 +_,7 @@
|
@@ -254,6 +_,9 @@
|
||||||
GLFW.glfwGetFramebufferSize(this.window, 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) net.minecraftforge.fml.loading.ImmediateWindowHandler.updateFBSize(w->this.framebufferWidth=w, h->this.framebufferHeight=h);
|
+ if (this.framebufferHeight == 0 || this.framebufferWidth == 0) {
|
||||||
}
|
+ net.minecraftforge.fml.loading.ImmediateWindowHandler.updateFBSize(w -> this.framebufferWidth = w, h -> this.framebufferHeight = h);
|
||||||
|
+ }
|
||||||
|
}
|
||||||
|
|
||||||
private void onResize(long p_85428_, int p_85429_, int p_85430_) {
|
private void onResize(long p_85428_, int p_85429_, int p_85430_) {
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
--- a/com/mojang/blaze3d/vertex/BufferBuilder.java
|
|
||||||
+++ b/com/mojang/blaze3d/vertex/BufferBuilder.java
|
|
||||||
@@ -477,4 +_,14 @@
|
|
||||||
this.sorting = p_277855_;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+
|
|
||||||
+ // Forge start
|
|
||||||
+ public void putBulkData(ByteBuffer buffer) {
|
|
||||||
+ ensureCapacity(buffer.limit() + this.format.getVertexSize());
|
|
||||||
+ this.buffer.position(this.nextElementByte);
|
|
||||||
+ this.buffer.put(buffer);
|
|
||||||
+ this.buffer.position(0);
|
|
||||||
+ this.vertices += buffer.limit() / this.format.getVertexSize();
|
|
||||||
+ this.nextElementByte += buffer.limit();
|
|
||||||
+ }
|
|
||||||
}
|
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
--- a/com/mojang/blaze3d/vertex/PoseStack.java
|
--- a/com/mojang/blaze3d/vertex/PoseStack.java
|
||||||
+++ b/com/mojang/blaze3d/vertex/PoseStack.java
|
+++ b/com/mojang/blaze3d/vertex/PoseStack.java
|
||||||
@@ -11,7 +_,7 @@
|
@@ -13,7 +_,7 @@
|
||||||
import org.joml.Quaternionf;
|
import org.joml.Vector3f;
|
||||||
|
|
||||||
@OnlyIn(Dist.CLIENT)
|
@OnlyIn(Dist.CLIENT)
|
||||||
-public class PoseStack {
|
-public class PoseStack {
|
||||||
+public class PoseStack implements net.minecraftforge.client.extensions.IForgePoseStack {
|
+public class PoseStack implements net.minecraftforge.client.extensions.IForgePoseStack {
|
||||||
private final Deque<PoseStack.Pose> poseStack = Util.make(Queues.newArrayDeque(), (p_85848_) -> {
|
private final Deque<PoseStack.Pose> poseStack = Util.make(Queues.newArrayDeque(), p_85848_ -> {
|
||||||
Matrix4f matrix4f = new Matrix4f();
|
Matrix4f matrix4f = new Matrix4f();
|
||||||
Matrix3f matrix3f = new Matrix3f();
|
Matrix3f matrix3f = new Matrix3f();
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
--- a/com/mojang/blaze3d/vertex/SheetedDecalTextureGenerator.java
|
--- a/com/mojang/blaze3d/vertex/SheetedDecalTextureGenerator.java
|
||||||
+++ b/com/mojang/blaze3d/vertex/SheetedDecalTextureGenerator.java
|
+++ b/com/mojang/blaze3d/vertex/SheetedDecalTextureGenerator.java
|
||||||
@@ -46,7 +_,7 @@
|
@@ -62,7 +_,7 @@
|
||||||
|
public VertexConsumer setNormal(float p_344306_, float p_342091_, float p_344579_) {
|
||||||
public void endVertex() {
|
this.delegate.setNormal(p_344306_, p_342091_, p_344579_);
|
||||||
Vector3f vector3f = this.normalInversePose.transform(new Vector3f(this.nx, this.ny, this.nz));
|
Vector3f vector3f = this.normalInversePose.transform(p_344306_, p_342091_, p_344579_, this.normal);
|
||||||
- Direction direction = Direction.getNearest(vector3f.x(), vector3f.y(), vector3f.z());
|
- Direction direction = Direction.getNearest(vector3f.x(), vector3f.y(), vector3f.z());
|
||||||
+ Direction direction = net.minecraftforge.client.ForgeHooksClient.getNearestStable(vector3f.x(), vector3f.y(), vector3f.z());
|
+ Direction direction = net.minecraftforge.client.ForgeHooksClient.getNearestStable(vector3f.x(), vector3f.y(), vector3f.z());
|
||||||
Vector4f vector4f = this.cameraInversePose.transform(new Vector4f(this.x, this.y, this.z, 1.0F));
|
Vector3f vector3f1 = this.cameraInversePose.transformPosition(this.x, this.y, this.z, this.worldPos);
|
||||||
vector4f.rotateY((float)Math.PI);
|
vector3f1.rotateY((float) Math.PI);
|
||||||
vector4f.rotateX((-(float)Math.PI / 2F));
|
vector3f1.rotateX((float) (-Math.PI / 2));
|
||||||
@@ -1,38 +1,24 @@
|
|||||||
--- 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 @@
|
@@ -12,7 +_,7 @@
|
||||||
import org.lwjgl.system.MemoryStack;
|
import org.lwjgl.system.MemoryStack;
|
||||||
|
|
||||||
@OnlyIn(Dist.CLIENT)
|
@OnlyIn(Dist.CLIENT)
|
||||||
-public interface VertexConsumer {
|
-public interface VertexConsumer {
|
||||||
+public interface VertexConsumer extends net.minecraftforge.client.extensions.IForgeVertexConsumer {
|
+public interface VertexConsumer extends net.minecraftforge.client.extensions.IForgeVertexConsumer {
|
||||||
VertexConsumer vertex(double p_85945_, double p_85946_, double p_85947_);
|
VertexConsumer addVertex(float p_344294_, float p_342213_, float p_344859_);
|
||||||
|
|
||||||
VertexConsumer color(int p_85973_, int p_85974_, int p_85975_, int p_85976_);
|
VertexConsumer setColor(int p_342749_, int p_344324_, int p_343336_, int p_342831_);
|
||||||
@@ -64,6 +_,10 @@
|
@@ -135,10 +_,11 @@
|
||||||
}
|
}
|
||||||
|
|
||||||
default void putBulkData(PoseStack.Pose p_85996_, BakedQuad p_85997_, float[] p_85998_, float p_85999_, float p_86000_, float p_86001_, int[] p_86002_, int p_86003_, boolean p_86004_) {
|
int i1 = FastColor.ARGB32.color(k, (int)f3, (int)f4, (int)f5);
|
||||||
+ putBulkData(p_85996_, p_85997_, p_85998_, p_85999_, p_86000_, p_86001_, 1, p_86002_, p_86003_, p_86004_);
|
- int j1 = p_331444_[l];
|
||||||
+ }
|
+ int j1 = applyBakedLighting(p_331444_[l], bytebuffer);
|
||||||
+
|
float f10 = bytebuffer.getFloat(16);
|
||||||
+ default void putBulkData(PoseStack.Pose p_85996_, BakedQuad p_85997_, float[] p_85998_, float p_85999_, float p_86000_, float p_86001_, float alpha, int[] p_86002_, int p_86003_, boolean p_86004_) {
|
float f9 = bytebuffer.getFloat(20);
|
||||||
float[] afloat = new float[]{p_85998_[0], p_85998_[1], p_85998_[2], p_85998_[3]};
|
Vector3f vector3f1 = matrix4f.transformPosition(f, f1, f2, new Vector3f());
|
||||||
int[] aint = new int[]{p_86002_[0], p_86002_[1], p_86002_[2], p_86002_[3]};
|
+ applyBakedNormals(vector3f, bytebuffer, p_85988_.normal());
|
||||||
int[] aint1 = p_85997_.getVertices();
|
this.addVertex(vector3f1.x(), vector3f1.y(), vector3f1.z(), i1, f10, f9, p_85993_, j1, vector3f.x(), vector3f.y(), vector3f.z());
|
||||||
@@ -99,11 +_,13 @@
|
|
||||||
f5 = afloat[k] * p_86001_;
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
- int l = aint[k];
|
|
||||||
+ int l = applyBakedLighting(p_86002_[k], bytebuffer);
|
|
||||||
float f9 = bytebuffer.getFloat(16);
|
|
||||||
float f10 = bytebuffer.getFloat(20);
|
|
||||||
Vector4f vector4f = matrix4f.transform(new Vector4f(f, f1, f2, 1.0F));
|
|
||||||
- this.vertex(vector4f.x(), vector4f.y(), vector4f.z(), f3, f4, f5, 1.0F, f9, f10, p_86003_, l, vector3f.x(), vector3f.y(), vector3f.z());
|
|
||||||
+ applyBakedNormals(vector3f, bytebuffer, p_85996_.normal());
|
|
||||||
+ float vertexAlpha = p_86004_ ? alpha * (float) (bytebuffer.get(15) & 255) / 255.0F : alpha;
|
|
||||||
+ this.vertex(vector4f.x(), vector4f.y(), vector4f.z(), f3, f4, f5, vertexAlpha, f9, f10, p_86003_, l, vector3f.x(), vector3f.y(), vector3f.z());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -1,14 +1,41 @@
|
|||||||
--- 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
|
||||||
@@ -176,4 +_,11 @@
|
@@ -13,7 +_,7 @@
|
||||||
return i;
|
import net.minecraftforge.api.distmarker.OnlyIn;
|
||||||
}
|
|
||||||
}
|
@OnlyIn(Dist.CLIENT)
|
||||||
|
-public class VertexFormat {
|
||||||
|
+public class VertexFormat implements net.minecraftforge.client.extensions.IForgeVertexFormat {
|
||||||
|
public static final int UNKNOWN_ELEMENT = -1;
|
||||||
|
private final List<VertexFormatElement> elements;
|
||||||
|
private final List<String> names;
|
||||||
|
@@ -22,6 +_,7 @@
|
||||||
|
private final int[] offsetsByElement = new int[32];
|
||||||
|
@Nullable
|
||||||
|
private VertexBuffer immediateDrawVertexBuffer;
|
||||||
|
+ 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_) {
|
||||||
|
this.elements = p_343616_;
|
||||||
|
@@ -34,6 +_,11 @@
|
||||||
|
int j = vertexformatelement != null ? p_343616_.indexOf(vertexformatelement) : -1;
|
||||||
|
this.offsetsByElement[i] = j != -1 ? p_345522_.getInt(j) : -1;
|
||||||
|
}
|
||||||
+
|
+
|
||||||
+ public ImmutableMap<String, VertexFormatElement> getElementMapping() { return elementMapping; }
|
+ ImmutableMap.Builder<String, VertexFormatElement> elements = ImmutableMap.builder();
|
||||||
+ public int getOffset(int index) { return offsets.getInt(index); }
|
+ for (int i = 0; i < p_343616_.size(); i++)
|
||||||
+ public boolean hasPosition() { return elements.stream().anyMatch(e -> e.getUsage() == VertexFormatElement.Usage.POSITION); }
|
+ elements.put(p_345241_.get(i), p_343616_.get(i));
|
||||||
+ public boolean hasNormal() { return elements.stream().anyMatch(e -> e.getUsage() == VertexFormatElement.Usage.NORMAL); }
|
+ this.elementMapping = elements.buildOrThrow();
|
||||||
+ public boolean hasColor() { return elements.stream().anyMatch(e -> e.getUsage() == VertexFormatElement.Usage.COLOR); }
|
}
|
||||||
+ public boolean hasUV(int which) { return elements.stream().anyMatch(e -> e.getUsage() == VertexFormatElement.Usage.UV && e.getIndex() == which); }
|
|
||||||
}
|
public static VertexFormat.Builder builder() {
|
||||||
|
@@ -158,6 +_,9 @@
|
||||||
|
|
||||||
|
return vertexbuffer;
|
||||||
|
}
|
||||||
|
+
|
||||||
|
+ public ImmutableMap<String, VertexFormatElement> getElementMapping() { return elementMapping; }
|
||||||
|
+ public int getOffset(int index) { return offsetsByElement[index]; }
|
||||||
|
|
||||||
|
@OnlyIn(Dist.CLIENT)
|
||||||
|
public static class Builder {
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
--- a/com/mojang/blaze3d/vertex/VertexFormatElement.java
|
|
||||||
+++ b/com/mojang/blaze3d/vertex/VertexFormatElement.java
|
|
||||||
@@ -90,6 +_,10 @@
|
|
||||||
this.usage.clearBufferState(this.index, p_166964_);
|
|
||||||
}
|
|
||||||
|
|
||||||
+ public int getElementCount() {
|
|
||||||
+ return count;
|
|
||||||
+ }
|
|
||||||
+
|
|
||||||
@OnlyIn(Dist.CLIENT)
|
|
||||||
public static enum Type {
|
|
||||||
FLOAT(4, "Float", 5126),
|
|
||||||
@@ -1,31 +1,31 @@
|
|||||||
--- a/com/mojang/math/Transformation.java
|
--- a/com/mojang/math/Transformation.java
|
||||||
+++ b/com/mojang/math/Transformation.java
|
+++ b/com/mojang/math/Transformation.java
|
||||||
@@ -13,7 +_,7 @@
|
@@ -13,7 +_,7 @@
|
||||||
|
import org.joml.Quaternionf;
|
||||||
import org.joml.Vector3f;
|
import org.joml.Vector3f;
|
||||||
import org.joml.Vector3fc;
|
|
||||||
|
|
||||||
-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 Matrix4f matrix;
|
private final Matrix4f matrix;
|
||||||
public static final Codec<Transformation> CODEC = RecordCodecBuilder.create((p_269604_) -> {
|
public static final Codec<Transformation> CODEC = RecordCodecBuilder.create(
|
||||||
return p_269604_.group(ExtraCodecs.VECTOR3F.fieldOf("translation").forGetter((p_269599_) -> {
|
p_269604_ -> p_269604_.group(
|
||||||
@@ -156,6 +_,19 @@
|
@@ -169,5 +_,19 @@
|
||||||
public int hashCode() {
|
vector3f1.lerp(p_175938_.getScale(), p_175939_);
|
||||||
return Objects.hash(this.matrix);
|
quaternionf1.slerp(p_175938_.getRightRotation(), p_175939_);
|
||||||
}
|
return new Transformation(vector3f, quaternionf, vector3f1, quaternionf1);
|
||||||
|
+ }
|
||||||
+
|
+
|
||||||
+ private Matrix3f normalTransform = null;
|
+ private Matrix3f normalTransform = null;
|
||||||
+ public Matrix3f getNormalMatrix() {
|
+ public Matrix3f getNormalMatrix() {
|
||||||
+ checkNormalTransform();
|
+ checkNormalTransform();
|
||||||
+ return normalTransform;
|
+ return normalTransform;
|
||||||
+ }
|
+ }
|
||||||
|
+
|
||||||
+ private void checkNormalTransform() {
|
+ private void checkNormalTransform() {
|
||||||
+ if (normalTransform == null) {
|
+ if (normalTransform == null) {
|
||||||
+ normalTransform = new Matrix3f(matrix);
|
+ normalTransform = new Matrix3f(matrix);
|
||||||
+ normalTransform.invert();
|
+ normalTransform.invert();
|
||||||
+ normalTransform.transpose();
|
+ normalTransform.transpose();
|
||||||
+ }
|
+ }
|
||||||
+ }
|
}
|
||||||
|
}
|
||||||
public Transformation slerp(Transformation p_175938_, float p_175939_) {
|
|
||||||
Vector3f vector3f = this.getTranslation();
|
|
||||||
+7
-7
@@ -1,10 +1,9 @@
|
|||||||
--- 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
|
||||||
@@ -61,6 +_,15 @@
|
@@ -71,6 +_,15 @@
|
||||||
return Component.empty().append(this.lines.title).append(": ").append(this.lines.detail);
|
}
|
||||||
}
|
|
||||||
|
|
||||||
+ @Override
|
@Override
|
||||||
+ public boolean keyPressed(int key, int scanCode, int modifiers) {
|
+ public boolean keyPressed(int key, int scanCode, int modifiers) {
|
||||||
+ if (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);
|
||||||
@@ -13,6 +12,7 @@
|
|||||||
+ return super.keyPressed(key, scanCode, modifiers);
|
+ return super.keyPressed(key, scanCode, modifiers);
|
||||||
+ }
|
+ }
|
||||||
+
|
+
|
||||||
public void render(GuiGraphics p_283497_, int p_88680_, int p_88681_, float p_88682_) {
|
+ @Override
|
||||||
super.render(p_283497_, p_88680_, p_88681_, p_88682_);
|
public void render(GuiGraphics p_283497_, int p_88680_, int p_88681_, float p_88682_) {
|
||||||
p_283497_.drawCenteredString(this.font, this.lines.title, this.width / 2, 80, -1);
|
super.render(p_283497_, p_88680_, p_88681_, p_88682_);
|
||||||
|
p_283497_.drawCenteredString(this.font, this.lines.title, this.width / 2, 80, -1);
|
||||||
@@ -1,48 +1,48 @@
|
|||||||
--- a/net/minecraft/CrashReport.java
|
--- a/net/minecraft/CrashReport.java
|
||||||
+++ b/net/minecraft/CrashReport.java
|
+++ b/net/minecraft/CrashReport.java
|
||||||
@@ -59,14 +_,9 @@
|
@@ -58,14 +_,9 @@
|
||||||
if (this.uncategorizedStackTrace != null && this.uncategorizedStackTrace.length > 0) {
|
if (this.uncategorizedStackTrace != null && this.uncategorizedStackTrace.length > 0) {
|
||||||
p_127520_.append("-- Head --\n");
|
p_127520_.append("-- Head --\n");
|
||||||
p_127520_.append("Thread: ").append(Thread.currentThread().getName()).append("\n");
|
p_127520_.append("Thread: ").append(Thread.currentThread().getName()).append("\n");
|
||||||
- p_127520_.append("Stacktrace:\n");
|
- p_127520_.append("Stacktrace:\n");
|
||||||
|
-
|
||||||
|
- for (StackTraceElement stacktraceelement : this.uncategorizedStackTrace) {
|
||||||
|
- p_127520_.append("\t").append("at ").append(stacktraceelement);
|
||||||
|
- p_127520_.append("\n");
|
||||||
|
- }
|
||||||
-
|
-
|
||||||
- for(StackTraceElement stacktraceelement : this.uncategorizedStackTrace) {
|
|
||||||
- p_127520_.append("\t").append("at ").append((Object)stacktraceelement);
|
|
||||||
- p_127520_.append("\n");
|
- p_127520_.append("\n");
|
||||||
- }
|
+ p_127520_.append(net.minecraftforge.logging.CrashReportAnalyser.appendSuspectedMods(this.exception, this.uncategorizedStackTrace));
|
||||||
|
+ p_127520_.append("Stacktrace:");
|
||||||
|
+ p_127520_.append(net.minecraftforge.logging.CrashReportExtender.generateEnhancedStackTrace(this.uncategorizedStackTrace));
|
||||||
|
}
|
||||||
|
|
||||||
|
for (CrashReportCategory crashreportcategory : this.details) {
|
||||||
|
@@ -73,6 +_,7 @@
|
||||||
|
p_127520_.append("\n\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
+ net.minecraftforge.logging.CrashReportExtender.extendSystemReport(systemReport);
|
||||||
|
this.systemReport.appendToCrashReportString(p_127520_);
|
||||||
|
}
|
||||||
|
|
||||||
|
@@ -92,18 +_,7 @@
|
||||||
|
throwable.setStackTrace(this.exception.getStackTrace());
|
||||||
|
}
|
||||||
|
|
||||||
|
- String s;
|
||||||
|
- try {
|
||||||
|
- stringwriter = new StringWriter();
|
||||||
|
- printwriter = new PrintWriter(stringwriter);
|
||||||
|
- throwable.printStackTrace(printwriter);
|
||||||
|
- s = stringwriter.toString();
|
||||||
|
- } finally {
|
||||||
|
- IOUtils.closeQuietly((Writer)stringwriter);
|
||||||
|
- IOUtils.closeQuietly((Writer)printwriter);
|
||||||
|
- }
|
||||||
-
|
-
|
||||||
- p_127520_.append("\n");
|
- return s;
|
||||||
+ p_127520_.append(net.minecraftforge.logging.CrashReportAnalyser.appendSuspectedMods(this.exception, this.uncategorizedStackTrace));
|
+ return net.minecraftforge.logging.CrashReportExtender.generateEnhancedStackTrace(throwable);
|
||||||
+ p_127520_.append("Stacktrace:");
|
}
|
||||||
+ p_127520_.append(net.minecraftforge.logging.CrashReportExtender.generateEnhancedStackTrace(this.uncategorizedStackTrace));
|
|
||||||
}
|
|
||||||
|
|
||||||
for(CrashReportCategory crashreportcategory : this.details) {
|
public String getFriendlyReport(ReportType p_343869_, List<String> p_342487_) {
|
||||||
@@ -74,6 +_,7 @@
|
|
||||||
p_127520_.append("\n\n");
|
|
||||||
}
|
|
||||||
|
|
||||||
+ net.minecraftforge.logging.CrashReportExtender.extendSystemReport(systemReport);
|
|
||||||
this.systemReport.appendToCrashReportString(p_127520_);
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -93,18 +_,7 @@
|
|
||||||
throwable.setStackTrace(this.exception.getStackTrace());
|
|
||||||
}
|
|
||||||
|
|
||||||
- String s;
|
|
||||||
- try {
|
|
||||||
- stringwriter = new StringWriter();
|
|
||||||
- printwriter = new PrintWriter(stringwriter);
|
|
||||||
- throwable.printStackTrace(printwriter);
|
|
||||||
- s = stringwriter.toString();
|
|
||||||
- } finally {
|
|
||||||
- IOUtils.closeQuietly((Writer)stringwriter);
|
|
||||||
- IOUtils.closeQuietly((Writer)printwriter);
|
|
||||||
- }
|
|
||||||
-
|
|
||||||
- return s;
|
|
||||||
+ return net.minecraftforge.logging.CrashReportExtender.generateEnhancedStackTrace(throwable);
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getFriendlyReport() {
|
|
||||||
@@ -1,38 +1,37 @@
|
|||||||
--- a/net/minecraft/CrashReportCategory.java
|
--- a/net/minecraft/CrashReportCategory.java
|
||||||
+++ b/net/minecraft/CrashReportCategory.java
|
+++ b/net/minecraft/CrashReportCategory.java
|
||||||
@@ -102,8 +_,10 @@
|
@@ -112,8 +_,10 @@
|
||||||
if (astacktraceelement.length <= 0) {
|
if (astacktraceelement.length <= 0) {
|
||||||
return 0;
|
return 0;
|
||||||
} else {
|
} else {
|
||||||
- this.stackTrace = new StackTraceElement[astacktraceelement.length - 3 - p_128149_];
|
- this.stackTrace = new StackTraceElement[astacktraceelement.length - 3 - p_128149_];
|
||||||
- System.arraycopy(astacktraceelement, 3 + p_128149_, this.stackTrace, 0, this.stackTrace.length);
|
- System.arraycopy(astacktraceelement, 3 + p_128149_, this.stackTrace, 0, this.stackTrace.length);
|
||||||
+ int len = astacktraceelement.length - 3 - p_128149_;
|
+ int len = astacktraceelement.length - 3 - p_128149_;
|
||||||
+ if (len <= 0) len = astacktraceelement.length;
|
+ if (len <= 0) len = astacktraceelement.length;
|
||||||
+ this.stackTrace = new StackTraceElement[len];
|
+ this.stackTrace = new StackTraceElement[len];
|
||||||
+ System.arraycopy(astacktraceelement, astacktraceelement.length - len, this.stackTrace, 0, this.stackTrace.length);
|
+ System.arraycopy(astacktraceelement, astacktraceelement.length - len, this.stackTrace, 0, this.stackTrace.length);
|
||||||
return this.stackTrace.length;
|
return this.stackTrace.length;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -147,17 +_,17 @@
|
@@ -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:");
|
||||||
-
|
-
|
||||||
- for(StackTraceElement stacktraceelement : this.stackTrace) {
|
- for (StackTraceElement stacktraceelement : this.stackTrace) {
|
||||||
- p_128169_.append("\n\tat ");
|
- p_128169_.append("\n\tat ");
|
||||||
- p_128169_.append((Object)stacktraceelement);
|
- p_128169_.append(stacktraceelement);
|
||||||
- }
|
- }
|
||||||
+ p_128169_.append(net.minecraftforge.logging.CrashReportExtender.generateEnhancedStackTrace(this.stackTrace));
|
+ p_128169_.append(net.minecraftforge.logging.CrashReportExtender.generateEnhancedStackTrace(this.stackTrace));
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
}
|
public StackTraceElement[] getStacktrace() {
|
||||||
|
return this.stackTrace;
|
||||||
public StackTraceElement[] getStacktrace() {
|
+ }
|
||||||
return this.stackTrace;
|
|
||||||
+ }
|
|
||||||
+
|
+
|
||||||
+ public void applyStackTrace(Throwable t) {
|
+ public void applyStackTrace(Throwable t) {
|
||||||
+ this.stackTrace = t.getStackTrace();
|
+ this.stackTrace = t.getStackTrace();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void populateBlockDetails(CrashReportCategory p_178951_, LevelHeightAccessor p_178952_, BlockPos p_178953_, @Nullable BlockState p_178954_) {
|
public static void populateBlockDetails(CrashReportCategory p_178951_, LevelHeightAccessor p_178952_, BlockPos p_178953_, @Nullable BlockState p_178954_) {
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
--- a/net/minecraft/SharedConstants.java
|
--- a/net/minecraft/SharedConstants.java
|
||||||
+++ b/net/minecraft/SharedConstants.java
|
+++ b/net/minecraft/SharedConstants.java
|
||||||
@@ -215,6 +_,7 @@
|
@@ -171,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 = false;
|
CommandSyntaxException.ENABLE_COMMAND_STACK_TRACES = false;
|
||||||
CommandSyntaxException.BUILT_IN_EXCEPTIONS = new BrigadierExceptions();
|
CommandSyntaxException.BUILT_IN_EXCEPTIONS = new BrigadierExceptions();
|
||||||
Loaded 100 of 2151 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user