Compare commits

...
37 Commits
Author SHA1 Message Date
LexManos a855b83de8 1.19.4 RB 3
https://forums.minecraftforge.net/topic/149473-forge-453-minecraft-1194/
2024-06-03 14:16:14 -07:00
LexManos 1c2de0cc72 Bump gradle to 8.8 2024-06-03 13:59:53 -07:00
Paint_NinjaandJ-RAP 388976f288 Fix NPE when acceptableValues in defineInList() does not allow nulls, backport of #9903 (#9908)
Co-authored-by: J-RAP <[email protected]>
2024-04-18 21:32:03 +01:00
Paint_Ninja 2b67a9f36d Optimise capabilities a tad, backport of #9886 (#9917) 2024-04-18 21:09:30 +01:00
Paint_Ninja 9305aff10f Make common config screen registration tasks easier, backport of #9884 (#9913) 2024-04-18 21:09:04 +01:00
Paint_Ninja dbd0dba883 Fix crowdin (#9924) 2024-04-15 22:34:03 +01:00
Paint_Ninja 959a2db3e0 Fix userdev by reverting CoreMods upgrades (#9923)
Was an obscure transitive dep issue
2024-04-15 21:25:00 +01:00
Paint_Ninja ae0c1fb4c1 [1.19.4] Bump CoreMods and ASM (#9898)
- CoreMods 5.1.2 -> 5.1.6
- ASM 9.6 -> 9.7
2024-04-04 14:01:57 +01:00
J-RAP 6b166f3f40 Bump some deps (#9879)
- CoreMods 5.0.1 -> 5.1.2
- ASM 9.5 -> 9.6
- Installer 2.1 -> 2.2
- Installer tools 1.3.0 -> 1.4.1
2024-03-10 21:24:22 +00:00
Paint_Ninja b1c0cc77bb Make common DisplayTest registration tasks easier (#9837)
Backport of #9822 to 1.19.4
2023-12-31 15:36:57 +00:00
Paint_Ninja c369f8186b Optimise ForgeConfigSpec and make Range public (#9826)
Backport of #9810 to 1.19.4
2023-12-30 21:13:33 +00:00
Paint_Ninja de4946a1ae Backport CrashReportAnalyser to 1.19.4 (#9756) 2023-11-02 13:19:07 -07:00
Paint_NinjaandSu5eD 76e3afd528 Improve mod description formatting in mods screen (#9770)
Co-authored-by: Su5eD <[email protected]>
2023-11-02 13:18:57 -07:00
Paint_Ninja 4a62c9ed87 Update to FG6 and Gradle 8, backport 1.20 MDK (#9753) 2023-10-18 13:39:53 -07:00
BigBigZhe cc75529ec4 Fix Melon/Pumpkin stems having wrong plant type causing them to remain after trampling farmland. 2023-10-11 22:55:40 -07:00
Paint_Ninja bbd8c2e07e Optimise path filter in mod loading (#9711) 2023-09-28 14:56:42 -07:00
Paint_NinjaandJab125 dfef5101f1 Improve mod loading error message for errors inside mod constructors (#9708)
Co-authored-by: Jab125 <[email protected]>
2023-09-28 14:56:12 -07:00
LexManos 664a2c06ad 1.19.4 RB 2 2023-09-21 11:52:10 -07:00
Paint_Ninjaandmalte0811 e85295a837 Fix Level leak in debug HUD (#9700)
Co-authored-by: malte0811 <[email protected]>
2023-09-02 17:02:03 -07:00
Paint_Ninjaanddhyces 21582ef641 Keep order of sources in PackRepository (#9703)
Co-authored-by: dhyces <[email protected]>
2023-09-02 16:21:21 -07:00
Paint_Ninja 020ec3d51b Fix DelegatingPackResources searching resource path twice (#9698) 2023-08-30 14:10:38 -07:00
Jonathan Colmenares 774b79e609 Fix parameter names in IForgeDimensionSpecialEffects.adjustLightmapColors to better describe what they are. (#9657) 2023-07-17 09:45:29 -07:00
Jonathan Colmenares ee6022b006 Add mods button to pause menu (#9654) 2023-07-17 08:41:11 -07:00
brandon3055 37efd2b8ae Fixed FluidUtil#tryFillContainer returning invalid result when simulating #9358 2023-07-15 10:52:26 -07:00
Random832 cf3d42ef38 Fix conflicting keybindings not having the correct click count set. #9360 2023-07-15 10:44:29 -07:00
RealMangoRage 03a505a3f2 Fixed AdvancementsScreen.java to render next/previous page buttons now. (#9650) 2023-07-14 19:22:33 -07:00
ChampionAsh5357 bdc856edf5 Properly Handle Fluid Updates while in a Boat Fix #9256 (#9428) 2023-07-14 19:06:07 -07:00
Silver_David 6eebea0896 New hook in IClientBlockExtensions to handle enabling tinting on breaking particles. #9446 2023-07-14 16:08:51 -07:00
Technici4n 9218e08955 Add EmptyEnergyStorage (#9487) 2023-07-14 11:34:12 -07:00
Paint_Ninja 7006fe4f29 Support IPv6 address compression for logged IPs 2023-07-14 11:30:57 -07:00
Paint_Ninja 301e7252b0 Add option to advertise dedicated servers to LAN. (#9502) 2023-07-14 07:07:36 -07:00
ChampionAsh5357 2b5852072c Add particle description data provider (#9510) 2023-07-13 19:35:07 -07:00
bconlon 0b38373a45 AlterGroundEvent for modifying block placement performed by AlterGroundDecorator (#9636) 2023-07-13 17:30:45 -07:00
Paint_Ninja 07e538f3dd Improve logging for server connections (#9622) 2023-07-11 11:04:45 -07:00
cech12 b39e300c1b Fix placing fluids into waterlogged blocks with FluidUtil::tryPlaceFluid. To behave more like vanilla MC-127110 (#9519) 2023-07-11 11:04:26 -07:00
LexManos 50db51a366 Add proper duplicate mod error message that includes the mod id(s) and mod files. (#9474) 2023-06-20 14:18:14 -07:00
LexManos df80acc49d Make 1.20.x the main TC branch. 2023-06-20 14:07:42 -07:00
98 changed files with 2012 additions and 428 deletions

No files matched your search

+3 -3
View File
@@ -36,9 +36,9 @@ project {
buildType(PullRequestCompatibility)
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_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("git_main_branch", "1.19.x", label = "Git Main Branch", description = "The git main or default branch to use in VCS operations.", 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", "8.8", 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_branch_spec", """
+:refs/heads/(main*)
+:refs/heads/(master*)
Vendored
-125
View File
@@ -1,125 +0,0 @@
@Library('forge-shared-library')_
pipeline {
options {
disableConcurrentBuilds()
}
agent {
docker {
image 'gradle:7-jdk16'
//args '-v forgegc:/home/gradle/.gradle_cache/'
}
}
environment {
GRADLE_ARGS = '--no-daemon --console=plain' // No daemon for now as FG3 kinda derps. //'-Dorg.gradle.daemon.idletimeout=5000'
DISCORD_WEBHOOK = credentials('forge-discord-jenkins-webhook')
DISCORD_PREFIX = "Job: Forge Branch: ${BRANCH_NAME} Build: #${BUILD_NUMBER}"
JENKINS_HEAD = 'https://wiki.jenkins-ci.org/download/attachments/2916393/headshot.png'
}
stages {
stage('notify_start') {
when {
not {
changeRequest()
}
}
steps {
discordSend(
title: "${DISCORD_PREFIX} Started",
successful: true,
result: 'ABORTED', //White border
thumbnail: JENKINS_HEAD,
webhookURL: DISCORD_WEBHOOK
)
}
}
/*
stage('pull_cache') {
steps {
sh 'cp -r /home/gradle/.gradle_cache/jdks/ /home/gradle/.gradle/jdks/'
sh 'cp -r /home/gradle/.gradle_cache/wrapper/ /home/gradle/.gradle/wrapper/'
sh 'cp -r /home/gradle/.gradle_cache/caches/ /home/gradle/.gradle/caches/'
}
}
*/
stage('setup') {
steps {
withGradle {
sh './gradlew ${GRADLE_ARGS} --refresh-dependencies --continue setup'
}
script {
env.MYVERSION = sh(returnStdout: true, script: './gradlew :forge:properties -q | grep "^version:" | cut -d" " -f2').trim()
env.FMLONLY_VERSION = sh(returnStdout: true, script: './gradlew :fmlonly:properties -q | grep "^version:" | cut -d" " -f2').trim()
}
}
}
stage('changelog') {
when {
not {
changeRequest()
}
}
steps {
writeChangelog(currentBuild, 'build/changelog.txt')
}
}
stage('publish') {
when {
not {
changeRequest()
}
}
environment {
CROWDIN = credentials('forge-crowdin')
KEYSTORE = credentials('forge-jenkins-keystore-old')
KEYSTORE_KEYPASS = credentials('forge-jenkins-keystore-old-keypass')
KEYSTORE_STOREPASS = credentials('forge-jenkins-keystore-old-keypass')
}
steps {
withCredentials([usernamePassword(credentialsId: 'maven-forge-user', usernameVariable: 'MAVEN_USER', passwordVariable: 'MAVEN_PASSWORD')]) {
withGradle {
sh './gradlew ${GRADLE_ARGS} publish -PkeystoreKeyPass=${KEYSTORE_KEYPASS} -PkeystoreStorePass=${KEYSTORE_STOREPASS} -Pkeystore=${KEYSTORE} -PcrowdinKey=${CROWDIN}'
}
}
}
post {
success {
build job: 'filegenerator', parameters: [string(name: 'COMMAND', value: "promote net.minecraftforge:forge ${env.MYVERSION} latest")], propagate: false, wait: false
build job: 'filegenerator', parameters: [string(name: 'COMMAND', value: "promote net.minecraftforge:fmlonly ${env.FMLONLY_VERSION} latest")], propagate: false, wait: false
}
}
}
stage('test_publish_pr') { //Publish to local repo to test full process, but don't include credentials so it can't sign/publish to maven
when {
changeRequest()
}
environment {
CROWDIN = credentials('forge-crowdin')
}
steps {
withGradle {
sh './gradlew ${GRADLE_ARGS} publish -PcrowdinKey=${CROWDIN}'
}
}
}
}
post {
always {
script {
archiveArtifacts artifacts: 'projects/forge/build/libs/**/*.*', fingerprint: true, onlyIfSuccessful: true, allowEmptyArchive: true
if (env.CHANGE_ID == null) { // This is unset for non-PRs
discordSend(
title: "${DISCORD_PREFIX} Finished ${currentBuild.currentResult}",
description: '```\n' + getChanges(currentBuild) + '\n```',
successful: currentBuild.resultIsBetterOrEqualTo("SUCCESS"),
result: currentBuild.currentResult,
thumbnail: JENKINS_HEAD,
webhookURL: DISCORD_WEBHOOK
)
}
}
}
}
}
+28 -17
View File
@@ -1,3 +1,4 @@
import de.undercouch.gradle.tasks.download.Download
import groovy.json.JsonBuilder
import net.minecraftforge.forge.tasks.checks.CheckATs
import net.minecraftforge.forge.tasks.checks.CheckExcs
@@ -23,12 +24,12 @@ import org.objectweb.asm.Opcodes
plugins {
id 'org.cadixdev.licenser' version '0.6.1'
id 'com.github.ben-manes.versions' version '0.36.0'
id 'net.minecraftforge.gradleutils' version '2.+'
id 'com.github.ben-manes.versions' version '0.46.0'
id 'net.minecraftforge.gradleutils' version '[2.2,2.3)'
id 'eclipse'
id 'de.undercouch.download' version '5.1.3'
id 'net.minecraftforge.gradle.patcher' version '[5.1.50,5.2.0)' apply false
id 'net.minecraftforge.gradle.mcp' version '[5.1.50,5.2.0)' apply false
id 'de.undercouch.download' version '5.4.0'
id 'net.minecraftforge.gradle.patcher' version '[6.0,6.2)' apply false
id 'net.minecraftforge.gradle.mcp' version '[6.0,6.2)' apply false
}
Util.init() //Init all our extension methods!
@@ -54,8 +55,8 @@ ext {
MODLAUNCHER_VERSION = '10.0.8'
SECUREJARHANDLER_VERSION = '2.1.6'
BOOTSTRAPLAUNCHER_VERSION = '1.1.2'
ASM_VERSION = '9.5'
INSTALLER_VERSION = '2.1.+'
ASM_VERSION = '9.7'
INSTALLER_VERSION = '2.2.+'
MIXIN_VERSION = '0.8.5'
TERMINALCONSOLEAPPENDER_VERSION = '1.2.0'
JLINE_VERSION = '3.12.+'
@@ -81,7 +82,7 @@ ext {
FORGE_VERSION = VERSION.substring(MC_VERSION.length() + 1)
BINPATCH_TOOL = 'net.minecraftforge:binarypatcher:1.1.1:fatjar'
INSTALLER_TOOLS = 'net.minecraftforge:installertools:1.3.0'
INSTALLER_TOOLS = 'net.minecraftforge:installertools:1.4.1'
JAR_SPLITTER = 'net.minecraftforge:jarsplitter:1.1.4'
FART = 'net.minecraftforge:ForgeAutoRenamingTool:0.1.22:all'
MIN_TAG_FOR_CHANGELOG = '41.0'
@@ -102,7 +103,7 @@ def extraTxts = [
rootProject.tasks.createChangelog.outputFile
]
task downloadVersionManifest(type: Download) {
tasks.register('downloadVersionManifest', Download) {
src 'https://piston-meta.mojang.com/mc/game/version_manifest_v2.json'
dest file('build/versions/version_manifest.json')
useETag 'all'
@@ -345,7 +346,7 @@ def sharedFmlonlyForge = { Project prj ->
}
prj.task([type: DownloadMavenArtifact], 'downloadInstaller') {
artifact = "net.minecraftforge:installer:${INSTALLER_VERSION}:shrunk"
artifact = "net.minecraftforge:installer:${INSTALLER_VERSION}:fatjar"
changing = true
}
@@ -884,6 +885,10 @@ project(':forge') {
apply plugin: 'net.minecraftforge.gradle.patcher'
apply plugin: 'org.cadixdev.licenser'
applyPatches {
level 'WARNING'
}
sourceSets {
main {
java {
@@ -1164,9 +1169,12 @@ project(':forge') {
]
}
task crowdin(type: Crowdin) {
key = project.hasProperty('crowdinKey') ? project.crowdinKey : null
//TODO: Merge our english.json?
tasks.register('downloadCrowdin', Download) {
src 'https://files.minecraftforge.net/crowdin.zip'
dest file('build/crowdin.zip')
useETag 'all'
onlyIfModified true
quiet true
}
sharedFmlonlyForge.call(project)
@@ -1572,9 +1580,12 @@ project(':forge') {
from extraTxts
// add crowdin locales
from { crowdin.output.present && crowdin.output.get().asFile.exists() ? zipTree(crowdin.output) : null}
dependsOn crowdin
duplicatesStrategy = 'exclude'
from zipTree(downloadCrowdin.dest).matching {
include 'assets/forge/lang/*.json'
}
dependsOn downloadCrowdin
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
doFirst {
MANIFESTS.each{ pkg, values ->
@@ -1619,7 +1630,7 @@ project(':forge') {
exclude it
}
filter(ReplaceTokens, tokens: [
FORGE_VERSION: project.version,
FORGE_VERSION: FORGE_VERSION,
FORGE_GROUP: project.group,
FORGE_NAME: project.name,
MC_VERSION: MC_VERSION,
+2 -2
View File
@@ -7,7 +7,7 @@ dependencies {
implementation 'org.ow2.asm:asm:9.5'
implementation 'org.ow2.asm:asm-tree:9.5'
implementation 'net.minecraftforge:srgutils:0.5.+'
implementation 'commons-io:commons-io:2.8.0'
implementation 'com.google.code.gson:gson:2.10'
implementation 'commons-io:commons-io:2.12.0'
implementation 'com.google.code.gson:gson:2.10.1'
implementation 'org.eclipse.jgit:org.eclipse.jgit:6.5.0.202303070854-r'
}
@@ -4,7 +4,7 @@ import groovy.json.JsonBuilder
import org.gradle.api.DefaultTask
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.TaskAction
import org.objectweb.asm.tree.ClassNode
import org.objectweb.asm.tree.FieldNode
@@ -12,7 +12,9 @@ import org.objectweb.asm.tree.MethodNode
abstract class BytecodeFinder extends DefaultTask {
@InputFile abstract RegularFileProperty getJar()
@OutputFile abstract RegularFileProperty getOutput()
// It should be fine to mark the output as internal as we want to control when we run it anyways.
// This also shuts Gradle 8 up about implicit task dependencies.
@Internal abstract RegularFileProperty getOutput()
BytecodeFinder() {
output.convention(project.layout.buildDirectory.dir(name).map { it.file("output.json") })
@@ -27,6 +27,6 @@ abstract class BytecodePredicateFinder extends BytecodeFinder {
@Internal
@Override
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.stream().sorted().toList() ?: {throw new RuntimeException('Failed to find any targets, please ensure that method names and descriptors are correct.')}()
}
}
@@ -32,7 +32,7 @@ class TeamcityRequests {
@Nullable
static Map<String, Build> buildsByCommit() throws IOException {
final Map<String, Build> builds = [:]
jsonRequest(new TypeToken<Builds>() {}, "https://teamcity.minecraftforge.net/guestAuth/app/rest/builds?fields=build:(revisions,number)&locator=buildType:(id:MinecraftForge_MinecraftForge_MinecraftForge_MinecraftForge__Build),count:300,status:SUCCESS")
jsonRequest(new TypeToken<Builds>() {}, 'https://teamcity.minecraftforge.net/guestAuth/app/rest/builds?fields=build:(revisions,number)&locator=buildType:(id:MinecraftForge_MinecraftForge_MinecraftForge_MinecraftForge__Build),defaultFilter:false,count:300,status:SUCCESS')
?.build?.forEach {
it.revisions.revision.each { rev -> builds[rev.version] = it }
}
@@ -81,14 +81,6 @@ public class Util {
if (!checkExists(url)) {
url = "https://maven.minecraftforge.net/${path}"
}
//TODO remove when Mojang launcher is updated
if (!classifiers && art.classifier != null) {
//Mojang launcher doesn't currently support classifiers, so... move it to part of the version, and force the extension to 'jar'
// However, keep the path normal so that our mirror system works.
art.version = "${art.version}-${art.classifier}"
art.classifier = null
art.extension = 'jar'
}
ret[key] = [
name: "${art.group}:${art.name}:${art.version}" + (art.classifier == null ? '' : ":${art.classifier}") + (art.extension == 'jar' ? '' : "@${art.extension}"),
downloads: [
@@ -171,7 +171,7 @@ abstract class CheckATs extends CheckTask {
}
private static List<String> joinBack(TreeMap<String, ATParser.Entry> lines, Map<String, InheritanceData> inheritance, IMappingFile mappings) {
final data = []
final List<String> data = []
final remapComment = { ATParser.Entry entry ->
if (!mappings || !entry || !entry.desc) return null
final comment = entry.comment?.substring(1)?.trim()
@@ -91,18 +91,20 @@ abstract class CheckTask extends DefaultTask implements VerificationTask {
@DelegatesTo(genericTypeIndex = 0, target = 'type') Closure configuration) {
taskName = taskName.capitalize()
tasks.register("check$taskName", clazz) { CheckTask task ->
configuration.setDelegate((T) task)
configuration.call(task)
task.mode.set(CheckMode.CHECK)
task.group = 'checks'
def castedTask = task as T
configuration.setDelegate(castedTask)
configuration.call(castedTask)
castedTask.mode.set(CheckMode.CHECK)
castedTask.group = 'checks'
}
tasks.named('checkAll').configure { it.dependsOn("check$taskName") }
tasks.register("checkAndFix$taskName", clazz) { CheckTask task ->
configuration.setDelegate((T) task)
configuration.call(task)
task.mode.set(CheckMode.FIX)
task.group = 'checks'
def castedTask = task as T
configuration.setDelegate(castedTask)
configuration.call(castedTask)
castedTask.mode.set(CheckMode.CHECK)
castedTask.group = 'checks'
}
tasks.named('checkAllAndFix').configure { it.dependsOn("checkAndFix$taskName") }
}
+7 -6
View File
@@ -10,8 +10,9 @@ Forge is a free, open-source modding API all of your favourite mods use!
| Version | Support |
|---------| ------------- |
| 1.19.x | Active |
| 1.18.x | LTS |
| 1.20.x | Active |
| 1.19.4 | Legacy |
| 1.19.2 | Legacy |
* [Download]
* [Forum]
@@ -68,9 +69,9 @@ Please ensure you have a valid email address associated with your GitHub account
[Discord]: https://discord.minecraftforge.net/
[Documentation]: https://docs.minecraftforge.net/
[Getting-Started]: https://docs.minecraftforge.net/en/latest/gettingstarted/
[ForgeDev]: https://docs.minecraftforge.net/en/latest/forgedev/
[Pull-Requests]: https://docs.minecraftforge.net/en/latest/forgedev/#making-changes-and-pull-requests
[Documentation]: https://docs.minecraftforge.net/en/1.19.x/
[Getting-Started]: https://docs.minecraftforge.net/en/1.19.x/gettingstarted/
[ForgeDev]: https://docs.minecraftforge.net/en/1.19.x/forgedev/
[Pull-Requests]: https://docs.minecraftforge.net/en/1.19.x/forgedev/#making-changes-and-pull-requests
[Patreon]: https://www.patreon.com/LexManos
@@ -95,5 +95,24 @@ public interface IExtensionPoint<T extends Record>
@SuppressWarnings("JavadocReference") // reference to NetworkConstants, ForgeHooksClient
record DisplayTest(Supplier<String> suppliedVersion, BiPredicate<String, Boolean> remoteVersionTest) implements IExtensionPoint<DisplayTest> {
public static final String IGNORESERVERONLY = "OHNOES\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31";
/**
* Ignores any version information coming from the server - use for server only mods
*/
public static final Supplier<DisplayTest> IGNORE_SERVER_VERSION = () -> new DisplayTest(IGNORESERVERONLY, (remoteVersion, isFromServer) -> true);
/**
* Ignores all information and provides no information
*/
public static final Supplier<DisplayTest> IGNORE_ALL_VERSION = () -> new DisplayTest("", (remoteVersion, isFromServer) -> true);
/**
* An optional alternative to {@link #DisplayTest(Supplier, BiPredicate)} which accepts a constant version string
* instead of a {@link Supplier}.
* <p>Internally, the provided version string is wrapped in a Supplier for you.</p>
*/
public DisplayTest(String version, BiPredicate<String, Boolean> remoteVersionTest) {
this(() -> version, remoteVersionTest);
}
}
}
@@ -20,6 +20,7 @@ import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Supplier;
@@ -63,9 +64,9 @@ public abstract class ModContainer
() -> new IExtensionPoint.DisplayTest(() -> this.modInfo.getVersion().toString(),
(incoming, isNetwork) -> Objects.equals(incoming, this.modInfo.getVersion().toString()));
case "IGNORE_SERVER_VERSION" -> // Ignores any version information coming from the server - use for server only mods
() -> new IExtensionPoint.DisplayTest(() -> IExtensionPoint.DisplayTest.IGNORESERVERONLY, (incoming, isNetwork) -> true);
IExtensionPoint.DisplayTest.IGNORE_SERVER_VERSION;
case "IGNORE_ALL_VERSION" -> // Ignores all information and provides no information
() -> new IExtensionPoint.DisplayTest(() -> "", (incoming, isNetwork) -> true);
IExtensionPoint.DisplayTest.IGNORE_ALL_VERSION;
case "NONE" -> null; // NO display test at all - use this if you're going to do your own display test
default -> // any other value throws an exception
throw new IllegalArgumentException("Invalid displayTest value supplied in mods.toml");
@@ -142,6 +143,22 @@ public abstract class ModContainer
extensionPoints.put(point, extension);
}
public void registerDisplayTest(IExtensionPoint.DisplayTest displayTest) {
registerExtensionPoint(IExtensionPoint.DisplayTest.class, () -> displayTest);
}
public void registerDisplayTest(Supplier<IExtensionPoint.DisplayTest> displayTest) {
registerExtensionPoint(IExtensionPoint.DisplayTest.class, displayTest);
}
public void registerDisplayTest(String version, BiPredicate<String, Boolean> remoteVersionTest) {
registerDisplayTest(new IExtensionPoint.DisplayTest(version, remoteVersionTest));
}
public void registerDisplayTest(Supplier<String> suppliedVersion, BiPredicate<String, Boolean> remoteVersionTest) {
registerDisplayTest(new IExtensionPoint.DisplayTest(suppliedVersion, remoteVersionTest));
}
public void addConfig(final ModConfig modConfig) {
configs.put(modConfig.getType(), modConfig);
}
@@ -12,6 +12,7 @@ import net.minecraftforge.fml.loading.FMLLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.function.BiPredicate;
import java.util.function.Supplier;
public class ModLoadingContext
@@ -50,6 +51,44 @@ public class ModLoadingContext
getActiveContainer().registerExtensionPoint(point, extension);
}
/**
* Register a {@link IExtensionPoint.DisplayTest} with the mod container.
* <p>A shorthand for registering a DisplayTest with {@link #registerExtensionPoint(Class, Supplier)}.</p>
* @param displayTest The {@link IExtensionPoint.DisplayTest} to register
*/
public void registerDisplayTest(IExtensionPoint.DisplayTest displayTest) {
getActiveContainer().registerDisplayTest(() -> displayTest);
}
/**
* Register a {@link IExtensionPoint.DisplayTest} with the mod container.
* <p>A shorthand for registering a DisplayTest supplier with {@link #registerExtensionPoint(Class, Supplier)}.</p>
* @param displayTest The {@link Supplier<IExtensionPoint.DisplayTest>} to register
*/
public void registerDisplayTest(Supplier<IExtensionPoint.DisplayTest> displayTest) {
getActiveContainer().registerDisplayTest(displayTest);
}
/**
* Register a {@link IExtensionPoint.DisplayTest} with the mod container.
* <p>A shorthand for registering a DisplayTest with {@link #registerExtensionPoint(Class, Supplier)} that also
* creates the DisplayTest instance for you using the provided parameters.</p>
* @see IExtensionPoint.DisplayTest#DisplayTest(String, BiPredicate)
*/
public void registerDisplayTest(String version, BiPredicate<String, Boolean> remoteVersionTest) {
getActiveContainer().registerDisplayTest(new IExtensionPoint.DisplayTest(version, remoteVersionTest));
}
/**
* Register a {@link IExtensionPoint.DisplayTest} with the mod container.
* <p>A shorthand for registering a DisplayTest with {@link #registerExtensionPoint(Class, Supplier)} that also
* creates the DisplayTest instance for you using the provided parameters.</p>
* @see IExtensionPoint.DisplayTest#DisplayTest(Supplier, BiPredicate)
*/
public void registerDisplayTest(Supplier<String> suppliedVersion, BiPredicate<String, Boolean> remoteVersionTest) {
getActiveContainer().registerDisplayTest(new IExtensionPoint.DisplayTest(suppliedVersion, remoteVersionTest));
}
public void registerConfig(ModConfig.Type type, IConfigSpec<?> spec) {
if (spec.isEmpty())
{
@@ -11,11 +11,17 @@ import net.minecraftforge.forgespi.language.IModInfo;
import org.apache.maven.artifact.versioning.ArtifactVersion;
import org.slf4j.Logger;
import java.util.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.*;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.joining;
import static net.minecraftforge.fml.loading.LogMarkers.LOADING;
public class UniqueModListBuilder
{
@@ -66,28 +72,35 @@ public class UniqueModListBuilder
// Its theoretically possible that some mod has somehow moved an id to a secondary place, thus causing a dupe.
// We can't handle this
final List<IModInfo> dupedMods = modIds.values().stream()
final List<String> dupedModErrors = modIds.values().stream()
.filter(modInfos -> modInfos.size() > 1)
.map(modInfos -> modInfos.get(0))
.toList();
.map(mods -> String.format("\tMod ID: '%s' from mod files: %s",
mods.get(0).getModId(),
mods.stream()
.map(modInfo -> modInfo.getOwningFile().getFile().getFileName()).collect(joining(", "))
)).toList();
if (!dupedMods.isEmpty()) {
final List<EarlyLoadingException.ExceptionData> duplicateModErrors = dupedMods.stream()
.map(dm -> new EarlyLoadingException.ExceptionData("fml.modloading.dupedmod", dm, Objects.toString(dm)))
.toList();
throw new EarlyLoadingException("Duplicate mods found", null, duplicateModErrors);
if (!dupedModErrors.isEmpty()) {
LOGGER.error(LOADING, "Found duplicate mods:\n{}", dupedModErrors.stream().collect(joining("\n")));
throw new EarlyLoadingException("Duplicate mods found", null, dupedModErrors.stream()
.map(s -> new EarlyLoadingException.ExceptionData(s))
.toList());
}
final List<ModFile> dupedLibs = versionedLibIds.values().stream()
.filter(modFiles -> modFiles.size() > 1)
.map(modFiles -> modFiles.get(0))
.toList();
if (!dupedLibs.isEmpty()) {
final List<EarlyLoadingException.ExceptionData> duplicateLibErrors = dupedLibs.stream()
.map(dm -> new EarlyLoadingException.ExceptionData("fml.modloading.dupedlib.versioned", dm, Objects.toString(dm)))
.toList();
throw new EarlyLoadingException("Duplicate plugins or libraries found", null, duplicateLibErrors);
final List<String> dupedLibErrors = versionedLibIds.values().stream()
.filter(modFiles -> modFiles.size() > 1)
.map(mods -> String.format("\tLibrary: '%s' from files: %s",
getModId(mods.get(0)),
mods.stream()
.map(modFile -> modFile.getFileName()).collect(joining(", "))
)).toList();
if (!dupedLibErrors.isEmpty()) {
LOGGER.error(LOADING, "Found duplicate plugins or libraries:\n{}", dupedLibErrors.stream().collect(joining("\n")));
throw new EarlyLoadingException("Duplicate plugins or libraries found", null, dupedLibErrors.stream()
.map(s -> new EarlyLoadingException.ExceptionData(s))
.toList());
}
// Collect unique mod files by module name. This will be used for deduping purposes
@@ -38,7 +38,7 @@ public abstract class AbstractModProvider implements IModProvider
var sj = SecureJar.from(
Manifest::new,
jar -> jar.moduleDataProvider().findFile(MODS_TOML).isPresent() ? mjm : JarMetadata.from(jar, path),
(root, p) -> true,
null,
path
);
@@ -34,7 +34,7 @@ public class ExplodedDirectoryLocator implements IModLocator {
explodedMods.forEach(explodedMod ->
ModJarMetadata.buildFile(this,
jar->jar.moduleDataProvider().findFile("/META-INF/mods.toml").isPresent(),
(a,b) -> true,
null,
explodedMod.paths().toArray(Path[]::new))
.ifPresentOrElse(f->mods.put(explodedMod, f), () -> LOGGER.warn(LogMarkers.LOADING, "Failed to find exploded resource mods.toml in directory {}", explodedMod.paths().get(0).toString())));
return mods.values().stream().map(mf->new IModLocator.ModFileOrException(mf, null)).toList();
@@ -69,7 +69,9 @@ public class ModInfo implements IModInfo, IConfigurable
.map(s -> StringSubstitutor.replace(s, ownFile.map(ModFileInfo::getFile).orElse(null)))
.map(DefaultArtifactVersion::new).orElse(DEFAULT_VERSION);
this.displayName = config.<String>getConfigElement("displayName").orElse(this.modId);
this.description = config.<String>getConfigElement("description").orElse("MISSING DESCRIPTION");
this.description = config.<String>getConfigElement("description")
.orElse("MISSING DESCRIPTION")
.replace("\r\n", "\n").stripIndent();
this.logoFile = Optional.ofNullable(config.<String>getConfigElement("logoFile")
.orElseGet(() -> ownFile.flatMap(mf -> mf.<String>getConfigElement("logoFile")).orElse(null)));
@@ -196,7 +198,7 @@ public class ModInfo implements IModInfo, IConfigurable
private final boolean mandatory;
private final Ordering ordering;
private final DependencySide side;
private Optional<URL> referralUrl;
private final Optional<URL> referralUrl;
public ModVersion(final IModInfo owner, final IConfigurable config) {
this.owner = owner;
@@ -31,7 +31,7 @@ public final class ModJarMetadata implements JarMetadata {
// TODO: Remove helper functions to cleanup api
@Deprecated(forRemoval = true, since="1.18")
static IModFile buildFile(IModLocator locator, Path... files) {
return buildFile(locator, j->true, (a,b) -> true, files).orElseThrow(()->new IllegalArgumentException("Failed to find valid JAR file"));
return buildFile(locator, j->true, null, files).orElseThrow(()->new IllegalArgumentException("Failed to find valid JAR file"));
}
// TODO: Remove helper functions to cleanup api
@@ -43,7 +43,7 @@ public abstract class CommonClientLaunchHandler extends CommonLaunchHandler {
var lowcodelang = LibraryFinder.findPathForMaven(vers.forgeGroup(), "lowcodelanguage", "", "", vers.mcAndForgeVersion());
var mclang = LibraryFinder.findPathForMaven(vers.forgeGroup(), "mclanguage", "", "", vers.mcAndForgeVersion());
return new LocatedPaths(mcstream.build().toList(), (a,b) -> true, modstream.build().toList(), List.of(fmlcore, javafmllang, lowcodelang, mclang));
return new LocatedPaths(mcstream.build().toList(), null, modstream.build().toList(), List.of(fmlcore, javafmllang, lowcodelang, mclang));
}
protected abstract void processMCStream(VersionInfo versionInfo, Stream.Builder<Path> mc, Stream.Builder<List<Path>> mods);
@@ -42,13 +42,21 @@ public abstract class CommonServerLaunchHandler extends CommonLaunchHandler {
!path.startsWith("META-INF/"));
}, mcextra
);
// Todo in 1.20.2: Change the default filter to null instead of always true.
BiPredicate<String, String> filter = (path, base) -> true;
final BiPredicate<String, String> alwaysTrueFilter = filter;
var mcstream = Stream.<Path>builder().add(mc).add(mcextra_filtered.getRootPath());
var modstream = Stream.<List<Path>>builder();
filter = processMCStream(vers, mcstream, filter, modstream);
// Ensure backwards compatibility if anything overrides processMCStream()
// and expects the default always true filter by only changing it to null afterwards if left unchanged.
if (filter == alwaysTrueFilter)
filter = null;
var fmlcore = LibraryFinder.findPathForMaven(vers.forgeGroup(), "fmlcore", "", "", vers.mcAndForgeVersion());
var javafmllang = LibraryFinder.findPathForMaven(vers.forgeGroup(), "javafmllanguage", "", "", vers.mcAndForgeVersion());
var lowcodelang = LibraryFinder.findPathForMaven(vers.forgeGroup(), "lowcodelanguage", "", "", vers.mcAndForgeVersion());
Binary file not shown.
+2 -1
View File
@@ -1,5 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip
networkTimeout=10000
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored
+12 -7
View File
@@ -55,7 +55,7 @@
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
@@ -80,13 +80,10 @@ do
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# 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"'
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
@@ -143,12 +140,16 @@ fi
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
@@ -193,6 +194,10 @@ if "$cygwin" || "$msys" ; then
done
fi
# 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"'
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
Vendored
+1
View File
@@ -26,6 +26,7 @@ if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@@ -21,6 +21,8 @@ import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import java.lang.reflect.InvocationTargetException;
import java.util.Objects;
import java.util.Optional;
public class FMLModContainer extends ModContainer
@@ -70,6 +72,11 @@ public class FMLModContainer extends ModContainer
}
catch (Throwable e)
{
// When a mod constructor throws an exception, it's wrapped in an InvocationTargetException which hides the
// actual exception from the mod loading error screen.
if (e instanceof InvocationTargetException wrapped)
e = Objects.requireNonNullElse(wrapped.getCause(), e); // unwrap the exception
LOGGER.error(LOADING,"Failed to create mod instance. ModID: {}, class {}", getModId(), modClass.getName(), e);
throw new ModLoadingException(modInfo, ModLoadingStage.CONSTRUCT, "fml.modloading.failedtoloadmod", e, modClass);
}
+6 -6
View File
@@ -16,14 +16,14 @@ Step 1: Open your command-line and browse to the folder where you extracted the
Step 2: You're left with a choice.
If you prefer to use Eclipse:
1. Run the following command: `gradlew genEclipseRuns` (`./gradlew genEclipseRuns` if you are on Mac/Linux)
2. Open Eclipse, Import > Existing Gradle Project > Select Folder
1. Run the following command: `./gradlew genEclipseRuns`
or run `gradlew eclipse` to generate the project.
If you prefer to use IntelliJ:
1. Open IDEA, and import project.
2. Select your build.gradle file and have it import.
3. Run the following command: `gradlew genIntellijRuns` (`./gradlew genIntellijRuns` if you are on Mac/Linux)
3. Run the following command: `./gradlew genIntellijRuns`
4. Refresh the Gradle Project in IDEA if required.
If at any point you are missing libraries in your IDE, or you've run into problems you can
@@ -40,7 +40,7 @@ https://github.com/MinecraftForge/MCPConfig/blob/master/Mojang.md
Additional Resources:
=========================
Community Documentation: https://mcforge.readthedocs.io/en/latest/gettingstarted/
LexManos' Install Video: https://www.youtube.com/watch?v=8VEdtQLuLO0
Forge Forum: https://forums.minecraftforge.net/
Forge Discord: https://discord.gg/UvedJ9m
Community Documentation: https://docs.minecraftforge.net/en/1.19.x/gettingstarted/
LexManos' Install Video: https://youtu.be/8VEdtQLuLO0
Forge Forums: https://forums.minecraftforge.net/
Forge Discord: https://discord.minecraftforge.net/
+103 -74
View File
@@ -1,12 +1,16 @@
plugins {
id 'eclipse'
id 'idea'
id 'maven-publish'
id 'net.minecraftforge.gradle' version '5.1.+'
id 'net.minecraftforge.gradle' version '[6.0,6.2)'
}
version = '1.0'
group = 'com.yourname.modid' // http://maven.apache.org/guides/mini/guide-naming-conventions.html
archivesBaseName = 'modid'
version = mod_version
group = mod_group_id
base {
archivesName = mod_id
}
// Mojang ships Java 17 to end users in 1.18+, so your mod should target Java 17.
java.toolchain.languageVersion = JavaLanguageVersion.of(17)
@@ -26,14 +30,36 @@ minecraft {
//
// 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.
mappings channel: '@MAPPING_CHANNEL@', version: '@MAPPING_VERSION@'
mappings channel: mapping_channel, version: mapping_version
// accessTransformer = file('src/main/resources/META-INF/accesstransformer.cfg') // Currently, this location cannot be changed from the default.
// 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.
// enableEclipsePrepareRuns = true
// enableIdeaPrepareRuns = true
// This property allows configuring Gradle's ProcessResources task(s) to run on IDE output locations before launching the game.
// It is REQUIRED to be set to true for this template to function.
// See https://docs.gradle.org/current/dsl/org.gradle.language.jvm.tasks.ProcessResources.html
copyIdeResources = true
// When true, this property will add the folder name of all declared run configurations to generated IDE run configurations.
// The folder name can be set on a run configuration using the "folderName" property.
// By default, the folder name of a run configuration is the name of the Gradle project containing it.
// generateRunFolders = true
// This property enables access transformers for use in development.
// They will be applied to the Minecraft artifact.
// The access transformer file can be anywhere in the project.
// However, it must be at "META-INF/accesstransformer.cfg" in the final mod jar to be loaded by Forge.
// This default location is a best practice to automatically put the file in the right place in the final jar.
// See https://docs.minecraftforge.net/en/latest/advanced/accesstransformers/ for more information.
// accessTransformer = file('src/main/resources/META-INF/accesstransformer.cfg')
// Default run configurations.
// These can be tweaked, removed, or duplicated as needed.
runs {
client {
// applies to all the run configs below
configureEach {
workingDirectory project.file('run')
// Recommended logging data for a userdev environment
@@ -49,65 +75,38 @@ minecraft {
property 'forge.logging.console.level', 'debug'
// Comma-separated list of namespaces to load gametests from. Empty = all namespaces.
property 'forge.enabledGameTestNamespaces', 'examplemod'
property 'forge.enabledGameTestNamespaces', mod_id
mods {
examplemod {
"${mod_id}" {
source sourceSets.main
}
}
}
client {
// Comma-separated list of namespaces to load gametests from. Empty = all namespaces.
property 'forge.enabledGameTestNamespaces', mod_id
}
server {
workingDirectory project.file('run')
property 'forge.logging.markers', 'REGISTRIES'
property 'forge.logging.console.level', 'debug'
property 'forge.enabledGameTestNamespaces', 'examplemod'
mods {
examplemod {
source sourceSets.main
}
}
property 'forge.enabledGameTestNamespaces', mod_id
args '--nogui'
}
// This run config launches GameTestServer and runs all registered gametests, then exits.
// By default, the server will crash when no gametests are provided.
// The gametest system is also enabled by default for other run configs under the /test command.
gameTestServer {
workingDirectory project.file('run')
property 'forge.logging.markers', 'REGISTRIES'
property 'forge.logging.console.level', 'debug'
property 'forge.enabledGameTestNamespaces', 'examplemod'
mods {
examplemod {
source sourceSets.main
}
}
property 'forge.enabledGameTestNamespaces', mod_id
}
data {
workingDirectory project.file('run')
property 'forge.logging.markers', 'REGISTRIES'
property 'forge.logging.console.level', 'debug'
// example of overriding the workingDirectory set in configureEach above
workingDirectory project.file('run-data')
// Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources.
args '--mod', 'examplemod', '--all', '--output', file('src/generated/resources/'), '--existing', file('src/main/resources/')
mods {
examplemod {
source sourceSets.main
}
}
args '--mod', mod_id, '--all', '--output', file('src/generated/resources/'), '--existing', file('src/main/resources/')
}
}
}
@@ -119,53 +118,83 @@ repositories {
// Put repositories for dependencies here
// ForgeGradle automatically adds the Forge maven and Maven Central for you
// If you have mod jar dependencies in ./libs, you can declare them as a repository like so:
// If you have mod jar dependencies in ./libs, you can declare them as a repository like so.
// See https://docs.gradle.org/current/userguide/declaring_repositories.html#sub:flat_dir_resolver
// flatDir {
// dir 'libs'
// }
}
dependencies {
// Specify the version of Minecraft to use. If this is any group other than 'net.minecraft', it is assumed
// that the dep is a ForgeGradle 'patcher' dependency, and its patches will be applied.
// The userdev artifact is a special name and will get all sorts of transformations applied to it.
minecraft '@FORGE_GROUP@:@FORGE_NAME@:@FORGE_VERSION@'
// Specify the version of Minecraft to use.
// Any artifact can be supplied so long as it has a "userdev" classifier artifact and is a compatible patcher artifact.
// The "userdev" classifier will be requested and setup by ForgeGradle.
// If the group id is "net.minecraft" and the artifact id is one of ["client", "server", "joined"],
// 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}"
// Real mod deobf dependency examples - these get remapped to your current mappings
// implementation fg.deobf("com.tterrag.registrate:Registrate:MC${mc_version}-${registrate_version}") // Adds registrate as a dependency
// Example mod dependency with JEI - using fg.deobf() ensures the dependency is remapped to your development mappings
// 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 fg.deobf("mezz.jei:jei-${mc_version}-forge-api:${jei_version}")
// runtimeOnly fg.deobf("mezz.jei:jei-${mc_version}-forge:${jei_version}")
// Examples using mod jars from ./libs
// Example mod dependency using a mod jar from ./libs with a flat dir repository
// This maps to ./libs/coolmod-${mc_version}-${coolmod_version}.jar
// The group id is ignored when searching -- in this case, it is "blank"
// implementation fg.deobf("blank:coolmod-${mc_version}:${coolmod_version}")
// For more info...
// For more info:
// http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html
// http://www.gradle.org/docs/current/userguide/dependency_management.html
}
// Example for how to get properties into the manifest for reading at runtime.
jar {
manifest {
attributes([
"Specification-Title" : "examplemod",
"Specification-Vendor" : "examplemodsareus",
"Specification-Version" : "1", // We are version 1 of ourselves
"Implementation-Title" : project.name,
"Implementation-Version" : project.jar.archiveVersion,
"Implementation-Vendor" : "examplemodsareus",
"Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ")
])
// This block of code expands all declared replace properties in the specified resource targets.
// A missing property will result in an error. Properties are expanded using ${} Groovy notation.
// When "copyIdeResources" is enabled, this will also run before the game launches in IDE environments.
// See https://docs.gradle.org/current/dsl/org.gradle.language.jvm.tasks.ProcessResources.html
tasks.named('processResources', ProcessResources).configure {
var replaceProperties = [
minecraft_version: minecraft_version, minecraft_version_range: minecraft_version_range,
forge_version: forge_version, forge_version_range: forge_version_range,
loader_version_range: loader_version_range,
mod_id: mod_id, mod_name: mod_name, mod_license: mod_license, mod_version: mod_version,
mod_authors: mod_authors, mod_description: mod_description,
]
inputs.properties replaceProperties
filesMatching(['META-INF/mods.toml', 'pack.mcmeta']) {
expand replaceProperties + [project: project]
}
}
// Example configuration to allow publishing using the maven-publish plugin
// This is the preferred method to reobfuscate your jar file
jar.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
// publish.dependsOn('reobfJar')
// Example for how to get properties into the manifest for reading at runtime.
tasks.named('jar', Jar).configure {
manifest {
attributes([
'Specification-Title' : mod_id,
'Specification-Vendor' : mod_authors,
'Specification-Version' : '1', // We are version 1 of ourselves
'Implementation-Title' : project.name,
'Implementation-Version' : project.jar.archiveVersion,
'Implementation-Vendor' : mod_authors,
'Implementation-Timestamp': new Date().format("yyyy-MM-dd'T'HH:mm:ssZ")
])
}
// 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
publishing {
publications {
mavenJava(MavenPublication) {
register('mavenJava', MavenPublication) {
artifact jar
}
}
+56 -1
View File
@@ -1,4 +1,59 @@
# Sets default memory used for gradle commands. Can be overridden by user or command line properties.
# This is required to provide enough memory for the Minecraft decompilation process.
org.gradle.jvmargs=-Xmx3G
org.gradle.daemon=false
org.gradle.daemon=false
## Environment Properties
# The Minecraft version must agree with the Forge version to get a valid artifact
minecraft_version=@MC_VERSION@
# The Minecraft version range can use any release version of Minecraft as bounds.
# Snapshots, pre-releases, and release candidates are not guaranteed to sort properly
# as they do not follow standard versioning conventions.
minecraft_version_range=[@MC_VERSION@,@MC_NEXT_VERSION@)
# The Forge version must agree with the Minecraft version to get a valid artifact
forge_version=@FORGE_VERSION@
# The Forge version range can use any version of Forge as bounds or match the loader version range
forge_version_range=[@FORGE_SPEC_VERSION@,)
# The loader version range can only use the major version of Forge/FML as bounds
loader_version_range=[@FORGE_SPEC_VERSION@,)
# The mapping channel to use for mappings.
# The default set of supported mapping channels are ["official", "snapshot", "snapshot_nodoc", "stable", "stable_nodoc"].
# Additional mapping channels can be registered through the "channelProviders" extension in a Gradle plugin.
#
# | Channel | Version | |
# |-----------|----------------------|--------------------------------------------------------------------------------|
# | official | MCVersion | Official field/method names from Mojang mapping files |
# | parchment | YYYY.MM.DD-MCVersion | Open community-sourced parameter names and javadocs layered on top of official |
#
# You must be aware of the Mojang license when using the 'official' or 'parchment' mappings.
# See more information here: https://github.com/MinecraftForge/MCPConfig/blob/master/Mojang.md
#
# Parchment is an unofficial project maintained by ParchmentMC, separate from Minecraft Forge.
# Additional setup is needed to use their mappings, see https://parchmentmc.org/docs/getting-started
mapping_channel=@MAPPING_CHANNEL@
# The mapping version to query from the mapping channel.
# This must match the format required by the mapping channel.
mapping_version=@MAPPING_VERSION@
## Mod Properties
# The unique mod identifier for the mod. Must be lowercase in English locale. Must fit the regex [a-z][a-z0-9_]{1,63}
# Must match the String constant located in the main mod class annotated with @Mod.
mod_id=examplemod
# The human-readable display name for the mod.
mod_name=Example Mod
# The license of the mod. Review your options at https://choosealicense.com/. All Rights Reserved is the default.
mod_license=All Rights Reserved
# The mod version. See https://semver.org/
mod_version=1.0.0
# The group ID for the mod. It is only important when publishing as an artifact to a Maven repository.
# This should match the base package used for the mod sources.
# See https://maven.apache.org/guides/mini/guide-naming-conventions.html
mod_group_id=com.example.examplemod
# The authors of the mod. This is a simple text string that is used for display purposes in the mod list.
mod_authors=YourNameHere, OtherNameHere
# The description of the mod. This is a simple multiline text string that is used for display purposes in the mod list.
mod_description=Example mod description.\nNewline characters can be used and will be replaced properly.
+8 -1
View File
@@ -1,6 +1,13 @@
pluginManagement {
repositories {
gradlePluginPortal()
maven { url = 'https://maven.minecraftforge.net/' }
maven {
name = 'MinecraftForge'
url = 'https://maven.minecraftforge.net/'
}
}
}
plugins {
id 'org.gradle.toolchains.foojay-resolver-convention' version '0.7.0'
}
@@ -0,0 +1,64 @@
package com.example.examplemod;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.Item;
import net.minecraftforge.common.ForgeConfigSpec;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.config.ModConfigEvent;
import net.minecraftforge.registries.ForgeRegistries;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
// An example config class. This is not required, but it's a good idea to have one to keep your config organized.
// Demonstrates how to use Forge's config APIs
@Mod.EventBusSubscriber(modid = ExampleMod.MODID, bus = Mod.EventBusSubscriber.Bus.MOD)
public class Config
{
private static final ForgeConfigSpec.Builder BUILDER = new ForgeConfigSpec.Builder();
private static final ForgeConfigSpec.BooleanValue LOG_DIRT_BLOCK = BUILDER
.comment("Whether to log the dirt block on common setup")
.define("logDirtBlock", true);
private static final ForgeConfigSpec.IntValue MAGIC_NUMBER = BUILDER
.comment("A magic number")
.defineInRange("magicNumber", 42, 0, Integer.MAX_VALUE);
public static final ForgeConfigSpec.ConfigValue<String> MAGIC_NUMBER_INTRODUCTION = BUILDER
.comment("What you want the introduction message to be for the magic number")
.define("magicNumberIntroduction", "The magic number is... ");
// a list of strings that are treated as resource locations for items
private static final ForgeConfigSpec.ConfigValue<List<? extends String>> ITEM_STRINGS = BUILDER
.comment("A list of items to log on common setup.")
.defineListAllowEmpty(Collections.singletonList("items"), () -> List.of("minecraft:iron_ingot"), Config::validateItemName);
static final ForgeConfigSpec SPEC = BUILDER.build();
public static boolean logDirtBlock;
public static int magicNumber;
public static String magicNumberIntroduction;
public static Set<Item> items;
private static boolean validateItemName(final Object obj)
{
return obj instanceof final String itemName && ForgeRegistries.ITEMS.containsKey(new ResourceLocation(itemName));
}
@SubscribeEvent
static void onLoad(final ModConfigEvent event)
{
logDirtBlock = LOG_DIRT_BLOCK.get();
magicNumber = MAGIC_NUMBER.get();
magicNumberIntroduction = MAGIC_NUMBER_INTRODUCTION.get();
// convert the list of strings into a set of items
items = ITEM_STRINGS.get().stream()
.map(itemName -> ForgeRegistries.ITEMS.getValue(new ResourceLocation(itemName)))
.collect(Collectors.toSet());
}
}
@@ -15,7 +15,9 @@ import net.minecraftforge.event.CreativeModeTabEvent;
import net.minecraftforge.event.server.ServerStartingEvent;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.ModLoadingContext;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.config.ModConfig;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
@@ -59,13 +61,22 @@ public class ExampleMod
// Register the item to a creative tab
modEventBus.addListener(this::addCreative);
// 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);
}
private void commonSetup(final FMLCommonSetupEvent event)
{
// Some common setup code
LOGGER.info("HELLO FROM COMMON SETUP");
LOGGER.info("DIRT BLOCK >> {}", ForgeRegistries.BLOCKS.getKey(Blocks.DIRT));
if (Config.logDirtBlock)
LOGGER.info("DIRT BLOCK >> {}", ForgeRegistries.BLOCKS.getKey(Blocks.DIRT));
LOGGER.info(Config.magicNumberIntroduction + Config.magicNumber);
Config.items.forEach((item) -> LOGGER.info("ITEM >> {}", item.toString()));
}
private void addCreative(CreativeModeTabEvent.BuildContents event)
+30 -36
View File
@@ -6,32 +6,30 @@
# The name of the mod loader type to load - for regular FML @Mod mods it should be javafml
modLoader="javafml" #mandatory
# A version range to match for said mod loader - for regular FML @Mod it will be the forge version
loaderVersion="[@FORGE_SPEC_VERSION@,)" #mandatory This is typically bumped every Minecraft version by Forge. See our download page for lists of versions.
loaderVersion="${loader_version_range}" #mandatory This is typically bumped every Minecraft version by Forge. See our download page for lists of versions.
# The license for you mod. This is mandatory metadata and allows for easier comprehension of your redistributive properties.
# Review your options at https://choosealicense.com/. All rights reserved is the default copyright stance, and is thus the default here.
license="All rights reserved"
license="${mod_license}"
# A URL to refer people to when problems occur with this mod
#issueTrackerURL="https://change.me.to.your.issue.tracker.example.invalid/" #optional
# A list of mods - how many allowed here is determined by the individual mod loader
[[mods]] #mandatory
# The modid of the mod
modId="examplemod" #mandatory
# The version number of the mod - there's a few well known ${} variables useable here or just hardcode it
# ${file.jarVersion} will substitute the value of the Implementation-Version as read from the mod's JAR file metadata
# see the associated build.gradle script for how to populate this completely automatically during a build
version="${file.jarVersion}" #mandatory
# A display name for the mod
displayName="Example Mod" #mandatory
modId="${mod_id}" #mandatory
# The version number of the mod
version="${mod_version}" #mandatory
# A display name for the mod
displayName="${mod_name}" #mandatory
# A URL to query for updates for this mod. See the JSON update specification https://docs.minecraftforge.net/en/latest/misc/updatechecker/
#updateJSONURL="https://change.me.example.invalid/updates.json" #optional
# A URL for the "homepage" for this mod, displayed in the mod UI
#displayURL="https://change.me.to.your.mods.homepage.example.invalid/" #optional
# A file name (in the root of the mod JAR) containing a logo for display
logoFile="examplemod.png" #optional
#logoFile="examplemod.png" #optional
# A text field displayed in the mod UI
credits="Thanks for this example mod goes to Java" #optional
#credits="" #optional
# A text field displayed in the mod UI
authors="Love, Cheese and small house plants" #optional
authors="${mod_authors}" #optional
# Display Test controls the display for your mod in the server connection screen
# MATCH_VERSION means that your mod will cause a red X if the versions on client and server differ. This is the default behaviour and should be what you choose if you have server and client elements to your mod.
# IGNORE_SERVER_VERSION means that your mod will not cause a red X if it's present on the server but not on the client. This is what you should use if you're a server only mod.
@@ -41,30 +39,26 @@ authors="Love, Cheese and small house plants" #optional
#displayTest="MATCH_VERSION" # MATCH_VERSION is the default if nothing is specified (#optional)
# The description text for the mod (multi line!) (#mandatory)
description='''
This is a long form description of the mod. You can write whatever you want here
Have some lorem ipsum.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed mollis lacinia magna. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed sagittis luctus odio eu tempus. Interdum et malesuada fames ac ante ipsum primis in faucibus. Pellentesque volutpat ligula eget lacus auctor sagittis. In hac habitasse platea dictumst. Nunc gravida elit vitae sem vehicula efficitur. Donec mattis ipsum et arcu lobortis, eleifend sagittis sem rutrum. Cras pharetra quam eget posuere fermentum. Sed id tincidunt justo. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
'''
description='''${mod_description}'''
# A dependency - use the . to indicate dependency for a specific modid. Dependencies are optional.
[[dependencies.examplemod]] #optional
# the modid of the dependency
modId="forge" #mandatory
# Does this dependency have to exist - if not, ordering below must be specified
mandatory=true #mandatory
# The version range of the dependency
versionRange="[@FORGE_SPEC_VERSION@,)" #mandatory
# An ordering relationship for the dependency - BEFORE or AFTER required if the relationship is not mandatory
ordering="NONE"
# Side this dependency is applied on - BOTH, CLIENT or SERVER
side="BOTH"
[[dependencies.${mod_id}]] #optional
# the modid of the dependency
modId="forge" #mandatory
# Does this dependency have to exist - if not, ordering below must be specified
mandatory=true #mandatory
# The version range of the dependency
versionRange="${forge_version_range}" #mandatory
# An ordering relationship for the dependency - BEFORE or AFTER required if the dependency is not mandatory
# BEFORE - This mod is loaded BEFORE the dependency
# AFTER - This mod is loaded AFTER the dependency
ordering="NONE"
# Side this dependency is applied on - BOTH, CLIENT, or SERVER
side="BOTH"
# Here's another dependency
[[dependencies.examplemod]]
modId="minecraft"
mandatory=true
[[dependencies.${mod_id}]]
modId="minecraft"
mandatory=true
# This version range declares a minimum of the current minecraft version up to but not including the next major version
versionRange="[@MC_VERSION@,@MC_NEXT_VERSION@)"
ordering="NONE"
side="BOTH"
versionRange="${minecraft_version_range}"
ordering="NONE"
side="BOTH"
@@ -1,6 +1,6 @@
--- a/net/minecraft/CrashReport.java
+++ b/net/minecraft/CrashReport.java
@@ -57,14 +_,8 @@
@@ -57,14 +_,9 @@
if (this.f_127506_ != null && this.f_127506_.length > 0) {
p_127520_.append("-- Head --\n");
p_127520_.append("Thread: ").append(Thread.currentThread().getName()).append("\n");
@@ -12,6 +12,7 @@
- }
-
- p_127520_.append("\n");
+ p_127520_.append(net.minecraftforge.logging.CrashReportAnalyser.appendSuspectedMods(this.f_127501_, this.f_127506_));
+ p_127520_.append("Stacktrace:");
+ p_127520_.append(net.minecraftforge.logging.CrashReportExtender.generateEnhancedStackTrace(this.f_127506_));
}
@@ -12,6 +12,15 @@
private static final Set<String> f_90811_ = Sets.newHashSet();
public static final String f_167805_ = "key.categories.movement";
public static final String f_167806_ = "key.categories.misc";
@@ -41,7 +_,7 @@
private int f_90818_;
public static void m_90835_(InputConstants.Key p_90836_) {
- KeyMapping keymapping = f_90810_.get(p_90836_);
+ for (KeyMapping keymapping : f_90810_.getAll(p_90836_))
if (keymapping != null) {
++keymapping.f_90818_;
}
@@ -49,7 +_,7 @@
}
@@ -0,0 +1,11 @@
--- a/net/minecraft/client/gui/screens/ConnectScreen.java
+++ b/net/minecraft/client/gui/screens/ConnectScreen.java
@@ -72,6 +_,8 @@
}
if (!optional.isPresent()) {
+ ConnectScreen.f_95683_.error("Couldn't connect to server: Unknown host \"{}\"", p_249536_.m_171863_());
+ net.minecraftforge.network.DualStackUtils.logInitialPreferences();
p_251955_.execute(() -> {
p_251955_.m_91152_(new DisconnectedScreen(ConnectScreen.this.f_95686_, CommonComponents.f_130661_, ConnectScreen.f_169260_));
});
@@ -0,0 +1,10 @@
--- a/net/minecraft/client/gui/screens/PauseScreen.java
+++ b/net/minecraft/client/gui/screens/PauseScreen.java
@@ -83,6 +_,7 @@
} else {
gridlayout$rowhelper.m_264139_(this.m_262456_(f_262254_, SocialInteractionsScreen::new));
}
+ gridlayout$rowhelper.m_264108_(Button.m_253074_(Component.m_237115_("fml.menu.mods"), button -> this.f_96541_.m_91152_(new net.minecraftforge.client.gui.ModListScreen(this))).m_252780_(f_262268_).m_253136_(), 2);
Component component = this.f_96541_.m_91090_() ? f_262217_ : f_262246_;
this.f_252482_ = gridlayout$rowhelper.m_264108_(Button.m_253074_(component, (p_275864_) -> {
@@ -34,7 +34,7 @@
this.f_97334_.m_104401_(advancementtab.m_97182_(), true);
break;
}
@@ -98,6 +_,11 @@
@@ -98,9 +_,15 @@
int i = (this.f_96543_ - 252) / 2;
int j = (this.f_96544_ - 140) / 2;
this.m_7333_(p_97361_);
@@ -46,6 +46,10 @@
this.m_97373_(p_97361_, p_97362_, p_97363_, i, j);
this.m_97356_(p_97361_, i, j);
this.m_97381_(p_97361_, p_97362_, p_97363_, i, j);
+ super.m_86412_(p_97361_, p_97362_, p_97363_, p_97364_);
}
public boolean m_7979_(double p_97347_, double p_97348_, int p_97349_, double p_97350_, double p_97351_) {
@@ -138,10 +_,12 @@
RenderSystem.m_157456_(0, f_97330_);
@@ -1,5 +1,14 @@
--- a/net/minecraft/client/particle/TerrainParticle.java
+++ b/net/minecraft/client/particle/TerrainParticle.java
@@ -28,7 +_,7 @@
this.f_107227_ = 0.6F;
this.f_107228_ = 0.6F;
this.f_107229_ = 0.6F;
- if (!p_172458_.m_60713_(Blocks.f_50440_)) {
+ if (net.minecraftforge.client.extensions.common.IClientBlockExtensions.of(p_172458_).areBreakingParticlesTinted(p_172458_, p_172451_, p_172459_)) {
int i = Minecraft.m_91087_().m_91298_().m_92577_(p_172458_, p_172451_, p_172459_, 0);
this.f_107227_ *= (float)(i >> 16 & 255) / 255.0F;
this.f_107228_ *= (float)(i >> 8 & 255) / 255.0F;
@@ -69,7 +_,13 @@
public static class Provider implements ParticleProvider<BlockParticleOption> {
public Particle m_6966_(BlockParticleOption p_108304_, ClientLevel p_108305_, double p_108306_, double p_108307_, double p_108308_, double p_108309_, double p_108310_, double p_108311_) {
@@ -9,21 +9,13 @@
this.f_120088_.setSoTimeout(5000);
this.f_120088_.joinGroup(this.f_120087_);
}
@@ -87,7 +_,19 @@
@@ -87,7 +_,11 @@
String s = LanServerPinger.m_120111_(p_120097_);
String s1 = LanServerPinger.m_120116_(p_120097_);
if (s1 != null) {
- s1 = p_120098_.getHostAddress() + ":" + s1;
+ if (net.minecraftforge.network.DualStackUtils.checkIPv6(p_120098_)) {
+ final String ip;
+
+ // compress to short form if enabled in config
+ if (net.minecraftforge.common.ForgeConfig.CLIENT.compressLanIPv6Addresses.get())
+ ip = com.google.common.net.InetAddresses.toAddrString(p_120098_);
+ else
+ ip = p_120098_.getHostAddress();
+
+ s1 = "[" + ip + "]:" + s1;
+ s1 = "[" + com.google.common.net.InetAddresses.toAddrString(p_120098_) + "]:" + s1;
+ } else {
+ s1 = p_120098_.getHostAddress() + ":" + s1;
+ }
@@ -1,6 +1,6 @@
--- a/net/minecraft/client/server/LanServerPinger.java
+++ b/net/minecraft/client/server/LanServerPinger.java
@@ -16,7 +_,7 @@
@@ -13,7 +_,7 @@
public class LanServerPinger extends Thread {
private static final AtomicInteger f_120101_ = new AtomicInteger(0);
private static final Logger f_120102_ = LogUtils.getLogger();
@@ -9,7 +9,7 @@
public static final int f_174975_ = 4445;
private static final long f_174976_ = 1500L;
private final String f_120103_;
@@ -39,7 +_,7 @@
@@ -36,7 +_,7 @@
while(!this.isInterrupted() && this.f_120105_) {
try {
@@ -1,5 +1,14 @@
--- a/net/minecraft/server/dedicated/DedicatedServer.java
+++ b/net/minecraft/server/dedicated/DedicatedServer.java
@@ -68,6 +_,8 @@
private MinecraftServerGui f_139605_;
@Nullable
private final TextFilterClient f_139606_;
+ @Nullable
+ private net.minecraft.client.server.LanServerPinger dediLanPinger;
public DedicatedServer(Thread p_214789_, LevelStorageSource.LevelStorageAccess p_214790_, PackRepository p_214791_, WorldStem p_214792_, DedicatedServerSettings p_214793_, DataFixer p_214794_, Services p_214795_, ChunkProgressListenerFactory p_214796_) {
super(p_214789_, p_214790_, p_214791_, p_214792_, Proxy.NO_PROXY, p_214794_, p_214795_, p_214796_);
@@ -79,6 +_,7 @@
public boolean m_7038_() throws IOException {
Thread thread = new Thread("Server console handler") {
@@ -22,7 +31,7 @@
if (dedicatedserverproperties.f_139744_ != null) {
this.m_129900_().m_46170_(GameRules.f_46153_).m_46246_(dedicatedserverproperties.f_139744_, this);
}
@@ -183,12 +_,13 @@
@@ -183,12 +_,18 @@
thread1.start();
}
@@ -33,7 +42,34 @@
}
- return true;
+ if (net.minecraftforge.common.ForgeConfig.SERVER.advertiseDedicatedServerToLan.get()) {
+ this.dediLanPinger = new net.minecraft.client.server.LanServerPinger(this.m_129916_(), String.valueOf(this.m_7448_()));
+ this.dediLanPinger.start();
+ }
+
+ return net.minecraftforge.server.ServerLifecycleHooks.handleServerStarting(this);
}
}
@@ -263,6 +_,10 @@
this.f_139601_.m_7530_();
}
+ if (this.dediLanPinger != null) {
+ this.dediLanPinger.interrupt();
+ this.dediLanPinger = null;
+ }
}
public void m_5703_(BooleanSupplier p_139661_) {
@@ -492,6 +_,10 @@
public void m_7041_() {
super.m_7041_();
+ if (this.dediLanPinger != null) {
+ this.dediLanPinger.interrupt();
+ this.dediLanPinger = null;
+ }
Util.m_137580_();
SkullBlockEntity.m_196704_();
}
@@ -15,6 +15,16 @@
this.m_10055_();
} else if (this.f_10019_ == ServerLoginPacketListenerImpl.State.DELAY_ACCEPT) {
ServerPlayer serverplayer = this.f_10018_.m_6846_().m_11259_(this.f_10021_.getId());
@@ -138,7 +_,8 @@
}
public String m_10056_() {
- return this.f_10021_ != null ? this.f_10021_ + " (" + this.f_10013_.m_129523_() + ")" : String.valueOf((Object)this.f_10013_.m_129523_());
+ final String addressString = net.minecraftforge.network.DualStackUtils.getAddressString(this.f_10013_.m_129523_());
+ return this.f_10021_ != null ? this.f_10021_ + " (" + addressString + ")" : addressString;
}
public void m_5990_(ServerboundHelloPacket p_10047_) {
@@ -147,14 +_,14 @@
GameProfile gameprofile = this.f_10018_.m_236731_();
if (gameprofile != null && p_10047_.f_238040_().equalsIgnoreCase(gameprofile.getName())) {
@@ -5,7 +5,7 @@
public PackRepository(RepositorySource... p_251886_) {
- this.f_10497_ = ImmutableSet.copyOf(p_251886_);
+ this.f_10497_ = new java.util.HashSet<>(List.of(p_251886_)); //Forge: This needs to be a mutable set, so that we can add to it later on.
+ this.f_10497_ = new java.util.LinkedHashSet<>(List.of(p_251886_)); //Forge: This needs to be a mutable set, so that we can add to it later on.
}
public void m_10506_() {
@@ -8,7 +8,15 @@
public PlayerList(MinecraftServer p_203842_, LayeredRegistryAccess<RegistryLayer> p_251844_, PlayerDataStorage p_203844_, int p_203845_) {
this.f_11195_ = p_203842_;
@@ -168,6 +_,7 @@
@@ -161,13 +_,14 @@
p_11263_.m_143425_(serverlevel1);
String s1 = "local";
if (p_11262_.m_129523_() != null) {
- s1 = p_11262_.m_129523_().toString();
+ s1 = net.minecraftforge.network.DualStackUtils.getAddressString(p_11262_.m_129523_());
}
f_11188_.info("{}[{}] logged in with entity id {} at ({}, {}, {})", p_11263_.m_7755_().getString(), s1, p_11263_.m_19879_(), p_11263_.m_20185_(), p_11263_.m_20186_(), p_11263_.m_20189_());
LevelData leveldata = serverlevel1.m_6106_();
p_11263_.m_143427_(compoundtag);
ServerGamePacketListenerImpl servergamepacketlistenerimpl = new ServerGamePacketListenerImpl(this.f_11195_, p_11262_, p_11263_);
@@ -160,7 +160,7 @@
this.m_5496_(soundtype.m_56776_(), soundtype.m_56773_() * 0.15F, soundtype.m_56774_());
}
}
@@ -1074,19 +_,22 @@
@@ -1074,31 +_,38 @@
public void m_5844_() {
if (this.m_6069_()) {
@@ -188,6 +188,24 @@
}
void m_20074_() {
Entity entity = this.m_20202_();
+ java.util.function.BooleanSupplier updateFluidHeight = () -> this.m_204031_(FluidTags.f_13131_, 0.014D);
if (entity instanceof Boat boat) {
if (!boat.m_5842_()) {
this.f_19798_ = false;
- return;
+ updateFluidHeight = () -> {
+ this.updateFluidHeightAndDoFluidPushing(state -> this.shouldUpdateFluidWhileBoating(state, boat));
+ return false;
+ };
}
}
- if (this.m_204031_(FluidTags.f_13131_, 0.014D)) {
+ if (updateFluidHeight.getAsBoolean()) {
if (!this.f_19798_ && !this.f_19803_) {
this.m_5841_();
}
@@ -1115,6 +_,7 @@
private void m_20323_() {
this.f_19800_ = this.m_204029_(FluidTags.f_13131_);
@@ -414,19 +432,24 @@
});
}
@@ -2861,9 +_,17 @@
@@ -2861,9 +_,22 @@
this.f_19859_ = this.m_146908_();
}
+ @Deprecated // Forge: Use no parameter version instead, only for vanilla Tags
+ @Deprecated // Forge: Use predicate version instead, only for vanilla Tags
public boolean m_204031_(TagKey<Fluid> p_204032_, double p_204033_) {
+ this.updateFluidHeightAndDoFluidPushing();
+ this.updateFluidHeightAndDoFluidPushing(com.google.common.base.Predicates.alwaysTrue());
+ if(p_204032_ == FluidTags.f_13131_) return this.isInFluidType(net.minecraftforge.common.ForgeMod.WATER_TYPE.get());
+ else if (p_204032_ == FluidTags.f_13132_) return this.isInFluidType(net.minecraftforge.common.ForgeMod.LAVA_TYPE.get());
+ else return false;
+ }
+
+ @Deprecated(forRemoval = true, since = "1.19.4")
+ public void updateFluidHeightAndDoFluidPushing() {
+ this.updateFluidHeightAndDoFluidPushing(com.google.common.base.Predicates.alwaysTrue());
+ }
+
+ public void updateFluidHeightAndDoFluidPushing(Predicate<FluidState> shouldUpdate) {
if (this.m_146899_()) {
- return false;
+ return;
@@ -446,7 +469,7 @@
FluidState fluidstate = this.f_19853_.m_6425_(blockpos$mutableblockpos);
- if (fluidstate.m_205070_(p_204032_)) {
+ net.minecraftforge.fluids.FluidType fluidType = fluidstate.getFluidType();
+ if (!fluidType.isAir()) {
+ if (!fluidType.isAir() && shouldUpdate.test(fluidstate)) {
double d1 = (double)((float)i2 + fluidstate.m_76155_(this.f_19853_, blockpos$mutableblockpos));
if (d1 >= aabb.f_82289_) {
flag1 = true;
@@ -721,7 +721,7 @@
+
+ @Override
+ public <T> net.minecraftforge.common.util.LazyOptional<T> getCapability(net.minecraftforge.common.capabilities.Capability<T> capability, @Nullable Direction facing) {
+ if (this.m_6084_() && capability == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER) {
+ if (capability == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER && this.m_6084_()) {
+ if (facing == null) return handlers[2].cast();
+ else if (facing.m_122434_().m_122478_()) return handlers[0].cast();
+ else if (facing.m_122434_().m_122479_()) return handlers[1].cast();
@@ -38,7 +38,7 @@
+
+ @Override
+ public <T> net.minecraftforge.common.util.LazyOptional<T> getCapability(net.minecraftforge.common.capabilities.Capability<T> capability, @Nullable net.minecraft.core.Direction facing) {
+ if (this.m_6084_() && capability == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER && itemHandler != null)
+ if (capability == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER && itemHandler != null && this.m_6084_())
+ return itemHandler.cast();
+ return super.getCapability(capability, facing);
+ }
@@ -445,7 +445,7 @@
+
+ @Override
+ public <T> net.minecraftforge.common.util.LazyOptional<T> getCapability(net.minecraftforge.common.capabilities.Capability<T> capability, @Nullable Direction facing) {
+ if (this.m_6084_() && capability == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER) {
+ if (capability == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER && this.m_6084_()) {
+ if (facing == null) return playerJoinedHandler.cast();
+ else if (facing.m_122434_().m_122478_()) return playerMainHandler.cast();
+ else if (facing.m_122434_().m_122479_()) return playerEquipmentHandler.cast();
@@ -19,7 +19,7 @@
+
+ @Override
+ public <T> net.minecraftforge.common.util.LazyOptional<T> getCapability(net.minecraftforge.common.capabilities.Capability<T> capability, @Nullable net.minecraft.core.Direction facing) {
+ if (this.m_6084_() && capability == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER)
+ if (capability == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER && this.m_6084_())
+ return itemHandler.cast();
+ return super.getCapability(capability, facing);
+ }
@@ -9,7 +9,7 @@
+
+ @Override
+ public <T> net.minecraftforge.common.util.LazyOptional<T> getCapability(net.minecraftforge.common.capabilities.Capability<T> capability, @Nullable net.minecraft.core.Direction facing) {
+ if (this.m_6084_() && capability == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER)
+ if (capability == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER && this.m_6084_())
+ return itemHandler.cast();
+ return super.getCapability(capability, facing);
+ }
@@ -153,7 +153,7 @@
}
}
@@ -487,5 +_,34 @@
@@ -487,5 +_,33 @@
p_58342_.m_36491_(itemstack);
}
@@ -164,13 +164,12 @@
+
+ @Override
+ public <T> net.minecraftforge.common.util.LazyOptional<T> getCapability(net.minecraftforge.common.capabilities.Capability<T> capability, @Nullable Direction facing) {
+ if (!this.f_58859_ && facing != null && capability == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER) {
+ if (facing == Direction.UP)
+ return handlers[0].cast();
+ else if (facing == Direction.DOWN)
+ return handlers[1].cast();
+ else
+ return handlers[2].cast();
+ if (capability == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER && facing != null && !this.f_58859_) {
+ return switch (facing) {
+ case UP -> handlers[0].cast();
+ case DOWN -> handlers[1].cast();
+ default -> handlers[2].cast();
+ };
+ }
+ return super.getCapability(capability, facing);
+ }
@@ -11,7 +11,7 @@
+ }
+
+ public <T> net.minecraftforge.common.util.LazyOptional<T> getCapability(net.minecraftforge.common.capabilities.Capability<T> cap, @org.jetbrains.annotations.Nullable net.minecraft.core.Direction side) {
+ if (!this.f_58859_ && cap == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER)
+ if (cap == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER && !this.f_58859_)
+ return itemHandler.cast();
+ return super.getCapability(cap, side);
+ }
@@ -51,7 +51,7 @@
}
}
@@ -255,5 +_,34 @@
@@ -255,5 +_,33 @@
protected AbstractContainerMenu m_6555_(int p_58990_, Inventory p_58991_) {
return new BrewingStandMenu(p_58990_, p_58991_, this, this.f_58971_);
@@ -62,13 +62,12 @@
+
+ @Override
+ public <T> net.minecraftforge.common.util.LazyOptional<T> getCapability(net.minecraftforge.common.capabilities.Capability<T> capability, @Nullable Direction facing) {
+ if (!this.f_58859_ && facing != null && capability == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER) {
+ if (facing == Direction.UP)
+ return handlers[0].cast();
+ else if (facing == Direction.DOWN)
+ return handlers[1].cast();
+ else
+ return handlers[2].cast();
+ if (capability == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER && facing != null && !this.f_58859_) {
+ return switch (facing) {
+ case UP -> handlers[0].cast();
+ case DOWN -> handlers[1].cast();
+ default -> handlers[2].cast();
+ };
+ }
+ return super.getCapability(capability, facing);
+ }
@@ -17,7 +17,7 @@
+
+ @Override
+ public <T> net.minecraftforge.common.util.LazyOptional<T> getCapability(net.minecraftforge.common.capabilities.Capability<T> cap, Direction side) {
+ if (!this.f_58859_ && cap == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER) {
+ if (cap == net.minecraftforge.common.capabilities.ForgeCapabilities.ITEM_HANDLER && !this.f_58859_) {
+ if (this.chestHandler == null)
+ this.chestHandler = net.minecraftforge.common.util.LazyOptional.of(this::createHandler);
+ return this.chestHandler.cast();
@@ -0,0 +1,11 @@
--- a/net/minecraft/world/level/levelgen/feature/treedecorators/AlterGroundDecorator.java
+++ b/net/minecraft/world/level/levelgen/feature/treedecorators/AlterGroundDecorator.java
@@ -72,7 +_,7 @@
for(int i = 2; i >= -3; --i) {
BlockPos blockpos = p_225975_.m_6630_(i);
if (Feature.m_65788_(p_225974_.m_226058_(), blockpos)) {
- p_225974_.m_226061_(blockpos, this.f_69303_.m_213972_(p_225974_.m_226067_(), p_225975_));
+ p_225974_.m_226061_(blockpos, net.minecraftforge.event.ForgeEventFactory.alterGround(p_225974_.m_226058_(), p_225974_.m_226067_(), blockpos, this.f_69303_.m_213972_(p_225974_.m_226067_(), p_225975_)));
break;
}
+14
View File
@@ -6,6 +6,20 @@ pluginManagement {
}
}
buildscript {
dependencies {
classpath('com.google.code.gson:gson') {
version {
strictly '2.10.1'
}
}
}
}
plugins {
id 'org.gradle.toolchains.foojay-resolver-convention' version '0.7.0'
}
rootProject.name = 'ForgeRoot'
include 'fmlloader'
+1 -1
View File
@@ -1,7 +1,7 @@
{
"pack": {
"description": {
"text": "examplemod resources"
"text": "${mod_id} resources"
},
"forge:server_data_pack_format": 12,
"pack_format": 13
@@ -0,0 +1,12 @@
{
"textures": [
"minecraft:generic_7",
"minecraft:generic_6",
"minecraft:generic_5",
"minecraft:generic_4",
"minecraft:generic_3",
"minecraft:generic_2",
"minecraft:generic_1",
"minecraft:generic_0"
]
}
@@ -0,0 +1,5 @@
{
"textures": [
"minecraft:drip_hang"
]
}
@@ -0,0 +1,30 @@
{
"textures": [
"minecraft:sga_a",
"minecraft:sga_b",
"minecraft:sga_c",
"minecraft:sga_d",
"minecraft:sga_e",
"minecraft:sga_f",
"minecraft:sga_g",
"minecraft:sga_h",
"minecraft:sga_i",
"minecraft:sga_j",
"minecraft:sga_k",
"minecraft:sga_l",
"minecraft:sga_m",
"minecraft:sga_n",
"minecraft:sga_o",
"minecraft:sga_p",
"minecraft:sga_q",
"minecraft:sga_r",
"minecraft:sga_s",
"minecraft:sga_t",
"minecraft:sga_u",
"minecraft:sga_v",
"minecraft:sga_w",
"minecraft:sga_x",
"minecraft:sga_y",
"minecraft:sga_z"
]
}
@@ -0,0 +1,8 @@
{
"textures": [
"minecraft:splash_0",
"minecraft:splash_1",
"minecraft:splash_2",
"minecraft:splash_3"
]
}
@@ -13,10 +13,30 @@ import net.minecraftforge.forgespi.language.IModInfo;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.Function;
public class ConfigScreenHandler
{
public record ConfigScreenFactory(BiFunction<Minecraft, Screen, Screen> screenFunction) implements IExtensionPoint<ConfigScreenFactory> {}
/**
* @param screenFunction A function that takes the {@link Minecraft} client instance and the mods screen as
* arguments and returns your config screen to show when the player clicks the config button
* for your mod on the mods screen.
* <p>You should call {@link Minecraft#setScreen(Screen)} with the provided client instance
* and mods screen for the action of your close button.</p>
*/
public record ConfigScreenFactory(BiFunction<Minecraft, Screen, Screen> screenFunction) implements IExtensionPoint<ConfigScreenFactory> {
/**
* @param screenFunction A function that takes the mods screen as an argument and returns your config screen to
* show when the player clicks the config button for your mod on the mods screen.
* <p>You should call {@link Minecraft#setScreen(Screen)} with the provided mods screen
* for the action of your close button, using {@link Screen#minecraft} to get the client
* instance.</p>
*/
public ConfigScreenFactory(Function<Screen, Screen> screenFunction) {
this((mcClient, modsScreen) -> screenFunction.apply(modsScreen));
}
}
public static Optional<BiFunction<Minecraft, Screen, Screen>> getScreenFactoryFor(IModInfo selectedMod)
{
return ModList.get().getModContainerById(selectedMod.getModId()).
@@ -67,15 +67,15 @@ public interface IForgeDimensionSpecialEffects
* Allows for manipulating the coloring of the lightmap texture.
* Will be called for each 16*16 combination of sky/block light values.
*
* @param level The current level (client-side).
* @param partialTicks Progress between ticks.
* @param skyDarken Current darkness of the sky.
* @param skyLight Sky light brightness factor.
* @param blockLight Block light brightness factor.
* @param pixelX X-coordinate of the lightmap texture.
* @param pixelY Y-coordinate of the lightmap texture.
* @param colors The color values that will be used: [r, g, b].
* @param level The current level (client-side).
* @param partialTicks Progress between ticks.
* @param skyDarken Current darkness of the sky (can be used to calculate sky light).
* @param blockLightRedFlicker Block light flicker factor (red color) (can be used to calculate block light).
* @param skyLight Sky light brightness (accounting for sky darkness).
* @param pixelX X-coordinate of the lightmap texture (block).
* @param pixelY Y-coordinate of the lightmap texture (sky).
* @param colors The color values that will be used: [r, g, b].
* @see LightTexture#updateLightTexture(float)
*/
default void adjustLightmapColors(ClientLevel level, float partialTicks, float skyDarken, float skyLight, float blockLight, int pixelX, int pixelY, Vector3f colors) {}
default void adjustLightmapColors(ClientLevel level, float partialTicks, float skyDarken, float blockLightRedFlicker, float skyLight, int pixelX, int pixelY, Vector3f colors) {}
}
@@ -5,6 +5,7 @@
package net.minecraftforge.client.extensions.common;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.particle.ParticleEngine;
import net.minecraft.core.BlockPos;
import net.minecraft.world.effect.MobEffects;
@@ -14,6 +15,7 @@ import net.minecraft.world.item.enchantment.EnchantmentHelper;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.LevelReader;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.Material;
import net.minecraft.world.phys.HitResult;
@@ -111,4 +113,17 @@ public interface IClientBlockExtensions
}
return originalColor;
}
/**
* Returns true if the breaking particles created from the {@link BlockState} passed should be tinted with biome colors.
*
* @param state The state of this block
* @param level The level the particles are spawning in
* @param pos The position of the block
* @return {@code true} if the particles should be tinted.
*/
default boolean areBreakingParticlesTinted(BlockState state, ClientLevel level, BlockPos pos)
{
return !state.is(Blocks.GRASS_BLOCK);
}
}
@@ -496,6 +496,13 @@ public class ForgeGui extends Gui
}
}
@Override
public void clearCache()
{
super.clearCache();
this.debugOverlay.clearChunkCache();
}
protected void renderRecordOverlay(int width, int height, float partialTick, PoseStack pStack)
{
if (overlayMessageTime > 0)
@@ -27,6 +27,7 @@ public class KeyMappingLookup
}
}
@Deprecated(forRemoval = true)
@Nullable
public KeyMapping get(InputConstants.Key keyCode)
{
@@ -59,6 +60,16 @@ public class KeyMappingLookup
return null;
}
/**
* Returns all active keys associated with the given key code and the active
* modifiers and conflict context.
*
* This could probably be renamed to something like getActiveMappings, but
* that would be a breaking change.
*
* @param keyCode the key being pressed
* @return the list of key mappings
*/
public List<KeyMapping> getAll(InputConstants.Key keyCode)
{
List<KeyMapping> matchingBindings = new ArrayList<KeyMapping>();
@@ -67,7 +78,11 @@ public class KeyMappingLookup
Collection<KeyMapping> bindings = bindingsMap.get(keyCode);
if (bindings != null)
{
matchingBindings.addAll(bindings);
for (KeyMapping binding : bindings)
{
if (binding.isConflictContextAndModifierActive())
matchingBindings.add(binding);
}
}
}
return matchingBindings;
@@ -30,6 +30,8 @@ public class ForgeConfig {
public final ConfigValue<String> permissionHandler;
public final BooleanValue advertiseDedicatedServerToLan;
Server(ForgeConfigSpec.Builder builder) {
builder.comment("Server configuration settings")
.push("server");
@@ -69,6 +71,11 @@ public class ForgeConfig {
.translation("forge.configgui.permissionHandler")
.define("permissionHandler", "forge:default_handler");
advertiseDedicatedServerToLan = builder
.comment("Set this to true to enable advertising the dedicated server to local LAN clients so that it shows up in the Multiplayer screen automatically.")
.translation("forge.configgui.advertiseDedicatedServerToLan")
.define("advertiseDedicatedServerToLan", true);
builder.pop();
}
}
@@ -123,6 +130,7 @@ public class ForgeConfig {
public final BooleanValue useCombinedDepthStencilAttachment;
@Deprecated(since = "1.20.1", forRemoval = true) // Config option ignored.
public final BooleanValue compressLanIPv6Addresses;
Client(ForgeConfigSpec.Builder builder) {
@@ -152,7 +160,7 @@ public class ForgeConfig {
.define("useCombinedDepthStencilAttachment", false);
compressLanIPv6Addresses = builder
.comment("When enabled, Forge will convert discovered 'Open to LAN' IPv6 addresses to their more compact, compressed representation")
.comment("[DEPRECATED] [NOW IN COMMON CONFIG] When enabled, Forge will convert discovered 'Open to LAN' IPv6 addresses to their more compact, compressed representation")
.translation("forge.configgui.compressLanIPv6Addresses")
.define("compressLanIPv6Addresses", true);
@@ -24,6 +24,7 @@ import java.util.Objects;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import net.minecraftforge.fml.config.IConfigSpec;
@@ -53,15 +54,16 @@ import org.jetbrains.annotations.Nullable;
*/
public class ForgeConfigSpec extends UnmodifiableConfigWrapper<UnmodifiableConfig> implements IConfigSpec<ForgeConfigSpec>//TODO: Remove extends and pipe everything through getSpec/getValues?
{
private Map<List<String>, String> levelComments;
private Map<List<String>, String> levelTranslationKeys;
private final Map<List<String>, String> levelComments;
private final Map<List<String>, String> levelTranslationKeys;
private UnmodifiableConfig values;
private final UnmodifiableConfig values;
private Config childConfig;
private boolean isCorrecting = false;
private static final Logger LOGGER = LogManager.getLogger();
private static final Pattern WINDOWS_NEWLINE = Pattern.compile("\r\n");
private ForgeConfigSpec(UnmodifiableConfig storage, UnmodifiableConfig values, Map<List<String>, String> levelComments, Map<List<String>, String> levelTranslationKeys) {
super(storage);
@@ -123,11 +125,9 @@ public class ForgeConfigSpec extends UnmodifiableConfigWrapper<UnmodifiableConfi
private void resetCaches(final Iterable<Object> configValues) {
configValues.forEach(value -> {
if (value instanceof ConfigValue) {
final ConfigValue<?> configValue = (ConfigValue<?>) value;
if (value instanceof ConfigValue<?> configValue) {
configValue.clearCache();
} else if (value instanceof Config) {
final Config innerConfig = (Config) value;
} else if (value instanceof Config innerConfig) {
this.resetCaches(innerConfig.valueMap().values());
}
});
@@ -268,10 +268,10 @@ public class ForgeConfigSpec extends UnmodifiableConfigWrapper<UnmodifiableConfi
{
if (obj1 instanceof String string1 && obj2 instanceof String string2)
{
if (string1.length() > 0 && string2.length() > 0)
if (!string1.isEmpty() && !string2.isEmpty())
{
return string1.replaceAll("\r\n", "\n")
.equals(string2.replaceAll("\r\n", "\n"));
return WINDOWS_NEWLINE.matcher(string1).replaceAll("\n")
.equals(WINDOWS_NEWLINE.matcher(string2).replaceAll("\n"));
}
}
@@ -283,10 +283,10 @@ public class ForgeConfigSpec extends UnmodifiableConfigWrapper<UnmodifiableConfi
{
private final Config storage = Config.of(LinkedHashMap::new, InMemoryFormat.withUniversalSupport()); // Use LinkedHashMap for consistent ordering
private BuilderContext context = new BuilderContext();
private Map<List<String>, String> levelComments = new HashMap<>();
private Map<List<String>, String> levelTranslationKeys = new HashMap<>();
private List<String> currentPath = new ArrayList<>();
private List<ConfigValue<?>> values = new ArrayList<>();
private final Map<List<String>, String> levelComments = new HashMap<>();
private final Map<List<String>, String> levelTranslationKeys = new HashMap<>();
private final List<String> currentPath = new ArrayList<>();
private final List<ConfigValue<?>> values = new ArrayList<>();
//Object
public <T> ConfigValue<T> define(String path, T defaultValue) {
@@ -350,7 +350,7 @@ public class ForgeConfigSpec extends UnmodifiableConfigWrapper<UnmodifiableConfi
return defineInList(path, () -> defaultValue, acceptableValues);
}
public <T> ConfigValue<T> defineInList(List<String> path, Supplier<T> defaultSupplier, Collection<? extends T> acceptableValues) {
return define(path, defaultSupplier, acceptableValues::contains);
return define(path, defaultSupplier, o -> o != null && acceptableValues.contains(o));
}
public <T> ConfigValue<List<? extends T>> defineList(String path, List<? extends T> defaultValue, Predicate<Object> elementValidator) {
return defineList(split(path), defaultValue, elementValidator);
@@ -370,7 +370,7 @@ public class ForgeConfigSpec extends UnmodifiableConfigWrapper<UnmodifiableConfi
LOGGER.debug(CORE, "List on key {} is deemed to need correction. It is null, not a list, or an empty list. Modders, consider defineListAllowEmpty?", path.get(path.size() - 1));
return getDefault();
}
List<?> list = Lists.newArrayList((List<?>) value);
List<?> list = new ArrayList<>((List<?>) value);
list.removeIf(elementValidator.negate());
if (list.isEmpty()) {
LOGGER.debug(CORE, "List on key {} is deemed to need correction. It failed validation.", path.get(path.size() - 1));
@@ -390,7 +390,7 @@ public class ForgeConfigSpec extends UnmodifiableConfigWrapper<UnmodifiableConfi
LOGGER.debug(CORE, "List on key {} is deemed to need correction, as it is null or not a list.", path.get(path.size() - 1));
return getDefault();
}
List<?> list = Lists.newArrayList((List<?>) value);
List<?> list = new ArrayList<>((List<?>) value);
list.removeIf(elementValidator.negate());
if (list.isEmpty()) {
LOGGER.debug(CORE, "List on key {} is deemed to need correction. It failed validation.", path.get(path.size() - 1));
@@ -691,7 +691,7 @@ public class ForgeConfigSpec extends UnmodifiableConfigWrapper<UnmodifiableConfi
}
@SuppressWarnings("unused")
private static class Range<V extends Comparable<? super V>> implements Predicate<Object>
public static class Range<V extends Comparable<? super V>> implements Predicate<Object>
{
private final Class<? extends V> clazz;
private final V min;
@@ -821,7 +821,7 @@ public class ForgeConfigSpec extends UnmodifiableConfigWrapper<UnmodifiableConfi
public List<String> getPath()
{
return Lists.newArrayList(path);
return new ArrayList<>(path);
}
/**
@@ -8,6 +8,7 @@ package net.minecraftforge.common;
import net.minecraft.world.level.block.CropBlock;
import net.minecraft.world.level.block.FlowerBlock;
import net.minecraft.world.level.block.SaplingBlock;
import net.minecraft.world.level.block.AttachedStemBlock;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.core.BlockPos;
@@ -17,6 +18,7 @@ public interface IPlantable
{
default PlantType getPlantType(BlockGetter level, BlockPos pos) {
if (this instanceof CropBlock) return PlantType.CROP;
if (this instanceof AttachedStemBlock) return PlantType.CROP;
if (this instanceof SaplingBlock) return PlantType.PLAINS;
if (this instanceof FlowerBlock) return PlantType.PLAINS;
if (this == Blocks.DEAD_BUSH) return PlantType.DESERT;
@@ -5,17 +5,25 @@
package net.minecraftforge.common;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screens.Screen;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.ClientCommandHandler;
import net.minecraftforge.client.ConfigScreenHandler;
import net.minecraftforge.eventbus.api.BusBuilder;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.ModLoadingContext;
import net.minecraftforge.fml.loading.FMLEnvironment;
import net.minecraftforge.network.DualStackUtils;
import net.minecraftforge.versions.forge.ForgeVersion;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import java.util.function.BiFunction;
import java.util.function.Function;
public class MinecraftForge
{
/**
@@ -42,8 +50,39 @@ public class MinecraftForge
UsernameCache.load();
TierSortingRegistry.init();
if (FMLEnvironment.dist == Dist.CLIENT) ClientCommandHandler.init();
DualStackUtils.initialise();
}
/**
* Register a config screen for the active mod container.
* @param screenFunction A function that takes the mods screen as an argument and returns your config screen to
* show when the player clicks the config button for your mod on the mods screen.
* <p>You should call {@link Minecraft#setScreen(Screen)} with the provided mods screen for the
* action of your close button, using {@link Screen#minecraft} to get the client instance.</p>
* @see ModLoadingContext#registerExtensionPoint(Class, Supplier)
* @see ModLoadingContext#registerConfig(ModConfig.Type, IConfigSpec)
*/
public static void registerConfigScreen(Function<Screen, Screen> screenFunction) {
registerConfigScreen((mcClient, modsScreen) -> screenFunction.apply(modsScreen));
}
/**
* Register a config screen for the active mod container.
* @param screenFunction A function that takes the {@link Minecraft} client instance and the mods screen as
* arguments and returns your config screen to show when the player clicks the config button
* for your mod on the mods screen.
* <p>You should call {@link Minecraft#setScreen(Screen)} with the provided client instance
* and mods screen for the action of your close button.</p>
* @see ModLoadingContext#registerExtensionPoint(Class, Supplier)
* @see ModLoadingContext#registerConfig(ModConfig.Type, IConfigSpec)
*/
public static void registerConfigScreen(BiFunction<Minecraft, Screen, Screen> screenFunction) {
ModLoadingContext.get().registerExtensionPoint(
ConfigScreenHandler.ConfigScreenFactory.class,
() -> new ConfigScreenHandler.ConfigScreenFactory(screenFunction)
);
}
/*
public static void preloadCrashClasses(ASMDataTable table, String modID, Set<String> classes)
{
@@ -7,12 +7,11 @@ package net.minecraftforge.common.capabilities;
import javax.annotation.ParametersAreNonnullByDefault;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import com.google.common.collect.Lists;
import net.minecraft.MethodsReturnNonnullByDefault;
import net.minecraft.nbt.Tag;
import net.minecraft.nbt.CompoundTag;
@@ -36,9 +35,9 @@ import org.jetbrains.annotations.Nullable;
@MethodsReturnNonnullByDefault
public final class CapabilityDispatcher implements INBTSerializable<CompoundTag>, ICapabilityProvider
{
private ICapabilityProvider[] caps;
private INBTSerializable<Tag>[] writers;
private String[] names;
private final ICapabilityProvider[] caps;
private final INBTSerializable<Tag>[] writers;
private final String[] names;
private final List<Runnable> listeners;
public CapabilityDispatcher(Map<ResourceLocation, ICapabilityProvider> list, List<Runnable> listeners)
@@ -49,9 +48,9 @@ public final class CapabilityDispatcher implements INBTSerializable<CompoundTag>
@SuppressWarnings("unchecked")
public CapabilityDispatcher(Map<ResourceLocation, ICapabilityProvider> list, List<Runnable> listeners, @Nullable ICapabilityProvider parent)
{
List<ICapabilityProvider> lstCaps = Lists.newArrayList();
List<INBTSerializable<Tag>> lstWriters = Lists.newArrayList();
List<String> lstNames = Lists.newArrayList();
List<ICapabilityProvider> lstCaps = new ArrayList<>();
List<INBTSerializable<Tag>> lstWriters = new ArrayList<>();
List<String> lstNames = new ArrayList<>();
this.listeners = listeners;
if (parent != null) // Parents go first!
@@ -0,0 +1,238 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common.data;
import com.google.common.base.Preconditions;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import net.minecraft.Util;
import net.minecraft.client.particle.ParticleEngine;
import net.minecraft.client.particle.ParticleProvider;
import net.minecraft.core.particles.ParticleType;
import net.minecraft.data.CachedOutput;
import net.minecraft.data.DataProvider;
import net.minecraft.data.PackOutput;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.packs.PackType;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.registries.ForgeRegistries;
import org.jetbrains.annotations.VisibleForTesting;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Stream;
/**
* A data provider for {@link net.minecraft.client.particle.ParticleDescription}s.
*
* <p>To use this provider, extend this class and implement {@link #addDescriptions()}.
* Then, register an instance using {@link net.minecraft.data.DataGenerator#addProvider(boolean, Factory)}
* via the {@link net.minecraftforge.data.event.GatherDataEvent} on the {@linkplain FMLJavaModLoadingContext#getModEventBus() mod event bus}.
*
* <p>A description can be added to a {@link ParticleType} which uses a {@linkplain #sprite(ParticleType, ResourceLocation) sprite}
* or {@linkplain #spriteSet(ParticleType, Iterable) sprite set}.
*
* <pre>{@code
* @Override
* protected void addDescriptions() {
* // Single sprite
* this.sprite(ParticleTypes.DRIPPING_LAVA, new ResourceLocation("drip_hang"));
*
* // Multiple sprites
* this.spriteSet(ParticleTypes.CLOUD, new ResourceLocation("generic"), 8, true);
* }
* }</pre>
*
* <p>A particle description holds a list of textures used when rendering the
* particle to the screen. All registered particle descriptions are stitched
* together into a texture atlas called {@link net.minecraft.client.renderer.texture.TextureAtlas#LOCATION_PARTICLES}.
* A {@link ParticleType} whose particle uses the texture atlas, typically via
* the {@link net.minecraft.client.particle.ParticleRenderType}, can then reference
* the necessary texture during rendering.
*
* <p>Particles with a particle description must have their particle providers
* attached to a {@link ParticleType} as a {@linkplain net.minecraftforge.client.event.RegisterParticleProvidersEvent#registerSprite(ParticleType, ParticleProvider.Sprite) sprite}
* or {@linkplain net.minecraftforge.client.event.RegisterParticleProvidersEvent#registerSpriteSet(ParticleType, ParticleEngine.SpriteParticleRegistration) sprite set}
* consumer.
*
* @see DataProvider
* @see net.minecraft.client.particle.ParticleDescription
*/
public abstract class ParticleDescriptionProvider implements DataProvider {
private final PackOutput.PathProvider particlesPath;
@VisibleForTesting
protected final ExistingFileHelper fileHelper;
@VisibleForTesting
protected final Map<ResourceLocation, List<String>> descriptions;
/**
* Creates an instance of the data provider.
*
* @param output the expected root directory the data generator outputs to
* @param fileHelper the helper used to validate a texture's existence
*/
protected ParticleDescriptionProvider(PackOutput output, ExistingFileHelper fileHelper) {
this.particlesPath = output.createPathProvider(PackOutput.Target.RESOURCE_PACK, "particles");
this.fileHelper = fileHelper;
this.descriptions = new HashMap<>();
}
/**
* Registers the particle descriptions generated by {@link #sprite(ParticleType, ResourceLocation)}
* or one of the {@link #spriteSet(ParticleType, Iterable) sprite set methods}.
*/
protected abstract void addDescriptions();
/**
* Creates a new particle description that contains a single texture for the
* associated {@link ParticleType}.
*
* <p>Particle types with this description should be attached to a particle provider
* via {@link net.minecraftforge.client.event.RegisterParticleProvidersEvent#registerSprite(ParticleType, ParticleProvider.Sprite)}.
*
* @param type the particle type the textures are applied
* for
* @param texture the texture to render for the particle type
* @throws NullPointerException if the particle type is not registered
* @throws IllegalArgumentException if a texture does not have an associated PNG
* file, or the particle type has already been
* provided
*/
protected void sprite(ParticleType<?> type, ResourceLocation texture) {
this.spriteSet(type, texture);
}
/**
* Creates a new particle description that contains multiple textures for the
* associated {@link ParticleType}. The textures are generated from a common
* name and appended with a number representing the state of the animation.
*
* <pre>{@code
* minecraft:generic_0
* minecraft:generic_1
* minecraft:generic_2
* // ...
* }</pre>
*
* <p>Particle types with this description should be attached to a particle provider
* via {@link net.minecraftforge.client.event.RegisterParticleProvidersEvent#registerSpriteSet(ParticleType, ParticleEngine.SpriteParticleRegistration)}.
*
* @param type the particle type the textures are applied
* for
* @param baseName the common name of all the textures
* @param numOfTextures the number of textures within the set
* @param reverse when {@code true}, the textures will be
* listed in descending order
* @throws NullPointerException if the particle type is not registered
* @throws IllegalArgumentException if a texture does not have an associated PNG
* file, or the particle type has already been
* provided
*/
protected void spriteSet(ParticleType<?> type, ResourceLocation baseName, int numOfTextures, boolean reverse) {
Preconditions.checkArgument(numOfTextures > 0, "The number of textures to generate must be positive");
this.spriteSet(type, () -> new Iterator<>() {
private int counter = 0;
@Override
public boolean hasNext() {
return this.counter < numOfTextures;
}
@Override
public ResourceLocation next() {
var texture = baseName.withSuffix("_" + (reverse ? numOfTextures - this.counter - 1 : this.counter));
this.counter++;
return texture;
}
});
}
/**
* Creates a new particle description that contains multiple textures for the
* associated {@link ParticleType}. The textures are passed as varargs with
* at least one texture present.
*
* <p>Particle types with this description should be attached to a particle provider
* via {@link net.minecraftforge.client.event.RegisterParticleProvidersEvent#registerSpriteSet(ParticleType, ParticleEngine.SpriteParticleRegistration)}.
*
* @param type the particle type the textures are applied
* for
* @param texture the first texture in the description
* @param textures a list of subsequent textures to render for
* the particle type
* @throws NullPointerException if the particle type is not registered
* @throws IllegalArgumentException if a texture does not have an associated PNG
* file, or the particle type has already been
* provided
*/
protected void spriteSet(ParticleType<?> type, ResourceLocation texture, ResourceLocation... textures) {
this.spriteSet(type, Stream.concat(Stream.of(texture), Arrays.stream(textures))::iterator);
}
/**
* Creates a new particle description that contains multiple textures for the
* associated {@link ParticleType}. The textures are passed as an iterable.
*
* <p>Particle types with this description should be attached to a particle provider
* via {@link net.minecraftforge.client.event.RegisterParticleProvidersEvent#registerSpriteSet(ParticleType, ParticleEngine.SpriteParticleRegistration)}.
*
* @param type the particle type the textures are applied
* for
* @param textures a list of textures to render for the
* particle type
* @throws NullPointerException if the particle type is not registered
* @throws IllegalArgumentException if there are no textures provided, a texture
* does not have an associated PNG file, or
* the particle type has already been provided
*/
protected void spriteSet(ParticleType<?> type, Iterable<ResourceLocation> textures) {
// Make sure particle type is registered
var particle = Preconditions.checkNotNull(ForgeRegistries.PARTICLE_TYPES.getKey(type), "The particle type is not registered");
// Validate textures
List<String> desc = new ArrayList<>();
for (var texture : textures) {
Preconditions.checkArgument(this.fileHelper.exists(texture, PackType.CLIENT_RESOURCES, ".png", "textures/particle"),
"Texture '%s' does not exist in any known resource pack", texture);
desc.add(texture.toString());
}
Preconditions.checkArgument(desc.size() > 0, "The particle type '%s' must have one texture", particle);
// Insert into map
if (this.descriptions.putIfAbsent(particle, desc) != null) {
throw new IllegalArgumentException(String.format("The particle type '%s' already has a description associated with it", particle));
}
}
@Override
public CompletableFuture<?> run(CachedOutput cache) {
this.addDescriptions();
return CompletableFuture.allOf(
this.descriptions.entrySet().stream().map(entry -> {
// Map entries to the description format
var textures = new JsonArray();
entry.getValue().forEach(textures::add);
return DataProvider.saveStable(cache,
Util.make(new JsonObject(), obj -> obj.add("textures", textures)),
this.particlesPath.json(entry.getKey())
);
}).toArray(CompletableFuture[]::new)
);
}
@Override
public String getName() {
return "Particle Descriptions";
}
}
@@ -5,6 +5,7 @@
package net.minecraftforge.common.extensions;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.vehicle.Boat;
import net.minecraft.world.level.material.FluidState;
import net.minecraftforge.fluids.FluidType;
@@ -37,4 +38,17 @@ public interface IForgeBoat
{
return type.supportsBoating(self());
}
/**
* When {@code false}, the fluid will no longer update its height value while
* within a boat while it is not within a fluid ({@link Boat#isUnderWater()}.
*
* @param state the state of the fluid the rider is within
* @param rider the rider of the boat
* @return {@code true} if the fluid height should be updated, {@code false} otherwise
*/
default boolean shouldUpdateFluidWhileRiding(FluidState state, Entity rider)
{
return state.shouldUpdateWhileBoating(self(), rider);
}
}
@@ -13,6 +13,7 @@ import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.ai.attributes.AttributeInstance;
import net.minecraft.world.entity.boss.enderdragon.EnderDragon;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.vehicle.Boat;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.entity.Entity;
@@ -424,4 +425,17 @@ public interface IForgeEntity extends ICapabilitySerializable<CompoundTag>
{
return false;
}
/**
* When {@code false}, the fluid will no longer update its height value while
* within a boat while it is not within a fluid ({@link Boat#isUnderWater()}.
*
* @param state the state of the fluid the rider is within
* @param boat the boat the rider is within that is not inside a fluid
* @return {@code true} if the fluid height should be updated, {@code false} otherwise
*/
default boolean shouldUpdateFluidWhileBoating(FluidState state, Boat boat)
{
return boat.shouldUpdateFluidWhileRiding(state, self());
}
}
@@ -6,6 +6,7 @@
package net.minecraftforge.common.extensions;
import net.minecraft.core.BlockPos;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.vehicle.Boat;
@@ -94,6 +95,20 @@ public interface IForgeFluid
return getFluidType().supportsBoating(state, boat);
}
/**
* When {@code false}, the fluid will no longer update its height value while
* within a boat while it is not within a fluid ({@link Boat#isUnderWater()}.
*
* @param state the state of the fluid the rider is within
* @param boat the boat the rider is within that is not inside a fluid
* @param rider the rider of the boat
* @return {@code true} if the fluid height should be updated, {@code false} otherwise
*/
default boolean shouldUpdateWhileBoating(FluidState state, Boat boat, Entity rider)
{
return getFluidType().shouldUpdateWhileBoating(state, boat, rider);
}
/**
* Gets the path type of this fluid when an entity is pathfinding. When
* {@code null}, uses vanilla behavior.
@@ -6,6 +6,7 @@
package net.minecraftforge.common.extensions;
import net.minecraft.core.BlockPos;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.vehicle.Boat;
@@ -88,6 +89,19 @@ public interface IForgeFluidState
return self().getType().supportsBoating(self(), boat);
}
/**
* When {@code false}, the fluid will no longer update its height value while
* within a boat while it is not within a fluid ({@link Boat#isUnderWater()}.
*
* @param boat the boat the rider is within that is not inside a fluid
* @param rider the rider of the boat
* @return {@code true} if the fluid height should be updated, {@code false} otherwise
*/
default boolean shouldUpdateWhileBoating(Boat boat, Entity rider)
{
return self().getType().shouldUpdateWhileBoating(self(), boat, rider);
}
/**
* Gets the path type of this fluid when an entity is pathfinding. When
* {@code null}, uses vanilla behavior.
@@ -48,7 +48,7 @@ public class LazyOptional<T>
// non-null and contains non-null value -> resolved
// non-null and contains null -> resolved, but supplier returned null (contract violation)
private Mutable<T> resolved;
private Set<NonNullConsumer<LazyOptional<T>>> listeners = new HashSet<>();
private final Set<NonNullConsumer<LazyOptional<T>>> listeners = new HashSet<>();
private boolean isValid = true;
private static final @NotNull LazyOptional<Void> EMPTY = new LazyOptional<>(null);
@@ -0,0 +1,58 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.energy;
/**
* Implementation of {@link IEnergyStorage} that cannot store, receive, or provide energy.
* Use the {@link #INSTANCE}, don't instantiate. Example:
* <pre>{@code
* ItemStack stack = ...;
* IEnergyStorage storage = stack.getCapability(ForgeCapabilities.ENERGY).orElse(EmptyEnergyStorage.INSTANCE);
* // Use storage without checking whether it's present.
* }</pre>
*/
public class EmptyEnergyStorage implements IEnergyStorage
{
public static final EmptyEnergyStorage INSTANCE = new EmptyEnergyStorage();
protected EmptyEnergyStorage() {}
@Override
public int receiveEnergy(int maxReceive, boolean simulate)
{
return 0;
}
@Override
public int extractEnergy(int maxExtract, boolean simulate)
{
return 0;
}
@Override
public int getEnergyStored()
{
return 0;
}
@Override
public int getMaxEnergyStored()
{
return 0;
}
@Override
public boolean canExtract()
{
return false;
}
@Override
public boolean canReceive()
{
return false;
}
}
@@ -29,6 +29,7 @@ import net.minecraft.world.DifficultyInstance;
import net.minecraft.world.entity.MobCategory;
import net.minecraft.world.entity.projectile.Projectile;
import net.minecraft.world.entity.projectile.ThrownEnderpearl;
import net.minecraft.world.level.LevelSimulatedReader;
import net.minecraft.world.level.biome.MobSpawnSettings;
import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.world.level.levelgen.feature.ConfiguredFeature;
@@ -125,6 +126,7 @@ import net.minecraftforge.event.entity.player.PlayerWakeUpEvent;
import net.minecraftforge.event.entity.player.SleepingLocationCheckEvent;
import net.minecraftforge.event.entity.player.SleepingTimeCheckEvent;
import net.minecraftforge.event.furnace.FurnaceFuelBurnTimeEvent;
import net.minecraftforge.event.level.AlterGroundEvent;
import net.minecraftforge.event.level.BlockEvent;
import net.minecraftforge.event.level.BlockEvent.BlockToolModificationEvent;
import net.minecraftforge.event.level.BlockEvent.CreateFluidSourceEvent;
@@ -567,7 +569,7 @@ public class ForgeEventFactory
private static CapabilityDispatcher gatherCapabilities(AttachCapabilitiesEvent<?> event, @Nullable ICapabilityProvider parent)
{
MinecraftForge.EVENT_BUS.post(event);
return event.getCapabilities().size() > 0 || parent != null ? new CapabilityDispatcher(event.getCapabilities(), event.getListeners(), parent) : null;
return !event.getCapabilities().isEmpty() || parent != null ? new CapabilityDispatcher(event.getCapabilities(), event.getListeners(), parent) : null;
}
public static boolean fireSleepingLocationCheck(LivingEntity player, BlockPos sleepingLocation)
@@ -680,6 +682,13 @@ public class ForgeEventFactory
return event;
}
public static BlockState alterGround(LevelSimulatedReader level, RandomSource random, BlockPos pos, BlockState altered)
{
AlterGroundEvent event = new AlterGroundEvent(level, random, pos, altered);
MinecraftForge.EVENT_BUS.post(event);
return event.getNewAlteredState();
}
public static void fireChunkTicketLevelUpdated(ServerLevel level, long chunkPos, int oldTicketLevel, int newTicketLevel, @Nullable ChunkHolder chunkHolder)
{
if (oldTicketLevel != newTicketLevel)
@@ -0,0 +1,79 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.event.level;
import net.minecraft.core.BlockPos;
import net.minecraft.util.RandomSource;
import net.minecraft.world.level.LevelSimulatedReader;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.levelgen.feature.treedecorators.TreeDecorator;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.eventbus.api.Cancelable;
import net.minecraftforge.eventbus.api.Event;
import org.jetbrains.annotations.ApiStatus;
/**
* This event is fired when {@link net.minecraft.world.level.levelgen.feature.treedecorators.AlterGroundDecorator#placeBlockAt(TreeDecorator.Context, BlockPos)}
* attempts to alter a ground block when generating a feature. An example of this would be large spruce trees converting grass blocks into podzol.
* <p>
* This event is not {@linkplain Cancelable cancellable}.
* <p>
* This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus}
* only on the {@linkplain net.minecraftforge.fml.LogicalSide#SERVER logical server}.
*/
public class AlterGroundEvent extends Event {
private final LevelSimulatedReader level;
private final RandomSource random;
private final BlockPos pos;
private final BlockState originalAltered;
private BlockState newAltered;
@ApiStatus.Internal
public AlterGroundEvent(LevelSimulatedReader level, RandomSource random, BlockPos pos, BlockState altered) {
super();
this.level = level;
this.random = random;
this.pos = pos;
this.originalAltered = altered;
this.newAltered = altered;
}
public LevelSimulatedReader getLevel() {
return this.level;
}
public RandomSource getRandom() {
return this.random;
}
/**
* {@return the position of the block that will be altered}
*/
public BlockPos getPos() {
return this.pos;
}
/**
* {@return the original block state that would be placed by the ground decorator}
*/
public BlockState getOriginalAlteredState() {
return this.originalAltered;
}
/**
* {@return the new block state to be placed by the ground decorator}
*/
public BlockState getNewAlteredState() {
return this.newAltered;
}
/**
* @param newAltered the new block state to be placed by the ground decorator
*/
public void setNewAlteredState(BlockState newAltered) {
this.newAltered = newAltered;
}
}
@@ -355,6 +355,20 @@ public class FluidType
return this.supportsBoating(boat);
}
/**
* When {@code false}, the fluid will no longer update its height value while
* within a boat while it is not within a fluid ({@link Boat#isUnderWater()}.
*
* @param state the state of the fluid the rider is within
* @param boat the boat the rider is within that is not inside a fluid
* @param rider the rider of the boat
* @return {@code true} if the fluid height should be updated, {@code false} otherwise
*/
public boolean shouldUpdateWhileBoating(FluidState state, Boat boat, Entity rider)
{
return !this.supportsBoating(state, boat);
}
/**
* Returns whether the entity can ride in this vehicle under the fluid.
*
@@ -147,7 +147,9 @@ public class FluidUtil
}
else
{
containerFluidHandler.fill(simulatedTransfer, IFluidHandler.FluidAction.SIMULATE);
// We are acting on a COPY of the stack, so performing changes on the source is acceptable even if we are simulating.
// We need to perform the change otherwise the call to getContainer() will be incorrect.
containerFluidHandler.fill(simulatedTransfer, IFluidHandler.FluidAction.EXECUTE);
}
ItemStack resultContainer = containerFluidHandler.getContainer();
@@ -15,8 +15,6 @@ import net.minecraftforge.fluids.FluidType;
import net.minecraftforge.fluids.FluidUtil;
import net.minecraftforge.fluids.capability.templates.VoidFluidHandler;
import net.minecraftforge.fluids.capability.IFluidHandler.FluidAction;
/**
* Wrapper around any block, only accounts for fluid placement, otherwise the block acts a void.
* If the block in question inherits from the Forge implementations,
@@ -73,11 +71,11 @@ public class BlockWrapper extends VoidFluidHandler
BlockState state = world.getBlockState(blockPos);
if (liquidContainer.canPlaceLiquid(world, blockPos, state, resource.getFluid()))
{
//If we are executing try to actually fill the container, if it failed return that we failed
if (action.simulate() || liquidContainer.placeLiquid(world, blockPos, state, resource.getFluid().getFluidType().getStateForPlacement(world, blockPos, resource)))
if (action.execute())
{
return FluidType.BUCKET_VOLUME;
liquidContainer.placeLiquid(world, blockPos, state, resource.getFluid().getFluidType().getStateForPlacement(world, blockPos, resource));
}
return FluidType.BUCKET_VOLUME;
}
}
return 0;
@@ -0,0 +1,227 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.logging;
import com.mojang.logging.LogUtils;
import net.minecraftforge.fml.ModList;
import net.minecraftforge.fml.loading.FMLLoader;
import net.minecraftforge.forgespi.language.IModInfo;
import org.slf4j.Logger;
import org.spongepowered.asm.mixin.extensibility.IMixinInfo;
import org.spongepowered.asm.mixin.transformer.ClassInfo;
import org.spongepowered.asm.mixin.transformer.meta.MixinMerged;
import javax.annotation.Nullable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
public final class CrashReportAnalyser {
private static final Logger LOGGER = LogUtils.getLogger();
private static final Map<String, IModInfo> PACKAGE_MOD_CACHE = new HashMap<>();
private static final Map<IModInfo, String[]> SUSPECTED_MODS = new HashMap<>();
private CrashReportAnalyser() {}
/**
* Tries to cache, analyze and append the suspected mods for this crash to the crash report.
* */
public static String appendSuspectedMods(Throwable throwable, StackTraceElement[] uncategorizedStackTrace) {
StringBuilder stringBuilder = new StringBuilder();
try {
cacheModList();
analyseCrashReport(throwable, uncategorizedStackTrace);
buildSuspectedModsSection(stringBuilder);
}
catch (Throwable t) {
LOGGER.error("Failed to append suspected mod(s) to crash report!", t);
}
return stringBuilder.toString();
}
/**
* Tries to analyze the given exception and uncategorized stacktrace of the crash report.
* It checks the stacktrace for any occurrence of the package names cached in the {@link #PACKAGE_MOD_CACHE},
* including mixin classes.
* **/
private static void analyseCrashReport(Throwable throwable, StackTraceElement[] uncategorizedStackTrace) {
scanThrowable(throwable);
scanStacktrace(uncategorizedStackTrace);
}
/**
* Converts the suspected mod(s) for this crash to a String to be added to the crash report,
* including the mods name, its id, version and an issues link if available,
* as well as the position where the exception occurred (either the stacktrace element
* or the mixin class and its target(s))
* **/
private static void buildSuspectedModsSection(StringBuilder stringBuilder) {
stringBuilder.append("Suspected Mod");
stringBuilder.append(SUSPECTED_MODS.size() == 1 ? ": " : "s: ");
if (SUSPECTED_MODS.isEmpty()) {
stringBuilder.append("NONE\n");
}
else {
SUSPECTED_MODS.forEach((iModInfo, position) -> {
stringBuilder
.append("\n\t")
.append(iModInfo.getDisplayName())
.append(" (").append(iModInfo.getModId()).append("),")
.append(" Version: ").append(iModInfo.getVersion());
iModInfo.getOwningFile().getConfig().<String>getConfigElement("issueTrackerURL").ifPresent(issuesLink -> {
stringBuilder
.append("\n\t\t")
.append("Issue tracker URL: ")
.append(issuesLink);
});
stringBuilder.append("\n\t\t");
for (String s : position) {
stringBuilder.append(s);
}
stringBuilder.append("\n");
});
SUSPECTED_MODS.clear();
}
}
/**
* Checks the stacktrace of the given throwable and all its children for any occurrence of the package names cached in the {@link #PACKAGE_MOD_CACHE},
* including mixin classes.
* **/
private static void scanThrowable(Throwable throwable) {
scanStacktrace(throwable.getStackTrace());
if (throwable.getCause() != null && throwable.getCause() != throwable) {
scanThrowable(throwable.getCause());
}
}
/**
* Checks the given stacktrace for any occurrence of the package names cached in the {@link #PACKAGE_MOD_CACHE},
* including mixin classes.
* **/
private static void scanStacktrace(StackTraceElement[] stackTrace) {
for (StackTraceElement stackTraceElement : stackTrace) {
identifyByClass(stackTraceElement);
identifyByMixins(stackTraceElement);
}
}
/**
* Iterates over all loaded mods, resolving and caching their package names with the corresponding {@link IModInfo}.
* **/
private static void cacheModList() {
ModList modList = ModList.get();
ModuleLayer gameLayer = FMLLoader.getGameLayer();
if (modList != null) {
modList.getMods().forEach(iModInfo -> {
//Don't cache minecraft or forge as they will always be included in the stacktrace
if (!iModInfo.getModId().equals("forge") && !iModInfo.getModId().equals("minecraft")) {
Set<String> packages = new HashSet<>();
gameLayer.findModule(iModInfo.getModId()).ifPresent(module -> packages.addAll(module.getPackages()));
packages.forEach(s -> PACKAGE_MOD_CACHE.put(s, iModInfo));
}
});
}
}
private static void identifyByClass(StackTraceElement stackTraceElement) {
blameIfPresent(stackTraceElement);
}
private static void identifyByMixins(StackTraceElement stackTraceElement) {
IMixinInfo mixinInfo = getMixinInfo(stackTraceElement);
if (mixinInfo != null) {
String elementAsString = stackTraceElement.toString();
String mixinClassName = mixinInfo.getClassName();
List<String> targetClasses = mixinInfo.getTargetClasses();
blameIfPresent(mixinClassName, "Mixin class: ", mixinClassName, "\n\t\tTarget", (targetClasses.size() == 1 ? ": " + targetClasses.get(0) : "s: " + targetClasses).replaceAll("/", "."), "\n\t\tat ", elementAsString);
}
}
private static void blameIfPresent(StackTraceElement stackTraceElement) {
blameIfPresent(stackTraceElement.getClassName(), "at ", stackTraceElement.toString());
}
private static void blameIfPresent(String className, String... position) {
String commonPackage = findMatchingPackage(className);
if (commonPackage != null) {
SUSPECTED_MODS.putIfAbsent(PACKAGE_MOD_CACHE.get(commonPackage), position);
}
}
/**
* Checks if the beginning of the given class name is contained in the {@link #PACKAGE_MOD_CACHE}
* @return the package name of the class or null if it is not present in the cache
* */
@Nullable
private static String findMatchingPackage(String className) {
for (String s : PACKAGE_MOD_CACHE.keySet()) {
if (className.startsWith(s)) {
return s;
}
}
return null;
}
@Nullable
private static MixinMerged findMixinMerged(StackTraceElement element) {
try {
Class<?> clazz = Class.forName(element.getClassName());
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
if (method.getName().equals(element.getMethodName())) {
MixinMerged mixinMerged = method.getAnnotation(MixinMerged.class);
if (mixinMerged != null) {
return mixinMerged;
}
}
}
}
catch (ClassNotFoundException | NoClassDefFoundError ignored) {}
return null;
}
/**
* Tries to identify any applied mixin for the class and method provided by the stacktrace element.
* @param element the stacktrace element to check
* @return the {@link IMixinInfo} for the class and method or null if there is no mixin applied at this position
* **/
@Nullable
private static IMixinInfo getMixinInfo(StackTraceElement element) {
MixinMerged mixinMerged = findMixinMerged(element);
if (mixinMerged != null) {
ClassInfo classInfo = ClassInfo.forName(mixinMerged.mixin().replace('.', '/'));
if (classInfo != null) {
try {
Field mixinField = ClassInfo.class.getDeclaredField("mixin");
mixinField.setAccessible(true);
return (IMixinInfo) mixinField.get(classInfo);
}
catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
return null;
}
}
@@ -5,12 +5,21 @@
package net.minecraftforge.network;
import com.mojang.logging.LogUtils;
import com.google.common.net.InetAddresses;
import net.minecraft.client.multiplayer.resolver.ResolvedServerAddress;
import net.minecraft.client.multiplayer.resolver.ServerAddress;
import net.minecraft.client.multiplayer.resolver.ServerNameResolver;
import net.minecraft.util.HttpUtil;
import org.jetbrains.annotations.ApiStatus;
import org.slf4j.Logger;
import javax.annotation.Nullable;
import java.net.Inet4Address;
import net.minecraftforge.common.ForgeConfig;
import javax.annotation.Nullable;
import java.net.SocketAddress;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
@@ -19,6 +28,19 @@ import java.util.Optional;
public class DualStackUtils
{
private static final String INITIAL_PREFER_IPv4_STACK = System.getProperty("java.net.preferIPv4Stack") == null ? "false" : System.getProperty("java.net.preferIPv4Stack");
private static final String INITIAL_PREFER_IPv6_ADDRESSES = System.getProperty("java.net.preferIPv6Addresses") == null ? "false" : System.getProperty("java.net.preferIPv6Addresses");
private static final Logger LOGGER = LogUtils.getLogger();
/**
* Called by {@link net.minecraftforge.common.MinecraftForge} to load this class so that the initial network
* property constants are set before any of the other methods in this class are called. This is so we can
* distinguish what Java's read once on JVM start vs what we've set for Netty.
*/
@ApiStatus.Internal
public static void initialise() {}
/**
* Resolve the address and see if Java and the OS return an IPv6 or IPv4 one, then let Netty know
* accordingly (it doesn't understand the {@code java.net.preferIPv6Addresses=system} property).
@@ -45,14 +67,49 @@ public class DualStackUtils
*/
public static boolean checkIPv6(final InetAddress inetAddress)
{
if (inetAddress instanceof Inet6Address)
// only log debug messages if we're not in the server pinger thread, as otherwise it's unclear which IP
// corresponds to which server as soon as you have more than one server in the multiplayer server list
final String currentThreadName = Thread.currentThread().getName();
final boolean shouldLogDebug = !currentThreadName.contains("Server Pinger #");
if (inetAddress instanceof Inet6Address addr)
{
if (shouldLogDebug)
LOGGER.debug("Detected IPv6 address: \"" + addr.getHostAddress() + "\"");
System.setProperty("java.net.preferIPv4Stack", "false");
System.setProperty("java.net.preferIPv6Addresses", "true");
return true;
}
else if (inetAddress instanceof Inet4Address addr)
{
if (shouldLogDebug)
LOGGER.debug("Detected IPv4 address: \"" + addr.getHostAddress() + "\"");
System.setProperty("java.net.preferIPv4Stack", "true");
System.setProperty("java.net.preferIPv6Addresses", "false");
return false;
}
else
{
if (shouldLogDebug) {
final String addr = inetAddress == null ? "null" : "\"" + inetAddress.getHostAddress() + "\"";
LOGGER.debug("Unable to determine IP version of address: " + addr);
}
if (INITIAL_PREFER_IPv4_STACK.equalsIgnoreCase("false") && INITIAL_PREFER_IPv6_ADDRESSES.equalsIgnoreCase("true"))
{
if (shouldLogDebug)
LOGGER.debug("Assuming IPv6 as Java was explicitly told to prefer it...");
System.setProperty("java.net.preferIPv4Stack", "false");
System.setProperty("java.net.preferIPv6Addresses", "true");
return true;
}
if (shouldLogDebug)
LOGGER.debug("Assuming IPv4...");
System.setProperty("java.net.preferIPv4Stack", "true");
System.setProperty("java.net.preferIPv6Addresses", "false");
return false;
@@ -81,8 +138,43 @@ public class DualStackUtils
}
}
/**
* Used for the "Open to LAN" feature.
* @return The multicast group to use for LAN discovery - IPv6 if available, IPv4 otherwise.
*/
public static String getMulticastGroup() {
if (checkIPv6(getLocalAddress())) return "FF75:230::60";
else return "224.0.2.60";
}
/**
* Logs the initial values of the {@code java.net.preferIPv4Stack} and {@code java.net.preferIPv6Addresses} system
* properties that Java has read on JVM start. Useful for debugging hostname lookup failures.
*/
public static void logInitialPreferences() {
LOGGER.debug("Initial IPv4 stack preference: " + INITIAL_PREFER_IPv4_STACK);
LOGGER.debug("Initial IPv6 addresses preference: " + INITIAL_PREFER_IPv6_ADDRESSES);
}
/**
* {@link SocketAddress#toString()} but with IPv6 address compression support
*/
public static String getAddressString(final SocketAddress address) {
if (address instanceof final InetSocketAddress inetAddress) {
String formatted;
if (inetAddress.isUnresolved()) {
formatted = inetAddress.getHostName() + "/<unresolved>";
} else {
formatted = InetAddresses.toAddrString(inetAddress.getAddress());
if (inetAddress.getAddress() instanceof Inet6Address)
formatted = '[' + formatted + ']';
formatted = '/' + formatted;
}
return formatted + ':' + inetAddress.getPort();
}
return address.toString();
}
}
@@ -103,7 +103,7 @@ public class DelegatingPackResources extends AbstractPackResources
{
IoSupplier<InputStream> ioSupplier = pack.getResource(type, location);
if (ioSupplier != null)
return pack.getResource(type, location);
return ioSupplier;
}
return null;
+2 -3
View File
@@ -1,18 +1,17 @@
modLoader="javafml"
loaderVersion="[24,]"
issueTrackerURL="http://www.minecraftforge.net/"
issueTrackerURL="https://minecraftforge.net/"
logoFile="forge_logo.png"
license="LGPL v2.1"
[[mods]]
modId="forge"
# We use the global forge version
version="${global.forgeVersion}"
updateJSONURL="https://files.minecraftforge.net/net/minecraftforge/forge/promotions_slim.json"
displayURL="https://minecraftforge.net/"
displayName="Forge"
credits="Anyone who has contributed on Github and supports our development"
authors="LexManos,cpw"
description='''
Forge, a broad compatibility API.
'''
+3 -1
View File
@@ -4,4 +4,6 @@
# checkAndFixSAS will populate all overrides as nessasary. Prefixing added lines with \t
# checkAndFixSAS also supports names using . so simplest way to find the correct line to add is to get the AT line from the bot
# and remove the access modifier.
#==================================================================================================================================
# You need to run the setup task again after running checkAndFixSAS for genPatches to pick up the changes.
#==================================================================================================================================
net/minecraft/client/server/LanServerPinger
@@ -0,0 +1,27 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.debug;
import net.minecraft.world.level.block.Blocks;
import net.minecraftforge.event.level.AlterGroundEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
@Mod("alter_ground_event_test")
@Mod.EventBusSubscriber
public class AlterGroundEventTest {
public static final boolean ENABLE = true;
@SubscribeEvent
public static void onAlterGround(AlterGroundEvent event)
{
if (ENABLE) {
if (event.getOriginalAlteredState().is(Blocks.PODZOL)) {
event.setNewAlteredState(Blocks.REDSTONE_BLOCK.defaultBlockState());
}
}
}
}
@@ -0,0 +1,19 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.debug;
import net.minecraftforge.fml.common.Mod;
/**
* Test that the mod loading error screen shows the cause of the crash when a mod constructor throws an exception.
* <p>Enable or disable this test in the mods.toml</p>
*/
@Mod("constructor_throw_test")
public class ConstructorThrowTest {
public ConstructorThrowTest() {
throw new RuntimeException("Test");
}
}
@@ -15,6 +15,7 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
@@ -34,6 +35,7 @@ import net.minecraft.DetectedVersion;
import net.minecraft.Util;
import net.minecraft.advancements.critereon.InventoryChangeTrigger;
import net.minecraft.core.*;
import net.minecraft.core.particles.ParticleTypes;
import net.minecraft.core.registries.Registries;
import net.minecraft.data.CachedOutput;
import net.minecraft.data.PackOutput;
@@ -169,6 +171,7 @@ public class DataGeneratorTest
gen.addProvider(event.includeClient(), itemModels);
gen.addProvider(event.includeClient(), new BlockStates(packOutput, itemModels.existingFileHelper));
gen.addProvider(event.includeClient(), new SoundDefinitions(packOutput, event.getExistingFileHelper()));
gen.addProvider(event.includeClient(), new ParticleDescriptions(packOutput, event.getExistingFileHelper()));
gen.addProvider(event.includeServer(), new Recipes(packOutput));
gen.addProvider(event.includeServer(), new Tags(packOutput, lookupProvider, event.getExistingFileHelper()));
@@ -1120,6 +1123,80 @@ public class DataGeneratorTest
}
}
private static class ParticleDescriptions extends ParticleDescriptionProvider {
public ParticleDescriptions(PackOutput output, ExistingFileHelper fileHelper) {
super(output, fileHelper);
}
@Override
protected void addDescriptions() {
this.sprite(ParticleTypes.DRIPPING_LAVA, new ResourceLocation("drip_hang"));
this.spriteSet(ParticleTypes.CLOUD, new ResourceLocation("generic"), 8, true);
this.spriteSet(ParticleTypes.FISHING,
new ResourceLocation("splash_0"),
new ResourceLocation("splash_1"),
new ResourceLocation("splash_2"),
new ResourceLocation("splash_3")
);
this.spriteSet(ParticleTypes.ENCHANT, () -> new Iterator<>() {
private final ResourceLocation base = new ResourceLocation("sga");
private char suffix = 'a';
@Override
public boolean hasNext() {
return this.suffix <= 'z';
}
@Override
public ResourceLocation next() {
return this.base.withSuffix("_" + this.suffix++);
}
});
}
@Override
public CompletableFuture<?> run(CachedOutput cache) {
return super.run(cache).thenRun(this::validateResults);
}
private void validateResults() {
var errors = Stream.of(ParticleTypes.DRIPPING_LAVA, ParticleTypes.CLOUD, ParticleTypes.FISHING, ParticleTypes.ENCHANT)
.map(ForgeRegistries.PARTICLE_TYPES::getKey).map(particle -> {
try (var resource = this.fileHelper.getResource(particle, PackType.CLIENT_RESOURCES, ".json", "particles").openAsReader()) {
var existingTextures = GSON.fromJson(resource, JsonObject.class).get("textures").getAsJsonArray();
var generatedTextures = this.descriptions.get(particle);
// Check texture size
if (existingTextures.size() != generatedTextures.size()) {
LOGGER.error("%s had a different number of sprites, expected %s, actual %s", particle, existingTextures.size(), generatedTextures.size());
return particle;
}
boolean error = false;
for (int i = 0; i < generatedTextures.size(); ++i) {
if (!existingTextures.get(i).getAsString().equals(generatedTextures.get(i))) {
LOGGER.error("%s index %s: expected %s, actual %s", particle, i, existingTextures.get(i).getAsString(), generatedTextures.get(i));
error = true;
}
}
return error ? particle : null;
} catch (IOException e) {
throw new RuntimeException(e);
}
}).filter(Objects::nonNull).toList();
if (!errors.isEmpty()) {
throw new AssertionError(String.format("Validation errors found in %s; see above for details", errors.stream().reduce("", (str, rl) -> str + ", " + rl, (str1, str2) -> str1 + ", " + str2)));
}
}
}
private static <T extends ModelBuilder<T>> List<String> testModelResults(Map<ResourceLocation, T> models, ExistingFileHelper existingFileHelper, Set<ResourceLocation> toIgnore) {
List<String> ret = new ArrayList<>();
models.forEach((loc, model) -> {
@@ -38,6 +38,7 @@ public class FluidUtilTest
private static void runTests(FMLCommonSetupEvent commonSetupEvent)
{
test_tryEmptyContainer();
test_tryFillContainer();
test_tryEmptyContainerAndStow_stackable();
LogManager.getLogger().info("FluidUtilTest ok!");
@@ -70,6 +71,35 @@ public class FluidUtilTest
checkItemStack(sourceStack, Items.WATER_BUCKET, 2); // Apparently the stack is not supposed to be modified
}
/**
* Ensures that tryFillContainer doesn't change the target fluid handler when simulating.
* Ant that the result of the simulated transfver is valid.
* Regression test for the root cause of <a href="https://github.com/MinecraftForge/MinecraftForge/issues/6796">issue #6796</a>.
*/
private static void test_tryFillContainer()
{
var targetStack = new ItemStack(Items.BUCKET, 2);
var sourceTank = new FluidTank(10000);
sourceTank.setFluid(new FluidStack(Fluids.WATER, 5000));
// Simulate is not supposed to modify anything
var simulateResult = FluidUtil.tryFillContainer(targetStack, sourceTank, 1000, null, false);
if (!simulateResult.isSuccess())
throw new AssertionError("Failed to transfer.");
checkItemStack(simulateResult.getResult(), Items.WATER_BUCKET, 1);
// Tank and stack shouldn't be modified
checkItemStack(targetStack, Items.BUCKET, 2);
checkFluidStack(sourceTank.getFluid(), Fluids.WATER, 5000);
// Execute should modify
var executeResult = FluidUtil.tryFillContainer(targetStack, sourceTank, 1000, null, true);
if (!executeResult.isSuccess())
throw new AssertionError("Failed to transfer.");
checkItemStack(executeResult.getResult(), Items.WATER_BUCKET, 1);
checkFluidStack(sourceTank.getFluid(), Fluids.WATER, 4000);
checkItemStack(targetStack, Items.BUCKET, 2);
}
/**
* Ensures that tryEmptyContainerAndStow doesn't duplicate fluids in the target when the container is stackable.
* Regression test for <a href="https://github.com/MinecraftForge/MinecraftForge/issues/6796">issue #6796</a>.
@@ -0,0 +1,55 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.debug;
import com.mojang.blaze3d.platform.InputConstants;
import net.minecraft.client.KeyMapping;
import net.minecraft.client.Minecraft;
import net.minecraft.network.chat.Component;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Items;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.event.RegisterKeyMappingsEvent;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.TickEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.FMLConstructModEvent;
@Mod("keymapping_test")
public class KeyMappingTest
{
@Mod.EventBusSubscriber(modid = "keymapping_test", value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
public static class ClientStuff {
// these are two separate keys to stand in for keys added by different
// mods that each do something similar with a held item from the
// respective mod, so the user wants them on the same physical key.
static KeyMapping stickKey = new KeyMapping("stick_key", InputConstants.KEY_BACKSLASH, KeyMapping.CATEGORY_MISC);
static KeyMapping rockKey = new KeyMapping("rock_key", InputConstants.KEY_BACKSLASH, KeyMapping.CATEGORY_MISC);
@SubscribeEvent
public static void init(FMLConstructModEvent event) {
MinecraftForge.EVENT_BUS.addListener(ClientStuff::tick);
}
@SubscribeEvent
public static void initKeys(RegisterKeyMappingsEvent event) {
event.register(stickKey);
event.register(rockKey);
}
public static void tick(TickEvent.ClientTickEvent event) {
if(event.phase != TickEvent.Phase.START) return;
if(stickKey.consumeClick()) {
Player player = Minecraft.getInstance().player;
if(player != null && player.getMainHandItem().is(Items.STICK))
player.sendSystemMessage(Component.literal("stick found!"));
}
if(rockKey.consumeClick()) {
Player player = Minecraft.getInstance().player;
if(player != null && player.getMainHandItem().is(Items.COBBLESTONE))
player.sendSystemMessage(Component.literal("rock found!"));
}
}
}
}
@@ -0,0 +1,135 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.debug.item;
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResultHolder;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.CreativeModeTabs;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.ClipContext;
import net.minecraft.world.level.Level;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import net.minecraftforge.event.CreativeModeTabEvent;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fluids.FluidActionResult;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidType;
import net.minecraftforge.fluids.FluidUtil;
import net.minecraftforge.fluids.capability.templates.FluidHandlerItemStackSimple;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.RegistryObject;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicReference;
@Mod(CustomFluidContainerTest.MODID)
public class CustomFluidContainerTest
{
public static final String MODID = "custom_fluid_container_test";
public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, MODID);
public static final boolean ENABLED = true;
public static final RegistryObject<Item> CUSTOM_FLUID_CONTAINER = ITEMS.register("custom_fluid_container", () -> new CustomFluidContainer((new Item.Properties()).stacksTo(1)));
public CustomFluidContainerTest()
{
if (ENABLED)
{
IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();
ITEMS.register(modEventBus);
modEventBus.addListener(this::addCreative);
}
}
private void addCreative(CreativeModeTabEvent.BuildContents event)
{
if (event.getTab() == CreativeModeTabs.INGREDIENTS)
event.accept(CUSTOM_FLUID_CONTAINER);
}
/**
* A custom fluid container item with a capacity of a vanilla bucket which uses the FluidUtil functionalities to pickup and place fluids.
*/
private static class CustomFluidContainer extends Item
{
public CustomFluidContainer(Properties properties)
{
super(properties);
}
@Override
@Nonnull
public Component getName(@Nonnull ItemStack itemStack) {
AtomicReference<String> name = new AtomicReference<>("Custom Fluid Container");
FluidUtil.getFluidHandler(itemStack).ifPresent(fluidHandler ->
{
FluidStack fluidStack = fluidHandler.getFluidInTank(0);
if (fluidStack.isEmpty())
{
name.set(name.get() + " (empty)");
}
else
{
name.set(name.get() + " (" + fluidStack.getFluid().getFluidType().getDescription().getString() + ")");
}
});
return Component.literal(name.get());
}
@Override
public InteractionResultHolder<ItemStack> use(Level level, Player player, InteractionHand hand)
{
var itemStack = player.getItemInHand(hand);
var result = new AtomicReference<FluidActionResult>();
FluidUtil.getFluidHandler(itemStack).ifPresent(fluidHandler ->
{
var fluidStack = fluidHandler.getFluidInTank(0);
if (fluidStack.isEmpty())
{
var blockHitResult = getPlayerPOVHitResult(level, player, ClipContext.Fluid.SOURCE_ONLY);
result.set(FluidUtil.tryPickUpFluid(itemStack, player, level, blockHitResult.getBlockPos(), blockHitResult.getDirection()));
}
else
{
var blockHitResult = getPlayerPOVHitResult(level, player, ClipContext.Fluid.NONE);
//try to place fluid in hit block (waterlogging, fill tank, ...). When no success try the block on the hit side.
for (BlockPos pos : Arrays.asList(blockHitResult.getBlockPos(), blockHitResult.getBlockPos().relative(blockHitResult.getDirection())))
{
result.set(FluidUtil.tryPlaceFluid(player, level, hand, pos, itemStack, fluidStack));
if (result.get().isSuccess())
{
break;
}
}
}
});
if (result.get() != null && result.get().isSuccess())
{
return InteractionResultHolder.sidedSuccess(result.get().getResult(), level.isClientSide());
}
return super.use(level, player, hand);
}
@Override
public ICapabilityProvider initCapabilities(@Nonnull ItemStack stack, @Nullable CompoundTag nbt)
{
return new FluidHandlerItemStackSimple(stack, FluidType.BUCKET_VOLUME);
}
}
}
@@ -34,7 +34,7 @@ public class MdkDatagen
var packOutput = gen.getPackOutput();
gen.addProvider(true, new PackMetadataGenerator(packOutput)
.add(PackMetadataSection.TYPE, new PackMetadataSection(
Component.literal("examplemod resources"),
Component.literal("${mod_id} resources"),
DetectedVersion.BUILT_IN.getPackVersion(PackType.CLIENT_RESOURCES),
Arrays.stream(PackType.values()).collect(Collectors.toMap(Function.identity(), DetectedVersion.BUILT_IN::getPackVersion))
))
+9
View File
@@ -33,6 +33,9 @@ modId="mdk_datagen"
[[mods]]
modId="custom_preset_editor_test"
#[[mods]]
# modId="constructor_throw_test"
# LEGACY TEST CASES
###### The mods below are from the old test framework and need to be yeeted later again.
@@ -293,6 +296,12 @@ modId="render_level_stages_test"
modId="trade_with_villager_event_test"
[[mods]]
modId="chunk_event_load_new_chunk_test"
[[mods]]
modId="alter_ground_event_test"
[[mods]]
modId="custom_fluid_container_test"
[[mods]]
modId="keymapping_test"
# ADD ABOVE THIS LINE
@@ -0,0 +1,6 @@
{
"parent": "item/generated",
"textures": {
"layer0": "item/bucket"
}
}