Compare commits

..
Author SHA1 Message Date
retrooper 9b3cf41f35 Working on loading API improvements for Spigot. 2022-12-07 22:20:44 +01:00
977 changed files with 142041 additions and 2481438 deletions

No files matched your search

+3 -1
View File
@@ -1,3 +1,5 @@
# These are supported funding model platforms
github: [retrooper]
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: retrooper
custom: ['https://paypal.me/retrooperdev']
+13 -29
View File
@@ -8,63 +8,47 @@ jobs:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- uses: actions/checkout@v4
- name: Validate gradle wrapper
uses: gradle/actions/wrapper-validation@v3
- name: Set up JDK 21
uses: actions/setup-java@v4
- uses: actions/checkout@v2
- name: Set up JDK 8
uses: actions/setup-java@v2
with:
java-version: '21'
distribution: 'temurin'
cache: 'gradle'
java-version: '8'
distribution: 'adopt'
server-id: github # Value of the distributionManagement/repository/id field of the pom.xml
settings-path: ${{ github.workspace }} # location for the settings.xml file
- name: Build with Gradle
run: chmod +x gradlew && ./gradlew build
run: gradle shadowJar
- name: Upload build artifacts api
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v1
with:
name: api-build
path: api/build/libs
- name: Upload build artifacts spigot
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v1
with:
name: spigot-build
path: spigot/build/libs
- name: Upload build artifacts netty-common
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v1
with:
name: netty-common-build
path: netty-common/build/libs
- name: Upload build artifacts bungeecord
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v1
with:
name: bungeecord-build
path: bungeecord/build/libs
- name: Upload build artifacts velocity
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v1
with:
name: velocity-build
path: velocity/build/libs
- name: Upload build artifacts fabric
uses: actions/upload-artifact@v4
with:
name: fabric-build
path: fabric/build/libs
- name: Upload build artifacts sponge
uses: actions/upload-artifact@v4
with:
name: sponge-build
path: sponge/build/libs
path: velocity/build/libs
-8
View File
@@ -102,7 +102,6 @@ $RECYCLE.BIN/
.gradle
build/
bin/
# Ignore Gradle GUI config
gradle-app.setting
@@ -119,10 +118,3 @@ run/
!gradle-wrapper.jar
/src/main/resources/plugin.yml
/.idea/
.vscode/
.project
.settings/
.classpath
# Build Source Kotlin
/buildSrc/.kotlin/
+27 -32
View File
@@ -1,42 +1,37 @@
<!--suppress HtmlDeprecatedAttribute -->
<div align="center">
<h2><i>PacketEvents</i></h2>
<h3><i>A powerful networking library for Minecraft packet processing and manipulation.</i></h3>
<a href="https://github.com/retrooper/packetevents/actions"><img src="https://img.shields.io/github/actions/workflow/status/retrooper/packetevents/gradle-publish.yml?style=for-the-badge&logo=github"></a>
<a href="https://discord.gg/DVHxPPxHZc"><img src="https://img.shields.io/discord/721686193061888071?color=5562e9&logo=discord&logoColor=white&style=for-the-badge"></a>
<img src="https://img.shields.io/github/license/retrooper/packetevents?style=for-the-badge&logo=github">
<a href="https://bstats.org/plugin/bukkit/packetevents/11327"><img src="https://img.shields.io/bstats/servers/11327?style=for-the-badge"></a>
<a href="https://github.com/retrooper/packetevents/releases"><img src="https://img.shields.io/github/downloads/retrooper/packetevents/total.svg?style=for-the-badge&logo=github"></a>
</div>
<h3>Resources</h3>
# packetevents
- [Read documentation](https://docs.packetevents.com/)
- [Getting Started](https://docs.packetevents.com/getting-started)
- [JavaDocs](https://javadocs.packetevents.com)
- [Releases](https://github.com/retrooper/packetevents/releases/)
- [GitHub](https://github.com/retrooper/packetevents/releases/)
- [Modrinth](https://modrinth.com/plugin/packetevents)
- [SpigotMC](https://www.spigotmc.org/resources/packetevents-api.80279/)
- [Development Builds](https://ci.codemc.io/job/retrooper/job/packetevents)
- [Statistics](https://bstats.org/plugin/bukkit/packetevents/11327)
[![](https://jitpack.io/v/retrooper/packetevents.svg)](https://jitpack.io/#retrooper/packetevents)
<h3>Sponsors</h3>
PacketEvents is a powerful packet library. Our packet wrappers are efficient and easy to use. With our API, you can write code that runs on many platforms including Spigot, BungeeCord, Velocity, and even client-sided Fabric! Switch to PacketEvents today by joining \
our [Discord Server](https://discord.me/packetevents) for help.
<i>Thanks to the following sponsors for supporting this project:</i>
### Links
* [Find release builds on SpigotMC](https://www.spigotmc.org/resources/packetevents-api.80279/)
* [View documentation on our JavaDocs Page](https://packetevents.github.io/javadocs)
### Setup
[Learn more](https://github.com/retrooper/packetevents/wiki/Setup-2.0)
<a href="https://pebblehost.com"><img src="https://pebblehost.com/src/img/logos/main-old.png" width=150><br>
### Sponsorships
[![](https://www.ej-technologies.com/images/product_banners/jprofiler_small.png)](https://www.ej-technologies.com/products/jprofiler/overview.html)
<a href="https://www.ej-technologies.com"><img src="https://www.ej-technologies.com/images/product_banners/jprofiler_small.png"><br>
### Statistics
PacketEvents optionally collects statistics using [bStats](https://bstats.org/)\
Check out our [bStats page](https://bstats.org/plugin/bukkit/packetevents/11327)
<a href="https://github.com/radstevee"><img src="https://github.com/radstevee.png" width="50px" alt="radstevee"/></a><br>
This library is licensed under the GPLv3 (General Public License version 3). Here are a few sources to learn more about the license.\
[![](https://www.gnu.org/graphics/gplv3-with-text-136x68.png)](https://github.com/retrooper/packetevents/blob/2.0/LICENSE)
### GPL Resources
* https://www.gnu.org/philosophy/free-sw.html
* https://www.gnu.org/philosophy/free-sw.html#clarifying
* https://www.gnu.org/licenses/copyleft.en.html
* https://www.gnu.org/licenses/quick-guide-gplv3.html
* https://gpl-violations.org/faq/sourcecode-faq/
<h3>Credits</h3>
<i>Here are some projects that we are heavily inspired by, thus we have integrated</i>\
<i>small portions of their code into our work.</i>
[Protocol Documentation for the Minecraft Java Edition](https://minecraft.wiki/w/Minecraft_Wiki:Projects/wiki.vg_merge/Protocol)\
### Credit to these projects
[wiki.vg/Protocol](https://wiki.vg/Protocol)\
[netty](https://github.com/netty/netty)\
[gson](https://github.com/google/gson)\
[adventure](https://github.com/KyoriPowered/adventure)\
[ViaVersion](https://github.com/ViaVersion/ViaVersion)\
[ProtocolSupport](https://github.com/ProtocolSupport/ProtocolSupport)\
[adventure](https://github.com/KyoriPowered/adventure)\
[MCProtocolLib](https://github.com/GeyserMC/MCProtocolLib/)
+3
View File
@@ -0,0 +1,3 @@
dependencies {
compileOnly(adventureDependencies)
}
-106
View File
@@ -1,106 +0,0 @@
import com.github.retrooper.compression.strategy.dir.JsonBase64DataDirStrategy
import com.github.retrooper.compression.strategy.dir.JsonRegistryCompressionDirStrategy
import com.github.retrooper.compression.strategy.dir.JsonToNbtDirStrategy
import com.github.retrooper.excludeAdventure
plugins {
packetevents.`shadow-conventions`
packetevents.`library-conventions`
`mapping-compression`
`pe-version`
}
// papermc repo + disableAutoTargetJvm needed for mockbukkit
repositories {
maven("https://repo.papermc.io/repository/maven-public/")
}
java {
withJavadocJar()
}
dependencies {
compileOnlyApi(libs.bundles.adventure)
compileOnlyApi(libs.bundles.adventure.serializers)
implementation(libs.adventure.api)
api(project(":patch:adventure-text-serializer-gson", "shadow")) {
excludeAdventure()
}
api(libs.adventure.text.serializer.legacy) {
excludeAdventure()
}
compileOnly(libs.gson)
testImplementation(libs.bundles.adventure)
testImplementation(project(":patch:adventure-text-serializer-gson"))
testImplementation(libs.adventure.text.serializer.legacy)
testImplementation(project(":netty-common"))
testImplementation(testlibs.mockbukkit)
testImplementation(testlibs.slf4j)
testImplementation(testlibs.bundles.junit)
testImplementation(libs.netty)
testImplementation(libs.classgraph)
}
mappingCompression {
mappingDirectory = rootDir.resolve("mappings")
outDirectory = project.layout.buildDirectory.dir("mappings/generated/assets/mappings")
with<JsonToNbtDirStrategy> {
compress("data")
}
with<JsonBase64DataDirStrategy> {
compress("item_base_components")
}
with<JsonRegistryCompressionDirStrategy> {
compress("registries")
}
}
tasks {
assemble {
setDependsOn(dependsOn.filterNot { it == "shadowNoAdventure" })
}
javadoc {
mustRunAfter(generateVersionsFile)
}
sourcesJar {
mustRunAfter(generateVersionsFile)
}
withType<JavaCompile> {
dependsOn(generateVersionsFile)
}
processResources {
dependsOn(compressMappings)
from(project.layout.buildDirectory.dir("mappings/generated").get())
}
generateVersionsFile {
packageName = "com.github.retrooper.packetevents.util"
}
test {
useJUnitPlatform()
}
shadowJar {
exclude {
val path = it.path
path.startsWith("net/kyori") && !path.startsWith("net/kyori/adventure/text/serializer") && !path.startsWith(
"net/kyori/option"
)
}
}
}
publishing {
publications {
named<MavenPublication>("shadow") {
artifact(tasks["javadocJar"])
}
}
}
@@ -18,15 +18,20 @@
package com.github.retrooper.packetevents;
import org.jetbrains.annotations.ApiStatus;
import com.github.retrooper.packetevents.injector.ChannelInjector;
import com.github.retrooper.packetevents.manager.player.PlayerManager;
import com.github.retrooper.packetevents.manager.protocol.ProtocolManager;
import com.github.retrooper.packetevents.manager.server.ServerManager;
import com.github.retrooper.packetevents.netty.NettyManager;
import com.github.retrooper.packetevents.settings.PacketEventsSettings;
import com.github.retrooper.packetevents.util.LogManager;
public final class PacketEvents {
private static PacketEventsAPI<?> API;
//Put these variable names anywhere else, they are really only for the injectors
@ApiStatus.Internal
public static String IDENTIFIER, ENCODER_NAME, DECODER_NAME, CONNECTION_HANDLER_NAME, SERVER_CHANNEL_HANDLER_NAME,
TIMEOUT_HANDLER_NAME;
TIMEOUT_HANDLER_NAME;
public static PacketEventsAPI<?> getAPI() {
return API;
@@ -35,4 +40,87 @@ public final class PacketEvents {
public static void setAPI(PacketEventsAPI<?> api) {
API = api;
}
public static Builder builder() {
return new Builder();
}
public abstract static class Context<T> {
private final Object pluginInstance;
private final ProtocolManager protocolManager;
private final ServerManager serverManager;
private final PlayerManager playerManager;
private final NettyManager nettyManager;
private final ChannelInjector injector;
private final LogManager logManager;
protected boolean lateBind = false;
public Context(Object pluginInstance, ProtocolManager protocolManager, ServerManager serverManager, PlayerManager playerManager,
NettyManager nettyManager, ChannelInjector injector, LogManager logManager) {
this.pluginInstance = pluginInstance;
this.protocolManager = protocolManager;
this.serverManager = serverManager;
this.playerManager = playerManager;
this.nettyManager = nettyManager;
this.injector = injector;
this.logManager = logManager;
}
protected abstract PacketEventsAPI<T> build();
public Object getPluginInstance() {
return pluginInstance;
}
public ProtocolManager getProtocolManager() {
return protocolManager;
}
public ServerManager getServerManager() {
return serverManager;
}
public PlayerManager getPlayerManager() {
return playerManager;
}
public NettyManager getNettyManager() {
return nettyManager;
}
public ChannelInjector getInjector() {
return injector;
}
public LogManager getLogManager() {
return logManager;
}
}
public static class Builder {
private Context<?> context = null;
private PacketEventsSettings settings = new PacketEventsSettings();
public Builder context(Context<?> context) {
this.context = context;
return this;
}
public Builder settings(PacketEventsSettings settings) {
this.settings = settings;
return this;
}
public PacketEventsAPI<?> build() {
if (context == null) {
throw new IllegalStateException("Failed to build a PacketEvents instance. Please specify a PacketEvents context in the PacketEvents builder to allow PacketEvents to load the correct implementation.");
}
PacketEventsAPI<?> api = context.build();
api.setSettings(settings);
//The implementation may have already set the API.
if (getAPI() == null) {
setAPI(api);
}
return api;
}
}
}
@@ -27,34 +27,37 @@ import com.github.retrooper.packetevents.netty.NettyManager;
import com.github.retrooper.packetevents.settings.PacketEventsSettings;
import com.github.retrooper.packetevents.util.LogManager;
import com.github.retrooper.packetevents.util.PEVersion;
//Note: The PEVersions class is generated. Refer to PEVersionTask.kt
import com.github.retrooper.packetevents.util.PEVersions;
import com.github.retrooper.packetevents.util.updatechecker.UpdateChecker;
import java.util.logging.Logger;
public abstract class PacketEventsAPI<T> {
private final EventManager eventManager = new EventManager();
private final PacketEventsSettings settings = new PacketEventsSettings();
private final UpdateChecker updateChecker = new UpdateChecker();
private final LogManager logManager = new LogManager();
private static final Logger LOGGER = Logger.getLogger(PacketEventsAPI.class.getName());
private static final EventManager EVENT_MANAGER = new EventManager();
private static final UpdateChecker UPDATE_CHECKER = new UpdateChecker();
private static final LogManager LOG_MANAGER = new LogManager();
private final Logger LOGGER = Logger.getLogger(PacketEventsAPI.class.getName());
private PacketEventsSettings settings = new PacketEventsSettings();
//TODO UPDATE
private static final PEVersion VERSION = new PEVersion(2, 0, 0);
public EventManager getEventManager() {
return eventManager;
return EVENT_MANAGER;
}
public PacketEventsSettings getSettings() {
return settings;
}
public void setSettings(PacketEventsSettings settings) {
this.settings = settings;
}
public UpdateChecker getUpdateChecker() {
return updateChecker;
return UPDATE_CHECKER;
}
public PEVersion getVersion() {
//Note: The PEVersions class is generated by the auto-version task. Refer to PEVersionTask.kt
return PEVersions.CURRENT;
return VERSION;
}
public Logger getLogger() {
@@ -62,7 +65,7 @@ public abstract class PacketEventsAPI<T> {
}
public LogManager getLogManager() {
return logManager;
return LOG_MANAGER;
}
public abstract void load();
@@ -75,8 +78,6 @@ public abstract class PacketEventsAPI<T> {
public abstract void terminate();
public abstract boolean isTerminated();
public abstract T getPlugin();
public abstract ServerManager getServerManager();
@@ -1,28 +0,0 @@
package com.github.retrooper.packetevents.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.Documented;
/**
* Marks an API element as obsolete and makes this information available
* at runtime via reflection. Use in conjunction with an IDE-recognized
* annotation like @ApiStatus.Obsolete if IDE warnings are also desired.
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD}) // Adjust targets as needed
public @interface RuntimeObsolete {
/**
* Specifies in which version the API became obsolete.
* Should generally match the value in the corresponding @ApiStatus.Obsolete annotation.
*/
String since() default "";
/**
* Optional: Add a reason or replacement suggestion.
*/
String reason() default "";
}
@@ -19,40 +19,15 @@
package com.github.retrooper.packetevents.event;
import com.github.retrooper.packetevents.PacketEvents;
import com.github.retrooper.packetevents.exception.InvalidHandshakeException;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.logging.Level;
/**
* Class for event managing. Implements both, internal and API methods.
*
* @apiNote It is highly recommended to register the event listeners at server start-up,
* without frequent modifications during runtime, since this class needs to recalculate all of
* its event listeners during any modifications. In other words, it assumes that reads (events fired)
* greatly outnumber writes (listeners modifications). If your case requires frequent listener modifications,
* open a pull request on GitHub and describe your case.
*
* @author retrooper
* @author ShadowOfHeaven (optimization)
*
*/
public class EventManager {
//Using a ConcurrentHashMap is faster and more secure here, compared to Collections.synchronizedMap(new EnumMap<>(PacketListenerPriority.class))
//This is mainly due to:
//1. On each modification Collections.synchronizedMap synchronizes the whole Map object, while ConcurrentHashMap only it's internal, currently modified Node
//2. ConcurrentHashMap won't fail in a multi-thread environment, while Collections.synchronizedMap is said to have a lot of potential problems,
//being a generalized method for synchronization
private final Map<PacketListenerPriority, Set<PacketListenerCommon>> listenersMap = new ConcurrentHashMap<>();
//Since reads greatly outnumber writes, create an array for the best possible iteration time
//Updated as a whole on writes, no index modifications are allowed
private volatile PacketListenerCommon[] listeners = new PacketListenerCommon[0];
private final Map<Byte, HashSet<PacketListenerCommon>> listenersMap = new ConcurrentHashMap<>();
/**
* Call the PacketEvent.
@@ -67,43 +42,28 @@ public class EventManager {
callEvent(event, null);
}
/**
* Call the PacketEvent.
* This method processes the event on all the registered dynamic packet event listeners.
* The {@link PacketListenerPriority#LOWEST} prioritized listeners will be processing first,
* the {@link PacketListenerPriority#MONITOR} will be processing last and can
* be the final decider whether the event has been cancelled or not.
*
* @param event {@link PacketEvent}
* @param postCallListenerAction The action to be ran after all the listeners have finished processing
*/
public void callEvent(PacketEvent event, @Nullable Runnable postCallListenerAction) {
for (PacketListenerCommon listener : listeners) {
try {
event.call(listener);
} catch (Exception t) {
// ignore handshake exceptions
if (t.getClass() != InvalidHandshakeException.class) {
PacketEvents.getAPI().getLogger().log(Level.WARNING, "PacketEvents caught an unhandled exception while calling your listener.", t);
for (byte priority = PacketListenerPriority.LOWEST.getId(); priority <= PacketListenerPriority.MONITOR.getId(); priority++) {
HashSet<PacketListenerCommon> listeners = listenersMap.get(priority);
if (listeners != null) {
for (PacketListenerCommon listener : listeners) {
try {
event.call(listener);
} catch (Throwable t) {
PacketEvents.getAPI().getLogger().log(Level.WARNING, "PacketEvents caught an unhandled exception while calling your listener.", t);
}
if (postCallListenerAction != null) {
postCallListenerAction.run();
}
}
}
if (postCallListenerAction != null) {
postCallListenerAction.run();
}
}
// For performance reasons, we don't want to re-encode the packet if it's not needed.
if (event instanceof ProtocolPacketEvent && !((ProtocolPacketEvent) event).needsReEncode()) {
((ProtocolPacketEvent) event).setLastUsedWrapper(null);
if (event instanceof ProtocolPacketEvent && PacketEvents.getAPI().getSettings().shouldListenersReadOnly()) {
((ProtocolPacketEvent<?>) event).setLastUsedWrapper(null);
}
}
/**
* Register the dynamic packet event listener.
*
* @param listener {@link PacketListenerCommon}
* @param priority {@link PacketListenerPriority}
*/
public PacketListenerCommon registerListener(PacketListener listener, PacketListenerPriority priority) {
PacketListenerCommon packetListenerAbstract = listener.asAbstract(priority);
return registerListener(packetListenerAbstract);
@@ -115,8 +75,13 @@ public class EventManager {
* @param listener {@link PacketListenerCommon}
*/
public PacketListenerCommon registerListener(PacketListenerCommon listener) {
this.registerListenerNoRecalculation(listener);
this.recalculateListeners();
byte priority = listener.getPriority().getId();
HashSet<PacketListenerCommon> listenerSet = listenersMap.get(priority);
if (listenerSet == null) {
listenerSet = new HashSet<>();
}
listenerSet.add(listener);
listenersMap.put(priority, listenerSet);
return listener;
}
@@ -127,22 +92,21 @@ public class EventManager {
*/
public PacketListenerCommon[] registerListeners(PacketListenerCommon... listeners) {
for (PacketListenerCommon listener : listeners) {
this.registerListenerNoRecalculation(listener);
registerListener(listener);
}
this.recalculateListeners();
return listeners;
}
public void unregisterListener(PacketListenerCommon listener) {
if (this.unregisterListenerNoRecalculation(listener)) this.recalculateListeners();
HashSet<PacketListenerCommon> listenerSet = listenersMap.get(listener.getPriority().getId());
if (listenerSet == null) return;
listenerSet.remove(listener);
}
public void unregisterListeners(PacketListenerCommon... listeners) {
boolean modified = false;
for (PacketListenerCommon listener : listeners) {
modified |= this.unregisterListenerNoRecalculation(listener);//OR - at least one of these needs to be true to return true, meaning the boolean will permanently stay true if once set so
unregisterListener(listener);
}
if (modified) this.recalculateListeners();
}
@@ -150,36 +114,6 @@ public class EventManager {
* Unregister all dynamic packet event listeners.
*/
public void unregisterAllListeners() {
this.listenersMap.clear();
synchronized (this) {//like booky10 said, the synchronization is necessary here
this.listeners = new PacketListenerCommon[0];
}
}
//Needs to be synchronized in order to avoid race conditions (for example where the 'listeners' variable
//is overridden by its non-up-to-date value, simply because it finished a bit later than the most recent update)
private void recalculateListeners() {
synchronized (this) {
List<PacketListenerCommon> list = new ArrayList<>();
//adds from LOWEST to MONITOR, so in the correct order
for (PacketListenerPriority priority : PacketListenerPriority.values()) {
Set<PacketListenerCommon> set = this.listenersMap.get(priority);
if (set != null) list.addAll(set);
}
this.listeners = list.toArray(new PacketListenerCommon[0]);
}
}
//Internal registration methods, specifically separated for lesser overhead when registering an array of Listeners
private void registerListenerNoRecalculation(PacketListenerCommon listener) {
Set<PacketListenerCommon> listenerSet = this.listenersMap.computeIfAbsent(listener.getPriority(), p -> new CopyOnWriteArraySet<>());
listenerSet.add(listener);
}
//Returns true if the listener was removed, so a modification occurred
private boolean unregisterListenerNoRecalculation(PacketListenerCommon listener) {
Set<PacketListenerCommon> listenerSet = this.listenersMap.get(listener.getPriority());
return listenerSet != null && listenerSet.remove(listener);
listenersMap.clear();
}
}
@@ -30,7 +30,8 @@ package com.github.retrooper.packetevents.event;
*/
public enum PacketListenerPriority {
/**
* This listener will be run first and has little say in the outcome of events.
* Listener is of very low importance.
* This listener will be ran first.
*/
LOWEST,
@@ -40,11 +41,8 @@ public enum PacketListenerPriority {
LOW,
/**
* The normal listener priority.
* If possible, always pick this.
* It allows other projects to easily overturn your decisions.
* Moreover, it is pretty bold to assume that your project should
* always have the final say.
* Default listener priority.
* Listener is neither important nor unimportant and may run normally.
*/
NORMAL,
@@ -54,13 +52,13 @@ public enum PacketListenerPriority {
HIGH,
/**
* Listener is of critical importance. Use this to decide the final state of packets.
* Listener is of critical importance and wants to decide the cancellation of an event.
*/
HIGHEST,
/**
* Only use this priority if you want to perform logic based on the outcome of an event.
* Please do not modify packets in this stage.
* Listener is purely trying to decide the cancellation of an event.
* This listener should be ran last.
*/
MONITOR;
@@ -18,6 +18,7 @@
package com.github.retrooper.packetevents.event;
import com.github.retrooper.packetevents.event.simple.*;
import com.github.retrooper.packetevents.exception.PacketProcessException;
import com.github.retrooper.packetevents.manager.server.ServerVersion;
import com.github.retrooper.packetevents.netty.buffer.ByteBufHelper;
@@ -25,7 +26,7 @@ import com.github.retrooper.packetevents.protocol.PacketSide;
import com.github.retrooper.packetevents.protocol.packettype.PacketTypeCommon;
import com.github.retrooper.packetevents.protocol.player.User;
public class PacketReceiveEvent extends ProtocolPacketEvent {
public class PacketReceiveEvent extends ProtocolPacketEvent<Object> {
protected PacketReceiveEvent(Object channel, User user, Object player, Object rawByteBuf,
boolean autoProtocolTranslation) throws PacketProcessException {
super(PacketSide.CLIENT, channel, user, player, rawByteBuf, autoProtocolTranslation);
@@ -46,13 +47,20 @@ public class PacketReceiveEvent extends ProtocolPacketEvent {
@Override
public PacketReceiveEvent clone() {
try {
Object clonedBuffer = ByteBufHelper.retainedDuplicate(getByteBuf());
return new PacketReceiveEvent(getPacketId(), getPacketType(), getServerVersion(),
getChannel(), getUser(), getPlayer(), clonedBuffer);
} catch (PacketProcessException e) {
e.printStackTrace();
if (this instanceof PacketHandshakeReceiveEvent) {
return ((PacketHandshakeReceiveEvent)this).clone();
}
else if (this instanceof PacketStatusReceiveEvent) {
return ((PacketStatusReceiveEvent)this).clone();
}
else if (this instanceof PacketLoginReceiveEvent) {
return ((PacketLoginReceiveEvent)this).clone();
}
else if (this instanceof PacketPlayReceiveEvent) {
return ((PacketPlayReceiveEvent)this).clone();
}
else {
return null;
}
return null;
}
}
@@ -18,7 +18,9 @@
package com.github.retrooper.packetevents.event;
import com.github.retrooper.packetevents.event.simple.PacketHandshakeSendEvent;
import com.github.retrooper.packetevents.event.simple.PacketLoginSendEvent;
import com.github.retrooper.packetevents.event.simple.PacketPlaySendEvent;
import com.github.retrooper.packetevents.event.simple.PacketStatusSendEvent;
import com.github.retrooper.packetevents.exception.PacketProcessException;
import com.github.retrooper.packetevents.manager.server.ServerVersion;
import com.github.retrooper.packetevents.netty.buffer.ByteBufHelper;
@@ -26,12 +28,7 @@ import com.github.retrooper.packetevents.protocol.PacketSide;
import com.github.retrooper.packetevents.protocol.packettype.PacketTypeCommon;
import com.github.retrooper.packetevents.protocol.player.User;
import java.util.ArrayList;
import java.util.List;
public class PacketSendEvent extends ProtocolPacketEvent {
private List<Runnable> tasksAfterSend = null;
public class PacketSendEvent extends ProtocolPacketEvent<Object> {
protected PacketSendEvent(Object channel, User user, Object player, Object rawByteBuf,
boolean autoProtocolTranslation) throws PacketProcessException {
super(PacketSide.SERVER, channel, user, player, rawByteBuf, autoProtocolTranslation);
@@ -51,27 +48,19 @@ public class PacketSendEvent extends ProtocolPacketEvent {
listener.onPacketSend(this);
}
public List<Runnable> getTasksAfterSend() {
if (tasksAfterSend == null) {
tasksAfterSend = new ArrayList<>();
}
return tasksAfterSend;
}
public boolean hasTasksAfterSend() {
return tasksAfterSend != null && !tasksAfterSend.isEmpty();
}
@Override
public PacketSendEvent clone() {
try {
Object clonedBuffer = ByteBufHelper.retainedDuplicate(getByteBuf());
return new PacketSendEvent(getPacketId(), getPacketType(), getServerVersion(),
getChannel(), getUser(), getPlayer(), clonedBuffer);
} catch (PacketProcessException e) {
e.printStackTrace();
if (this instanceof PacketStatusSendEvent) {
return ((PacketStatusSendEvent)this).clone();
}
else if (this instanceof PacketLoginSendEvent) {
return ((PacketLoginSendEvent)this).clone();
}
else if (this instanceof PacketPlaySendEvent) {
return ((PacketPlaySendEvent)this).clone();
}
else {
return null;
}
return null;
}
}
@@ -24,11 +24,11 @@ package com.github.retrooper.packetevents.event;
* @author retrooper
* @since 1.6.9
*/
public interface PlayerEvent {
public interface PlayerEvent<T> {
/**
* Associated player.
*
* @return Player.
*/
<T> T getPlayer();
T getPlayer();
}
@@ -19,7 +19,6 @@
package com.github.retrooper.packetevents.event;
import com.github.retrooper.packetevents.PacketEvents;
import com.github.retrooper.packetevents.exception.InvalidDisconnectPacketSend;
import com.github.retrooper.packetevents.exception.PacketProcessException;
import com.github.retrooper.packetevents.manager.server.ServerVersion;
import com.github.retrooper.packetevents.netty.buffer.ByteBufHelper;
@@ -36,15 +35,14 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.List;
public abstract class ProtocolPacketEvent extends PacketEvent implements PlayerEvent, CancellableEvent, UserEvent {
public abstract class ProtocolPacketEvent<T> extends PacketEvent implements PlayerEvent<T>, CancellableEvent, UserEvent {
private final Object channel;
private final ConnectionState connectionState;
private final User user;
private final Object player;
private final T player;
private Object byteBuf;
private final int packetID;
private final PacketTypeCommon packetType;
@@ -53,10 +51,9 @@ public abstract class ProtocolPacketEvent extends PacketEvent implements PlayerE
private PacketWrapper<?> lastUsedWrapper;
private List<Runnable> postTasks = null;
private boolean cloned;
private boolean needsReEncode = PacketEvents.getAPI().getSettings().reEncodeByDefault();
public ProtocolPacketEvent(PacketSide packetSide, Object channel,
User user, Object player, Object byteBuf,
User user, T player, Object byteBuf,
boolean autoProtocolTranslation) throws PacketProcessException {
this.channel = channel;
this.user = user;
@@ -79,21 +76,16 @@ public abstract class ProtocolPacketEvent extends PacketEvent implements PlayerE
throw new PacketProcessException("Failed to read the Packet ID of a packet. (Size: " + size + ")");
}
ClientVersion version = serverVersion.toClientVersion();
ConnectionState state = packetSide == PacketSide.CLIENT ? user.getDecoderState() : user.getEncoderState();
this.packetType = PacketType.getById(packetSide, state,
this.packetType = PacketType.getById(packetSide, user.getConnectionState(),
version, packetID);
if (this.packetType == null) {
// mojang messed up and keeps sending disconnect packets in the wrong protocol state
if (PacketType.getById(packetSide, ConnectionState.PLAY, version, packetID) == PacketType.Play.Server.DISCONNECT) {
throw new InvalidDisconnectPacketSend();
}
throw new PacketProcessException("Failed to map the Packet ID " + packetID + " to a PacketType constant. Bound: " + packetSide.getOpposite() + ", Connection state: " + user.getDecoderState() + ", Server version: " + serverVersion.getReleaseName());
throw new PacketProcessException("Failed to map the Packet ID " + packetID + " to a PacketType constant. Bound: " + packetSide.getOpposite() + ", Connection state: " + user.getConnectionState() + ", Server version: " + serverVersion.getReleaseName());
}
this.connectionState = state;
this.connectionState = user.getConnectionState();
}
public ProtocolPacketEvent(int packetID, PacketTypeCommon packetType, ServerVersion serverVersion, Object channel,
User user, Object player, Object byteBuf) {
User user, T player, Object byteBuf) {
this.channel = channel;
this.user = user;
this.player = player;
@@ -101,21 +93,10 @@ public abstract class ProtocolPacketEvent extends PacketEvent implements PlayerE
this.byteBuf = byteBuf;
this.packetID = packetID;
this.packetType = packetType;
this.connectionState = (packetType != null && packetType.getSide() == PacketSide.SERVER)
? user.getEncoderState() : user.getDecoderState();
this.connectionState = user.getConnectionState();
cloned = true;
}
public void markForReEncode(boolean needsReEncode) {
this.needsReEncode = needsReEncode;
}
public boolean needsReEncode() {
return needsReEncode;
}
public boolean isClone() {
return cloned;
}
@@ -124,15 +105,8 @@ public abstract class ProtocolPacketEvent extends PacketEvent implements PlayerE
return channel;
}
public SocketAddress getAddress() {
return ChannelHelper.remoteAddress(this.channel);
}
/**
* <strong>WARNING:</strong> This doesn't support local addresses or unix sockets.
*/
public InetSocketAddress getSocketAddress() {
return (InetSocketAddress) this.getAddress();
return (InetSocketAddress) ChannelHelper.remoteAddress(channel);
}
@Override
@@ -141,13 +115,10 @@ public abstract class ProtocolPacketEvent extends PacketEvent implements PlayerE
}
@Override
public <T> T getPlayer() {
return (T) player;
public T getPlayer() {
return player;
}
/**
* Gets the connection state this packet has been sent/received in.
*/
public ConnectionState getConnectionState() {
return connectionState;
}
@@ -180,6 +151,7 @@ public abstract class ProtocolPacketEvent extends PacketEvent implements PlayerE
this.byteBuf = byteBuf;
}
@Deprecated
public int getPacketId() {
return packetID;
}
@@ -224,7 +196,7 @@ public abstract class ProtocolPacketEvent extends PacketEvent implements PlayerE
}
@Override
public ProtocolPacketEvent clone() {
public ProtocolPacketEvent<?> clone() {
return this instanceof PacketReceiveEvent ? ((PacketReceiveEvent) this).clone()
: ((PacketSendEvent) this).clone();
}
@@ -41,11 +41,7 @@ public abstract class SimplePacketListenerAbstract extends PacketListenerCommon
onPacketStatusReceive((PacketStatusReceiveEvent) event);
} else if (event instanceof PacketLoginReceiveEvent) {
onPacketLoginReceive((PacketLoginReceiveEvent) event);
}
else if (event instanceof PacketConfigReceiveEvent) {
onPacketConfigReceive((PacketConfigReceiveEvent) event);
}
else if (event instanceof PacketPlayReceiveEvent) {
} else if (event instanceof PacketPlayReceiveEvent) {
onPacketPlayReceive((PacketPlayReceiveEvent) event);
}
}
@@ -56,11 +52,7 @@ public abstract class SimplePacketListenerAbstract extends PacketListenerCommon
onPacketStatusSend((PacketStatusSendEvent) event);
} else if (event instanceof PacketLoginSendEvent) {
onPacketLoginSend((PacketLoginSendEvent) event);
}
else if (event instanceof PacketConfigSendEvent) {
onPacketConfigSend((PacketConfigSendEvent) event);
}
else if (event instanceof PacketPlaySendEvent) {
} else if (event instanceof PacketPlaySendEvent) {
onPacketPlaySend((PacketPlaySendEvent) event);
}
}
@@ -80,12 +72,6 @@ public abstract class SimplePacketListenerAbstract extends PacketListenerCommon
public void onPacketLoginSend(PacketLoginSendEvent event) {
}
public void onPacketConfigReceive(PacketConfigReceiveEvent event) {
}
public void onPacketConfigSend(PacketConfigSendEvent event) {
}
public void onPacketPlayReceive(PacketPlayReceiveEvent event) {
}
@@ -20,7 +20,7 @@ package com.github.retrooper.packetevents.event;
import com.github.retrooper.packetevents.protocol.player.User;
public class UserLoginEvent extends PacketEvent implements CallableEvent, UserEvent, PlayerEvent {
public class UserLoginEvent extends PacketEvent implements CallableEvent, UserEvent, PlayerEvent<Object> {
private final User user;
private final Object player;
@@ -35,8 +35,8 @@ public class UserLoginEvent extends PacketEvent implements CallableEvent, UserEv
}
@Override
public <T> T getPlayer() {
return (T) player;
public Object getPlayer() {
return player;
}
@Override
@@ -1,59 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2022 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.event.simple;
import com.github.retrooper.packetevents.event.PacketReceiveEvent;
import com.github.retrooper.packetevents.exception.PacketProcessException;
import com.github.retrooper.packetevents.manager.server.ServerVersion;
import com.github.retrooper.packetevents.netty.buffer.ByteBufHelper;
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
import com.github.retrooper.packetevents.protocol.packettype.PacketTypeCommon;
import com.github.retrooper.packetevents.protocol.player.User;
public class PacketConfigReceiveEvent extends PacketReceiveEvent {
public PacketConfigReceiveEvent(Object channel, User user,
Object player, Object rawByteBuf,
boolean autoProtocolTranslation) throws PacketProcessException {
super(channel, user, player, rawByteBuf, autoProtocolTranslation);
}
protected PacketConfigReceiveEvent(int packetId, PacketTypeCommon packetType,
ServerVersion serverVersion,
Object channel,
User user, Object player, Object byteBuf) throws PacketProcessException {
super(packetId, packetType, serverVersion, channel, user, player, byteBuf);
}
@Override
public PacketConfigReceiveEvent clone() {
try {
Object clonedBuffer = ByteBufHelper.retainedDuplicate(getByteBuf());
return new PacketConfigReceiveEvent(getPacketId(), getPacketType(), getServerVersion(),
getChannel(), getUser(), getPlayer(), clonedBuffer);
} catch (PacketProcessException e) {
e.printStackTrace();
}
return null;
}
public PacketType.Configuration.Client getPacketType() {
return (PacketType.Configuration.Client) super.getPacketType();
}
}
@@ -1,59 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2022 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.event.simple;
import com.github.retrooper.packetevents.event.PacketSendEvent;
import com.github.retrooper.packetevents.exception.PacketProcessException;
import com.github.retrooper.packetevents.manager.server.ServerVersion;
import com.github.retrooper.packetevents.netty.buffer.ByteBufHelper;
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
import com.github.retrooper.packetevents.protocol.packettype.PacketTypeCommon;
import com.github.retrooper.packetevents.protocol.player.User;
public class PacketConfigSendEvent extends PacketSendEvent {
public PacketConfigSendEvent(Object channel, User user,
Object player, Object rawByteBuf,
boolean autoProtocolTranslation) throws PacketProcessException {
super(channel, user, player, rawByteBuf, autoProtocolTranslation);
}
protected PacketConfigSendEvent(int packetId, PacketTypeCommon packetType,
ServerVersion serverVersion,
Object channel,
User user, Object player, Object byteBuf) throws PacketProcessException {
super(packetId, packetType, serverVersion, channel, user, player, byteBuf);
}
@Override
public PacketConfigSendEvent clone() {
try {
Object clonedBuffer = ByteBufHelper.retainedDuplicate(getByteBuf());
return new PacketConfigSendEvent(getPacketId(), getPacketType(), getServerVersion(),
getChannel(), getUser(), getPlayer(), clonedBuffer);
} catch (PacketProcessException e) {
e.printStackTrace();
}
return null;
}
public PacketType.Configuration.Server getPacketType() {
return (PacketType.Configuration.Server) super.getPacketType();
}
}
@@ -1,5 +0,0 @@
package com.github.retrooper.packetevents.exception;
public class CancelPacketException extends RuntimeException {
public static final CancelPacketException INSTANCE = new CancelPacketException();
}
@@ -1,4 +0,0 @@
package com.github.retrooper.packetevents.exception;
public class InvalidDisconnectPacketSend extends RuntimeException {
}
@@ -1,4 +0,0 @@
package com.github.retrooper.packetevents.exception;
public class InvalidHandshakeException extends RuntimeException {
}
@@ -18,7 +18,7 @@
package com.github.retrooper.packetevents.exception;
public class PacketProcessException extends RuntimeException {
public class PacketProcessException extends Exception {
public PacketProcessException(String msg, Throwable cause) {
super(msg, cause);
}
@@ -18,11 +18,11 @@
package com.github.retrooper.packetevents.injector;
import com.github.retrooper.packetevents.protocol.PacketSide;
import com.github.retrooper.packetevents.protocol.ConnectionState;
import com.github.retrooper.packetevents.protocol.player.User;
import org.jetbrains.annotations.Nullable;
public interface ChannelInjector {
default boolean isServerBound() {
return true;
}
@@ -31,15 +31,13 @@ public interface ChannelInjector {
void uninject();
User getUser(Object channel);
void changeConnectionState(Object channel, @Nullable ConnectionState connectionState);
void updateUser(Object channel, User user);
void setPlayer(Object channel, Object player);
boolean isPlayerSet(Object channel);
boolean isProxy();
default PacketSide getPacketSide() {
return PacketSide.SERVER;
}
boolean hasPlayer(Object player);
}
@@ -26,18 +26,19 @@ import com.github.retrooper.packetevents.event.PacketSendEvent;
import com.github.retrooper.packetevents.manager.protocol.ProtocolManager;
import com.github.retrooper.packetevents.manager.server.ServerVersion;
import com.github.retrooper.packetevents.protocol.ConnectionState;
import com.github.retrooper.packetevents.protocol.nbt.NBTCompound;
import com.github.retrooper.packetevents.protocol.nbt.NBTList;
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
import com.github.retrooper.packetevents.protocol.player.ClientVersion;
import com.github.retrooper.packetevents.protocol.player.User;
import com.github.retrooper.packetevents.protocol.player.UserProfile;
import com.github.retrooper.packetevents.util.LogManager;
import com.github.retrooper.packetevents.util.mappings.SynchronizedRegistriesHandler;
import com.github.retrooper.packetevents.wrapper.configuration.server.WrapperConfigServerRegistryData;
import com.github.retrooper.packetevents.wrapper.handshaking.client.WrapperHandshakingClientHandshake;
import com.github.retrooper.packetevents.wrapper.login.server.WrapperLoginServerLoginSuccess;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerJoinGame;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerRespawn;
import java.net.InetSocketAddress;
public class InternalPacketListener extends PacketListenerAbstract {
public InternalPacketListener() {
@@ -65,57 +66,49 @@ public class InternalPacketListener extends PacketListenerAbstract {
//Map username with channel
synchronized (channel) {
PacketEvents.getAPI().getProtocolManager().setChannel(profile.getUUID(), channel);
ProtocolManager.CHANNELS.put(profile.getUUID(), channel);
}
PacketEvents.getAPI().getLogManager().debug("Mapped player UUID with their channel.");
// Switch the user's connection state to new state, but the variable event.getConnectionState() remains LOGIN
// We switch user state immediately to remain in sync with vanilla, allowing you to encode packets immediately
boolean proxy = PacketEvents.getAPI().getInjector().isProxy();
if (proxy ? event.getUser().getClientVersion().isNewerThanOrEquals(ClientVersion.V_1_20_2)
: event.getServerVersion().isNewerThanOrEquals(ServerVersion.V_1_20_2)) {
user.setEncoderState(ConnectionState.CONFIGURATION);
} else {
user.setConnectionState(ConnectionState.PLAY);
}
//Update connection state(injectors might do some adjustments when we transition into PLAY state)
//This also updates it for the user instance
event.getPostTasks().add(() -> {
PacketEvents.getAPI().getInjector().changeConnectionState(channel, ConnectionState.PLAY);
PacketEvents.getAPI().getLogManager().debug("Transitioned " + profile.getName() + " into the PLAY state!");
});
}
// The server sends dimension information in configuration phase, since 1.20.2
else if (event.getPacketType() == PacketType.Configuration.Server.REGISTRY_DATA) {
WrapperConfigServerRegistryData packet = new WrapperConfigServerRegistryData(event);
// Join game can be used to update world height, and sets dimension data
if (packet.getElements() != null) { // 1.20.2 to 1.20.5
SynchronizedRegistriesHandler.handleRegistry(user, packet.getServerVersion().toClientVersion(),
packet.getRegistryKey(), packet.getElements());
}
if (packet.getRegistryData() != null) { // since 1.20.5
SynchronizedRegistriesHandler.handleLegacyRegistries(user, packet.getServerVersion()
.toClientVersion(), packet.getRegistryData());
}
}
// The server sends registry info in login packet for 1.16 to 1.20.1
else if (event.getPacketType() == PacketType.Play.Server.JOIN_GAME) {
WrapperPlayServerJoinGame joinGame = new WrapperPlayServerJoinGame(event);
user.setEntityId(joinGame.getEntityId());
if (joinGame.getDimensionCodec() != null) { // 1.16 to 1.20.1
SynchronizedRegistriesHandler.handleLegacyRegistries(user, joinGame.getServerVersion().toClientVersion(),
joinGame.getDimensionCodec());
if (event.getServerVersion().isOlderThanOrEquals(ServerVersion.V_1_16_5)) {
return; // Fixed world height, no tags are sent to the client
}
user.setDimensionType(joinGame.getDimensionType());
// Store world height
NBTList<NBTCompound> list = joinGame.getDimensionCodec().getCompoundTagOrNull("minecraft:dimension_type").getCompoundListTagOrNull("value");
user.setWorldNBT(list);
// Update world height
NBTCompound worldNBT = user.getWorldNBT(joinGame.getDimension().getDimensionName()).getCompoundTagOrNull("element");
user.setMinWorldHeight(worldNBT.getNumberTagOrNull("min_y").getAsInt());
user.setTotalWorldHeight(worldNBT.getNumberTagOrNull("height").getAsInt());
}
// Respawn is used to switch dimensions
else if (event.getPacketType() == PacketType.Play.Server.RESPAWN) {
WrapperPlayServerRespawn packet = new WrapperPlayServerRespawn(event);
user.setDimensionType(packet.getDimensionType());
} else if (event.getPacketType() == PacketType.Play.Server.CONFIGURATION_START) {
user.setEncoderState(ConnectionState.CONFIGURATION);
} else if (event.getPacketType() == PacketType.Configuration.Server.CONFIGURATION_END) {
user.setEncoderState(ConnectionState.PLAY);
if (event.getServerVersion().isOlderThanOrEquals(ServerVersion.V_1_16_5)) {
return; // Fixed world height, no tags are sent to the client
}
WrapperPlayServerRespawn respawn = new WrapperPlayServerRespawn(event);
NBTCompound worldNBT = user.getWorldNBT(respawn.getDimension().getDimensionName()).getCompoundTagOrNull("element"); // This is 1.17+, it always sends the world name
user.setMinWorldHeight(worldNBT.getNumberTagOrNull("min_y").getAsInt());
user.setTotalWorldHeight(worldNBT.getNumberTagOrNull("height").getAsInt());
}
}
@@ -123,24 +116,22 @@ public class InternalPacketListener extends PacketListenerAbstract {
public void onPacketReceive(PacketReceiveEvent event) {
User user = event.getUser();
if (event.getPacketType() == PacketType.Handshaking.Client.HANDSHAKE) {
WrapperHandshakingClientHandshake packet = new WrapperHandshakingClientHandshake(event);
ClientVersion clientVersion = packet.getClientVersion();
ConnectionState state = packet.getNextConnectionState();
LogManager logger = PacketEvents.getAPI().getLogManager();
if (logger.isDebug()) {
logger.debug("Processed handshake for " + event.getAddress() + ": "
+ state.name() + " / " + packet.getClientVersion().getReleaseName());
Object channel = event.getChannel();
InetSocketAddress address = event.getSocketAddress();
WrapperHandshakingClientHandshake handshake = new WrapperHandshakingClientHandshake(event);
ConnectionState nextState = handshake.getNextConnectionState();
ClientVersion clientVersion = handshake.getClientVersion();
if (clientVersion == ClientVersion.UNKNOWN) {
return;
}
//Update client version for this event call(and user)
user.setClientVersion(clientVersion);
user.setConnectionState(state);
} else if (event.getPacketType() == PacketType.Login.Client.LOGIN_SUCCESS_ACK) {
user.setDecoderState(ConnectionState.CONFIGURATION);
} else if (event.getPacketType() == PacketType.Play.Client.CONFIGURATION_ACK) {
user.setDecoderState(ConnectionState.CONFIGURATION);
} else if (event.getPacketType() == PacketType.Configuration.Client.CONFIGURATION_END_ACK) {
user.setDecoderState(ConnectionState.PLAY);
PacketEvents.getAPI().getLogManager().debug("Processed " + address.getHostString() + ":" + address.getPort() + "'s client version. Client Version: " + clientVersion.getReleaseName());
event.getPostTasks().add(() -> {
//Transition into the LOGIN OR STATUS connection state
PacketEvents.getAPI().getInjector().changeConnectionState(channel, nextState);
PacketEvents.getAPI().getLogManager().debug("Transitioned " + address.getHostString() + ":" + address.getPort() + " into the " + nextState + " state!");
});
}
}
}
}
@@ -19,12 +19,10 @@
package com.github.retrooper.packetevents.manager.player;
import com.github.retrooper.packetevents.PacketEvents;
import com.github.retrooper.packetevents.event.ProtocolPacketEvent;
import com.github.retrooper.packetevents.protocol.ConnectionState;
import com.github.retrooper.packetevents.protocol.player.ClientVersion;
import com.github.retrooper.packetevents.protocol.player.User;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
public interface PlayerManager {
@@ -36,17 +34,7 @@ public interface PlayerManager {
User getUser(@NotNull Object player);
/**
* <strong>WARNING</strong>: Usage of this method should be avoided. Please use either
* {@link User#getDecoderState()} or {@link User#getEncoderState()}.<br>
* To access the specific state a packet event was sent/received in, use {@link ProtocolPacketEvent#getConnectionState()}.
* <p>
* Since 1.20.2, the Minecraft protocol allows the decoder/encoder connection states to de-sync.
*
* @throws IllegalStateException if encoder/decoder connection states do not match
*/
@ApiStatus.Obsolete
default ConnectionState getConnectionState(@NotNull Object player) throws IllegalStateException {
default ConnectionState getConnectionState(@NotNull Object player) {
return getUser(player).getConnectionState();
}
@@ -20,12 +20,12 @@ package com.github.retrooper.packetevents.manager.protocol;
import com.github.retrooper.packetevents.PacketEvents;
import com.github.retrooper.packetevents.netty.channel.ChannelHelper;
import com.github.retrooper.packetevents.protocol.ConnectionState;
import com.github.retrooper.packetevents.protocol.ProtocolVersion;
import com.github.retrooper.packetevents.protocol.player.ClientVersion;
import com.github.retrooper.packetevents.protocol.player.User;
import com.github.retrooper.packetevents.util.PacketTransformationUtil;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import org.jetbrains.annotations.ApiStatus;
import java.util.Collection;
import java.util.Map;
@@ -33,10 +33,7 @@ import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
public interface ProtocolManager {
@ApiStatus.Internal
Map<UUID, Object> CHANNELS = new ConcurrentHashMap<>();
// Use SocketAddress because ProtocolLib wraps Channels with NettyChannelProxy class
@ApiStatus.Internal
Map<Object, User> USERS = new ConcurrentHashMap<>();
default Collection<User> getUsers() {
@@ -94,75 +91,67 @@ public interface ProtocolManager {
}
}
//TODO Make it clear that this only updates the connection state in our user.
//Sometimes you should use getInjector().changeConnectionState because that can allow the injector to make adjustments.
//This is very important, especially on Spigot.
//As soon as we switch to the play state on spigot, our injector makes some adjustments.
default void changeConnectionState(Object channel, ConnectionState connectionState) {
getUser(channel).setConnectionState(connectionState);
}
default void setClientVersion(Object channel, ClientVersion version) {
getUser(channel).setClientVersion(version);
}
@ApiStatus.Internal
default Object[] transformWrappers(PacketWrapper<?> wrapper, Object channel, boolean outgoing) {
default Object[] transformWrappers(PacketWrapper<?> wrapper) {
//It is possible that our packet transformer util decides to transform one wrapper into multiple packets.
//(Correcting some mistakes on your end)
PacketWrapper<?>[] wrappers = PacketTransformationUtil.transform(wrapper);
Object[] buffers = new Object[wrappers.length];
for (int i = 0; i < wrappers.length; i++) {
PacketWrapper<?> wrappper = wrappers[i];
synchronized (wrappper.bufferLock) {
wrappper.prepareForSend(channel, outgoing);
buffers[i] = wrappper.buffer;
// Fix race condition when sending packets to multiple people (due to when the buffer is freed)
wrappper.buffer = null;
}
wrappers[i].prepareForSend();
buffers[i] = wrappers[i].buffer;
}
return buffers;
}
default void sendPacket(Object channel, PacketWrapper<?> wrapper) {
Object[] transformed = transformWrappers(wrapper, channel, true);
Object[] transformed = transformWrappers(wrapper);
sendPackets(channel, transformed);
}
default void sendPacketSilently(Object channel, PacketWrapper<?> wrapper) {
Object[] transformed = transformWrappers(wrapper, channel, true);
Object[] transformed = transformWrappers(wrapper);
sendPacketsSilently(channel, transformed);
}
default void writePacket(Object channel, PacketWrapper<?> wrapper) {
Object[] transformed = transformWrappers(wrapper, channel, true);
Object[] transformed = transformWrappers(wrapper);
writePackets(channel, transformed);
}
default void writePacketSilently(Object channel, PacketWrapper<?> wrapper) {
Object[] transformed = transformWrappers(wrapper, channel, true);
Object[] transformed = transformWrappers(wrapper);
writePacketsSilently(channel, transformed);
}
default void receivePacket(Object channel, PacketWrapper<?> wrapper) {
Object[] transformed = transformWrappers(wrapper, channel, false);
Object[] transformed = transformWrappers(wrapper);
receivePackets(channel, transformed);
}
default void receivePacketSilently(Object channel, PacketWrapper<?> wrapper) {
Object[] transformed = transformWrappers(wrapper, channel, false);
Object[] transformed = transformWrappers(wrapper);
receivePacketsSilently(channel, transformed);
}
default User getUser(Object channel) {
Object pipeline = ChannelHelper.getPipeline(channel);
return USERS.get(pipeline);
return USERS.get(channel);
}
@ApiStatus.Internal
default User removeUser(Object channel) {
Object pipeline = ChannelHelper.getPipeline(channel);
return USERS.remove(pipeline);
}
@ApiStatus.Internal
default void setUser(Object channel, User user) {
synchronized (channel) {
Object pipeline = ChannelHelper.getPipeline(channel);
USERS.put(pipeline, user);
USERS.put(channel, user);
}
PacketEvents.getAPI().getInjector().updateUser(channel, user);
}
@@ -170,23 +159,4 @@ public interface ProtocolManager {
default Object getChannel(UUID uuid) {
return CHANNELS.get(uuid);
}
@ApiStatus.Internal
default void setChannel(UUID uuid, Object channel) {
CHANNELS.put(uuid, channel);
}
@ApiStatus.Internal
default void removeChannel(Object channel) {
CHANNELS.values().remove(channel);
}
@ApiStatus.Internal
default void removeChannelById(UUID uuid) {
CHANNELS.remove(uuid);
}
default boolean hasChannel(Object channel) {
return CHANNELS.containsValue(channel);
}
}
@@ -18,10 +18,6 @@
package com.github.retrooper.packetevents.manager.server;
import com.github.retrooper.packetevents.protocol.player.ClientVersion;
import com.github.retrooper.packetevents.protocol.player.User;
import org.jetbrains.annotations.Nullable;
public interface ServerManager {
/**
* Get the server version.
@@ -38,20 +34,4 @@ public interface ServerManager {
default SystemOS getOS() {
return SystemOS.getOS();
}
/**
* Gets a platform-specific network-synchronized-registries cache key.
* <p>
* This tells packetevents, if a registry should be cached or read again. On
* backend servers with global registries, this may be a constant value. On
* proxy servers with per-server registries, this may be a value which depends
* on the current server the {@link User} is on.
*
* @param user the {@link User} for which the registry gets read
* @param version the version the packet is for
* @return some value or null for no caching at all
*/
default @Nullable Object getRegistryCacheKey(User user, ClientVersion version) {
return null; // no caching
}
}
@@ -34,7 +34,7 @@ public enum ServerVersion {
//TODO Rename to MinecraftVersion?
V_1_7_10(5),
V_1_8(47), V_1_8_3(47), V_1_8_8(47),
V_1_9(107), V_1_9_1(108), V_1_9_2(109), V_1_9_4(110),
V_1_9(107), V_1_9_2(109), V_1_9_4(110),
//1.10 and 1.10.1 are redundant
V_1_10(210), V_1_10_1(210), V_1_10_2(210),
V_1_11(315), V_1_11_2(316),
@@ -46,11 +46,7 @@ public enum ServerVersion {
V_1_17(755), V_1_17_1(756),
V_1_18(757), V_1_18_1(757), V_1_18_2(758),
//1.19.1 and 1.19.2 have the same protocol version
V_1_19(759), V_1_19_1(760), V_1_19_2(760), V_1_19_3(761), V_1_19_4(762),
//1.20 and 1.20.1 have the same protocol version. 1.20.3 and 1.20.4 have the same protocol version. 1.20.5 and 1.20.6 have the same protocol version
V_1_20(763), V_1_20_1(763), V_1_20_2(764), V_1_20_3(765), V_1_20_4(765), V_1_20_5(766), V_1_20_6(766),
//1.21 and 1.21.1 have the same protocol version. 1.21.2 and 1.21.3 have the same protocol version
V_1_21(767), V_1_21_1(767), V_1_21_2(768), V_1_21_3(768), V_1_21_4(769), V_1_21_5(770),
V_1_19(759), V_1_19_1(760), V_1_19_2(760),
//TODO UPDATE Add server version constant
ERROR(-1, true);
@@ -24,13 +24,8 @@ public interface ByteBufAllocationOperator {
Object copiedBuffer(byte[] bytes);
Object buffer();
Object buffer(int initialCapacity);
Object directBuffer();
Object directBuffer(int initialCapacity);
Object compositeBuffer();
Object compositeBuffer(int maxNumComponents);
Object emptyBuffer();
}
@@ -103,14 +103,6 @@ public class ByteBufHelper {
PacketEvents.getAPI().getNettyManager().getByteBufOperator().writeShort(buffer, value);
}
public static int readMedium(Object buffer) {
return PacketEvents.getAPI().getNettyManager().getByteBufOperator().readMedium(buffer);
}
public static void writeMedium(Object buffer, int value) {
PacketEvents.getAPI().getNettyManager().getByteBufOperator().writeMedium(buffer, value);
}
public static int readInt(Object buffer) {
return PacketEvents.getAPI().getNettyManager().getByteBufOperator().readInt(buffer);
}
@@ -239,19 +231,6 @@ public class ByteBufHelper {
return PacketEvents.getAPI().getNettyManager().getByteBufOperator().resetWriterIndex(buffer);
}
public static Object allocateNewBuffer(Object buffer) {
return PacketEvents.getAPI().getNettyManager().getByteBufOperator().allocateNewBuffer(buffer);
}
public static int getByteSize(int value) {
for (int i = 1; i < 5; ++i) {
if ((value & -1 << i * 7) == 0) {
return i;
}
}
return 5;
}
public static int readVarInt(Object buffer) {
int value = 0;
int length = 0;
@@ -18,8 +18,6 @@
package com.github.retrooper.packetevents.netty.buffer;
import com.github.retrooper.packetevents.exception.PacketProcessException;
import java.io.*;
//TODO give netty credit
public class ByteBufInputStream extends InputStream implements DataInput {
@@ -42,27 +40,27 @@ public class ByteBufInputStream extends InputStream implements DataInput {
this(buffer, ByteBufHelper.readableBytes(buffer), releaseOnClose);
}
public ByteBufInputStream(Object buffer, int maxLength, boolean releaseOnClose) {
public ByteBufInputStream(Object buffer, int length, boolean releaseOnClose) {
this.lineBuf = new StringBuilder();
if (buffer == null) {
throw new NullPointerException("buffer");
} else if (maxLength < 0) {
} else if (length < 0) {
if (releaseOnClose) {
ByteBufHelper.release(buffer);
}
throw new IllegalArgumentException("maxLength: " + maxLength);
} else if (ByteBufHelper.readableBytes(buffer) > maxLength) {
throw new IllegalArgumentException("length: " + length);
} else if (length > ByteBufHelper.readableBytes(buffer)) {
if (releaseOnClose) {
ByteBufHelper.release(buffer);
}
throw new IndexOutOfBoundsException("Too many bytes to be read - Found " + ByteBufHelper.readableBytes(buffer) + ", maximum is " + maxLength);
throw new IndexOutOfBoundsException("Too many bytes to be read - Needs " + length + ", maximum is " + ByteBufHelper.readableBytes(buffer));
} else {
this.releaseOnClose = releaseOnClose;
this.buffer = buffer;
this.startIndex = ByteBufHelper.readerIndex(buffer);
this.endIndex = this.startIndex + ByteBufHelper.readableBytes(buffer);
this.endIndex = this.startIndex + length;
ByteBufHelper.markReaderIndex(buffer);
}
}
@@ -206,8 +204,7 @@ public class ByteBufInputStream extends InputStream implements DataInput {
}
public String readUTF() throws IOException {
String text = DataInputStream.readUTF(this);
return text;
return DataInputStream.readUTF(this);
}
public int readUnsignedByte() throws IOException {
@@ -228,14 +225,7 @@ public class ByteBufInputStream extends InputStream implements DataInput {
if (fieldSize < 0) {
throw new IndexOutOfBoundsException("fieldSize cannot be a negative number");
} else if (fieldSize > this.available()) {
int value = this.available();
String msg = "fieldSize is too long! Length is " + fieldSize + ", but maximum is " + value;
if (value == 0) {
throw new PacketProcessException(msg);
}
else {
throw new EOFException(msg);
}
throw new EOFException("fieldSize is too long! Length is " + fieldSize + ", but maximum is " + this.available());
}
}
}
@@ -35,14 +35,12 @@ public interface ByteBufOperator {
byte readByte(Object buffer);
short readShort(Object buffer);
int readMedium(Object buffer);
int readInt(Object buffer);
long readUnsignedInt(Object buffer);
long readLong(Object buffer);
void writeByte(Object buffer, int value);
void writeShort(Object buffer, int value);
void writeMedium(Object buffer, int value);
void writeInt(Object buffer, int value);
void writeLong(Object buffer, long value);
@@ -74,8 +72,6 @@ public interface ByteBufOperator {
Object markWriterIndex(Object buffer);
Object resetWriterIndex(Object buffer);
Object allocateNewBuffer(Object buffer);
default float readFloat(Object buffer) {
return Float.intBitsToFloat(readInt(buffer));
}
@@ -40,20 +40,4 @@ public class UnpooledByteBufAllocationHelper {
public static Object compositeBuffer() {
return PacketEvents.getAPI().getNettyManager().getByteBufAllocationOperator().compositeBuffer();
}
public static Object buffer(int initialCapacity) {
return PacketEvents.getAPI().getNettyManager().getByteBufAllocationOperator().buffer(initialCapacity);
}
public static Object directBuffer(int initialCapacity) {
return PacketEvents.getAPI().getNettyManager().getByteBufAllocationOperator().directBuffer(initialCapacity);
}
public static Object compositeBuffer(int maxNumComponents) {
return PacketEvents.getAPI().getNettyManager().getByteBufAllocationOperator().compositeBuffer(maxNumComponents);
}
public static Object emptyBuffer() {
return PacketEvents.getAPI().getNettyManager().getByteBufAllocationOperator().emptyBuffer();
}
}
@@ -81,10 +81,6 @@ public class ChannelHelper {
return Arrays.toString(pipelineHandlerNames(channel).toArray(new String[0]));
}
public static Object getPipeline(Object channel) {
return PacketEvents.getAPI().getNettyManager().getChannelOperator().getPipeline(channel);
}
public static Object getPipelineHandler(Object channel, String name) {
return PacketEvents.getAPI().getNettyManager().getChannelOperator().getPipelineHandler(channel, name);
}
@@ -93,10 +89,6 @@ public class ChannelHelper {
return PacketEvents.getAPI().getNettyManager().getChannelOperator().getPipelineContext(channel, handlerName);
}
public static Object pooledByteBuf(Object channel) {
return PacketEvents.getAPI().getNettyManager().getChannelOperator().pooledByteBuf(channel);
}
public static void runInEventLoop(Object channel, Runnable runnable) {
PacketEvents.getAPI().getNettyManager().getChannelOperator().runInEventLoop(channel, runnable);
}
@@ -20,41 +20,26 @@ package com.github.retrooper.packetevents.netty.channel;
import java.net.SocketAddress;
import java.util.List;
import java.util.Set;
public interface ChannelOperator {
Set<Class<? extends Throwable>> getIgnoredHandlerExceptions();
SocketAddress remoteAddress(Object channel);
SocketAddress localAddress(Object channel);
boolean isOpen(Object channel);
Object close(Object channel);
Object write(Object channel, Object buffer);
Object flush(Object channel);
Object writeAndFlush(Object channel, Object buffer);
Object fireChannelRead(Object channel, Object buffer);
Object writeInContext(Object channel, String ctx, Object buffer);
Object flushInContext(Object channel, String ctx);
Object writeAndFlushInContext(Object channel, String ctx, Object buffer);
Object fireChannelReadInContext(Object channel, String ctx, Object buffer);
List<String> pipelineHandlerNames(Object channel);
Object getPipelineHandler(Object channel, String name);
Object getPipelineContext(Object channel, String name);
Object getPipeline(Object channel);
void runInEventLoop(Object channel, Runnable runnable);
Object pooledByteBuf(Object channel);
}
@@ -23,7 +23,7 @@ package com.github.retrooper.packetevents.protocol;
* @since 1.8
*/
public enum ConnectionState {
HANDSHAKING, STATUS, LOGIN, PLAY, CONFIGURATION;
HANDSHAKING, STATUS, LOGIN, PLAY;
public static ConnectionState getById(int id) {
if (id >= values().length || id < 0) {
@@ -1,52 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2023 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.attribute;
import com.github.retrooper.packetevents.PacketEvents;
import com.github.retrooper.packetevents.protocol.mapper.MappedEntity;
import com.github.retrooper.packetevents.protocol.player.ClientVersion;
import com.github.retrooper.packetevents.resources.ResourceLocation;
import com.github.retrooper.packetevents.util.MathUtil;
public interface Attribute extends MappedEntity {
@Override
default ResourceLocation getName() {
return this.getName(PacketEvents.getAPI().getServerManager().getVersion().toClientVersion());
}
ResourceLocation getName(ClientVersion version);
default double sanitizeValue(double value) {
return this.sanitizeValue(value, PacketEvents.getAPI().getServerManager().getVersion().toClientVersion());
}
default double sanitizeValue(double value, ClientVersion version) {
if (!Double.isNaN(value)) {
return MathUtil.clamp(value, this.getMinValue(), this.getMaxValue());
}
return this.getMinValue();
}
double getDefaultValue();
double getMinValue();
double getMaxValue();
}
@@ -1,25 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2024 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.attribute;
public enum AttributeOperation {
ADDITION,
MULTIPLY_BASE,
MULTIPLY_TOTAL,
}
@@ -1,356 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2023 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.attribute;
import com.github.retrooper.packetevents.protocol.player.ClientVersion;
import com.github.retrooper.packetevents.resources.ResourceLocation;
import com.github.retrooper.packetevents.util.mappings.VersionedRegistry;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
public final class Attributes {
private static final VersionedRegistry<Attribute> REGISTRY = new VersionedRegistry<>("attribute");
private Attributes() {
}
private static Attribute define(
String key, @Nullable String legacyPrefix,
double def, double min, double max
) {
return REGISTRY.define(key, data ->
new StaticAttribute(data, legacyPrefix, def, min, max));
}
public static VersionedRegistry<Attribute> getRegistry() {
return REGISTRY;
}
public static Attribute getByName(String name) {
// "remapping" to support < 1.21.2
String normedName = ResourceLocation.normString(name);
if (normedName.startsWith(ResourceLocation.VANILLA_NAMESPACE + ":generic.")
|| normedName.startsWith(ResourceLocation.VANILLA_NAMESPACE + ":player.")
|| normedName.startsWith(ResourceLocation.VANILLA_NAMESPACE + ":zombie.")) {
normedName = normedName.substring(normedName.indexOf('.') + 1);
}
return REGISTRY.getByName(normedName);
}
public static Attribute getById(ClientVersion version, int id) {
return REGISTRY.getById(version, id);
}
public static final Attribute ARMOR = define("armor",
"generic", 0d, 0d, 30d);
public static final Attribute ARMOR_TOUGHNESS = define("armor_toughness",
"generic", 0d, 0d, 20d);
public static final Attribute ATTACK_DAMAGE = define("attack_damage",
"generic", 2d, 0d, 2048d);
public static final Attribute ATTACK_KNOCKBACK = define("attack_knockback",
"generic", 0d, 0d, 5d);
public static final Attribute ATTACK_SPEED = define("attack_speed",
"generic", 4d, 0d, 1024d);
public static final Attribute FLYING_SPEED = define("flying_speed",
"generic", 0.4d, 0d, 1024d);
public static final Attribute FOLLOW_RANGE = define("follow_range",
"generic", 32d, 0d, 2048d);
public static final Attribute KNOCKBACK_RESISTANCE = define("knockback_resistance",
"generic", 0d, 0d, 1d);
public static final Attribute LUCK = define("luck",
"generic", 0d, -1024d, 1024d);
public static final Attribute MAX_HEALTH = define("max_health",
"generic", 20d, 1d, 1024d);
public static final Attribute MOVEMENT_SPEED = define("movement_speed",
"generic", 0.7d, 0d, 1024d);
public static final Attribute SPAWN_REINFORCEMENTS = define("spawn_reinforcements",
"zombie", 0d, 0d, 1d);
/**
* Added with 1.20.2
*/
public static final Attribute MAX_ABSORPTION = define("max_absorption",
"generic", 0d, 0d, 2048d);
/**
* Added with 1.20.5
*/
public static final Attribute BLOCK_BREAK_SPEED = define("block_break_speed",
"player", 1d, 0d, 1024d);
/**
* Added with 1.20.5
*/
public static final Attribute BLOCK_INTERACTION_RANGE = define("block_interaction_range",
"player", 4.5d, 0d, 64d);
/**
* Added with 1.20.5
*/
public static final Attribute ENTITY_INTERACTION_RANGE = define("entity_interaction_range",
"player", 3d, 0d, 64d);
/**
* Added with 1.20.5
*/
public static final Attribute FALL_DAMAGE_MULTIPLIER = define("fall_damage_multiplier",
"generic", 1d, 0d, 100d);
/**
* Added with 1.20.5
*/
public static final Attribute GRAVITY = define("gravity",
"generic", 0.08d, -1d, 1d);
/**
* Added with 1.20.5
*/
public static final Attribute JUMP_STRENGTH = define("jump_strength",
"generic", 0.42d, 0d, 32d);
/**
* Added with 1.20.5
*/
public static final Attribute SAFE_FALL_DISTANCE = define("safe_fall_distance",
"generic", 3d, 0d, 1024d);
/**
* Added with 1.20.5
*/
public static final Attribute SCALE = define("scale",
"generic", 1d, 1d / 16d, 16d);
/**
* Added with 1.20.5
*/
public static final Attribute STEP_HEIGHT = define("step_height",
"generic", 0.6d, 0d, 10d);
/**
* Added with 1.21
*/
public static final Attribute BURNING_TIME = define("burning_time",
"generic", 0d, 1d, 1024d);
/**
* Added with 1.21
*/
public static final Attribute EXPLOSION_KNOCKBACK_RESISTANCE = define("explosion_knockback_resistance",
"generic", 0d, 0d, 1d);
/**
* Added with 1.21
*/
public static final Attribute MINING_EFFICIENCY = define("mining_efficiency",
"player", 0d, 0d, 1024d);
/**
* Added with 1.21
*/
public static final Attribute MOVEMENT_EFFICIENCY = define("movement_efficiency",
"generic", 0d, 0d, 1d);
/**
* Added with 1.21
*/
public static final Attribute OXYGEN_BONUS = define("oxygen_bonus",
"generic", 0d, 0d, 1024d);
/**
* Added with 1.21
*/
public static final Attribute SNEAKING_SPEED = define("sneaking_speed",
"player", 0.3d, 0d, 1d);
/**
* Added with 1.21
*/
public static final Attribute SUBMERGED_MINING_SPEED = define("submerged_mining_speed",
"player", 0.2d, 0d, 20d);
/**
* Added with 1.21
*/
public static final Attribute SWEEPING_DAMAGE_RATIO = define("sweeping_damage_ratio",
"player", 0d, 0d, 1d);
/**
* Added with 1.21
*/
public static final Attribute WATER_MOVEMENT_EFFICIENCY = define("water_movement_efficiency",
"generic", 0d, 0d, 1d);
/**
* Added with 1.21.2
*/
public static final Attribute TEMPT_RANGE = define("tempt_range",
null, 10d, 0d, 2048d);
/**
* This attribute has been renamed in 1.20.5 to {@link #JUMP_STRENGTH}
*/
@ApiStatus.Obsolete
public static final Attribute HORSE_JUMP_STRENGTH = define("horse.jump_strength",
null, 0.7d, 0d, 2d);
/**
* All attribute "type" prefixes were removed with 1.21.2
*/
@Deprecated
public static final Attribute GENERIC_ARMOR = ARMOR;
/**
* All attribute "type" prefixes were removed with 1.21.2
*/
@Deprecated
public static final Attribute GENERIC_ARMOR_TOUGHNESS = ARMOR_TOUGHNESS;
/**
* All attribute "type" prefixes were removed with 1.21.2
*/
@Deprecated
public static final Attribute GENERIC_ATTACK_DAMAGE = ATTACK_DAMAGE;
/**
* All attribute "type" prefixes were removed with 1.21.2
*/
@Deprecated
public static final Attribute GENERIC_ATTACK_KNOCKBACK = ATTACK_KNOCKBACK;
/**
* All attribute "type" prefixes were removed with 1.21.2
*/
@Deprecated
public static final Attribute GENERIC_ATTACK_SPEED = ATTACK_SPEED;
/**
* All attribute "type" prefixes were removed with 1.21.2
*/
@Deprecated
public static final Attribute GENERIC_FLYING_SPEED = FLYING_SPEED;
/**
* All attribute "type" prefixes were removed with 1.21.2
*/
@Deprecated
public static final Attribute GENERIC_FOLLOW_RANGE = FOLLOW_RANGE;
/**
* All attribute "type" prefixes were removed with 1.21.2
*/
@Deprecated
public static final Attribute GENERIC_KNOCKBACK_RESISTANCE = KNOCKBACK_RESISTANCE;
/**
* All attribute "type" prefixes were removed with 1.21.2
*/
@Deprecated
public static final Attribute GENERIC_LUCK = LUCK;
/**
* All attribute "type" prefixes were removed with 1.21.2
*/
@Deprecated
public static final Attribute GENERIC_MAX_HEALTH = MAX_HEALTH;
/**
* All attribute "type" prefixes were removed with 1.21.2
*/
@Deprecated
public static final Attribute GENERIC_MOVEMENT_SPEED = MOVEMENT_SPEED;
/**
* All attribute "type" prefixes were removed with 1.21.2
*/
@Deprecated
public static final Attribute ZOMBIE_SPAWN_REINFORCEMENTS = SPAWN_REINFORCEMENTS;
/**
* All attribute "type" prefixes were removed with 1.21.2
*/
@Deprecated
public static final Attribute GENERIC_MAX_ABSORPTION = MAX_ABSORPTION;
/**
* All attribute "type" prefixes were removed with 1.21.2
*/
@Deprecated
public static final Attribute PLAYER_BLOCK_BREAK_SPEED = BLOCK_BREAK_SPEED;
/**
* All attribute "type" prefixes were removed with 1.21.2
*/
@Deprecated
public static final Attribute PLAYER_BLOCK_INTERACTION_RANGE = BLOCK_INTERACTION_RANGE;
/**
* All attribute "type" prefixes were removed with 1.21.2
*/
@Deprecated
public static final Attribute PLAYER_ENTITY_INTERACTION_RANGE = ENTITY_INTERACTION_RANGE;
/**
* All attribute "type" prefixes were removed with 1.21.2
*/
@Deprecated
public static final Attribute GENERIC_FALL_DAMAGE_MULTIPLIER = FALL_DAMAGE_MULTIPLIER;
/**
* All attribute "type" prefixes were removed with 1.21.2
*/
@Deprecated
public static final Attribute GENERIC_GRAVITY = GRAVITY;
/**
* All attribute "type" prefixes were removed with 1.21.2
*/
@Deprecated
public static final Attribute GENERIC_JUMP_STRENGTH = JUMP_STRENGTH;
/**
* All attribute "type" prefixes were removed with 1.21.2
*/
@Deprecated
public static final Attribute GENERIC_SAFE_FALL_DISTANCE = SAFE_FALL_DISTANCE;
/**
* All attribute "type" prefixes were removed with 1.21.2
*/
@Deprecated
public static final Attribute GENERIC_SCALE = SCALE;
/**
* All attribute "type" prefixes were removed with 1.21.2
*/
@Deprecated
public static final Attribute GENERIC_STEP_HEIGHT = STEP_HEIGHT;
/**
* All attribute "type" prefixes were removed with 1.21.2
*/
@Deprecated
public static final Attribute GENERIC_BURNING_TIME = BURNING_TIME;
/**
* All attribute "type" prefixes were removed with 1.21.2
*/
@Deprecated
public static final Attribute GENERIC_EXPLOSION_KNOCKBACK_RESISTANCE = EXPLOSION_KNOCKBACK_RESISTANCE;
/**
* All attribute "type" prefixes were removed with 1.21.2
*/
@Deprecated
public static final Attribute PLAYER_MINING_EFFICIENCY = MINING_EFFICIENCY;
/**
* All attribute "type" prefixes were removed with 1.21.2
*/
@Deprecated
public static final Attribute GENERIC_MOVEMENT_EFFICIENCY = MOVEMENT_EFFICIENCY;
/**
* All attribute "type" prefixes were removed with 1.21.2
*/
@Deprecated
public static final Attribute GENERIC_OXYGEN_BONUS = OXYGEN_BONUS;
/**
* All attribute "type" prefixes were removed with 1.21.2
*/
@Deprecated
public static final Attribute PLAYER_SNEAKING_SPEED = SNEAKING_SPEED;
/**
* All attribute "type" prefixes were removed with 1.21.2
*/
@Deprecated
public static final Attribute PLAYER_SUBMERGED_MINING_SPEED = SUBMERGED_MINING_SPEED;
/**
* All attribute "type" prefixes were removed with 1.21.2
*/
@Deprecated
public static final Attribute PLAYER_SWEEPING_DAMAGE_RATIO = SWEEPING_DAMAGE_RATIO;
/**
* All attribute "type" prefixes were removed with 1.21.2
*/
@Deprecated
public static final Attribute GENERIC_WATER_MOVEMENT_EFFICIENCY = WATER_MOVEMENT_EFFICIENCY;
static {
REGISTRY.unloadMappings();
}
}
@@ -1,71 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2024 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.attribute;
import com.github.retrooper.packetevents.protocol.mapper.AbstractMappedEntity;
import com.github.retrooper.packetevents.protocol.player.ClientVersion;
import com.github.retrooper.packetevents.resources.ResourceLocation;
import com.github.retrooper.packetevents.util.mappings.TypesBuilderData;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
public class StaticAttribute extends AbstractMappedEntity implements Attribute {
private final @Nullable ResourceLocation legacyName;
private final double defaultValue;
private final double minValue;
private final double maxValue;
@ApiStatus.Internal
public StaticAttribute(
@Nullable TypesBuilderData data, String legacyPrefix,
double defaultValue, double minValue, double maxValue
) {
super(data);
this.defaultValue = defaultValue;
this.minValue = minValue;
this.maxValue = maxValue;
this.legacyName = legacyPrefix == null || data == null ? null : new ResourceLocation(
data.getName().getNamespace(), legacyPrefix + "." + data.getName().getKey());
}
@Override
public ResourceLocation getName(ClientVersion version) {
if (this.data == null) {
throw new UnsupportedOperationException();
}
return version.isNewerThanOrEquals(ClientVersion.V_1_21_2) || this.legacyName == null
? this.data.getName() : this.legacyName;
}
@Override
public double getDefaultValue() {
return this.defaultValue;
}
@Override
public double getMinValue() {
return this.minValue;
}
@Override
public double getMaxValue() {
return this.maxValue;
}
}
@@ -18,150 +18,8 @@
package com.github.retrooper.packetevents.protocol.chat;
import com.github.retrooper.packetevents.protocol.chat.message.ChatMessage_v1_19_1;
import com.github.retrooper.packetevents.protocol.mapper.CopyableEntity;
import com.github.retrooper.packetevents.protocol.mapper.DeepComparableEntity;
import com.github.retrooper.packetevents.protocol.mapper.MappedEntity;
import com.github.retrooper.packetevents.protocol.nbt.NBT;
import com.github.retrooper.packetevents.protocol.nbt.NBTCompound;
import com.github.retrooper.packetevents.protocol.nbt.NBTString;
import com.github.retrooper.packetevents.protocol.player.ClientVersion;
import com.github.retrooper.packetevents.util.mappings.TypesBuilderData;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.util.Index;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.UnknownNullability;
import java.util.Objects;
public interface ChatType extends MappedEntity {
import static com.github.retrooper.packetevents.util.adventure.AdventureIndexUtil.indexValueOrThrow;
public interface ChatType extends MappedEntity, CopyableEntity<ChatType>, DeepComparableEntity {
@UnknownNullability("only nullable for 1.19")
ChatTypeDecoration getChatDecoration();
@ApiStatus.Obsolete(since = "1.19.1")
@Nullable ChatTypeDecoration getOverlayDecoration();
@UnknownNullability("only nullable for 1.19")
ChatTypeDecoration getNarrationDecoration();
@ApiStatus.Obsolete(since = "1.19.1")
@Nullable NarrationPriority getNarrationPriority();
static ChatType readDirect(PacketWrapper<?> wrapper) {
ChatTypeDecoration chatDecoration = ChatTypeDecoration.read(wrapper);
ChatTypeDecoration narrationDecoration = ChatTypeDecoration.read(wrapper);
return new StaticChatType(chatDecoration, narrationDecoration);
}
static void writeDirect(PacketWrapper<?> wrapper, ChatType chatType) {
ChatTypeDecoration.write(wrapper, chatType.getChatDecoration());
ChatTypeDecoration.write(wrapper, chatType.getNarrationDecoration());
}
static ChatType decode(NBT nbt, ClientVersion version, @Nullable TypesBuilderData data) {
// everything is nullable in 1.19, even the chat format!
NBTCompound compound = (NBTCompound) nbt;
NBTCompound chatTag = compound.getCompoundTagOrNull("chat");
NBTCompound narrationTag = compound.getCompoundTagOrNull("narration");
ChatTypeDecoration overlay = null;
NarrationPriority narrationPriority = null;
if (version.isOlderThan(ClientVersion.V_1_19_1)) {
NBTCompound overlayTag = compound.getCompoundTagOrNull("overlay");
if (overlayTag != null) {
// why is this nullable? why is this wrapped? There is no reason to wrap this...
overlayTag = overlayTag.getCompoundTagOrNull("description");
if (overlayTag != null) {
overlay = ChatTypeDecoration.decode(overlayTag, version);
}
}
if (chatTag != null) {
chatTag = chatTag.getCompoundTagOrNull("description");
}
if (narrationTag != null) {
// the priority is the ONLY value which isn't nullable!
narrationPriority = indexValueOrThrow(NarrationPriority.ID_INDEX,
narrationTag.getStringTagValueOrThrow("priority"));
narrationTag = narrationTag.getCompoundTagOrNull("description");
}
} else {
// ensure this isn't null in everything but 1.19
Objects.requireNonNull(chatTag, "NBT chat does not exist");
Objects.requireNonNull(narrationTag, "NBT narration does not exist");
}
ChatTypeDecoration chat = chatTag == null ? null : ChatTypeDecoration.decode(chatTag, version);
ChatTypeDecoration narration = narrationTag == null ? null : ChatTypeDecoration.decode(narrationTag, version);
return new StaticChatType(data, chat, overlay, narration, narrationPriority);
}
static NBT encode(ChatType chatType, ClientVersion version) {
NBTCompound compound = new NBTCompound();
NBT chatTag = chatType.getChatDecoration() == null ? null :
ChatTypeDecoration.encode(chatType.getChatDecoration(), version);
NBT narrationTag = chatType.getNarrationDecoration() == null ? null :
ChatTypeDecoration.encode(chatType.getNarrationDecoration(), version);
if (version.isOlderThan(ClientVersion.V_1_19_1)) {
ChatTypeDecoration overlayDeco = chatType.getOverlayDecoration();
if (overlayDeco != null) {
NBTCompound overlayCompound = new NBTCompound();
overlayCompound.setTag("description",
ChatTypeDecoration.encode(overlayDeco, version));
compound.setTag("overlay", overlayCompound);
}
if (narrationTag != null) {
NBTCompound narrationCompound = new NBTCompound();
narrationCompound.setTag("description", narrationTag);
if (chatType.getNarrationPriority() != null) {
narrationCompound.setTag("priority", new NBTString(chatType.getNarrationPriority().getId()));
}
narrationTag = narrationCompound;
}
if (chatTag != null) {
NBTCompound chatCompound = new NBTCompound();
chatCompound.setTag("description", chatTag);
chatTag = chatCompound;
}
}
if (chatTag != null) {
compound.setTag("chat", chatTag);
}
if (narrationTag != null) {
compound.setTag("narration", narrationTag);
}
return compound;
}
class Bound extends ChatMessage_v1_19_1.ChatTypeBoundNetwork {
public Bound(ChatType type, Component name, @Nullable Component targetName) {
super(type, name, targetName);
}
}
@ApiStatus.Obsolete(since = "1.19.1")
enum NarrationPriority {
CHAT("chat"),
SYSTEM("system");
public static final Index<String, NarrationPriority> ID_INDEX = Index.create(
NarrationPriority.class, NarrationPriority::getId);
private final String id;
NarrationPriority(String id) {
this.id = id;
}
public String getId() {
return this.id;
}
}
}
@@ -1,195 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2024 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.chat;
import com.github.retrooper.packetevents.protocol.nbt.NBT;
import com.github.retrooper.packetevents.protocol.nbt.NBTCompound;
import com.github.retrooper.packetevents.protocol.nbt.NBTList;
import com.github.retrooper.packetevents.protocol.nbt.NBTString;
import com.github.retrooper.packetevents.protocol.player.ClientVersion;
import com.github.retrooper.packetevents.util.adventure.AdventureSerializer;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.ComponentLike;
import net.kyori.adventure.text.format.Style;
import net.kyori.adventure.util.Index;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.function.BiFunction;
import static com.github.retrooper.packetevents.protocol.chat.ChatTypeDecoration.Parameter.CONTENT;
import static com.github.retrooper.packetevents.protocol.chat.ChatTypeDecoration.Parameter.SENDER;
import static com.github.retrooper.packetevents.protocol.chat.ChatTypeDecoration.Parameter.TARGET;
import static com.github.retrooper.packetevents.util.adventure.AdventureIndexUtil.indexValueOrThrow;
import static java.util.Arrays.asList;
import static net.kyori.adventure.text.format.NamedTextColor.GRAY;
import static net.kyori.adventure.text.format.Style.empty;
import static net.kyori.adventure.text.format.Style.style;
import static net.kyori.adventure.text.format.TextDecoration.ITALIC;
public class ChatTypeDecoration {
private final String translationKey;
private final List<Parameter> parameters;
private final Style style;
public ChatTypeDecoration(String translationKey, List<Parameter> parameters, Style style) {
this.translationKey = translationKey;
this.parameters = Collections.unmodifiableList(new ArrayList<>(parameters));
this.style = style;
}
public static ChatTypeDecoration read(PacketWrapper<?> wrapper) {
String translationKey = wrapper.readString();
List<Parameter> parameters = wrapper.readList(ew -> ew.readEnum(Parameter.values()));
Style style = wrapper.readStyle();
return new ChatTypeDecoration(translationKey, parameters, style);
}
public static void write(PacketWrapper<?> wrapper, ChatTypeDecoration decoration) {
wrapper.writeString(decoration.translationKey);
wrapper.writeList(decoration.parameters, PacketWrapper::writeEnum);
wrapper.writeStyle(decoration.style);
}
public static ChatTypeDecoration decode(NBT nbt, ClientVersion version) {
NBTCompound compound = (NBTCompound) nbt;
String translationKey = compound.getStringTagValueOrThrow("translation_key");
NBT paramsTag = compound.getTagOrThrow("parameters");
List<Parameter> params;
if (paramsTag instanceof NBTList<?>) {
params = new ArrayList<>();
NBTList<?> paramsTagList = (NBTList<?>) paramsTag;
for (NBT paramTag : paramsTagList.getTags()) {
String paramId = ((NBTString) paramTag).getValue();
params.add(indexValueOrThrow(Parameter.ID_INDEX, paramId));
}
} else {
String paramId = ((NBTString) paramsTag).getValue();
params = Collections.singletonList(indexValueOrThrow(Parameter.ID_INDEX, paramId));
}
NBTCompound styleTag = compound.getCompoundTagOrNull("style");
Style style = styleTag == null ? empty() :
AdventureSerializer.serializer(version).nbt().deserializeStyle(styleTag);
return new ChatTypeDecoration(translationKey, params, style);
}
public static NBT encode(ChatTypeDecoration decoration, ClientVersion version) {
NBTList<NBTString> paramsTag = NBTList.createStringList();
for (Parameter param : decoration.parameters) {
paramsTag.addTag(new NBTString(param.getId()));
}
NBTCompound compound = new NBTCompound();
compound.setTag("translation_key", new NBTString(decoration.translationKey));
compound.setTag("parameters", paramsTag);
if (!decoration.style.isEmpty()) {
compound.setTag("style", AdventureSerializer.serializer(version)
.nbt().serializeStyle(decoration.style));
}
return compound;
}
public static ChatTypeDecoration withSender(String translationKey) {
return new ChatTypeDecoration(translationKey, asList(SENDER, CONTENT), empty());
}
public static ChatTypeDecoration incomingDirectMessage(String translationKey) {
return new ChatTypeDecoration(translationKey, asList(SENDER, CONTENT),
style(GRAY, ITALIC));
}
public static ChatTypeDecoration outgoingDirectMessage(String translationKey) {
return new ChatTypeDecoration(translationKey, asList(TARGET, CONTENT),
style(GRAY, ITALIC));
}
public static ChatTypeDecoration teamMessage(String translationKey) {
return new ChatTypeDecoration(translationKey, asList(TARGET, SENDER, CONTENT), empty());
}
public Component decorate(Component component, ChatType.Bound chatType) {
ComponentLike[] components = new ComponentLike[this.parameters.size()];
for (int i = 0; i < components.length; i++) {
Parameter parameter = this.parameters.get(i);
components[i] = parameter.selector.apply(component, chatType);
}
return Component.translatable(this.translationKey, null, this.style, components);
}
public String getTranslationKey() {
return this.translationKey;
}
public List<Parameter> getParameters() {
return this.parameters;
}
public Style getStyle() {
return this.style;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof ChatTypeDecoration)) return false;
ChatTypeDecoration that = (ChatTypeDecoration) obj;
if (!this.translationKey.equals(that.translationKey)) return false;
if (!this.parameters.equals(that.parameters)) return false;
return this.style.equals(that.style);
}
@Override
public int hashCode() {
return Objects.hash(this.translationKey, this.parameters, this.style);
}
public enum Parameter {
SENDER("sender", (component, type) -> type.getName()),
TARGET("target", (component, type) -> type.getTargetName() != null
? type.getTargetName() : Component.empty()),
CONTENT("content", (component, type) -> component);
public static final Index<String, Parameter> ID_INDEX = Index.create(
Parameter.class, Parameter::getId);
private final String id;
private final BiFunction<Component, ChatType.Bound, Component> selector;
Parameter(String id, BiFunction<Component, ChatType.Bound, Component> selector) {
this.id = id;
this.selector = selector;
}
public String getId() {
return this.id;
}
@Deprecated
public static @Nullable Parameter valueByName(String id) {
return ID_INDEX.value(id);
}
}
}
@@ -19,67 +19,68 @@
package com.github.retrooper.packetevents.protocol.chat;
import com.github.retrooper.packetevents.protocol.player.ClientVersion;
import com.github.retrooper.packetevents.util.mappings.VersionedRegistry;
import org.jetbrains.annotations.ApiStatus;
import com.github.retrooper.packetevents.resources.ResourceLocation;
import com.github.retrooper.packetevents.util.TypesBuilder;
import com.github.retrooper.packetevents.util.TypesBuilderData;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import static com.github.retrooper.packetevents.protocol.chat.ChatTypeDecoration.incomingDirectMessage;
import static com.github.retrooper.packetevents.protocol.chat.ChatTypeDecoration.outgoingDirectMessage;
import static com.github.retrooper.packetevents.protocol.chat.ChatTypeDecoration.teamMessage;
import static com.github.retrooper.packetevents.protocol.chat.ChatTypeDecoration.withSender;
public class ChatTypes {
private static final Map<String, ChatType> CHAT_TYPE_MAP = new HashMap<>();
//Key - mappings version, value - map with chat type ids and chat types
private static final Map<Byte, Map<Integer, ChatType>> CHAT_TYPE_ID_MAP = new HashMap<>();
private static final TypesBuilder TYPES_BUILDER = new TypesBuilder("chat/chat_type_mappings",
ClientVersion.V_1_18_2,
ClientVersion.V_1_19,
ClientVersion.V_1_19_1);
public final class ChatTypes {
private static final VersionedRegistry<ChatType> REGISTRY = new VersionedRegistry<>("chat_type");
private ChatTypes() {
static {
TYPES_BUILDER.unloadFileMappings();
}
@ApiStatus.Internal
public static ChatType define(String key) {
return define(key, withSender("chat.type.text"));
}
@ApiStatus.Internal
public static ChatType define(String key, ChatTypeDecoration chatDeco) {
return define(key, chatDeco, withSender("chat.type.text.narrate"));
}
@ApiStatus.Internal
public static ChatType define(String key, ChatTypeDecoration chatDeco, ChatTypeDecoration narrationDeco) {
return REGISTRY.define(key, data ->
new StaticChatType(data, chatDeco, narrationDeco));
}
public static VersionedRegistry<ChatType> getRegistry() {
return REGISTRY;
TypesBuilderData data = TYPES_BUILDER.define(key);
ChatType chatType = new ChatType() {
private final int[] ids = data.getData();
@Override
public ResourceLocation getName() {
return data.getName();
}
@Override
public int getId(ClientVersion version) {
int index = TYPES_BUILDER.getDataIndex(version);
return ids[index];
}
};
CHAT_TYPE_MAP.put(chatType.getName().toString(), chatType);
for (ClientVersion version : TYPES_BUILDER.getVersions()) {
int index = TYPES_BUILDER.getDataIndex(version);
Map<Integer, ChatType> typeIdMap = CHAT_TYPE_ID_MAP.computeIfAbsent((byte) index, k -> new HashMap<>());
typeIdMap.put(chatType.getId(version), chatType);
}
return chatType;
}
//with minecraft:key
public static ChatType getByName(String name) {
return REGISTRY.getByName(name);
return CHAT_TYPE_MAP.get(name);
}
public static ChatType getById(ClientVersion version, int id) {
return REGISTRY.getById(version, id);
int index = TYPES_BUILDER.getDataIndex(version);
return CHAT_TYPE_ID_MAP.get((byte) index).get(id);
}
public static final ChatType CHAT = define("chat");
public static final ChatType SAY_COMMAND = define("say_command",
withSender("chat.type.announcement"));
public static final ChatType MSG_COMMAND_INCOMING = define("msg_command_incoming",
incomingDirectMessage("commands.message.display.incoming"));
public static final ChatType MSG_COMMAND_OUTGOING = define("msg_command_outgoing",
outgoingDirectMessage("commands.message.display.outgoing"));
public static final ChatType TEAM_MSG_COMMAND_INCOMING = define("team_msg_command_incoming",
teamMessage("chat.type.team.text"));
public static final ChatType TEAM_MSG_COMMAND_OUTGOING = define("team_msg_command_outgoing",
teamMessage("chat.type.team.sent"));
public static final ChatType EMOTE_COMMAND = define("emote_command",
withSender("chat.type.emote"),
withSender("chat.type.emote"));
// added by CraftBukkit for a few versions
public static final ChatType SAY_COMMAND = define("say_command");
public static final ChatType MSG_COMMAND_INCOMING = define("msg_command_incoming");
public static final ChatType MSG_COMMAND_OUTGOING = define("msg_command_outgoing");
public static final ChatType TEAM_MSG_COMMAND_INCOMING = define("team_msg_command_incoming");
public static final ChatType TEAM_MSG_COMMAND_OUTGOING = define("team_msg_command_outgoing");
public static final ChatType EMOTE_COMMAND = define("emote_command");
public static final ChatType RAW = define("raw");
@Deprecated
@@ -90,17 +91,4 @@ public final class ChatTypes {
public static final ChatType MSG_COMMAND = define("msg_command");
@Deprecated
public static final ChatType TEAM_MSG_COMMAND = define("team_msg_command");
/**
* Returns an immutable view of the chat types.
*
* @return Chat Types
*/
public static Collection<ChatType> values() {
return REGISTRY.getEntries();
}
static {
REGISTRY.unloadMappings();
}
}
@@ -1,12 +1,10 @@
package com.github.retrooper.packetevents.protocol.chat;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import java.util.UUID;
@@ -34,22 +32,6 @@ public class LastSeenMessages {
return entries;
}
public static class Packed {
private List<MessageSignature.Packed> packedMessageSignatures;
public Packed(List<MessageSignature.Packed> packedMessageSignatures) {
this.packedMessageSignatures = packedMessageSignatures;
}
public List<MessageSignature.Packed> getPackedMessageSignatures() {
return packedMessageSignatures;
}
public void setPackedMessageSignatures(List<MessageSignature.Packed> packedMessageSignatures) {
this.packedMessageSignatures = packedMessageSignatures;
}
}
public static class Entry {
private final UUID uuid;
private final byte[] signature;
@@ -68,11 +50,11 @@ public class LastSeenMessages {
}
}
public static class LegacyUpdate {
public static class Update {
private final LastSeenMessages lastSeenMessages;
private final @Nullable Entry lastReceived;
public LegacyUpdate(LastSeenMessages lastSeenMessages, @Nullable Entry lastReceived) {
public Update(LastSeenMessages lastSeenMessages, @Nullable Entry lastReceived) {
this.lastSeenMessages = lastSeenMessages;
this.lastReceived = lastReceived;
}
@@ -85,40 +67,4 @@ public class LastSeenMessages {
return lastReceived;
}
}
public static class Update {
private final int offset;
private final BitSet acknowledged;
private final byte checksum;
/**
* Checksum has been added with 1.21.5
*/
@ApiStatus.Obsolete
public Update(int offset, BitSet acknowledged) {
this(offset, acknowledged, (byte) 0);
}
public Update(int offset, BitSet acknowledged, byte checksum) {
this.offset = offset;
this.acknowledged = acknowledged;
this.checksum = checksum;
}
public int getOffset() {
return offset;
}
public BitSet getAcknowledged() {
return acknowledged;
}
/**
* Added with 1.21.5
*/
public byte getChecksum() {
return this.checksum;
}
}
}
@@ -1,70 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2023 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.chat;
import org.jetbrains.annotations.Nullable;
import java.util.Optional;
public class MessageSignature {
private byte[] bytes;
public MessageSignature(byte[] bytes) {
this.bytes = bytes;
}
public byte[] getBytes() {
return bytes;
}
public void setBytes(byte[] bytes) {
this.bytes = bytes;
}
public static class Packed {
private int id;
private @Nullable MessageSignature fullSignature;
public Packed(@Nullable MessageSignature fullSignature) {
this.id = -1;
this.fullSignature = fullSignature;
}
public Packed(int id) {
this.id = id;
this.fullSignature = null;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Optional<MessageSignature> getFullSignature() {
return Optional.ofNullable(fullSignature);
}
public void setFullSignature(@Nullable MessageSignature fullSignature) {
this.fullSignature = fullSignature;
}
}
}
@@ -1,126 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2022 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.chat;
import com.github.retrooper.packetevents.PacketEvents;
import com.github.retrooper.packetevents.protocol.chat.Parsers.Parser;
import com.github.retrooper.packetevents.resources.ResourceLocation;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.Optional;
public class Node {
private byte flags;
private List<Integer> children;
private int redirectNodeIndex;
private Optional<String> name;
private Optional<Parser> parser;
private Optional<List<Object>> properties;
private Optional<ResourceLocation> suggestionsType;
public Node(
byte flags, List<Integer> children, int redirectNodeIndex, @Nullable String name,
@Nullable Integer parserID, @Nullable List<Object> properties, @Nullable ResourceLocation suggestionsType
) {
this(flags, children, redirectNodeIndex, name, parserID == null ? null : Parsers.getById(
PacketEvents.getAPI().getServerManager().getVersion().toClientVersion(), parserID),
properties, suggestionsType);
}
public Node(
byte flags, List<Integer> children, int redirectNodeIndex, @Nullable String name, @Nullable Parser parser,
@Nullable List<Object> properties, @Nullable ResourceLocation suggestionsType
) {
this.flags = flags;
this.children = children;
this.redirectNodeIndex = redirectNodeIndex;
this.name = Optional.ofNullable(name);
this.parser = Optional.ofNullable(parser);
this.properties = Optional.ofNullable(properties);
this.suggestionsType = Optional.ofNullable(suggestionsType);
}
public byte getFlags() {
return flags;
}
public void setFlags(byte flags) {
this.flags = flags;
}
public List<Integer> getChildren() {
return children;
}
public void setChildren(List<Integer> children) {
this.children = children;
}
public int getRedirectNodeIndex() {
return redirectNodeIndex;
}
public void setRedirectNodeIndex(int redirectNodeIndex) {
this.redirectNodeIndex = redirectNodeIndex;
}
public Optional<String> getName() {
return name;
}
public void setName(Optional<String> name) {
this.name = name;
}
public Optional<Parser> getParser() {
return this.parser;
}
public void setParser(Optional<Parser> parser) {
this.parser = parser;
}
public Optional<Integer> getParserID() {
return this.parser.map(parser -> parser.getId(PacketEvents.getAPI()
.getServerManager().getVersion().toClientVersion()));
}
public void setParserID(Optional<Integer> parserID) {
this.parser = parserID.map(id -> Parsers.getById(PacketEvents.getAPI()
.getServerManager().getVersion().toClientVersion(), id));
}
public Optional<List<Object>> getProperties() {
return properties;
}
public void setProperties(Optional<List<Object>> properties) {
this.properties = properties;
}
public Optional<ResourceLocation> getSuggestionsType() {
return suggestionsType;
}
public void setSuggestionsType(Optional<ResourceLocation> suggestionsType) {
this.suggestionsType = suggestionsType;
}
}
@@ -1,265 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2024 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.chat;
import com.github.retrooper.packetevents.manager.server.ServerVersion;
import com.github.retrooper.packetevents.protocol.mapper.AbstractMappedEntity;
import com.github.retrooper.packetevents.protocol.player.ClientVersion;
import com.github.retrooper.packetevents.resources.ResourceLocation;
import com.github.retrooper.packetevents.util.mappings.TypesBuilderData;
import com.github.retrooper.packetevents.util.mappings.VersionedRegistry;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.function.Function;
public final class Parsers {
private static final VersionedRegistry<Parser> REGISTRY = new VersionedRegistry<>("argument_type");
private Parsers() {
}
@ApiStatus.Internal
public static Parser define(String key) {
return define(key, null, null);
}
@ApiStatus.Internal
public static Parser define(String key, @Nullable Reader reader, @Nullable Writer writer) {
return REGISTRY.define(key, data -> new Parser(data, reader, writer));
}
public static Parser getByName(String name) {
return REGISTRY.getByName(name);
}
public static Parser getById(ClientVersion version, int id) {
return REGISTRY.getById(version, id);
}
public static List<Parser> getParsers() {
return new ArrayList<>(REGISTRY.getEntries());
}
public static VersionedRegistry<Parser> getRegistry() {
return REGISTRY;
}
public static final Parser BRIGADIER_BOOL = define("brigadier:bool", null, null);
public static final Parser BRIGADIER_FLOAT = define("brigadier:float",
packetWrapper -> {
byte flags = packetWrapper.readByte();
float min = (flags & 0x01) != 0 ? packetWrapper.readFloat() : -Float.MAX_VALUE;
float max = (flags & 0x02) != 0 ? packetWrapper.readFloat() : Float.MAX_VALUE;
return Arrays.asList(flags, min, max);
},
(packetWrapper, properties) -> {
byte flags = (byte) properties.get(0);
packetWrapper.writeByte(flags);
if ((flags & 0x01) != 0) packetWrapper.writeFloat((float) properties.get(1));
if ((flags & 0x02) != 0) packetWrapper.writeFloat((float) properties.get(2));
}
);
public static final Parser BRIGADIER_DOUBLE = define("brigadier:double",
packetWrapper -> {
byte flags = packetWrapper.readByte();
double min = (flags & 0x01) != 0 ? packetWrapper.readDouble() : -Double.MAX_VALUE;
double max = (flags & 0x02) != 0 ? packetWrapper.readDouble() : Double.MAX_VALUE;
return Arrays.asList(flags, min, max);
},
(packetWrapper, properties) -> {
byte flags = (byte) properties.get(0);
packetWrapper.writeByte(flags);
if ((flags & 0x01) != 0) packetWrapper.writeDouble((double) properties.get(1));
if ((flags & 0x02) != 0) packetWrapper.writeDouble((double) properties.get(2));
}
);
public static final Parser BRIGADIER_INTEGER = define("brigadier:integer",
packetWrapper -> {
byte flags = packetWrapper.readByte();
int min = (flags & 0x01) != 0 ? packetWrapper.readInt() : Integer.MIN_VALUE;
int max = (flags & 0x02) != 0 ? packetWrapper.readInt() : Integer.MAX_VALUE;
return Arrays.asList(flags, min, max);
},
(packetWrapper, properties) -> {
byte flags = (byte) properties.get(0);
packetWrapper.writeByte(flags);
if ((flags & 0x01) != 0) packetWrapper.writeInt((int) properties.get(1));
if ((flags & 0x02) != 0) packetWrapper.writeInt((int) properties.get(2));
}
);
public static final Parser BRIGADIER_LONG = define("brigadier:long",
packetWrapper -> {
byte flags = packetWrapper.readByte();
long min = (flags & 0x01) != 0 ? packetWrapper.readLong() : Long.MIN_VALUE;
long max = (flags & 0x02) != 0 ? packetWrapper.readLong() : Long.MAX_VALUE;
return Arrays.asList(flags, min, max);
},
(packetWrapper, properties) -> {
byte flags = (byte) properties.get(0);
packetWrapper.writeByte(flags);
if ((flags & 0x01) != 0) packetWrapper.writeLong((long) properties.get(1));
if ((flags & 0x02) != 0) packetWrapper.writeLong((long) properties.get(2));
}
);
public static final Parser BRIGADIER_STRING = define("brigadier:string",
packetWrapper -> Collections.singletonList(packetWrapper.readVarInt()),
(packetWrapper, properties) -> packetWrapper.writeVarInt((Integer) properties.get(0))
);
public static final Parser ENTITY = define("entity",
packetWrapper -> Collections.singletonList(packetWrapper.readByte()),
(packetWrapper, properties) -> packetWrapper.writeByte(((Byte) properties.get(0)).intValue())
);
public static final Parser GAME_PROFILE = define("game_profile", null, null);
public static final Parser BLOCK_POS = define("block_pos", null, null);
public static final Parser COLUMN_POS = define("column_pos", null, null);
public static final Parser VEC3 = define("vec3", null, null);
public static final Parser VEC2 = define("vec2", null, null);
public static final Parser BLOCK_STATE = define("block_state", null, null);
public static final Parser BLOCK_PREDICATE = define("block_predicate", null, null);
public static final Parser ITEM_STACK = define("item_stack", null, null);
public static final Parser ITEM_PREDICATE = define("item_predicate", null, null);
public static final Parser COLOR = define("color", null, null);
public static final Parser COMPONENT = define("component", null, null);
public static final Parser STYLE = define("style", null, null);
public static final Parser MESSAGE = define("message", null, null);
public static final Parser NBT_COMPOUND_TAG = define("nbt_compound_tag", null, null);
@ApiStatus.Obsolete
public static final Parser NBT = define("nbt", null, null);
public static final Parser NBT_TAG = define("nbt_tag", null, null);
public static final Parser NBT_PATH = define("nbt_path", null, null);
public static final Parser OBJECTIVE = define("objective", null, null);
public static final Parser OBJECTIVE_CRITERIA = define("objective_criteria", null, null);
public static final Parser OPERATION = define("operation", null, null);
public static final Parser PARTICLE = define("particle", null, null);
public static final Parser ANGLE = define("angle", null, null);
public static final Parser ROTATION = define("rotation", null, null);
public static final Parser SCOREBOARD_SLOT = define("scoreboard_slot", null, null);
public static final Parser SCORE_HOLDER = define("score_holder",
packetWrapper -> Collections.singletonList(packetWrapper.readByte()),
(packetWrapper, properties) -> packetWrapper.writeByte(((Byte) properties.get(0)).intValue())
);
public static final Parser SWIZZLE = define("swizzle", null, null);
public static final Parser TEAM = define("team", null, null);
public static final Parser ITEM_SLOT = define("item_slot", null, null);
public static final Parser ITEM_SLOTS = define("item_slots", null, null);
public static final Parser RESOURCE_LOCATION = define("resource_location", null, null);
public static final Parser MOB_EFFECT = define("mob_effect", null, null);
public static final Parser FUNCTION = define("function", null, null);
public static final Parser ENTITY_ANCHOR = define("entity_anchor", null, null);
public static final Parser INT_RANGE = define("int_range", null, null);
public static final Parser FLOAT_RANGE = define("float_range", null, null);
public static final Parser ITEM_ENCHANTMENT = define("item_enchantment", null, null);
public static final Parser ENTITY_SUMMON = define("entity_summon", null, null);
public static final Parser DIMENSION = define("dimension", null, null);
public static final Parser GAMEMODE = define("gamemode", null, null);
public static final Parser TIME = define("time",
wrapper -> Collections.singletonList(wrapper.getServerVersion()
.isNewerThanOrEquals(ServerVersion.V_1_19_4) ? wrapper.readInt() : 0),
(wrapper, properties) -> {
if (wrapper.getServerVersion().isNewerThanOrEquals(ServerVersion.V_1_19_4)) {
wrapper.writeInt((int) properties.get(0));
}
}
);
public static final Parser RESOURCE_OR_TAG = define("resource_or_tag",
packetWrapper -> Collections.singletonList(packetWrapper.readIdentifier()),
(packetWrapper, properties) -> packetWrapper.writeIdentifier((ResourceLocation) properties.get(0))
);
public static final Parser RESOURCE_OR_TAG_KEY = define("resource_or_tag_key",
packetWrapper -> Collections.singletonList(packetWrapper.readIdentifier()),
(packetWrapper, properties) -> packetWrapper.writeIdentifier((ResourceLocation) properties.get(0))
);
public static final Parser RESOURCE = define("resource",
packetWrapper -> Collections.singletonList(packetWrapper.readIdentifier()),
(packetWrapper, properties) -> packetWrapper.writeIdentifier((ResourceLocation) properties.get(0))
);
public static final Parser RESOURCE_KEY = define("resource_key",
packetWrapper -> Collections.singletonList(packetWrapper.readIdentifier()),
(packetWrapper, properties) -> packetWrapper.writeIdentifier((ResourceLocation) properties.get(0))
);
public static final Parser TEMPLATE_MIRROR = define("template_mirror", null, null);
public static final Parser TEMPLATE_ROTATION = define("template_rotation", null, null);
public static final Parser HEIGHTMAP = define("heightmap", null, null);
public static final Parser LOOT_TABLE = define("loot_table", null, null);
public static final Parser LOOT_PREDICATE = define("loot_predicate", null, null);
public static final Parser LOOT_MODIFIER = define("loot_modifier", null, null);
public static final Parser UUID = define("uuid", null, null);
/**
* Added with 1.21.5
*/
public static final Parser RESOURCE_SELECTOR = define("resource_selector",
wrapper -> Collections.singletonList(wrapper.readIdentifier()),
(wrapper, value) -> wrapper.writeIdentifier((ResourceLocation) value.get(0))
);
static {
REGISTRY.unloadMappings();
}
@FunctionalInterface
public interface Reader extends Function<PacketWrapper<?>, List<Object>> {}
@FunctionalInterface
public interface Writer extends BiConsumer<PacketWrapper<?>, List<Object>> {}
public static final class Parser extends AbstractMappedEntity {
private final Reader reader;
private final Writer writer;
@Deprecated
public Parser(String name, @Nullable Function<PacketWrapper<?>, List<Object>> read, @Nullable BiConsumer<PacketWrapper<?>, List<Object>> write) {
this(
new TypesBuilderData(new ResourceLocation(name), new int[0]),
read == null ? null : read::apply,
write == null ? null : write::accept
);
}
@ApiStatus.Internal
public Parser(@Nullable TypesBuilderData data, @Nullable Reader reader, @Nullable Writer writer) {
super(data);
this.reader = reader;
this.writer = writer;
}
public Optional<List<Object>> readProperties(PacketWrapper<?> wrapper) {
if (this.reader != null) {
return Optional.of(this.reader.apply(wrapper));
}
return Optional.empty();
}
public void writeProperties(PacketWrapper<?> wrapper, List<Object> properties) {
if (this.writer != null) {
this.writer.accept(wrapper, properties);
}
}
}
}
@@ -1,41 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2022 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.chat;
import com.github.retrooper.packetevents.protocol.player.PublicProfileKey;
import java.util.UUID;
public class RemoteChatSession {
private final UUID sessionId;
private final PublicProfileKey publicProfileKey;
public RemoteChatSession(UUID sessionId, PublicProfileKey publicProfileKey) {
this.sessionId = sessionId;
this.publicProfileKey = publicProfileKey;
}
public UUID getSessionId() {
return sessionId;
}
public PublicProfileKey getPublicProfileKey() {
return publicProfileKey;
}
}
@@ -1,27 +0,0 @@
package com.github.retrooper.packetevents.protocol.chat;
public class SignedCommandArgument {
private String argument;
private MessageSignature signature;
public SignedCommandArgument(String argument, MessageSignature signature) {
this.argument = argument;
this.signature = signature;
}
public String getArgument() {
return argument;
}
public void setArgument(String argument) {
this.argument = argument;
}
public MessageSignature getSignature() {
return signature;
}
public void setSignature(MessageSignature signature) {
this.signature = signature;
}
}
@@ -1,123 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2024 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.chat;
import com.github.retrooper.packetevents.protocol.mapper.AbstractMappedEntity;
import com.github.retrooper.packetevents.util.mappings.TypesBuilderData;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.UnknownNullability;
import java.util.Objects;
public class StaticChatType extends AbstractMappedEntity implements ChatType {
private final @UnknownNullability("only nullable for 1.19") ChatTypeDecoration chatDecoration;
private final @Nullable ChatTypeDecoration overlayDecoration;
private final @UnknownNullability("only nullable for 1.19") ChatTypeDecoration narrationDecoration;
private final @Nullable NarrationPriority narrationPriority;
public StaticChatType(
ChatTypeDecoration chatDecoration,
ChatTypeDecoration narrationDecoration
) {
this(null, chatDecoration, null, narrationDecoration, null);
}
@ApiStatus.Internal
public StaticChatType(
@Nullable TypesBuilderData data,
ChatTypeDecoration chatDecoration,
ChatTypeDecoration narrationDecoration
) {
this(data, chatDecoration, null, narrationDecoration, null);
}
public StaticChatType(
@UnknownNullability("only nullable for 1.19") ChatTypeDecoration chatDecoration,
@Nullable ChatTypeDecoration overlayDecoration,
@UnknownNullability("only nullable for 1.19") ChatTypeDecoration narrationDecoration,
@Nullable NarrationPriority narrationPriority
) {
this(null, chatDecoration, overlayDecoration, narrationDecoration, narrationPriority);
}
@ApiStatus.Internal
public StaticChatType(
@Nullable TypesBuilderData data,
@UnknownNullability("only nullable for 1.19") ChatTypeDecoration chatDecoration,
@Nullable ChatTypeDecoration overlayDecoration,
@UnknownNullability("only nullable for 1.19") ChatTypeDecoration narrationDecoration,
@Nullable NarrationPriority narrationPriority
) {
super(data);
this.chatDecoration = chatDecoration;
this.overlayDecoration = overlayDecoration;
this.narrationDecoration = narrationDecoration;
this.narrationPriority = narrationPriority;
}
@Override
public ChatType copy(@Nullable TypesBuilderData newData) {
return new StaticChatType(newData, this.chatDecoration,
this.overlayDecoration, this.narrationDecoration, this.narrationPriority);
}
@Override
public @UnknownNullability("only nullable for 1.19") ChatTypeDecoration getChatDecoration() {
return this.chatDecoration;
}
@Override
public @Nullable ChatTypeDecoration getOverlayDecoration() {
return this.overlayDecoration;
}
@Override
public @UnknownNullability("only nullable for 1.19") ChatTypeDecoration getNarrationDecoration() {
return this.narrationDecoration;
}
@Override
public @Nullable NarrationPriority getNarrationPriority() {
return this.narrationPriority;
}
@Override
public boolean deepEquals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof StaticChatType)) return false;
if (!super.equals(obj)) return false;
StaticChatType that = (StaticChatType) obj;
if (!Objects.equals(this.chatDecoration, that.chatDecoration)) return false;
if (!Objects.equals(this.overlayDecoration, that.overlayDecoration)) return false;
if (!Objects.equals(this.narrationDecoration, that.narrationDecoration)) return false;
return this.narrationPriority == that.narrationPriority;
}
@Override
public int deepHashCode() {
return Objects.hash(super.hashCode(), this.chatDecoration, this.overlayDecoration, this.narrationDecoration, this.narrationPriority);
}
@Override
public String toString() {
return "StaticChatType{chatDecoration=" + this.chatDecoration + ", overlayDecoration=" + this.overlayDecoration + ", narrationDecoration=" + this.narrationDecoration + ", narrationPriority=" + this.narrationPriority + '}';
}
}
@@ -24,9 +24,10 @@ import org.jetbrains.annotations.Nullable;
import java.time.Instant;
import java.util.UUID;
//We'll extend ChatMessage_v1_16 for now, hopefully no breaking changes in the future
public class ChatMessage_v1_19 extends ChatMessage_v1_16 {
public class ChatMessage_v1_19 extends ChatMessage {
private @Nullable Component unsignedChatContent;
private UUID senderUUID;
private Component senderDisplayName;
private @Nullable Component teamName;
private Instant timestamp;
@@ -36,8 +37,9 @@ public class ChatMessage_v1_19 extends ChatMessage_v1_16 {
public ChatMessage_v1_19(Component chatContent, @Nullable Component unsignedChatContent, ChatType type,
UUID senderUUID, Component senderDisplayName, @Nullable Component teamName, Instant timestamp,
long salt, byte[] signature) {
super(chatContent, type, senderUUID);
super(chatContent, type);
this.unsignedChatContent = unsignedChatContent;
this.senderUUID = senderUUID;
this.senderDisplayName = senderDisplayName;
this.teamName = teamName;
this.timestamp = timestamp;
@@ -49,6 +51,10 @@ public class ChatMessage_v1_19 extends ChatMessage_v1_16 {
return unsignedChatContent;
}
public UUID getSenderUUID() {
return senderUUID;
}
public Component getSenderDisplayName() {
return senderDisplayName;
}
@@ -73,6 +79,10 @@ public class ChatMessage_v1_19 extends ChatMessage_v1_16 {
this.unsignedChatContent = unsignedChatContent;
}
public void setSenderUUID(UUID senderUUID) {
this.senderUUID = senderUUID;
}
public void setSenderDisplayName(Component senderDisplayName) {
this.senderDisplayName = senderDisplayName;
}
@@ -26,11 +26,12 @@ import org.jetbrains.annotations.Nullable;
import java.time.Instant;
import java.util.UUID;
//We'll extend ChatMessage_v1_16 for now, hopefully no breaking changes in the future
public class ChatMessage_v1_19_1 extends ChatMessage_v1_16 {
public class ChatMessage_v1_19_1 extends ChatMessage {
private String plainContent;
private @Nullable Component unsignedChatContent;
private ChatType.Bound chatFormatting;
private UUID senderUUID;
private ChatTypeBoundNetwork chatType;
private byte @Nullable [] previousSignature;
private byte[] signature;
private Instant timestamp;
@@ -40,15 +41,16 @@ public class ChatMessage_v1_19_1 extends ChatMessage_v1_16 {
public ChatMessage_v1_19_1(String plainContent, Component decoratedChatContent,
@Nullable Component unsignedChatContent,
UUID senderUUID, ChatType.Bound chatFormatting,
UUID senderUUID, ChatTypeBoundNetwork chatType,
byte @Nullable [] previousSignature, byte[] signature,
Instant timestamp, long salt,
LastSeenMessages lastSeenMessages,
FilterMask filterMask) {
super(decoratedChatContent, chatFormatting.getType(), senderUUID);
super(decoratedChatContent, chatType.getType());
this.plainContent = plainContent;
this.unsignedChatContent = unsignedChatContent;
this.chatFormatting = chatFormatting;
this.senderUUID = senderUUID;
this.chatType = chatType;
this.previousSignature = previousSignature;
this.signature = signature;
this.timestamp = timestamp;
@@ -77,40 +79,30 @@ public class ChatMessage_v1_19_1 extends ChatMessage_v1_16 {
this.unsignedChatContent = unsignedChatContent;
}
public UUID getSenderUUID() {
return senderUUID;
}
public void setSenderUUID(UUID senderUUID) {
this.senderUUID = senderUUID;
}
@Override
public ChatType getType() {
return chatFormatting.getType();
return chatType.getType();
}
@Override
public void setType(ChatType type) {
chatFormatting.setType(type);
chatType.setType(type);
}
public ChatType.Bound getChatFormatting() {
return chatFormatting;
public ChatTypeBoundNetwork getChatType() {
return chatType;
}
public void setChatFormatting(ChatType.Bound chatFormatting) {
this.chatFormatting = chatFormatting;
}
/**
* Retrieves the chat formatting. Please refer to {@link ChatMessage_v1_19_1#getChatFormatting}
* @return chat formatting which contains the actual chat type.
*/
@Deprecated
public ChatType.Bound getChatType() {
return chatFormatting;
}
/**
* Sets the chat formatting. Please refer to {@link ChatMessage_v1_19_1#setChatFormatting}
* @param chatFormatting formatting which contains the actual chat type.
*/
@Deprecated
public void setChatType(ChatType.Bound chatFormatting) {
this.chatFormatting = chatFormatting;
public void setChatType(ChatTypeBoundNetwork type) {
this.chatType = type;
}
public byte @Nullable [] getPreviousSignature() {
@@ -161,10 +153,6 @@ public class ChatMessage_v1_19_1 extends ChatMessage_v1_16 {
this.filterMask = filterMask;
}
/**
* Please refer to {@link com.github.retrooper.packetevents.protocol.chat.ChatType.Bound}
*/
@Deprecated
public static class ChatTypeBoundNetwork {
private ChatType type;
private Component name;
@@ -1,138 +0,0 @@
package com.github.retrooper.packetevents.protocol.chat.message;
import com.github.retrooper.packetevents.protocol.chat.ChatType;
import com.github.retrooper.packetevents.protocol.chat.LastSeenMessages;
import com.github.retrooper.packetevents.protocol.chat.filter.FilterMask;
import com.github.retrooper.packetevents.util.adventure.AdventureSerializer;
import net.kyori.adventure.text.Component;
import org.jetbrains.annotations.Nullable;
import java.time.Instant;
import java.util.Optional;
import java.util.UUID;
public class ChatMessage_v1_19_3 extends ChatMessage_v1_16 {
int index;
byte[] signature;
String plainContent;
Instant timestamp;
long salt;
LastSeenMessages.Packed lastSeenMessagesPacked;
@Nullable Component unsignedChatContent;
FilterMask filterMask;
ChatType.Bound chatFormatting;
public ChatMessage_v1_19_3(UUID senderUUID, int index, byte[] signature, String plainContent, Instant timestamp, long salt, LastSeenMessages.Packed lastSeenMessagesPacked, @Nullable Component unsignedChatContent, FilterMask filterMask, ChatType.Bound chatFormatting) {
super(Component.text(plainContent), chatFormatting.getType(), senderUUID);
this.index = index;
this.signature = signature;
this.plainContent = plainContent;
this.timestamp = timestamp;
this.salt = salt;
this.lastSeenMessagesPacked = lastSeenMessagesPacked;
this.unsignedChatContent = unsignedChatContent;
this.filterMask = filterMask;
this.chatFormatting = chatFormatting;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public byte[] getSignature() {
return signature;
}
public void setSignature(byte[] signature) {
this.signature = signature;
}
@Override
public Component getChatContent() {
return Component.text(plainContent);
}
@Deprecated
@Override
public void setChatContent(Component chatContent) {
throw new UnsupportedOperationException("PacketEvents is not able to serialize components to plain-text. Please use the #setPlainContent instead to update the content.");
}
public String getPlainContent() {
return plainContent;
}
public void setPlainContent(String plainContent) {
this.plainContent = plainContent;
}
public Instant getTimestamp() {
return timestamp;
}
public void setTimestamp(Instant timestamp) {
this.timestamp = timestamp;
}
public long getSalt() {
return salt;
}
public void setSalt(long salt) {
this.salt = salt;
}
public LastSeenMessages.Packed getLastSeenMessagesPacked() {
return lastSeenMessagesPacked;
}
public void setLastSeenMessagesPacked(LastSeenMessages.Packed lastSeenMessagesPacked) {
this.lastSeenMessagesPacked = lastSeenMessagesPacked;
}
public Optional<Component> getUnsignedChatContent() {
return Optional.ofNullable(unsignedChatContent);
}
public void setUnsignedChatContent(@Nullable Component unsignedChatContent) {
this.unsignedChatContent = unsignedChatContent;
}
public FilterMask getFilterMask() {
return filterMask;
}
public void setFilterMask(FilterMask filterMask) {
this.filterMask = filterMask;
}
public ChatType.Bound getChatFormatting() {
return chatFormatting;
}
public void setChatFormatting(ChatType.Bound chatFormatting) {
this.chatFormatting = chatFormatting;
}
/**
* Retrieves the chat formatting. Please refer to {@link ChatMessage_v1_19_3#getChatFormatting}
* @return chat formatting which contains the actual chat type.
*/
@Deprecated
public ChatType.Bound getChatType() {
return chatFormatting;
}
/**
* Sets the chat formatting. Please refer to {@link ChatMessage_v1_19_3#setChatFormatting}
* @param chatFormatting formatting which contains the actual chat type.
*/
@Deprecated
public void setChatType(ChatType.Bound chatFormatting) {
this.chatFormatting = chatFormatting;
}
}
@@ -1,49 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2025 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.chat.message;
import com.github.retrooper.packetevents.protocol.chat.ChatType;
import com.github.retrooper.packetevents.protocol.chat.LastSeenMessages;
import com.github.retrooper.packetevents.protocol.chat.filter.FilterMask;
import net.kyori.adventure.text.Component;
import org.jetbrains.annotations.Nullable;
import java.time.Instant;
import java.util.UUID;
//We'll extend ChatMessage_v1_19_3 for now, hopefully no breaking changes in the future
public class ChatMessage_v1_21_5 extends ChatMessage_v1_19_3 {
int globalIndex;
public ChatMessage_v1_21_5(int globalIndex, UUID senderUUID, int index, byte[] signature, String plainContent,
Instant timestamp, long salt, LastSeenMessages.Packed lastSeenMessagesPacked, @Nullable Component unsignedChatContent,
FilterMask filterMask, ChatType.Bound chatFormatting) {
super(senderUUID, index, signature, plainContent, timestamp, salt, lastSeenMessagesPacked, unsignedChatContent, filterMask, chatFormatting);
this.globalIndex = globalIndex;
}
public int getGlobalIndex() {
return this.globalIndex;
}
public void setGlobalIndex(int globalIndex) {
this.globalIndex = globalIndex;
}
}
@@ -31,13 +31,14 @@ public class ChatMessageProcessorLegacy implements ChatMessageProcessor {
@Override
public ChatMessage readChatMessage(@NotNull PacketWrapper<?> wrapper) {
Component chatContent = wrapper.readComponent();
ChatType type = wrapper.readMappedEntity(ChatTypes.getRegistry());
int id = wrapper.readByte();
ChatType type = ChatTypes.getById(wrapper.getServerVersion().toClientVersion(), id);
return new ChatMessageLegacy(chatContent, type);
}
@Override
public void writeChatMessage(@NotNull PacketWrapper<?> wrapper, @NotNull ChatMessage data) {
wrapper.writeComponent(data.getChatContent());
wrapper.writeMappedEntity(data.getType());
wrapper.writeByte(data.getType().getId(wrapper.getServerVersion().toClientVersion()));
}
}
@@ -33,7 +33,8 @@ public class ChatMessageProcessor_v1_16 implements ChatMessageProcessor {
@Override
public ChatMessage readChatMessage(@NotNull PacketWrapper<?> wrapper) {
Component chatContent = wrapper.readComponent();
ChatType type = wrapper.readMappedEntity(ChatTypes.getRegistry());
int id = wrapper.readByte();
ChatType type = ChatTypes.getById(wrapper.getServerVersion().toClientVersion(), id);
UUID senderUUID = wrapper.readUUID();
return new ChatMessage_v1_16(chatContent, type, senderUUID);
}
@@ -41,7 +42,7 @@ public class ChatMessageProcessor_v1_16 implements ChatMessageProcessor {
@Override
public void writeChatMessage(@NotNull PacketWrapper<?> wrapper, @NotNull ChatMessage data) {
wrapper.writeComponent(data.getChatContent());
wrapper.writeMappedEntity(data.getType());
wrapper.writeByte(data.getType().getId(wrapper.getServerVersion().toClientVersion()));
wrapper.writeUUID(((ChatMessage_v1_16) data).getSenderUUID());
}
}
@@ -36,7 +36,8 @@ public class ChatMessageProcessor_v1_19 implements ChatMessageProcessor {
public ChatMessage readChatMessage(@NotNull PacketWrapper<?> wrapper) {
Component chatContent = wrapper.readComponent();
Component unsignedChatContent = wrapper.readOptional(PacketWrapper::readComponent);
ChatType type = wrapper.readMappedEntity(ChatTypes.getRegistry());
int id = wrapper.readVarInt();
ChatType type = ChatTypes.getById(wrapper.getServerVersion().toClientVersion(), id);
UUID senderUUID = wrapper.readUUID();
Component senderDisplayName = wrapper.readComponent();
@Nullable Component teamName = wrapper.readOptional(PacketWrapper::readComponent);
@@ -52,7 +53,7 @@ public class ChatMessageProcessor_v1_19 implements ChatMessageProcessor {
ChatMessage_v1_19 newData = (ChatMessage_v1_19) data;
wrapper.writeComponent(newData.getChatContent());
wrapper.writeOptional(newData.getUnsignedChatContent(), PacketWrapper::writeComponent);
wrapper.writeMappedEntity(newData.getType());
wrapper.writeVarInt(newData.getType().getId(wrapper.getServerVersion().toClientVersion()));
wrapper.writeUUID(newData.getSenderUUID());
wrapper.writeComponent(newData.getSenderDisplayName());
wrapper.writeOptional(newData.getTeamName(), PacketWrapper::writeComponent);
@@ -40,9 +40,7 @@ public class ChatMessageProcessor_v1_19_1 implements ChatMessageProcessor {
byte[] signature = wrapper.readByteArray();
String plainContent = wrapper.readString(256);
Component chatContent = wrapper.readOptional(PacketWrapper::readComponent);
if (chatContent == null && plainContent.isEmpty()) {
chatContent = Component.empty();
} else if (chatContent == null) {
if (chatContent == null) {
chatContent = Component.text(plainContent);
}
Instant timestamp = wrapper.readTimestamp();
@@ -50,8 +48,14 @@ public class ChatMessageProcessor_v1_19_1 implements ChatMessageProcessor {
LastSeenMessages lastSeenMessages = wrapper.readLastSeenMessages();
Component unsignedChatContent = wrapper.readOptional(PacketWrapper::readComponent);
FilterMask filterMask = wrapper.readFilterMask();
ChatType.Bound chatFormatting = wrapper.readChatTypeBoundNetwork();
return new ChatMessage_v1_19_1(plainContent, chatContent, unsignedChatContent, senderUUID, chatFormatting,
int id = wrapper.readVarInt();
ChatType type = ChatTypes.getById(wrapper.getServerVersion().toClientVersion(), id);
Component name = wrapper.readComponent();
Component targetName = wrapper.readOptional(PacketWrapper::readComponent);
ChatMessage_v1_19_1.ChatTypeBoundNetwork chatType = new ChatMessage_v1_19_1.ChatTypeBoundNetwork(type, name, targetName);
return new ChatMessage_v1_19_1(plainContent, chatContent, unsignedChatContent, senderUUID, chatType,
previousSignature, signature, timestamp, salt, lastSeenMessages, filterMask);
}
@@ -68,6 +72,8 @@ public class ChatMessageProcessor_v1_19_1 implements ChatMessageProcessor {
wrapper.writeLastSeenMessages(newData.getLastSeenMessages());
wrapper.writeOptional(newData.getUnsignedChatContent(), PacketWrapper::writeComponent);
wrapper.writeFilterMask(newData.getFilterMask());
wrapper.writeChatTypeBoundNetwork(newData.getChatFormatting());
wrapper.writeVarInt(newData.getChatType().getType().getId(wrapper.getServerVersion().toClientVersion()));
wrapper.writeComponent(newData.getChatType().getName());
wrapper.writeOptional(newData.getChatType().getTargetName(), PacketWrapper::writeComponent);
}
}
@@ -1,48 +0,0 @@
package com.github.retrooper.packetevents.protocol.chat.message.reader.impl;
import com.github.retrooper.packetevents.protocol.chat.ChatType;
import com.github.retrooper.packetevents.protocol.chat.LastSeenMessages;
import com.github.retrooper.packetevents.protocol.chat.filter.FilterMask;
import com.github.retrooper.packetevents.protocol.chat.message.ChatMessage;
import com.github.retrooper.packetevents.protocol.chat.message.ChatMessage_v1_19_1;
import com.github.retrooper.packetevents.protocol.chat.message.ChatMessage_v1_19_3;
import com.github.retrooper.packetevents.protocol.chat.message.reader.ChatMessageProcessor;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import net.kyori.adventure.text.Component;
import org.jetbrains.annotations.NotNull;
import java.time.Instant;
import java.util.UUID;
public class ChatMessageProcessor_v1_19_3 implements ChatMessageProcessor {
@Override
public ChatMessage readChatMessage(@NotNull PacketWrapper<?> wrapper) {
UUID senderUUID = wrapper.readUUID();
int index = wrapper.readVarInt();
byte[] signature = wrapper.readOptional((w) -> w.readBytes(256));
String plainContent = wrapper.readString(256);
Instant timestamp = wrapper.readTimestamp();
long salt = wrapper.readLong();
LastSeenMessages.Packed lastSeenMessagesPacked = wrapper.readLastSeenMessagesPacked();
Component unsignedChatContent = wrapper.readOptional(PacketWrapper::readComponent);
FilterMask filterMask = wrapper.readFilterMask();
ChatType.Bound chatType = wrapper.readChatTypeBoundNetwork();
return new ChatMessage_v1_19_3(senderUUID, index, signature, plainContent, timestamp, salt, lastSeenMessagesPacked, unsignedChatContent, filterMask, chatType);
}
@Override
public void writeChatMessage(@NotNull PacketWrapper<?> wrapper, @NotNull ChatMessage data) {
ChatMessage_v1_19_3 newData = (ChatMessage_v1_19_3) data;
wrapper.writeUUID(newData.getSenderUUID());
wrapper.writeVarInt(newData.getIndex());
wrapper.writeOptional(newData.getSignature(), PacketWrapper::writeBytes);
wrapper.writeString(newData.getPlainContent());
wrapper.writeTimestamp(newData.getTimestamp());
wrapper.writeLong(newData.getSalt());
wrapper.writeLastSeenMessagesPacked(newData.getLastSeenMessagesPacked());
wrapper.writeOptional(newData.getUnsignedChatContent().orElse(null), PacketWrapper::writeComponent);
wrapper.writeFilterMask(newData.getFilterMask());
wrapper.writeChatTypeBoundNetwork(newData.getChatFormatting());
}
}
@@ -1,68 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2025 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.chat.message.reader.impl;
import com.github.retrooper.packetevents.protocol.chat.ChatType;
import com.github.retrooper.packetevents.protocol.chat.LastSeenMessages;
import com.github.retrooper.packetevents.protocol.chat.filter.FilterMask;
import com.github.retrooper.packetevents.protocol.chat.message.ChatMessage;
import com.github.retrooper.packetevents.protocol.chat.message.ChatMessage_v1_21_5;
import com.github.retrooper.packetevents.protocol.chat.message.reader.ChatMessageProcessor;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import net.kyori.adventure.text.Component;
import org.jetbrains.annotations.NotNull;
import java.time.Instant;
import java.util.UUID;
public class ChatMessageProcessor_v1_21_5 implements ChatMessageProcessor {
@Override
public ChatMessage readChatMessage(@NotNull PacketWrapper<?> wrapper) {
int globalIndex = wrapper.readVarInt();
UUID senderUUID = wrapper.readUUID();
int index = wrapper.readVarInt();
byte[] signature = wrapper.readOptional((w) -> w.readBytes(256));
String plainContent = wrapper.readString(256);
Instant timestamp = wrapper.readTimestamp();
long salt = wrapper.readLong();
LastSeenMessages.Packed lastSeenMessagesPacked = wrapper.readLastSeenMessagesPacked();
Component unsignedChatContent = wrapper.readOptional(PacketWrapper::readComponent);
FilterMask filterMask = wrapper.readFilterMask();
ChatType.Bound chatType = wrapper.readChatTypeBoundNetwork();
return new ChatMessage_v1_21_5(globalIndex, senderUUID, index, signature, plainContent, timestamp, salt, lastSeenMessagesPacked, unsignedChatContent, filterMask, chatType);
}
@Override
public void writeChatMessage(@NotNull PacketWrapper<?> wrapper, @NotNull ChatMessage data) {
ChatMessage_v1_21_5 newData = (ChatMessage_v1_21_5) data;
wrapper.writeVarInt(newData.getGlobalIndex());
wrapper.writeUUID(newData.getSenderUUID());
wrapper.writeVarInt(newData.getIndex());
wrapper.writeOptional(newData.getSignature(), PacketWrapper::writeBytes);
wrapper.writeString(newData.getPlainContent());
wrapper.writeTimestamp(newData.getTimestamp());
wrapper.writeLong(newData.getSalt());
wrapper.writeLastSeenMessagesPacked(newData.getLastSeenMessagesPacked());
wrapper.writeOptional(newData.getUnsignedChatContent().orElse(null), PacketWrapper::writeComponent);
wrapper.writeFilterMask(newData.getFilterMask());
wrapper.writeChatTypeBoundNetwork(newData.getChatFormatting());
}
}
@@ -1,146 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2024 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.color;
import com.github.retrooper.packetevents.protocol.nbt.NBT;
import com.github.retrooper.packetevents.protocol.nbt.NBTFloat;
import com.github.retrooper.packetevents.protocol.nbt.NBTInt;
import com.github.retrooper.packetevents.protocol.nbt.NBTList;
import com.github.retrooper.packetevents.protocol.nbt.NBTNumber;
import com.github.retrooper.packetevents.protocol.nbt.NBTType;
import com.github.retrooper.packetevents.protocol.player.ClientVersion;
import com.github.retrooper.packetevents.util.MathUtil;
import org.jetbrains.annotations.Range;
public final class AlphaColor extends Color {
public static final AlphaColor WHITE = new AlphaColor(0xFFFFFFFF);
private final int alpha;
public AlphaColor(
@Range(from = 0L, to = 255L) int red,
@Range(from = 0L, to = 255L) int green,
@Range(from = 0L, to = 255L) int blue
) {
this(255, red, green, blue);
}
public AlphaColor(
@Range(from = 0L, to = 255L) int alpha,
@Range(from = 0L, to = 255L) int red,
@Range(from = 0L, to = 255L) int green,
@Range(from = 0L, to = 255L) int blue
) {
super(red, green, blue);
this.alpha = alpha;
}
public AlphaColor(
@Range(from = 0L, to = 1L) float red,
@Range(from = 0L, to = 1L) float green,
@Range(from = 0L, to = 1L) float blue
) {
this(1f, red, green, blue);
}
public AlphaColor(
@Range(from = 0L, to = 1L) float alpha,
@Range(from = 0L, to = 1L) float red,
@Range(from = 0L, to = 1L) float green,
@Range(from = 0L, to = 1L) float blue
) {
super(red, green, blue);
this.alpha = MathUtil.floor(alpha * 255f);
}
public AlphaColor(int rgb) {
this((rgb >> 24) & BIT_MASK,
(rgb >> 16) & BIT_MASK,
(rgb >> 8) & BIT_MASK,
rgb & BIT_MASK);
}
public static AlphaColor decode(NBT nbt, ClientVersion version) {
if (nbt instanceof NBTNumber) {
return new AlphaColor(((NBTNumber) nbt).getAsInt());
}
NBTList<?> list = (NBTList<?>) nbt;
float red = ((NBTNumber) list.getTag(0)).getAsFloat();
float green = ((NBTNumber) list.getTag(1)).getAsFloat();
float blue = ((NBTNumber) list.getTag(2)).getAsFloat();
float alpha = ((NBTNumber) list.getTag(3)).getAsFloat();
return new AlphaColor(alpha, red, green, blue);
}
public static NBT encode(AlphaColor color, ClientVersion version) {
if (version.isNewerThanOrEquals(ClientVersion.V_1_21_2)) {
return new NBTInt(color.asRGB());
}
NBTList<NBTFloat> list = new NBTList<>(NBTType.FLOAT, 4);
list.addTag(new NBTFloat(color.red));
list.addTag(new NBTFloat(color.green));
list.addTag(new NBTFloat(color.blue));
list.addTag(new NBTFloat(color.alpha));
return list;
}
public AlphaColor withAlpha(@Range(from = 0L, to = 255L) int alpha) {
return new AlphaColor(alpha, this.red, this.green, this.blue);
}
@Override
public AlphaColor withRed(@Range(from = 0L, to = 255L) int red) {
return new AlphaColor(this.alpha, red, this.green, this.blue);
}
@Override
public AlphaColor withGreen(@Range(from = 0L, to = 255L) int green) {
return new AlphaColor(this.alpha, this.red, green, this.blue);
}
@Override
public AlphaColor withBlue(@Range(from = 0L, to = 255L) int blue) {
return new AlphaColor(this.alpha, this.red, this.green, blue);
}
@Override
public int asRGB() {
return (this.alpha << 24) | (this.red << 16) | (this.green << 8) | this.blue;
}
public @Range(from = 0L, to = 255L) int alpha() {
return this.alpha;
}
@Override
public @Range(from = 0L, to = 255L) int red() {
return this.red;
}
@Override
public @Range(from = 0L, to = 255L) int green() {
return this.green;
}
@Override
public @Range(from = 0L, to = 255L) int blue() {
return this.blue;
}
}
@@ -1,120 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2024 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.color;
import com.github.retrooper.packetevents.protocol.nbt.NBT;
import com.github.retrooper.packetevents.protocol.nbt.NBTFloat;
import com.github.retrooper.packetevents.protocol.nbt.NBTInt;
import com.github.retrooper.packetevents.protocol.nbt.NBTList;
import com.github.retrooper.packetevents.protocol.nbt.NBTNumber;
import com.github.retrooper.packetevents.protocol.nbt.NBTType;
import com.github.retrooper.packetevents.protocol.player.ClientVersion;
import com.github.retrooper.packetevents.util.MathUtil;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import net.kyori.adventure.util.RGBLike;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Range;
public class Color implements RGBLike {
protected static final int BIT_MASK = 0xFF;
protected final int red, green, blue;
public Color(@Range(from = 0L, to = 255L) int red, @Range(from = 0L, to = 255L) int green, @Range(from = 0L, to = 255L) int blue) {
this.red = red;
this.green = green;
this.blue = blue;
}
public Color(
@Range(from = 0L, to = 1L) float red,
@Range(from = 0L, to = 1L) float green,
@Range(from = 0L, to = 1L) float blue
) {
this(MathUtil.floor(red * 255f),
MathUtil.floor(green * 255f),
MathUtil.floor(blue * 255f));
}
public Color(int rgb) {
this((rgb >> 16) & BIT_MASK, (rgb >> 8) & BIT_MASK, rgb & BIT_MASK);
}
public static Color read(PacketWrapper<?> wrapper) {
return new Color(wrapper.readInt());
}
public static void write(PacketWrapper<?> wrapper, Color color) {
wrapper.writeInt(color.asRGB());
}
public static Color decode(NBT nbt, ClientVersion version) {
if (nbt instanceof NBTNumber) {
return new Color(((NBTNumber) nbt).getAsInt());
}
NBTList<?> list = (NBTList<?>) nbt;
float red = ((NBTNumber) list.getTag(0)).getAsFloat();
float green = ((NBTNumber) list.getTag(1)).getAsFloat();
float blue = ((NBTNumber) list.getTag(2)).getAsFloat();
return new Color(red, green, blue);
}
public static NBT encode(Color color, ClientVersion version) {
if (version.isNewerThanOrEquals(ClientVersion.V_1_21_2)) {
return new NBTInt(color.asRGB());
}
NBTList<NBTFloat> list = new NBTList<>(NBTType.FLOAT, 3);
list.addTag(new NBTFloat(color.red));
list.addTag(new NBTFloat(color.green));
list.addTag(new NBTFloat(color.blue));
return list;
}
public @NotNull Color withRed(@Range(from = 0L, to = 255L) int red) {
return new Color(red, green, blue);
}
public @NotNull Color withGreen(@Range(from = 0L, to = 255L) int green) {
return new Color(red, green, blue);
}
public @NotNull Color withBlue(@Range(from = 0L, to = 255L) int blue) {
return new Color(red, green, blue);
}
public int asRGB() {
return (this.red << 16) | (this.green << 8) | this.blue;
}
@Override
public @Range(from = 0L, to = 255L) int red() {
return red;
}
@Override
public @Range(from = 0L, to = 255L) int green() {
return green;
}
@Override
public @Range(from = 0L, to = 255L) int blue() {
return blue;
}
}
@@ -1,114 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2024 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.color;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import net.kyori.adventure.util.RGBLike;
import org.jetbrains.annotations.NotNull;
public enum DyeColor implements RGBLike {
WHITE(new Color(0xf9fffe), new Color(0xffffff), new Color(0xf0f0f0), 8),
ORANGE(new Color(0xf9801d), new Color(0xff681f), new Color(0xeb8844), 15),
MAGENTA(new Color(0xc74ebd), new Color(0xff00ff), new Color(0xc354cd), 16),
LIGHT_BLUE(new Color(0x3ab3da), new Color(0x9ac0cd), new Color(0x6689d3), 17),
YELLOW(new Color(0xfed83d), new Color(0xffff00), new Color(0xdecf2a), 18),
LIME(new Color(0x80c71f), new Color(0xbfff00), new Color(0x41cd34), 19),
PINK(new Color(0xf38baa), new Color(0xff69b4), new Color(0xd88198), 20),
GRAY(new Color(0x474f52), new Color(0x808080), new Color(0x434343), 21),
LIGHT_GRAY(new Color(0x9d9d97), new Color(0xd3d3d3), new Color(0xababab), 22),
CYAN(new Color(0x169c9c), new Color(0xffff), new Color(0x287697), 23),
PURPLE(new Color(0x8932b8), new Color(0xa020f0), new Color(0x7b2fbe), 24),
BLUE(new Color(0x3c44aa), new Color(0xff), new Color(0x253192), 25),
BROWN(new Color(0x835432), new Color(0x8b4513), new Color(0x51301a), 26),
GREEN(new Color(0x5e7c16), new Color(0xff00), new Color(0x3b511a), 27),
RED(new Color(0xb02e26), new Color(0xff0000), new Color(0xb3312c), 28),
BLACK(new Color(0x1d1d21), new Color(0x0), new Color(0x1e1b1b), 29);
private static final DyeColor[] COLORS = values();
private final Color textureDiffuseColor;
private final Color textColor;
private final Color fireworkColor;
private final int mapColorId;
DyeColor(@NotNull Color textureDiffuseColor, @NotNull Color textColor,
@NotNull Color fireworkColor, int mapColorId) {
this.textureDiffuseColor = textureDiffuseColor;
this.textColor = textColor;
this.fireworkColor = fireworkColor;
this.mapColorId = mapColorId;
}
public static DyeColor read(PacketWrapper<?> wrapper) {
return wrapper.readEnum(COLORS);
}
public static void write(PacketWrapper<?> wrapper, DyeColor color) {
wrapper.writeEnum(color);
}
public @NotNull Color color() {
return this.textureDiffuseColor;
}
public @NotNull Color textColor() {
return this.textColor;
}
public @NotNull Color fireworkColor() {
return this.fireworkColor;
}
@Override
public int red() {
return this.textureDiffuseColor.red();
}
@Override
public int green() {
return this.textureDiffuseColor.green();
}
@Override
public int blue() {
return this.textureDiffuseColor.blue();
}
public int mapColorId() {
return this.mapColorId;
}
}
@@ -1,114 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2024 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.component;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Predicate;
public class ComponentPredicate implements Predicate<IComponentMap> {
private List<ComponentValue<?>> requiredComponents;
public ComponentPredicate() {
this(new ArrayList<>());
}
public ComponentPredicate(List<ComponentValue<?>> requiredComponents) {
this.requiredComponents = requiredComponents;
}
public static ComponentPredicate read(PacketWrapper<?> wrapper) {
List<ComponentValue<?>> components = wrapper.readList(ComponentValue::read);
return new ComponentPredicate(components);
}
public static void write(PacketWrapper<?> wrapper, ComponentPredicate predicate) {
wrapper.writeList(predicate.requiredComponents, ComponentValue::write);
}
public static ComponentPredicate emptyPredicate() {
return new ComponentPredicate(new ArrayList<>());
}
@SuppressWarnings("unchecked")
public static ComponentPredicate fromPatches(PatchableComponentMap components) {
Map<ComponentType<?>, Optional<?>> patches = components.getPatches();
List<ComponentValue<?>> values = new ArrayList<>(patches.size());
for (Map.Entry<ComponentType<?>, Optional<?>> patch : patches.entrySet()) {
if (patch.getValue().isPresent()) {
values.add(new ComponentValue<>(
(ComponentType<Object>) patch.getKey(),
patch.getValue().get()
));
}
}
return new ComponentPredicate(values);
}
public PatchableComponentMap asPatches(StaticComponentMap base) {
PatchableComponentMap patched = new PatchableComponentMap(base);
for (ComponentValue<?> component : this.requiredComponents) {
patched.set(component);
}
return patched;
}
@Override
public boolean test(IComponentMap components) {
for (ComponentValue<?> component : this.requiredComponents) {
Optional<?> value = components.getOptional(component.getType());
if (!value.isPresent() || !component.getValue().equals(value.get())) {
return false;
}
}
return true;
}
public List<ComponentValue<?>> getRequiredComponents() {
return this.requiredComponents;
}
public void setRequiredComponents(List<ComponentValue<?>> requiredComponents) {
this.requiredComponents = requiredComponents;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof ComponentPredicate)) return false;
ComponentPredicate that = (ComponentPredicate) obj;
return this.requiredComponents.equals(that.requiredComponents);
}
@Override
public int hashCode() {
return Objects.hashCode(this.requiredComponents);
}
@Override
public String toString() {
return "ComponentPredicate{requiredComponents=" + this.requiredComponents + '}';
}
}
@@ -1,51 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2024 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.component;
import com.github.retrooper.packetevents.protocol.mapper.MappedEntity;
import com.github.retrooper.packetevents.protocol.nbt.NBT;
import com.github.retrooper.packetevents.protocol.player.ClientVersion;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import org.jetbrains.annotations.ApiStatus;
import java.util.function.Function;
public interface ComponentType<T> extends MappedEntity {
T read(PacketWrapper<?> wrapper);
void write(PacketWrapper<?> wrapper, T content);
T decode(NBT nbt, ClientVersion version);
NBT encode(T value, ClientVersion version);
@ApiStatus.Internal
<Z> ComponentType<Z> legacyMap(Function<T, Z> mapper, Function<Z, T> unmapper);
interface Decoder<T> {
T decode(NBT nbt, ClientVersion version);
}
interface Encoder<T> {
NBT encode(T value, ClientVersion version);
}
}
@@ -1,487 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2024 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.component;
import com.github.retrooper.packetevents.protocol.color.DyeColor;
import com.github.retrooper.packetevents.protocol.component.builtin.AxolotlVariantComponent;
import com.github.retrooper.packetevents.protocol.component.builtin.CatCollarComponent;
import com.github.retrooper.packetevents.protocol.component.builtin.CatVariantComponent;
import com.github.retrooper.packetevents.protocol.component.builtin.ChickenVariantComponent;
import com.github.retrooper.packetevents.protocol.component.builtin.CowVariantComponent;
import com.github.retrooper.packetevents.protocol.component.builtin.FoxVariantComponent;
import com.github.retrooper.packetevents.protocol.component.builtin.FrogVariantComponent;
import com.github.retrooper.packetevents.protocol.component.builtin.HorseVariantComponent;
import com.github.retrooper.packetevents.protocol.component.builtin.LlamaVariantComponent;
import com.github.retrooper.packetevents.protocol.component.builtin.MooshroomVariantComponent;
import com.github.retrooper.packetevents.protocol.component.builtin.PaintingVariantComponent;
import com.github.retrooper.packetevents.protocol.component.builtin.ParrotVariantComponent;
import com.github.retrooper.packetevents.protocol.component.builtin.PigVariantComponent;
import com.github.retrooper.packetevents.protocol.component.builtin.RabbitVariantComponent;
import com.github.retrooper.packetevents.protocol.component.builtin.SalmonSizeComponent;
import com.github.retrooper.packetevents.protocol.component.builtin.SheepColorComponent;
import com.github.retrooper.packetevents.protocol.component.builtin.ShulkerColorComponent;
import com.github.retrooper.packetevents.protocol.component.builtin.TropicalFishBaseColorComponent;
import com.github.retrooper.packetevents.protocol.component.builtin.TropicalFishPatternColorComponent;
import com.github.retrooper.packetevents.protocol.component.builtin.TropicalFishPatternComponent;
import com.github.retrooper.packetevents.protocol.component.builtin.VillagerVariantComponent;
import com.github.retrooper.packetevents.protocol.component.builtin.WolfCollarComponent;
import com.github.retrooper.packetevents.protocol.component.builtin.WolfSoundVariantComponent;
import com.github.retrooper.packetevents.protocol.component.builtin.WolfVariantComponent;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ArmorTrim;
import com.github.retrooper.packetevents.protocol.component.builtin.item.BannerLayers;
import com.github.retrooper.packetevents.protocol.component.builtin.item.BundleContents;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ChargedProjectiles;
import com.github.retrooper.packetevents.protocol.component.builtin.item.CustomData;
import com.github.retrooper.packetevents.protocol.component.builtin.item.DebugStickState;
import com.github.retrooper.packetevents.protocol.component.builtin.item.FireworkExplosion;
import com.github.retrooper.packetevents.protocol.component.builtin.item.FoodProperties;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemAdventurePredicate;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemAttributeModifiers;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemBees;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemBlockStateProperties;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemBlocksAttacks;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemBreakSound;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemConsumable;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemContainerContents;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemContainerLoot;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemCustomModelData;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemDamageResistant;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemDeathProtection;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemDyeColor;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemEnchantable;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemEnchantments;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemEquippable;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemFireworks;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemInstrument;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemJukeboxPlayable;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemLock;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemLore;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemMapDecorations;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemMapPostProcessingState;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemModel;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemPotionContents;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemPotionDurationScale;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemProfile;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemProvidesBannerPatterns;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemProvidesTrimMaterial;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemRarity;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemRecipes;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemRepairable;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemTool;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemTooltipDisplay;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemTooltipStyle;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemUnbreakable;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemUseCooldown;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemUseRemainder;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemWeapon;
import com.github.retrooper.packetevents.protocol.component.builtin.item.LodestoneTracker;
import com.github.retrooper.packetevents.protocol.component.builtin.item.PotDecorations;
import com.github.retrooper.packetevents.protocol.component.builtin.item.SuspiciousStewEffects;
import com.github.retrooper.packetevents.protocol.component.builtin.item.WritableBookContent;
import com.github.retrooper.packetevents.protocol.component.builtin.item.WrittenBookContent;
import com.github.retrooper.packetevents.protocol.item.instrument.Instrument;
import com.github.retrooper.packetevents.protocol.mapper.MaybeMappedEntity;
import com.github.retrooper.packetevents.protocol.nbt.NBTCompound;
import com.github.retrooper.packetevents.protocol.player.ClientVersion;
import com.github.retrooper.packetevents.resources.ResourceLocation;
import com.github.retrooper.packetevents.util.Dummy;
import com.github.retrooper.packetevents.util.mappings.VersionedRegistry;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import com.github.retrooper.packetevents.wrapper.PacketWrapper.Reader;
import com.github.retrooper.packetevents.wrapper.PacketWrapper.Writer;
import net.kyori.adventure.text.Component;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
/**
* Contains all item data component types.
*
* @see EnchantEffectComponentTypes
*/
public final class ComponentTypes {
private static final VersionedRegistry<ComponentType<?>> REGISTRY = new VersionedRegistry<>("data_component_type");
private ComponentTypes() {
}
@ApiStatus.Internal
public static <T> ComponentType<T> define(String key) {
return define(key, null, null);
}
@ApiStatus.Internal
public static <T> ComponentType<T> define(String key, @Nullable Reader<T> reader, @Nullable Writer<T> writer) {
return REGISTRY.define(key, data -> new StaticComponentType<>(data, reader, writer));
}
public static VersionedRegistry<ComponentType<?>> getRegistry() {
return REGISTRY;
}
public static ComponentType<?> getByName(String name) {
return REGISTRY.getByName(name);
}
public static ComponentType<?> getById(ClientVersion version, int id) {
return REGISTRY.getById(version, id);
}
public static final ComponentType<NBTCompound> CUSTOM_DATA = define("custom_data",
// mojang wraps their "persistent" codec as a stream codec just here,
// so packetevents has to handle nbt strings
CustomData::read, CustomData::write);
public static final ComponentType<Integer> MAX_STACK_SIZE = define("max_stack_size",
PacketWrapper::readVarInt, PacketWrapper::writeVarInt);
public static final ComponentType<Integer> MAX_DAMAGE = define("max_damage",
PacketWrapper::readVarInt, PacketWrapper::writeVarInt);
public static final ComponentType<Integer> DAMAGE = define("damage",
PacketWrapper::readVarInt, PacketWrapper::writeVarInt);
public static final ComponentType<ItemUnbreakable> UNBREAKABLE_MODERN = define("unbreakable",
ItemUnbreakable::read, ItemUnbreakable::write);
/**
* Changed in 1.21.5
*/
@Deprecated
public static final ComponentType<Boolean> UNBREAKABLE = UNBREAKABLE_MODERN.legacyMap(
ItemUnbreakable::isShowInTooltip, ItemUnbreakable::new);
public static final ComponentType<Component> CUSTOM_NAME = define("custom_name",
PacketWrapper::readComponent, PacketWrapper::writeComponent);
public static final ComponentType<Component> ITEM_NAME = define("item_name",
PacketWrapper::readComponent, PacketWrapper::writeComponent);
public static final ComponentType<ItemLore> LORE = define("lore",
ItemLore::read, ItemLore::write);
public static final ComponentType<ItemRarity> RARITY = define("rarity",
wrapper -> wrapper.readEnum(ItemRarity.values()), PacketWrapper::writeEnum);
public static final ComponentType<ItemEnchantments> ENCHANTMENTS = define("enchantments",
ItemEnchantments::read, ItemEnchantments::write);
public static final ComponentType<ItemAdventurePredicate> CAN_PLACE_ON = define("can_place_on",
ItemAdventurePredicate::read, ItemAdventurePredicate::write);
public static final ComponentType<ItemAdventurePredicate> CAN_BREAK = define("can_break",
ItemAdventurePredicate::read, ItemAdventurePredicate::write);
public static final ComponentType<ItemAttributeModifiers> ATTRIBUTE_MODIFIERS = define("attribute_modifiers",
ItemAttributeModifiers::read, ItemAttributeModifiers::write);
public static final ComponentType<ItemCustomModelData> CUSTOM_MODEL_DATA_LISTS = define("custom_model_data",
ItemCustomModelData::read, ItemCustomModelData::write);
/**
* Rewritten in 1.21.4
*/
@Deprecated
public static final ComponentType<Integer> CUSTOM_MODEL_DATA = CUSTOM_MODEL_DATA_LISTS.legacyMap(
ItemCustomModelData::getLegacyId, ItemCustomModelData::new);
/**
* Removed with 1.21.5
*/
@ApiStatus.Obsolete
public static final ComponentType<Dummy> HIDE_ADDITIONAL_TOOLTIP = define("hide_additional_tooltip",
Dummy::dummyRead, Dummy::dummyWrite);
/**
* Removed with 1.21.5
*/
@ApiStatus.Obsolete
public static final ComponentType<Dummy> HIDE_TOOLTIP = define("hide_tooltip",
Dummy::dummyRead, Dummy::dummyWrite);
public static final ComponentType<Integer> REPAIR_COST = define("repair_cost",
PacketWrapper::readVarInt, PacketWrapper::writeVarInt);
public static final ComponentType<Dummy> CREATIVE_SLOT_LOCK = define("creative_slot_lock",
Dummy::dummyRead, Dummy::dummyWrite);
public static final ComponentType<Boolean> ENCHANTMENT_GLINT_OVERRIDE = define("enchantment_glint_override",
PacketWrapper::readBoolean, PacketWrapper::writeBoolean);
public static final ComponentType<Dummy> INTANGIBLE_PROJECTILE = define("intangible_projectile",
Dummy::dummyReadNbt, Dummy::dummyWriteNbt);
public static final ComponentType<FoodProperties> FOOD = define("food",
FoodProperties::read, FoodProperties::write);
/**
* Has been migrated to #DAMAGE_RESISTANT with 1.21.2.
*/
@ApiStatus.Obsolete
public static final ComponentType<Dummy> FIRE_RESISTANT = define("fire_resistant",
Dummy::dummyRead, Dummy::dummyWrite);
public static final ComponentType<ItemTool> TOOL = define("tool",
ItemTool::read, ItemTool::write);
public static final ComponentType<ItemEnchantments> STORED_ENCHANTMENTS = define("stored_enchantments",
ItemEnchantments::read, ItemEnchantments::write);
public static final ComponentType<ItemDyeColor> DYED_COLOR = define("dyed_color",
ItemDyeColor::read, ItemDyeColor::write);
public static final ComponentType<Integer> MAP_COLOR = define("map_color",
PacketWrapper::readInt, PacketWrapper::writeInt);
public static final ComponentType<Integer> MAP_ID = define("map_id",
PacketWrapper::readVarInt, PacketWrapper::writeVarInt);
public static final ComponentType<ItemMapDecorations> MAP_DECORATIONS = define("map_decorations",
ItemMapDecorations::read, ItemMapDecorations::write);
public static final ComponentType<ItemMapPostProcessingState> MAP_POST_PROCESSING = define("map_post_processing",
wrapper -> wrapper.readEnum(ItemMapPostProcessingState.values()), PacketWrapper::writeEnum);
public static final ComponentType<ChargedProjectiles> CHARGED_PROJECTILES = define("charged_projectiles",
ChargedProjectiles::read, ChargedProjectiles::write);
public static final ComponentType<BundleContents> BUNDLE_CONTENTS = define("bundle_contents",
BundleContents::read, BundleContents::write);
public static final ComponentType<ItemPotionContents> POTION_CONTENTS = define("potion_contents",
ItemPotionContents::read, ItemPotionContents::write);
public static final ComponentType<SuspiciousStewEffects> SUSPICIOUS_STEW_EFFECTS = define("suspicious_stew_effects",
SuspiciousStewEffects::read, SuspiciousStewEffects::write);
public static final ComponentType<WritableBookContent> WRITABLE_BOOK_CONTENT = define("writable_book_content",
WritableBookContent::read, WritableBookContent::write);
public static final ComponentType<WrittenBookContent> WRITTEN_BOOK_CONTENT = define("written_book_content",
WrittenBookContent::read, WrittenBookContent::write);
public static final ComponentType<ArmorTrim> TRIM = define("trim",
ArmorTrim::read, ArmorTrim::write);
public static final ComponentType<DebugStickState> DEBUG_STICK_STATE = define("debug_stick_state",
DebugStickState::read, DebugStickState::write);
public static final ComponentType<NBTCompound> ENTITY_DATA = define("entity_data",
PacketWrapper::readNBT, PacketWrapper::writeNBT);
public static final ComponentType<NBTCompound> BUCKET_ENTITY_DATA = define("bucket_entity_data",
PacketWrapper::readNBT, PacketWrapper::writeNBT);
public static final ComponentType<NBTCompound> BLOCK_ENTITY_DATA = define("block_entity_data",
PacketWrapper::readNBT, PacketWrapper::writeNBT);
public static final ComponentType<ItemInstrument> ITEM_INSTRUMENT = define("instrument",
ItemInstrument::read, ItemInstrument::write);
@Deprecated
public static final ComponentType<Instrument> INSTRUMENT = ITEM_INSTRUMENT.legacyMap(
inst -> inst.getInstrument().getValue(),
inst -> new ItemInstrument(new MaybeMappedEntity<>(inst)));
public static final ComponentType<Integer> OMINOUS_BOTTLE_AMPLIFIER = define("ominous_bottle_amplifier",
PacketWrapper::readVarInt, PacketWrapper::writeVarInt);
public static final ComponentType<ItemRecipes> RECIPES = define("recipes",
ItemRecipes::read, ItemRecipes::write);
public static final ComponentType<LodestoneTracker> LODESTONE_TRACKER = define("lodestone_tracker",
LodestoneTracker::read, LodestoneTracker::write);
public static final ComponentType<FireworkExplosion> FIREWORK_EXPLOSION = define("firework_explosion",
FireworkExplosion::read, FireworkExplosion::write);
public static final ComponentType<ItemFireworks> FIREWORKS = define("fireworks",
ItemFireworks::read, ItemFireworks::write);
public static final ComponentType<ItemProfile> PROFILE = define("profile",
ItemProfile::read, ItemProfile::write);
public static final ComponentType<ResourceLocation> NOTE_BLOCK_SOUND = define("note_block_sound",
PacketWrapper::readIdentifier, PacketWrapper::writeIdentifier);
public static final ComponentType<BannerLayers> BANNER_PATTERNS = define("banner_patterns",
BannerLayers::read, BannerLayers::write);
public static final ComponentType<DyeColor> BASE_COLOR = define("base_color",
wrapper -> wrapper.readEnum(DyeColor.values()), PacketWrapper::writeEnum);
public static final ComponentType<PotDecorations> POT_DECORATIONS = define("pot_decorations",
PotDecorations::read, PotDecorations::write);
public static final ComponentType<ItemContainerContents> CONTAINER = define("container",
ItemContainerContents::read, ItemContainerContents::write);
public static final ComponentType<ItemBlockStateProperties> BLOCK_STATE = define("block_state",
ItemBlockStateProperties::read, ItemBlockStateProperties::write);
public static final ComponentType<ItemBees> BEES = define("bees",
ItemBees::read, ItemBees::write);
public static final ComponentType<ItemLock> LOCK = define("lock",
ItemLock::read, ItemLock::write);
public static final ComponentType<ItemContainerLoot> CONTAINER_LOOT = define("container_loot",
ItemContainerLoot::read, ItemContainerLoot::write);
// added in 1.21
public static final ComponentType<ItemJukeboxPlayable> JUKEBOX_PLAYABLE = define("jukebox_playable",
ItemJukeboxPlayable::read, ItemJukeboxPlayable::write);
// added in 1.21.2
public static final ComponentType<ItemConsumable> CONSUMABLE = define("consumable",
ItemConsumable::read, ItemConsumable::write);
public static final ComponentType<ItemUseRemainder> USE_REMAINDER = define("use_remainder",
ItemUseRemainder::read, ItemUseRemainder::write);
public static final ComponentType<ItemUseCooldown> USE_COOLDOWN = define("use_cooldown",
ItemUseCooldown::read, ItemUseCooldown::write);
public static final ComponentType<ItemEnchantable> ENCHANTABLE = define("enchantable",
ItemEnchantable::read, ItemEnchantable::write);
public static final ComponentType<ItemRepairable> REPAIRABLE = define("repairable",
ItemRepairable::read, ItemRepairable::write);
public static final ComponentType<ItemModel> ITEM_MODEL = define("item_model",
ItemModel::read, ItemModel::write);
public static final ComponentType<ItemDamageResistant> DAMAGE_RESISTANT = define("damage_resistant",
ItemDamageResistant::read, ItemDamageResistant::write);
public static final ComponentType<ItemEquippable> EQUIPPABLE = define("equippable",
ItemEquippable::read, ItemEquippable::write);
public static final ComponentType<Dummy> GLIDER = define("glider",
Dummy::dummyRead, Dummy::dummyWrite);
public static final ComponentType<ItemDeathProtection> DEATH_PROTECTION = define("death_protection",
ItemDeathProtection::read, ItemDeathProtection::write);
public static final ComponentType<ItemTooltipStyle> TOOLTIP_STYLE = define("tooltip_style",
ItemTooltipStyle::read, ItemTooltipStyle::write);
/**
* Added with 1.21.5
*/
public static final ComponentType<ItemTooltipDisplay> TOOLTIP_DISPLAY = define("tooltip_display",
ItemTooltipDisplay::read, ItemTooltipDisplay::write);
/**
* Added with 1.21.5
*/
public static final ComponentType<ItemWeapon> WEAPON = define("weapon",
ItemWeapon::read, ItemWeapon::write);
/**
* Added with 1.21.5
*/
public static final ComponentType<ItemBlocksAttacks> BLOCKS_ATTACKS = define("blocks_attacks",
ItemBlocksAttacks::read, ItemBlocksAttacks::write);
/**
* Added with 1.21.5
*/
public static final ComponentType<ItemPotionDurationScale> POTION_DURATION_SCALE = define("potion_duration_scale",
ItemPotionDurationScale::read, ItemPotionDurationScale::write);
/**
* Added with 1.21.5
*/
public static final ComponentType<ItemProvidesTrimMaterial> PROVIDES_TRIM_MATERIAL = define("provides_trim_material",
ItemProvidesTrimMaterial::read, ItemProvidesTrimMaterial::write);
/**
* Added with 1.21.5
*/
public static final ComponentType<ItemProvidesBannerPatterns> PROVIDES_BANNER_PATTERNS = define("provides_banner_patterns",
ItemProvidesBannerPatterns::read, ItemProvidesBannerPatterns::write);
/**
* Added with 1.21.5
*/
public static final ComponentType<ItemBreakSound> BREAK_SOUND = define("break_sound",
ItemBreakSound::read, ItemBreakSound::write);
/**
* Added with 1.21.5
*/
public static final ComponentType<VillagerVariantComponent> VILLAGER_VARIANT = define("villager/variant",
VillagerVariantComponent::read, VillagerVariantComponent::write);
/**
* Added with 1.21.5
*/
public static final ComponentType<WolfVariantComponent> WOLF_VARIANT = define("wolf/variant",
WolfVariantComponent::read, WolfVariantComponent::write);
/**
* Added with 1.21.5
*/
public static final ComponentType<WolfSoundVariantComponent> WOLF_SOUND_VARIANT = define("wolf/sound_variant",
WolfSoundVariantComponent::read, WolfSoundVariantComponent::write);
/**
* Added with 1.21.5
*/
public static final ComponentType<WolfCollarComponent> WOLF_COLLAR = define("wolf/collar",
WolfCollarComponent::read, WolfCollarComponent::write);
/**
* Added with 1.21.5
*/
public static final ComponentType<FoxVariantComponent> FOX_VARIANT = define("fox/variant",
FoxVariantComponent::read, FoxVariantComponent::write);
/**
* Added with 1.21.5
*/
public static final ComponentType<SalmonSizeComponent> SALMON_SIZE = define("salmon/size",
SalmonSizeComponent::read, SalmonSizeComponent::write);
/**
* Added with 1.21.5
*/
public static final ComponentType<ParrotVariantComponent> PARROT_VARIANT = define("parrot/variant",
ParrotVariantComponent::read, ParrotVariantComponent::write);
/**
* Added with 1.21.5
*/
public static final ComponentType<TropicalFishPatternComponent> TROPICAL_FISH_PATTERN = define("tropical_fish/pattern",
TropicalFishPatternComponent::read, TropicalFishPatternComponent::write);
/**
* Added with 1.21.5
*/
public static final ComponentType<TropicalFishBaseColorComponent> TROPICAL_FISH_BASE_COLOR = define("tropical_fish/base_color",
TropicalFishBaseColorComponent::read, TropicalFishBaseColorComponent::write);
/**
* Added with 1.21.5
*/
public static final ComponentType<TropicalFishPatternColorComponent> TROPICAL_FISH_PATTERN_COLOR = define("tropical_fish/pattern_color",
TropicalFishPatternColorComponent::read, TropicalFishPatternColorComponent::write);
/**
* Added with 1.21.5
*/
public static final ComponentType<MooshroomVariantComponent> MOOSHROOM_VARIANT = define("mooshroom/variant",
MooshroomVariantComponent::read, MooshroomVariantComponent::write);
/**
* Added with 1.21.5
*/
public static final ComponentType<RabbitVariantComponent> RABBIT_VARIANT = define("rabbit/variant",
RabbitVariantComponent::read, RabbitVariantComponent::write);
/**
* Added with 1.21.5
*/
public static final ComponentType<PigVariantComponent> PIG_VARIANT = define("pig/variant",
PigVariantComponent::read, PigVariantComponent::write);
/**
* Added with 1.21.5
*/
public static final ComponentType<CowVariantComponent> COW_VARIANT = define("cow/variant",
CowVariantComponent::read, CowVariantComponent::write);
/**
* Added with 1.21.5
*/
public static final ComponentType<ChickenVariantComponent> CHICKEN_VARIANT = define("chicken/variant",
ChickenVariantComponent::read, ChickenVariantComponent::write);
/**
* Added with 1.21.5
*/
public static final ComponentType<FrogVariantComponent> FROG_VARIANT = define("frog/variant",
FrogVariantComponent::read, FrogVariantComponent::write);
/**
* Added with 1.21.5
*/
public static final ComponentType<HorseVariantComponent> HORSE_VARIANT = define("horse/variant",
HorseVariantComponent::read, HorseVariantComponent::write);
/**
* Added with 1.21.5
*/
public static final ComponentType<PaintingVariantComponent> PAINTING_VARIANT = define("painting/variant",
PaintingVariantComponent::read, PaintingVariantComponent::write);
/**
* Added with 1.21.5
*/
public static final ComponentType<LlamaVariantComponent> LLAMA_VARIANT = define("llama/variant",
LlamaVariantComponent::read, LlamaVariantComponent::write);
/**
* Added with 1.21.5
*/
public static final ComponentType<AxolotlVariantComponent> AXOLOTL_VARIANT = define("axolotl/variant",
AxolotlVariantComponent::read, AxolotlVariantComponent::write);
/**
* Added with 1.21.5
*/
public static final ComponentType<CatVariantComponent> CAT_VARIANT = define("cat/variant",
CatVariantComponent::read, CatVariantComponent::write);
/**
* Added with 1.21.5
*/
public static final ComponentType<CatCollarComponent> CAT_COLLAR = define("cat/collar",
CatCollarComponent::read, CatCollarComponent::write);
/**
* Added with 1.21.5
*/
public static final ComponentType<SheepColorComponent> SHEEP_COLOR = define("sheep/color",
SheepColorComponent::read, SheepColorComponent::write);
/**
* Added with 1.21.5
*/
public static final ComponentType<ShulkerColorComponent> SHULKER_COLOR = define("shulker/color",
ShulkerColorComponent::read, ShulkerColorComponent::write);
/**
* Returns an immutable view of the component types.
*
* @return Component Types
*/
public static Collection<ComponentType<?>> values() {
return REGISTRY.getEntries();
}
static {
REGISTRY.unloadMappings();
}
}
@@ -1,76 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2024 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.component;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import java.util.Objects;
public final class ComponentValue<T> {
private final ComponentType<T> type;
private final T value;
public ComponentValue(ComponentType<T> type, T value) {
this.type = type;
this.value = value;
}
public static ComponentValue<?> read(PacketWrapper<?> wrapper) {
ComponentType<?> type = wrapper.readMappedEntity(ComponentTypes::getById);
return read0(wrapper, type);
}
private static <T> ComponentValue<T> read0(PacketWrapper<?> wrapper, ComponentType<T> type) {
// additional method required here for proper handling because of how generics work
return new ComponentValue<>(type, type.read(wrapper));
}
public static <T> void write(PacketWrapper<?> wrapper, ComponentValue<T> value) {
wrapper.writeMappedEntity(value.type);
value.type.write(wrapper, value.value);
}
public ComponentType<T> getType() {
return this.type;
}
public T getValue() {
return this.value;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof ComponentValue)) return false;
ComponentValue<?> that = (ComponentValue<?>) obj;
if (!this.type.equals(that.type)) return false;
return this.value.equals(that.value);
}
@Override
public int hashCode() {
return Objects.hash(this.type, this.value);
}
@Override
public String toString() {
return "ComponentValue{type=" + this.type + ", value=" + this.value + '}';
}
}
@@ -1,119 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2024 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.component;
import com.github.retrooper.packetevents.protocol.component.ComponentType.Decoder;
import com.github.retrooper.packetevents.protocol.component.ComponentType.Encoder;
import com.github.retrooper.packetevents.protocol.nbt.NBT;
import com.github.retrooper.packetevents.util.mappings.VersionedRegistry;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
/**
* Contains all enchantment effect component types.
*
* @see ComponentTypes
*/
public final class EnchantEffectComponentTypes {
private static final VersionedRegistry<ComponentType<?>> REGISTRY = new VersionedRegistry<>("enchantment_effect_component_type");
private EnchantEffectComponentTypes() {
}
@ApiStatus.Internal
public static <T> ComponentType<T> define(String key) {
return define(key, null, null);
}
@ApiStatus.Internal
public static <T> ComponentType<T> define(String key, @Nullable Decoder<T> reader, @Nullable Encoder<T> writer) {
return REGISTRY.define(key, data -> new StaticComponentType<>(data, reader, writer));
}
public static VersionedRegistry<ComponentType<?>> getRegistry() {
return REGISTRY;
}
// just pass everything through for now
public static ComponentType<NBT> DAMAGE_PROTECTION = define("damage_protection",
(nbt, version) -> nbt, (val, version) -> val);
public static ComponentType<NBT> DAMAGE_IMMUNITY = define("damage_immunity",
(nbt, version) -> nbt, (val, version) -> val);
public static ComponentType<NBT> DAMAGE = define("damage",
(nbt, version) -> nbt, (val, version) -> val);
public static ComponentType<NBT> SMASH_DAMAGE_PER_FALLEN_BLOCK = define("smash_damage_per_fallen_block",
(nbt, version) -> nbt, (val, version) -> val);
public static ComponentType<NBT> KNOCKBACK = define("knockback",
(nbt, version) -> nbt, (val, version) -> val);
public static ComponentType<NBT> ARMOR_EFFECTIVENESS = define("armor_effectiveness",
(nbt, version) -> nbt, (val, version) -> val);
public static ComponentType<NBT> POST_ATTACK = define("post_attack",
(nbt, version) -> nbt, (val, version) -> val);
public static ComponentType<NBT> HIT_BLOCK = define("hit_block",
(nbt, version) -> nbt, (val, version) -> val);
public static ComponentType<NBT> ITEM_DAMAGE = define("item_damage",
(nbt, version) -> nbt, (val, version) -> val);
public static ComponentType<NBT> ATTRIBUTES = define("attributes",
(nbt, version) -> nbt, (val, version) -> val);
public static ComponentType<NBT> EQUIPMENT_DROPS = define("equipment_drops",
(nbt, version) -> nbt, (val, version) -> val);
public static ComponentType<NBT> LOCATION_CHANGED = define("location_changed",
(nbt, version) -> nbt, (val, version) -> val);
public static ComponentType<NBT> TICK = define("tick",
(nbt, version) -> nbt, (val, version) -> val);
public static ComponentType<NBT> AMMO_USE = define("ammo_use",
(nbt, version) -> nbt, (val, version) -> val);
public static ComponentType<NBT> PROJECTILE_PIERCING = define("projectile_piercing",
(nbt, version) -> nbt, (val, version) -> val);
public static ComponentType<NBT> PROJECTILE_SPAWNED = define("projectile_spawned",
(nbt, version) -> nbt, (val, version) -> val);
public static ComponentType<NBT> PROJECTILE_SPREAD = define("projectile_spread",
(nbt, version) -> nbt, (val, version) -> val);
public static ComponentType<NBT> PROJECTILE_COUNT = define("projectile_count",
(nbt, version) -> nbt, (val, version) -> val);
public static ComponentType<NBT> TRIDENT_RETURN_ACCELERATION = define("trident_return_acceleration",
(nbt, version) -> nbt, (val, version) -> val);
public static ComponentType<NBT> FISHING_TIME_REDUCTION = define("fishing_time_reduction",
(nbt, version) -> nbt, (val, version) -> val);
public static ComponentType<NBT> FISHING_LUCK_BONUS = define("fishing_luck_bonus",
(nbt, version) -> nbt, (val, version) -> val);
public static ComponentType<NBT> BLOCK_EXPERIENCE = define("block_experience",
(nbt, version) -> nbt, (val, version) -> val);
public static ComponentType<NBT> MOB_EXPERIENCE = define("mob_experience",
(nbt, version) -> nbt, (val, version) -> val);
public static ComponentType<NBT> REPAIR_WITH_XP = define("repair_with_xp",
(nbt, version) -> nbt, (val, version) -> val);
public static ComponentType<NBT> CROSSBOW_CHARGE_TIME = define("crossbow_charge_time",
(nbt, version) -> nbt, (val, version) -> val);
public static ComponentType<NBT> CROSSBOW_CHARGING_SOUNDS = define("crossbow_charging_sounds",
(nbt, version) -> nbt, (val, version) -> val);
public static ComponentType<NBT> TRIDENT_SOUND = define("trident_sound",
(nbt, version) -> nbt, (val, version) -> val);
public static ComponentType<NBT> PREVENT_EQUIPMENT_DROP = define("prevent_equipment_drop",
(nbt, version) -> nbt, (val, version) -> val);
public static ComponentType<NBT> PREVENT_ARMOR_CHANGE = define("prevent_armor_change",
(nbt, version) -> nbt, (val, version) -> val);
public static ComponentType<NBT> TRIDENT_SPIN_ATTACK_STRENGTH = define("trident_spin_attack_strength",
(nbt, version) -> nbt, (val, version) -> val);
static {
REGISTRY.unloadMappings();
}
}
@@ -1,57 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2025 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.component;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public final class HashedComponentPatchMap {
private final Map<ComponentType<?>, Integer> addedComponents;
private final Set<ComponentType<?>> removedComponents;
public HashedComponentPatchMap(Map<ComponentType<?>, Integer> addedComponents, Set<ComponentType<?>> removedComponents) {
this.addedComponents = addedComponents;
this.removedComponents = removedComponents;
}
public static HashedComponentPatchMap read(PacketWrapper<?> wrapper) {
Map<ComponentType<?>, Integer> addedComponents = wrapper.readMap(ew ->
ew.readMappedEntity(ComponentTypes.getRegistry()), PacketWrapper::readInt);
Set<ComponentType<?>> removedComponents = wrapper.readCollection(HashSet::new, ew ->
ew.readMappedEntity(ComponentTypes.getRegistry()));
return new HashedComponentPatchMap(addedComponents, removedComponents);
}
public static void write(PacketWrapper<?> wrapper, HashedComponentPatchMap map) {
wrapper.writeMap(map.addedComponents, PacketWrapper::writeMappedEntity, PacketWrapper::writeInt);
wrapper.writeCollection(map.removedComponents, PacketWrapper::writeMappedEntity);
}
public Map<ComponentType<?>, Integer> getAddedComponents() {
return this.addedComponents;
}
public Set<ComponentType<?>> getRemovedComponents() {
return this.removedComponents;
}
}
@@ -1,89 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2024 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.component;
import com.github.retrooper.packetevents.protocol.nbt.NBT;
import com.github.retrooper.packetevents.protocol.nbt.NBTCompound;
import com.github.retrooper.packetevents.protocol.player.ClientVersion;
import com.github.retrooper.packetevents.util.mappings.IRegistry;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.Nullable;
import java.util.Map;
import java.util.Optional;
public interface IComponentMap {
@SuppressWarnings("unchecked") // safe in this case
static StaticComponentMap decode(NBT nbt, ClientVersion version, IRegistry<? extends ComponentType<?>> registry) {
NBTCompound compound = (NBTCompound) nbt;
StaticComponentMap.Builder components = StaticComponentMap.builder();
for (Map.Entry<String, NBT> entry : compound.getTags().entrySet()) {
ComponentType<?> type = registry.getByName(entry.getKey());
if (type == null) {
throw new IllegalStateException("Unknown component type named " + entry.getKey() + " encountered");
}
Object value = type.decode(entry.getValue(), version);
components.set((ComponentType<? super Object>) type, value);
}
return components.build();
}
@SuppressWarnings("unchecked") // safe in this case
static NBT encode(StaticComponentMap components, ClientVersion version) {
NBTCompound compound = new NBTCompound();
for (Map.Entry<ComponentType<?>, ?> entry : components.getDelegate().entrySet()) {
String key = entry.getKey().getName().toString();
NBT value = ((ComponentType<? super Object>) entry.getKey()).encode(entry.getValue(), version);
compound.setTag(key, value);
}
return compound;
}
default <T> Optional<T> getOptional(ComponentType<T> type) {
return Optional.ofNullable(this.get(type));
}
boolean has(ComponentType<?> type);
@Contract("_, !null -> !null")
default <T> @Nullable T getOr(ComponentType<T> type, @Nullable T otherValue) {
T value = this.get(type);
if (value != null) {
return value;
}
return otherValue;
}
<T> @Nullable T get(ComponentType<T> type);
default <T> void set(ComponentValue<T> component) {
this.set(component.getType(), component.getValue());
}
default <T> void set(ComponentType<T> type, @Nullable T value) {
this.set(type, Optional.ofNullable(value));
}
default <T> void unset(ComponentType<T> type) {
this.set(type, Optional.empty());
}
<T> void set(ComponentType<T> type, Optional<T> value);
}
@@ -1,117 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2024 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.component;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
public class PatchableComponentMap implements IComponentMap {
public static final PatchableComponentMap EMPTY = new PatchableComponentMap(
Collections.emptyMap(), Collections.emptyMap());
private final Map<ComponentType<?>, ?> base;
private final Map<ComponentType<?>, Optional<?>> patches;
public PatchableComponentMap(StaticComponentMap base) {
this(base.getDelegate(), new HashMap<>());
}
public PatchableComponentMap(Map<ComponentType<?>, ?> base) {
this(base, new HashMap<>());
}
public PatchableComponentMap(
StaticComponentMap base,
Map<ComponentType<?>, Optional<?>> patches
) {
this(base.getDelegate(), patches);
}
public PatchableComponentMap(
Map<ComponentType<?>, ?> base,
Map<ComponentType<?>, Optional<?>> patches
) {
this.base = Collections.unmodifiableMap(new HashMap<>(base));
this.patches = patches;
}
@SuppressWarnings("unchecked") // no
@Override
public <T> @Nullable T get(ComponentType<T> type) {
Optional<?> patched = this.patches.get(type);
if (patched != null) {
return (T) patched.orElse(null);
}
return (T) this.base.get(type);
}
@Override
public <T> void set(ComponentType<T> type, Optional<T> value) {
Object baseVal = this.base.get(type);
T newVal = value.orElse(null);
if (Objects.equals(baseVal, newVal)) {
this.patches.remove(type); // fallback to base
} else {
this.patches.put(type, value);
}
}
@Override
public boolean has(ComponentType<?> type) {
Optional<?> patched = this.patches.get(type);
return patched != null ? patched.isPresent() : this.base.containsKey(type);
}
public PatchableComponentMap copy() {
return new PatchableComponentMap(this.base, new HashMap<>(this.patches));
}
public Map<ComponentType<?>, ?> getBase() {
return this.base;
}
public Map<ComponentType<?>, Optional<?>> getPatches() {
return this.patches;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof PatchableComponentMap)) return false;
PatchableComponentMap that = (PatchableComponentMap) obj;
if (!this.base.equals(that.base)) return false;
return this.patches.equals(that.patches);
}
@Override
public int hashCode() {
return Objects.hash(this.base, this.patches);
}
@Override
public String toString() {
return "PatchableComponentMap{base=" + this.base + ", patches=" + this.patches + '}';
}
}
@@ -1,147 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2024 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.component;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemAttributeModifiers;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemEnchantments;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemLore;
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemRarity;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
public class StaticComponentMap implements IComponentMap {
public static final StaticComponentMap EMPTY = new StaticComponentMap(Collections.emptyMap());
@ApiStatus.Obsolete
public static final StaticComponentMap SHARED_ITEM_COMPONENTS = builder()
.set(ComponentTypes.MAX_STACK_SIZE, 64)
.set(ComponentTypes.LORE, ItemLore.EMPTY)
.set(ComponentTypes.ENCHANTMENTS, ItemEnchantments.EMPTY)
.set(ComponentTypes.REPAIR_COST, 0)
.set(ComponentTypes.ATTRIBUTE_MODIFIERS, ItemAttributeModifiers.EMPTY)
.set(ComponentTypes.RARITY, ItemRarity.COMMON)
.build();
private final boolean empty;
private final Map<ComponentType<?>, ?> delegate;
public StaticComponentMap(Map<ComponentType<?>, ?> delegate) {
this.empty = delegate.isEmpty();
this.delegate = this.empty ? Collections.emptyMap()
: Collections.unmodifiableMap(new HashMap<>(delegate));
}
public static Builder builder() {
return new Builder();
}
@Override
public boolean has(ComponentType<?> type) {
return !this.empty && this.delegate.containsKey(type);
}
@SuppressWarnings("unchecked") // no
@Override
public <T> @Nullable T get(ComponentType<T> type) {
return this.empty ? null : (T) this.delegate.get(type);
}
@Override
public <T> void set(ComponentType<T> type, Optional<T> value) {
throw new UnsupportedOperationException();
}
public StaticComponentMap merge(StaticComponentMap prioritizedMap) {
return builder().setAll(this).setAll(prioritizedMap).build();
}
public Map<ComponentType<?>, ?> getDelegate() {
return this.delegate;
}
public boolean isEmpty() {
return this.empty;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof StaticComponentMap)) return false;
StaticComponentMap that = (StaticComponentMap) obj;
return this.delegate.equals(that.delegate);
}
@Override
public int hashCode() {
return Objects.hashCode(this.delegate);
}
@Override
public String toString() {
return "Components" + this.delegate;
}
public static class Builder {
private final Map<ComponentType<?>, Object> map = new HashMap<>();
public Builder() {
}
public StaticComponentMap build() {
return new StaticComponentMap(this.map);
}
public Builder setAll(StaticComponentMap.Builder map) {
return this.setAll(map.map);
}
public Builder setAll(StaticComponentMap map) {
return this.setAll(map.getDelegate());
}
@SuppressWarnings("unchecked")
public Builder setAll(Map<ComponentType<?>, ?> map) {
for (Map.Entry<ComponentType<?>, ?> entry : map.entrySet()) {
this.set((ComponentType<Object>) entry.getKey(), entry.getValue());
}
return this;
}
public <T> Builder set(ComponentType<T> type, Optional<T> value) {
return this.set(type, value.orElse(null));
}
public <T> Builder set(ComponentType<T> type, @Nullable T value) {
if (value == null) {
this.map.remove(type);
} else {
this.map.put(type, value);
}
return this;
}
}
}
@@ -1,109 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2024 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.component;
import com.github.retrooper.packetevents.protocol.mapper.AbstractMappedEntity;
import com.github.retrooper.packetevents.protocol.nbt.NBT;
import com.github.retrooper.packetevents.protocol.player.ClientVersion;
import com.github.retrooper.packetevents.util.mappings.TypesBuilderData;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import com.github.retrooper.packetevents.wrapper.PacketWrapper.Reader;
import com.github.retrooper.packetevents.wrapper.PacketWrapper.Writer;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
import java.util.function.Function;
public class StaticComponentType<T> extends AbstractMappedEntity implements ComponentType<T> {
private final @Nullable Reader<T> reader;
private final @Nullable Writer<T> writer;
private final @Nullable Decoder<T> decoder;
private final @Nullable Encoder<T> encoder;
@ApiStatus.Internal
public StaticComponentType(
@Nullable TypesBuilderData data,
@Nullable Reader<T> reader,
@Nullable Writer<T> writer
) {
this(data, reader, writer, null, null);
}
@ApiStatus.Internal
public StaticComponentType(
@Nullable TypesBuilderData data,
@Nullable Decoder<T> decoder,
@Nullable Encoder<T> encoder
) {
this(data, null, null, decoder, encoder);
}
@ApiStatus.Internal
public StaticComponentType(
@Nullable TypesBuilderData data,
@Nullable Reader<T> reader,
@Nullable Writer<T> writer,
@Nullable Decoder<T> decoder,
@Nullable Encoder<T> encoder
) {
super(data);
this.reader = reader;
this.writer = writer;
this.decoder = decoder;
this.encoder = encoder;
}
@Override
public T read(PacketWrapper<?> wrapper) {
return this.reader != null ? this.reader.apply(wrapper) : null;
}
@Override
public void write(PacketWrapper<?> wrapper, T content) {
if (this.writer != null) {
this.writer.accept(wrapper, content);
}
}
@Override
public T decode(NBT nbt, ClientVersion version) {
if (this.decoder != null) {
return this.decoder.decode(nbt, version);
}
throw new UnsupportedOperationException();
}
@Override
public NBT encode(T value, ClientVersion version) {
if (this.encoder != null) {
return this.encoder.encode(value, version);
}
throw new UnsupportedOperationException();
}
@Override
public <Z> ComponentType<Z> legacyMap(Function<T, Z> mapper, Function<Z, T> unmapper) {
Reader<Z> reader = this.reader != null ? wrapper -> mapper.apply(this.reader.apply(wrapper)) : null;
Writer<Z> writer = this.writer != null ? (wrapper, value) -> this.writer.accept(wrapper, unmapper.apply(value)) : null;
Decoder<Z> decoder = this.decoder != null ? (nbt, version) -> mapper.apply(this.decoder.decode(nbt, version)) : null;
Encoder<Z> encoder = this.encoder != null ? (value, version) -> this.encoder.encode(unmapper.apply(value), version) : null;
return new StaticComponentType<>(this.data, reader, writer, decoder, encoder);
}
}
@@ -1,63 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2025 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.component.builtin;
import com.github.retrooper.packetevents.protocol.entity.axolotl.AxolotlVariant;
import com.github.retrooper.packetevents.protocol.entity.axolotl.AxolotlVariants;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import java.util.Objects;
public class AxolotlVariantComponent {
private AxolotlVariant variant;
public AxolotlVariantComponent(AxolotlVariant variant) {
this.variant = variant;
}
public static AxolotlVariantComponent read(PacketWrapper<?> wrapper) {
AxolotlVariant type = wrapper.readMappedEntity(AxolotlVariants.getRegistry());
return new AxolotlVariantComponent(type);
}
public static void write(PacketWrapper<?> wrapper, AxolotlVariantComponent component) {
wrapper.writeMappedEntity(component.variant);
}
public AxolotlVariant getVariant() {
return this.variant;
}
public void setVariant(AxolotlVariant variant) {
this.variant = variant;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof AxolotlVariantComponent)) return false;
AxolotlVariantComponent that = (AxolotlVariantComponent) obj;
return this.variant.equals(that.variant);
}
@Override
public int hashCode() {
return Objects.hashCode(this.variant);
}
}
@@ -1,62 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2025 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.component.builtin;
import com.github.retrooper.packetevents.protocol.color.DyeColor;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import java.util.Objects;
public class CatCollarComponent {
private DyeColor color;
public CatCollarComponent(DyeColor color) {
this.color = color;
}
public static CatCollarComponent read(PacketWrapper<?> wrapper) {
DyeColor type = DyeColor.read(wrapper);
return new CatCollarComponent(type);
}
public static void write(PacketWrapper<?> wrapper, CatCollarComponent component) {
DyeColor.write(wrapper, component.color);
}
public DyeColor getDyeColor() {
return this.color;
}
public void setDyeColor(DyeColor color) {
this.color = color;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof CatCollarComponent)) return false;
CatCollarComponent that = (CatCollarComponent) obj;
return this.color.equals(that.color);
}
@Override
public int hashCode() {
return Objects.hashCode(this.color);
}
}
@@ -1,63 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2025 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.component.builtin;
import com.github.retrooper.packetevents.protocol.entity.cat.CatVariant;
import com.github.retrooper.packetevents.protocol.entity.cat.CatVariants;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import java.util.Objects;
public class CatVariantComponent {
private CatVariant variant;
public CatVariantComponent(CatVariant variant) {
this.variant = variant;
}
public static CatVariantComponent read(PacketWrapper<?> wrapper) {
CatVariant type = wrapper.readMappedEntity(CatVariants.getRegistry());
return new CatVariantComponent(type);
}
public static void write(PacketWrapper<?> wrapper, CatVariantComponent component) {
wrapper.writeMappedEntity(component.variant);
}
public CatVariant getVariant() {
return this.variant;
}
public void setVariant(CatVariant variant) {
this.variant = variant;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof CatVariantComponent)) return false;
CatVariantComponent that = (CatVariantComponent) obj;
return this.variant.equals(that.variant);
}
@Override
public int hashCode() {
return Objects.hashCode(this.variant);
}
}
@@ -1,65 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2025 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.component.builtin;
import com.github.retrooper.packetevents.protocol.entity.chicken.ChickenVariant;
import com.github.retrooper.packetevents.protocol.entity.chicken.ChickenVariants;
import com.github.retrooper.packetevents.protocol.mapper.MaybeMappedEntity;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import java.util.Objects;
public class ChickenVariantComponent {
private MaybeMappedEntity<ChickenVariant> variant;
public ChickenVariantComponent(MaybeMappedEntity<ChickenVariant> variant) {
this.variant = variant;
}
public static ChickenVariantComponent read(PacketWrapper<?> wrapper) {
MaybeMappedEntity<ChickenVariant> variant = MaybeMappedEntity.read(wrapper,
ChickenVariants.getRegistry(), ChickenVariant::read);
return new ChickenVariantComponent(variant);
}
public static void write(PacketWrapper<?> wrapper, ChickenVariantComponent component) {
MaybeMappedEntity.write(wrapper, component.variant, ChickenVariant::write);
}
public MaybeMappedEntity<ChickenVariant> getVariant() {
return this.variant;
}
public void setVariant(MaybeMappedEntity<ChickenVariant> variant) {
this.variant = variant;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ChickenVariantComponent)) return false;
ChickenVariantComponent that = (ChickenVariantComponent) obj;
return this.variant.equals(that.variant);
}
@Override
public int hashCode() {
return Objects.hashCode(this.variant);
}
}
@@ -1,63 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2025 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.component.builtin;
import com.github.retrooper.packetevents.protocol.entity.cow.CowVariant;
import com.github.retrooper.packetevents.protocol.entity.cow.CowVariants;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import java.util.Objects;
public class CowVariantComponent {
private CowVariant variant;
public CowVariantComponent(CowVariant variant) {
this.variant = variant;
}
public static CowVariantComponent read(PacketWrapper<?> wrapper) {
CowVariant type = wrapper.readMappedEntity(CowVariants.getRegistry());
return new CowVariantComponent(type);
}
public static void write(PacketWrapper<?> wrapper, CowVariantComponent component) {
wrapper.writeMappedEntity(component.variant);
}
public CowVariant getVariant() {
return this.variant;
}
public void setVariant(CowVariant variant) {
this.variant = variant;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof CowVariantComponent)) return false;
CowVariantComponent that = (CowVariantComponent) obj;
return this.variant.equals(that.variant);
}
@Override
public int hashCode() {
return Objects.hashCode(this.variant);
}
}
@@ -1,63 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2025 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.component.builtin;
import com.github.retrooper.packetevents.protocol.entity.fox.FoxVariant;
import com.github.retrooper.packetevents.protocol.entity.fox.FoxVariants;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import java.util.Objects;
public class FoxVariantComponent {
private FoxVariant variant;
public FoxVariantComponent(FoxVariant variant) {
this.variant = variant;
}
public static FoxVariantComponent read(PacketWrapper<?> wrapper) {
FoxVariant type = wrapper.readMappedEntity(FoxVariants.getRegistry());
return new FoxVariantComponent(type);
}
public static void write(PacketWrapper<?> wrapper, FoxVariantComponent component) {
wrapper.writeMappedEntity(component.variant);
}
public FoxVariant getVariant() {
return this.variant;
}
public void setVariant(FoxVariant variant) {
this.variant = variant;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof FoxVariantComponent)) return false;
FoxVariantComponent that = (FoxVariantComponent) obj;
return this.variant.equals(that.variant);
}
@Override
public int hashCode() {
return Objects.hashCode(this.variant);
}
}
@@ -1,63 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2025 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.component.builtin;
import com.github.retrooper.packetevents.protocol.entity.frog.FrogVariant;
import com.github.retrooper.packetevents.protocol.entity.frog.FrogVariants;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import java.util.Objects;
public class FrogVariantComponent {
private FrogVariant variant;
public FrogVariantComponent(FrogVariant variant) {
this.variant = variant;
}
public static FrogVariantComponent read(PacketWrapper<?> wrapper) {
FrogVariant variant = wrapper.readMappedEntity(FrogVariants.getRegistry());
return new FrogVariantComponent(variant);
}
public static void write(PacketWrapper<?> wrapper, FrogVariantComponent component) {
wrapper.writeMappedEntity(component.variant);
}
public FrogVariant getVariant() {
return this.variant;
}
public void setVariant(FrogVariant variant) {
this.variant = variant;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof FrogVariantComponent)) return false;
FrogVariantComponent that = (FrogVariantComponent) obj;
return this.variant.equals(that.variant);
}
@Override
public int hashCode() {
return Objects.hashCode(this.variant);
}
}
@@ -1,63 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2025 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.component.builtin;
import com.github.retrooper.packetevents.protocol.entity.horse.HorseVariant;
import com.github.retrooper.packetevents.protocol.entity.horse.HorseVariants;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import java.util.Objects;
public class HorseVariantComponent {
private HorseVariant variant;
public HorseVariantComponent(HorseVariant variant) {
this.variant = variant;
}
public static HorseVariantComponent read(PacketWrapper<?> wrapper) {
HorseVariant variant = wrapper.readMappedEntity(HorseVariants.getRegistry());
return new HorseVariantComponent(variant);
}
public static void write(PacketWrapper<?> wrapper, HorseVariantComponent component) {
wrapper.writeMappedEntity(component.variant);
}
public HorseVariant getVariant() {
return this.variant;
}
public void setVariant(HorseVariant variant) {
this.variant = variant;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof HorseVariantComponent)) return false;
HorseVariantComponent that = (HorseVariantComponent) obj;
return this.variant.equals(that.variant);
}
@Override
public int hashCode() {
return Objects.hashCode(this.variant);
}
}
@@ -1,63 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2025 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.component.builtin;
import com.github.retrooper.packetevents.protocol.entity.llama.LlamaVariant;
import com.github.retrooper.packetevents.protocol.entity.llama.LlamaVariants;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import java.util.Objects;
public class LlamaVariantComponent {
private LlamaVariant variant;
public LlamaVariantComponent(LlamaVariant variant) {
this.variant = variant;
}
public static LlamaVariantComponent read(PacketWrapper<?> wrapper) {
LlamaVariant type = wrapper.readMappedEntity(LlamaVariants.getRegistry());
return new LlamaVariantComponent(type);
}
public static void write(PacketWrapper<?> wrapper, LlamaVariantComponent component) {
wrapper.writeMappedEntity(component.variant);
}
public LlamaVariant getVariant() {
return this.variant;
}
public void setVariant(LlamaVariant variant) {
this.variant = variant;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof LlamaVariantComponent)) return false;
LlamaVariantComponent that = (LlamaVariantComponent) obj;
return this.variant.equals(that.variant);
}
@Override
public int hashCode() {
return Objects.hashCode(this.variant);
}
}
@@ -1,63 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2025 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.component.builtin;
import com.github.retrooper.packetevents.protocol.entity.mooshroom.MooshroomVariant;
import com.github.retrooper.packetevents.protocol.entity.mooshroom.MooshroomVariants;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import java.util.Objects;
public class MooshroomVariantComponent {
private MooshroomVariant variant;
public MooshroomVariantComponent(MooshroomVariant variant) {
this.variant = variant;
}
public static MooshroomVariantComponent read(PacketWrapper<?> wrapper) {
MooshroomVariant type = wrapper.readMappedEntity(MooshroomVariants.getRegistry());
return new MooshroomVariantComponent(type);
}
public static void write(PacketWrapper<?> wrapper, MooshroomVariantComponent component) {
wrapper.writeMappedEntity(component.variant);
}
public MooshroomVariant getVariant() {
return this.variant;
}
public void setVariant(MooshroomVariant variant) {
this.variant = variant;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof MooshroomVariantComponent)) return false;
MooshroomVariantComponent that = (MooshroomVariantComponent) obj;
return this.variant.equals(that.variant);
}
@Override
public int hashCode() {
return Objects.hashCode(this.variant);
}
}
@@ -1,63 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2025 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.component.builtin;
import com.github.retrooper.packetevents.protocol.world.painting.PaintingVariant;
import com.github.retrooper.packetevents.protocol.world.painting.PaintingVariants;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import java.util.Objects;
public class PaintingVariantComponent {
private PaintingVariant variant;
public PaintingVariantComponent(PaintingVariant variant) {
this.variant = variant;
}
public static PaintingVariantComponent read(PacketWrapper<?> wrapper) {
PaintingVariant variant = wrapper.readMappedEntity(PaintingVariants.getRegistry());
return new PaintingVariantComponent(variant);
}
public static void write(PacketWrapper<?> wrapper, PaintingVariantComponent component) {
wrapper.writeMappedEntity(component.variant);
}
public PaintingVariant getVariant() {
return this.variant;
}
public void setVariant(PaintingVariant variant) {
this.variant = variant;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof PaintingVariantComponent)) return false;
PaintingVariantComponent that = (PaintingVariantComponent) obj;
return this.variant.equals(that.variant);
}
@Override
public int hashCode() {
return Objects.hashCode(this.variant);
}
}
@@ -1,63 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2025 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.component.builtin;
import com.github.retrooper.packetevents.protocol.entity.parrot.ParrotVariant;
import com.github.retrooper.packetevents.protocol.entity.parrot.ParrotVariants;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import java.util.Objects;
public class ParrotVariantComponent {
private ParrotVariant variant;
public ParrotVariantComponent(ParrotVariant variant) {
this.variant = variant;
}
public static ParrotVariantComponent read(PacketWrapper<?> wrapper) {
ParrotVariant type = wrapper.readMappedEntity(ParrotVariants.getRegistry());
return new ParrotVariantComponent(type);
}
public static void write(PacketWrapper<?> wrapper, ParrotVariantComponent component) {
wrapper.writeMappedEntity(component.variant);
}
public ParrotVariant getVariant() {
return this.variant;
}
public void setVariant(ParrotVariant variant) {
this.variant = variant;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ParrotVariantComponent)) return false;
ParrotVariantComponent that = (ParrotVariantComponent) obj;
return this.variant.equals(that.variant);
}
@Override
public int hashCode() {
return Objects.hashCode(this.variant);
}
}
@@ -1,63 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2025 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.component.builtin;
import com.github.retrooper.packetevents.protocol.entity.pig.PigVariant;
import com.github.retrooper.packetevents.protocol.entity.pig.PigVariants;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import java.util.Objects;
public class PigVariantComponent {
private PigVariant variant;
public PigVariantComponent(PigVariant variant) {
this.variant = variant;
}
public static PigVariantComponent read(PacketWrapper<?> wrapper) {
PigVariant type = wrapper.readMappedEntity(PigVariants.getRegistry());
return new PigVariantComponent(type);
}
public static void write(PacketWrapper<?> wrapper, PigVariantComponent component) {
wrapper.writeMappedEntity(component.variant);
}
public PigVariant getVariant() {
return this.variant;
}
public void setVariant(PigVariant variant) {
this.variant = variant;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof PigVariantComponent)) return false;
PigVariantComponent that = (PigVariantComponent) obj;
return this.variant.equals(that.variant);
}
@Override
public int hashCode() {
return Objects.hashCode(this.variant);
}
}
@@ -1,63 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2025 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.component.builtin;
import com.github.retrooper.packetevents.protocol.entity.rabbit.RabbitVariant;
import com.github.retrooper.packetevents.protocol.entity.rabbit.RabbitVariants;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import java.util.Objects;
public class RabbitVariantComponent {
private RabbitVariant variant;
public RabbitVariantComponent(RabbitVariant variant) {
this.variant = variant;
}
public static RabbitVariantComponent read(PacketWrapper<?> wrapper) {
RabbitVariant type = wrapper.readMappedEntity(RabbitVariants.getRegistry());
return new RabbitVariantComponent(type);
}
public static void write(PacketWrapper<?> wrapper, RabbitVariantComponent component) {
wrapper.writeMappedEntity(component.variant);
}
public RabbitVariant getVariant() {
return this.variant;
}
public void setVariant(RabbitVariant variant) {
this.variant = variant;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof RabbitVariantComponent)) return false;
RabbitVariantComponent that = (RabbitVariantComponent) obj;
return this.variant.equals(that.variant);
}
@Override
public int hashCode() {
return Objects.hashCode(this.variant);
}
}
@@ -1,63 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2025 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.component.builtin;
import com.github.retrooper.packetevents.protocol.entity.salmon.SalmonVariant;
import com.github.retrooper.packetevents.protocol.entity.salmon.SalmonVariants;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import java.util.Objects;
public class SalmonSizeComponent {
private SalmonVariant variant;
public SalmonSizeComponent(SalmonVariant variant) {
this.variant = variant;
}
public static SalmonSizeComponent read(PacketWrapper<?> wrapper) {
SalmonVariant type = wrapper.readMappedEntity(SalmonVariants.getRegistry());
return new SalmonSizeComponent(type);
}
public static void write(PacketWrapper<?> wrapper, SalmonSizeComponent component) {
wrapper.writeMappedEntity(component.variant);
}
public SalmonVariant getVariant() {
return this.variant;
}
public void setVariant(SalmonVariant variant) {
this.variant = variant;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof SalmonSizeComponent)) return false;
SalmonSizeComponent that = (SalmonSizeComponent) obj;
return this.variant.equals(that.variant);
}
@Override
public int hashCode() {
return Objects.hashCode(this.variant);
}
}
@@ -1,62 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2025 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.component.builtin;
import com.github.retrooper.packetevents.protocol.color.DyeColor;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import java.util.Objects;
public class SheepColorComponent {
private DyeColor color;
public SheepColorComponent(DyeColor color) {
this.color = color;
}
public static SheepColorComponent read(PacketWrapper<?> wrapper) {
DyeColor type = DyeColor.read(wrapper);
return new SheepColorComponent(type);
}
public static void write(PacketWrapper<?> wrapper, SheepColorComponent component) {
DyeColor.write(wrapper, component.color);
}
public DyeColor getDyeColor() {
return this.color;
}
public void setDyeColor(DyeColor color) {
this.color = color;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof SheepColorComponent)) return false;
SheepColorComponent that = (SheepColorComponent) obj;
return this.color.equals(that.color);
}
@Override
public int hashCode() {
return Objects.hashCode(this.color);
}
}
@@ -1,62 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2025 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.component.builtin;
import com.github.retrooper.packetevents.protocol.color.DyeColor;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import java.util.Objects;
public class ShulkerColorComponent {
private DyeColor color;
public ShulkerColorComponent(DyeColor color) {
this.color = color;
}
public static ShulkerColorComponent read(PacketWrapper<?> wrapper) {
DyeColor type = DyeColor.read(wrapper);
return new ShulkerColorComponent(type);
}
public static void write(PacketWrapper<?> wrapper, ShulkerColorComponent component) {
DyeColor.write(wrapper, component.color);
}
public DyeColor getDyeColor() {
return this.color;
}
public void setDyeColor(DyeColor color) {
this.color = color;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ShulkerColorComponent)) return false;
ShulkerColorComponent that = (ShulkerColorComponent) obj;
return this.color.equals(that.color);
}
@Override
public int hashCode() {
return Objects.hashCode(this.color);
}
}
@@ -1,62 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2025 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.component.builtin;
import com.github.retrooper.packetevents.protocol.color.DyeColor;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import java.util.Objects;
public class TropicalFishBaseColorComponent {
private DyeColor color;
public TropicalFishBaseColorComponent(DyeColor color) {
this.color = color;
}
public static TropicalFishBaseColorComponent read(PacketWrapper<?> wrapper) {
DyeColor type = DyeColor.read(wrapper);
return new TropicalFishBaseColorComponent(type);
}
public static void write(PacketWrapper<?> wrapper, TropicalFishBaseColorComponent component) {
DyeColor.write(wrapper, component.color);
}
public DyeColor getDyeColor() {
return this.color;
}
public void setDyeColor(DyeColor color) {
this.color = color;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof TropicalFishBaseColorComponent)) return false;
TropicalFishBaseColorComponent that = (TropicalFishBaseColorComponent) obj;
return this.color.equals(that.color);
}
@Override
public int hashCode() {
return Objects.hashCode(this.color);
}
}
@@ -1,62 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2025 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.component.builtin;
import com.github.retrooper.packetevents.protocol.color.DyeColor;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import java.util.Objects;
public class TropicalFishPatternColorComponent {
private DyeColor color;
public TropicalFishPatternColorComponent(DyeColor color) {
this.color = color;
}
public static TropicalFishPatternColorComponent read(PacketWrapper<?> wrapper) {
DyeColor type = DyeColor.read(wrapper);
return new TropicalFishPatternColorComponent(type);
}
public static void write(PacketWrapper<?> wrapper, TropicalFishPatternColorComponent component) {
DyeColor.write(wrapper, component.color);
}
public DyeColor getDyeColor() {
return this.color;
}
public void setDyeColor(DyeColor color) {
this.color = color;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof TropicalFishPatternColorComponent)) return false;
TropicalFishPatternColorComponent that = (TropicalFishPatternColorComponent) obj;
return this.color.equals(that.color);
}
@Override
public int hashCode() {
return Objects.hashCode(this.color);
}
}
@@ -1,63 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2025 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.component.builtin;
import com.github.retrooper.packetevents.protocol.entity.tropicalfish.TropicalFishPattern;
import com.github.retrooper.packetevents.protocol.entity.tropicalfish.TropicalFishPatterns;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import java.util.Objects;
public class TropicalFishPatternComponent {
private TropicalFishPattern variant;
public TropicalFishPatternComponent(TropicalFishPattern variant) {
this.variant = variant;
}
public static TropicalFishPatternComponent read(PacketWrapper<?> wrapper) {
TropicalFishPattern type = wrapper.readMappedEntity(TropicalFishPatterns.getRegistry());
return new TropicalFishPatternComponent(type);
}
public static void write(PacketWrapper<?> wrapper, TropicalFishPatternComponent component) {
wrapper.writeMappedEntity(component.variant);
}
public TropicalFishPattern getVariant() {
return this.variant;
}
public void setVariant(TropicalFishPattern variant) {
this.variant = variant;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof TropicalFishPatternComponent)) return false;
TropicalFishPatternComponent that = (TropicalFishPatternComponent) obj;
return this.variant.equals(that.variant);
}
@Override
public int hashCode() {
return Objects.hashCode(this.variant);
}
}
@@ -1,63 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2025 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.component.builtin;
import com.github.retrooper.packetevents.protocol.entity.villager.type.VillagerType;
import com.github.retrooper.packetevents.protocol.entity.villager.type.VillagerTypes;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import java.util.Objects;
public class VillagerVariantComponent {
private VillagerType villagerType;
public VillagerVariantComponent(VillagerType villagerType) {
this.villagerType = villagerType;
}
public static VillagerVariantComponent read(PacketWrapper<?> wrapper) {
VillagerType type = wrapper.readMappedEntity(VillagerTypes.getRegistry());
return new VillagerVariantComponent(type);
}
public static void write(PacketWrapper<?> wrapper, VillagerVariantComponent component) {
wrapper.writeMappedEntity(component.villagerType);
}
public VillagerType getVillagerType() {
return this.villagerType;
}
public void setVillagerType(VillagerType villagerType) {
this.villagerType = villagerType;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof VillagerVariantComponent)) return false;
VillagerVariantComponent that = (VillagerVariantComponent) obj;
return this.villagerType.equals(that.villagerType);
}
@Override
public int hashCode() {
return Objects.hashCode(this.villagerType);
}
}
@@ -1,62 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2025 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.component.builtin;
import com.github.retrooper.packetevents.protocol.color.DyeColor;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import java.util.Objects;
public class WolfCollarComponent {
private DyeColor color;
public WolfCollarComponent(DyeColor color) {
this.color = color;
}
public static WolfCollarComponent read(PacketWrapper<?> wrapper) {
DyeColor type = DyeColor.read(wrapper);
return new WolfCollarComponent(type);
}
public static void write(PacketWrapper<?> wrapper, WolfCollarComponent component) {
DyeColor.write(wrapper, component.color);
}
public DyeColor getDyeColor() {
return this.color;
}
public void setDyeColor(DyeColor color) {
this.color = color;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof WolfCollarComponent)) return false;
WolfCollarComponent that = (WolfCollarComponent) obj;
return this.color.equals(that.color);
}
@Override
public int hashCode() {
return Objects.hashCode(this.color);
}
}
@@ -1,63 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2025 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.component.builtin;
import com.github.retrooper.packetevents.protocol.entity.wolfvariant.WolfSoundVariant;
import com.github.retrooper.packetevents.protocol.entity.wolfvariant.WolfSoundVariants;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import java.util.Objects;
public class WolfSoundVariantComponent {
private WolfSoundVariant soundVariant;
public WolfSoundVariantComponent(WolfSoundVariant soundVariant) {
this.soundVariant = soundVariant;
}
public static WolfSoundVariantComponent read(PacketWrapper<?> wrapper) {
WolfSoundVariant type = wrapper.readMappedEntity(WolfSoundVariants.getRegistry());
return new WolfSoundVariantComponent(type);
}
public static void write(PacketWrapper<?> wrapper, WolfSoundVariantComponent component) {
wrapper.writeMappedEntity(component.soundVariant);
}
public WolfSoundVariant getSoundVariant() {
return this.soundVariant;
}
public void setSoundVariant(WolfSoundVariant soundVariant) {
this.soundVariant = soundVariant;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof WolfSoundVariantComponent)) return false;
WolfSoundVariantComponent that = (WolfSoundVariantComponent) obj;
return this.soundVariant.equals(that.soundVariant);
}
@Override
public int hashCode() {
return Objects.hashCode(this.soundVariant);
}
}
@@ -1,63 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2025 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.component.builtin;
import com.github.retrooper.packetevents.protocol.entity.wolfvariant.WolfVariant;
import com.github.retrooper.packetevents.protocol.entity.wolfvariant.WolfVariants;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import java.util.Objects;
public class WolfVariantComponent {
private WolfVariant variant;
public WolfVariantComponent(WolfVariant variant) {
this.variant = variant;
}
public static WolfVariantComponent read(PacketWrapper<?> wrapper) {
WolfVariant type = wrapper.readMappedEntity(WolfVariants.getRegistry());
return new WolfVariantComponent(type);
}
public static void write(PacketWrapper<?> wrapper, WolfVariantComponent component) {
wrapper.writeMappedEntity(component.variant);
}
public WolfVariant getVariant() {
return this.variant;
}
public void setVariant(WolfVariant variant) {
this.variant = variant;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof WolfVariantComponent)) return false;
WolfVariantComponent that = (WolfVariantComponent) obj;
return this.variant.equals(that.variant);
}
@Override
public int hashCode() {
return Objects.hashCode(this.variant);
}
}
@@ -1,119 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2024 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.component.builtin.item;
import com.github.retrooper.packetevents.manager.server.ServerVersion;
import com.github.retrooper.packetevents.protocol.item.trimmaterial.TrimMaterial;
import com.github.retrooper.packetevents.protocol.item.trimpattern.TrimPattern;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import org.jetbrains.annotations.ApiStatus;
import java.util.Objects;
public class ArmorTrim {
private TrimMaterial material;
private TrimPattern pattern;
/**
* Removed in 1.21.5
*/
@ApiStatus.Obsolete
private boolean showInTooltip;
public ArmorTrim(TrimMaterial material, TrimPattern pattern) {
this(material, pattern, true);
}
/**
* {@link #showInTooltip} has been removed in 1.21.5
*/
@ApiStatus.Obsolete
public ArmorTrim(TrimMaterial material, TrimPattern pattern, boolean showInTooltip) {
this.material = material;
this.pattern = pattern;
this.showInTooltip = showInTooltip;
}
public static ArmorTrim read(PacketWrapper<?> wrapper) {
TrimMaterial material = TrimMaterial.read(wrapper);
TrimPattern pattern = TrimPattern.read(wrapper);
boolean showInTooltip = wrapper.getServerVersion().isNewerThanOrEquals(ServerVersion.V_1_21_5) || wrapper.readBoolean();
return new ArmorTrim(material, pattern, showInTooltip);
}
public static void write(PacketWrapper<?> wrapper, ArmorTrim trim) {
TrimMaterial.write(wrapper, trim.material);
TrimPattern.write(wrapper, trim.pattern);
if (wrapper.getServerVersion().isOlderThan(ServerVersion.V_1_21_5)) {
wrapper.writeBoolean(trim.showInTooltip);
}
}
public TrimMaterial getMaterial() {
return this.material;
}
public void setMaterial(TrimMaterial material) {
this.material = material;
}
public TrimPattern getPattern() {
return this.pattern;
}
public void setPattern(TrimPattern pattern) {
this.pattern = pattern;
}
/**
* Removed in 1.21.5
*/
@ApiStatus.Obsolete
public boolean isShowInTooltip() {
return this.showInTooltip;
}
/**
* Removed in 1.21.5
*/
@ApiStatus.Obsolete
public void setShowInTooltip(boolean showInTooltip) {
this.showInTooltip = showInTooltip;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof ArmorTrim)) return false;
ArmorTrim armorTrim = (ArmorTrim) obj;
if (this.showInTooltip != armorTrim.showInTooltip) return false;
if (!this.material.equals(armorTrim.material)) return false;
return this.pattern.equals(armorTrim.pattern);
}
@Override
public int hashCode() {
return Objects.hash(this.material, this.pattern, this.showInTooltip);
}
@Override
public String toString() {
return "ArmorTrim{material=" + this.material + ", pattern=" + this.pattern + ", showInTooltip=" + this.showInTooltip + '}';
}
}
@@ -1,123 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2024 retrooper and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.retrooper.packetevents.protocol.component.builtin.item;
import com.github.retrooper.packetevents.protocol.color.DyeColor;
import com.github.retrooper.packetevents.protocol.item.banner.BannerPattern;
import com.github.retrooper.packetevents.protocol.item.banner.BannerPatterns;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import java.util.List;
import java.util.Objects;
public class BannerLayers {
private List<Layer> layers;
public BannerLayers(List<Layer> layers) {
this.layers = layers;
}
public static BannerLayers read(PacketWrapper<?> wrapper) {
List<Layer> layers = wrapper.readList(Layer::read);
return new BannerLayers(layers);
}
public static void write(PacketWrapper<?> wrapper, BannerLayers patterns) {
wrapper.writeList(patterns.layers, Layer::write);
}
public void addLayer(Layer layer) {
this.layers.add(layer);
}
public List<Layer> getLayers() {
return this.layers;
}
public void setLayers(List<Layer> layers) {
this.layers = layers;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof BannerLayers)) return false;
BannerLayers that = (BannerLayers) obj;
return this.layers.equals(that.layers);
}
@Override
public int hashCode() {
return Objects.hashCode(this.layers);
}
public static class Layer {
private BannerPattern pattern;
private DyeColor color;
public Layer(BannerPattern pattern, DyeColor color) {
this.pattern = pattern;
this.color = color;
}
public static Layer read(PacketWrapper<?> wrapper) {
BannerPattern pattern = wrapper.readMappedEntityOrDirect(
BannerPatterns.getRegistry(), BannerPattern::readDirect);
DyeColor color = DyeColor.read(wrapper);
return new Layer(pattern, color);
}
public static void write(PacketWrapper<?> wrapper, Layer layer) {
wrapper.writeMappedEntityOrDirect(layer.pattern, BannerPattern::writeDirect);
DyeColor.write(wrapper, layer.color);
}
public BannerPattern getPattern() {
return this.pattern;
}
public void setPattern(BannerPattern pattern) {
this.pattern = pattern;
}
public DyeColor getColor() {
return this.color;
}
public void setColor(DyeColor color) {
this.color = color;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof Layer)) return false;
Layer layer = (Layer) obj;
if (!this.pattern.equals(layer.pattern)) return false;
return this.color == layer.color;
}
@Override
public int hashCode() {
return Objects.hash(this.pattern, this.color);
}
}
}
Loaded 100 of 977 files, more files were not shown because too many files have changed in this diff. Show more