diff --git a/build.gradle b/build.gradle
index 9fe9ede03c..0fa882916a 100644
--- a/build.gradle
+++ b/build.gradle
@@ -248,7 +248,7 @@ project(':clean') {
ideaModule "${rootProject.name}.${project.name}.main"
main 'net.minecraft.client.main.Main'
- workingDirectory project.file('run')
+ workingDirectory project.file('run/client')
args '--gameDir', '.'
args '--version', MC_VERSION
@@ -263,7 +263,7 @@ project(':clean') {
ideaModule "${rootProject.name}.${project.name}.main"
main 'net.minecraft.server.Main'
- workingDirectory project.file('run')
+ workingDirectory project.file('run/server')
}
}
}
@@ -476,7 +476,6 @@ def sharedFmlonlyForge = { Project prj ->
}
for (def run : prj.patcher.runs) {
if (run.parents) continue // We already added this to the parent run config
- run.workingDirectory prj.file('run')
if (run.name.contains('client') || run.name.contains('data')) {
// Natives are loaded from the classpath now in all cases
@@ -652,6 +651,7 @@ project(':forge') {
runs {
forge_client {
+ workingDirectory file('run/client')
property 'eventbus.checkTypesOnDispatch', 'true'
args '--launchTarget', 'forgeclientdev'
ideaModule "${rootProject.name}.${project.name}.main"
@@ -661,6 +661,7 @@ project(':forge') {
}
forge_test_client {
+ workingDirectory file('run/client_test')
parent runs.forge_client
taskName 'forge_test_client'
@@ -675,6 +676,7 @@ project(':forge') {
}
forge_server {
+ workingDirectory file('run/server')
args '--launchTarget', 'forgeserverdev'
ideaModule "${rootProject.name}.${project.name}.main"
@@ -684,6 +686,7 @@ project(':forge') {
}
forge_test_server {
+ workingDirectory file('run/server_test')
parent runs.forge_server
taskName 'forge_test_server'
diff --git a/fmlcore/src/main/java/net/minecraftforge/fml/IExtensionPoint.java b/fmlcore/src/main/java/net/minecraftforge/fml/IExtensionPoint.java
index 731901cb2b..d1fdf4f997 100644
--- a/fmlcore/src/main/java/net/minecraftforge/fml/IExtensionPoint.java
+++ b/fmlcore/src/main/java/net/minecraftforge/fml/IExtensionPoint.java
@@ -25,6 +25,7 @@ import java.util.function.Supplier;
* @param the type of the record which is held by the extension point
*/
@SuppressWarnings("unused") // Type parameter T
+// TODO: Complete re-write, this hasnt actually be used in a generic way by mods and we could make it a lot simpler.
public interface IExtensionPoint
{
/**
@@ -40,7 +41,7 @@ public interface IExtensionPoint
* where {@code true} means it is from the server and {@code false} means it is from the world save. The return
* value of the predicate determines whether the remote version is "compatible" for the purposes of the display test.
*
- *
The local compatibility version may be of the value {@link net.minecraftforge.network.NetworkConstants#IGNORESERVERONLY},
+ *
The local compatibility version may be of the value {@link DisplayTest#IGNORESERVERONLY},
* in which case clients will ignore the mod's presence if it is present on the server but not on the client.
* However, the remote version test predicate must still accept this value as a remote version in order to display
* as compatible if the mod is present on the client.
@@ -94,6 +95,6 @@ public interface IExtensionPoint
*/
@SuppressWarnings("JavadocReference") // reference to NetworkConstants, ForgeHooksClient
record DisplayTest(Supplier suppliedVersion, BiPredicate remoteVersionTest) implements IExtensionPoint {
- 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";
+ public static final String IGNORESERVERONLY = "SERVER_ONLY";
}
}
diff --git a/patches/minecraft/net/minecraft/client/Minecraft.java.patch b/patches/minecraft/net/minecraft/client/Minecraft.java.patch
index 16edc79eea..f4888c8910 100644
--- a/patches/minecraft/net/minecraft/client/Minecraft.java.patch
+++ b/patches/minecraft/net/minecraft/client/Minecraft.java.patch
@@ -79,9 +79,12 @@
Util.m_137521_(p_296164_, (p_296162_) -> {
this.m_91239_(p_296162_, minecraft$gameloadcookie);
}, () -> {
-@@ -575,7 +_,7 @@
+@@ -574,8 +_,10 @@
+
this.f_167847_.m_168556_();
this.m_293750_(minecraft$gameloadcookie);
++ if (net.minecraftforge.client.loading.ClientModLoader.completeModLoading())
++ return; // Do not overwrite the error screen if there are errors
});
- }, false));
+ }, false).get());
@@ -150,23 +153,6 @@
});
}
-@@ -872,13 +_,13 @@
- Bootstrap.m_135875_(p_91333_.m_127526_());
- if (p_91333_.m_127527_() != null) {
- Bootstrap.m_135875_("#@!@# Game crashed! Crash report saved to: #@!@# " + p_91333_.m_127527_());
-- System.exit(-1);
-+ net.minecraftforge.server.ServerLifecycleHooks.handleExit(-1);
- } else if (p_91333_.m_127512_(file2)) {
- Bootstrap.m_135875_("#@!@# Game crashed! Crash report saved to: #@!@# " + file2.getAbsolutePath());
-- System.exit(-1);
-+ net.minecraftforge.server.ServerLifecycleHooks.handleExit(-1);
- } else {
- Bootstrap.m_135875_("#@?@# Game crashed! Crash report could not be saved. #@?@#");
-- System.exit(-2);
-+ net.minecraftforge.server.ServerLifecycleHooks.handleExit(-2);
- }
-
- }
@@ -1003,10 +_,6 @@
f_90982_.error("setScreen called from non-game thread");
}
@@ -185,13 +171,13 @@
+ net.minecraftforge.client.ForgeHooksClient.clearGuiLayers(this);
+ Screen old = this.f_91080_;
+ if (p_91153_ != null) {
-+ var event = net.minecraftforge.event.ForgeEventFactory.onScreenOpening(old, p_91153_);
++ var event = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenOpening(old, p_91153_);
+ if (event == null) return;
+ p_91153_ = event;
+ }
+
+ if (old != null && p_91153_ != old) {
-+ net.minecraftforge.event.ForgeEventFactory.onScreenClose(old);
++ net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenClose(old);
+ old.m_7861_();
+ }
+
diff --git a/patches/minecraft/net/minecraft/client/MouseHandler.java.patch b/patches/minecraft/net/minecraft/client/MouseHandler.java.patch
index ca13b2e2b5..6d7b2b6de1 100644
--- a/patches/minecraft/net/minecraft/client/MouseHandler.java.patch
+++ b/patches/minecraft/net/minecraft/client/MouseHandler.java.patch
@@ -4,7 +4,7 @@
this.f_91510_ = -1;
}
-+ if (net.minecraftforge.event.ForgeEventFactory.onMouseButtonPre(p_91532_, p_91533_, p_91534_)) return;
++ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseButtonPre(p_91532_, p_91533_, p_91534_)) return;
boolean[] aboolean = new boolean[]{false};
if (this.f_91503_.m_91265_() == null) {
if (this.f_91503_.f_91080_ == null) {
@@ -13,19 +13,19 @@
screen.m_169415_();
Screen.m_96579_(() -> {
- aboolean[0] = screen.m_6375_(d0, d1, i);
-+ aboolean[0] = net.minecraftforge.event.ForgeEventFactory.onScreenMouseClickedPre(screen, d0, d1, i);
++ aboolean[0] = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseClickedPre(screen, d0, d1, i);
+ if (!aboolean[0]) {
+ aboolean[0] = this.f_91503_.f_91080_.m_6375_(d0, d1, i);
-+ aboolean[0] = net.minecraftforge.event.ForgeEventFactory.onScreenMouseClickedPost(screen, d0, d1, i, aboolean[0]);
++ aboolean[0] = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseClickedPost(screen, d0, d1, i, aboolean[0]);
+ }
}, "mouseClicked event handler", screen.getClass().getCanonicalName());
} else {
Screen.m_96579_(() -> {
- aboolean[0] = screen.m_6348_(d0, d1, i);
-+ aboolean[0] = net.minecraftforge.event.ForgeEventFactory.onScreenMouseReleasedPre(screen, d0, d1, i);
++ aboolean[0] = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseReleasedPre(screen, d0, d1, i);
+ if (!aboolean[0]) {
+ aboolean[0] = this.f_91503_.f_91080_.m_6348_(d0, d1, i);
-+ aboolean[0] = net.minecraftforge.event.ForgeEventFactory.onScreenMouseReleasedPost(screen, d0, d1, i, aboolean[0]);
++ aboolean[0] = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseReleasedPost(screen, d0, d1, i, aboolean[0]);
+ }
}, "mouseReleased event handler", screen.getClass().getCanonicalName());
}
@@ -34,7 +34,7 @@
}
}
-+ net.minecraftforge.event.ForgeEventFactory.onMouseButtonPost(p_91532_, p_91533_, p_91534_);
++ net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseButtonPost(p_91532_, p_91533_, p_91534_);
}
}
@@ -44,9 +44,9 @@
double d4 = this.f_91508_ * (double)this.f_91503_.m_91268_().m_85446_() / (double)this.f_91503_.m_91268_().m_85444_();
- this.f_91503_.f_91080_.m_6050_(d3, d4, d1, d2);
this.f_91503_.f_91080_.m_169415_();
-+ if (net.minecraftforge.event.ForgeEventFactory.onScreenMouseScrollPre(this.f_91503_.f_91080_, d3, d4, d1, d2)) return;
++ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseScrollPre(this.f_91503_.f_91080_, d3, d4, d1, d2)) return;
+ if (this.f_91503_.f_91080_.m_6050_(d3, d4, d1, d2)) return;
-+ net.minecraftforge.event.ForgeEventFactory.onScreenMouseScrollPost(this.f_91503_.f_91080_, d3, d4, d1, d2);
++ net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseScrollPost(this.f_91503_.f_91080_, d3, d4, d1, d2);
} else if (this.f_91503_.f_91074_ != null) {
if (this.f_291070_ != 0.0D && Math.signum(d1) != Math.signum(this.f_291070_)) {
this.f_291070_ = 0.0D;
@@ -54,7 +54,7 @@
this.f_291070_ -= (double)j;
this.f_291867_ -= (double)i;
int k = i == 0 ? -j : i;
-+ if (net.minecraftforge.event.ForgeEventFactory.onMouseScroll(this, d1, d2)) return;
++ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseScroll(this, d1, d2)) return;
if (this.f_91503_.f_91074_.m_5833_()) {
if (this.f_91503_.f_91065_.m_93085_().m_94768_()) {
this.f_91503_.f_91065_.m_93085_().m_205380_(-k);
@@ -63,9 +63,9 @@
double d3 = (p_91564_ - this.f_91508_) * (double)this.f_91503_.m_91268_().m_85446_() / (double)this.f_91503_.m_91268_().m_85444_();
Screen.m_96579_(() -> {
- screen.m_7979_(d0, d1, this.f_91510_, d2, d3);
-+ if (net.minecraftforge.event.ForgeEventFactory.onScreenMouseDragPre(screen, d0, d1, this.f_91510_, d2, d3)) return;
++ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseDragPre(screen, d0, d1, this.f_91510_, d2, d3)) return;
+ if (screen.m_7979_(d0, d1, this.f_91510_, d2, d3)) return;
-+ net.minecraftforge.event.ForgeEventFactory.onScreenMouseDragPost(screen, d0, d1, this.f_91510_, d2, d3);
++ net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseDragPost(screen, d0, d1, this.f_91510_, d2, d3);
}, "mouseDragged event handler", screen.getClass().getCanonicalName());
}
diff --git a/patches/minecraft/net/minecraft/client/multiplayer/ClientCommonPacketListenerImpl.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/ClientCommonPacketListenerImpl.java.patch
index 774457e4f6..501766c4d4 100644
--- a/patches/minecraft/net/minecraft/client/multiplayer/ClientCommonPacketListenerImpl.java.patch
+++ b/patches/minecraft/net/minecraft/client/multiplayer/ClientCommonPacketListenerImpl.java.patch
@@ -4,7 +4,7 @@
}
public void m_293213_(ClientboundCustomPayloadPacket p_298103_) {
-+ if (net.minecraftforge.network.NetworkHooks.onCustomPayload(p_298103_, this.f_290549_)) return;
++ if (net.minecraftforge.common.ForgeHooks.onCustomPayload(p_298103_, this.f_290549_)) return;
CustomPacketPayload custompacketpayload = p_298103_.f_291001_();
if (!(custompacketpayload instanceof DiscardedPayload)) {
PacketUtils.m_131363_(p_298103_, this, this.f_291812_);
diff --git a/patches/minecraft/net/minecraft/client/multiplayer/ClientConfigurationPacketListenerImpl.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/ClientConfigurationPacketListenerImpl.java.patch
new file mode 100644
index 0000000000..3b662c3eb3
--- /dev/null
+++ b/patches/minecraft/net/minecraft/client/multiplayer/ClientConfigurationPacketListenerImpl.java.patch
@@ -0,0 +1,10 @@
+--- a/net/minecraft/client/multiplayer/ClientConfigurationPacketListenerImpl.java
++++ b/net/minecraft/client/multiplayer/ClientConfigurationPacketListenerImpl.java
+@@ -71,6 +_,7 @@
+ this.f_290549_.m_129505_(new ClientPacketListener(this.f_291812_, this.f_290549_, new CommonListenerCookie(this.f_290697_, this.f_291019_, this.f_291454_, this.f_291167_, this.f_291180_, this.f_291024_, this.f_291028_)));
+ this.f_290549_.m_294304_();
+ this.f_290549_.m_129512_(new ServerboundFinishConfigurationPacket());
++ net.minecraftforge.common.ForgeHooks.handleClientConfigurationComplete(this.f_290549_);
+ }
+
+ public void m_9933_() {
diff --git a/patches/minecraft/net/minecraft/client/multiplayer/ClientHandshakePacketListenerImpl.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/ClientHandshakePacketListenerImpl.java.patch
index 55f97013d8..eb6ccaf610 100644
--- a/patches/minecraft/net/minecraft/client/multiplayer/ClientHandshakePacketListenerImpl.java.patch
+++ b/patches/minecraft/net/minecraft/client/multiplayer/ClientHandshakePacketListenerImpl.java.patch
@@ -1,27 +1,18 @@
--- a/net/minecraft/client/multiplayer/ClientHandshakePacketListenerImpl.java
+++ b/net/minecraft/client/multiplayer/ClientHandshakePacketListenerImpl.java
-@@ -133,6 +_,7 @@
- this.f_104521_.accept(Component.m_237115_("connect.joining"));
- GameProfile gameprofile = p_104547_.m_134774_();
- this.f_104522_.m_129512_(new ServerboundLoginAcknowledgedPacket());
-+ net.minecraftforge.network.NetworkHooks.handleClientLoginSuccess(this.f_104522_);
- this.f_104522_.m_129505_(new ClientConfigurationPacketListenerImpl(this.f_104519_, this.f_104522_, new CommonListenerCookie(gameprofile, this.f_104519_.m_261007_().m_285995_(this.f_260722_, this.f_260612_, this.f_285614_), ClientRegistryLayer.m_245874_().m_247579_(), FeatureFlags.f_244332_, (String)null, this.f_243717_, this.f_104520_)));
- this.f_104522_.m_129512_(new ServerboundCustomPayloadPacket(new BrandPayload(ClientBrandRetriever.getClientModName())));
- this.f_104522_.m_129512_(new ServerboundClientInformationPacket(this.f_104519_.f_91066_.m_294596_()));
-@@ -142,7 +_,7 @@
+@@ -141,6 +_,7 @@
+ public void m_7026_(Component p_104543_) {
if (this.f_243717_ != null && this.f_243717_.m_295074_()) {
this.f_104519_.m_91152_(new DisconnectedRealmsScreen(this.f_104520_, CommonComponents.f_130661_, p_104543_));
++ } else if (net.minecraftforge.client.ForgeHooksClient.onClientDisconnect(this.f_104522_, this.f_104519_, this.f_104520_, p_104543_)) {
} else {
-- this.f_104519_.m_91152_(new DisconnectedScreen(this.f_104520_, CommonComponents.f_130661_, p_104543_));
-+ this.f_104519_.m_91152_(net.minecraftforge.network.NetworkHooks.getModMismatchData(f_104522_) != null ? new net.minecraftforge.client.gui.ModMismatchDisconnectedScreen(this.f_104520_, CommonComponents.f_130661_, p_104543_, net.minecraftforge.network.NetworkHooks.getModMismatchData(f_104522_)) : new DisconnectedScreen(this.f_104520_, CommonComponents.f_130661_, p_104543_));
+ this.f_104519_.m_91152_(new DisconnectedScreen(this.f_104520_, CommonComponents.f_130661_, p_104543_));
}
-
- }
@@ -163,6 +_,7 @@
}
public void m_7254_(ClientboundCustomQueryPacket p_104545_) {
-+ if (net.minecraftforge.network.NetworkHooks.onCustomPayload(p_104545_, this.f_104522_)) return;
++ if (net.minecraftforge.common.ForgeHooks.onCustomPayload(p_104545_, this.f_104522_)) return;
this.f_104521_.accept(Component.m_237115_("connect.negotiating"));
this.f_104522_.m_129512_(new ServerboundCustomQueryAnswerPacket(p_104545_.f_134745_(), (CustomQueryAnswerPayload)null));
}
diff --git a/patches/minecraft/net/minecraft/client/multiplayer/ClientPacketListener.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/ClientPacketListener.java.patch
index d8b08099f5..e952da5925 100644
--- a/patches/minecraft/net/minecraft/client/multiplayer/ClientPacketListener.java.patch
+++ b/patches/minecraft/net/minecraft/client/multiplayer/ClientPacketListener.java.patch
@@ -8,14 +8,6 @@
int i = p_105030_.f_132360_();
this.f_291812_.f_91074_.m_20234_(i);
this.f_104889_.m_104630_(i, this.f_291812_.f_91074_);
-@@ -400,6 +_,7 @@
- this.f_291812_.f_91074_.m_287199_(commonplayerspawninfo.f_291470_());
- this.f_291812_.f_91072_.m_171805_(commonplayerspawninfo.f_291098_(), commonplayerspawninfo.f_290730_());
- this.f_291812_.f_91066_.m_193770_(p_105030_.f_132370_());
-+ net.minecraftforge.network.NetworkHooks.sendMCRegistryPackets(f_290549_, "PLAY_TO_SERVER");
- this.f_252517_ = null;
- this.f_244346_ = new LastSeenMessagesTracker(20);
- this.f_244113_ = MessageSignatureCache.m_246587_();
@@ -1026,7 +_,9 @@
localplayer1.m_21204_().m_22159_(localplayer.m_21204_());
}
diff --git a/patches/minecraft/net/minecraft/client/renderer/entity/EntityRenderDispatcher.java.patch b/patches/minecraft/net/minecraft/client/renderer/entity/EntityRenderDispatcher.java.patch
index b0d9ccd71e..c6a69be1bf 100644
--- a/patches/minecraft/net/minecraft/client/renderer/entity/EntityRenderDispatcher.java.patch
+++ b/patches/minecraft/net/minecraft/client/renderer/entity/EntityRenderDispatcher.java.patch
@@ -27,6 +27,6 @@
EntityRendererProvider.Context entityrendererprovider$context = new EntityRendererProvider.Context(this, this.f_173995_, this.f_234576_, this.f_234577_, p_174004_, this.f_173996_, this.f_114365_);
this.f_114362_ = EntityRenderers.m_174049_(entityrendererprovider$context);
this.f_114363_ = EntityRenderers.m_174051_(entityrendererprovider$context);
-+ net.minecraftforge.event.ForgeEventFactory.gatherLayers(f_114362_, f_114363_, entityrendererprovider$context);
++ net.minecraftforge.client.event.ForgeEventFactoryClient.gatherLayers(f_114362_, f_114363_, entityrendererprovider$context);
}
}
diff --git a/patches/minecraft/net/minecraft/network/CompressionEncoder.java.patch b/patches/minecraft/net/minecraft/network/CompressionEncoder.java.patch
index 904c8e3ac3..b317b385ce 100644
--- a/patches/minecraft/net/minecraft/network/CompressionEncoder.java.patch
+++ b/patches/minecraft/net/minecraft/network/CompressionEncoder.java.patch
@@ -16,7 +16,7 @@
+ if (!DISABLE_PACKET_DEBUG && i > net.minecraft.network.CompressionDecoder.f_182672_) {
+ p_129453_.markReaderIndex();
+ LOGGER.error("Attempted to send packet over maximum protocol size: {} > {}\nData:\n{}", i, net.minecraft.network.CompressionDecoder.f_182672_,
-+ net.minecraftforge.logging.PacketDump.getContentDump(p_129453_));
++ net.minecraftforge.common.util.HexDumper.dump(p_129453_));
+ p_129453_.resetReaderIndex();
+ }
byte[] abyte = new byte[i];
diff --git a/patches/minecraft/net/minecraft/network/Connection.java.patch b/patches/minecraft/net/minecraft/network/Connection.java.patch
index 5436876f17..6476259254 100644
--- a/patches/minecraft/net/minecraft/network/Connection.java.patch
+++ b/patches/minecraft/net/minecraft/network/Connection.java.patch
@@ -1,14 +1,18 @@
--- a/net/minecraft/network/Connection.java
+++ b/net/minecraft/network/Connection.java
-@@ -102,6 +_,7 @@
+@@ -102,15 +_,19 @@
private volatile Component f_290021_;
@Nullable
BandwidthDebugMonitor f_291520_;
+ private java.util.function.Consumer activationHandler;
++ private final net.minecraftforge.common.util.PacketLogger packetLogger;
public Connection(PacketFlow p_129482_) {
this.f_129466_ = p_129482_;
-@@ -111,6 +_,7 @@
++ this.packetLogger = new net.minecraftforge.common.util.PacketLogger(this);
+ }
+
+ public void channelActive(ChannelHandlerContext p_129525_) throws Exception {
super.channelActive(p_129525_);
this.f_129468_ = p_129525_.channel();
this.f_129469_ = this.f_129468_.remoteAddress();
@@ -16,6 +20,32 @@
if (this.f_290021_ != null) {
this.m_129507_(this.f_290021_);
}
+@@ -169,6 +_,7 @@
+ } else {
+ if (packetlistener.m_294638_(p_129488_)) {
+ try {
++ packetLogger.recv(p_129488_);
+ m_129517_(p_129488_, packetlistener);
+ } catch (RunningOnDifferentThreadException runningondifferentthreadexception) {
+ } catch (RejectedExecutionException rejectedexecutionexception) {
+@@ -237,7 +_,8 @@
+ this.m_295864_((p_296374_) -> {
+ p_296374_.m_294993_(p_297789_);
+ this.m_129505_(p_298739_);
+- p_296374_.m_129520_(new ClientIntentionPacket(SharedConstants.m_183709_().m_132495_(), p_300730_, p_300598_, p_297789_), (PacketSendListener)null, true);
++ // TODO: Change this to be a immediately sent login custom payload packet?
++ p_296374_.m_129520_(new ClientIntentionPacket(SharedConstants.m_183709_().m_132495_(), net.minecraftforge.network.NetworkContext.enhanceHostName(p_300730_), p_300598_, p_297789_), (PacketSendListener)null, true);
+ });
+ }
+
+@@ -289,6 +_,7 @@
+
+ private void m_243087_(Packet> p_243260_, @Nullable PacketSendListener p_243290_, boolean p_299937_) {
+ ChannelFuture channelfuture = p_299937_ ? this.f_129468_.writeAndFlush(p_243260_) : this.f_129468_.write(p_243260_);
++ channelfuture.addListener(f -> packetLogger.send(p_243260_));
+ if (p_243290_ != null) {
+ channelfuture.addListener((p_243167_) -> {
+ if (p_243167_.isSuccess()) {
@@ -395,7 +_,7 @@
if (this.f_129469_ == null) {
return "local";
@@ -30,15 +60,31 @@
public static ChannelFuture m_290025_(InetSocketAddress p_290034_, boolean p_290035_, final Connection p_290031_) {
+ net.minecraftforge.network.DualStackUtils.checkIPv6(p_290034_.getAddress());
-+ p_290031_.activationHandler = net.minecraftforge.network.NetworkHooks::registerClientLoginChannel;
++ p_290031_.activationHandler = net.minecraftforge.network.NetworkRegistry::onConnectionStart;
Class extends SocketChannel> oclass;
EventLoopGroup eventloopgroup;
if (Epoll.isAvailable() && p_290035_) {
+@@ -465,7 +_,14 @@
+ PacketFlow packetflow = p_265104_.m_178539_();
+ AttributeKey> attributekey = m_295397_(p_265104_);
+ AttributeKey> attributekey1 = m_295397_(packetflow);
+- p_265436_.addLast("splitter", new Varint21FrameDecoder(p_299297_)).addLast("decoder", new PacketDecoder(attributekey)).addLast("prepender", new Varint21LengthFieldPrepender()).addLast("encoder", new PacketEncoder(attributekey1)).addLast("unbundler", new PacketBundleUnpacker(attributekey1)).addLast("bundler", new PacketBundlePacker(attributekey));
++ p_265436_
++ .addLast("splitter", new Varint21FrameDecoder(p_299297_))
++ .addLast("decoder", new PacketDecoder(attributekey))
++ .addLast("prepender", new Varint21LengthFieldPrepender())
++ .addLast("encoder", new PacketEncoder(attributekey1))
++ .addLast("unbundler", new PacketBundleUnpacker(attributekey1))
++ .addLast("bundler", new PacketBundlePacker(attributekey)
++ );
+ }
+
+ public void m_295611_(ChannelPipeline p_300754_) {
@@ -485,6 +_,7 @@
public static Connection m_129493_(SocketAddress p_129494_) {
final Connection connection = new Connection(PacketFlow.CLIENTBOUND);
-+ connection.activationHandler = net.minecraftforge.network.NetworkHooks::registerClientLoginChannel;
++ connection.activationHandler = net.minecraftforge.network.NetworkRegistry::onConnectionStart;
(new Bootstrap()).group(f_129464_.get()).handler(new ChannelInitializer() {
protected void initChannel(Channel p_129557_) {
Connection.m_294111_(p_129557_);
@@ -52,8 +98,8 @@
+ return this.f_129468_;
+ }
+
-+ public PacketFlow getDirection() {
-+ return this.f_129466_;
++ public ConnectionProtocol getProtocol() {
++ return this.f_129468_.attr(m_295397_(m_178314_())).get().m_295191_();
}
public void m_292855_(SampleLogger p_300126_) {
diff --git a/patches/minecraft/net/minecraft/network/ConnectionProtocol.java.patch b/patches/minecraft/net/minecraft/network/ConnectionProtocol.java.patch
new file mode 100644
index 0000000000..ced1fce361
--- /dev/null
+++ b/patches/minecraft/net/minecraft/network/ConnectionProtocol.java.patch
@@ -0,0 +1,240 @@
+--- a/net/minecraft/network/ConnectionProtocol.java
++++ b/net/minecraft/network/ConnectionProtocol.java
+@@ -212,11 +_,232 @@
+ import org.slf4j.Logger;
+
+ public enum ConnectionProtocol {
+- HANDSHAKING("handshake", m_129600_().m_129625_(PacketFlow.CLIENTBOUND, new ConnectionProtocol.PacketSet()).m_129625_(PacketFlow.SERVERBOUND, (new ConnectionProtocol.PacketSet()).m_178330_(ClientIntentionPacket.class, ClientIntentionPacket::new))),
+- PLAY("play", m_129600_().m_129625_(PacketFlow.CLIENTBOUND, (new ConnectionProtocol.PacketSet()).m_264543_(ClientboundBundlePacket.class, ClientboundBundlePacket::new).m_178330_(ClientboundAddEntityPacket.class, ClientboundAddEntityPacket::new).m_178330_(ClientboundAddExperienceOrbPacket.class, ClientboundAddExperienceOrbPacket::new).m_178330_(ClientboundAddPlayerPacket.class, ClientboundAddPlayerPacket::new).m_178330_(ClientboundAnimatePacket.class, ClientboundAnimatePacket::new).m_178330_(ClientboundAwardStatsPacket.class, ClientboundAwardStatsPacket::new).m_178330_(ClientboundBlockChangedAckPacket.class, ClientboundBlockChangedAckPacket::new).m_178330_(ClientboundBlockDestructionPacket.class, ClientboundBlockDestructionPacket::new).m_178330_(ClientboundBlockEntityDataPacket.class, ClientboundBlockEntityDataPacket::new).m_178330_(ClientboundBlockEventPacket.class, ClientboundBlockEventPacket::new).m_178330_(ClientboundBlockUpdatePacket.class, ClientboundBlockUpdatePacket::new).m_178330_(ClientboundBossEventPacket.class, ClientboundBossEventPacket::new).m_178330_(ClientboundChangeDifficultyPacket.class, ClientboundChangeDifficultyPacket::new).m_178330_(ClientboundChunkBatchFinishedPacket.class, ClientboundChunkBatchFinishedPacket::new).m_178330_(ClientboundChunkBatchStartPacket.class, ClientboundChunkBatchStartPacket::new).m_178330_(ClientboundChunksBiomesPacket.class, ClientboundChunksBiomesPacket::new).m_178330_(ClientboundClearTitlesPacket.class, ClientboundClearTitlesPacket::new).m_178330_(ClientboundCommandSuggestionsPacket.class, ClientboundCommandSuggestionsPacket::new).m_178330_(ClientboundCommandsPacket.class, ClientboundCommandsPacket::new).m_178330_(ClientboundContainerClosePacket.class, ClientboundContainerClosePacket::new).m_178330_(ClientboundContainerSetContentPacket.class, ClientboundContainerSetContentPacket::new).m_178330_(ClientboundContainerSetDataPacket.class, ClientboundContainerSetDataPacket::new).m_178330_(ClientboundContainerSetSlotPacket.class, ClientboundContainerSetSlotPacket::new).m_178330_(ClientboundCooldownPacket.class, ClientboundCooldownPacket::new).m_178330_(ClientboundCustomChatCompletionsPacket.class, ClientboundCustomChatCompletionsPacket::new).m_178330_(ClientboundCustomPayloadPacket.class, ClientboundCustomPayloadPacket::new).m_178330_(ClientboundDamageEventPacket.class, ClientboundDamageEventPacket::new).m_178330_(ClientboundDeleteChatPacket.class, ClientboundDeleteChatPacket::new).m_178330_(ClientboundDisconnectPacket.class, ClientboundDisconnectPacket::new).m_178330_(ClientboundDisguisedChatPacket.class, ClientboundDisguisedChatPacket::new).m_178330_(ClientboundEntityEventPacket.class, ClientboundEntityEventPacket::new).m_178330_(ClientboundExplodePacket.class, ClientboundExplodePacket::new).m_178330_(ClientboundForgetLevelChunkPacket.class, ClientboundForgetLevelChunkPacket::new).m_178330_(ClientboundGameEventPacket.class, ClientboundGameEventPacket::new).m_178330_(ClientboundHorseScreenOpenPacket.class, ClientboundHorseScreenOpenPacket::new).m_178330_(ClientboundHurtAnimationPacket.class, ClientboundHurtAnimationPacket::new).m_178330_(ClientboundInitializeBorderPacket.class, ClientboundInitializeBorderPacket::new).m_178330_(ClientboundKeepAlivePacket.class, ClientboundKeepAlivePacket::new).m_178330_(ClientboundLevelChunkWithLightPacket.class, ClientboundLevelChunkWithLightPacket::new).m_178330_(ClientboundLevelEventPacket.class, ClientboundLevelEventPacket::new).m_178330_(ClientboundLevelParticlesPacket.class, ClientboundLevelParticlesPacket::new).m_178330_(ClientboundLightUpdatePacket.class, ClientboundLightUpdatePacket::new).m_178330_(ClientboundLoginPacket.class, ClientboundLoginPacket::new).m_178330_(ClientboundMapItemDataPacket.class, ClientboundMapItemDataPacket::new).m_178330_(ClientboundMerchantOffersPacket.class, ClientboundMerchantOffersPacket::new).m_178330_(ClientboundMoveEntityPacket.Pos.class, ClientboundMoveEntityPacket.Pos::m_179000_).m_178330_(ClientboundMoveEntityPacket.PosRot.class, ClientboundMoveEntityPacket.PosRot::m_179002_).m_178330_(ClientboundMoveEntityPacket.Rot.class, ClientboundMoveEntityPacket.Rot::m_179004_).m_178330_(ClientboundMoveVehiclePacket.class, ClientboundMoveVehiclePacket::new).m_178330_(ClientboundOpenBookPacket.class, ClientboundOpenBookPacket::new).m_178330_(ClientboundOpenScreenPacket.class, ClientboundOpenScreenPacket::new).m_178330_(ClientboundOpenSignEditorPacket.class, ClientboundOpenSignEditorPacket::new).m_178330_(ClientboundPingPacket.class, ClientboundPingPacket::new).m_178330_(ClientboundPongResponsePacket.class, ClientboundPongResponsePacket::new).m_178330_(ClientboundPlaceGhostRecipePacket.class, ClientboundPlaceGhostRecipePacket::new).m_178330_(ClientboundPlayerAbilitiesPacket.class, ClientboundPlayerAbilitiesPacket::new).m_178330_(ClientboundPlayerChatPacket.class, ClientboundPlayerChatPacket::new).m_178330_(ClientboundPlayerCombatEndPacket.class, ClientboundPlayerCombatEndPacket::new).m_178330_(ClientboundPlayerCombatEnterPacket.class, ClientboundPlayerCombatEnterPacket::new).m_178330_(ClientboundPlayerCombatKillPacket.class, ClientboundPlayerCombatKillPacket::new).m_178330_(ClientboundPlayerInfoRemovePacket.class, ClientboundPlayerInfoRemovePacket::new).m_178330_(ClientboundPlayerInfoUpdatePacket.class, ClientboundPlayerInfoUpdatePacket::new).m_178330_(ClientboundPlayerLookAtPacket.class, ClientboundPlayerLookAtPacket::new).m_178330_(ClientboundPlayerPositionPacket.class, ClientboundPlayerPositionPacket::new).m_178330_(ClientboundRecipePacket.class, ClientboundRecipePacket::new).m_178330_(ClientboundRemoveEntitiesPacket.class, ClientboundRemoveEntitiesPacket::new).m_178330_(ClientboundRemoveMobEffectPacket.class, ClientboundRemoveMobEffectPacket::new).m_178330_(ClientboundResourcePackPacket.class, ClientboundResourcePackPacket::new).m_178330_(ClientboundRespawnPacket.class, ClientboundRespawnPacket::new).m_178330_(ClientboundRotateHeadPacket.class, ClientboundRotateHeadPacket::new).m_178330_(ClientboundSectionBlocksUpdatePacket.class, ClientboundSectionBlocksUpdatePacket::new).m_178330_(ClientboundSelectAdvancementsTabPacket.class, ClientboundSelectAdvancementsTabPacket::new).m_178330_(ClientboundServerDataPacket.class, ClientboundServerDataPacket::new).m_178330_(ClientboundSetActionBarTextPacket.class, ClientboundSetActionBarTextPacket::new).m_178330_(ClientboundSetBorderCenterPacket.class, ClientboundSetBorderCenterPacket::new).m_178330_(ClientboundSetBorderLerpSizePacket.class, ClientboundSetBorderLerpSizePacket::new).m_178330_(ClientboundSetBorderSizePacket.class, ClientboundSetBorderSizePacket::new).m_178330_(ClientboundSetBorderWarningDelayPacket.class, ClientboundSetBorderWarningDelayPacket::new).m_178330_(ClientboundSetBorderWarningDistancePacket.class, ClientboundSetBorderWarningDistancePacket::new).m_178330_(ClientboundSetCameraPacket.class, ClientboundSetCameraPacket::new).m_178330_(ClientboundSetCarriedItemPacket.class, ClientboundSetCarriedItemPacket::new).m_178330_(ClientboundSetChunkCacheCenterPacket.class, ClientboundSetChunkCacheCenterPacket::new).m_178330_(ClientboundSetChunkCacheRadiusPacket.class, ClientboundSetChunkCacheRadiusPacket::new).m_178330_(ClientboundSetDefaultSpawnPositionPacket.class, ClientboundSetDefaultSpawnPositionPacket::new).m_178330_(ClientboundSetDisplayObjectivePacket.class, ClientboundSetDisplayObjectivePacket::new).m_178330_(ClientboundSetEntityDataPacket.class, ClientboundSetEntityDataPacket::new).m_178330_(ClientboundSetEntityLinkPacket.class, ClientboundSetEntityLinkPacket::new).m_178330_(ClientboundSetEntityMotionPacket.class, ClientboundSetEntityMotionPacket::new).m_178330_(ClientboundSetEquipmentPacket.class, ClientboundSetEquipmentPacket::new).m_178330_(ClientboundSetExperiencePacket.class, ClientboundSetExperiencePacket::new).m_178330_(ClientboundSetHealthPacket.class, ClientboundSetHealthPacket::new).m_178330_(ClientboundSetObjectivePacket.class, ClientboundSetObjectivePacket::new).m_178330_(ClientboundSetPassengersPacket.class, ClientboundSetPassengersPacket::new).m_178330_(ClientboundSetPlayerTeamPacket.class, ClientboundSetPlayerTeamPacket::new).m_178330_(ClientboundSetScorePacket.class, ClientboundSetScorePacket::new).m_178330_(ClientboundSetSimulationDistancePacket.class, ClientboundSetSimulationDistancePacket::new).m_178330_(ClientboundSetSubtitleTextPacket.class, ClientboundSetSubtitleTextPacket::new).m_178330_(ClientboundSetTimePacket.class, ClientboundSetTimePacket::new).m_178330_(ClientboundSetTitleTextPacket.class, ClientboundSetTitleTextPacket::new).m_178330_(ClientboundSetTitlesAnimationPacket.class, ClientboundSetTitlesAnimationPacket::new).m_178330_(ClientboundSoundEntityPacket.class, ClientboundSoundEntityPacket::new).m_178330_(ClientboundSoundPacket.class, ClientboundSoundPacket::new).m_178330_(ClientboundStartConfigurationPacket.class, ClientboundStartConfigurationPacket::new).m_178330_(ClientboundStopSoundPacket.class, ClientboundStopSoundPacket::new).m_178330_(ClientboundSystemChatPacket.class, ClientboundSystemChatPacket::new).m_178330_(ClientboundTabListPacket.class, ClientboundTabListPacket::new).m_178330_(ClientboundTagQueryPacket.class, ClientboundTagQueryPacket::new).m_178330_(ClientboundTakeItemEntityPacket.class, ClientboundTakeItemEntityPacket::new).m_178330_(ClientboundTeleportEntityPacket.class, ClientboundTeleportEntityPacket::new).m_178330_(ClientboundUpdateAdvancementsPacket.class, ClientboundUpdateAdvancementsPacket::new).m_178330_(ClientboundUpdateAttributesPacket.class, ClientboundUpdateAttributesPacket::new).m_178330_(ClientboundUpdateMobEffectPacket.class, ClientboundUpdateMobEffectPacket::new).m_178330_(ClientboundUpdateRecipesPacket.class, ClientboundUpdateRecipesPacket::new).m_178330_(ClientboundUpdateTagsPacket.class, ClientboundUpdateTagsPacket::new)).m_129625_(PacketFlow.SERVERBOUND, (new ConnectionProtocol.PacketSet()).m_178330_(ServerboundAcceptTeleportationPacket.class, ServerboundAcceptTeleportationPacket::new).m_178330_(ServerboundBlockEntityTagQuery.class, ServerboundBlockEntityTagQuery::new).m_178330_(ServerboundChangeDifficultyPacket.class, ServerboundChangeDifficultyPacket::new).m_178330_(ServerboundChatAckPacket.class, ServerboundChatAckPacket::new).m_178330_(ServerboundChatCommandPacket.class, ServerboundChatCommandPacket::new).m_178330_(ServerboundChatPacket.class, ServerboundChatPacket::new).m_178330_(ServerboundChatSessionUpdatePacket.class, ServerboundChatSessionUpdatePacket::new).m_178330_(ServerboundChunkBatchReceivedPacket.class, ServerboundChunkBatchReceivedPacket::new).m_178330_(ServerboundClientCommandPacket.class, ServerboundClientCommandPacket::new).m_178330_(ServerboundClientInformationPacket.class, ServerboundClientInformationPacket::new).m_178330_(ServerboundCommandSuggestionPacket.class, ServerboundCommandSuggestionPacket::new).m_178330_(ServerboundConfigurationAcknowledgedPacket.class, ServerboundConfigurationAcknowledgedPacket::new).m_178330_(ServerboundContainerButtonClickPacket.class, ServerboundContainerButtonClickPacket::new).m_178330_(ServerboundContainerClickPacket.class, ServerboundContainerClickPacket::new).m_178330_(ServerboundContainerClosePacket.class, ServerboundContainerClosePacket::new).m_178330_(ServerboundCustomPayloadPacket.class, ServerboundCustomPayloadPacket::new).m_178330_(ServerboundEditBookPacket.class, ServerboundEditBookPacket::new).m_178330_(ServerboundEntityTagQuery.class, ServerboundEntityTagQuery::new).m_178330_(ServerboundInteractPacket.class, ServerboundInteractPacket::new).m_178330_(ServerboundJigsawGeneratePacket.class, ServerboundJigsawGeneratePacket::new).m_178330_(ServerboundKeepAlivePacket.class, ServerboundKeepAlivePacket::new).m_178330_(ServerboundLockDifficultyPacket.class, ServerboundLockDifficultyPacket::new).m_178330_(ServerboundMovePlayerPacket.Pos.class, ServerboundMovePlayerPacket.Pos::m_179685_).m_178330_(ServerboundMovePlayerPacket.PosRot.class, ServerboundMovePlayerPacket.PosRot::m_179687_).m_178330_(ServerboundMovePlayerPacket.Rot.class, ServerboundMovePlayerPacket.Rot::m_179689_).m_178330_(ServerboundMovePlayerPacket.StatusOnly.class, ServerboundMovePlayerPacket.StatusOnly::m_179697_).m_178330_(ServerboundMoveVehiclePacket.class, ServerboundMoveVehiclePacket::new).m_178330_(ServerboundPaddleBoatPacket.class, ServerboundPaddleBoatPacket::new).m_178330_(ServerboundPickItemPacket.class, ServerboundPickItemPacket::new).m_178330_(ServerboundPingRequestPacket.class, ServerboundPingRequestPacket::new).m_178330_(ServerboundPlaceRecipePacket.class, ServerboundPlaceRecipePacket::new).m_178330_(ServerboundPlayerAbilitiesPacket.class, ServerboundPlayerAbilitiesPacket::new).m_178330_(ServerboundPlayerActionPacket.class, ServerboundPlayerActionPacket::new).m_178330_(ServerboundPlayerCommandPacket.class, ServerboundPlayerCommandPacket::new).m_178330_(ServerboundPlayerInputPacket.class, ServerboundPlayerInputPacket::new).m_178330_(ServerboundPongPacket.class, ServerboundPongPacket::new).m_178330_(ServerboundRecipeBookChangeSettingsPacket.class, ServerboundRecipeBookChangeSettingsPacket::new).m_178330_(ServerboundRecipeBookSeenRecipePacket.class, ServerboundRecipeBookSeenRecipePacket::new).m_178330_(ServerboundRenameItemPacket.class, ServerboundRenameItemPacket::new).m_178330_(ServerboundResourcePackPacket.class, ServerboundResourcePackPacket::new).m_178330_(ServerboundSeenAdvancementsPacket.class, ServerboundSeenAdvancementsPacket::new).m_178330_(ServerboundSelectTradePacket.class, ServerboundSelectTradePacket::new).m_178330_(ServerboundSetBeaconPacket.class, ServerboundSetBeaconPacket::new).m_178330_(ServerboundSetCarriedItemPacket.class, ServerboundSetCarriedItemPacket::new).m_178330_(ServerboundSetCommandBlockPacket.class, ServerboundSetCommandBlockPacket::new).m_178330_(ServerboundSetCommandMinecartPacket.class, ServerboundSetCommandMinecartPacket::new).m_178330_(ServerboundSetCreativeModeSlotPacket.class, ServerboundSetCreativeModeSlotPacket::new).m_178330_(ServerboundSetJigsawBlockPacket.class, ServerboundSetJigsawBlockPacket::new).m_178330_(ServerboundSetStructureBlockPacket.class, ServerboundSetStructureBlockPacket::new).m_178330_(ServerboundSignUpdatePacket.class, ServerboundSignUpdatePacket::new).m_178330_(ServerboundSwingPacket.class, ServerboundSwingPacket::new).m_178330_(ServerboundTeleportToEntityPacket.class, ServerboundTeleportToEntityPacket::new).m_178330_(ServerboundUseItemOnPacket.class, ServerboundUseItemOnPacket::new).m_178330_(ServerboundUseItemPacket.class, ServerboundUseItemPacket::new))),
+- STATUS("status", m_129600_().m_129625_(PacketFlow.SERVERBOUND, (new ConnectionProtocol.PacketSet()).m_178330_(ServerboundStatusRequestPacket.class, ServerboundStatusRequestPacket::new).m_178330_(ServerboundPingRequestPacket.class, ServerboundPingRequestPacket::new)).m_129625_(PacketFlow.CLIENTBOUND, (new ConnectionProtocol.PacketSet()).m_178330_(ClientboundStatusResponsePacket.class, ClientboundStatusResponsePacket::new).m_178330_(ClientboundPongResponsePacket.class, ClientboundPongResponsePacket::new))),
+- LOGIN("login", m_129600_().m_129625_(PacketFlow.CLIENTBOUND, (new ConnectionProtocol.PacketSet()).m_178330_(ClientboundLoginDisconnectPacket.class, ClientboundLoginDisconnectPacket::new).m_178330_(ClientboundHelloPacket.class, ClientboundHelloPacket::new).m_178330_(ClientboundGameProfilePacket.class, ClientboundGameProfilePacket::new).m_178330_(ClientboundLoginCompressionPacket.class, ClientboundLoginCompressionPacket::new).m_178330_(ClientboundCustomQueryPacket.class, ClientboundCustomQueryPacket::new)).m_129625_(PacketFlow.SERVERBOUND, (new ConnectionProtocol.PacketSet()).m_178330_(ServerboundHelloPacket.class, ServerboundHelloPacket::new).m_178330_(ServerboundKeyPacket.class, ServerboundKeyPacket::new).m_178330_(ServerboundCustomQueryAnswerPacket.class, ServerboundCustomQueryAnswerPacket::m_294367_).m_178330_(ServerboundLoginAcknowledgedPacket.class, ServerboundLoginAcknowledgedPacket::new))),
+- CONFIGURATION("configuration", m_129600_().m_129625_(PacketFlow.CLIENTBOUND, (new ConnectionProtocol.PacketSet()).m_178330_(ClientboundCustomPayloadPacket.class, ClientboundCustomPayloadPacket::new).m_178330_(ClientboundDisconnectPacket.class, ClientboundDisconnectPacket::new).m_178330_(ClientboundFinishConfigurationPacket.class, ClientboundFinishConfigurationPacket::new).m_178330_(ClientboundKeepAlivePacket.class, ClientboundKeepAlivePacket::new).m_178330_(ClientboundPingPacket.class, ClientboundPingPacket::new).m_178330_(ClientboundRegistryDataPacket.class, ClientboundRegistryDataPacket::new).m_178330_(ClientboundResourcePackPacket.class, ClientboundResourcePackPacket::new).m_178330_(ClientboundUpdateEnabledFeaturesPacket.class, ClientboundUpdateEnabledFeaturesPacket::new).m_178330_(ClientboundUpdateTagsPacket.class, ClientboundUpdateTagsPacket::new)).m_129625_(PacketFlow.SERVERBOUND, (new ConnectionProtocol.PacketSet()).m_178330_(ServerboundClientInformationPacket.class, ServerboundClientInformationPacket::new).m_178330_(ServerboundCustomPayloadPacket.class, ServerboundCustomPayloadPacket::new).m_178330_(ServerboundFinishConfigurationPacket.class, ServerboundFinishConfigurationPacket::new).m_178330_(ServerboundKeepAlivePacket.class, ServerboundKeepAlivePacket::new).m_178330_(ServerboundPongPacket.class, ServerboundPongPacket::new).m_178330_(ServerboundResourcePackPacket.class, ServerboundResourcePackPacket::new)));
++ HANDSHAKING("handshake", m_129600_()
++ .m_129625_(PacketFlow.CLIENTBOUND, new ConnectionProtocol.PacketSet<>())
++ .m_129625_(PacketFlow.SERVERBOUND, (new ConnectionProtocol.PacketSet())
++ .m_178330_(ClientIntentionPacket.class, ClientIntentionPacket::new)
++ )
++ ),
++ PLAY("play", m_129600_()
++ .m_129625_(PacketFlow.CLIENTBOUND, (new ConnectionProtocol.PacketSet())
++ .m_264543_(ClientboundBundlePacket.class, ClientboundBundlePacket::new)
++ .m_178330_(ClientboundAddEntityPacket.class, ClientboundAddEntityPacket::new)
++ .m_178330_(ClientboundAddExperienceOrbPacket.class, ClientboundAddExperienceOrbPacket::new)
++ .m_178330_(ClientboundAddPlayerPacket.class, ClientboundAddPlayerPacket::new)
++ .m_178330_(ClientboundAnimatePacket.class, ClientboundAnimatePacket::new)
++ .m_178330_(ClientboundAwardStatsPacket.class, ClientboundAwardStatsPacket::new)
++ .m_178330_(ClientboundBlockChangedAckPacket.class, ClientboundBlockChangedAckPacket::new)
++ .m_178330_(ClientboundBlockDestructionPacket.class, ClientboundBlockDestructionPacket::new)
++ .m_178330_(ClientboundBlockEntityDataPacket.class, ClientboundBlockEntityDataPacket::new)
++ .m_178330_(ClientboundBlockEventPacket.class, ClientboundBlockEventPacket::new)
++ .m_178330_(ClientboundBlockUpdatePacket.class, ClientboundBlockUpdatePacket::new)
++ .m_178330_(ClientboundBossEventPacket.class, ClientboundBossEventPacket::new)
++ .m_178330_(ClientboundChangeDifficultyPacket.class, ClientboundChangeDifficultyPacket::new)
++ .m_178330_(ClientboundChunkBatchFinishedPacket.class, ClientboundChunkBatchFinishedPacket::new)
++ .m_178330_(ClientboundChunkBatchStartPacket.class, ClientboundChunkBatchStartPacket::new)
++ .m_178330_(ClientboundChunksBiomesPacket.class, ClientboundChunksBiomesPacket::new)
++ .m_178330_(ClientboundClearTitlesPacket.class, ClientboundClearTitlesPacket::new)
++ .m_178330_(ClientboundCommandSuggestionsPacket.class, ClientboundCommandSuggestionsPacket::new)
++ .m_178330_(ClientboundCommandsPacket.class, ClientboundCommandsPacket::new)
++ .m_178330_(ClientboundContainerClosePacket.class, ClientboundContainerClosePacket::new)
++ .m_178330_(ClientboundContainerSetContentPacket.class, ClientboundContainerSetContentPacket::new)
++ .m_178330_(ClientboundContainerSetDataPacket.class, ClientboundContainerSetDataPacket::new)
++ .m_178330_(ClientboundContainerSetSlotPacket.class, ClientboundContainerSetSlotPacket::new)
++ .m_178330_(ClientboundCooldownPacket.class, ClientboundCooldownPacket::new)
++ .m_178330_(ClientboundCustomChatCompletionsPacket.class, ClientboundCustomChatCompletionsPacket::new)
++ .m_178330_(ClientboundCustomPayloadPacket.class, ClientboundCustomPayloadPacket::new)
++ .m_178330_(ClientboundDamageEventPacket.class, ClientboundDamageEventPacket::new)
++ .m_178330_(ClientboundDeleteChatPacket.class, ClientboundDeleteChatPacket::new)
++ .m_178330_(ClientboundDisconnectPacket.class, ClientboundDisconnectPacket::new)
++ .m_178330_(ClientboundDisguisedChatPacket.class, ClientboundDisguisedChatPacket::new)
++ .m_178330_(ClientboundEntityEventPacket.class, ClientboundEntityEventPacket::new)
++ .m_178330_(ClientboundExplodePacket.class, ClientboundExplodePacket::new)
++ .m_178330_(ClientboundForgetLevelChunkPacket.class, ClientboundForgetLevelChunkPacket::new)
++ .m_178330_(ClientboundGameEventPacket.class, ClientboundGameEventPacket::new)
++ .m_178330_(ClientboundHorseScreenOpenPacket.class, ClientboundHorseScreenOpenPacket::new)
++ .m_178330_(ClientboundHurtAnimationPacket.class, ClientboundHurtAnimationPacket::new)
++ .m_178330_(ClientboundInitializeBorderPacket.class, ClientboundInitializeBorderPacket::new)
++ .m_178330_(ClientboundKeepAlivePacket.class, ClientboundKeepAlivePacket::new)
++ .m_178330_(ClientboundLevelChunkWithLightPacket.class, ClientboundLevelChunkWithLightPacket::new)
++ .m_178330_(ClientboundLevelEventPacket.class, ClientboundLevelEventPacket::new)
++ .m_178330_(ClientboundLevelParticlesPacket.class, ClientboundLevelParticlesPacket::new)
++ .m_178330_(ClientboundLightUpdatePacket.class, ClientboundLightUpdatePacket::new)
++ .m_178330_(ClientboundLoginPacket.class, ClientboundLoginPacket::new)
++ .m_178330_(ClientboundMapItemDataPacket.class, ClientboundMapItemDataPacket::new)
++ .m_178330_(ClientboundMerchantOffersPacket.class, ClientboundMerchantOffersPacket::new)
++ .m_178330_(ClientboundMoveEntityPacket.Pos.class, ClientboundMoveEntityPacket.Pos::m_179000_)
++ .m_178330_(ClientboundMoveEntityPacket.PosRot.class, ClientboundMoveEntityPacket.PosRot::m_179002_)
++ .m_178330_(ClientboundMoveEntityPacket.Rot.class, ClientboundMoveEntityPacket.Rot::m_179004_)
++ .m_178330_(ClientboundMoveVehiclePacket.class, ClientboundMoveVehiclePacket::new)
++ .m_178330_(ClientboundOpenBookPacket.class, ClientboundOpenBookPacket::new)
++ .m_178330_(ClientboundOpenScreenPacket.class, ClientboundOpenScreenPacket::new)
++ .m_178330_(ClientboundOpenSignEditorPacket.class, ClientboundOpenSignEditorPacket::new)
++ .m_178330_(ClientboundPingPacket.class, ClientboundPingPacket::new)
++ .m_178330_(ClientboundPongResponsePacket.class, ClientboundPongResponsePacket::new)
++ .m_178330_(ClientboundPlaceGhostRecipePacket.class, ClientboundPlaceGhostRecipePacket::new)
++ .m_178330_(ClientboundPlayerAbilitiesPacket.class, ClientboundPlayerAbilitiesPacket::new)
++ .m_178330_(ClientboundPlayerChatPacket.class, ClientboundPlayerChatPacket::new)
++ .m_178330_(ClientboundPlayerCombatEndPacket.class, ClientboundPlayerCombatEndPacket::new)
++ .m_178330_(ClientboundPlayerCombatEnterPacket.class, ClientboundPlayerCombatEnterPacket::new)
++ .m_178330_(ClientboundPlayerCombatKillPacket.class, ClientboundPlayerCombatKillPacket::new)
++ .m_178330_(ClientboundPlayerInfoRemovePacket.class, ClientboundPlayerInfoRemovePacket::new)
++ .m_178330_(ClientboundPlayerInfoUpdatePacket.class, ClientboundPlayerInfoUpdatePacket::new)
++ .m_178330_(ClientboundPlayerLookAtPacket.class, ClientboundPlayerLookAtPacket::new)
++ .m_178330_(ClientboundPlayerPositionPacket.class, ClientboundPlayerPositionPacket::new)
++ .m_178330_(ClientboundRecipePacket.class, ClientboundRecipePacket::new)
++ .m_178330_(ClientboundRemoveEntitiesPacket.class, ClientboundRemoveEntitiesPacket::new)
++ .m_178330_(ClientboundRemoveMobEffectPacket.class, ClientboundRemoveMobEffectPacket::new)
++ .m_178330_(ClientboundResourcePackPacket.class, ClientboundResourcePackPacket::new)
++ .m_178330_(ClientboundRespawnPacket.class, ClientboundRespawnPacket::new)
++ .m_178330_(ClientboundRotateHeadPacket.class, ClientboundRotateHeadPacket::new)
++ .m_178330_(ClientboundSectionBlocksUpdatePacket.class, ClientboundSectionBlocksUpdatePacket::new)
++ .m_178330_(ClientboundSelectAdvancementsTabPacket.class, ClientboundSelectAdvancementsTabPacket::new)
++ .m_178330_(ClientboundServerDataPacket.class, ClientboundServerDataPacket::new)
++ .m_178330_(ClientboundSetActionBarTextPacket.class, ClientboundSetActionBarTextPacket::new)
++ .m_178330_(ClientboundSetBorderCenterPacket.class, ClientboundSetBorderCenterPacket::new)
++ .m_178330_(ClientboundSetBorderLerpSizePacket.class, ClientboundSetBorderLerpSizePacket::new)
++ .m_178330_(ClientboundSetBorderSizePacket.class, ClientboundSetBorderSizePacket::new)
++ .m_178330_(ClientboundSetBorderWarningDelayPacket.class, ClientboundSetBorderWarningDelayPacket::new)
++ .m_178330_(ClientboundSetBorderWarningDistancePacket.class, ClientboundSetBorderWarningDistancePacket::new)
++ .m_178330_(ClientboundSetCameraPacket.class, ClientboundSetCameraPacket::new)
++ .m_178330_(ClientboundSetCarriedItemPacket.class, ClientboundSetCarriedItemPacket::new)
++ .m_178330_(ClientboundSetChunkCacheCenterPacket.class, ClientboundSetChunkCacheCenterPacket::new)
++ .m_178330_(ClientboundSetChunkCacheRadiusPacket.class, ClientboundSetChunkCacheRadiusPacket::new)
++ .m_178330_(ClientboundSetDefaultSpawnPositionPacket.class, ClientboundSetDefaultSpawnPositionPacket::new)
++ .m_178330_(ClientboundSetDisplayObjectivePacket.class, ClientboundSetDisplayObjectivePacket::new)
++ .m_178330_(ClientboundSetEntityDataPacket.class, ClientboundSetEntityDataPacket::new)
++ .m_178330_(ClientboundSetEntityLinkPacket.class, ClientboundSetEntityLinkPacket::new)
++ .m_178330_(ClientboundSetEntityMotionPacket.class, ClientboundSetEntityMotionPacket::new)
++ .m_178330_(ClientboundSetEquipmentPacket.class, ClientboundSetEquipmentPacket::new)
++ .m_178330_(ClientboundSetExperiencePacket.class, ClientboundSetExperiencePacket::new)
++ .m_178330_(ClientboundSetHealthPacket.class, ClientboundSetHealthPacket::new)
++ .m_178330_(ClientboundSetObjectivePacket.class, ClientboundSetObjectivePacket::new)
++ .m_178330_(ClientboundSetPassengersPacket.class, ClientboundSetPassengersPacket::new)
++ .m_178330_(ClientboundSetPlayerTeamPacket.class, ClientboundSetPlayerTeamPacket::new)
++ .m_178330_(ClientboundSetScorePacket.class, ClientboundSetScorePacket::new)
++ .m_178330_(ClientboundSetSimulationDistancePacket.class, ClientboundSetSimulationDistancePacket::new)
++ .m_178330_(ClientboundSetSubtitleTextPacket.class, ClientboundSetSubtitleTextPacket::new)
++ .m_178330_(ClientboundSetTimePacket.class, ClientboundSetTimePacket::new)
++ .m_178330_(ClientboundSetTitleTextPacket.class, ClientboundSetTitleTextPacket::new)
++ .m_178330_(ClientboundSetTitlesAnimationPacket.class, ClientboundSetTitlesAnimationPacket::new)
++ .m_178330_(ClientboundSoundEntityPacket.class, ClientboundSoundEntityPacket::new)
++ .m_178330_(ClientboundSoundPacket.class, ClientboundSoundPacket::new)
++ .m_178330_(ClientboundStartConfigurationPacket.class, ClientboundStartConfigurationPacket::new)
++ .m_178330_(ClientboundStopSoundPacket.class, ClientboundStopSoundPacket::new)
++ .m_178330_(ClientboundSystemChatPacket.class, ClientboundSystemChatPacket::new)
++ .m_178330_(ClientboundTabListPacket.class, ClientboundTabListPacket::new)
++ .m_178330_(ClientboundTagQueryPacket.class, ClientboundTagQueryPacket::new)
++ .m_178330_(ClientboundTakeItemEntityPacket.class, ClientboundTakeItemEntityPacket::new)
++ .m_178330_(ClientboundTeleportEntityPacket.class, ClientboundTeleportEntityPacket::new)
++ .m_178330_(ClientboundUpdateAdvancementsPacket.class, ClientboundUpdateAdvancementsPacket::new)
++ .m_178330_(ClientboundUpdateAttributesPacket.class, ClientboundUpdateAttributesPacket::new)
++ .m_178330_(ClientboundUpdateMobEffectPacket.class, ClientboundUpdateMobEffectPacket::new)
++ .m_178330_(ClientboundUpdateRecipesPacket.class, ClientboundUpdateRecipesPacket::new)
++ .m_178330_(ClientboundUpdateTagsPacket.class, ClientboundUpdateTagsPacket::new)
++ )
++ .m_129625_(PacketFlow.SERVERBOUND, (new ConnectionProtocol.PacketSet())
++ .m_178330_(ServerboundAcceptTeleportationPacket.class, ServerboundAcceptTeleportationPacket::new)
++ .m_178330_(ServerboundBlockEntityTagQuery.class, ServerboundBlockEntityTagQuery::new)
++ .m_178330_(ServerboundChangeDifficultyPacket.class, ServerboundChangeDifficultyPacket::new)
++ .m_178330_(ServerboundChatAckPacket.class, ServerboundChatAckPacket::new)
++ .m_178330_(ServerboundChatCommandPacket.class, ServerboundChatCommandPacket::new)
++ .m_178330_(ServerboundChatPacket.class, ServerboundChatPacket::new)
++ .m_178330_(ServerboundChatSessionUpdatePacket.class, ServerboundChatSessionUpdatePacket::new)
++ .m_178330_(ServerboundChunkBatchReceivedPacket.class, ServerboundChunkBatchReceivedPacket::new)
++ .m_178330_(ServerboundClientCommandPacket.class, ServerboundClientCommandPacket::new)
++ .m_178330_(ServerboundClientInformationPacket.class, ServerboundClientInformationPacket::new)
++ .m_178330_(ServerboundCommandSuggestionPacket.class, ServerboundCommandSuggestionPacket::new)
++ .m_178330_(ServerboundConfigurationAcknowledgedPacket.class, ServerboundConfigurationAcknowledgedPacket::new)
++ .m_178330_(ServerboundContainerButtonClickPacket.class, ServerboundContainerButtonClickPacket::new)
++ .m_178330_(ServerboundContainerClickPacket.class, ServerboundContainerClickPacket::new)
++ .m_178330_(ServerboundContainerClosePacket.class, ServerboundContainerClosePacket::new)
++ .m_178330_(ServerboundCustomPayloadPacket.class, ServerboundCustomPayloadPacket::new)
++ .m_178330_(ServerboundEditBookPacket.class, ServerboundEditBookPacket::new)
++ .m_178330_(ServerboundEntityTagQuery.class, ServerboundEntityTagQuery::new)
++ .m_178330_(ServerboundInteractPacket.class, ServerboundInteractPacket::new)
++ .m_178330_(ServerboundJigsawGeneratePacket.class, ServerboundJigsawGeneratePacket::new)
++ .m_178330_(ServerboundKeepAlivePacket.class, ServerboundKeepAlivePacket::new)
++ .m_178330_(ServerboundLockDifficultyPacket.class, ServerboundLockDifficultyPacket::new)
++ .m_178330_(ServerboundMovePlayerPacket.Pos.class, ServerboundMovePlayerPacket.Pos::m_179685_)
++ .m_178330_(ServerboundMovePlayerPacket.PosRot.class, ServerboundMovePlayerPacket.PosRot::m_179687_)
++ .m_178330_(ServerboundMovePlayerPacket.Rot.class, ServerboundMovePlayerPacket.Rot::m_179689_)
++ .m_178330_(ServerboundMovePlayerPacket.StatusOnly.class, ServerboundMovePlayerPacket.StatusOnly::m_179697_)
++ .m_178330_(ServerboundMoveVehiclePacket.class, ServerboundMoveVehiclePacket::new)
++ .m_178330_(ServerboundPaddleBoatPacket.class, ServerboundPaddleBoatPacket::new)
++ .m_178330_(ServerboundPickItemPacket.class, ServerboundPickItemPacket::new)
++ .m_178330_(ServerboundPingRequestPacket.class, ServerboundPingRequestPacket::new)
++ .m_178330_(ServerboundPlaceRecipePacket.class, ServerboundPlaceRecipePacket::new)
++ .m_178330_(ServerboundPlayerAbilitiesPacket.class, ServerboundPlayerAbilitiesPacket::new)
++ .m_178330_(ServerboundPlayerActionPacket.class, ServerboundPlayerActionPacket::new)
++ .m_178330_(ServerboundPlayerCommandPacket.class, ServerboundPlayerCommandPacket::new)
++ .m_178330_(ServerboundPlayerInputPacket.class, ServerboundPlayerInputPacket::new)
++ .m_178330_(ServerboundPongPacket.class, ServerboundPongPacket::new)
++ .m_178330_(ServerboundRecipeBookChangeSettingsPacket.class, ServerboundRecipeBookChangeSettingsPacket::new)
++ .m_178330_(ServerboundRecipeBookSeenRecipePacket.class, ServerboundRecipeBookSeenRecipePacket::new)
++ .m_178330_(ServerboundRenameItemPacket.class, ServerboundRenameItemPacket::new)
++ .m_178330_(ServerboundResourcePackPacket.class, ServerboundResourcePackPacket::new)
++ .m_178330_(ServerboundSeenAdvancementsPacket.class, ServerboundSeenAdvancementsPacket::new)
++ .m_178330_(ServerboundSelectTradePacket.class, ServerboundSelectTradePacket::new)
++ .m_178330_(ServerboundSetBeaconPacket.class, ServerboundSetBeaconPacket::new)
++ .m_178330_(ServerboundSetCarriedItemPacket.class, ServerboundSetCarriedItemPacket::new)
++ .m_178330_(ServerboundSetCommandBlockPacket.class, ServerboundSetCommandBlockPacket::new)
++ .m_178330_(ServerboundSetCommandMinecartPacket.class, ServerboundSetCommandMinecartPacket::new)
++ .m_178330_(ServerboundSetCreativeModeSlotPacket.class, ServerboundSetCreativeModeSlotPacket::new)
++ .m_178330_(ServerboundSetJigsawBlockPacket.class, ServerboundSetJigsawBlockPacket::new)
++ .m_178330_(ServerboundSetStructureBlockPacket.class, ServerboundSetStructureBlockPacket::new)
++ .m_178330_(ServerboundSignUpdatePacket.class, ServerboundSignUpdatePacket::new)
++ .m_178330_(ServerboundSwingPacket.class, ServerboundSwingPacket::new)
++ .m_178330_(ServerboundTeleportToEntityPacket.class, ServerboundTeleportToEntityPacket::new)
++ .m_178330_(ServerboundUseItemOnPacket.class, ServerboundUseItemOnPacket::new)
++ .m_178330_(ServerboundUseItemPacket.class, ServerboundUseItemPacket::new)
++ )
++ ),
++ STATUS("status", m_129600_()
++ .m_129625_(PacketFlow.SERVERBOUND, (new ConnectionProtocol.PacketSet())
++ .m_178330_(ServerboundStatusRequestPacket.class, ServerboundStatusRequestPacket::new)
++ .m_178330_(ServerboundPingRequestPacket.class, ServerboundPingRequestPacket::new)
++ )
++ .m_129625_(PacketFlow.CLIENTBOUND, (new ConnectionProtocol.PacketSet())
++ .m_178330_(ClientboundStatusResponsePacket.class, ClientboundStatusResponsePacket::new)
++ .m_178330_(ClientboundPongResponsePacket.class, ClientboundPongResponsePacket::new)
++ )
++ ),
++ LOGIN("login", m_129600_()
++ .m_129625_(PacketFlow.CLIENTBOUND, (new ConnectionProtocol.PacketSet())
++ .m_178330_(ClientboundLoginDisconnectPacket.class, ClientboundLoginDisconnectPacket::new)
++ .m_178330_(ClientboundHelloPacket.class, ClientboundHelloPacket::new)
++ .m_178330_(ClientboundGameProfilePacket.class, ClientboundGameProfilePacket::new)
++ .m_178330_(ClientboundLoginCompressionPacket.class, ClientboundLoginCompressionPacket::new)
++ .m_178330_(ClientboundCustomQueryPacket.class, ClientboundCustomQueryPacket::new)
++ )
++ .m_129625_(PacketFlow.SERVERBOUND, (new ConnectionProtocol.PacketSet())
++ .m_178330_(ServerboundHelloPacket.class, ServerboundHelloPacket::new)
++ .m_178330_(ServerboundKeyPacket.class, ServerboundKeyPacket::new)
++ .m_178330_(ServerboundCustomQueryAnswerPacket.class, ServerboundCustomQueryAnswerPacket::m_294367_)
++ .m_178330_(ServerboundLoginAcknowledgedPacket.class, ServerboundLoginAcknowledgedPacket::new)
++ )
++ ),
++ CONFIGURATION("configuration", m_129600_()
++ .m_129625_(PacketFlow.CLIENTBOUND, (new ConnectionProtocol.PacketSet())
++ .m_178330_(ClientboundCustomPayloadPacket.class, ClientboundCustomPayloadPacket::new)
++ .m_178330_(ClientboundDisconnectPacket.class, ClientboundDisconnectPacket::new)
++ .m_178330_(ClientboundFinishConfigurationPacket.class, ClientboundFinishConfigurationPacket::new)
++ .m_178330_(ClientboundKeepAlivePacket.class, ClientboundKeepAlivePacket::new)
++ .m_178330_(ClientboundPingPacket.class, ClientboundPingPacket::new)
++ .m_178330_(ClientboundRegistryDataPacket.class, ClientboundRegistryDataPacket::new)
++ .m_178330_(ClientboundResourcePackPacket.class, ClientboundResourcePackPacket::new)
++ .m_178330_(ClientboundUpdateEnabledFeaturesPacket.class, ClientboundUpdateEnabledFeaturesPacket::new)
++ .m_178330_(ClientboundUpdateTagsPacket.class, ClientboundUpdateTagsPacket::new)
++ )
++ .m_129625_(PacketFlow.SERVERBOUND, (new ConnectionProtocol.PacketSet())
++ .m_178330_(ServerboundClientInformationPacket.class, ServerboundClientInformationPacket::new)
++ .m_178330_(ServerboundCustomPayloadPacket.class, ServerboundCustomPayloadPacket::new)
++ .m_178330_(ServerboundFinishConfigurationPacket.class, ServerboundFinishConfigurationPacket::new)
++ .m_178330_(ServerboundKeepAlivePacket.class, ServerboundKeepAlivePacket::new)
++ .m_178330_(ServerboundPongPacket.class, ServerboundPongPacket::new)
++ .m_178330_(ServerboundResourcePackPacket.class, ServerboundResourcePackPacket::new)
++ )
++ );
+
+ public static final int f_263799_ = -1;
+ private final String f_129573_;
diff --git a/patches/minecraft/net/minecraft/network/protocol/common/ClientboundCustomPayloadPacket.java.patch b/patches/minecraft/net/minecraft/network/protocol/common/ClientboundCustomPayloadPacket.java.patch
index d598b4f56d..dad0e933a1 100644
--- a/patches/minecraft/net/minecraft/network/protocol/common/ClientboundCustomPayloadPacket.java.patch
+++ b/patches/minecraft/net/minecraft/network/protocol/common/ClientboundCustomPayloadPacket.java.patch
@@ -15,7 +15,7 @@
if (i >= 0 && i <= 1048576) {
- p_297545_.skipBytes(i);
- return new DiscardedPayload(p_299265_);
-+ return new DiscardedPayload(p_299265_, p_297545_);
++ return new DiscardedPayload(p_299265_, new FriendlyByteBuf(p_297545_.readBytes(i)));
} else {
throw new IllegalArgumentException("Payload may not be larger than 1048576 bytes");
}
diff --git a/patches/minecraft/net/minecraft/network/protocol/common/ServerboundCustomPayloadPacket.java.patch b/patches/minecraft/net/minecraft/network/protocol/common/ServerboundCustomPayloadPacket.java.patch
index dd02c51dba..b96e87ccdd 100644
--- a/patches/minecraft/net/minecraft/network/protocol/common/ServerboundCustomPayloadPacket.java.patch
+++ b/patches/minecraft/net/minecraft/network/protocol/common/ServerboundCustomPayloadPacket.java.patch
@@ -15,7 +15,7 @@
if (i >= 0 && i <= 32767) {
- p_299925_.skipBytes(i);
- return new DiscardedPayload(p_300234_);
-+ return new DiscardedPayload(p_300234_, p_299925_);
++ return new DiscardedPayload(p_300234_, new FriendlyByteBuf(p_299925_.readBytes(i)));
} else {
throw new IllegalArgumentException("Payload may not be larger than 32767 bytes");
}
diff --git a/patches/minecraft/net/minecraft/network/protocol/handshake/ClientIntentionPacket.java.patch b/patches/minecraft/net/minecraft/network/protocol/handshake/ClientIntentionPacket.java.patch
deleted file mode 100644
index 2fd8a71fa7..0000000000
--- a/patches/minecraft/net/minecraft/network/protocol/handshake/ClientIntentionPacket.java.patch
+++ /dev/null
@@ -1,11 +0,0 @@
---- a/net/minecraft/network/protocol/handshake/ClientIntentionPacket.java
-+++ b/net/minecraft/network/protocol/handshake/ClientIntentionPacket.java
-@@ -13,7 +_,7 @@
-
- public void m_5779_(FriendlyByteBuf p_134737_) {
- p_134737_.m_130130_(this.f_134720_);
-- p_134737_.m_130070_(this.f_134721_);
-+ p_134737_.m_130070_(this.f_134721_ + "\0" + net.minecraftforge.network.NetworkConstants.NETVERSION + "\0");
- p_134737_.writeShort(this.f_134722_);
- p_134737_.m_130130_(this.f_134723_.m_293527_());
- }
diff --git a/patches/minecraft/net/minecraft/network/protocol/login/ClientboundCustomQueryPacket.java.patch b/patches/minecraft/net/minecraft/network/protocol/login/ClientboundCustomQueryPacket.java.patch
index ec3b545754..0aa34ba0ed 100644
--- a/patches/minecraft/net/minecraft/network/protocol/login/ClientboundCustomQueryPacket.java.patch
+++ b/patches/minecraft/net/minecraft/network/protocol/login/ClientboundCustomQueryPacket.java.patch
@@ -15,7 +15,7 @@
if (i >= 0 && i <= 1048576) {
- p_297706_.skipBytes(i);
- return new DiscardedQueryPayload(p_299981_);
-+ return new DiscardedQueryPayload(p_299981_, p_297706_);
++ return new DiscardedQueryPayload(p_299981_, new FriendlyByteBuf(p_297706_.readBytes(i)));
} else {
throw new IllegalArgumentException("Payload may not be larger than 1048576 bytes");
}
diff --git a/patches/minecraft/net/minecraft/network/protocol/login/ServerboundCustomQueryAnswerPacket.java.patch b/patches/minecraft/net/minecraft/network/protocol/login/ServerboundCustomQueryAnswerPacket.java.patch
index 39d55ef85c..911b2352ed 100644
--- a/patches/minecraft/net/minecraft/network/protocol/login/ServerboundCustomQueryAnswerPacket.java.patch
+++ b/patches/minecraft/net/minecraft/network/protocol/login/ServerboundCustomQueryAnswerPacket.java.patch
@@ -15,7 +15,7 @@
if (i >= 0 && i <= 1048576) {
- p_299934_.skipBytes(i);
- return DiscardedQueryAnswerPayload.f_290582_;
-+ return new DiscardedQueryAnswerPayload(p_299934_);
++ return new DiscardedQueryAnswerPayload(new FriendlyByteBuf(p_299934_.readBytes(i)));
} else {
throw new IllegalArgumentException("Payload may not be larger than 1048576 bytes");
}
@@ -24,7 +24,7 @@
p_298492_.m_10044_(this);
}
+
++ @Nullable @Override public FriendlyByteBuf getInternalData() { return this.f_290461_ instanceof DiscardedQueryAnswerPayload dc ? dc.data() : null; }
++ @Override public net.minecraft.resources.ResourceLocation getName() { return net.minecraftforge.network.NetworkInitialization.LOGIN_NAME; }
+ @Override public int getIndex() { return f_290801_(); }
-+ @Override public net.minecraft.resources.ResourceLocation getName() { return net.minecraftforge.network.LoginWrapper.WRAPPER; }
-+ @Nullable @Override public FriendlyByteBuf getInternalData() { return this.f_290461_ == null ? null : ((DiscardedQueryAnswerPayload)this.f_290461_).data(); }
}
diff --git a/patches/minecraft/net/minecraft/server/level/ServerPlayer.java.patch b/patches/minecraft/net/minecraft/server/level/ServerPlayer.java.patch
index e7307b909d..f558197393 100644
--- a/patches/minecraft/net/minecraft/server/level/ServerPlayer.java.patch
+++ b/patches/minecraft/net/minecraft/server/level/ServerPlayer.java.patch
@@ -1,5 +1,14 @@
--- a/net/minecraft/server/level/ServerPlayer.java
+++ b/net/minecraft/server/level/ServerPlayer.java
+@@ -149,7 +_,7 @@
+ import net.minecraft.world.scores.criteria.ObjectiveCriteria;
+ import org.slf4j.Logger;
+
+-public class ServerPlayer extends Player {
++public class ServerPlayer extends Player implements net.minecraftforge.common.extensions.IForgeServerPlayer {
+ private static final Logger f_8907_ = LogUtils.getLogger();
+ private static final int f_143381_ = 32;
+ private static final int f_143382_ = 10;
@@ -571,6 +_,7 @@
public void m_6667_(DamageSource p_9035_) {
diff --git a/patches/minecraft/net/minecraft/server/network/ConfigurationTask.java.patch b/patches/minecraft/net/minecraft/server/network/ConfigurationTask.java.patch
new file mode 100644
index 0000000000..1b99bb8b9c
--- /dev/null
+++ b/patches/minecraft/net/minecraft/server/network/ConfigurationTask.java.patch
@@ -0,0 +1,13 @@
+--- a/net/minecraft/server/network/ConfigurationTask.java
++++ b/net/minecraft/server/network/ConfigurationTask.java
+@@ -4,6 +_,10 @@
+ import net.minecraft.network.protocol.Packet;
+
+ public interface ConfigurationTask {
++ default void start(net.minecraftforge.network.config.ConfigurationTaskContext ctx) {
++ m_293075_(ctx::send);
++ }
++
+ void m_293075_(Consumer> p_299398_);
+
+ ConfigurationTask.Type m_293172_();
diff --git a/patches/minecraft/net/minecraft/server/network/ServerCommonPacketListenerImpl.java.patch b/patches/minecraft/net/minecraft/server/network/ServerCommonPacketListenerImpl.java.patch
index 3c71309ff8..ccc7398e6a 100644
--- a/patches/minecraft/net/minecraft/server/network/ServerCommonPacketListenerImpl.java.patch
+++ b/patches/minecraft/net/minecraft/server/network/ServerCommonPacketListenerImpl.java.patch
@@ -4,7 +4,7 @@
}
public void m_293234_(ServerboundCustomPayloadPacket p_300164_) {
-+ net.minecraftforge.network.NetworkHooks.onCustomPayload(p_300164_, this.f_291338_);
++ net.minecraftforge.common.ForgeHooks.onCustomPayload(p_300164_, this.f_291338_);
}
public void m_293248_(ServerboundResourcePackPacket p_300656_) {
diff --git a/patches/minecraft/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java.patch b/patches/minecraft/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java.patch
new file mode 100644
index 0000000000..272c9268c4
--- /dev/null
+++ b/patches/minecraft/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java.patch
@@ -0,0 +1,50 @@
+--- a/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java
++++ b/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java
+@@ -36,16 +_,19 @@
+ public class ServerConfigurationPacketListenerImpl extends ServerCommonPacketListenerImpl implements TickablePacketListener, ServerConfigurationPacketListener {
+ private static final Logger f_291519_ = LogUtils.getLogger();
+ private static final Component f_291657_ = Component.m_237115_("multiplayer.disconnect.invalid_player_data");
++ private static final ConfigurationTask.Type VANILLA_START = new ConfigurationTask.Type("vanilla_start");
+ private final GameProfile f_291596_;
+ private final Queue f_290691_ = new ConcurrentLinkedQueue<>();
+ @Nullable
+ private ConfigurationTask f_291862_;
+ private ClientInformation f_290851_;
++ private final net.minecraftforge.network.config.ConfigurationTaskContext taskContext;
+
+ public ServerConfigurationPacketListenerImpl(MinecraftServer p_301415_, Connection p_298106_, CommonListenerCookie p_301309_) {
+ super(p_301415_, p_298106_, p_301309_);
+ this.f_291596_ = p_301309_.f_290628_();
+ this.f_290851_ = p_301309_.f_290565_();
++ this.taskContext = new net.minecraftforge.network.config.ConfigurationTaskContext(p_298106_, this::m_141995_, this::m_293514_);
+ }
+
+ protected GameProfile m_293343_() {
+@@ -61,12 +_,17 @@
+ return this.f_291338_.m_129536_();
+ }
+
+- public void m_294295_() {
++ private void vanillaStart() {
+ this.m_141995_(new ClientboundCustomPayloadPacket(new BrandPayload(this.f_291389_.getServerModName())));
+ LayeredRegistryAccess layeredregistryaccess = this.f_291389_.m_247573_();
+ this.m_141995_(new ClientboundUpdateEnabledFeaturesPacket(FeatureFlags.f_244280_.m_245829_(this.f_291389_.m_129910_().m_247623_())));
+ this.m_141995_(new ClientboundRegistryDataPacket((new RegistryAccess.ImmutableRegistryAccess(RegistrySynchronization.m_257599_(layeredregistryaccess))).m_203557_()));
+ this.m_141995_(new ClientboundUpdateTagsPacket(TagNetworkSerialization.m_245799_(layeredregistryaccess)));
++ }
++
++ public void m_294295_() {
++ net.minecraftforge.event.ForgeEventFactory.gatherLoginConfigTasks(this.f_291338_, this.f_290691_::add);
++ this.f_290691_.add(new net.minecraftforge.network.config.SimpleConfigurationTask(VANILLA_START, this::vanillaStart));
+ this.m_295612_();
+ this.f_290691_.add(new JoinWorldTask());
+ this.m_295676_();
+@@ -135,7 +_,7 @@
+ ConfigurationTask configurationtask = this.f_290691_.poll();
+ if (configurationtask != null) {
+ this.f_291862_ = configurationtask;
+- configurationtask.m_293075_(this::m_141995_);
++ configurationtask.start(this.taskContext);
+ }
+
+ }
diff --git a/patches/minecraft/net/minecraft/server/network/ServerLoginPacketListenerImpl.java.patch b/patches/minecraft/net/minecraft/server/network/ServerLoginPacketListenerImpl.java.patch
index e4efd7b764..822cfadaa5 100644
--- a/patches/minecraft/net/minecraft/server/network/ServerLoginPacketListenerImpl.java.patch
+++ b/patches/minecraft/net/minecraft/server/network/ServerLoginPacketListenerImpl.java.patch
@@ -1,42 +1,5 @@
--- a/net/minecraft/server/network/ServerLoginPacketListenerImpl.java
+++ b/net/minecraft/server/network/ServerLoginPacketListenerImpl.java
-@@ -62,7 +_,10 @@
- }
-
- public void m_9933_() {
-- if (this.f_10019_ == ServerLoginPacketListenerImpl.State.VERIFYING) {
-+ if (this.f_10019_ == State.NEGOTIATING) { //TODO: Redesign with new protocol switching Mojang added
-+ if (net.minecraftforge.network.NetworkHooks.tickNegotiation(this.f_10013_))
-+ this.f_10019_ = State.VERIFYING;
-+ } else if (this.f_10019_ == ServerLoginPacketListenerImpl.State.VERIFYING) {
- this.m_294778_(Objects.requireNonNull(this.f_291112_));
- }
-
-@@ -101,7 +_,7 @@
-
- public String m_10056_() {
- String s = this.f_10013_.m_295656_(this.f_10018_.m_292975_());
-- return this.f_291165_ != null ? this.f_291165_ + " (" + s + ")" : s;
-+ return this.f_291112_ != null ? this.f_291112_ + " (" + s + ")" : s;
- }
-
- public void m_5990_(ServerboundHelloPacket p_10047_) {
-@@ -110,13 +_,13 @@
- this.f_291165_ = p_10047_.f_238040_();
- GameProfile gameprofile = this.f_10018_.m_236731_();
- if (gameprofile != null && this.f_291165_.equalsIgnoreCase(gameprofile.getName())) {
-- this.m_294008_(gameprofile);
-+ this.f_10019_ = ServerLoginPacketListenerImpl.State.NEGOTIATING; // FORGE: continue NEGOTIATING, we move to READY_TO_ACCEPT after Forge is ready
- } else {
- if (this.f_10018_.m_129797_() && !this.f_10013_.m_129531_()) {
- this.f_10019_ = ServerLoginPacketListenerImpl.State.KEY;
- this.f_10013_.m_129512_(new ClientboundHelloPacket("", this.f_10018_.m_129790_().getPublic().getEncoded(), this.f_252396_));
- } else {
-- this.m_294008_(m_295545_(this.f_291165_));
-+ this.f_10019_ = ServerLoginPacketListenerImpl.State.NEGOTIATING; // FORGE: continue NEGOTIATING, we move to READY_TO_ACCEPT after Forge is ready
- }
-
- }
@@ -180,7 +_,7 @@
throw new IllegalStateException("Protocol error", cryptexception);
}
@@ -46,20 +9,11 @@
public void run() {
String s1 = Objects.requireNonNull(ServerLoginPacketListenerImpl.this.f_291165_, "Player name not initialized");
-@@ -200,7 +_,7 @@
- } catch (AuthenticationUnavailableException authenticationunavailableexception) {
- if (ServerLoginPacketListenerImpl.this.f_10018_.m_129792_()) {
- ServerLoginPacketListenerImpl.f_10015_.warn("Authentication servers are down but will let them in anyway!");
-- ServerLoginPacketListenerImpl.this.m_294008_(ServerLoginPacketListenerImpl.m_295545_(s1));
-+ ServerLoginPacketListenerImpl.this.f_10019_ = ServerLoginPacketListenerImpl.State.NEGOTIATING; // FORGE: continue NEGOTIATING, we move to READY_TO_ACCEPT after Forge is ready
- } else {
- ServerLoginPacketListenerImpl.this.m_10053_(Component.m_237115_("multiplayer.disconnect.authservers_down"));
- ServerLoginPacketListenerImpl.f_10015_.error("Couldn't verify username because servers are unavailable");
@@ -220,6 +_,7 @@
}
public void m_10044_(ServerboundCustomQueryAnswerPacket p_297965_) {
-+ if (!net.minecraftforge.network.NetworkHooks.onCustomPayload(p_297965_, this.f_10013_))
++ if (!net.minecraftforge.common.ForgeHooks.onCustomPayload(p_297965_, this.f_10013_))
this.m_10053_(f_291075_);
}
diff --git a/patches/minecraft/net/minecraft/server/players/PlayerList.java.patch b/patches/minecraft/net/minecraft/server/players/PlayerList.java.patch
index 88f263d740..9bac5c2a30 100644
--- a/patches/minecraft/net/minecraft/server/players/PlayerList.java.patch
+++ b/patches/minecraft/net/minecraft/server/players/PlayerList.java.patch
@@ -8,14 +8,6 @@
public PlayerList(MinecraftServer p_203842_, LayeredRegistryAccess p_251844_, PlayerDataStorage p_203844_, int p_203845_) {
this.f_11195_ = p_203842_;
-@@ -163,6 +_,7 @@
- LevelData leveldata = serverlevel1.m_6106_();
- p_11263_.m_143427_(compoundtag);
- ServerGamePacketListenerImpl servergamepacketlistenerimpl = new ServerGamePacketListenerImpl(this.f_11195_, p_11262_, p_11263_, p_297215_);
-+ net.minecraftforge.network.NetworkHooks.sendMCRegistryPackets(p_11262_, "PLAY_TO_CLIENT");
- GameRules gamerules = serverlevel1.m_46469_();
- boolean flag = gamerules.m_46207_(GameRules.f_46156_);
- boolean flag1 = gamerules.m_46207_(GameRules.f_46145_);
@@ -171,6 +_,7 @@
servergamepacketlistenerimpl.m_141995_(new ClientboundChangeDifficultyPacket(leveldata.m_5472_(), leveldata.m_5474_()));
servergamepacketlistenerimpl.m_141995_(new ClientboundPlayerAbilitiesPacket(p_11263_.m_150110_()));
diff --git a/patches/minecraft/net/minecraft/world/entity/EntityType.java.patch b/patches/minecraft/net/minecraft/world/entity/EntityType.java.patch
index 613416b95d..dee3529d78 100644
--- a/patches/minecraft/net/minecraft/world/entity/EntityType.java.patch
+++ b/patches/minecraft/net/minecraft/world/entity/EntityType.java.patch
@@ -7,7 +7,7 @@
+ private final java.util.function.Predicate> velocityUpdateSupplier;
+ private final java.util.function.ToIntFunction> trackingRangeSupplier;
+ private final java.util.function.ToIntFunction> updateIntervalSupplier;
-+ private final java.util.function.BiFunction customClientFactory;
++ private final java.util.function.BiFunction customClientFactory;
+
private static EntityType m_20634_(String p_20635_, EntityType.Builder p_20636_) {
return Registry.m_122961_(BuiltInRegistries.f_256780_, p_20635_, p_20636_.m_20712_(p_20635_));
@@ -29,7 +29,7 @@
- this.f_244139_ = p_273518_;
+ this(p_273268_, p_272918_, p_273417_, p_273389_, p_273556_, p_272654_, p_273631_, p_272946_, p_272895_, p_273451_, p_273518_, EntityType::defaultVelocitySupplier, EntityType::defaultTrackingRangeSupplier, EntityType::defaultUpdateIntervalSupplier, null);
+ }
-+ public EntityType(EntityType.EntityFactory p_251402_, MobCategory p_251431_, boolean p_251439_, boolean p_251973_, boolean p_252007_, boolean p_250908_, ImmutableSet p_250201_, EntityDimensions p_251742_, int p_250479_, int p_249249_, FeatureFlagSet p_250427_, final java.util.function.Predicate> velocityUpdateSupplier, final java.util.function.ToIntFunction> trackingRangeSupplier, final java.util.function.ToIntFunction> updateIntervalSupplier, final java.util.function.BiFunction customClientFactory) {
++ public EntityType(EntityType.EntityFactory p_251402_, MobCategory p_251431_, boolean p_251439_, boolean p_251973_, boolean p_252007_, boolean p_250908_, ImmutableSet p_250201_, EntityDimensions p_251742_, int p_250479_, int p_249249_, FeatureFlagSet p_250427_, final java.util.function.Predicate> velocityUpdateSupplier, final java.util.function.ToIntFunction> trackingRangeSupplier, final java.util.function.ToIntFunction> updateIntervalSupplier, final java.util.function.BiFunction customClientFactory) {
+ this.f_20535_ = p_251402_;
+ this.f_20536_ = p_251431_;
+ this.f_20541_ = p_250908_;
@@ -76,7 +76,7 @@
return this.f_204038_;
}
-+ public T customClientSpawn(net.minecraftforge.network.PlayMessages.SpawnEntity packet, Level world) {
++ public T customClientSpawn(net.minecraftforge.network.packets.SpawnEntity packet, Level world) {
+ if (customClientFactory == null) return this.m_20615_(world);
+ return customClientFactory.apply(packet, world);
+ }
@@ -92,7 +92,7 @@
+ private java.util.function.Predicate> velocityUpdateSupplier = EntityType::defaultVelocitySupplier;
+ private java.util.function.ToIntFunction> trackingRangeSupplier = EntityType::defaultTrackingRangeSupplier;
+ private java.util.function.ToIntFunction> updateIntervalSupplier = EntityType::defaultUpdateIntervalSupplier;
-+ private java.util.function.BiFunction customClientFactory;
++ private java.util.function.BiFunction customClientFactory;
+
private Builder(EntityType.EntityFactory p_20696_, MobCategory p_20697_) {
this.f_20685_ = p_20696_;
@@ -120,7 +120,7 @@
+ * By default, entities are spawned clientside via {@link EntityType#create(Level)}}.
+ * If you need finer control over the spawning process, use this to get read access to the spawn packet.
+ */
-+ public EntityType.Builder setCustomClientFactory(java.util.function.BiFunction customClientFactory) {
++ public EntityType.Builder setCustomClientFactory(java.util.function.BiFunction customClientFactory) {
+ this.customClientFactory = customClientFactory;
+ return this;
+ }
diff --git a/patches/minecraft/net/minecraft/world/entity/LivingEntity.java.patch b/patches/minecraft/net/minecraft/world/entity/LivingEntity.java.patch
index b27169de71..a99083f603 100644
--- a/patches/minecraft/net/minecraft/world/entity/LivingEntity.java.patch
+++ b/patches/minecraft/net/minecraft/world/entity/LivingEntity.java.patch
@@ -31,7 +31,7 @@
public static AttributeSupplier.Builder m_21183_() {
- return AttributeSupplier.m_22244_().m_22266_(Attributes.f_22276_).m_22266_(Attributes.f_22278_).m_22266_(Attributes.f_22279_).m_22266_(Attributes.f_22284_).m_22266_(Attributes.f_22285_).m_22266_(Attributes.f_290864_);
-+ return AttributeSupplier.m_22244_().m_22266_(Attributes.f_22276_).m_22266_(Attributes.f_22278_).m_22266_(Attributes.f_22279_).m_22266_(Attributes.f_22284_).m_22266_(Attributes.f_22285_).m_22266_(net.minecraftforge.common.ForgeMod.SWIM_SPEED.get()).m_22266_(net.minecraftforge.common.ForgeMod.NAMETAG_DISTANCE.get()).m_22266_(net.minecraftforge.common.ForgeMod.ENTITY_GRAVITY.get()).m_22266_(net.minecraftforge.common.ForgeMod.STEP_HEIGHT_ADDITION.get());
++ return AttributeSupplier.m_22244_().m_22266_(Attributes.f_22276_).m_22266_(Attributes.f_22278_).m_22266_(Attributes.f_22279_).m_22266_(Attributes.f_22284_).m_22266_(Attributes.f_22285_).m_22266_(Attributes.f_290864_).m_22266_(net.minecraftforge.common.ForgeMod.SWIM_SPEED.get()).m_22266_(net.minecraftforge.common.ForgeMod.NAMETAG_DISTANCE.get()).m_22266_(net.minecraftforge.common.ForgeMod.ENTITY_GRAVITY.get()).m_22266_(net.minecraftforge.common.ForgeMod.STEP_HEIGHT_ADDITION.get());
}
protected void m_7840_(double p_20990_, boolean p_20991_, BlockState p_20992_, BlockPos p_20993_) {
diff --git a/patches/minecraft/net/minecraft/world/inventory/MenuType.java.patch b/patches/minecraft/net/minecraft/world/inventory/MenuType.java.patch
index 939dc5f2b4..5060610832 100644
--- a/patches/minecraft/net/minecraft/world/inventory/MenuType.java.patch
+++ b/patches/minecraft/net/minecraft/world/inventory/MenuType.java.patch
@@ -17,8 +17,8 @@
+
+ @Override
+ public T create(int windowId, Inventory playerInv, net.minecraft.network.FriendlyByteBuf extraData) {
-+ if (this.f_39981_ instanceof net.minecraftforge.network.IContainerFactory) {
-+ return ((net.minecraftforge.network.IContainerFactory) this.f_39981_).create(windowId, playerInv, extraData);
++ if (this.f_39981_ instanceof net.minecraftforge.network.IContainerFactory ctr) {
++ return ctr.create(windowId, playerInv, extraData);
+ }
+ return m_39985_(windowId, playerInv);
}
diff --git a/src/main/java/net/minecraftforge/client/ForgeHooksClient.java b/src/main/java/net/minecraftforge/client/ForgeHooksClient.java
index 7768c68244..a826efb21e 100644
--- a/src/main/java/net/minecraftforge/client/ForgeHooksClient.java
+++ b/src/main/java/net/minecraftforge/client/ForgeHooksClient.java
@@ -145,6 +145,7 @@ import net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions;
import net.minecraftforge.client.extensions.common.IClientItemExtensions;
import net.minecraftforge.client.extensions.common.IClientMobEffectExtensions;
import net.minecraftforge.client.gui.ClientTooltipComponentManager;
+import net.minecraftforge.client.gui.ModMismatchDisconnectedScreen;
import net.minecraftforge.client.gui.overlay.GuiOverlayManager;
import net.minecraftforge.client.model.data.ModelData;
import net.minecraftforge.client.textures.ForgeTextureMetadata;
@@ -165,7 +166,8 @@ import net.minecraftforge.fml.VersionChecker;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.forge.snapshots.ForgeSnapshotsModClient;
import net.minecraftforge.gametest.ForgeGameTestHooks;
-import net.minecraftforge.network.NetworkConstants;
+import net.minecraftforge.network.NetworkContext;
+import net.minecraftforge.network.NetworkInitialization;
import net.minecraftforge.network.NetworkRegistry;
import net.minecraftforge.network.ServerStatusPing;
import net.minecraftforge.registries.GameData;
@@ -201,8 +203,7 @@ import java.util.stream.Collectors;
import java.util.stream.Stream;
@ApiStatus.Internal
-public class ForgeHooksClient
-{
+public class ForgeHooksClient {
private static final Logger LOGGER = LogManager.getLogger();
private static final Marker CLIENTHOOKS = MarkerManager.getMarker("CLIENTHOOKS");
@@ -218,21 +219,18 @@ public class ForgeHooksClient
guiLayers.forEach(screen -> screen.resize(minecraft, width, height));
}
- public static void clearGuiLayers(Minecraft minecraft)
- {
+ public static void clearGuiLayers(Minecraft minecraft) {
while(guiLayers.size() > 0)
popGuiLayerInternal(minecraft);
}
- private static void popGuiLayerInternal(Minecraft minecraft)
- {
+ private static void popGuiLayerInternal(Minecraft minecraft) {
if (minecraft.screen != null)
minecraft.screen.removed();
minecraft.screen = guiLayers.pop();
}
- public static void pushGuiLayer(Minecraft minecraft, Screen screen)
- {
+ public static void pushGuiLayer(Minecraft minecraft, Screen screen) {
if (minecraft.screen != null)
guiLayers.push(minecraft.screen);
minecraft.screen = Objects.requireNonNull(screen);
@@ -240,10 +238,8 @@ public class ForgeHooksClient
minecraft.getNarrator().sayNow(screen.getNarrationMessage());
}
- public static void popGuiLayer(Minecraft minecraft)
- {
- if (guiLayers.size() == 0)
- {
+ public static void popGuiLayer(Minecraft minecraft) {
+ if (guiLayers.size() == 0) {
minecraft.setScreen(null);
return;
}
@@ -253,22 +249,19 @@ public class ForgeHooksClient
minecraft.getNarrator().sayNow(minecraft.screen.getNarrationMessage());
}
- public static float getGuiFarPlane()
- {
+ public static float getGuiFarPlane() {
// 1000 units for the overlay background,
// and 10000 units for each layered Screen,
return 1000.0F + 10000.0F * (1 + guiLayers.size());
}
- public static String getArmorTexture(Entity entity, ItemStack armor, String _default, EquipmentSlot slot, String type)
- {
+ public static String getArmorTexture(Entity entity, ItemStack armor, String _default, EquipmentSlot slot, String type) {
String result = armor.getItem().getArmorTexture(armor, entity, slot, type);
return result != null ? result : _default;
}
- public static boolean onDrawHighlight(LevelRenderer context, Camera camera, HitResult target, float partialTick, PoseStack poseStack, MultiBufferSource bufferSource)
- {
+ public static boolean onDrawHighlight(LevelRenderer context, Camera camera, HitResult target, float partialTick, PoseStack poseStack, MultiBufferSource bufferSource) {
switch (target.getType()) {
case BLOCK:
if (!(target instanceof BlockHitResult blockTarget)) return false;
@@ -287,40 +280,33 @@ public class ForgeHooksClient
stage.dispatch(levelRenderer, poseStack, projectionMatrix, renderTick, camera, frustum);
}
- public static boolean renderSpecificFirstPersonHand(InteractionHand hand, PoseStack poseStack, MultiBufferSource bufferSource, int packedLight, float partialTick, float interpPitch, float swingProgress, float equipProgress, ItemStack stack)
- {
+ public static boolean renderSpecificFirstPersonHand(InteractionHand hand, PoseStack poseStack, MultiBufferSource bufferSource, int packedLight, float partialTick, float interpPitch, float swingProgress, float equipProgress, ItemStack stack) {
return MinecraftForge.EVENT_BUS.post(new RenderHandEvent(hand, poseStack, bufferSource, packedLight, partialTick, interpPitch, swingProgress, equipProgress, stack));
}
- public static boolean renderSpecificFirstPersonArm(PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight, AbstractClientPlayer player, HumanoidArm arm)
- {
+ public static boolean renderSpecificFirstPersonArm(PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight, AbstractClientPlayer player, HumanoidArm arm) {
return MinecraftForge.EVENT_BUS.post(new RenderArmEvent(poseStack, multiBufferSource, packedLight, player, arm));
}
- public static void onTextureStitchedPost(TextureAtlas map)
- {
+ public static void onTextureStitchedPost(TextureAtlas map) {
ModLoader.get().postEvent(new TextureStitchEvent.Post(map));
}
- public static void onBlockColorsInit(BlockColors blockColors)
- {
+ public static void onBlockColorsInit(BlockColors blockColors) {
ModLoader.get().postEvent(new RegisterColorHandlersEvent.Block(blockColors));
}
- public static void onItemColorsInit(ItemColors itemColors, BlockColors blockColors)
- {
+ public static void onItemColorsInit(ItemColors itemColors, BlockColors blockColors) {
ModLoader.get().postEvent(new RegisterColorHandlersEvent.Item(itemColors, blockColors));
}
- public static Model getArmorModel(LivingEntity entityLiving, ItemStack itemStack, EquipmentSlot slot, HumanoidModel> _default)
- {
+ public static Model getArmorModel(LivingEntity entityLiving, ItemStack itemStack, EquipmentSlot slot, HumanoidModel> _default) {
return IClientItemExtensions.of(itemStack).getGenericArmorModel(entityLiving, itemStack, slot, _default);
}
/** Copies humanoid model properties from the original model to another, used for armor models */
@SuppressWarnings("unchecked")
- public static void copyModelProperties(HumanoidModel original, HumanoidModel> replacement)
- {
+ public static void copyModelProperties(HumanoidModel original, HumanoidModel> replacement) {
// this function does not make use of the generic, so the unchecked cast should be safe
original.copyPropertiesTo((HumanoidModel)replacement);
replacement.head.visible = original.head.visible;
@@ -333,35 +319,27 @@ public class ForgeHooksClient
}
//This properly moves the domain, if provided, to the front of the string before concatenating
- public static String fixDomain(String base, String complex)
- {
+ public static String fixDomain(String base, String complex) {
int idx = complex.indexOf(':');
if (idx == -1)
- {
return base + complex;
- }
String name = complex.substring(idx + 1, complex.length());
- if (idx > 1)
- {
+ if (idx > 1) {
String domain = complex.substring(0, idx);
return domain + ':' + base + name;
- }
- else
- {
+ } else {
return base + name;
}
}
- public static float getFieldOfViewModifier(Player entity, float fovModifier)
- {
+ public static float getFieldOfViewModifier(Player entity, float fovModifier) {
ComputeFovModifierEvent fovModifierEvent = new ComputeFovModifierEvent(entity, fovModifier);
MinecraftForge.EVENT_BUS.post(fovModifierEvent);
return fovModifierEvent.getNewFovModifier();
}
- public static double getFieldOfView(GameRenderer renderer, Camera camera, double partialTick, double fov, boolean usedConfiguredFov)
- {
+ public static double getFieldOfView(GameRenderer renderer, Camera camera, double partialTick, double fov, boolean usedConfiguredFov) {
ViewportEvent.ComputeFov event = new ViewportEvent.ComputeFov(renderer, camera, partialTick, fov, usedConfiguredFov);
MinecraftForge.EVENT_BUS.post(event);
return event.getFOV();
@@ -370,19 +348,16 @@ public class ForgeHooksClient
/**
* Initialization of Forge Renderers.
*/
- static
- {
+ static {
//FluidRegistry.renderIdFluid = RenderingRegistry.getNextAvailableRenderId();
//RenderingRegistry.registerBlockHandler(RenderBlockFluid.instance);
}
- public static void renderMainMenu(TitleScreen gui, GuiGraphics guiGraphics, Font font, int width, int height, int alpha)
- {
+ public static void renderMainMenu(TitleScreen gui, GuiGraphics guiGraphics, Font font, int width, int height, int alpha) {
VersionChecker.Status status = ForgeVersion.getStatus();
ForgeSnapshotsModClient.renderMainMenuWarning(status, gui, guiGraphics, font, width, height, alpha);
- forgeStatusLine = switch(status)
- {
+ forgeStatusLine = switch(status) {
// case FAILED -> " Version check failed";
// case UP_TO_DATE -> "Forge up to date";
// case AHEAD -> "Using non-recommended Forge build, issues may arise.";
@@ -393,15 +368,13 @@ public class ForgeHooksClient
public static String forgeStatusLine;
@Nullable
- public static SoundInstance playSound(SoundEngine manager, SoundInstance sound)
- {
+ public static SoundInstance playSound(SoundEngine manager, SoundInstance sound) {
PlaySoundEvent e = new PlaySoundEvent(manager, sound);
MinecraftForge.EVENT_BUS.post(e);
return e.getSound();
}
- public static void drawScreen(Screen screen, GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTick)
- {
+ public static void drawScreen(Screen screen, GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTick) {
guiGraphics.pose().pushPose();
guiLayers.forEach(layer -> {
// Prevent the background layers from thinking the mouse is over their controls and showing them as highlighted.
@@ -412,15 +385,13 @@ public class ForgeHooksClient
guiGraphics.pose().popPose();
}
- private static void drawScreenInternal(Screen screen, GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTick)
- {
+ private static void drawScreenInternal(Screen screen, GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTick) {
if (!MinecraftForge.EVENT_BUS.post(new ScreenEvent.Render.Pre(screen, guiGraphics, mouseX, mouseY, partialTick)))
screen.renderWithTooltip(guiGraphics, mouseX, mouseY, partialTick);
MinecraftForge.EVENT_BUS.post(new ScreenEvent.Render.Post(screen, guiGraphics, mouseX, mouseY, partialTick));
}
- public static Vector3f getFogColor(Camera camera, float partialTick, ClientLevel level, int renderDistance, float darkenWorldAmount, float fogRed, float fogGreen, float fogBlue)
- {
+ public static Vector3f getFogColor(Camera camera, float partialTick, ClientLevel level, int renderDistance, float darkenWorldAmount, float fogRed, float fogGreen, float fogBlue) {
// Modify fog color depending on the fluid
FluidState state = level.getFluidState(camera.getBlockPosition());
Vector3f fluidFogColor = new Vector3f(fogRed, fogGreen, fogBlue);
@@ -434,48 +405,41 @@ public class ForgeHooksClient
return fluidFogColor;
}
- public static void onFogRender(FogRenderer.FogMode mode, FogType type, Camera camera, float partialTick, float renderDistance, float nearDistance, float farDistance, FogShape shape)
- {
+ public static void onFogRender(FogRenderer.FogMode mode, FogType type, Camera camera, float partialTick, float renderDistance, float nearDistance, float farDistance, FogShape shape) {
// Modify fog rendering depending on the fluid
FluidState state = camera.getEntity().level().getFluidState(camera.getBlockPosition());
if (camera.getPosition().y < (double)((float)camera.getBlockPosition().getY() + state.getHeight(camera.getEntity().level(), camera.getBlockPosition())))
IClientFluidTypeExtensions.of(state).modifyFogRender(camera, mode, renderDistance, partialTick, nearDistance, farDistance, shape);
ViewportEvent.RenderFog event = new ViewportEvent.RenderFog(mode, type, camera, partialTick, nearDistance, farDistance, shape);
- if (MinecraftForge.EVENT_BUS.post(event))
- {
+ if (MinecraftForge.EVENT_BUS.post(event)) {
RenderSystem.setShaderFogStart(event.getNearPlaneDistance());
RenderSystem.setShaderFogEnd(event.getFarPlaneDistance());
RenderSystem.setShaderFogShape(event.getFogShape());
}
}
- public static ViewportEvent.ComputeCameraAngles onCameraSetup(GameRenderer renderer, Camera camera, float partial)
- {
+ public static ViewportEvent.ComputeCameraAngles onCameraSetup(GameRenderer renderer, Camera camera, float partial) {
ViewportEvent.ComputeCameraAngles event = new ViewportEvent.ComputeCameraAngles(renderer, camera, partial, camera.getYRot(), camera.getXRot(), 0);
MinecraftForge.EVENT_BUS.post(event);
return event;
}
- public static void onModifyBakingResult(Map models, ModelBakery modelBakery)
- {
+ public static void onModifyBakingResult(Map models, ModelBakery modelBakery) {
ModLoader.get().postEvent(new ModelEvent.ModifyBakingResult(models, modelBakery));
}
- public static void onModelBake(ModelManager modelManager, Map models, ModelBakery modelBakery)
- {
+ public static void onModelBake(ModelManager modelManager, Map models, ModelBakery modelBakery) {
ModLoader.get().postEvent(new ModelEvent.BakingCompleted(modelManager, Collections.unmodifiableMap(models), modelBakery));
}
- public static BakedModel handleCameraTransforms(PoseStack poseStack, BakedModel model, ItemDisplayContext cameraTransformType, boolean applyLeftHandTransform)
- {
+ public static BakedModel handleCameraTransforms(PoseStack poseStack, BakedModel model, ItemDisplayContext cameraTransformType, boolean applyLeftHandTransform) {
model = model.applyTransform(cameraTransformType, poseStack, applyLeftHandTransform);
return model;
}
@SuppressWarnings("deprecation")
- public static TextureAtlasSprite[] getFluidSprites(BlockAndTintGetter level, BlockPos pos, FluidState fluidStateIn)
- {
+ public static TextureAtlasSprite[] getFluidSprites(BlockAndTintGetter level, BlockPos pos, FluidState fluidStateIn) {
IClientFluidTypeExtensions props = IClientFluidTypeExtensions.of(fluidStateIn);
ResourceLocation overlayTexture = props.getOverlayTexture(fluidStateIn, level, pos);
return new TextureAtlasSprite[] {
@@ -486,13 +450,11 @@ public class ForgeHooksClient
}
@SuppressWarnings("deprecation")
- public static Material getBlockMaterial(ResourceLocation loc)
- {
+ public static Material getBlockMaterial(ResourceLocation loc) {
return new Material(TextureAtlas.LOCATION_BLOCKS, loc);
}
- public static void fillNormal(int[] faceData, Direction facing)
- {
+ public static void fillNormal(int[] faceData, Direction facing) {
fillNormal(faceData, facing, false);
}
@@ -500,8 +462,7 @@ public class ForgeHooksClient
* internal, relies on fixed format of FaceBakery
*/
// TODO Do we need this?
- public static void fillNormal(int[] faceData, Direction facing, boolean calculateNormals)
- {
+ public static void fillNormal(int[] faceData, Direction facing, boolean calculateNormals) {
Vector3f v2;
if (calculateNormals || ForgeConfig.CLIENT.calculateAllNormals.get()) {
Vector3f v1 = getVertexPos(faceData, 3);
@@ -512,9 +473,8 @@ public class ForgeHooksClient
v2.sub(t2);
v2.cross(v1);
v2.normalize();
- } else {
+ } else
v2 = new Vector3f(facing.getNormal().getX(), facing.getNormal().getY(), facing.getNormal().getZ());
- }
int x = ((byte) Math.round(v2.x() * 127)) & 0xFF;
int y = ((byte) Math.round(v2.y() * 127)) & 0xFF;
int z = ((byte) Math.round(v2.z() * 127)) & 0xFF;
@@ -522,13 +482,10 @@ public class ForgeHooksClient
int normal = x | (y << 0x08) | (z << 0x10);
for(int i = 0; i < 4; i++)
- {
faceData[i * 8 + 7] = normal;
- }
}
- private static Vector3f getVertexPos(int[] data, int vertex)
- {
+ private static Vector3f getVertexPos(int[] data, int vertex) {
int idx = vertex * 8;
float x = Float.intBitsToFloat(data[idx]);
@@ -538,8 +495,7 @@ public class ForgeHooksClient
return new Vector3f(x, y, z);
}
- public static boolean calculateFaceWithoutAO(BlockAndTintGetter getter, BlockState state, BlockPos pos, BakedQuad quad, boolean isFaceCubic, float[] brightness, int[] lightmap)
- {
+ public static boolean calculateFaceWithoutAO(BlockAndTintGetter getter, BlockState state, BlockPos pos, BakedQuad quad, boolean isFaceCubic, float[] brightness, int[] lightmap) {
if (quad.hasAmbientOcclusion())
return false;
@@ -550,22 +506,17 @@ public class ForgeHooksClient
return true;
}
- public static void loadEntityShader(Entity entity, GameRenderer entityRenderer)
- {
- if (entity != null)
- {
+ public static void loadEntityShader(Entity entity, GameRenderer entityRenderer) {
+ if (entity != null) {
ResourceLocation shader = EntitySpectatorShaderManager.get(entity.getType());
if (shader != null)
- {
entityRenderer.loadEffect(shader);
- }
}
}
private static int slotMainHand = 0;
- public static boolean shouldCauseReequipAnimation(@NotNull ItemStack from, @NotNull ItemStack to, int slot)
- {
+ public static boolean shouldCauseReequipAnimation(@NotNull ItemStack from, @NotNull ItemStack to, int slot) {
boolean fromInvalid = from.isEmpty();
boolean toInvalid = to.isEmpty();
@@ -573,92 +524,77 @@ public class ForgeHooksClient
if (fromInvalid || toInvalid) return true;
boolean changed = false;
- if (slot != -1)
- {
+ if (slot != -1) {
changed = slot != slotMainHand;
slotMainHand = slot;
}
return from.getItem().shouldCauseReequipAnimation(from, to, changed);
}
- public static CustomizeGuiOverlayEvent.BossEventProgress onCustomizeBossEventProgress(GuiGraphics guiGraphics, Window window, LerpingBossEvent bossInfo, int x, int y, int increment)
- {
+ public static CustomizeGuiOverlayEvent.BossEventProgress onCustomizeBossEventProgress(GuiGraphics guiGraphics, Window window, LerpingBossEvent bossInfo, int x, int y, int increment) {
CustomizeGuiOverlayEvent.BossEventProgress evt = new CustomizeGuiOverlayEvent.BossEventProgress(window, guiGraphics,
Minecraft.getInstance().getPartialTick(), bossInfo, x, y, increment);
MinecraftForge.EVENT_BUS.post(evt);
return evt;
}
- public static ScreenshotEvent onScreenshot(NativeImage image, File screenshotFile)
- {
+ public static ScreenshotEvent onScreenshot(NativeImage image, File screenshotFile) {
ScreenshotEvent event = new ScreenshotEvent(image, screenshotFile);
MinecraftForge.EVENT_BUS.post(event);
return event;
}
- public static void onClientChangeGameType(PlayerInfo info, GameType currentGameMode, GameType newGameMode)
- {
- if (currentGameMode != newGameMode)
- {
+ public static void onClientChangeGameType(PlayerInfo info, GameType currentGameMode, GameType newGameMode) {
+ if (currentGameMode != newGameMode) {
ClientPlayerChangeGameTypeEvent evt = new ClientPlayerChangeGameTypeEvent(info, currentGameMode, newGameMode);
MinecraftForge.EVENT_BUS.post(evt);
}
}
- public static void onMovementInputUpdate(Player player, Input movementInput)
- {
+ public static void onMovementInputUpdate(Player player, Input movementInput) {
MinecraftForge.EVENT_BUS.post(new MovementInputUpdateEvent(player, movementInput));
}
- public static boolean onScreenKeyPressedPre(Screen guiScreen, int keyCode, int scanCode, int modifiers)
- {
+ public static boolean onScreenKeyPressedPre(Screen guiScreen, int keyCode, int scanCode, int modifiers) {
Event event = new ScreenEvent.KeyPressed.Pre(guiScreen, keyCode, scanCode, modifiers);
return MinecraftForge.EVENT_BUS.post(event);
}
- public static boolean onScreenKeyPressedPost(Screen guiScreen, int keyCode, int scanCode, int modifiers)
- {
+ public static boolean onScreenKeyPressedPost(Screen guiScreen, int keyCode, int scanCode, int modifiers) {
Event event = new ScreenEvent.KeyPressed.Post(guiScreen, keyCode, scanCode, modifiers);
return MinecraftForge.EVENT_BUS.post(event);
}
- public static boolean onScreenKeyReleasedPre(Screen guiScreen, int keyCode, int scanCode, int modifiers)
- {
+ public static boolean onScreenKeyReleasedPre(Screen guiScreen, int keyCode, int scanCode, int modifiers) {
Event event = new ScreenEvent.KeyReleased.Pre(guiScreen, keyCode, scanCode, modifiers);
return MinecraftForge.EVENT_BUS.post(event);
}
- public static boolean onScreenKeyReleasedPost(Screen guiScreen, int keyCode, int scanCode, int modifiers)
- {
+ public static boolean onScreenKeyReleasedPost(Screen guiScreen, int keyCode, int scanCode, int modifiers) {
Event event = new ScreenEvent.KeyReleased.Post(guiScreen, keyCode, scanCode, modifiers);
return MinecraftForge.EVENT_BUS.post(event);
}
- public static boolean onScreenCharTypedPre(Screen guiScreen, char codePoint, int modifiers)
- {
+ public static boolean onScreenCharTypedPre(Screen guiScreen, char codePoint, int modifiers) {
Event event = new ScreenEvent.CharacterTyped.Pre(guiScreen, codePoint, modifiers);
return MinecraftForge.EVENT_BUS.post(event);
}
- public static void onScreenCharTypedPost(Screen guiScreen, char codePoint, int modifiers)
- {
+ public static void onScreenCharTypedPost(Screen guiScreen, char codePoint, int modifiers) {
Event event = new ScreenEvent.CharacterTyped.Post(guiScreen, codePoint, modifiers);
MinecraftForge.EVENT_BUS.post(event);
}
- public static void onRecipesUpdated(RecipeManager mgr)
- {
+ public static void onRecipesUpdated(RecipeManager mgr) {
Event event = new RecipesUpdatedEvent(mgr);
MinecraftForge.EVENT_BUS.post(event);
}
- public static void onKeyInput(int key, int scanCode, int action, int modifiers)
- {
+ public static void onKeyInput(int key, int scanCode, int action, int modifiers) {
MinecraftForge.EVENT_BUS.post(new InputEvent.Key(key, scanCode, action, modifiers));
}
- public static InputEvent.InteractionKeyMappingTriggered onClickInput(int button, KeyMapping keyBinding, InteractionHand hand)
- {
+ public static InputEvent.InteractionKeyMappingTriggered onClickInput(int button, KeyMapping keyBinding, InteractionHand hand) {
InputEvent.InteractionKeyMappingTriggered event = new InputEvent.InteractionKeyMappingTriggered(button, keyBinding, hand);
MinecraftForge.EVENT_BUS.post(event);
return event;
@@ -676,15 +612,13 @@ public class ForgeHooksClient
public static void renderPistonMovedBlocks(BlockPos pos, BlockState state, PoseStack stack, MultiBufferSource bufferSource, Level level, boolean checkSides, int packedOverlay, BlockRenderDispatcher blockRenderer) {
var model = blockRenderer.getBlockModel(state);
- for (var renderType : model.getRenderTypes(state, RandomSource.create(state.getSeed(pos)), ModelData.EMPTY))
- {
+ for (var renderType : model.getRenderTypes(state, RandomSource.create(state.getSeed(pos)), ModelData.EMPTY)) {
VertexConsumer vertexConsumer = bufferSource.getBuffer(RenderTypeHelper.getMovingBlockRenderType(renderType));
blockRenderer.getModelRenderer().tesselateBlock(level, model, state, pos, stack, vertexConsumer, checkSides, RandomSource.create(), state.getSeed(pos), packedOverlay, ModelData.EMPTY, renderType);
}
}
- public static boolean shouldRenderEffect(MobEffectInstance effectInstance)
- {
+ public static boolean shouldRenderEffect(MobEffectInstance effectInstance) {
return IClientMobEffectExtensions.of(effectInstance).isVisibleInInventory(effectInstance);
}
@@ -701,24 +635,16 @@ public class ForgeHooksClient
}
@Nullable
- public static TextureAtlasSprite loadTextureAtlasSprite(
- ResourceLocation atlasName,
- SpriteContents contents,
- int atlasWidth, int atlasHeight,
- int spriteX, int spriteY, int mipmapLevel
- )
- {
+ public static TextureAtlasSprite loadTextureAtlasSprite(ResourceLocation atlasName, SpriteContents contents, int atlasWidth, int atlasHeight, int spriteX, int spriteY, int mipmapLevel) {
if (contents.forgeMeta == null || contents.forgeMeta.getLoader() == null)
return null;
return contents.forgeMeta.getLoader().makeSprite(atlasName, contents, atlasWidth, atlasHeight, spriteX, spriteY, mipmapLevel);
}
-
private static final Map> layerDefinitions = new HashMap<>();
- public static void registerLayerDefinition(ModelLayerLocation layerLocation, Supplier supplier)
- {
+ public static void registerLayerDefinition(ModelLayerLocation layerLocation, Supplier supplier) {
layerDefinitions.put(layerLocation, supplier);
}
@@ -726,15 +652,14 @@ public class ForgeHooksClient
layerDefinitions.forEach((k, v) -> builder.put(k, v.get()));
}
- public static void processForgeListPingData(ServerStatus packet, ServerData target)
- {
- packet.forgeData().ifPresentOrElse(forgeData ->
- {
+ public static void processForgeListPingData(ServerStatus packet, ServerData target) {
+ packet.forgeData().ifPresentOrElse(forgeData -> {
final Map mods = forgeData.getRemoteModData();
final Map remoteChannels = forgeData.getRemoteChannels();
final int fmlver = forgeData.getFMLNetworkVersion();
- boolean fmlNetMatches = fmlver == NetworkConstants.FMLNETVERSION;
+ int wantedVer = NetworkInitialization.getVersion();
+ boolean fmlNetMatches = fmlver == wantedVer;
boolean channelsMatch = NetworkRegistry.checkListPingCompatibilityForClient(remoteChannels);
AtomicBoolean result = new AtomicBoolean(true);
final List extraClientMods = new ArrayList<>();
@@ -742,15 +667,14 @@ public class ForgeHooksClient
mc.getCustomExtension(IExtensionPoint.DisplayTest.class).ifPresent(ext-> {
boolean foundModOnServer = ext.remoteVersionTest().test(mods.get(modid), true);
result.compareAndSet(true, foundModOnServer);
- if (!foundModOnServer) {
+ if (!foundModOnServer)
extraClientMods.add(modid);
- }
})
);
boolean modsMatch = result.get();
final Map extraServerMods = mods.entrySet().stream().
- filter(e -> !Objects.equals(NetworkConstants.IGNORESERVERONLY, e.getValue())).
+ filter(e -> !Objects.equals(IExtensionPoint.DisplayTest.IGNORESERVERONLY, e.getValue())).
filter(e -> !ModList.get().isLoaded(e.getKey())).
collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
@@ -764,20 +688,19 @@ public class ForgeHooksClient
.map(e -> e.getKey() + "@" + e.getValue())
.collect(Collectors.joining(", ")));
}
+
if (!modsMatch) {
extraReason = "fml.menu.multiplayer.modsincompatible";
LOGGER.info(CLIENTHOOKS, "Client has mods that are missing on server: {}", extraClientMods);
}
- if (!channelsMatch) {
- extraReason = "fml.menu.multiplayer.networkincompatible";
- }
- if (fmlver < NetworkConstants.FMLNETVERSION) {
+ if (!channelsMatch)
+ extraReason = "fml.menu.multiplayer.networkincompatible";
+ if (fmlver < wantedVer)
extraReason = "fml.menu.multiplayer.serveroutdated";
- }
- if (fmlver > NetworkConstants.FMLNETVERSION) {
+ if (fmlver > wantedVer)
extraReason = "fml.menu.multiplayer.clientoutdated";
- }
+
target.forgeData = new ExtendedServerListData("FML", extraServerMods.isEmpty() && fmlNetMatches && channelsMatch && modsMatch, mods.size(), extraReason, forgeData.isTruncated());
}, () -> target.forgeData = new ExtendedServerListData("VANILLA", NetworkRegistry.canConnectToVanillaServer(),0, null));
}
@@ -803,9 +726,7 @@ public class ForgeHooksClient
}
}
if (target.forgeData.truncated())
- {
tooltip += "\n" + ForgeI18n.parseMessage("fml.menu.multiplayer.truncated");
- }
break;
case "VANILLA":
if (target.forgeData.isCompatible()) {
@@ -830,19 +751,15 @@ public class ForgeHooksClient
}
}
- private static Connection getClientConnection()
- {
+ private static Connection getClientConnection() {
return Minecraft.getInstance().getConnection()!=null ? Minecraft.getInstance().getConnection().getConnection() : null;
}
- public static void handleClientLevelClosing(ClientLevel level)
- {
+ public static void handleClientLevelClosing(ClientLevel level) {
Connection client = getClientConnection();
// ONLY revert a non-local connection
if (client != null && !client.isMemoryConnection())
- {
GameData.revertToFrozen();
- }
}
public static void firePlayerLogin(MultiPlayerGameMode pc, LocalPlayer player, Connection networkManager) {
@@ -870,15 +787,13 @@ public class ForgeHooksClient
}
@Nullable
- public static Component onClientChat(ChatType.Bound boundChatType, Component message, UUID sender)
- {
+ public static Component onClientChat(ChatType.Bound boundChatType, Component message, UUID sender) {
ClientChatReceivedEvent event = new ClientChatReceivedEvent(boundChatType, message, sender);
return MinecraftForge.EVENT_BUS.post(event) ? null : event.getMessage();
}
@Nullable
- public static Component onClientPlayerChat(ChatType.Bound boundChatType, Component message, PlayerChatMessage playerChatMessage, UUID sender)
- {
+ public static Component onClientPlayerChat(ChatType.Bound boundChatType, Component message, PlayerChatMessage playerChatMessage, UUID sender) {
ClientChatReceivedEvent.Player event = new ClientChatReceivedEvent.Player(boundChatType, message, playerChatMessage, sender);
return MinecraftForge.EVENT_BUS.post(event) ? null : event.getMessage();
}
@@ -888,15 +803,13 @@ public class ForgeHooksClient
private static final ChatType.Bound SYSTEM_CHAT_TYPE_BOUND = SYSTEM_CHAT_TYPE.bind(Component.literal("System"));
@Nullable
- public static Component onClientSystemChat(Component message, boolean overlay)
- {
+ public static Component onClientSystemChat(Component message, boolean overlay) {
ClientChatReceivedEvent.System event = new ClientChatReceivedEvent.System(SYSTEM_CHAT_TYPE_BOUND, message, overlay);
return MinecraftForge.EVENT_BUS.post(event) ? null : event.getMessage();
}
@NotNull
- public static String onClientSendMessage(String message)
- {
+ public static String onClientSendMessage(String message) {
ClientChatEvent event = new ClientChatEvent(message);
return MinecraftForge.EVENT_BUS.post(event) ? "" : event.getMessage();
}
@@ -906,58 +819,49 @@ public class ForgeHooksClient
* for the input {@link RenderType}.
*/
@NotNull
- public static RenderType getEntityRenderType(RenderType chunkRenderType, boolean cull)
- {
+ public static RenderType getEntityRenderType(RenderType chunkRenderType, boolean cull) {
return RenderTypeHelper.getEntityRenderType(chunkRenderType, cull);
}
@Mod.EventBusSubscriber(value = Dist.CLIENT, modid="forge", bus= Mod.EventBusSubscriber.Bus.MOD)
- public static class ClientEvents
- {
+ public static class ClientEvents {
@Nullable
private static ShaderInstance rendertypeEntityTranslucentUnlitShader;
- public static ShaderInstance getEntityTranslucentUnlitShader()
- {
+ public static ShaderInstance getEntityTranslucentUnlitShader() {
return Objects.requireNonNull(rendertypeEntityTranslucentUnlitShader, "Attempted to call getEntityTranslucentUnlitShader before shaders have finished loading.");
}
@SubscribeEvent
- public static void registerShaders(RegisterShadersEvent event) throws IOException
- {
+ public static void registerShaders(RegisterShadersEvent event) throws IOException {
event.registerShader(new ShaderInstance(event.getResourceProvider(), new ResourceLocation("forge","rendertype_entity_unlit_translucent"), DefaultVertexFormat.NEW_ENTITY), (p_172645_) -> {
rendertypeEntityTranslucentUnlitShader = p_172645_;
});
}
}
- public static Font getTooltipFont(@NotNull ItemStack stack, Font fallbackFont)
- {
+ public static Font getTooltipFont(@NotNull ItemStack stack, Font fallbackFont) {
Font stackFont = IClientItemExtensions.of(stack).getFont(stack, IClientItemExtensions.FontContext.TOOLTIP);
return stackFont == null ? fallbackFont : stackFont;
}
- public static RenderTooltipEvent.Pre onRenderTooltipPre(@NotNull ItemStack stack, GuiGraphics graphics, int x, int y, int screenWidth, int screenHeight, @NotNull List components, @NotNull Font fallbackFont, @NotNull ClientTooltipPositioner positioner)
- {
+ public static RenderTooltipEvent.Pre onRenderTooltipPre(@NotNull ItemStack stack, GuiGraphics graphics, int x, int y, int screenWidth, int screenHeight, @NotNull List components, @NotNull Font fallbackFont, @NotNull ClientTooltipPositioner positioner) {
var preEvent = new RenderTooltipEvent.Pre(stack, graphics, x, y, screenWidth, screenHeight, getTooltipFont(stack, fallbackFont), components, positioner);
MinecraftForge.EVENT_BUS.post(preEvent);
return preEvent;
}
- public static RenderTooltipEvent.Color onRenderTooltipColor(@NotNull ItemStack stack, GuiGraphics graphics, int x, int y, @NotNull Font font, @NotNull List components)
- {
+ public static RenderTooltipEvent.Color onRenderTooltipColor(@NotNull ItemStack stack, GuiGraphics graphics, int x, int y, @NotNull Font font, @NotNull List components) {
var colorEvent = new RenderTooltipEvent.Color(stack, graphics, x, y, font, 0xf0100010, 0x505000FF, 0x5028007f, components);
MinecraftForge.EVENT_BUS.post(colorEvent);
return colorEvent;
}
- public static List gatherTooltipComponents(ItemStack stack, List extends FormattedText> textElements, int mouseX, int screenWidth, int screenHeight, Font fallbackFont)
- {
+ public static List gatherTooltipComponents(ItemStack stack, List extends FormattedText> textElements, int mouseX, int screenWidth, int screenHeight, Font fallbackFont) {
return gatherTooltipComponents(stack, textElements, Optional.empty(), mouseX, screenWidth, screenHeight, fallbackFont);
}
- public static List gatherTooltipComponents(ItemStack stack, List extends FormattedText> textElements, Optional itemComponent, int mouseX, int screenWidth, int screenHeight, Font fallbackFont)
- {
+ public static List gatherTooltipComponents(ItemStack stack, List extends FormattedText> textElements, Optional itemComponent, int mouseX, int screenWidth, int screenHeight, Font fallbackFont) {
Font font = getTooltipFont(stack, fallbackFont);
List> elements = textElements.stream()
.map((Function>) Either::left)
@@ -977,11 +881,9 @@ public class ForgeHooksClient
boolean needsWrap = false;
int tooltipX = mouseX + 12;
- if (tooltipX + tooltipTextWidth + 4 > screenWidth)
- {
+ if (tooltipX + tooltipTextWidth + 4 > screenWidth) {
tooltipX = mouseX - 16 - tooltipTextWidth;
- if (tooltipX < 4) // if the tooltip doesn't fit on the screen
- {
+ if (tooltipX < 4) { // if the tooltip doesn't fit on the screen
if (mouseX > screenWidth / 2)
tooltipTextWidth = mouseX - 12 - 8;
else
@@ -990,15 +892,13 @@ public class ForgeHooksClient
}
}
- if (event.getMaxWidth() > 0 && tooltipTextWidth > event.getMaxWidth())
- {
+ if (event.getMaxWidth() > 0 && tooltipTextWidth > event.getMaxWidth()) {
tooltipTextWidth = event.getMaxWidth();
needsWrap = true;
}
int tooltipTextWidthF = tooltipTextWidth;
- if (needsWrap)
- {
+ if (needsWrap) {
return event.getTooltipElements().stream()
.flatMap(either -> either.map(
text -> splitLine(text, font, tooltipTextWidthF),
@@ -1014,115 +914,83 @@ public class ForgeHooksClient
.toList();
}
- private static Stream splitLine(FormattedText text, Font font, int maxWidth)
- {
+ private static Stream splitLine(FormattedText text, Font font, int maxWidth) {
if (text instanceof Component component && component.getString().isEmpty())
- {
return Stream.of(component.getVisualOrderText()).map(ClientTooltipComponent::create);
- }
return font.split(text, maxWidth).stream().map(ClientTooltipComponent::create);
}
- public static Comparator makeParticleRenderTypeComparator(List renderOrder)
- {
+ public static Comparator makeParticleRenderTypeComparator(List renderOrder) {
Comparator vanillaComparator = Comparator.comparingInt(renderOrder::indexOf);
- return (typeOne, typeTwo) ->
- {
+ return (typeOne, typeTwo) -> {
boolean vanillaOne = renderOrder.contains(typeOne);
boolean vanillaTwo = renderOrder.contains(typeTwo);
if (vanillaOne && vanillaTwo)
- {
return vanillaComparator.compare(typeOne, typeTwo);
- }
if (!vanillaOne && !vanillaTwo)
- {
return Integer.compare(System.identityHashCode(typeOne), System.identityHashCode(typeTwo));
- }
return vanillaOne ? -1 : 1;
};
}
- public static ScreenEvent.RenderInventoryMobEffects onScreenPotionSize(Screen screen, int availableSpace, boolean compact, int horizontalOffset)
- {
+ public static ScreenEvent.RenderInventoryMobEffects onScreenPotionSize(Screen screen, int availableSpace, boolean compact, int horizontalOffset) {
final ScreenEvent.RenderInventoryMobEffects event = new ScreenEvent.RenderInventoryMobEffects(screen, availableSpace, compact, horizontalOffset);
MinecraftForge.EVENT_BUS.post(event);
return event;
}
- public static boolean onToastAdd(Toast toast)
- {
+ public static boolean onToastAdd(Toast toast) {
return MinecraftForge.EVENT_BUS.post(new ToastAddEvent(toast));
}
- public static boolean isBlockInSolidLayer(BlockState state)
- {
+ public static boolean isBlockInSolidLayer(BlockState state) {
var model = Minecraft.getInstance().getBlockRenderer().getBlockModel(state);
return model.getRenderTypes(state, RandomSource.create(), ModelData.EMPTY).contains(RenderType.solid());
}
- public static void createWorldConfirmationScreen(Runnable doConfirmedWorldLoad)
- {
+ public static void createWorldConfirmationScreen(Runnable doConfirmedWorldLoad) {
Component title = Component.translatable("selectWorld.backupQuestion.experimental");
Component msg = Component.translatable("selectWorld.backupWarning.experimental")
.append("\n\n")
.append(Component.translatable("forge.selectWorld.backupWarning.experimental.additional"));
- Screen screen = new ConfirmScreen(confirmed ->
- {
+ Screen screen = new ConfirmScreen(confirmed -> {
if (confirmed)
- {
doConfirmedWorldLoad.run();
- }
else
- {
Minecraft.getInstance().setScreen(null);
- }
}, title, msg, CommonComponents.GUI_PROCEED, CommonComponents.GUI_CANCEL);
Minecraft.getInstance().setScreen(screen);
}
- public static boolean renderFireOverlay(Player player, PoseStack mat)
- {
+ public static boolean renderFireOverlay(Player player, PoseStack mat) {
return renderBlockOverlay(player, mat, RenderBlockScreenEffectEvent.OverlayType.FIRE, Blocks.FIRE.defaultBlockState(), player.blockPosition());
}
- public static boolean renderWaterOverlay(Player player, PoseStack mat)
- {
+ public static boolean renderWaterOverlay(Player player, PoseStack mat) {
return renderBlockOverlay(player, mat, RenderBlockScreenEffectEvent.OverlayType.WATER, Blocks.WATER.defaultBlockState(), player.blockPosition());
}
- public static boolean renderBlockOverlay(Player player, PoseStack mat, RenderBlockScreenEffectEvent.OverlayType type, BlockState block, BlockPos pos)
- {
+ public static boolean renderBlockOverlay(Player player, PoseStack mat, RenderBlockScreenEffectEvent.OverlayType type, BlockState block, BlockPos pos) {
return MinecraftForge.EVENT_BUS.post(new RenderBlockScreenEffectEvent(player, mat, type, block, pos));
}
- public static int getMaxMipmapLevel(int width, int height)
- {
+ public static int getMaxMipmapLevel(int width, int height) {
return Math.min(
Mth.log2(Math.max(1, width)),
Mth.log2(Math.max(1, height))
);
}
- public static ResourceLocation getShaderImportLocation(String basePath, boolean isRelative, String importPath)
- {
+ public static ResourceLocation getShaderImportLocation(String basePath, boolean isRelative, String importPath) {
final var loc = new ResourceLocation(importPath);
final var normalised = FileUtil.normalizeResourcePath(
(isRelative ? basePath : "shaders/include/") + loc.getPath());
return new ResourceLocation(loc.getNamespace(), normalised);
}
- // Use ForgeHooks.onCreativeModeTabBuildContents()
- // since calling this will crash if called on server
- @Deprecated(forRemoval = true, since = "1.20.1")
- public static void onCreativeModeTabBuildContents(CreativeModeTab tab, ResourceKey tabKey, CreativeModeTab.DisplayItemsGenerator originalGenerator, CreativeModeTab.ItemDisplayParameters params, CreativeModeTab.Output output)
- {
- // Bounce to ForgeHooks.onCreativeModeBuildContents(...)
- ForgeHooks.onCreativeModeTabBuildContents(tab, tabKey, originalGenerator, params, output);
- }
-
/**
* This function is a clone of {@link Direction#getNearest(float, float, float)} designed to return a consistent
* direction when the normal is at an inflection point (ie 45 degrees) rounding errors
@@ -1138,8 +1006,7 @@ public class ForgeHooksClient
* @param nZ Z component of the normal
* @return the nearest Direction to the passed in normal, biased slightly in favor of the order of declaration
*/
- public static Direction getNearestStable(float nX, float nY, float nZ)
- {
+ public static Direction getNearestStable(float nX, float nY, float nZ) {
if (ForgeConfig.CLIENT.stabilizeDirectionGetNearest.get()) {
Direction ret = Direction.NORTH;
float sum = Float.MIN_VALUE;
@@ -1151,21 +1018,17 @@ public class ForgeHooksClient
}
}
return ret;
- } else {
+ } else
return Direction.getNearest(nX, nY, nZ);
- }
}
// Make sure the below method is only ever called once (by forge).
private static boolean initializedClientHooks = false;
// Runs during Minecraft construction, before initial resource loading.
@ApiStatus.Internal
- public static void initClientHooks(Minecraft mc, ReloadableResourceManager resourceManager)
- {
+ public static void initClientHooks(Minecraft mc, ReloadableResourceManager resourceManager) {
if (initializedClientHooks)
- {
throw new IllegalStateException("Client hooks initialized more than once");
- }
initializedClientHooks = true;
ForgeGameTestHooks.registerGametests();
@@ -1184,4 +1047,12 @@ public class ForgeHooksClient
ItemDecoratorHandler.init();
PresetEditorManager.init();
}
+
+ public static boolean onClientDisconnect(Connection connection, Minecraft mc, Screen parent, Component message) {
+ var mismatch = NetworkContext.get(connection).getMismatchs();
+ if (mismatch == null)
+ return false;
+ mc.setScreen(new ModMismatchDisconnectedScreen(parent, CommonComponents.CONNECT_FAILED, message, mismatch));
+ return true;
+ }
}
diff --git a/src/main/java/net/minecraftforge/client/event/ForgeEventFactoryClient.java b/src/main/java/net/minecraftforge/client/event/ForgeEventFactoryClient.java
new file mode 100644
index 0000000000..b186e01c18
--- /dev/null
+++ b/src/main/java/net/minecraftforge/client/event/ForgeEventFactoryClient.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) Forge Development LLC and contributors
+ * SPDX-License-Identifier: LGPL-2.1-only
+ */
+
+package net.minecraftforge.client.event;
+
+import java.util.Map;
+
+import org.jetbrains.annotations.Nullable;
+
+import net.minecraft.client.MouseHandler;
+import net.minecraft.client.gui.screens.Screen;
+import net.minecraft.client.renderer.entity.EntityRenderer;
+import net.minecraft.client.renderer.entity.EntityRendererProvider.Context;
+import net.minecraft.client.resources.PlayerSkin.Model;
+import net.minecraft.world.entity.EntityType;
+import net.minecraft.world.entity.player.Player;
+import net.minecraftforge.common.MinecraftForge;
+import net.minecraftforge.eventbus.api.Event;
+import net.minecraftforge.fml.ModLoader;
+
+public class ForgeEventFactoryClient {
+ private static boolean post(Event e) {
+ return MinecraftForge.EVENT_BUS.post(e);
+ }
+
+ private static E fire(E e) {
+ MinecraftForge.EVENT_BUS.post(e);
+ return e;
+ }
+
+ public static void gatherLayers(Map, EntityRenderer>> renderers, Map> playerRenderers, Context context) {
+ // TODO: Why is this a ModLoader event...
+ ModLoader.get().postEvent(new EntityRenderersEvent.AddLayers(renderers, playerRenderers, context));
+ }
+
+ public static boolean onScreenMouseReleasedPre(Screen guiScreen, double mouseX, double mouseY, int button) {
+ return post(new ScreenEvent.MouseButtonReleased.Pre(guiScreen, mouseX, mouseY, button));
+ }
+
+ public static boolean onScreenMouseReleasedPost(Screen guiScreen, double mouseX, double mouseY, int button, boolean handled) {
+ var result = fire(new ScreenEvent.MouseButtonReleased.Post(guiScreen, mouseX, mouseY, button, handled)).getResult();
+ return result == Event.Result.DEFAULT ? handled : result == Event.Result.ALLOW;
+ }
+
+ public static boolean onScreenMouseClickedPre(Screen guiScreen, double mouseX, double mouseY, int button) {
+ return post(new ScreenEvent.MouseButtonPressed.Pre(guiScreen, mouseX, mouseY, button));
+ }
+
+ public static boolean onScreenMouseClickedPost(Screen guiScreen, double mouseX, double mouseY, int button, boolean handled) {
+ var result = fire(new ScreenEvent.MouseButtonPressed.Post(guiScreen, mouseX, mouseY, button, handled)).getResult();
+ return result == Event.Result.DEFAULT ? handled : result == Event.Result.ALLOW;
+ }
+
+ public static boolean onMouseButtonPre(int button, int action, int mods) {
+ return post(new InputEvent.MouseButton.Pre(button, action, mods));
+ }
+
+ public static void onMouseButtonPost(int button, int action, int mods) {
+ post(new InputEvent.MouseButton.Post(button, action, mods));
+ }
+
+ public static boolean onScreenMouseScrollPre(Screen guiScreen, double mouseX, double mouseY, double deltaX, double deltaY) {
+ return post(new ScreenEvent.MouseScrolled.Pre(guiScreen, mouseX, mouseY, deltaX, deltaY));
+ }
+
+ public static void onScreenMouseScrollPost(Screen guiScreen, double mouseX, double mouseY, double deltaX, double deltaY) {
+ post(new ScreenEvent.MouseScrolled.Post(guiScreen, mouseX, mouseY, deltaX, deltaY));
+ }
+
+ public static boolean onMouseScroll(MouseHandler mouseHelper, double deltaX, double deltaY) {
+ return post(new InputEvent.MouseScrollingEvent(deltaX, deltaY, mouseHelper.isLeftPressed(), mouseHelper.isMiddlePressed(), mouseHelper.isRightPressed(), mouseHelper.xpos(), mouseHelper.ypos()));
+ }
+
+ public static boolean onScreenMouseDragPre(Screen guiScreen, double mouseX, double mouseY, int mouseButton, double dragX, double dragY) {
+ return post(new ScreenEvent.MouseDragged.Pre(guiScreen, mouseX, mouseY, mouseButton, dragX, dragY));
+ }
+
+ public static void onScreenMouseDragPost(Screen guiScreen, double mouseX, double mouseY, int mouseButton, double dragX, double dragY) {
+ post(new ScreenEvent.MouseDragged.Post(guiScreen, mouseX, mouseY, mouseButton, dragX, dragY));
+ }
+
+ public static @Nullable Screen onScreenOpening(Screen old, Screen screen) {
+ var event = new ScreenEvent.Opening(old, screen);
+ if (post(event))
+ return null;
+ return event.getNewScreen();
+ }
+
+ public static void onScreenClose(Screen screen) {
+ post(new ScreenEvent.Closing(screen));
+ }
+}
diff --git a/src/main/java/net/minecraftforge/client/gui/ModMismatchDisconnectedScreen.java b/src/main/java/net/minecraftforge/client/gui/ModMismatchDisconnectedScreen.java
index f07aabd80e..3d4d19fa6e 100644
--- a/src/main/java/net/minecraftforge/client/gui/ModMismatchDisconnectedScreen.java
+++ b/src/main/java/net/minecraftforge/client/gui/ModMismatchDisconnectedScreen.java
@@ -10,7 +10,6 @@ import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
-import java.util.Map.Entry;
import java.util.Optional;
import java.util.stream.Collectors;
@@ -39,46 +38,43 @@ import net.minecraft.util.FormattedCharSequence;
import net.minecraftforge.common.ForgeI18n;
import net.minecraftforge.fml.ModList;
import net.minecraftforge.fml.loading.FMLPaths;
-import net.minecraftforge.network.ConnectionData.ModMismatchData;
-import net.minecraftforge.network.NetworkRegistry;
+import net.minecraftforge.network.NetworkContext.NetworkMismatchData;
+import net.minecraftforge.network.packets.ModVersions;
-public class ModMismatchDisconnectedScreen extends Screen
-{
+//TODO: Oh god... Whoever wrote this was on something very very strong.
+public class ModMismatchDisconnectedScreen extends Screen {
private final Component reason;
private MultiLineLabel message = MultiLineLabel.EMPTY;
private final Screen parent;
private int textHeight;
- private final ModMismatchData modMismatchData;
private final Path modsDir;
private final Path logFile;
private final int listHeight;
- private final Map> presentModData;
- private final List missingModData;
- private final Map mismatchedModData;
+ private final NetworkMismatchData data;
+ private final boolean hasMismatches;
+
private final List allModIds;
private final Map presentModUrls;
- private final boolean mismatchedDataFromServer;
- public ModMismatchDisconnectedScreen(Screen parentScreen, Component title, Component reason, ModMismatchData modMismatchData)
- {
+ public ModMismatchDisconnectedScreen(Screen parentScreen, Component title, Component reason, NetworkMismatchData data) {
super(title);
this.parent = parentScreen;
this.reason = reason;
- this.modMismatchData = modMismatchData;
this.modsDir = FMLPaths.MODSDIR.get();
this.logFile = FMLPaths.GAMEDIR.get().resolve(Paths.get("logs","latest.log"));
- this.listHeight = modMismatchData.containsMismatches() ? 140 : 0;
- this.mismatchedDataFromServer = modMismatchData.mismatchedDataFromServer();
- this.presentModData = modMismatchData.presentModData();
- this.missingModData = modMismatchData.mismatchedModData().entrySet().stream().filter(e -> e.getValue().equals(NetworkRegistry.ABSENT.version())).map(Entry::getKey).collect(Collectors.toList());
- this.mismatchedModData = modMismatchData.mismatchedModData().entrySet().stream().filter(e -> !e.getValue().equals(NetworkRegistry.ABSENT.version())).collect(Collectors.toMap(Entry::getKey, Entry::getValue));
- this.allModIds = presentModData.keySet().stream().map(ResourceLocation::getNamespace).distinct().collect(Collectors.toList());
- this.presentModUrls = ModList.get().getMods().stream().filter(info -> allModIds.contains(info.getModId())).map(info -> Pair.of(info.getModId(), (String)info.getConfig().getConfigElement("displayURL").orElse(""))).collect(Collectors.toMap(Pair::getLeft, Pair::getRight));
+ this.data = data;
+ this.hasMismatches = !data.mismatched().isEmpty() || !data.missing().isEmpty();
+ this.listHeight = hasMismatches ? 140 : 0;
+
+ this.allModIds = data.mods().keySet().stream().distinct().collect(Collectors.toList());
+ this.presentModUrls = ModList.get().getMods().stream()
+ .filter(info -> allModIds.contains(info.getModId()))
+ .map(info -> Pair.of(info.getModId(), (String)info.getConfig().getConfigElement("displayURL").orElse("")))
+ .collect(Collectors.toMap(Pair::getLeft, Pair::getRight));
}
@Override
- protected void init()
- {
+ protected void init() {
this.message = MultiLineLabel.create(this.font, this.reason, this.width - 50);
this.textHeight = this.message.getLineCount() * 9;
@@ -86,7 +82,7 @@ public class ModMismatchDisconnectedScreen extends Screen
int listWidth = Math.min(440, this.width - 16);
int upperButtonHeight = Math.min((this.height + this.listHeight + this.textHeight) / 2 + 10, this.height - 50);
int lowerButtonHeight = Math.min((this.height + this.listHeight + this.textHeight) / 2 + 35, this.height - 25);
- if (modMismatchData.containsMismatches())
+ if (hasMismatches)
this.addRenderableWidget(new MismatchInfoPanel(minecraft, listWidth, listHeight, (this.height - this.listHeight) / 2, listLeft));
int buttonWidth = Math.min(210, this.width / 2 - 20);
@@ -102,17 +98,15 @@ public class ModMismatchDisconnectedScreen extends Screen
}
@Override
- public void render(GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTicks)
- {
+ public void render(GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTicks) {
this.renderBackground(guiGraphics, mouseX, mouseY, partialTicks);
- int textYOffset = modMismatchData.containsMismatches() ? 18 : 0;
+ int textYOffset = hasMismatches ? 18 : 0;
guiGraphics.drawCenteredString(this.font, this.title, this.width / 2, (this.height - this.listHeight - this.textHeight) / 2 - textYOffset - 9 * 2, 0xAAAAAA);
this.message.renderCentered(guiGraphics, this.width / 2, (this.height - this.listHeight - this.textHeight) / 2 - textYOffset);
super.render(guiGraphics, mouseX, mouseY, partialTicks);
}
- class MismatchInfoPanel extends ScrollPanel
- {
+ class MismatchInfoPanel extends ScrollPanel {
private final List>> lineTable;
private final int contentSize;
private final int nameIndent = 10;
@@ -120,41 +114,69 @@ public class ModMismatchDisconnectedScreen extends Screen
private final int nameWidth = tableWidth * 3 / 5;
private final int versionWidth = (tableWidth - nameWidth) / 2;
- public MismatchInfoPanel(Minecraft client, int width, int height, int top, int left)
- {
+ public MismatchInfoPanel(Minecraft client, int width, int height, int top, int left) {
super(client, width, height, top, left);
//The raw list of the strings in a table row, the components may still be too long for the final table and will be split up later. The first row element may have a style assigned to it that will be used for the whole content row.
List>> rawTable = new ArrayList<>();
- if (!missingModData.isEmpty())
- {
+ if (!data.missing().isEmpty()) {
//The header of the section, colored in gray
- rawTable.add(Pair.of(Component.literal(ForgeI18n.parseMessage(mismatchedDataFromServer ? "fml.modmismatchscreen.missingmods.server" : "fml.modmismatchscreen.missingmods.client")).withStyle(ChatFormatting.GRAY), null));
+ rawTable.add(Pair.of(
+ Component.literal(ForgeI18n.parseMessage(data.fromServer() ? "fml.modmismatchscreen.missingmods.server" : "fml.modmismatchscreen.missingmods.client")).withStyle(ChatFormatting.GRAY),
+ null
+ ));
//This table section contains the mod name and mod version of each mod that has a missing remote counterpart (if the mod is missing on the server, the client mod version is displayed, and vice versa)
- rawTable.add(Pair.of(Component.literal(ForgeI18n.parseMessage("fml.modmismatchscreen.table.modname")).withStyle(ChatFormatting.UNDERLINE), Pair.of("", ForgeI18n.parseMessage(mismatchedDataFromServer ? "fml.modmismatchscreen.table.youhave" : "fml.modmismatchscreen.table.youneed"))));
+ rawTable.add(Pair.of(
+ Component.literal(ForgeI18n.parseMessage("fml.modmismatchscreen.table.modname")).withStyle(ChatFormatting.UNDERLINE),
+ Pair.of(
+ "",
+ ForgeI18n.parseMessage(data.fromServer() ? "fml.modmismatchscreen.table.youhave" : "fml.modmismatchscreen.table.youneed")
+ )
+ ));
int i = 0;
- for (ResourceLocation mod : missingModData) {
- rawTable.add(Pair.of(toModNameComponent(mod, presentModData.get(mod).getLeft(), i), Pair.of("", presentModData.getOrDefault(mod, Pair.of("", "")).getRight())));
+ for (ResourceLocation mod : data.missing()) {
+ rawTable.add(Pair.of(
+ toModNameComponent(mod, data.mods().get(mod.getNamespace()).name(), i),
+ Pair.of(
+ "",
+ data.mods().getOrDefault(mod, new ModVersions.Info("", "")).version()
+ )
+ ));
if (++i >= 10) {
//If too many missing mod entries are present, append a line referencing how to see the full list and stop rendering any more entries
- rawTable.add(Pair.of(Component.literal(ForgeI18n.parseMessage("fml.modmismatchscreen.additional", missingModData.size() - i)).withStyle(ChatFormatting.ITALIC), Pair.of("", "")));
+ rawTable.add(Pair.of(
+ Component.literal(ForgeI18n.parseMessage("fml.modmismatchscreen.additional", data.missing().size() - i)).withStyle(ChatFormatting.ITALIC),
+ Pair.of("", "")
+ ));
break;
}
}
rawTable.add(Pair.of(Component.literal(" "), null)); //padding
}
- if (!mismatchedModData.isEmpty())
- {
+
+ if (!data.mismatched().isEmpty()) {
//The header of the table section, colored in gray
rawTable.add(Pair.of(Component.literal(ForgeI18n.parseMessage("fml.modmismatchscreen.mismatchedmods")).withStyle(ChatFormatting.GRAY), null));
//This table section contains the mod name and both mod versions of each mod that has a mismatching client and server version
- rawTable.add(Pair.of(Component.literal(ForgeI18n.parseMessage("fml.modmismatchscreen.table.modname")).withStyle(ChatFormatting.UNDERLINE), Pair.of(ForgeI18n.parseMessage(mismatchedDataFromServer ? "fml.modmismatchscreen.table.youhave" : "fml.modmismatchscreen.table.serverhas"), ForgeI18n.parseMessage(mismatchedDataFromServer ? "fml.modmismatchscreen.table.serverhas" : "fml.modmismatchscreen.table.youhave"))));
+ rawTable.add(Pair.of(
+ Component.literal(ForgeI18n.parseMessage("fml.modmismatchscreen.table.modname")).withStyle(ChatFormatting.UNDERLINE),
+ Pair.of(
+ ForgeI18n.parseMessage(data.fromServer() ? "fml.modmismatchscreen.table.youhave" : "fml.modmismatchscreen.table.serverhas"),
+ ForgeI18n.parseMessage(data.fromServer() ? "fml.modmismatchscreen.table.serverhas" : "fml.modmismatchscreen.table.youhave")
+ )
+ ));
int i = 0;
- for (Map.Entry modData : mismatchedModData.entrySet()) {
- rawTable.add(Pair.of(toModNameComponent(modData.getKey(), presentModData.get(modData.getKey()).getLeft(), i), Pair.of(presentModData.getOrDefault(modData.getKey(), Pair.of("", "")).getRight(), modData.getValue())));
+ for (var modData : data.mismatched().entrySet()) {
+ rawTable.add(Pair.of(
+ toModNameComponent(modData.getKey(), data.mods().get(modData.getKey().getNamespace()).name(), i),
+ Pair.of(
+ data.mods().getOrDefault(modData.getKey(), new ModVersions.Info("", "")).version(),
+ modData.getValue().received()
+ )
+ ));
if (++i >= 10) {
//If too many mismatched mod entries are present, append a line referencing how to see the full list and stop rendering any more entries
- rawTable.add(Pair.of(Component.literal(ForgeI18n.parseMessage("fml.modmismatchscreen.additional", mismatchedModData.size() - i)).withStyle(ChatFormatting.ITALIC), Pair.of("", "")));
+ rawTable.add(Pair.of(Component.literal(ForgeI18n.parseMessage("fml.modmismatchscreen.additional", data.mismatched().size() - i)).withStyle(ChatFormatting.ITALIC), Pair.of("", "")));
break;
}
}
@@ -172,8 +194,7 @@ public class ModMismatchDisconnectedScreen extends Screen
* @param versions The last two elements of the content row, usually representing the mod versions. If either one or both of them are not given, the first element may take up more space within the table.
* @return A list of table rows consisting of 3 elements each which consist of the same content as was given by the parameters, but split up to fit within the table dimensions.
*/
- private List>> splitLineToWidth(MutableComponent name, Pair versions)
- {
+ private List>> splitLineToWidth(MutableComponent name, Pair versions) {
Style style = name.getStyle();
int versionColumns = versions == null ? 0 : (versions.getLeft().isEmpty() ? (versions.getRight().isEmpty() ? 0 : 1) : 2);
int adaptedNameWidth = nameWidth + versionWidth * (2 - versionColumns) - 4; //the name width may be expanded when the version column string is missing
@@ -183,7 +204,13 @@ public class ModMismatchDisconnectedScreen extends Screen
List>> splitLines = new ArrayList<>();
int rowsOccupied = Math.max(nameLines.size(), Math.max(clientVersionLines.size(), serverVersionLines.size()));
for (int i = 0; i < rowsOccupied; i++) {
- splitLines.add(Pair.of(i < nameLines.size() ? nameLines.get(i) : FormattedCharSequence.EMPTY, versions == null ? null : Pair.of(i < clientVersionLines.size() ? clientVersionLines.get(i) : FormattedCharSequence.EMPTY, i < serverVersionLines.size() ? serverVersionLines.get(i) : FormattedCharSequence.EMPTY)));
+ splitLines.add(Pair.of(
+ i < nameLines.size() ? nameLines.get(i) : FormattedCharSequence.EMPTY,
+ versions == null ? null : Pair.of(
+ i < clientVersionLines.size() ? clientVersionLines.get(i) : FormattedCharSequence.EMPTY,
+ i < serverVersionLines.size() ? serverVersionLines.get(i) : FormattedCharSequence.EMPTY
+ )
+ ));
}
return splitLines;
}
@@ -196,8 +223,7 @@ public class ModMismatchDisconnectedScreen extends Screen
* @param color Defines the color of the returned style information. An odd number will result in a yellow, an even one in a gold color. This color variation makes it easier for users to distinguish different mod entries.
* @return A component with the mod name as the main text component, and an assigned style which will be used for the whole content row.
*/
- private MutableComponent toModNameComponent(ResourceLocation id, String modName, int color)
- {
+ private MutableComponent toModNameComponent(ResourceLocation id, String modName, int color) {
String modId = id.getNamespace();
String tooltipId = id.getPath().isEmpty() ? id.getNamespace() : id.toString();
return Component.literal(modName).withStyle(color % 2 == 0 ? ChatFormatting.GOLD : ChatFormatting.YELLOW)
@@ -206,8 +232,7 @@ public class ModMismatchDisconnectedScreen extends Screen
}
@Override
- protected int getContentHeight()
- {
+ protected int getContentHeight() {
int height = contentSize * (font.lineHeight + 3);
if (height < bottom - top - 4)
@@ -217,8 +242,7 @@ public class ModMismatchDisconnectedScreen extends Screen
}
@Override
- protected void drawPanel(GuiGraphics guiGraphics, int entryRight, int relativeY, Tesselator tess, int mouseX, int mouseY)
- {
+ protected void drawPanel(GuiGraphics guiGraphics, int entryRight, int relativeY, Tesselator tess, int mouseX, int mouseY) {
int i = 0;
for (Pair> line : lineTable) {
@@ -229,8 +253,7 @@ public class ModMismatchDisconnectedScreen extends Screen
//Only indent the given name if a version string is present. This makes it easier to distinguish table section headers and mod entries
int nameLeft = left + border + (versions == null ? 0 : nameIndent);
guiGraphics.drawString(font, name, nameLeft, relativeY + i * 12, color, false);
- if (versions != null)
- {
+ if (versions != null) {
guiGraphics.drawString(font, versions.getLeft(), left + border + nameIndent + nameWidth, relativeY + i * 12, color, false);
guiGraphics.drawString(font, versions.getRight(), left + border + nameIndent + nameWidth + versionWidth, relativeY + i * 12, color, false);
}
@@ -240,24 +263,18 @@ public class ModMismatchDisconnectedScreen extends Screen
}
@Override
- public void render(GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTicks)
- {
+ public void render(GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTicks) {
super.render(guiGraphics, mouseX, mouseY, partialTicks);
Style style = getComponentStyleAt(mouseX, mouseY);
if (style != null && style.getHoverEvent() != null)
- {
guiGraphics.renderComponentHoverEffect(font, style, mouseX, mouseY);
- }
}
- public Style getComponentStyleAt(double x, double y)
- {
- if (this.isMouseOver(x, y))
- {
+ public Style getComponentStyleAt(double x, double y) {
+ if (this.isMouseOver(x, y)) {
double relativeY = y - this.top + this.scrollDistance - border;
int slotIndex = (int)(relativeY + (border / 2)) / 12;
- if (slotIndex < contentSize)
- {
+ if (slotIndex < contentSize) {
//The relative x needs to take the potentially missing indent of the row into account. It does that by checking if the line has a version associated to it
double relativeX = x - left - border - (lineTable.get(slotIndex).getRight() == null ? 0 : nameIndent);
if (relativeX >= 0)
@@ -269,8 +286,7 @@ public class ModMismatchDisconnectedScreen extends Screen
}
@Override
- public boolean mouseClicked(final double mouseX, final double mouseY, final int button)
- {
+ public boolean mouseClicked(final double mouseX, final double mouseY, final int button) {
Style style = getComponentStyleAt(mouseX, mouseY);
if (style != null) {
handleComponentClicked(style);
@@ -280,8 +296,7 @@ public class ModMismatchDisconnectedScreen extends Screen
}
@Override
- public NarrationPriority narrationPriority()
- {
+ public NarrationPriority narrationPriority() {
return NarrationPriority.NONE;
}
diff --git a/src/main/java/net/minecraftforge/common/ForgeHooks.java b/src/main/java/net/minecraftforge/common/ForgeHooks.java
index 7976993c76..f6592705fa 100644
--- a/src/main/java/net/minecraftforge/common/ForgeHooks.java
+++ b/src/main/java/net/minecraftforge/common/ForgeHooks.java
@@ -5,41 +5,26 @@
package net.minecraftforge.common;
-import com.google.common.collect.Queues;
import java.net.URI;
import java.net.URISyntaxException;
-import java.util.ArrayList;
-import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
-import java.util.Deque;
import java.util.HashMap;
import java.util.List;
-import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
-import java.util.Set;
-import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
-import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
-import com.google.common.collect.Sets;
-import com.google.gson.Gson;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParseException;
import com.mojang.serialization.Dynamic;
import com.mojang.serialization.Lifecycle;
-import it.unimi.dsi.fastutil.objects.ObjectArrayList;
-import net.minecraft.ResourceLocationException;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.SharedSuggestionProvider;
@@ -50,28 +35,21 @@ import net.minecraft.core.HolderLookup;
import net.minecraft.core.HolderSet;
import net.minecraft.core.particles.ParticleTypes;
import net.minecraft.core.registries.Registries;
-import net.minecraft.network.chat.ChatDecorator;
+import net.minecraft.network.Connection;
import net.minecraft.network.chat.ClickEvent;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.network.chat.TextColor;
import net.minecraft.network.chat.contents.LiteralContents;
import net.minecraft.server.level.ServerLevel;
-import net.minecraft.server.packs.PackType;
-import net.minecraft.server.packs.metadata.pack.PackMetadataSection;
-import net.minecraft.server.packs.resources.Resource;
-import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.tags.BlockTags;
-import net.minecraft.tags.TagEntry;
import net.minecraft.tags.TagKey;
import net.minecraft.util.CrudeIncrementalIntIdentityHashBiMap;
-import net.minecraft.util.GsonHelper;
import net.minecraft.util.Mth;
import net.minecraft.util.datafix.fixes.StructuresBecomeConfiguredFix;
import net.minecraft.world.Difficulty;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
-import net.minecraft.world.effect.MobEffect;
import net.minecraft.world.effect.MobEffectUtil;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
@@ -98,14 +76,11 @@ import net.minecraft.world.level.gameevent.GameEvent;
import net.minecraft.world.level.material.Fluids;
import net.minecraft.world.level.storage.LevelStorageSource;
import net.minecraft.world.level.storage.WorldData;
-import net.minecraft.world.level.storage.loot.LootContext;
-import net.minecraft.world.level.storage.loot.LootTable;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.item.enchantment.EnchantmentHelper;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.server.level.ServerPlayer;
-import net.minecraft.server.network.FilteredText;
import net.minecraft.world.inventory.AnvilMenu;
import net.minecraft.world.Container;
import net.minecraft.world.item.context.UseOnContext;
@@ -147,7 +122,6 @@ import net.minecraftforge.event.VanillaGameEvent;
import net.minecraftforge.event.entity.EntityAttributeCreationEvent;
import net.minecraftforge.event.entity.EntityAttributeModificationEvent;
import net.minecraftforge.event.entity.EntityEvent;
-import net.minecraftforge.event.entity.EntityTravelToDimensionEvent;
import net.minecraftforge.event.entity.item.ItemTossEvent;
import net.minecraftforge.event.entity.living.EnderManAngerEvent;
import net.minecraftforge.event.entity.living.LivingAttackEvent;
@@ -177,9 +151,17 @@ import net.minecraftforge.event.entity.living.LivingGetProjectileEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.event.level.BlockEvent;
import net.minecraftforge.event.level.NoteBlockEvent;
+import net.minecraftforge.event.network.CustomPayloadEvent;
+import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.fluids.FluidType;
import net.minecraftforge.fml.ModList;
import net.minecraftforge.fml.ModLoader;
+import net.minecraftforge.fml.config.ConfigTracker;
+import net.minecraftforge.fml.util.thread.EffectiveSide;
+import net.minecraftforge.network.ConnectionType;
+import net.minecraftforge.network.ICustomPacket;
+import net.minecraftforge.network.NetworkContext;
+import net.minecraftforge.network.NetworkRegistry;
import net.minecraftforge.resource.ResourcePackLoader;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.ForgeRegistry;
@@ -187,7 +169,6 @@ import net.minecraftforge.registries.GameData;
import net.minecraftforge.registries.RegistryManager;
import net.minecraftforge.server.permission.PermissionAPI;
-import org.apache.commons.lang3.function.TriFunction;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
@@ -207,124 +188,103 @@ import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
-public class ForgeHooks
-{
+public class ForgeHooks {
private static final Logger LOGGER = LogManager.getLogger();
@SuppressWarnings("unused")
private static final Marker FORGEHOOKS = MarkerManager.getMarker("FORGEHOOKS");
private static final Marker WORLDPERSISTENCE = MarkerManager.getMarker("WP");
- public static boolean canContinueUsing(@NotNull ItemStack from, @NotNull ItemStack to)
- {
+ public static boolean canContinueUsing(@NotNull ItemStack from, @NotNull ItemStack to) {
if (!from.isEmpty() && !to.isEmpty())
- {
return from.getItem().canContinueUsing(from, to);
- }
return false;
}
- public static boolean isCorrectToolForDrops(@NotNull BlockState state, @NotNull Player player)
- {
+ public static boolean isCorrectToolForDrops(@NotNull BlockState state, @NotNull Player player) {
if (!state.requiresCorrectToolForDrops())
return ForgeEventFactory.doPlayerHarvestCheck(player, state, true);
return player.hasCorrectToolForDrops(state);
}
- public static boolean onItemStackedOn(ItemStack carriedItem, ItemStack stackedOnItem, Slot slot, ClickAction action, Player player, SlotAccess carriedSlotAccess)
- {
+ public static boolean onItemStackedOn(ItemStack carriedItem, ItemStack stackedOnItem, Slot slot, ClickAction action, Player player, SlotAccess carriedSlotAccess) {
return MinecraftForge.EVENT_BUS.post(new ItemStackedOnOtherEvent(carriedItem, stackedOnItem, slot, action, player, carriedSlotAccess));
}
- public static void onDifficultyChange(Difficulty difficulty, Difficulty oldDifficulty)
- {
+ public static void onDifficultyChange(Difficulty difficulty, Difficulty oldDifficulty) {
MinecraftForge.EVENT_BUS.post(new DifficultyChangeEvent(difficulty, oldDifficulty));
}
- public static LivingChangeTargetEvent onLivingChangeTarget(LivingEntity entity, LivingEntity originalTarget, ILivingTargetType targetType)
- {
+ public static LivingChangeTargetEvent onLivingChangeTarget(LivingEntity entity, LivingEntity originalTarget, ILivingTargetType targetType) {
LivingChangeTargetEvent event = new LivingChangeTargetEvent(entity, originalTarget, targetType);
MinecraftForge.EVENT_BUS.post(event);
return event;
}
- public static Brain> onLivingMakeBrain(LivingEntity entity, Brain> originalBrain, Dynamic> dynamic)
- {
+ public static Brain> onLivingMakeBrain(LivingEntity entity, Brain> originalBrain, Dynamic> dynamic) {
BrainBuilder> brainBuilder = originalBrain.createBuilder();
LivingMakeBrainEvent event = new LivingMakeBrainEvent(entity, brainBuilder);
MinecraftForge.EVENT_BUS.post(event);
return brainBuilder.makeBrain(dynamic);
}
- public static boolean onLivingTick(LivingEntity entity)
- {
+ public static boolean onLivingTick(LivingEntity entity) {
return MinecraftForge.EVENT_BUS.post(new LivingTickEvent(entity));
}
- public static boolean onLivingAttack(LivingEntity entity, DamageSource src, float amount)
- {
+ public static boolean onLivingAttack(LivingEntity entity, DamageSource src, float amount) {
return entity instanceof Player || !MinecraftForge.EVENT_BUS.post(new LivingAttackEvent(entity, src, amount));
}
- public static boolean onPlayerAttack(LivingEntity entity, DamageSource src, float amount)
- {
+ public static boolean onPlayerAttack(LivingEntity entity, DamageSource src, float amount) {
return !MinecraftForge.EVENT_BUS.post(new LivingAttackEvent(entity, src, amount));
}
- public static LivingKnockBackEvent onLivingKnockBack(LivingEntity target, float strength, double ratioX, double ratioZ)
- {
+ public static LivingKnockBackEvent onLivingKnockBack(LivingEntity target, float strength, double ratioX, double ratioZ) {
LivingKnockBackEvent event = new LivingKnockBackEvent(target, strength, ratioX, ratioZ);
MinecraftForge.EVENT_BUS.post(event);
return event;
}
- public static boolean onLivingUseTotem(LivingEntity entity, DamageSource damageSource, ItemStack totem, InteractionHand hand)
- {
+ public static boolean onLivingUseTotem(LivingEntity entity, DamageSource damageSource, ItemStack totem, InteractionHand hand) {
return !MinecraftForge.EVENT_BUS.post(new LivingUseTotemEvent(entity, damageSource, totem, hand));
}
- public static float onLivingHurt(LivingEntity entity, DamageSource src, float amount)
- {
+ public static float onLivingHurt(LivingEntity entity, DamageSource src, float amount) {
LivingHurtEvent event = new LivingHurtEvent(entity, src, amount);
return (MinecraftForge.EVENT_BUS.post(event) ? 0 : event.getAmount());
}
- public static float onLivingDamage(LivingEntity entity, DamageSource src, float amount)
- {
+ public static float onLivingDamage(LivingEntity entity, DamageSource src, float amount) {
LivingDamageEvent event = new LivingDamageEvent(entity, src, amount);
return (MinecraftForge.EVENT_BUS.post(event) ? 0 : event.getAmount());
}
- public static boolean onLivingDeath(LivingEntity entity, DamageSource src)
- {
+ public static boolean onLivingDeath(LivingEntity entity, DamageSource src) {
return MinecraftForge.EVENT_BUS.post(new LivingDeathEvent(entity, src));
}
- public static boolean onLivingDrops(LivingEntity entity, DamageSource source, Collection drops, int lootingLevel, boolean recentlyHit)
- {
+ public static boolean onLivingDrops(LivingEntity entity, DamageSource source, Collection drops, int lootingLevel, boolean recentlyHit) {
return MinecraftForge.EVENT_BUS.post(new LivingDropsEvent(entity, source, drops, lootingLevel, recentlyHit));
}
@Nullable
- public static float[] onLivingFall(LivingEntity entity, float distance, float damageMultiplier)
- {
+ public static float[] onLivingFall(LivingEntity entity, float distance, float damageMultiplier) {
LivingFallEvent event = new LivingFallEvent(entity, distance, damageMultiplier);
return (MinecraftForge.EVENT_BUS.post(event) ? null : new float[]{event.getDistance(), event.getDamageMultiplier()});
}
- public static int getLootingLevel(Entity target, @Nullable Entity killer, @Nullable DamageSource cause)
- {
+ public static int getLootingLevel(Entity target, @Nullable Entity killer, @Nullable DamageSource cause) {
int looting = 0;
- if (killer instanceof LivingEntity)
- looting = EnchantmentHelper.getMobLooting((LivingEntity)killer);
- if (target instanceof LivingEntity)
- looting = getLootingLevel((LivingEntity)target, cause, looting);
+ if (killer instanceof LivingEntity living)
+ looting = EnchantmentHelper.getMobLooting(living);
+ if (target instanceof LivingEntity living)
+ looting = getLootingLevel(living, cause, looting);
return looting;
}
- public static int getLootingLevel(LivingEntity target, @Nullable DamageSource cause, int level)
- {
+ public static int getLootingLevel(LivingEntity target, @Nullable DamageSource cause, int level) {
LootingLevelEvent event = new LootingLevelEvent(target, cause, level);
MinecraftForge.EVENT_BUS.post(event);
return event.getLootingLevel();
@@ -336,32 +296,23 @@ public class ForgeHooks
return Math.max(0,event.getVisibilityModifier());
}
- public static Optional isLivingOnLadder(@NotNull BlockState state, @NotNull Level level, @NotNull BlockPos pos, @NotNull LivingEntity entity)
- {
+ public static Optional isLivingOnLadder(@NotNull BlockState state, @NotNull Level level, @NotNull BlockPos pos, @NotNull LivingEntity entity) {
boolean isSpectator = (entity instanceof Player && entity.isSpectator());
if (isSpectator) return Optional.empty();
if (!ForgeConfig.SERVER.fullBoundingBoxLadders.get())
- {
return state.isLadder(level, pos, entity) ? Optional.of(pos) : Optional.empty();
- }
- else
- {
+ else {
AABB bb = entity.getBoundingBox();
int mX = Mth.floor(bb.minX);
int mY = Mth.floor(bb.minY);
int mZ = Mth.floor(bb.minZ);
- for (int y2 = mY; y2 < bb.maxY; y2++)
- {
- for (int x2 = mX; x2 < bb.maxX; x2++)
- {
- for (int z2 = mZ; z2 < bb.maxZ; z2++)
- {
+ for (int y2 = mY; y2 < bb.maxY; y2++) {
+ for (int x2 = mX; x2 < bb.maxX; x2++) {
+ for (int z2 = mZ; z2 < bb.maxZ; z2++) {
BlockPos tmp = new BlockPos(x2, y2, z2);
state = level.getBlockState(tmp);
if (state.isLadder(level, tmp, entity))
- {
return Optional.of(tmp);
- }
}
}
}
@@ -369,14 +320,13 @@ public class ForgeHooks
}
}
- public static void onLivingJump(LivingEntity entity)
- {
+ public static void onLivingJump(LivingEntity entity) {
MinecraftForge.EVENT_BUS.post(new LivingJumpEvent(entity));
}
+ @SuppressWarnings("resource")
@Nullable
- public static ItemEntity onPlayerTossEvent(@NotNull Player player, @NotNull ItemStack item, boolean includeName)
- {
+ public static ItemEntity onPlayerTossEvent(@NotNull Player player, @NotNull ItemStack item, boolean includeName) {
player.captureDrops(Lists.newArrayList());
ItemEntity ret = player.drop(item, false, includeName);
player.captureDrops(null);
@@ -393,8 +343,7 @@ public class ForgeHooks
return event.getEntity();
}
- public static boolean onVanillaGameEvent(Level level, GameEvent vanillaEvent, Vec3 pos, GameEvent.Context context)
- {
+ public static boolean onVanillaGameEvent(Level level, GameEvent vanillaEvent, Vec3 pos, GameEvent.Context context) {
return !MinecraftForge.EVENT_BUS.post(new VanillaGameEvent(level, vanillaEvent, pos, context));
}
@@ -412,8 +361,7 @@ public class ForgeHooks
Pattern.CASE_INSENSITIVE);
public static Component newChatWithLinks(String string){ return newChatWithLinks(string, true); }
- public static Component newChatWithLinks(String string, boolean allowMissingHeader)
- {
+ public static Component newChatWithLinks(String string, boolean allowMissingHeader) {
// Includes ipv4 and domain pattern
// Matches an ip (xx.xxx.xx.xxx) or a domain (something.com) with or
// without a protocol or path.
@@ -422,15 +370,13 @@ public class ForgeHooks
int lastEnd = 0;
// Find all urls
- while (matcher.find())
- {
+ while (matcher.find()) {
int start = matcher.start();
int end = matcher.end();
// Append the previous left overs.
String part = string.substring(lastEnd, start);
- if (part.length() > 0)
- {
+ if (part.length() > 0) {
if (ichat == null)
ichat = Component.literal(part);
else
@@ -440,13 +386,10 @@ public class ForgeHooks
String url = string.substring(start, end);
MutableComponent link = Component.literal(url);
- try
- {
+ try {
// Add schema so client doesn't crash.
- if ((new URI(url)).getScheme() == null)
- {
- if (!allowMissingHeader)
- {
+ if ((new URI(url)).getScheme() == null) {
+ if (!allowMissingHeader) {
if (ichat == null)
ichat = Component.literal(url);
else
@@ -455,9 +398,7 @@ public class ForgeHooks
}
url = "http://" + url;
}
- }
- catch (URISyntaxException e)
- {
+ } catch (URISyntaxException e) {
// Bad syntax bail out!
if (ichat == null) ichat = Component.literal(url);
else ichat.append(url);
@@ -481,8 +422,7 @@ public class ForgeHooks
return ichat;
}
- public static void dropXpForBlock(BlockState state, ServerLevel level, BlockPos pos, ItemStack stack)
- {
+ public static void dropXpForBlock(BlockState state, ServerLevel level, BlockPos pos, ItemStack stack) {
int fortuneLevel = stack.getEnchantmentLevel(Enchantments.BLOCK_FORTUNE);
int silkTouchLevel = stack.getEnchantmentLevel(Enchantments.SILK_TOUCH);
int exp = state.getExpDrop(level, level.random, pos, fortuneLevel, silkTouchLevel);
@@ -490,23 +430,18 @@ public class ForgeHooks
state.getBlock().popExperience(level, pos, exp);
}
- public static int onBlockBreakEvent(Level level, GameType gameType, ServerPlayer entityPlayer, BlockPos pos)
- {
+ public static int onBlockBreakEvent(Level level, GameType gameType, ServerPlayer entityPlayer, BlockPos pos) {
// Logic from tryHarvestBlock for pre-canceling the event
boolean preCancelEvent = false;
ItemStack itemstack = entityPlayer.getMainHandItem();
if (!itemstack.isEmpty() && !itemstack.getItem().canAttackBlock(level.getBlockState(pos), level, pos, entityPlayer))
- {
preCancelEvent = true;
- }
- if (gameType.isBlockPlacingRestricted())
- {
+ if (gameType.isBlockPlacingRestricted()) {
if (gameType == GameType.SPECTATOR)
preCancelEvent = true;
- if (!entityPlayer.mayBuild())
- {
+ if (!entityPlayer.mayBuild()) {
if (itemstack.isEmpty() || !itemstack.hasAdventureModeBreakTagForBlock(level.registryAccess().registryOrThrow(Registries.BLOCK), new BlockInWorld(level, pos, false)))
preCancelEvent = true;
}
@@ -514,9 +449,7 @@ public class ForgeHooks
// Tell client the block is gone immediately then process events
if (level.getBlockEntity(pos) == null)
- {
entityPlayer.connection.send(new ClientboundBlockUpdatePacket(pos, level.getFluidState(pos).createLegacyBlock()));
- }
// Post the block break event
BlockState state = level.getBlockState(pos);
@@ -525,27 +458,22 @@ public class ForgeHooks
MinecraftForge.EVENT_BUS.post(event);
// Handle if the event is canceled
- if (event.isCanceled())
- {
+ if (event.isCanceled()) {
// Let the client know the block still exists
entityPlayer.connection.send(new ClientboundBlockUpdatePacket(level, pos));
// Update any tile entity data for this block
BlockEntity blockEntity = level.getBlockEntity(pos);
- if (blockEntity != null)
- {
+ if (blockEntity != null) {
Packet> pkt = blockEntity.getUpdatePacket();
if (pkt != null)
- {
entityPlayer.connection.send(pkt);
- }
}
}
return event.isCanceled() ? -1 : event.getExpToDrop();
}
- public static InteractionResult onPlaceItemIntoWorld(@NotNull UseOnContext context)
- {
+ public static InteractionResult onPlaceItemIntoWorld(@NotNull UseOnContext context) {
ItemStack itemstack = context.getItemInHand();
Level level = context.getLevel();
@@ -570,15 +498,12 @@ public class ForgeHooks
level.captureBlockSnapshots = false;
- if (ret.consumesAction())
- {
+ if (ret.consumesAction()) {
// save new item data
int newSize = itemstack.getCount();
CompoundTag newNBT = null;
if (itemstack.getTag() != null)
- {
newNBT = itemstack.getTag().copy();
- }
@SuppressWarnings("unchecked")
List blockSnapshots = (List)level.capturedBlockSnapshots.clone();
level.capturedBlockSnapshots.clear();
@@ -591,33 +516,24 @@ public class ForgeHooks
boolean eventResult = false;
if (blockSnapshots.size() > 1)
- {
eventResult = ForgeEventFactory.onMultiBlockPlace(player, blockSnapshots, side);
- }
else if (blockSnapshots.size() == 1)
- {
eventResult = ForgeEventFactory.onBlockPlace(player, blockSnapshots.get(0), side);
- }
- if (eventResult)
- {
+ if (eventResult) {
ret = InteractionResult.FAIL; // cancel placement
// revert back all captured blocks
- for (BlockSnapshot blocksnapshot : Lists.reverse(blockSnapshots))
- {
+ for (BlockSnapshot blocksnapshot : Lists.reverse(blockSnapshots)) {
level.restoringBlockSnapshots = true;
blocksnapshot.restore(true, false);
level.restoringBlockSnapshots = false;
}
- }
- else
- {
+ } else {
// Change the stack to its new content
itemstack.setCount(newSize);
itemstack.setTag(newNBT);
- for (BlockSnapshot snap : blockSnapshots)
- {
+ for (BlockSnapshot snap : blockSnapshots) {
int updateFlag = snap.getFlag();
BlockState oldBlock = snap.getReplacedBlock();
BlockState newBlock = level.getBlockState(snap.getPos());
@@ -634,8 +550,7 @@ public class ForgeHooks
return ret;
}
- public static boolean onAnvilChange(AnvilMenu container, @NotNull ItemStack left, @NotNull ItemStack right, Container outputSlot, String name, int baseCost, Player player)
- {
+ public static boolean onAnvilChange(AnvilMenu container, @NotNull ItemStack left, @NotNull ItemStack right, Container outputSlot, String name, int baseCost, Player player) {
AnvilUpdateEvent e = new AnvilUpdateEvent(left, right, name, baseCost, player);
if (MinecraftForge.EVENT_BUS.post(e)) return false;
if (e.getOutput().isEmpty()) return true;
@@ -646,18 +561,15 @@ public class ForgeHooks
return false;
}
- public static float onAnvilRepair(Player player, @NotNull ItemStack output, @NotNull ItemStack left, @NotNull ItemStack right)
- {
+ public static float onAnvilRepair(Player player, @NotNull ItemStack output, @NotNull ItemStack left, @NotNull ItemStack right) {
AnvilRepairEvent e = new AnvilRepairEvent(player, left, right, output);
MinecraftForge.EVENT_BUS.post(e);
return e.getBreakChance();
}
- public static int onGrindstoneChange(@NotNull ItemStack top, @NotNull ItemStack bottom, Container outputSlot, int xp)
- {
+ public static int onGrindstoneChange(@NotNull ItemStack top, @NotNull ItemStack bottom, Container outputSlot, int xp) {
GrindstoneEvent.OnPlaceItem e = new GrindstoneEvent.OnPlaceItem(top, bottom, xp);
- if (MinecraftForge.EVENT_BUS.post(e))
- {
+ if (MinecraftForge.EVENT_BUS.post(e)) {
outputSlot.setItem(0, ItemStack.EMPTY);
return -1;
}
@@ -667,19 +579,16 @@ public class ForgeHooks
return e.getXp();
}
- public static boolean onGrindstoneTake(Container inputSlots, ContainerLevelAccess access, Function xpFunction)
- {
+ public static boolean onGrindstoneTake(Container inputSlots, ContainerLevelAccess access, Function xpFunction) {
access.execute((l,p) -> {
int xp = xpFunction.apply(l);
GrindstoneEvent.OnTakeItem e = new GrindstoneEvent.OnTakeItem(inputSlots.getItem(0), inputSlots.getItem(1), xp);
if (MinecraftForge.EVENT_BUS.post(e))
- {
return;
- }
- if (l instanceof ServerLevel)
- {
- ExperienceOrb.award((ServerLevel)l, Vec3.atCenterOf(p), e.getXp());
- }
+
+ if (l instanceof ServerLevel server)
+ ExperienceOrb.award(server, Vec3.atCenterOf(p), e.getXp());
+
l.levelEvent(1042, p, 0);
inputSlots.setItem(0, e.getNewTopItem());
inputSlots.setItem(1, e.getNewBottomItem());
@@ -689,22 +598,19 @@ public class ForgeHooks
}
private static ThreadLocal craftingPlayer = new ThreadLocal();
- public static void setCraftingPlayer(Player player)
- {
+ public static void setCraftingPlayer(Player player) {
craftingPlayer.set(player);
}
- public static Player getCraftingPlayer()
- {
+
+ public static Player getCraftingPlayer() {
return craftingPlayer.get();
}
+
@NotNull
- public static ItemStack getCraftingRemainingItem(@NotNull ItemStack stack)
- {
- if (stack.getItem().hasCraftingRemainingItem(stack))
- {
+ public static ItemStack getCraftingRemainingItem(@NotNull ItemStack stack) {
+ if (stack.getItem().hasCraftingRemainingItem(stack)) {
stack = stack.getItem().getCraftingRemainingItem(stack);
- if (!stack.isEmpty() && stack.isDamageableItem() && stack.getDamageValue() > stack.getMaxDamage())
- {
+ if (!stack.isEmpty() && stack.isDamageableItem() && stack.getDamageValue() > stack.getMaxDamage()) {
ForgeEventFactory.onPlayerDestroyItem(craftingPlayer.get(), stack, null);
return ItemStack.EMPTY;
}
@@ -713,35 +619,30 @@ public class ForgeHooks
return ItemStack.EMPTY;
}
- public static boolean onPlayerAttackTarget(Player player, Entity target)
- {
+ public static boolean onPlayerAttackTarget(Player player, Entity target) {
if (MinecraftForge.EVENT_BUS.post(new AttackEntityEvent(player, target))) return false;
ItemStack stack = player.getMainHandItem();
return stack.isEmpty() || !stack.getItem().onLeftClickEntity(stack, player, target);
}
- public static InteractionResult onInteractEntityAt(Player player, Entity entity, HitResult ray, InteractionHand hand)
- {
+ public static InteractionResult onInteractEntityAt(Player player, Entity entity, HitResult ray, InteractionHand hand) {
Vec3 vec3d = ray.getLocation().subtract(entity.position());
return onInteractEntityAt(player, entity, vec3d, hand);
}
- public static InteractionResult onInteractEntityAt(Player player, Entity entity, Vec3 vec3d, InteractionHand hand)
- {
+ public static InteractionResult onInteractEntityAt(Player player, Entity entity, Vec3 vec3d, InteractionHand hand) {
PlayerInteractEvent.EntityInteractSpecific evt = new PlayerInteractEvent.EntityInteractSpecific(player, hand, entity, vec3d);
MinecraftForge.EVENT_BUS.post(evt);
return evt.isCanceled() ? evt.getCancellationResult() : null;
}
- public static InteractionResult onInteractEntity(Player player, Entity entity, InteractionHand hand)
- {
+ public static InteractionResult onInteractEntity(Player player, Entity entity, InteractionHand hand) {
PlayerInteractEvent.EntityInteract evt = new PlayerInteractEvent.EntityInteract(player, hand, entity);
MinecraftForge.EVENT_BUS.post(evt);
return evt.isCanceled() ? evt.getCancellationResult() : null;
}
- public static InteractionResult onItemRightClick(Player player, InteractionHand hand)
- {
+ public static InteractionResult onItemRightClick(Player player, InteractionHand hand) {
PlayerInteractEvent.RightClickItem evt = new PlayerInteractEvent.RightClickItem(player, hand);
MinecraftForge.EVENT_BUS.post(evt);
return evt.isCanceled() ? evt.getCancellationResult() : null;
@@ -751,39 +652,33 @@ public class ForgeHooks
* @deprecated Use {@link #onLeftClickBlock(Player, BlockPos, Direction, ServerboundPlayerActionPacket.Action)} instead
*/
@Deprecated(since = "1.20.1", forRemoval = true)
- public static PlayerInteractEvent.LeftClickBlock onLeftClickBlock(Player player, BlockPos pos, Direction face)
- {
+ public static PlayerInteractEvent.LeftClickBlock onLeftClickBlock(Player player, BlockPos pos, Direction face) {
return onLeftClickBlock(player, pos, face, ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK);
}
- public static PlayerInteractEvent.LeftClickBlock onLeftClickBlock(Player player, BlockPos pos, Direction face, ServerboundPlayerActionPacket.Action action)
- {
+ public static PlayerInteractEvent.LeftClickBlock onLeftClickBlock(Player player, BlockPos pos, Direction face, ServerboundPlayerActionPacket.Action action) {
PlayerInteractEvent.LeftClickBlock evt = new PlayerInteractEvent.LeftClickBlock(player, pos, face, PlayerInteractEvent.LeftClickBlock.Action.convert(action));
MinecraftForge.EVENT_BUS.post(evt);
return evt;
}
- public static PlayerInteractEvent.LeftClickBlock onClientMineHold(Player player, BlockPos pos, Direction face)
- {
+ public static PlayerInteractEvent.LeftClickBlock onClientMineHold(Player player, BlockPos pos, Direction face) {
PlayerInteractEvent.LeftClickBlock evt = new PlayerInteractEvent.LeftClickBlock(player, pos, face, PlayerInteractEvent.LeftClickBlock.Action.CLIENT_HOLD);
MinecraftForge.EVENT_BUS.post(evt);
return evt;
}
- public static PlayerInteractEvent.RightClickBlock onRightClickBlock(Player player, InteractionHand hand, BlockPos pos, BlockHitResult hitVec)
- {
+ public static PlayerInteractEvent.RightClickBlock onRightClickBlock(Player player, InteractionHand hand, BlockPos pos, BlockHitResult hitVec) {
PlayerInteractEvent.RightClickBlock evt = new PlayerInteractEvent.RightClickBlock(player, hand, pos, hitVec);
MinecraftForge.EVENT_BUS.post(evt);
return evt;
}
- public static void onEmptyClick(Player player, InteractionHand hand)
- {
+ public static void onEmptyClick(Player player, InteractionHand hand) {
MinecraftForge.EVENT_BUS.post(new PlayerInteractEvent.RightClickEmpty(player, hand));
}
- public static void onEmptyLeftClick(Player player)
- {
+ public static void onEmptyLeftClick(Player player) {
MinecraftForge.EVENT_BUS.post(new PlayerInteractEvent.LeftClickEmpty(player));
}
@@ -800,8 +695,7 @@ public class ForgeHooks
/* TODO: GLM
private static final ThreadLocal> lootContext = new ThreadLocal<>();
- private static LootTableContext getLootTableContext()
- {
+ private static LootTableContext getLootTableContext() {
LootTableContext ctx = lootContext.get().peek();
if (ctx == null)
@@ -810,45 +704,34 @@ public class ForgeHooks
return ctx;
}
- public static TriFunction> getLootTableDeserializer(Gson gson, String directory)
- {
+ public static TriFunction> getLootTableDeserializer(Gson gson, String directory) {
return (location, data, resourceManager) -> {
- try
- {
+ try {
Resource resource = resourceManager.getResource(location.withPath(directory + "/" + location.getPath() + ".json")).orElse(null);
boolean custom = resource == null || !resource.isBuiltin();
return Optional.ofNullable(loadLootTable(gson, location, data, custom));
- }
- catch (Exception exception)
- {
+ } catch (Exception exception) {
LOGGER.error("Couldn't parse element {}:{}", directory, location, exception);
return Optional.empty();
}
};
}
- public static LootTable loadLootTable(Gson gson, ResourceLocation name, JsonElement data, boolean custom)
- {
+ public static LootTable loadLootTable(Gson gson, ResourceLocation name, JsonElement data, boolean custom) {
Deque que = lootContext.get();
- if (que == null)
- {
+ if (que == null) {
que = Queues.newArrayDeque();
lootContext.set(que);
}
LootTable ret;
- try
- {
+ try {
que.push(new LootTableContext(name, custom));
ret = gson.fromJson(data, LootTable.class);
ret.setLootTableId(name);
- }
- catch (JsonParseException e)
- {
+ } catch (JsonParseException e) {
throw e;
- }
- finally
- {
+ } finally {
que.pop();
}
@@ -861,23 +744,20 @@ public class ForgeHooks
return ret;
}
- private static class LootTableContext
- {
+ private static class LootTableContext {
public final ResourceLocation name;
public final boolean vanilla;
public final boolean custom;
public int poolCount = 0;
- private LootTableContext(ResourceLocation name, boolean custom)
- {
+ private LootTableContext(ResourceLocation name, boolean custom) {
this.name = name;
this.custom = custom;
this.vanilla = "minecraft".equals(this.name.getNamespace());
}
}
- public static String readPoolName(JsonObject json)
- {
+ public static String readPoolName(JsonObject json) {
LootTableContext ctx = getLootTableContext();
if (json.has("name"))
@@ -899,8 +779,7 @@ public class ForgeHooks
* @return the type of the fluid if vanilla
* @throws RuntimeException if the fluid is not a vanilla one
*/
- public static FluidType getVanillaFluidType(Fluid fluid)
- {
+ public static FluidType getVanillaFluidType(Fluid fluid) {
if (fluid == Fluids.EMPTY)
return ForgeMod.EMPTY_TYPE.get();
if (fluid == Fluids.WATER || fluid == Fluids.FLOWING_WATER)
@@ -912,59 +791,45 @@ public class ForgeHooks
throw new RuntimeException("Mod fluids must override getFluidType.");
}
- public static TagKey getTagFromVanillaTier(Tiers tier)
- {
- return switch(tier)
- {
- case WOOD -> Tags.Blocks.NEEDS_WOOD_TOOL;
- case GOLD -> Tags.Blocks.NEEDS_GOLD_TOOL;
- case STONE -> BlockTags.NEEDS_STONE_TOOL;
- case IRON -> BlockTags.NEEDS_IRON_TOOL;
- case DIAMOND -> BlockTags.NEEDS_DIAMOND_TOOL;
- case NETHERITE -> Tags.Blocks.NEEDS_NETHERITE_TOOL;
- };
- }
-
- public static Collection onCheckCreativeTabs(CreativeModeTab... vanillaTabs) {
- final List tabs = new ArrayList<>(Arrays.asList(vanillaTabs));
- return tabs;
+ public static TagKey getTagFromVanillaTier(Tiers tier) {
+ return switch(tier) {
+ case WOOD -> Tags.Blocks.NEEDS_WOOD_TOOL;
+ case GOLD -> Tags.Blocks.NEEDS_GOLD_TOOL;
+ case STONE -> BlockTags.NEEDS_STONE_TOOL;
+ case IRON -> BlockTags.NEEDS_IRON_TOOL;
+ case DIAMOND -> BlockTags.NEEDS_DIAMOND_TOOL;
+ case NETHERITE -> Tags.Blocks.NEEDS_NETHERITE_TOOL;
+ };
}
@FunctionalInterface
- public interface BiomeCallbackFunction
- {
+ public interface BiomeCallbackFunction {
Biome apply(final Biome.ClimateSettings climate, final BiomeSpecialEffects effects, final BiomeGenerationSettings gen, final MobSpawnSettings spawns);
}
- public static boolean onCropsGrowPre(Level level, BlockPos pos, BlockState state, boolean def)
- {
+ public static boolean onCropsGrowPre(Level level, BlockPos pos, BlockState state, boolean def) {
BlockEvent ev = new BlockEvent.CropGrowEvent.Pre(level,pos,state);
MinecraftForge.EVENT_BUS.post(ev);
- return (ev.getResult() == net.minecraftforge.eventbus.api.Event.Result.ALLOW || (ev.getResult() == net.minecraftforge.eventbus.api.Event.Result.DEFAULT && def));
+ return (ev.getResult() == Event.Result.ALLOW || (ev.getResult() == Event.Result.DEFAULT && def));
}
- public static void onCropsGrowPost(Level level, BlockPos pos, BlockState state)
- {
+ public static void onCropsGrowPost(Level level, BlockPos pos, BlockState state) {
MinecraftForge.EVENT_BUS.post(new BlockEvent.CropGrowEvent.Post(level, pos, state, level.getBlockState(pos)));
}
@Nullable
- public static CriticalHitEvent getCriticalHit(Player player, Entity target, boolean vanillaCritical, float damageModifier)
- {
+ public static CriticalHitEvent getCriticalHit(Player player, Entity target, boolean vanillaCritical, float damageModifier) {
CriticalHitEvent hitResult = new CriticalHitEvent(player, target, damageModifier, vanillaCritical);
MinecraftForge.EVENT_BUS.post(hitResult);
- if (hitResult.getResult() == net.minecraftforge.eventbus.api.Event.Result.ALLOW || (vanillaCritical && hitResult.getResult() == net.minecraftforge.eventbus.api.Event.Result.DEFAULT))
- {
+ if (hitResult.getResult() == Event.Result.ALLOW || (vanillaCritical && hitResult.getResult() == Event.Result.DEFAULT))
return hitResult;
- }
return null;
}
/**
* Hook to fire {@link ItemAttributeModifierEvent}. Modders should use {@link ItemStack#getAttributeModifiers(EquipmentSlot)} instead.
*/
- public static Multimap getAttributeModifiers(ItemStack stack, EquipmentSlot equipmentSlot, Multimap attributes)
- {
+ public static Multimap getAttributeModifiers(ItemStack stack, EquipmentSlot equipmentSlot, Multimap attributes) {
ItemAttributeModifierEvent event = new ItemAttributeModifierEvent(stack, equipmentSlot, attributes);
MinecraftForge.EVENT_BUS.post(event);
return event.getModifiers();
@@ -973,8 +838,7 @@ public class ForgeHooks
/**
* Hook to fire {@link LivingGetProjectileEvent}. Returns the ammo to be used.
*/
- public static ItemStack getProjectile(LivingEntity entity, ItemStack projectileWeaponItem, ItemStack projectile)
- {
+ public static ItemStack getProjectile(LivingEntity entity, ItemStack projectileWeaponItem, ItemStack projectile) {
LivingGetProjectileEvent event = new LivingGetProjectileEvent(entity, projectileWeaponItem, projectile);
MinecraftForge.EVENT_BUS.post(event);
return event.getProjectileItemStack();
@@ -984,51 +848,35 @@ public class ForgeHooks
* Used as the default implementation of {@link Item#getCreatorModId}. Call that method instead.
*/
@Nullable
- public static String getDefaultCreatorModId(@NotNull ItemStack itemStack)
- {
+ public static String getDefaultCreatorModId(@NotNull ItemStack itemStack) {
Item item = itemStack.getItem();
ResourceLocation registryName = ForgeRegistries.ITEMS.getKey(item);
String modId = registryName == null ? null : registryName.getNamespace();
- if ("minecraft".equals(modId))
- {
- if (item instanceof EnchantedBookItem)
- {
+ if ("minecraft".equals(modId)) {
+ if (item instanceof EnchantedBookItem) {
ListTag enchantmentsNbt = EnchantedBookItem.getEnchantments(itemStack);
- if (enchantmentsNbt.size() == 1)
- {
+ if (enchantmentsNbt.size() == 1) {
CompoundTag nbttagcompound = enchantmentsNbt.getCompound(0);
ResourceLocation resourceLocation = ResourceLocation.tryParse(nbttagcompound.getString("id"));
if (resourceLocation != null && ForgeRegistries.ENCHANTMENTS.containsKey(resourceLocation))
- {
return resourceLocation.getNamespace();
- }
}
- }
- else if (item instanceof PotionItem || item instanceof TippedArrowItem)
- {
+ } else if (item instanceof PotionItem || item instanceof TippedArrowItem) {
Potion potionType = PotionUtils.getPotion(itemStack);
ResourceLocation resourceLocation = ForgeRegistries.POTIONS.getKey(potionType);
if (resourceLocation != null)
- {
return resourceLocation.getNamespace();
- }
- }
- else if (item instanceof SpawnEggItem)
- {
- ResourceLocation resourceLocation = ForgeRegistries.ENTITY_TYPES.getKey(((SpawnEggItem) item).getType(null));
+ } else if (item instanceof SpawnEggItem egg) {
+ ResourceLocation resourceLocation = ForgeRegistries.ENTITY_TYPES.getKey(egg.getType(null));
if (resourceLocation != null)
- {
return resourceLocation.getNamespace();
- }
}
}
return modId;
}
- public static boolean onFarmlandTrample(Level level, BlockPos pos, BlockState state, float fallDistance, Entity entity)
- {
- if (entity.canTrample(state, pos, fallDistance))
- {
+ public static boolean onFarmlandTrample(Level level, BlockPos pos, BlockState state, float fallDistance, Entity entity) {
+ if (entity.canTrample(state, pos, fallDistance)) {
BlockEvent.FarmlandTrampleEvent event = new BlockEvent.FarmlandTrampleEvent(level, pos, state, fallDistance, entity);
MinecraftForge.EVENT_BUS.post(event);
return !event.isCanceled();
@@ -1043,12 +891,10 @@ public class ForgeHooks
return event.getVanillaNoteId();
}
- public static boolean hasNoElements(Ingredient ingredient)
- {
+ public static boolean hasNoElements(Ingredient ingredient) {
ItemStack[] items = ingredient.getItems();
if (items.length == 0) return true;
- if (items.length == 1)
- {
+ if (items.length == 1) {
//If we potentially added a barrier due to the ingredient being an empty tag, try and check if it is the stack we added
ItemStack item = items[0];
return item.getItem() == Items.BARRIER && item.getHoverName() instanceof MutableComponent hoverName && hoverName.getString().startsWith("Empty Tag: ");
@@ -1056,15 +902,10 @@ public class ForgeHooks
return false;
}
- @Deprecated(forRemoval = true, since = "1.20.1") // Tags use a codec now This was never used in 1.20
- public static void deserializeTagAdditions(List list, JsonObject json, List allList) {}
-
@Nullable
- public static EntityDataSerializer> getSerializer(int id, CrudeIncrementalIntIdentityHashBiMap> vanilla)
- {
+ public static EntityDataSerializer> getSerializer(int id, CrudeIncrementalIntIdentityHashBiMap> vanilla) {
EntityDataSerializer> serializer = vanilla.byId(id);
- if (serializer == null)
- {
+ if (serializer == null) {
// ForgeRegistries.DATA_SERIALIZERS is a deferred register now, so if this method is called too early, the registry will be null
ForgeRegistry> registry = (ForgeRegistry>) ForgeRegistries.ENTITY_DATA_SERIALIZERS.get();
if (registry != null)
@@ -1073,11 +914,9 @@ public class ForgeHooks
return serializer;
}
- public static int getSerializerId(EntityDataSerializer> serializer, CrudeIncrementalIntIdentityHashBiMap> vanilla)
- {
+ public static int getSerializerId(EntityDataSerializer> serializer, CrudeIncrementalIntIdentityHashBiMap> vanilla) {
int id = vanilla.getId(serializer);
- if (id < 0)
- {
+ if (id < 0) {
// ForgeRegistries.DATA_SERIALIZERS is a deferred register now, so if this method is called too early, the registry will be null
ForgeRegistry> registry = (ForgeRegistry>) ForgeRegistries.ENTITY_DATA_SERIALIZERS.get();
if (registry != null)
@@ -1086,8 +925,7 @@ public class ForgeHooks
return id;
}
- public static boolean canEntityDestroy(Level level, BlockPos pos, LivingEntity entity)
- {
+ public static boolean canEntityDestroy(Level level, BlockPos pos, LivingEntity entity) {
if (!level.isLoaded(pos))
return false;
BlockState state = level.getBlockState(pos);
@@ -1099,14 +937,10 @@ public class ForgeHooks
/**
* Gets the burn time of this itemstack.
*/
- public static int getBurnTime(ItemStack stack, @Nullable RecipeType> recipeType)
- {
+ public static int getBurnTime(ItemStack stack, @Nullable RecipeType> recipeType) {
if (stack.isEmpty())
- {
return 0;
- }
- else
- {
+ else {
Item item = stack.getItem();
int ret = stack.getBurnTime(recipeType);
return ForgeEventFactory.getItemBurnTime(stack, ret == -1 ? VANILLA_BURNS.getOrDefault(ForgeRegistries.ITEMS.getDelegateOrThrow(item), 0) : ret, recipeType);
@@ -1114,31 +948,12 @@ public class ForgeHooks
}
@SuppressWarnings("deprecation")
- public static synchronized void updateBurns()
- {
+ public static synchronized void updateBurns() {
VANILLA_BURNS.clear();
FurnaceBlockEntity.getFuel().entrySet().forEach(e -> VANILLA_BURNS.put(ForgeRegistries.ITEMS.getDelegateOrThrow(e.getKey()), e.getValue()));
}
// TODO: GLM
- /**
- * All loot table drops should be passed to this function so that mod added effects
- * (e.g. smelting enchantments) can be processed.
- *
- * @param list The loot generated
- * @param context The loot context that generated that loot
- * @return The modified list
- *
- * @deprecated Use {@link #modifyLoot(ResourceLocation, ObjectArrayList, LootContext)} instead.
- *
- * @implNote This method will use the {@linkplain LootTableIdCondition#UNKNOWN_LOOT_TABLE
- * unknown loot table marker} when redirecting.
- * /
- @Deprecated
- public static List modifyLoot(List list, LootContext context) {
- return modifyLoot(LootTableIdCondition.UNKNOWN_LOOT_TABLE, ObjectArrayList.wrap((ItemStack[]) list.toArray()), context);
- }
-
/**
* Handles the modification of loot table drops via the registered Global Loot Modifiers,
* so that custom effects can be processed.
@@ -1163,43 +978,34 @@ public class ForgeHooks
}
*/
- public static List getModPacks()
- {
+ public static List getModPacks() {
List modpacks = ResourcePackLoader.getPackNames();
if(modpacks.isEmpty())
throw new IllegalStateException("Attempted to retrieve mod packs before they were loaded in!");
return modpacks;
}
- public static List getModPacksWithVanilla()
- {
+ public static List getModPacksWithVanilla() {
List modpacks = getModPacks();
modpacks.add("vanilla");
return modpacks;
}
- private static final Set VANILLA_DIMS = Sets.newHashSet("minecraft:overworld", "minecraft:the_nether", "minecraft:the_end");
- private static final String DIMENSIONS_KEY = "dimensions";
- private static final String SEED_KEY = "seed";
-
private static final Map, AttributeSupplier> FORGE_ATTRIBUTES = new HashMap<>();
/** FOR INTERNAL USE ONLY, DO NOT CALL DIRECTLY */
@Deprecated
- public static Map, AttributeSupplier> getAttributesView()
- {
+ public static Map, AttributeSupplier> getAttributesView() {
return Collections.unmodifiableMap(FORGE_ATTRIBUTES);
}
/** FOR INTERNAL USE ONLY, DO NOT CALL DIRECTLY */
@Deprecated
- public static void modifyAttributes()
- {
+ public static void modifyAttributes() {
ModLoader.get().postEvent(new EntityAttributeCreationEvent(FORGE_ATTRIBUTES));
Map, AttributeSupplier.Builder> finalMap = new HashMap<>();
ModLoader.get().postEvent(new EntityAttributeModificationEvent(finalMap));
- finalMap.forEach((k, v) ->
- {
+ finalMap.forEach((k, v) -> {
AttributeSupplier supplier = DefaultAttributes.getSupplier(k);
AttributeSupplier.Builder newBuilder = supplier != null ? new AttributeSupplier.Builder(supplier) : new AttributeSupplier.Builder();
newBuilder.combine(v);
@@ -1207,31 +1013,26 @@ public class ForgeHooks
});
}
- public static void onEntityEnterSection(Entity entity, long packedOldPos, long packedNewPos)
- {
+ public static void onEntityEnterSection(Entity entity, long packedOldPos, long packedNewPos) {
MinecraftForge.EVENT_BUS.post(new EntityEvent.EnteringSection(entity, packedOldPos, packedNewPos));
}
- public static ShieldBlockEvent onShieldBlock(LivingEntity blocker, DamageSource source, float blocked)
- {
+ public static ShieldBlockEvent onShieldBlock(LivingEntity blocker, DamageSource source, float blocked) {
ShieldBlockEvent e = new ShieldBlockEvent(blocker, source, blocked);
MinecraftForge.EVENT_BUS.post(e);
return e;
}
- public static LivingSwapItemsEvent.Hands onLivingSwapHandItems(LivingEntity livingEntity)
- {
+ public static LivingSwapItemsEvent.Hands onLivingSwapHandItems(LivingEntity livingEntity) {
LivingSwapItemsEvent.Hands event = new LivingSwapItemsEvent.Hands(livingEntity);
MinecraftForge.EVENT_BUS.post(event);
return event;
}
- public static void writeAdditionalLevelSaveData(WorldData worldData, CompoundTag levelTag)
- {
+ public static void writeAdditionalLevelSaveData(WorldData worldData, CompoundTag levelTag) {
CompoundTag fmlData = new CompoundTag();
ListTag modList = new ListTag();
- ModList.get().getMods().forEach(mi ->
- {
+ ModList.get().getMods().forEach(mi -> {
final CompoundTag mod = new CompoundTag();
mod.putString("ModId", mi.getModId());
mod.putString("ModVersion", MavenVersionStringHelper.artifactVersionToString(mi.getVersion()));
@@ -1244,42 +1045,29 @@ public class ForgeHooks
LOGGER.debug(WORLDPERSISTENCE, "Gathering id map for writing to world save {}", worldData.getLevelName());
for (Map.Entry e : RegistryManager.ACTIVE.takeSnapshot(true).entrySet())
- {
registries.put(e.getKey().toString(), e.getValue().write());
- }
LOGGER.debug(WORLDPERSISTENCE, "ID Map collection complete {}", worldData.getLevelName());
levelTag.put("fml", fmlData);
}
- /**
- * @param rootTag Level data file contents.
- * @param levelDirectory Level currently being loaded.
- */
@ApiStatus.Internal
- public static void readAdditionalLevelSaveData(CompoundTag rootTag, LevelStorageSource.LevelDirectory levelDirectory)
- {
+ public static void readAdditionalLevelSaveData(CompoundTag rootTag, LevelStorageSource.LevelDirectory levelDirectory) {
CompoundTag tag = rootTag.getCompound("fml");
- if (tag.contains("LoadingModList"))
- {
+ if (tag.contains("LoadingModList")) {
ListTag modList = tag.getList("LoadingModList", net.minecraft.nbt.Tag.TAG_COMPOUND);
Map mismatchedVersions = new HashMap<>(modList.size());
Map missingVersions = new HashMap<>(modList.size());
- for (int i = 0; i < modList.size(); i++)
- {
+ for (int i = 0; i < modList.size(); i++) {
CompoundTag mod = modList.getCompound(i);
String modId = mod.getString("ModId");
if (Objects.equals("minecraft", modId))
- {
continue;
- }
String modVersion = mod.getString("ModVersion");
final var previousVersion = new DefaultArtifactVersion(modVersion);
- ModList.get().getModContainerById(modId).ifPresentOrElse(container ->
- {
+ ModList.get().getModContainerById(modId).ifPresentOrElse(container -> {
final var loadingVersion = container.getModInfo().getVersion();
- if (!loadingVersion.equals(previousVersion))
- {
+ if (!loadingVersion.equals(previousVersion)) {
// Enqueue mismatched versions for bulk event
mismatchedVersions.put(modId, previousVersion);
}
@@ -1293,49 +1081,42 @@ public class ForgeHooks
StringBuilder unresolved = new StringBuilder("The following mods have version differences that were not resolved:");
// For mods that were marked resolved, log the version resolution and the mod that resolved the mismatch
- mismatchEvent.getResolved().forEachOrdered((res) ->
- {
+ mismatchEvent.getResolved().forEachOrdered((res) -> {
final var modid = res.modid();
final var diff = res.versionDifference();
- if (res.wasSelfResolved())
- {
+ if (res.wasSelfResolved()) {
resolved.append(System.lineSeparator())
- .append(diff.isMissing()
- ? "%s (version %s -> MISSING, self-resolved)".formatted(modid, diff.oldVersion())
- : "%s (version %s -> %s, self-resolved)".formatted(modid, diff.oldVersion(), diff.newVersion())
- );
- }
- else
- {
+ .append(diff.isMissing()
+ ? "%s (version %s -> MISSING, self-resolved)".formatted(modid, diff.oldVersion())
+ : "%s (version %s -> %s, self-resolved)".formatted(modid, diff.oldVersion(), diff.newVersion())
+ );
+ } else {
final var resolver = res.resolver().getModId();
resolved.append(System.lineSeparator())
- .append(diff.isMissing()
- ? "%s (version %s -> MISSING, resolved by %s)".formatted(modid, diff.oldVersion(), resolver)
- : "%s (version %s -> %s, resolved by %s)".formatted(modid, diff.oldVersion(), diff.newVersion(), resolver)
- );
+ .append(diff.isMissing()
+ ? "%s (version %s -> MISSING, resolved by %s)".formatted(modid, diff.oldVersion(), resolver)
+ : "%s (version %s -> %s, resolved by %s)".formatted(modid, diff.oldVersion(), diff.newVersion(), resolver)
+ );
}
});
// For mods that did not specify handling, show a warning to users that errors may occur
- mismatchEvent.getUnresolved().forEachOrdered((unres) ->
- {
+ mismatchEvent.getUnresolved().forEachOrdered((unres) -> {
final var modid = unres.modid();
final var diff = unres.versionDifference();
unresolved.append(System.lineSeparator())
- .append(diff.isMissing()
- ? "%s (version %s -> MISSING)".formatted(modid, diff.oldVersion())
- : "%s (version %s -> %s)".formatted(modid, diff.oldVersion(), diff.newVersion())
- );
+ .append(diff.isMissing()
+ ? "%s (version %s -> MISSING)".formatted(modid, diff.oldVersion())
+ : "%s (version %s -> %s)".formatted(modid, diff.oldVersion(), diff.newVersion())
+ );
});
- if (mismatchEvent.anyResolved())
- {
+ if (mismatchEvent.anyResolved()) {
resolved.append(System.lineSeparator()).append("Things may not work well.");
LOGGER.debug(WORLDPERSISTENCE, resolved.toString());
}
- if (mismatchEvent.anyUnresolved())
- {
+ if (mismatchEvent.anyUnresolved()) {
unresolved.append(System.lineSeparator()).append("Things may not work well.");
LOGGER.warn(WORLDPERSISTENCE, unresolved.toString());
}
@@ -1343,26 +1124,21 @@ public class ForgeHooks
Multimap failedElements = null;
- if (tag.contains("Registries"))
- {
+ if (tag.contains("Registries")) {
Map snapshot = new HashMap<>();
CompoundTag regs = tag.getCompound("Registries");
for (String key : regs.getAllKeys())
- {
snapshot.put(new ResourceLocation(key), ForgeRegistry.Snapshot.read(regs.getCompound(key)));
- }
failedElements = GameData.injectSnapshot(snapshot, true, true);
}
- if (failedElements != null && !failedElements.isEmpty())
- {
+ if (failedElements != null && !failedElements.isEmpty()) {
StringBuilder buf = new StringBuilder();
buf.append("Forge Mod Loader could not load this save.\n\n")
.append("There are ").append(failedElements.size()).append(" unassigned registry entries in this save.\n")
.append("You will not be able to load until they are present again.\n\n");
- failedElements.asMap().forEach((name, entries) ->
- {
+ failedElements.asMap().forEach((name, entries) -> {
buf.append("Missing ").append(name).append(":\n");
entries.forEach(rl -> buf.append(" ").append(rl).append("\n"));
});
@@ -1370,8 +1146,7 @@ public class ForgeHooks
}
}
- public static String encodeLifecycle(Lifecycle lifecycle)
- {
+ public static String encodeLifecycle(Lifecycle lifecycle) {
if (lifecycle == Lifecycle.stable())
return "stable";
if (lifecycle == Lifecycle.experimental())
@@ -1381,8 +1156,7 @@ public class ForgeHooks
throw new IllegalArgumentException("Unknown lifecycle.");
}
- public static Lifecycle parseLifecycle(String lifecycle)
- {
+ public static Lifecycle parseLifecycle(String lifecycle) {
if (lifecycle.equals("stable"))
return Lifecycle.stable();
if (lifecycle.equals("experimental"))
@@ -1392,8 +1166,7 @@ public class ForgeHooks
throw new IllegalArgumentException("Unknown lifecycle.");
}
- public static boolean shouldSuppressEnderManAnger(EnderMan enderMan, Player player, ItemStack mask)
- {
+ public static boolean shouldSuppressEnderManAnger(EnderMan enderMan, Player player, ItemStack mask) {
return mask.isEnderMask(player, enderMan) || MinecraftForge.EVENT_BUS.post(new EnderManAngerEvent(enderMan, player));
}
@@ -1408,16 +1181,14 @@ public class ForgeHooks
* @hidden For internal use only.
*/
@Nullable
- public static StructuresBecomeConfiguredFix.Conversion getStructureConversion(String originalBiome)
- {
+ public static StructuresBecomeConfiguredFix.Conversion getStructureConversion(String originalBiome) {
return FORGE_CONVERSION_MAP.get().get(originalBiome);
}
/**
* @hidden For internal use only.
*/
- public static boolean checkStructureNamespace(String biome)
- {
+ public static boolean checkStructureNamespace(String biome) {
@Nullable ResourceLocation biomeLocation = ResourceLocation.tryParse(biome);
return biomeLocation != null && !biomeLocation.getNamespace().equals(ResourceLocation.DEFAULT_NAMESPACE);
}
@@ -1442,31 +1213,24 @@ public class ForgeHooks
* @param registryKey key of the registry
* @return path of the registry key. Prefixed with the namespace if it is not "minecraft"
*/
- public static String prefixNamespace(ResourceLocation registryKey)
- {
+ public static String prefixNamespace(ResourceLocation registryKey) {
return registryKey.getNamespace().equals("minecraft") ? registryKey.getPath() : registryKey.getNamespace() + "/" + registryKey.getPath();
}
- public static boolean canUseEntitySelectors(SharedSuggestionProvider provider)
- {
+ public static boolean canUseEntitySelectors(SharedSuggestionProvider provider) {
if (provider.hasPermission(Commands.LEVEL_GAMEMASTERS))
- {
return true;
- }
else if (provider instanceof CommandSourceStack source && source.source instanceof ServerPlayer player)
- {
return PermissionAPI.getPermission(player, ForgeMod.USE_SELECTORS_PERMISSION);
- }
return false;
}
@ApiStatus.Internal
- public static HolderLookup.RegistryLookup wrapRegistryLookup(final HolderLookup.RegistryLookup lookup)
- {
- return new HolderLookup.RegistryLookup.Delegate<>()
- {
+ public static HolderLookup.RegistryLookup wrapRegistryLookup(final HolderLookup.RegistryLookup lookup) {
+ return new HolderLookup.RegistryLookup.Delegate<>() {
@Override protected RegistryLookup parent() { return lookup; }
@Override public Stream> listTags() { return Stream.empty(); }
+ @SuppressWarnings("deprecation")
@Override public Optional> get(TagKey key) { return Optional.of(HolderSet.emptyNamed(lookup, key)); }
};
}
@@ -1481,36 +1245,26 @@ public class ForgeHooks
* @param refillAirAmount The amount of air to refill when the entity is able to breathe
* @implNote This method needs to closely replicate the logic found right after the call site in {@link LivingEntity#baseTick()} as it overrides it.
*/
- public static void onLivingBreathe(LivingEntity entity, int consumeAirAmount, int refillAirAmount)
- {
+ public static void onLivingBreathe(LivingEntity entity, int consumeAirAmount, int refillAirAmount) {
// Check things that vanilla considers to be air - these will cause the air supply to be increased.
boolean isAir = entity.getEyeInFluidType().isAir() || entity.level().getBlockState(BlockPos.containing(entity.getX(), entity.getEyeY(), entity.getZ())).is(Blocks.BUBBLE_COLUMN);
// The following effects cause the entity to not drown, but do not cause the air supply to be increased.
boolean canBreathe = !entity.canDrownInFluidType(entity.getEyeInFluidType()) || MobEffectUtil.hasWaterBreathing(entity) || (entity instanceof Player && ((Player) entity).getAbilities().invulnerable);
LivingBreatheEvent breatheEvent = new LivingBreatheEvent(entity, isAir || canBreathe, consumeAirAmount, refillAirAmount, isAir);
MinecraftForge.EVENT_BUS.post(breatheEvent);
- if (breatheEvent.canBreathe())
- {
+ if (breatheEvent.canBreathe()) {
if (breatheEvent.canRefillAir())
- {
entity.setAirSupply(Math.min(entity.getAirSupply() + breatheEvent.getRefillAirAmount(), entity.getMaxAirSupply()));
- }
- }
- else
- {
+ } else
entity.setAirSupply(entity.getAirSupply() - breatheEvent.getConsumeAirAmount());
- }
- if (entity.getAirSupply() <= 0)
- {
+ if (entity.getAirSupply() <= 0) {
LivingDrownEvent drownEvent = new LivingDrownEvent(entity, entity.getAirSupply() <= -20, 2.0F, 8);
- if (!MinecraftForge.EVENT_BUS.post(drownEvent) && drownEvent.isDrowning())
- {
+ if (!MinecraftForge.EVENT_BUS.post(drownEvent) && drownEvent.isDrowning()) {
entity.setAirSupply(0);
Vec3 vec3 = entity.getDeltaMovement();
- for (int i = 0; i < drownEvent.getBubbleCount(); ++i)
- {
+ for (int i = 0; i < drownEvent.getBubbleCount(); ++i) {
double d2 = entity.getRandom().nextDouble() - entity.getRandom().nextDouble();
double d3 = entity.getRandom().nextDouble() - entity.getRandom().nextDouble();
double d4 = entity.getRandom().nextDouble() - entity.getRandom().nextDouble();
@@ -1522,20 +1276,17 @@ public class ForgeHooks
}
if (!isAir && !entity.level().isClientSide && entity.isPassenger() && entity.getVehicle() != null && !entity.getVehicle().canBeRiddenUnderFluidType(entity.getEyeInFluidType(), entity))
- {
entity.stopRiding();
- }
}
- public static void onCreativeModeTabBuildContents(CreativeModeTab tab, ResourceKey tabKey, CreativeModeTab.DisplayItemsGenerator originalGenerator, CreativeModeTab.ItemDisplayParameters params, CreativeModeTab.Output output)
- {
+ public static void onCreativeModeTabBuildContents(CreativeModeTab tab, ResourceKey tabKey, CreativeModeTab.DisplayItemsGenerator originalGenerator, CreativeModeTab.ItemDisplayParameters params, CreativeModeTab.Output output) {
final var entries = new MutableHashedLinkedMap(ItemStackLinkedSet.TYPE_AND_TAG,
- (key, left, right) -> {
- //throw new IllegalStateException("Accidentally adding the same item stack twice " + key.getDisplayName().getString() + " to a Creative Mode Tab: " + tab.getDisplayName().getString());
- // Vanilla adds enchanting books twice in both visibilities.
- // This is just code cleanliness for them. For us lets just increase the visibility and merge the entries.
- return CreativeModeTab.TabVisibility.PARENT_AND_SEARCH_TABS;
- }
+ (key, left, right) -> {
+ //throw new IllegalStateException("Accidentally adding the same item stack twice " + key.getDisplayName().getString() + " to a Creative Mode Tab: " + tab.getDisplayName().getString());
+ // Vanilla adds enchanting books twice in both visibilities.
+ // This is just code cleanliness for them. For us lets just increase the visibility and merge the entries.
+ return CreativeModeTab.TabVisibility.PARENT_AND_SEARCH_TABS;
+ }
);
originalGenerator.accept(params, (stack, vis) -> {
@@ -1549,4 +1300,40 @@ public class ForgeHooks
for (var entry : entries)
output.accept(entry.getKey(), entry.getValue());
}
+
+ @ApiStatus.Internal
+ public static boolean onCustomPayload(final ICustomPacket> packet, final Connection connection) {
+ if (packet.getDirection().getReceptionSide() != EffectiveSide.get()) {
+ connection.disconnect(Component.literal("Illegal packet received, terminating connection"));
+ return false;
+ }
+
+ var context = new CustomPayloadEvent.Context(connection, packet.getDirection());
+ return onCustomPayload(new CustomPayloadEvent(packet, context));
+ }
+
+ @ApiStatus.Internal
+ public static boolean onCustomPayload(CustomPayloadEvent event) {
+ var channel = NetworkRegistry.findTarget(event.getChannel());
+ if (channel != null && channel.dispatch(event))
+ return true;
+
+ // Should we always fire this, even if the channel consumed the packet?
+ if (!event.getSource().getPacketHandled()) {
+ MinecraftForge.EVENT_BUS.post(event);
+ return event.getSource().getPacketHandled();
+ }
+
+ return false;
+ }
+
+ @ApiStatus.Internal
+ public static void handleClientConfigurationComplete(Connection connection) {
+ if (NetworkContext.get(connection).getType() == ConnectionType.VANILLA) {
+ LOGGER.info("Connected to a vanilla server. Catching up missing behaviour.");
+ ConfigTracker.INSTANCE.loadDefaultServerConfigs();
+ } else
+ LOGGER.info("Connected to a modded server.");
+ }
+
}
\ No newline at end of file
diff --git a/src/main/java/net/minecraftforge/common/ForgeInternalHandler.java b/src/main/java/net/minecraftforge/common/ForgeInternalHandler.java
index 1618b4b5c3..ad0e5b5fa5 100644
--- a/src/main/java/net/minecraftforge/common/ForgeInternalHandler.java
+++ b/src/main/java/net/minecraftforge/common/ForgeInternalHandler.java
@@ -19,6 +19,7 @@ import net.minecraftforge.event.entity.EntityJoinLevelEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.event.level.ChunkEvent;
import net.minecraftforge.event.level.LevelEvent;
+import net.minecraftforge.event.network.ConnectionStartEvent;
import net.minecraftforge.eventbus.api.EventPriority;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.event.TagsUpdatedEvent;
@@ -26,27 +27,24 @@ import net.minecraftforge.event.TickEvent;
import net.minecraftforge.event.TickEvent.ClientTickEvent;
import net.minecraftforge.event.TickEvent.ServerTickEvent;
import net.minecraftforge.fml.LogicalSide;
+import net.minecraftforge.network.filters.NetworkFilters;
import net.minecraftforge.common.util.LogicalSidedProvider;
import net.minecraftforge.server.command.ForgeCommand;
import net.minecraftforge.server.command.ConfigCommand;
-public class ForgeInternalHandler
-{
+public class ForgeInternalHandler {
@SubscribeEvent(priority = EventPriority.HIGH)
- public void onEntityJoinWorld(EntityJoinLevelEvent event)
- {
+ public void onEntityJoinWorld(EntityJoinLevelEvent event) {
Entity entity = event.getEntity();
- if (entity.getClass().equals(ItemEntity.class))
- {
+ if (entity.getClass().equals(ItemEntity.class)) {
ItemStack stack = ((ItemEntity)entity).getItem();
Item item = stack.getItem();
- if (item.hasCustomEntity(stack))
- {
+ if (item.hasCustomEntity(stack)) {
Entity newEntity = item.createEntity(event.getLevel(), entity, stack);
- if (newEntity != null)
- {
+ if (newEntity != null) {
entity.discard();
event.setCanceled(true);
+ @SuppressWarnings("resource")
var executor = LogicalSidedProvider.WORKQUEUE.get(event.getLevel().isClientSide ? LogicalSide.CLIENT : LogicalSide.SERVER);
executor.tell(new TickTask(0, () -> event.getLevel().addFreshEntity(newEntity)));
}
@@ -56,59 +54,49 @@ public class ForgeInternalHandler
@SubscribeEvent(priority = EventPriority.HIGHEST)
- public void onDimensionUnload(LevelEvent.Unload event)
- {
+ public void onDimensionUnload(LevelEvent.Unload event) {
if (event.getLevel() instanceof ServerLevel)
FakePlayerFactory.unloadLevel((ServerLevel) event.getLevel());
}
@SubscribeEvent
- public void onServerTick(ServerTickEvent event)
- {
+ public void onServerTick(ServerTickEvent event) {
WorldWorkerManager.tick(event.phase == TickEvent.Phase.START);
}
@SubscribeEvent
- public void checkSettings(ClientTickEvent event)
- {
+ public void checkSettings(ClientTickEvent event) {
//if (event.phase == Phase.END)
// CloudRenderer.updateCloudSettings();
}
@SubscribeEvent
- public void onChunkUnload(ChunkEvent.Unload event)
- {
+ public void onChunkUnload(ChunkEvent.Unload event) {
if (!event.getLevel().isClientSide())
FarmlandWaterManager.removeTickets(event.getChunk());
}
/*
@SubscribeEvent
- public void playerChangeDimension(PlayerEvent.PlayerChangedDimensionEvent event)
- {
+ public void playerChangeDimension(PlayerEvent.PlayerChangedDimensionEvent event) {
if (event.getPlayer() instanceof ServerPlayerEntity)
DimensionManager.rebuildPlayerMap(((ServerPlayerEntity)event.getPlayer()).server.getPlayerList(), true);
}
*/
@SubscribeEvent
- public void playerLogin(PlayerEvent.PlayerLoggedInEvent event)
- {
+ public void playerLogin(PlayerEvent.PlayerLoggedInEvent event) {
UsernameCache.setUsername(event.getEntity().getUUID(), event.getEntity().getGameProfile().getName());
}
@SubscribeEvent
- public void tagsUpdated(TagsUpdatedEvent event)
- {
+ public void tagsUpdated(TagsUpdatedEvent event) {
if (event.shouldUpdateStaticData())
- {
ForgeHooks.updateBurns();
- }
}
@SubscribeEvent
- public void onCommandsRegister(RegisterCommandsEvent event)
- {
+ public void onCommandsRegister(RegisterCommandsEvent event) {
new ForgeCommand(event.getDispatcher());
ConfigCommand.register(event.getDispatcher());
}
@@ -117,14 +105,12 @@ public class ForgeInternalHandler
private static LootModifierManager INSTANCE;
@SubscribeEvent
- public void onResourceReload(AddReloadListenerEvent event)
- {
+ public void onResourceReload(AddReloadListenerEvent event) {
INSTANCE = new LootModifierManager();
event.addListener(INSTANCE);
}
- static LootModifierManager getLootModifierManager()
- {
+ static LootModifierManager getLootModifierManager() {
if(INSTANCE == null)
throw new IllegalStateException("Can not retrieve LootModifierManager until resources have loaded once.");
return INSTANCE;
@@ -132,19 +118,20 @@ public class ForgeInternalHandler
*/
@SubscribeEvent
- public void resourceReloadListeners(AddReloadListenerEvent event)
- {
+ public void resourceReloadListeners(AddReloadListenerEvent event) {
event.addListener(TierSortingRegistry.getReloadListener());
event.addListener(CreativeModeTabRegistry.getReloadListener());
}
@SubscribeEvent(priority = EventPriority.HIGHEST)
- public void builtinMobSpawnBlocker(EntityJoinLevelEvent event)
- {
+ public void builtinMobSpawnBlocker(EntityJoinLevelEvent event) {
if(event.getEntity() instanceof Mob mob && mob.isSpawnCancelled())
- {
event.setCanceled(true);
- }
+ }
+
+ @SubscribeEvent
+ public void onConnectionStart(ConnectionStartEvent event) {
+ NetworkFilters.injectIfNecessary(event.getConnection());
}
}
diff --git a/src/main/java/net/minecraftforge/common/ForgeMod.java b/src/main/java/net/minecraftforge/common/ForgeMod.java
index 1129d504cb..b14373f339 100644
--- a/src/main/java/net/minecraftforge/common/ForgeMod.java
+++ b/src/main/java/net/minecraftforge/common/ForgeMod.java
@@ -71,7 +71,8 @@ import net.minecraftforge.registries.holdersets.AnyHolderSet;
import net.minecraftforge.registries.holdersets.HolderSetType;
import net.minecraftforge.registries.holdersets.NotHolderSet;
import net.minecraftforge.registries.holdersets.OrHolderSet;
-import net.minecraftforge.network.NetworkConstants;
+import net.minecraftforge.network.NetworkInitialization;
+import net.minecraftforge.network.tasks.ForgeNetworkConfigurationHandler;
import net.minecraftforge.event.server.ServerStoppingEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.data.event.GatherDataEvent;
@@ -115,11 +116,9 @@ import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
-import java.util.stream.Collectors;
@Mod("forge")
-public class ForgeMod
-{
+public class ForgeMod {
public static final String VERSION_CHECK_CAT = "version_checking";
private static final Logger LOGGER = LogManager.getLogger();
private static final Marker FORGEMOD = MarkerManager.getMarker("FORGEMOD");
@@ -260,9 +259,9 @@ public class ForgeMod
.viscosity(0))
{
@Override
- public void setItemMovement(ItemEntity entity)
- {
- if (!entity.isNoGravity()) entity.setDeltaMovement(entity.getDeltaMovement().add(0.0D, -0.04D, 0.0D));
+ public void setItemMovement(ItemEntity entity) {
+ if (!entity.isNoGravity())
+ entity.setDeltaMovement(entity.getDeltaMovement().add(0.0D, -0.04D, 0.0D));
}
});
public static final RegistryObject WATER_TYPE = VANILLA_FLUID_TYPES.register("water", () ->
@@ -278,60 +277,52 @@ public class ForgeMod
.canHydrate(true))
{
@Override
- public @Nullable BlockPathTypes getBlockPathType(FluidState state, BlockGetter level, BlockPos pos, @Nullable Mob mob, boolean canFluidLog)
- {
+ public @Nullable BlockPathTypes getBlockPathType(FluidState state, BlockGetter level, BlockPos pos, @Nullable Mob mob, boolean canFluidLog) {
return canFluidLog ? super.getBlockPathType(state, level, pos, mob, true) : null;
}
@Override
- public void initializeClient(Consumer consumer)
- {
- consumer.accept(new IClientFluidTypeExtensions()
- {
+ public void initializeClient(Consumer consumer) {
+ consumer.accept(new IClientFluidTypeExtensions() {
private static final ResourceLocation UNDERWATER_LOCATION = new ResourceLocation("textures/misc/underwater.png"),
WATER_STILL = new ResourceLocation("block/water_still"),
WATER_FLOW = new ResourceLocation("block/water_flow"),
WATER_OVERLAY = new ResourceLocation("block/water_overlay");
@Override
- public ResourceLocation getStillTexture()
- {
+ public ResourceLocation getStillTexture() {
return WATER_STILL;
}
@Override
- public ResourceLocation getFlowingTexture()
- {
+ public ResourceLocation getFlowingTexture() {
return WATER_FLOW;
}
@Nullable
@Override
- public ResourceLocation getOverlayTexture()
- {
+ public ResourceLocation getOverlayTexture() {
return WATER_OVERLAY;
}
@Override
- public ResourceLocation getRenderOverlayTexture(Minecraft mc)
- {
+ public ResourceLocation getRenderOverlayTexture(Minecraft mc) {
return UNDERWATER_LOCATION;
}
@Override
- public int getTintColor()
- {
+ public int getTintColor() {
return 0xFF3F76E4;
}
@Override
- public int getTintColor(FluidState state, BlockAndTintGetter getter, BlockPos pos)
- {
+ public int getTintColor(FluidState state, BlockAndTintGetter getter, BlockPos pos) {
return BiomeColors.getAverageWaterColor(getter, pos) | 0xFF000000;
}
});
}
});
+
public static final RegistryObject LAVA_TYPE = VANILLA_FLUID_TYPES.register("lava", () ->
new FluidType(FluidType.Properties.create()
.descriptionId("block.minecraft.lava")
@@ -347,35 +338,29 @@ public class ForgeMod
.temperature(1300))
{
@Override
- public double motionScale(Entity entity)
- {
+ public double motionScale(Entity entity) {
return entity.level().dimensionType().ultraWarm() ? 0.007D : 0.0023333333333333335D;
}
@Override
- public void setItemMovement(ItemEntity entity)
- {
+ public void setItemMovement(ItemEntity entity) {
Vec3 vec3 = entity.getDeltaMovement();
entity.setDeltaMovement(vec3.x * (double)0.95F, vec3.y + (double)(vec3.y < (double)0.06F ? 5.0E-4F : 0.0F), vec3.z * (double)0.95F);
}
@Override
- public void initializeClient(Consumer consumer)
- {
- consumer.accept(new IClientFluidTypeExtensions()
- {
+ public void initializeClient(Consumer consumer) {
+ consumer.accept(new IClientFluidTypeExtensions() {
private static final ResourceLocation LAVA_STILL = new ResourceLocation("block/lava_still"),
LAVA_FLOW = new ResourceLocation("block/lava_flow");
@Override
- public ResourceLocation getStillTexture()
- {
+ public ResourceLocation getStillTexture() {
return LAVA_STILL;
}
@Override
- public ResourceLocation getFlowingTexture()
- {
+ public ResourceLocation getFlowingTexture() {
return LAVA_FLOW;
}
});
@@ -390,21 +375,18 @@ public class ForgeMod
public static final RegistryObject FLOWING_MILK = RegistryObject.create(new ResourceLocation("flowing_milk"), ForgeRegistries.FLUIDS);
private static ForgeMod INSTANCE;
- public static ForgeMod getInstance()
- {
+ public static ForgeMod getInstance() {
return INSTANCE;
}
/**
* Run this method during mod constructor to enable milk and add it to the Minecraft milk bucket
*/
- public static void enableMilkFluid()
- {
+ public static void enableMilkFluid() {
enableMilkFluid = true;
}
- public ForgeMod()
- {
+ public ForgeMod() {
LOGGER.info(FORGEMOD,"Forge mod loading, version {}, for MC {} with MCP {}", ForgeVersion.getVersion(), MCPVersion.getMCVersion(), MCPVersion.getMCPVersion());
ForgeSnapshotsMod.logStartupWarning();
INSTANCE = this;
@@ -415,7 +397,8 @@ public class ForgeMod
return uuid.toString();
});
- LOGGER.debug(FORGEMOD, "Loading Network data for FML net version: {}", NetworkConstants.init());
+ NetworkInitialization.init();
+
CrashReportCallables.registerCrashCallable("FML", ForgeVersion::getSpec);
CrashReportCallables.registerCrashCallable("Forge", ()->ForgeVersion.getGroup()+":"+ForgeVersion.getVersion());
@@ -440,7 +423,6 @@ public class ForgeMod
HOLDER_SET_TYPES.register(modEventBus);
VANILLA_FLUID_TYPES.register(modEventBus);
MinecraftForge.EVENT_BUS.addListener(this::serverStopping);
- MinecraftForge.EVENT_BUS.addListener(this::missingSoundMapping);
ModLoadingContext.get().registerConfig(ModConfig.Type.CLIENT, ForgeConfig.clientSpec);
ModLoadingContext.get().registerConfig(ModConfig.Type.SERVER, ForgeConfig.serverSpec);
ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, ForgeConfig.commonSpec);
@@ -454,6 +436,7 @@ public class ForgeMod
MinecraftForge.EVENT_BUS.register(MinecraftForge.INTERNAL_HANDLER);
MinecraftForge.EVENT_BUS.addListener(this::mappingChanged);
MinecraftForge.EVENT_BUS.addListener(this::registerPermissionNodes);
+ MinecraftForge.EVENT_BUS.register(new ForgeNetworkConfigurationHandler());
ForgeRegistries.ITEMS.tags().addOptionalTagDefaults(Tags.Items.ENCHANTING_FUELS, Set.of(ForgeRegistries.ITEMS.getDelegateOrThrow(Items.LAPIS_LAZULI)));
@@ -462,28 +445,23 @@ public class ForgeMod
addAlias(ForgeRegistries.ATTRIBUTES, new ResourceLocation("forge", "attack_range"), new ResourceLocation("forge", "entity_reach"));
}
- public void preInit(FMLCommonSetupEvent evt)
- {
+ public void preInit(FMLCommonSetupEvent evt) {
VersionChecker.startVersionCheck();
//VanillaPacketSplitter.register();
}
- public void loadComplete(FMLLoadCompleteEvent event)
- {
+ public void loadComplete(FMLLoadCompleteEvent event) {
}
- public void serverStopping(ServerStoppingEvent evt)
- {
+ public void serverStopping(ServerStoppingEvent evt) {
WorldWorkerManager.clear();
}
- public void mappingChanged(IdMappingEvent evt)
- {
+ public void mappingChanged(IdMappingEvent evt) {
Ingredient.invalidateAll();
}
- public void gatherData(GatherDataEvent event)
- {
+ public void gatherData(GatherDataEvent event) {
DataGenerator gen = event.getGenerator();
PackOutput packOutput = gen.getPackOutput();
CompletableFuture lookupProvider = event.getLookupProvider();
@@ -509,33 +487,9 @@ public class ForgeMod
gen.addProvider(event.includeClient(), new VanillaSoundDefinitionsProvider(packOutput, existingFileHelper));
}
- public void missingSoundMapping(MissingMappingsEvent event)
- {
- if (event.getKey() != ForgeRegistries.Keys.SOUND_EVENTS)
- return;
-
- //Removed in 1.15, see https://minecraft.gamepedia.com/Parrot#History
- List removedSounds = Arrays.asList("entity.parrot.imitate.panda", "entity.parrot.imitate.zombie_pigman", "entity.parrot.imitate.enderman", "entity.parrot.imitate.polar_bear", "entity.parrot.imitate.wolf");
- for (MissingMappingsEvent.Mapping mapping : event.getAllMappings(ForgeRegistries.Keys.SOUND_EVENTS))
- {
- ResourceLocation regName = mapping.getKey();
- if (regName != null && regName.getNamespace().equals("minecraft"))
- {
- String path = regName.getPath();
- if (removedSounds.stream().anyMatch(s -> s.equals(path)))
- {
- LOGGER.info("Ignoring removed minecraft sound {}", regName);
- mapping.ignore();
- }
- }
- }
- }
-
// done in an event instead of deferred to only enable if a mod requests it
- public void registerFluids(RegisterEvent event)
- {
- if (enableMilkFluid)
- {
+ public void registerFluids(RegisterEvent event) {
+ if (enableMilkFluid) {
// register milk fill, empty sounds (delegates to water fill, empty sounds)
event.register(ForgeRegistries.Keys.SOUND_EVENTS, helper -> {
helper.register(BUCKET_EMPTY_MILK.getId(), SoundEvent.createVariableRangeEvent(BUCKET_EMPTY_MILK.getId()));
@@ -544,28 +498,23 @@ public class ForgeMod
// register fluid type
event.register(ForgeRegistries.Keys.FLUID_TYPES, helper -> helper.register(MILK_TYPE.getId(), new FluidType(
- FluidType.Properties.create().density(1024).viscosity(1024)
- .sound(SoundActions.BUCKET_FILL, BUCKET_FILL_MILK.get())
- .sound(SoundActions.BUCKET_EMPTY, BUCKET_EMPTY_MILK.get())
- )
- {
+ FluidType.Properties.create().density(1024).viscosity(1024)
+ .sound(SoundActions.BUCKET_FILL, BUCKET_FILL_MILK.get())
+ .sound(SoundActions.BUCKET_EMPTY, BUCKET_EMPTY_MILK.get())
+ ) {
@Override
- public void initializeClient(Consumer consumer)
- {
- consumer.accept(new IClientFluidTypeExtensions()
- {
- private static final ResourceLocation MILK_STILL = new ResourceLocation("forge", "block/milk_still"),
- MILK_FLOW = new ResourceLocation("forge", "block/milk_flowing");
+ public void initializeClient(Consumer consumer) {
+ consumer.accept(new IClientFluidTypeExtensions() {
+ private static final ResourceLocation MILK_STILL = new ResourceLocation("forge", "block/milk_still");
+ private static final ResourceLocation MILK_FLOW = new ResourceLocation("forge", "block/milk_flowing");
@Override
- public ResourceLocation getStillTexture()
- {
+ public ResourceLocation getStillTexture() {
return MILK_STILL;
}
@Override
- public ResourceLocation getFlowingTexture()
- {
+ public ResourceLocation getFlowingTexture() {
return MILK_FLOW;
}
});
@@ -583,24 +532,20 @@ public class ForgeMod
}
}
- public void registerVanillaDisplayContexts(RegisterEvent event)
- {
- if (event.getRegistryKey().equals(ForgeRegistries.Keys.DISPLAY_CONTEXTS))
- {
+ public void registerVanillaDisplayContexts(RegisterEvent event) {
+ if (event.getRegistryKey().equals(ForgeRegistries.Keys.DISPLAY_CONTEXTS)) {
IForgeRegistryInternal forgeRegistry = (IForgeRegistryInternal) event.getForgeRegistry();
if (forgeRegistry == null)
throw new IllegalStateException("Item display context was not a forge registry, wtf???");
Arrays.stream(ItemDisplayContext.values())
- .filter(Predicate.not(ItemDisplayContext::isModded))
- .forEach(ctx -> forgeRegistry.register(ctx.getId(), new ResourceLocation("minecraft", ctx.getSerializedName()), ctx));
+ .filter(Predicate.not(ItemDisplayContext::isModded))
+ .forEach(ctx -> forgeRegistry.register(ctx.getId(), new ResourceLocation("minecraft", ctx.getSerializedName()), ctx));
}
}
- public void registerRecipeSerializers(RegisterEvent event)
- {
- if (event.getRegistryKey().equals(ForgeRegistries.Keys.RECIPE_SERIALIZERS))
- {
+ public void registerRecipeSerializers(RegisterEvent event) {
+ if (event.getRegistryKey().equals(ForgeRegistries.Keys.RECIPE_SERIALIZERS)) {
CraftingHelper.register(AndCondition.Serializer.INSTANCE);
CraftingHelper.register(FalseCondition.Serializer.INSTANCE);
CraftingHelper.register(ItemExistsCondition.Serializer.INSTANCE);
@@ -623,8 +568,7 @@ public class ForgeMod
}
}
- public void registerLootData(RegisterEvent event)
- {
+ public void registerLootData(RegisterEvent event) {
if (!event.getRegistryKey().equals(Registries.LOOT_CONDITION_TYPE))
return;
@@ -635,8 +579,7 @@ public class ForgeMod
public static final PermissionNode USE_SELECTORS_PERMISSION = new PermissionNode<>("forge", "use_entity_selectors",
PermissionTypes.BOOLEAN, (player, uuid, contexts) -> player != null && player.hasPermissions(Commands.LEVEL_GAMEMASTERS));
- public void registerPermissionNodes(PermissionGatherEvent.Nodes event)
- {
+ public void registerPermissionNodes(PermissionGatherEvent.Nodes event) {
event.addNodes(USE_SELECTORS_PERMISSION);
}
@@ -644,8 +587,7 @@ public class ForgeMod
* TODO: Remove when {@link ForgeRegistry#addAlias(ResourceLocation, ResourceLocation)} is elevated to {@link IForgeRegistry}.
*/
@Deprecated(forRemoval = true, since = "1.20")
- private static void addAlias(IForgeRegistry registry, ResourceLocation from, ResourceLocation to)
- {
+ private static void addAlias(IForgeRegistry registry, ResourceLocation from, ResourceLocation to) {
ForgeRegistry fReg = (ForgeRegistry) registry;
fReg.addAlias(from, to);
}
diff --git a/src/main/java/net/minecraftforge/common/TierSortingRegistry.java b/src/main/java/net/minecraftforge/common/TierSortingRegistry.java
index 75679eaa7b..28b679189b 100644
--- a/src/main/java/net/minecraftforge/common/TierSortingRegistry.java
+++ b/src/main/java/net/minecraftforge/common/TierSortingRegistry.java
@@ -31,26 +31,28 @@ import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.event.ClientPlayerNetworkEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
+import net.minecraftforge.event.network.CustomPayloadEvent;
import net.minecraftforge.fml.loading.FMLEnvironment;
import net.minecraftforge.fml.loading.toposort.TopologicalSort;
+import net.minecraftforge.network.ChannelBuilder;
import net.minecraftforge.network.NetworkDirection;
-import net.minecraftforge.network.NetworkEvent;
-import net.minecraftforge.network.NetworkRegistry;
import net.minecraftforge.network.PacketDistributor;
-import net.minecraftforge.network.simple.SimpleChannel;
+import net.minecraftforge.network.SimpleChannel;
import net.minecraftforge.server.ServerLifecycleHooks;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
-import java.io.*;
-import java.util.*;
-import java.util.function.Supplier;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
import java.util.stream.Collectors;
-public class TierSortingRegistry
-{
+public class TierSortingRegistry {
private static final Logger LOGGER = LogManager.getLogger();
private static final ResourceLocation ITEM_TIER_ORDERING_JSON = new ResourceLocation("forge", "item_tier_ordering.json");
@@ -61,8 +63,7 @@ public class TierSortingRegistry
* @param after List of tiers to place this tier after (the tiers in the list will be considered lesser tiers)
* @param before List of tiers to place this tier before (the tiers in the list will be considered better tiers)
*/
- public static synchronized Tier registerTier(Tier tier, ResourceLocation name, List