Compare commits

...
129 Commits
Author SHA1 Message Date
retrooper 73420efbb7 Following semantic versioning. Release version: 1.8.0 2022-03-07 21:09:01 +01:00
retrooper c3bc1906b1 Merge remote-tracking branch 'origin/master' 2022-03-07 20:49:46 +01:00
retrooper 3c4a7323a0 Minor change to metrics. 2022-03-07 20:49:31 +01:00
retrooper 0a4fedff09 Finally releasing packetevents 1.8. 2022-03-07 20:42:41 +01:00
retrooper d1fb535ca7 WrappedPacketOutEntityEffect bug fix for 1.18.2 2022-03-05 17:43:43 +01:00
retrooper 5865e056d8 WrappedPacketOutEntity and WrappedPacketOutEntityHeadRotation now accept(support) floats for yaw and pitch, not that weird encoded byte angle.
NPC relative movement hopefully fixed.
2022-02-28 23:02:48 +01:00
retrooper eb561b98b2 Updated to 1.18.2. 2022-02-28 22:50:17 +01:00
retrooper 13b3ac7107 Bug fix in injecting players. 2022-02-04 19:22:58 +01:00
retrooper 1943ba2da1 Removed debug. 2022-02-04 15:22:03 +01:00
retrooper f90925e09b GeyserUtils fixed, now supports 2.0 Geyser API.
We now only inject into real socket channels.
2022-02-04 15:21:13 +01:00
retrooper e2ecb21892 Updated to Geyser 2.0 API 2022-02-02 21:33:39 +01:00
retrooper 80bc492370 Fixed broken ProtocolLib compatibility. 2022-01-31 21:30:14 +01:00
retrooper 691e8eb070 Little comment added 2022-01-21 22:48:58 +01:00
retrooper a83c3bac2a I know this isn't a perfect solution, but we want to process outgoing packets after ProtocolLib. So I went out of my way to for now only process the PLAY packets after them. We adjust our handler when protocollib is available.
PacketEventsSettings#compatInjector deprecated
2022-01-18 19:35:58 +01:00
retrooper 60a5357c34 PacketEvents v1.8 now sends the API Version to bStats. 2022-01-16 22:39:35 +01:00
retrooper af477f8479 Merge pull request #190 from retrooper/dev
1.18 support and more bug fixes merged to master branch
2022-01-06 12:40:29 +01:00
retrooper 6b82b38b59 Fixed javadocs and added plugin.yml to repository 2022-01-04 20:26:57 +01:00
retrooper 77918bb771 Minor change to a debug 2021-12-25 21:22:21 +01:00
retrooper c200b8fe35 1.8-pre-19 launching 2021-12-25 19:25:20 +01:00
DefineOutside 01cac8ded9 Merge pull request #177 from LIWKK/patch-30 2021-12-23 10:45:33 -06:00
Johannes d7a0d89d8e Fix WindowClick 1.9-1.16.5 2021-12-23 18:44:08 +02:00
retrooper 90ec7560b7 Merge remote-tracking branch 'origin/dev' into dev 2021-12-12 15:10:50 +01:00
retrooper eb96c5216b Fixed NMSUtils#getEffectId and NMSUtils#getMobEffectListById (Used in WrappedPacketOutRemoveEntityEffect) on 1.18 2021-12-12 15:10:34 +01:00
DefineOutside 176f2f7895 Merge remote-tracking branch 'origin/dev' into dev 2021-12-11 14:26:36 -06:00
DefineOutside 2489b7651b Fix 1.17.1+ support on set slot 2021-12-11 14:26:23 -06:00
retrooper 30981f8283 Merge remote-tracking branch 'origin/dev' into dev 2021-12-10 21:04:52 +01:00
retrooper 4537ac2d29 Added 1.18.1 support 2021-12-10 21:04:28 +01:00
retrooper 577d3476bb Merge pull request #171 from AlessioGr/master
Add Github actions to packetevents 1.8
2021-12-08 23:26:38 +01:00
DefineOutside 7adb2c2ecd Remove incorrect window click reflection to support 1.17 2021-12-07 16:33:23 -06:00
DefineOutside 1f02892284 1.17 support for the window click packet 2021-12-07 16:19:17 -06:00
DefineOutside 590e94ffc0 Add 1.17 support for the section position class 2021-12-06 17:16:20 -06:00
DefineOutside d5c2619bb3 Try fixing window items packet on 1.17.1 and 1.18 2021-12-06 17:15:05 -06:00
retrooper 935c9782a1 Fixed WrappedPacket#readGameMode and WrappedPacket#writeGameMode 2021-12-06 20:21:11 +01:00
retrooper 33b92f59d5 Small correction to WrappedPacket#writeAnyObject 2021-12-04 19:05:24 +01:00
MWHunter 6d7a06b93f Add support for SectionPosition in 1.18 2021-12-02 16:53:47 -06:00
MWHunter 0e42d7d14f Fix blockpos reflection on 1.18 2021-12-02 16:43:20 -06:00
Alessio Gravili 5cbdcc4158 JDK 8 2021-12-02 17:07:21 +01:00
Alessio Gravili db8f291475 Update gradle-publish.yml 2021-12-02 10:28:50 +01:00
Alessio Gravili 187084dca1 Update gradle-publish.yml 2021-12-02 10:26:52 +01:00
Alessio Gravili 316bc8070a Update gradle-publish.yml 2021-12-02 10:23:58 +01:00
Alessio Gravili 62685e9330 Create gradle-publish.yml 2021-12-02 10:22:58 +01:00
DefineOutside 169105af78 Update gradle-wrapper.properties 2021-12-01 10:44:51 -06:00
DefineOutside 398bb4b6db Update gradle-wrapper.properties 2021-12-01 10:43:56 -06:00
retrooper df56ea0aa6 Merge remote-tracking branch 'origin/dev' into dev 2021-12-01 17:25:32 +01:00
retrooper 95e73c775c Another minor bug fix in settings packet. 2021-12-01 17:25:23 +01:00
DefineOutside b8823ce00f Try fixing the map chunk packet for 1.18 2021-11-30 21:00:43 -06:00
DefineOutside 01658ce3c9 Add 1.18 support for WrappedPacketOutMapChunk 2021-11-30 18:29:57 -06:00
DefineOutside 934c181753 Support for reading 1.18 block positions 2021-11-30 17:11:20 -06:00
retrooper 0e3099e751 We should now work on 1.18 servers 2021-11-30 18:24:21 +01:00
retrooper 43ea7737ec Minor WrappedPacketInSettings change 2021-11-28 22:59:01 +01:00
retrooper 905dd43a0d Minor bug fix 2021-11-28 22:48:39 +01:00
retrooper 17f7c69b11 WrappedPacketInSettings updated to 1.18 2021-11-28 20:29:07 +01:00
retrooper 13965a4517 Added support for 1.18-rc3 2021-11-28 20:08:50 +01:00
retrooper 679d0ba037 One more minor change 2021-11-28 19:37:58 +01:00
retrooper 67e82e6d25 Merge remote-tracking branch 'origin/dev' 2021-11-28 19:32:55 +01:00
retrooper 9e58db6cb1 Minor optimizations by removing redundant/abandoned files;
ClientVersion and ServerVersion enums updated;
build.gradle optimized to remove unnecessary files;
2021-11-28 19:31:52 +01:00
retrooper e1fe2b9d99 Merge pull request #170 from byteful/unregister-listeners
Added methods to unregister PacketListenerAbstract(s).
2021-11-10 00:16:52 +01:00
byteful fd3b42ef6e Cleaned up the code a bit more. 2021-11-06 22:17:22 -05:00
byteful cf708adf55 Removed unnecessary code. 2021-11-06 22:03:36 -05:00
byteful 9f8a14b58a Added methods to unregister PacketListenerAbstract. 2021-11-06 21:39:55 -05:00
DefineOutside 1d31e06679 Merge pull request #169 from retrooper/MWHunter-patch-1
Try to fix build by updating geyser connector
2021-10-23 14:44:32 -05:00
DefineOutside a94e72ccd0 Revert to previous geyser api version 2021-10-23 14:37:34 -05:00
DefineOutside 35bd312ecf Try to fix build by updating geyser connector 2021-10-23 14:27:28 -05:00
DefineOutside 362d021745 Partially revert https://github.com/retrooper/packetevents/commit/5d1371c479c9811b87cc87a225063498654c96fe 2021-10-15 09:31:58 -05:00
DefineOutside 9d98af54e6 Data watcher takes NMS entity as argument, not bukkit entity 2021-10-13 20:30:07 -05:00
retrooper cb1438c86f Fixed WrappedPacketOutEntityVelocity#setVelocity 2021-10-10 18:23:45 +02:00
retrooper 75512add39 Fixed WrappedPacketOutWindowItems for 1.17.1 2021-10-09 20:40:43 +02:00
retrooper db1c913a3e Fixed WrappedPacketOutWindowItems for 1.17 2021-10-03 20:17:20 +02:00
DefineOutside 9c2609f4ee Vector3f should return Vector3f when cloned 2021-09-29 13:50:13 -05:00
DefineOutside 8336017bb9 Fix cloning vectors 2021-09-29 13:46:57 -05:00
retrooper 1ea4880ded Merge remote-tracking branch 'origin/dev' into dev 2021-09-26 15:52:26 +02:00
retrooper f54b8d7138 We now read the channel in network manager correctly 2021-09-26 15:52:19 +02:00
DefineOutside 52e7385864 Fix WrappedPacketOutSetCooldown 2021-09-24 22:20:09 -05:00
DefineOutside 5d1371c479 Optimize ServerVersion 2021-09-21 15:02:20 -05:00
DefineOutside 91916d0eaf Clean up WrappedPacketOutMapChunk 2021-09-20 16:44:53 -05:00
DefineOutside 73505209bc Use bitsets for WrappedPacketOutMapChunk 2021-09-20 16:35:49 -05:00
DefineOutside 934d5378e5 If a version lookup failed, try to resolve the client version again 2021-09-15 23:37:04 -05:00
retrooper 1ac55ffd50 1.8-pre-18 update 2021-09-10 20:50:45 +02:00
retrooper 9f265ef9ee Fixed cancelling event logic in listeners. 2021-09-10 20:47:44 +02:00
retrooper 0595fb6e03 Merge pull request #160 from retrooper/dev
Update master branch to a more stable build of PacketEvents.
2021-08-31 20:33:11 +02:00
retrooper 9172cd3c91 Fixed legacy viaversion api accessor 2021-08-31 20:28:57 +02:00
retrooper 7f655ad54b Created constructor for WrappedPacketLoginOutCustomPayload 2021-08-24 15:23:18 +02:00
retrooper 51af277d48 Netty channels are now acessible in the NMSPacketEvents 2021-08-23 21:21:49 +02:00
retrooper 8f566032aa Removed gradle build files, IDE files, and plugin.yml 2021-08-22 10:16:38 +02:00
retrooper d01fdce16a ServerUtils#getEntityById bug fixes 2021-08-19 07:20:13 +02:00
retrooper b956ca966b Hopefully minimized some bugs for ServerUtils#getEntityById 2021-08-18 22:41:35 +02:00
retrooper 4887d040ed Update README.md 2021-08-14 14:13:27 +02:00
retrooper 341f6632f5 Merge pull request #157 from LIWKK/patch-29
Update ViaVersionLookupUtils.java
2021-08-10 11:01:42 +02:00
Johannes 2cf93d6e17 Update ViaVersionLookupUtils.java 2021-08-09 20:17:24 +03:00
retrooper 4bbf43e83e Build issue fixed 2021-08-08 08:10:19 +02:00
retrooper bcd60977f5 WrappedPacketOutSetSlot now works on 1.17.1 2021-08-08 08:00:11 +02:00
retrooper 3c899e41b5 Adding some build files 2021-08-03 10:59:48 +02:00
retrooper 3653c9b07a Merge pull request #154 from MWHunter/viaversionclientversion
Fix getting player version for the first time with ViaVersion
2021-08-03 10:48:27 +02:00
DefineOutside c667980997 Fix getting player version for the first time with ViaVersion 2021-08-02 10:22:29 -05:00
retrooper df29b947a6 ViaVersion linkage error hopefully fixed 2021-08-02 10:48:10 +02:00
retrooper 55c3b9a446 Removed debugs when ViaVersion is present 2021-07-28 20:27:07 +02:00
retrooper 76ad95c63a PlayerUtils#writePacket and PlayerUtils#flushPackets created 2021-07-23 12:21:32 +02:00
retrooper e7235f1ef7 Fixed WrappedPacketInCustomPayload#getChannelName always returning "minecraft:brand" on 1.13+ server versions. 2021-07-21 22:16:02 +02:00
retrooper 1e26293c51 Extra NMS class added 2021-07-20 19:49:37 +02:00
retrooper 84f9bbf207 Removed invalid enum constants in ServerVersion 2021-07-20 13:59:32 +02:00
retrooper 40e13755ff NPC#teleport 2021-07-15 13:00:54 +02:00
retrooper 093c45609c Removed license notice from build files 2021-07-14 23:21:05 +02:00
retrooper 06d4333524 Copied Bukkit's BoundingBox util;
Fixed getEntityBoundingBox bugs on some newer server versions;
Corrected license notice in some files;
2021-07-14 23:15:37 +02:00
retrooper 78773c3a7b WrappedPacketOutSpawnEntity created;
Fixed incompatibilities with future ViaVersion versions(stopped using legacy API);
2021-07-14 21:58:24 +02:00
retrooper bd36cae8d0 ServerUtils#getEntityBoundingBox created 2021-07-14 21:08:26 +02:00
retrooper 2babb1ac44 Merge remote-tracking branch 'origin/dev' into dev 2021-07-14 12:13:30 +02:00
retrooper e29a15db7e Fixed sending WrappedPacketOutPosition for 1.9 -> 1.16.5 2021-07-14 12:13:22 +02:00
retrooper bb87ce9e77 Merge pull request #146 from MWHunter/fixserverversion
Fix ServerVersion#isNewerThan
2021-07-14 01:28:54 +02:00
DefineOutside b2b7687b33 Fix ServerVersion comparison 2021-07-13 18:13:16 -05:00
retrooper d182f9bd5b WrappedPacketInCustomPayload#getTag -> WrappedPacketInCustomPayload#getChannelName;
WrappedPacketOutCustomPayload#getTag -> WrappedPacketOutCustomPayload#getChannelName;
WrappedPacketLoginOutCustomPayload#getTag -> WrappedPacketLoginOutCustomPayload#getChannelName;

The channel name now also contains the namespace on newer server versions, it can be "minecraft:brand" on newer server versions instead of just "brand". Older versions such as 1.8 always had the namespace. I just made the names consistent. This is a sort of breaking change, thats why I didn't end up deprecating getTag, i want you guys to be aware of the breaking change.
2021-07-13 22:53:41 +02:00
retrooper ab4dba254d Code cleanup 2021-07-13 14:03:11 +02:00
retrooper 380b1e9a73 Merge pull request #143 from MWHunter/destroyattempttwo
Fix reading destroy packet on 1.17
2021-07-13 13:47:41 +02:00
retrooper 395cb6a6b7 WrappedPacketOutEntityDestroy now has 1.17.1 and has been cleaned up. 2021-07-13 13:47:27 +02:00
retrooper e3a6bec0ae Merge pull request #145 from MWHunter/useItem
Add WrappedPacketInUseItem
2021-07-13 13:17:01 +02:00
retrooper 8cd52c4f4d WrappedPacketInUseItem completed;
WrappedPacketInBlockPlace_1_9 optimized;
2021-07-13 13:16:31 +02:00
retrooper ef758b4ee3 Merge remote-tracking branch 'origin/dev' into dev 2021-07-13 12:57:51 +02:00
retrooper a75ad0e58e Small change 2021-07-13 12:57:34 +02:00
DefineOutside 2d282bee8e Add WrappedPacketInUseItem 2021-07-11 18:14:35 -05:00
DefineOutside 4b30678d6b Fix reading entity destroy on 1.17.1 2021-07-10 14:22:15 -05:00
retrooper 70ae66df17 Merge pull request #142 from MWHunter/flying
Fix FLYING packet on 1.17
2021-07-10 21:21:05 +02:00
retrooper 0a98140a1c Merge pull request #141 from MWHunter/dev
Fix WrappedPacketOutMapChunk for 1.17 void chunks
2021-07-10 21:18:55 +02:00
DefineOutside 2ce25c24ee Fix FLYING packet on 1.17 2021-07-10 13:57:23 -05:00
DefineOutside f27688c89f Fix WrappedPacketOutMapChunk for 1.17 void chunks 2021-07-10 12:07:39 -05:00
retrooper e287e63c58 WrappedPacketOutCollect fixed when attempting to send on 1.11+ 2021-07-09 11:35:25 +02:00
retrooper 6a44c3edbf Merge branch 'dev' of https://github.com/retrooper/packetevents into dev
 Conflicts:
	.gradle/7.0/executionHistory/executionHistory.bin
	.gradle/7.0/executionHistory/executionHistory.lock
	.gradle/7.0/fileHashes/fileHashes.bin
	.gradle/7.0/fileHashes/fileHashes.lock
	.gradle/buildOutputCleanup/buildOutputCleanup.lock
	.gradle/checksums/checksums.lock
2021-07-09 07:34:48 +02:00
retrooper cd28ced0c7 Merge pull request #138 from Tecnio/dev
Added WrappedPacketOutCollect
2021-07-09 07:32:41 +02:00
retrooper b05496db09 Fixed WrappedPacketOutCollect bugs and improved. 2021-07-09 07:31:14 +02:00
Tecnio c914ccbb90 Added WrappedPacketOutCollect 2021-07-09 04:49:00 +03:00
retrooper a236fb5523 packetevents 1.8-pre-17 2021-07-08 15:24:32 +02:00
101 changed files with 2490 additions and 964 deletions

No files matched your search

+33
View File
@@ -0,0 +1,33 @@
# This workflow will build a package using Gradle and then publish it to GitHub packages when a release is created
# For more information see: https://github.com/actions/setup-java/blob/main/docs/advanced-usage.md#Publishing-using-gradle
name: Gradle Package
on: [ push, pull_request ]
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- uses: actions/checkout@v2
- name: Set up JDK 8
uses: actions/setup-java@v2
with:
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: gradle :clean :build
- name: Upload build artifacts
uses: actions/upload-artifact@v1
with:
name: packetevents-dev-build.jar
path: build/libs
+5 -1
View File
@@ -110,4 +110,8 @@ dependency-reduced-pom.xml
buildNumber.properties
.mvn/timing.properties
# https://github.com/takari/maven-wrapper#usage-without-binary-jar
.mvn/wrapper/maven-wrapper.jar
.mvn/wrapper/maven-wrapper.jar
/src/main/resources/
/.gradle/
/.idea/
/build/
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+2 -4
View File
@@ -8,13 +8,11 @@ PacketEvents is an open-source Packet API. It has many cross-version packet-wrap
### Resources
* [SpigotMC](https://www.spigotmc.org/resources/packetevents-api.80279/)
* [JavaDoc](https://packetevents.github.io/javadocs)
* [Discord](https://discord.me/packetevents)
### Setup
[Learn more](https://github.com/retrooper/packetevents/wiki/1.-Setup)
### Discord
[Learn more](https://discord.me/packetevents)
### Contributing/Forking
[Learn more](https://github.com/retrooper/packetevents/wiki/2.-Contributing-and-Forking)\
Our discord server has a role for contributors and forkers.
@@ -23,7 +21,7 @@ Our discord server has a role for contributors and forkers.
[![](https://www.ej-technologies.com/images/product_banners/jprofiler_small.png)](https://www.ej-technologies.com/products/jprofiler/overview.html)
### Statistics
PacketEvents collects statistics anonymously through bStats. Participation is completely optional and you can opt-out at any time, although it is really helpful in figuring out what environments the plugin is running in (i.e. versions of Spigot, Java), so I can adjust development accordingly.
PacketEvents collects statistics anonymously using bStats. It helps give us an overview of what platforms use our project. If you really don't like, you can turn it off.
### Credit
PacketEvents uses an injector that is extremely similar to ViaVersion's injector. I have included license and copyright holder notice in the files taken from ViaVersion. Thank you ViaVersion.
+6 -15
View File
@@ -49,33 +49,24 @@ repositories {
maven {
url = uri('https://repo.maven.apache.org/maven2/')
}
mavenCentral()
}
dependencies {
implementation 'org.jetbrains:annotations:20.1.0'
implementation 'org.jetbrains:annotations:22.0.0'
compileOnly 'org.spigotmc:spigot-api:1.17.1-R0.1-SNAPSHOT'
compileOnly 'org.spigotmc:spigot-api:1.17-R0.1-SNAPSHOT'
compileOnly 'com.destroystokyo.paper:paper-api:1.16.5-R0.1-SNAPSHOT'
compileOnly 'org.geysermc:connector:1.2.1-SNAPSHOT'
compileOnly 'us.myles:viaversion:3.2.0'
compileOnly 'com.viaversion:viaversion-api:4.0.1'
compileOnly 'com.github.ProtocolSupport:ProtocolSupport:3d24efeda6'
/*compileOnly 'org.github.spigot:1.16.2:1.16.2'
compileOnly 'org.github.spigot:1.8.8:1.8.8'
compileOnly 'org.github.spigot:1.7.10:1.7.10'*/
compileOnly 'org.github.spigot:1.16.2:1.16.2'
compileOnly 'org.github.spigot:1.13.2:1.13.2'
compileOnly 'org.github.spigot:1.13:1.13'
compileOnly 'org.github.spigot:1.12.2:1.12.2'
compileOnly 'org.github.spigot:1.9.4:1.9.4'
compileOnly 'org.github.spigot:1.9:1.9'
compileOnly 'org.github.spigot:1.8.8:1.8.8'
compileOnly 'org.github.spigot:1.7.10:1.7.10'
}
group = 'io.github.retrooper'
version = '1.8-pre-17'
version = '1.8.0'
description = 'packetevents'
java.sourceCompatibility = JavaVersion.VERSION_1_8
@@ -89,4 +80,4 @@ publishing {
tasks.withType(JavaCompile) {
options.encoding = 'UTF-8'
}
}
+1 -1
View File
@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.0-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored
-16
View File
@@ -1,21 +1,5 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
@@ -57,7 +57,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
public final class PacketEvents implements Listener, EventManager {
private static PacketEvents instance;
private static Plugin plugin;
private final PEVersion version = new PEVersion(1, 7, 9, 17);
private final PEVersion version = new PEVersion(1, 8, 0);
private final EventManager eventManager = new PEEventManager();
private final PlayerUtils playerUtils = new PlayerUtils();
private final ServerUtils serverUtils = new ServerUtils();
@@ -191,6 +191,10 @@ public final class PacketEvents implements Listener, EventManager {
if (settings.isbStatsEnabled()) {
Metrics metrics = new Metrics((JavaPlugin) getPlugin(), 11327);
//Just to have an idea what versions of packetevents people use
metrics.addCustomChart(new Metrics.SimplePie("packetevents_version", () -> {
return getVersion().toString();
}));
}
//We must wait for the injector to initialize.
@@ -25,10 +25,9 @@ import org.bukkit.plugin.java.JavaPlugin;
public class PacketEventsPlugin extends JavaPlugin {
@Override
public void onLoad() {
PacketEvents.create(this);
PacketEventsSettings settings = PacketEvents.get().getSettings();
PacketEventsSettings settings = PacketEvents.create(this).getSettings();
settings
.fallbackServerVersion(ServerVersion.v_1_7_10)
.fallbackServerVersion(ServerVersion.getLatest())
.compatInjector(false)
.checkForUpdates(true)
.bStats(true);
@@ -1,21 +1,19 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2021 retrooper and contributors
*
* * This file is part of packetevents - https://github.com/retrooper/packetevents
* * Copyright (C) 2016-2021 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/>.
* 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 io.github.retrooper.packetevents.event;
@@ -29,10 +29,6 @@ public abstract class CancellableNMSPacketEvent extends NMSPacketEvent implement
super(channel, packet);
}
public CancellableNMSPacketEvent(InetSocketAddress address, NMSPacket packet) {
super(address, packet);
}
@Override
public boolean isCancelled() {
return cancelled;
@@ -35,17 +35,14 @@ import java.net.InetSocketAddress;
* @since 1.8
*/
public abstract class NMSPacketEvent extends PacketEvent implements CallableEvent {
private final Object channel;
private final InetSocketAddress socketAddress;
private final byte packetID;
protected NMSPacket packet;
protected boolean cancelled;
public NMSPacketEvent(Object channel, NMSPacket packet) {
this(ChannelUtils.getSocketAddress(channel), packet);//Call the constructor below
}
public NMSPacketEvent(InetSocketAddress address, NMSPacket packet) {
this.socketAddress = address;
this.channel = channel;
this.socketAddress = ChannelUtils.getSocketAddress(channel);
this.packet = packet;
packetID = PacketType.packetIDMap.getOrDefault(packet.getRawNMSPacket().getClass(), PacketType.INVALID);
}
@@ -59,6 +56,14 @@ public abstract class NMSPacketEvent extends PacketEvent implements CallableEven
return socketAddress;
}
/**
* Get the associated player's netty channel.
* @return Netty channel
*/
public Object getChannel() {
return channel;
}
/**
* This method returns the NMS name of the packet.
* To get the name of the packet we get the class of the packet and then the simple name of the class.
@@ -1,21 +1,19 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2021 retrooper and contributors
*
* * This file is part of packetevents - https://github.com/retrooper/packetevents
* * Copyright (C) 2016-2021 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/>.
* 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 io.github.retrooper.packetevents.event.eventtypes;
@@ -34,14 +34,10 @@ import java.net.InetSocketAddress;
* @since 1.8
*/
public class PacketHandshakeReceiveEvent extends CancellableNMSPacketEvent {
public PacketHandshakeReceiveEvent(final Object channel, final NMSPacket packet) {
public PacketHandshakeReceiveEvent(Object channel, NMSPacket packet) {
super(channel, packet);
}
public PacketHandshakeReceiveEvent(final InetSocketAddress socketAddress, final NMSPacket packet) {
super(socketAddress, packet);
}
@Override
public void call(PacketListenerAbstract listener) {
if (listener.clientSidedLoginAllowance == null || listener.clientSidedLoginAllowance.contains(getPacketId())) {
@@ -34,14 +34,10 @@ import java.net.InetSocketAddress;
* @since 1.8
*/
public class PacketLoginReceiveEvent extends CancellableNMSPacketEvent {
public PacketLoginReceiveEvent(final Object channel, final NMSPacket packet) {
public PacketLoginReceiveEvent(Object channel, NMSPacket packet) {
super(channel, packet);
}
public PacketLoginReceiveEvent(final InetSocketAddress socketAddress, final NMSPacket packet) {
super(socketAddress, packet);
}
@Override
public void call(PacketListenerAbstract listener) {
if (listener.clientSidedLoginAllowance == null || listener.clientSidedLoginAllowance.contains(getPacketId())) {
@@ -41,10 +41,6 @@ public class PacketLoginSendEvent extends CancellableNMSPacketEvent implements P
super(channel, packet);
}
public PacketLoginSendEvent(InetSocketAddress address, NMSPacket packet) {
super(address, packet);
}
@Override
public boolean isPostTaskAvailable() {
return postTask != null;
@@ -38,10 +38,6 @@ public class PacketStatusReceiveEvent extends CancellableNMSPacketEvent {
super(channel, packet);
}
public PacketStatusReceiveEvent(final InetSocketAddress socketAddress, final NMSPacket packet) {
super(socketAddress, packet);
}
@Override
public void call(PacketListenerAbstract listener) {
if (listener.clientSidedStatusAllowance == null || listener.clientSidedStatusAllowance.contains(getPacketId())) {
@@ -44,10 +44,6 @@ public class PacketStatusSendEvent extends CancellableNMSPacketEvent implements
super(channel, packet);
}
public PacketStatusSendEvent(InetSocketAddress address, NMSPacket packet) {
super(address, packet);
}
@Override
public boolean isPostTaskAvailable() {
return postTask != null;
@@ -156,6 +156,30 @@ public interface EventManager {
return this;
}
/**
* Unregister a PacketListenerAbstract listener.
*
* @param listener {@link PacketListenerAbstract}
* @return Same event manager instance.
*/
default EventManager unregisterListener(PacketListenerAbstract listener) {
if (listener != null) {
PEEventManager.EVENT_MANAGER_MODERN.unregisterListener(listener);
}
return this;
}
/**
* Unregister multiple PacketListenerAbstract listeners.
*
* @param listeners {@link PacketListenerAbstract}
* @return Same event manager instance.
*/
default EventManager unregisterListeners(PacketListenerAbstract... listeners) {
PEEventManager.EVENT_MANAGER_MODERN.unregisterListeners(listeners);
return this;
}
/**
* Unregister all registered event listeners.
* All the deprecated and the dynamic listeners will be unregistered.
@@ -45,10 +45,6 @@ class EventManagerModern {
* @see EventManagerLegacy#callEvent(PacketEvent, byte)
*/
public void callEvent(final PacketEvent event) {
boolean cancel = false;
if (event instanceof CancellableEvent) {
cancel = ((CancellableEvent) event).isCancelled();
}
byte highestReachedPriority = (byte) (PacketListenerPriority.LOWEST.getId() - 1);
for (byte priority = PacketListenerPriority.LOWEST.getId(); priority <= PacketListenerPriority.MONITOR.getId(); priority++) {
HashSet<PacketListenerAbstract> listeners = listenersMap.get(priority);
@@ -63,17 +59,10 @@ class EventManagerModern {
//TODO Remove, because its redundant. We are only keeping it for compatibility with the legacy event manager.
if (event instanceof CancellableEvent) {
if (priority > highestReachedPriority) {
CancellableEvent ce = (CancellableEvent) event;
cancel = ce.isCancelled();
highestReachedPriority = priority;
}
}
}
//TODO Remove. This is also redundant. The listeners are always called in order, the event is always being modified by each listener. The last listener therefore has the last decision on the cancellation.
if (event instanceof CancellableEvent) {
CancellableEvent ce = (CancellableEvent) event;
ce.setCancelled(cancel);
}
}
}
PEEventManager.EVENT_MANAGER_LEGACY.callEvent(event, highestReachedPriority);
@@ -105,6 +94,30 @@ class EventManagerModern {
}
}
/**
* Unregister the dynamic packet event listener.
*
* @param listener {@link PacketListenerAbstract}
*/
public synchronized void unregisterListener(final PacketListenerAbstract listener) {
byte priority = listener.getPriority().getId();
HashSet<PacketListenerAbstract> listenerSet = listenersMap.get(priority);
if (listenerSet != null) {
listenerSet.remove(listener);
}
}
/**
* Unregister multiple dynamic packet event listeners with one method.
*
* @param listeners {@link PacketListenerAbstract}
*/
public synchronized void unregisterListeners(PacketListenerAbstract... listeners) {
for (PacketListenerAbstract listener : listeners) {
unregisterListener(listener);
}
}
/**
* Unregister all dynamic packet event listeners.
*/
@@ -35,5 +35,9 @@ public interface ChannelInjector {
boolean hasInjected(Player player);
void writePacket(Object channel, Object rawNMSPacket);
void flushPackets(Object channel);
void sendPacket(Object channel, Object rawNMSPacket);
}
@@ -84,6 +84,14 @@ public class GlobalChannelInjector {
return injector.hasInjected(player);
}
public void writePacket(Object ch, Object rawNMSPacket) {
injector.writePacket(ch, rawNMSPacket);
}
public void flushPackets(Object ch) {
injector.flushPackets(ch);
}
public void sendPacket(Object ch, Object rawNMSPacket) {
injector.sendPacket(ch, rawNMSPacket);
}
@@ -1,6 +1,6 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2021 retrooper and contributors
* This file is part of ViaVersion - https://github.com/ViaVersion/ViaVersion
* Copyright (C) 2016-2021 ViaVersion 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
@@ -21,10 +21,11 @@ package io.github.retrooper.packetevents.injector.legacy;
import io.github.retrooper.packetevents.PacketEvents;
import io.github.retrooper.packetevents.processor.PacketProcessorInternal;
import net.minecraft.util.io.netty.channel.ChannelDuplexHandler;
import net.minecraft.util.io.netty.channel.ChannelHandler;
import net.minecraft.util.io.netty.channel.ChannelHandlerContext;
import net.minecraft.util.io.netty.channel.ChannelPromise;
import org.bukkit.entity.Player;
@ChannelHandler.Sharable
public class PlayerChannelHandlerLegacy extends ChannelDuplexHandler {
/**
* Associated player.
@@ -25,10 +25,12 @@ import io.github.retrooper.packetevents.packetwrappers.NMSPacket;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.utils.list.ListWrapper;
import io.github.retrooper.packetevents.utils.nms.NMSUtils;
import io.netty.channel.epoll.EpollSocketChannel;
import net.minecraft.util.io.netty.channel.Channel;
import net.minecraft.util.io.netty.channel.ChannelFuture;
import net.minecraft.util.io.netty.channel.ChannelHandler;
import net.minecraft.util.io.netty.channel.ChannelInitializer;
import net.minecraft.util.io.netty.channel.socket.nio.NioSocketChannel;
import org.bukkit.entity.Player;
import org.bukkit.plugin.PluginDescriptionFile;
@@ -125,9 +127,11 @@ public class EarlyChannelInjectorLegacy implements EarlyInjector {
List<Object> networkManagers = NMSUtils.getNetworkManagers();
synchronized (networkManagers) {
for (Object networkManager : networkManagers) {
WrappedPacket networkManagerWrapper = new WrappedPacket(new NMSPacket(networkManager));
WrappedPacket networkManagerWrapper = new WrappedPacket(new NMSPacket(networkManager), NMSUtils.networkManagerClass);
Channel channel = (Channel) networkManagerWrapper.readObject(0, NMSUtils.nettyChannelClass);
if (channel == null) {
if (channel == null ||
(!(channel.getClass().equals(NioSocketChannel.class))) &&
!(channel.getClass().equals(EpollSocketChannel.class))) {
continue;
}
@@ -279,6 +283,18 @@ public class EarlyChannelInjectorLegacy implements EarlyInjector {
return handler != null && handler.player != null;
}
@Override
public void writePacket(Object ch, Object rawNMSPacket) {
Channel channel = (Channel) ch;
channel.write(rawNMSPacket);
}
@Override
public void flushPackets(Object ch) {
Channel channel = (Channel) ch;
channel.flush();
}
@Override
public void sendPacket(Object ch, Object rawNMSPacket) {
Channel channel = (Channel) ch;
@@ -21,8 +21,10 @@ package io.github.retrooper.packetevents.injector.legacy.early;
import io.github.retrooper.packetevents.PacketEvents;
import io.github.retrooper.packetevents.injector.legacy.PlayerChannelHandlerLegacy;
import io.github.retrooper.packetevents.utils.reflection.Reflection;
import io.netty.channel.epoll.EpollSocketChannel;
import net.minecraft.util.io.netty.channel.Channel;
import net.minecraft.util.io.netty.channel.ChannelInitializer;
import net.minecraft.util.io.netty.channel.socket.nio.NioSocketChannel;
import java.lang.reflect.Method;
@@ -47,12 +49,15 @@ public class PEChannelInitializerLegacy extends ChannelInitializer<Channel> {
protected void initChannel(Channel channel) throws Exception {
initChannelMethod.invoke(oldChannelInitializer, channel);
PlayerChannelHandlerLegacy channelHandler = new PlayerChannelHandlerLegacy();
if (channel.pipeline().get("packet_handler") != null) {
String handlerName = PacketEvents.get().getHandlerName();
if (channel.pipeline().get(handlerName) != null) {
PacketEvents.get().getPlugin().getLogger().warning("[PacketEvents] Attempted to initialize a channel twice!");
} else {
channel.pipeline().addBefore("packet_handler", handlerName, channelHandler);
if (channel.getClass().equals(NioSocketChannel.class)
|| channel.getClass().equals(EpollSocketChannel.class)) {
if (channel.pipeline().get("packet_handler") != null) {
String handlerName = PacketEvents.get().getHandlerName();
if (channel.pipeline().get(handlerName) != null) {
PacketEvents.get().getPlugin().getLogger().warning("[PacketEvents] Attempted to initialize a channel twice!");
} else {
channel.pipeline().addBefore("packet_handler", handlerName, channelHandler);
}
}
}
}
@@ -21,7 +21,9 @@ package io.github.retrooper.packetevents.injector.legacy.late;
import io.github.retrooper.packetevents.PacketEvents;
import io.github.retrooper.packetevents.injector.LateInjector;
import io.github.retrooper.packetevents.injector.legacy.PlayerChannelHandlerLegacy;
import io.netty.channel.epoll.EpollSocketChannel;
import net.minecraft.util.io.netty.channel.Channel;
import net.minecraft.util.io.netty.channel.socket.nio.NioSocketChannel;
import org.bukkit.entity.Player;
public class LateChannelInjectorLegacy implements LateInjector {
@@ -40,7 +42,10 @@ public class LateChannelInjectorLegacy implements LateInjector {
PlayerChannelHandlerLegacy playerChannelHandlerLegacy = new PlayerChannelHandlerLegacy();
playerChannelHandlerLegacy.player = player;
Channel channel = (Channel) PacketEvents.get().getPlayerUtils().getChannel(player);
channel.pipeline().addBefore("packet_handler", PacketEvents.get().getHandlerName(), playerChannelHandlerLegacy);
if (channel.getClass().equals(NioSocketChannel.class)
|| channel.getClass().equals(EpollSocketChannel.class)) {
channel.pipeline().addBefore("packet_handler", PacketEvents.get().getHandlerName(), playerChannelHandlerLegacy);
}
}
@Override
@@ -61,6 +66,18 @@ public class LateChannelInjectorLegacy implements LateInjector {
return channel.pipeline().get(PacketEvents.get().getHandlerName()) != null;
}
@Override
public void writePacket(Object ch, Object rawNMSPacket) {
Channel channel = (Channel) ch;
channel.write(rawNMSPacket);
}
@Override
public void flushPackets(Object ch) {
Channel channel = (Channel) ch;
channel.flush();
}
@Override
public void sendPacket(Object rawChannel, Object packet) {
Channel channel = (Channel) rawChannel;
@@ -1,6 +1,6 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2021 retrooper and contributors
* This file is part of ViaVersion - https://github.com/ViaVersion/ViaVersion
* Copyright (C) 2016-2021 ViaVersion 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
@@ -21,10 +21,11 @@ package io.github.retrooper.packetevents.injector.modern;
import io.github.retrooper.packetevents.PacketEvents;
import io.github.retrooper.packetevents.processor.PacketProcessorInternal;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import org.bukkit.entity.Player;
@ChannelHandler.Sharable
public class PlayerChannelHandlerModern extends ChannelDuplexHandler {
/**
* Associated player.
@@ -29,6 +29,8 @@ import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.epoll.EpollSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.bukkit.entity.Player;
import org.bukkit.plugin.PluginDescriptionFile;
@@ -73,10 +75,10 @@ public class EarlyChannelInjectorModern implements EarlyInjector {
@Override
public void inject() {
try {
if (PaperChannelInjector.PAPER_INJECTION_METHOD) {
/* if (PaperChannelInjector.PAPER_INJECTION_METHOD) {
PaperChannelInjector.setPaperChannelInitializeListener();
return;
}
}*/
Object serverConnection = NMSUtils.getMinecraftServerConnection();
for (Field field : serverConnection.getClass().getDeclaredFields()) {
field.setAccessible(true);
@@ -128,9 +130,11 @@ public class EarlyChannelInjectorModern implements EarlyInjector {
List<Object> networkManagers = NMSUtils.getNetworkManagers();
synchronized (networkManagers) {
for (Object networkManager : networkManagers) {
WrappedPacket networkManagerWrapper = new WrappedPacket(new NMSPacket(networkManager));
WrappedPacket networkManagerWrapper = new WrappedPacket(new NMSPacket(networkManager), NMSUtils.networkManagerClass);
Channel channel = (Channel) networkManagerWrapper.readObject(0, NMSUtils.nettyChannelClass);
if (channel == null) {
if (channel == null ||
(!(channel.getClass().equals(NioSocketChannel.class))) &&
!(channel.getClass().equals(EpollSocketChannel.class))) {
continue;
}
@@ -195,13 +199,13 @@ public class EarlyChannelInjectorModern implements EarlyInjector {
@Override
public void eject() {
// TODO: Uninject from players currently online to prevent protocol lib issues.
if (PaperChannelInjector.PAPER_INJECTION_METHOD) {
/* if (PaperChannelInjector.PAPER_INJECTION_METHOD) {
try {
PaperChannelInjector.removePaperChannelInitializeListener();
} catch (ReflectiveOperationException e) {
e.printStackTrace();
}
}
}*/
Field childHandlerField = null;
for (ChannelFuture future : injectedFutures) {
List<String> names = future.channel().pipeline().names();
@@ -288,6 +292,18 @@ public class EarlyChannelInjectorModern implements EarlyInjector {
return handler != null && handler.player != null;
}
@Override
public void writePacket(Object ch, Object rawNMSPacket) {
Channel channel = (Channel) ch;
channel.write(rawNMSPacket);
}
@Override
public void flushPackets(Object ch) {
Channel channel = (Channel) ch;
channel.flush();
}
@Override
public void sendPacket(Object ch, Object rawNMSPacket) {
Channel channel = (Channel) ch;
@@ -23,6 +23,8 @@ import io.github.retrooper.packetevents.injector.modern.PlayerChannelHandlerMode
import io.github.retrooper.packetevents.utils.reflection.Reflection;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.epoll.EpollSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import java.lang.reflect.Method;
@@ -36,13 +38,16 @@ public class PEChannelInitializerModern extends ChannelInitializer<Channel> {
}
public static void postInitChannel(Channel channel) {
PlayerChannelHandlerModern channelHandler = new PlayerChannelHandlerModern();
if (channel.pipeline().get("packet_handler") != null) {
String handlerName = PacketEvents.get().getHandlerName();
if (channel.pipeline().get(handlerName) != null) {
PacketEvents.get().getPlugin().getLogger().warning("[PacketEvents] Attempted to initialize a channel twice!");
} else {
channel.pipeline().addBefore("packet_handler", handlerName, channelHandler);
if (channel.getClass().equals(NioSocketChannel.class)
|| channel.getClass().equals(EpollSocketChannel.class)) {
PlayerChannelHandlerModern channelHandler = new PlayerChannelHandlerModern();
if (channel.pipeline().get("packet_handler") != null) {
String handlerName = PacketEvents.get().getHandlerName();
if (channel.pipeline().get(handlerName) != null) {
PacketEvents.get().getPlugin().getLogger().warning("[PacketEvents] Attempted to initialize a channel twice!");
} else {
channel.pipeline().addBefore("packet_handler", handlerName, channelHandler);
}
}
}
}
@@ -22,6 +22,8 @@ import io.github.retrooper.packetevents.PacketEvents;
import io.github.retrooper.packetevents.injector.LateInjector;
import io.github.retrooper.packetevents.injector.modern.PlayerChannelHandlerModern;
import io.netty.channel.Channel;
import io.netty.channel.epoll.EpollSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.bukkit.entity.Player;
public class LateChannelInjectorModern implements LateInjector {
@@ -40,7 +42,10 @@ public class LateChannelInjectorModern implements LateInjector {
PlayerChannelHandlerModern playerChannelHandlerModern = new PlayerChannelHandlerModern();
playerChannelHandlerModern.player = player;
Channel channel = (Channel) PacketEvents.get().getPlayerUtils().getChannel(player);
channel.pipeline().addBefore("packet_handler", PacketEvents.get().getHandlerName(), playerChannelHandlerModern);
if (channel.getClass().equals(NioSocketChannel.class) ||
channel.getClass().equals(EpollSocketChannel.class)) {
channel.pipeline().addBefore("packet_handler", PacketEvents.get().getHandlerName(), playerChannelHandlerModern);
}
}
@Override
@@ -62,6 +67,18 @@ public class LateChannelInjectorModern implements LateInjector {
return channel.pipeline().get(PacketEvents.get().getHandlerName()) != null;
}
@Override
public void writePacket(Object ch, Object rawNMSPacket) {
Channel channel = (Channel) ch;
channel.write(rawNMSPacket);
}
@Override
public void flushPackets(Object ch) {
Channel channel = (Channel) ch;
channel.flush();
}
@Override
public void sendPacket(Object rawChannel, Object packet) {
Channel channel = (Channel) rawChannel;
@@ -39,6 +39,7 @@ public class PacketType {
*/
public static final byte INVALID = -128;
public static final Map<Class<?>, Byte> packetIDMap = new IdentityHashMap<>();
private static final boolean isNine = ServerVersion.getVersion().isNewerThanOrEquals(ServerVersion.v_1_9);
private static void insertPacketID(Class<?> cls, byte packetID) {
if (cls != null) {
@@ -220,7 +221,7 @@ public class PacketType {
insertPacketID(PacketTypeClasses.Play.Client.POSITION, POSITION);
insertPacketID(PacketTypeClasses.Play.Client.POSITION_LOOK, POSITION_LOOK);
insertPacketID(PacketTypeClasses.Play.Client.LOOK, LOOK);
insertPacketID(PacketTypeClasses.Play.Client.FLYING, FLYING);
insertPacketID(PacketTypeClasses.Play.Client.GROUND, FLYING);
insertPacketID(PacketTypeClasses.Play.Client.VEHICLE_MOVE, VEHICLE_MOVE);
insertPacketID(PacketTypeClasses.Play.Client.BOAT_MOVE, BOAT_MOVE);
insertPacketID(PacketTypeClasses.Play.Client.PICK_ITEM, PICK_ITEM);
@@ -286,10 +287,7 @@ public class PacketType {
* @return Has the client placed a block?
*/
public static boolean isBlockPlace(final byte packetID) {
final ServerVersion version = PacketEvents.get().getServerUtils().getVersion();
return version.isNewerThan(ServerVersion.v_1_8_8) ?
packetID == PacketType.Play.Client.USE_ITEM
: packetID == PacketType.Play.Client.BLOCK_PLACE;
return isNine ? packetID == PacketType.Play.Client.USE_ITEM : packetID == PacketType.Play.Client.BLOCK_PLACE;
}
}
}
@@ -139,7 +139,7 @@ public class PacketTypeClasses {
public static class Client {
private static String COMMON_PREFIX;
private static String PREFIX;
public static Class<?> FLYING, POSITION, POSITION_LOOK, LOOK, CLIENT_COMMAND,
public static Class<?> FLYING, POSITION, POSITION_LOOK, LOOK, GROUND, CLIENT_COMMAND,
TRANSACTION, BLOCK_DIG, ENTITY_ACTION, USE_ENTITY,
WINDOW_CLICK, STEER_VEHICLE, CUSTOM_PAYLOAD, ARM_ANIMATION,
BLOCK_PLACE, USE_ITEM, ABILITIES, HELD_ITEM_SLOT,
@@ -172,7 +172,12 @@ public class PacketTypeClasses {
POSITION_LOOK = SubclassUtil.getSubClass(FLYING, "PacketPlayInPositionLook");
LOOK = SubclassUtil.getSubClass(FLYING, "PacketPlayInLook");
}
if (PacketEvents.get().getServerUtils().getVersion().isNewerThanOrEquals(ServerVersion.v_1_17)) {
GROUND = SubclassUtil.getSubClass(FLYING, "d");
}
else {
GROUND = FLYING;
}
//This packet does not exist in the 1.17+ protocol
TRANSACTION = Reflection.getClassByNameWithoutException(COMMON_PREFIX + "Transaction");
//This packet was added in 1.17 protocol
@@ -394,8 +399,12 @@ public class PacketTypeClasses {
SET_SUBTITLE_TEXT = Reflection.getClassByNameWithoutException(PREFIX + "ClientboundSetSubtitleTextPacket");
SET_TITLES_ANIMATION = Reflection.getClassByNameWithoutException(PREFIX + "ClientboundSetTitlesAnimationPacket");
SET_TITLE_TEXT = Reflection.getClassByNameWithoutException(PREFIX + "ClientboundSetTitleTextPacket");
// 1.18+ only, doesn't follow the naming convention
if (MAP_CHUNK == null) {
MAP_CHUNK = Reflection.getClassByNameWithoutException("net.minecraft.network.protocol.game.ClientboundLevelChunkWithLightPacket");
}
}
}
}
}
@@ -34,6 +34,7 @@ import io.github.retrooper.packetevents.utils.vector.Vector3i;
import io.github.retrooper.packetevents.utils.world.Difficulty;
import io.github.retrooper.packetevents.utils.world.Dimension;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.Nullable;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
@@ -50,10 +51,10 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
public class WrappedPacket implements WrapperPacketReader, WrapperPacketWriter {
private static final Map<Class<? extends WrappedPacket>, Boolean> LOADED_WRAPPERS = new ConcurrentHashMap<>();
private static final Map<Class<?>, Map<Class<?>, Field[]>> FIELD_CACHE = new ConcurrentHashMap<>();
private static final Field[] EMPTY_FIELD_ARRAY = new Field[0];
private static byte isVersion_1_17 = -1;
public static ServerVersion version;
protected final NMSPacket packet;
private final Class<?> packetClass;
@@ -382,6 +383,9 @@ public class WrappedPacket implements WrapperPacketReader, WrapperPacketWriter {
public void writeAnyObject(int index, Object value) {
try {
Field f = packetClass.getDeclaredFields()[index];
if (!f.isAccessible()) {
f.setAccessible(true);
}
f.set(packet.getRawNMSPacket(), value);
} catch (Exception e) {
throw new WrapperFieldNotFoundException("PacketEvents failed to find any field indexed " + index + " in the " + ClassUtil.getClassSimpleName(packetClass) + " class!");
@@ -392,8 +396,7 @@ public class WrappedPacket implements WrapperPacketReader, WrapperPacketWriter {
public void writeEnumConstant(int index, Enum<?> enumConstant) {
try {
write(enumConstant.getClass(), index, enumConstant);
}
catch (WrapperFieldNotFoundException ex) {
} catch (WrapperFieldNotFoundException ex) {
write(enumConstant.getDeclaringClass(), index, enumConstant);
}
}
@@ -413,9 +416,22 @@ public class WrappedPacket implements WrapperPacketReader, WrapperPacketWriter {
public Vector3i readBlockPosition(int index) {
Object blockPosObj = readObject(index, NMSUtils.blockPosClass);
try {
int x = (int) NMSUtils.getBlockPosX.invoke(blockPosObj);
int y = (int) NMSUtils.getBlockPosY.invoke(blockPosObj);
int z = (int) NMSUtils.getBlockPosZ.invoke(blockPosObj);
int x = (Integer) NMSUtils.getBlockPosX.invoke(blockPosObj);
int y = (Integer) NMSUtils.getBlockPosY.invoke(blockPosObj);
int z = (Integer) NMSUtils.getBlockPosZ.invoke(blockPosObj);
return new Vector3i(x, y, z);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
return null;
}
}
public Vector3i readSectionPosition(int index) {
Object blockPosObj = readObject(index, NMSUtils.sectionPositionClass);
try {
int x = (Integer) NMSUtils.getBlockPosX.invoke(blockPosObj);
int y = (Integer) NMSUtils.getBlockPosY.invoke(blockPosObj);
int z = (Integer) NMSUtils.getBlockPosZ.invoke(blockPosObj);
return new Vector3i(x, y, z);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
@@ -438,13 +454,19 @@ public class WrappedPacket implements WrapperPacketReader, WrapperPacketWriter {
write(NMSUtils.nmsItemStackClass, index, nmsItemStack);
}
@Nullable
public GameMode readGameMode(int index) {
Enum<?> enumConst = readEnumConstant(index, NMSUtils.enumGameModeClass);
return GameMode.values()[enumConst.ordinal() - 1];
int targetIndex = enumConst.ordinal() - 1;
if (targetIndex == -1) {
return null;
}
return GameMode.values()[targetIndex];
}
public void writeGameMode(int index, GameMode gameMode) {
Enum<?> enumConst = EnumUtil.valueByIndex(NMSUtils.enumGameModeClass, gameMode.ordinal() + 1);
public void writeGameMode(int index, @Nullable GameMode gameMode) {
int i = gameMode != null ? (gameMode.ordinal() + 1) : (0);
Enum<?> enumConst = EnumUtil.valueByIndex(NMSUtils.enumGameModeClass, i);
writeEnumConstant(index, enumConst);
}
@@ -491,6 +513,27 @@ public class WrappedPacket implements WrapperPacketReader, WrapperPacketWriter {
write(NMSUtils.iChatBaseComponentClass, index, iChatBaseComponent);
}
public String readMinecraftKey(int index) {
if (isVersion_1_17 == -1) {
isVersion_1_17 = (byte) (version.isNewerThanOrEquals(ServerVersion.v_1_17) ? 1 : 0);
}
int namespaceIndex = isVersion_1_17 == 1 ? 2 : 0;
int keyIndex = isVersion_1_17 == 1 ? 3 : 1;
Object minecraftKey = readObject(index, NMSUtils.minecraftKeyClass);
WrappedPacket minecraftKeyWrapper = new WrappedPacket(new NMSPacket(minecraftKey));
return minecraftKeyWrapper.readString(namespaceIndex) + ":" + minecraftKeyWrapper.readString(keyIndex);
}
public void writeMinecraftKey(int index, String content) {
Object minecraftKey = null;
try {
minecraftKey = NMSUtils.minecraftKeyConstructor.newInstance(content);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
write(NMSUtils.minecraftKeyClass, index, minecraftKey);
}
public List<Object> readList(int index) {
return read(index, List.class);
}
@@ -40,6 +40,12 @@ public class WrappedPacketLoginOutCustomPayload extends WrappedPacket implements
super(packet);
}
public WrappedPacketLoginOutCustomPayload(int messageID, String channelName, byte[] data) {
this.messageID = messageID;
this.channelName = channelName;
this.data = data;
}
@Override
protected void load() {
v_1_17 = version.isNewerThanOrEquals(ServerVersion.v_1_17);
@@ -78,8 +84,7 @@ public class WrappedPacketLoginOutCustomPayload extends WrappedPacket implements
public String getChannelName() {
if (packet != null) {
Object minecraftKey = readObject(0, NMSUtils.minecraftKeyClass);
return NMSUtils.getStringFromMinecraftKey(minecraftKey);
return readMinecraftKey(0);
}
else {
return channelName;
@@ -88,8 +93,7 @@ public class WrappedPacketLoginOutCustomPayload extends WrappedPacket implements
public void setChannelName(String channelName) {
if (packet != null) {
Object minecraftKey = NMSUtils.generateMinecraftKey(channelName);
writeObject(0, minecraftKey);
writeMinecraftKey(0, channelName);
} else {
this.channelName = channelName;
}
@@ -123,7 +127,7 @@ public class WrappedPacketLoginOutCustomPayload extends WrappedPacket implements
@Override
public Object asNMSPacket() throws Exception {
Object byteBufObject = PacketEvents.get().getByteBufUtil().newByteBuf(data);
Object minecraftKey = NMSUtils.generateMinecraftKey(channelName);
Object minecraftKey = NMSUtils.generateMinecraftKeyNew(channelName);
Object dataSerializer = packetDataSerializerConstructor.newInstance(byteBufObject);
return constructor.newInstance(getMessageId(), minecraftKey, dataSerializer);
}
@@ -29,27 +29,18 @@ import io.github.retrooper.packetevents.utils.vector.Vector3i;
import java.lang.reflect.InvocationTargetException;
final class WrappedPacketInBlockPlace_1_9 extends WrappedPacket {
private static Class<?> movingObjectPositionBlockClass;
private Object movingObjPos;
public WrappedPacketInBlockPlace_1_9(final NMSPacket packet) {
super(packet);
}
@Override
protected void load() {
movingObjectPositionBlockClass = NMSUtils.getNMSClassWithoutException("MovingObjectPositionBlock");
if (movingObjectPositionBlockClass == null) {
movingObjectPositionBlockClass = NMSUtils.getNMClassWithoutException("world.phys.MovingObjectPositionBlock");
}
}
public Vector3i getBlockPosition() {
if (movingObjectPositionBlockClass == null) {
if (NMSUtils.movingObjectPositionBlockClass == null) {
return readBlockPosition(0);
} else {
if (movingObjPos == null) {
movingObjPos = readObject(0, movingObjectPositionBlockClass);
movingObjPos = readObject(0, NMSUtils.movingObjectPositionBlockClass);
}
WrappedPacket movingObjectPosWrapper = new WrappedPacket(new NMSPacket(movingObjPos));
return movingObjectPosWrapper.readBlockPosition(0);
@@ -57,11 +48,11 @@ final class WrappedPacketInBlockPlace_1_9 extends WrappedPacket {
}
public void setBlockPosition(Vector3i blockPos) {
if (movingObjectPositionBlockClass == null) {
if (NMSUtils.movingObjectPositionBlockClass == null) {
writeBlockPosition(0, blockPos);
} else {
if (movingObjPos == null) {
movingObjPos = readObject(0, movingObjectPositionBlockClass);
movingObjPos = readObject(0, NMSUtils.movingObjectPositionBlockClass);
}
WrappedPacket movingObjectPosWrapper = new WrappedPacket(new NMSPacket(movingObjPos));
movingObjectPosWrapper.writeBlockPosition(0, blockPos);
@@ -70,11 +61,11 @@ final class WrappedPacketInBlockPlace_1_9 extends WrappedPacket {
public Direction getDirection() {
Enum<?> enumConst;
if (movingObjectPositionBlockClass == null) {
if (NMSUtils.movingObjectPositionBlockClass == null) {
enumConst = readEnumConstant(0, NMSUtils.enumDirectionClass);
} else {
if (movingObjPos == null) {
movingObjPos = readObject(0, movingObjectPositionBlockClass);
movingObjPos = readObject(0, NMSUtils.movingObjectPositionBlockClass);
}
WrappedPacket movingObjectPosWrapper = new WrappedPacket(new NMSPacket(movingObjPos));
enumConst = movingObjectPosWrapper.readEnumConstant(0, NMSUtils.enumDirectionClass);
@@ -84,11 +75,11 @@ final class WrappedPacketInBlockPlace_1_9 extends WrappedPacket {
public void setDirection(Direction direction) {
Enum<?> enumConst = EnumUtil.valueByIndex(NMSUtils.enumDirectionClass, direction.ordinal());
if (movingObjectPositionBlockClass == null) {
if (NMSUtils.movingObjectPositionBlockClass == null) {
writeEnumConstant(0, enumConst);
} else {
if (movingObjPos == null) {
movingObjPos = readObject(0, movingObjectPositionBlockClass);
movingObjPos = readObject(0, NMSUtils.movingObjectPositionBlockClass);
}
WrappedPacket movingObjectPosWrapper = new WrappedPacket(new NMSPacket(movingObjPos));
movingObjectPosWrapper.writeEnumConstant(0, enumConst);
@@ -37,9 +37,8 @@ public final class WrappedPacketInClientCommand extends WrappedPacket {
@Override
protected void load() {
v_1_16 = version.isNewerThanOrEquals(ServerVersion.v_1_16);
try {
enumClientCommandClass = NMSUtils.getNMSEnumClass("EnumClientCommand");
} catch (ClassNotFoundException e) {
enumClientCommandClass = NMSUtils.getNMSEnumClassWithoutException("EnumClientCommand");
if (enumClientCommandClass == null) {
//Probably a subclass
enumClientCommandClass = SubclassUtil.getEnumSubClass(PacketTypeClasses.Play.Client.CLIENT_COMMAND, "EnumClientCommand");
}
@@ -28,7 +28,7 @@ import io.github.retrooper.packetevents.utils.server.ServerVersion;
import org.bukkit.entity.Player;
public final class WrappedPacketInCustomPayload extends WrappedPacket {
private static boolean v_1_17, strPresent, byteArrayPresent;
private static boolean strPresent, byteArrayPresent;
public WrappedPacketInCustomPayload(NMSPacket packet) {
super(packet);
@@ -36,27 +36,23 @@ public final class WrappedPacketInCustomPayload extends WrappedPacket {
@Override
protected void load() {
Class<?> packetClass = PacketTypeClasses.Play.Client.CUSTOM_PAYLOAD;
strPresent = Reflection.getField(packetClass, String.class, 0) != null;
byteArrayPresent = Reflection.getField(packetClass, byte[].class, 0) != null;
v_1_17 = version.isNewerThanOrEquals(ServerVersion.v_1_17);
strPresent = Reflection.getField(PacketTypeClasses.Play.Client.CUSTOM_PAYLOAD, String.class, 0) != null;
byteArrayPresent = Reflection.getField(PacketTypeClasses.Play.Client.CUSTOM_PAYLOAD, byte[].class, 0) != null;
}
public String getTag() {
public String getChannelName() {
if (strPresent) {
return readString(0);
} else {
Object minecraftKey = readObject(v_1_17 ? 1 : 0, NMSUtils.minecraftKeyClass);
return NMSUtils.getStringFromMinecraftKey(minecraftKey);
return readMinecraftKey(1);
}
}
public void setTag(String tag) {
public void setChannelName(String channelName) {
if (strPresent) {
writeString(0, tag);
writeString(0, channelName);
} else {
Object minecraftKey = NMSUtils.generateMinecraftKey(tag);
write(NMSUtils.minecraftKeyClass, v_1_17 ? 1 : 0, minecraftKey);
writeMinecraftKey(1, channelName);
}
}
@@ -1,3 +1,21 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2021 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 io.github.retrooper.packetevents.packetwrappers.play.in.jigsawgenerate;
import io.github.retrooper.packetevents.packetwrappers.NMSPacket;
@@ -8,7 +26,6 @@ import io.github.retrooper.packetevents.utils.vector.Vector3i;
* Sent when Generate is pressed on the Jigsaw Block interface.
*
* @author Tecnio
* @see <a href="https://wiki.vg/Protocol#Generate_Structure"</a>
*/
public class WrappedPacketInJigsawGenerate extends WrappedPacket {
@@ -1,21 +1,19 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2021 retrooper and contributors
*
* * This file is part of packetevents - https://github.com/retrooper/packetevents
* * Copyright (C) 2016-2021 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/>.
* 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 io.github.retrooper.packetevents.packetwrappers.play.in.pong;
@@ -32,7 +32,7 @@ import java.util.Set;
public class WrappedPacketInSettings extends WrappedPacket {
private static Class<? extends Enum<?>> chatVisibilityEnumClass;
private static boolean isLowerThan_v_1_8, v_1_17;
private static boolean isLowerThan_v_1_8, v_1_17, v_1_18;
public WrappedPacketInSettings(final NMSPacket packet) {
super(packet);
@@ -42,6 +42,7 @@ public class WrappedPacketInSettings extends WrappedPacket {
protected void load() {
isLowerThan_v_1_8 = version.isOlderThan(ServerVersion.v_1_8);
v_1_17 = version.isNewerThanOrEquals(ServerVersion.v_1_17);
v_1_18 = version.isNewerThanOrEquals(ServerVersion.v_1_18);
chatVisibilityEnumClass = NMSUtils.getNMSEnumClassWithoutException("EnumChatVisibility");
if (chatVisibilityEnumClass == null) {
//They are on 1.17+
@@ -62,11 +63,11 @@ public class WrappedPacketInSettings extends WrappedPacket {
}
public int getViewDistance() {
return readInt(v_1_17 ? 1 : 0);
return readInt((v_1_17 && !v_1_18) ? 1 : 0);
}
public void setViewDistance(int viewDistance) {
writeInt(v_1_17 ? 1 : 0, viewDistance);
writeInt((v_1_17 && !v_1_18) ? 1 : 0, viewDistance);
}
public ChatVisibility getChatVisibility() {
@@ -87,19 +88,37 @@ public class WrappedPacketInSettings extends WrappedPacket {
writeBoolean(0, chatColors);
}
public Optional<Boolean> isTextFilteringEnabled() {
if (!v_1_17) {
return Optional.empty();
//Added in 1.17
public boolean isTextFilteringEnabled() {
if (v_1_17) {
return readBoolean(1);
}
return Optional.of(!readBoolean(1));
return false;
}
public void setTextFilteringEnabled(boolean textFilteringEnabled) {
//Added in 1.17
public void setTextFilteringEnabled(boolean enabled) {
if (v_1_17) {
writeBoolean(1, !textFilteringEnabled);
writeBoolean(1, enabled);
}
}
//Added in 1.18
public boolean isServerListingsAllowed() {
if (v_1_18) {
return readBoolean(2);
}
return true;
}
//Added in 1.18
public void setServerListingsAllowed(boolean allowed) {
if (v_1_18) {
writeBoolean(2, allowed);
}
}
public byte getDisplaySkinPartsMask() {
byte mask = 0;
if (isLowerThan_v_1_8) {
@@ -108,7 +127,7 @@ public class WrappedPacketInSettings extends WrappedPacket {
mask |= 0x01;
}
} else {
mask = (byte) readInt(v_1_17 ? 2 : 1);
mask = (byte) readInt((v_1_17 && !v_1_18) ? 2 : 1);
}
return mask;
}
@@ -118,7 +137,7 @@ public class WrappedPacketInSettings extends WrappedPacket {
boolean capeEnabled = (mask & 0x01) == 0x01;
writeBoolean(1, capeEnabled);
} else {
writeInt(v_1_17 ? 2 : 1, mask);
writeInt((v_1_17 && !v_1_18) ? 2 : 1, mask);
}
}
@@ -133,11 +133,12 @@ public final class WrappedPacketInUseEntity extends WrappedPacketEntityAbstracti
return action;
}
//TODO Finish this
protected void setAction(EntityUseAction action) {
this.action = action;
Enum<?> enumConst = EnumUtil.valueByIndex((Class<? extends Enum<?>>) enumEntityUseActionClass, action.ordinal());
if (v_1_17) {
//TODO Add 1.17 support
//TODO Add 1.17+ support
}
else {
writeEnumConstant(0, enumConst);
@@ -0,0 +1,81 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2021 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 io.github.retrooper.packetevents.packetwrappers.play.in.useitem;
import io.github.retrooper.packetevents.packetwrappers.NMSPacket;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.utils.enums.EnumUtil;
import io.github.retrooper.packetevents.utils.nms.NMSUtils;
import io.github.retrooper.packetevents.utils.player.Hand;
import io.github.retrooper.packetevents.utils.reflection.Reflection;
import io.github.retrooper.packetevents.utils.server.ServerVersion;
import io.github.retrooper.packetevents.utils.vector.Vector3i;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
public class WrappedPacketInUseItem extends WrappedPacket {
private static boolean v_1_14;
public WrappedPacketInUseItem(final NMSPacket packet) {
super(packet);
}
@Override
protected void load() {
v_1_14 = version.isNewerThanOrEquals(ServerVersion.v_1_14);
}
public Hand getHand() {
return Hand.values()[readEnumConstant(0, NMSUtils.enumHandClass).ordinal()];
}
public void setHand(Hand hand) {
Enum<?> enumConstant = EnumUtil.valueByIndex(NMSUtils.enumHandClass, hand.ordinal());
writeEnumConstant(0, enumConstant);
}
public Vector3i getBlockPosition() {
if (v_1_14) {
Object movingBlockPosition = readObject(0, NMSUtils.movingObjectPositionBlockClass);
WrappedPacket movingBlockPositionWrapper = new WrappedPacket(new NMSPacket(movingBlockPosition));
return movingBlockPositionWrapper.readBlockPosition(0);
}
else {
return readBlockPosition(0);
}
}
public void setBlockPosition(Vector3i blockPosition) {
if (v_1_14) {
Object movingBlockPosition = readObject(0, NMSUtils.movingObjectPositionBlockClass);
WrappedPacket movingBlockPositionWrapper = new WrappedPacket(new NMSPacket(movingBlockPosition));
movingBlockPositionWrapper.writeBlockPosition(0, blockPosition);
}
else {
writeBlockPosition(0, blockPosition);
}
}
@Override
public boolean isSupported() {
return version.isNewerThanOrEquals(ServerVersion.v_1_9);
}
}
@@ -37,7 +37,6 @@ public class WrappedPacketInVehicleMove extends WrappedPacket {
writeDouble(2, position.z);
}
//TODO Cut off at 1.8.1
@Deprecated
public double getX() {
return readDouble(0);
@@ -18,25 +18,16 @@
package io.github.retrooper.packetevents.packetwrappers.play.in.windowclick;
import io.github.retrooper.packetevents.packettype.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.NMSPacket;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.utils.enums.EnumUtil;
import io.github.retrooper.packetevents.utils.nms.NMSUtils;
import io.github.retrooper.packetevents.utils.reflection.Reflection;
import io.github.retrooper.packetevents.utils.server.ServerVersion;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Optional;
public class WrappedPacketInWindowClick extends WrappedPacket {
private static boolean v_1_17;
private static boolean legacy, v_1_17;
private static Class<? extends Enum<?>> invClickTypeClass;
private static boolean isClickModePrimitive;
public WrappedPacketInWindowClick(NMSPacket packet) {
super(packet);
@@ -44,53 +35,60 @@ public class WrappedPacketInWindowClick extends WrappedPacket {
@Override
protected void load() {
legacy = version.isOlderThanOrEquals(ServerVersion.v_1_8_8);
v_1_17 = version.isNewerThanOrEquals(ServerVersion.v_1_17);
invClickTypeClass = NMSUtils.getNMSEnumClassWithoutException("InventoryClickType");
if (invClickTypeClass == null) {
invClickTypeClass = NMSUtils.getNMEnumClassWithoutException("world.inventory.InventoryClickType");
}
isClickModePrimitive = Reflection.getField(PacketTypeClasses.Play.Client.WINDOW_CLICK, int.class, 3) != null;
}
// Unique ID for the inventory, 0 for player's inventory
public int getWindowId() {
return readInt(0);
return readInt(v_1_17 ? 1 : 0);
}
public void setWindowId(int windowID) {
writeInt(0, windowID);
writeInt(v_1_17 ? 1 : 0, windowID);
}
// Id of clicked slot
public int getWindowSlot() {
return readInt(1);
return readInt(v_1_17 ? 3 : 1);
}
public void setWindowSlot(int slot) {
writeInt(1, slot);
writeInt(v_1_17 ? 3 : 1, slot);
}
// Left or right click
public int getWindowButton() {
return readInt(2);
return readInt(v_1_17 ? 4 : 2);
}
public void setWindowButton(int button) {
writeInt(2, button);
writeInt(v_1_17 ? 4 : 2, button);
}
public Optional<Short> getActionNumber() {
// Used to sync together client and server
public int getActionNumber() {
if (v_1_17) {
return Optional.empty();
return readInt(2);
}
return Optional.of(readShort(0));
return readShort(0);
}
public void setActionNumber(short actionNumber) {
if (!v_1_17) {
writeShort(0, actionNumber);
public void setActionNumber(int actionNumber) {
if (v_1_17) {
writeInt(2, actionNumber);
} else {
writeShort(0, (short) actionNumber);
}
}
// Type of click - shift clicking, hotbar, drag, pickup...
public int getMode() {
if (isClickModePrimitive) {
if(legacy) {
return readInt(3);
} else {
Enum<?> enumConst = readEnumConstant(0, invClickTypeClass);
@@ -99,7 +97,7 @@ public class WrappedPacketInWindowClick extends WrappedPacket {
}
public void setMode(int mode) {
if (isClickModePrimitive) {
if(legacy) {
writeInt(3, mode);
} else {
Enum<?> enumConst = EnumUtil.valueByIndex(invClickTypeClass, mode);
@@ -117,6 +115,6 @@ public class WrappedPacketInWindowClick extends WrappedPacket {
}
public void setClickedItemStack(ItemStack stack) {
writeItemStack(0, stack);
writeItemStack(0, stack);
}
}
@@ -1,3 +1,21 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2021 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 io.github.retrooper.packetevents.packetwrappers.play.out.bedit;
import io.github.retrooper.packetevents.packetwrappers.NMSPacket;
@@ -12,7 +30,6 @@ import java.util.Optional;
/**
* @author Tecnio
* @see <a href="https://wiki.vg/Protocol#Edit_Book"</a>
*/
public class WrappedPacketInBEdit extends WrappedPacket {
private static boolean v_1_13, v_1_17;
@@ -32,7 +32,6 @@ import java.lang.reflect.Constructor;
* This packet is used for a number of actions and animations performed by blocks, usually non-persistent.
*
* @author Tecnio
* @see <a href="https://wiki.vg/Protocol#Block_Action"</a>
*/
public class WrappedPacketOutBlockAction extends WrappedPacket implements SendableWrapper {
@@ -0,0 +1,121 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2021 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 io.github.retrooper.packetevents.packetwrappers.play.out.collect;
import io.github.retrooper.packetevents.packettype.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.NMSPacket;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.packetwrappers.api.SendableWrapper;
import io.github.retrooper.packetevents.utils.server.ServerVersion;
import java.lang.reflect.Constructor;
import java.util.Optional;
public class WrappedPacketOutCollect extends WrappedPacket implements SendableWrapper {
private static boolean v_1_11;
private static Constructor<?> packetConstructor;
private int collectedEntityId, collectorEntityId, itemCount;
public WrappedPacketOutCollect(NMSPacket packet) {
super(packet);
}
public WrappedPacketOutCollect(int collectedEntityId, int collectorEntityId, int itemCount) {
this.collectedEntityId = collectedEntityId;
this.collectorEntityId = collectorEntityId;
this.itemCount = itemCount;
}
@Override
protected void load() {
v_1_11 = version.isNewerThanOrEquals(ServerVersion.v_1_11);
try {
if (v_1_11) {
packetConstructor = PacketTypeClasses.Play.Server.COLLECT.getConstructor(int.class, int.class, int.class);
} else {
packetConstructor = PacketTypeClasses.Play.Server.COLLECT.getConstructor(int.class, int.class);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public int getCollectedEntityId() {
if (packet != null) {
return readInt(0);
} else {
return this.collectedEntityId;
}
}
public void setCollectedEntityId(int id) {
if (packet != null) {
writeInt(0, id);
} else {
this.collectedEntityId = id;
}
}
public int getCollectorEntityId() {
if (packet != null) {
return readInt(1);
} else {
return this.collectorEntityId;
}
}
public void setCollectorEntityId(int id) {
if (packet != null) {
writeInt(1, id);
} else {
this.collectorEntityId = id;
}
}
public Optional<Integer> getItemCount() {
if (!v_1_11) {
return Optional.empty();
}
if (packet != null) {
return Optional.of(readInt(2));
} else {
return Optional.of(this.itemCount);
}
}
public void setItemCount(int count) {
if (v_1_11) {
if (packet != null) {
writeInt(2, count);
} else {
this.itemCount = count;
}
}
}
@Override
public Object asNMSPacket() throws Exception {
/*
* On newer versions the packet has an extra field which is the picked up item count.
*/
return v_1_11
? packetConstructor.newInstance(getCollectedEntityId(), getCollectorEntityId(), (int) (getItemCount().get()))
: packetConstructor.newInstance(getCollectedEntityId(), getCollectorEntityId());
}
}
@@ -35,11 +35,11 @@ public class WrappedPacketOutCustomPayload extends WrappedPacket implements Send
private static int minecraftKeyIndexInClass;
private static byte constructorMode;
private String tag;
private String channelName;
private byte[] data;
public WrappedPacketOutCustomPayload(String tag, byte[] data) {
this.tag = tag;
public WrappedPacketOutCustomPayload(String channelName, byte[] data) {
this.channelName = channelName;
this.data = data;
}
@@ -53,7 +53,7 @@ public class WrappedPacketOutCustomPayload extends WrappedPacket implements Send
try {
packetDataSerializerConstructor = NMSUtils.packetDataSerializerClass.getConstructor(NMSUtils.byteBufClass);
} catch (NullPointerException | NoSuchMethodException e) {
//For some reason some 1.7.10 spigots don't have this constructor although its on normal spigot 1.7.10???
//For some reason some annoying 1.7.10 spigot forks don't have this constructor?
}
//Constructors:
@@ -92,33 +92,35 @@ public class WrappedPacketOutCustomPayload extends WrappedPacket implements Send
}
}
public String getTag() {
public String getChannelName() {
if (packet != null) {
switch (constructorMode) {
case 0:
case 1:
return readString(0);
case 2:
Object minecraftKey = readObject(minecraftKeyIndexInClass, NMSUtils.minecraftKeyClass);
return NMSUtils.getStringFromMinecraftKey(minecraftKey);
return readMinecraftKey(minecraftKeyIndexInClass);
default:
return null;
}
return null;
}
return tag;
else {
return channelName;
}
}
public void setTag(String tag) {
public void setChannelName(String channelName) {
if (packet != null) {
switch (constructorMode) {
case 0:
case 1:
writeString(0, tag);
writeString(0, channelName);
case 2:
Object minecraftKey = NMSUtils.generateMinecraftKey(tag);
write(NMSUtils.minecraftKeyClass, minecraftKeyIndexInClass, minecraftKey);
writeMinecraftKey(0, channelName);
}
} else {
this.tag = tag;
}
else {
this.channelName = channelName;
}
}
@@ -130,8 +132,9 @@ public class WrappedPacketOutCustomPayload extends WrappedPacket implements Send
case 1:
case 2:
return PacketEvents.get().getByteBufUtil().getBytes(getBuffer());
default:
return new byte[0];
}
return new byte[0];
}
return data;
}
@@ -156,7 +159,6 @@ public class WrappedPacketOutCustomPayload extends WrappedPacket implements Send
private Object getBuffer() {
Object dataSerializer = readObject(0, NMSUtils.packetDataSerializerClass);
WrappedPacket dataSerializerWrapper = new WrappedPacket(new NMSPacket(dataSerializer));
return dataSerializerWrapper.readObject(0, NMSUtils.byteBufClass);
}
@@ -182,12 +184,12 @@ public class WrappedPacketOutCustomPayload extends WrappedPacket implements Send
Object dataSerializer;
switch (constructorMode) {
case 0:
return constructor.newInstance(getTag(), data);
return constructor.newInstance(getChannelName(), data);
case 1:
dataSerializer = packetDataSerializerConstructor.newInstance(PacketEvents.get().getByteBufUtil().newByteBuf(data));
return constructor.newInstance(getTag(), dataSerializer);
return constructor.newInstance(getChannelName(), dataSerializer);
case 2:
Object minecraftKey = NMSUtils.generateMinecraftKey(getTag());
Object minecraftKey = NMSUtils.generateMinecraftKeyNew(getChannelName());
dataSerializer = packetDataSerializerConstructor.newInstance(PacketEvents.get().getByteBufUtil().newByteBuf(data));
return constructor.newInstance(minecraftKey, dataSerializer);
default:
@@ -35,11 +35,12 @@ public class WrappedPacketOutEntity extends WrappedPacketEntityAbstraction imple
//Byte = 1.7.10->1.8.8, Int = 1.9->1.15.x, Short = 1.16.x
private static byte mode; //byte = 0, int = 1, short = 2
private static double dXYZDivisor;
private static final float ROTATION_FACTOR = 256.0F / 360.0F;
private static int yawByteIndex = 0;
private static int pitchByteIndex = 1;
private static Constructor<?> entityPacketConstructor, entityRelMovePacketConstructor, entityLookConstructor, entityRelMoveLookConstructor;
private double deltaX, deltaY, deltaZ;
private byte pitch, yaw;
private float pitch, yaw;
private boolean onGround, rotating, moving;
public WrappedPacketOutEntity(NMSPacket packet) {
@@ -48,7 +49,7 @@ public class WrappedPacketOutEntity extends WrappedPacketEntityAbstraction imple
}
public WrappedPacketOutEntity(int entityID, double deltaX, double deltaY, double deltaZ,
byte yaw, byte pitch, boolean onGround, boolean rotating, boolean moving) {
float yaw, float pitch, boolean onGround, boolean rotating, boolean moving) {
this.entityID = entityID;
this.deltaX = deltaX;
this.deltaY = deltaY;
@@ -61,22 +62,22 @@ public class WrappedPacketOutEntity extends WrappedPacketEntityAbstraction imple
}
public WrappedPacketOutEntity(int entityID, double deltaX, double deltaY, double deltaZ,
byte yaw, byte pitch, boolean onGround, boolean rotating) {
float yaw, float pitch, boolean onGround, boolean rotating) {
this(entityID, deltaX, deltaY, deltaZ, yaw, pitch, onGround, rotating, false);
}
public WrappedPacketOutEntity(int entityID, double deltaX, double deltaY, double deltaZ,
byte yaw, byte pitch, boolean onGround) {
float yaw, float pitch, boolean onGround) {
this(entityID, deltaX, deltaY, deltaZ, yaw, pitch, onGround, false, false);
}
public WrappedPacketOutEntity(Entity entity, double deltaX, double deltaY, double deltaZ,
byte yaw, byte pitch, boolean onGround, boolean isLook) {
float yaw, float pitch, boolean onGround, boolean isLook) {
this(entity.getEntityId(), deltaX, deltaY, deltaZ, yaw, pitch, onGround, isLook);
}
public WrappedPacketOutEntity(Entity entity, double deltaX, double deltaY, double deltaZ,
byte yaw, byte pitch, boolean onGround) {
float yaw, float pitch, boolean onGround) {
this(entity.getEntityId(), deltaX, deltaY, deltaZ, yaw, pitch, onGround, false);
}
@@ -116,33 +117,33 @@ public class WrappedPacketOutEntity extends WrappedPacketEntityAbstraction imple
}
public byte getPitch() {
public float getPitch() {
if (packet != null) {
return readByte(pitchByteIndex);
return readByte(pitchByteIndex) / ROTATION_FACTOR;
} else {
return pitch;
}
}
public void setPitch(byte pitch) {
public void setPitch(float pitch) {
if (packet != null) {
writeByte(pitchByteIndex, pitch);
writeByte(pitchByteIndex, (byte) (pitch * ROTATION_FACTOR));
} else {
this.pitch = pitch;
}
}
public byte getYaw() {
public float getYaw() {
if (packet != null) {
return readByte(yawByteIndex);
return readByte(yawByteIndex) / ROTATION_FACTOR;
} else {
return yaw;
}
}
public void setYaw(byte yaw) {
public void setYaw(float yaw) {
if (packet != null) {
writeByte(yawByteIndex, yaw);
writeByte(yawByteIndex, (byte) (yaw * ROTATION_FACTOR));
}
}
@@ -315,10 +316,12 @@ public class WrappedPacketOutEntity extends WrappedPacketEntityAbstraction imple
@Override
public Object asNMSPacket() throws Exception {
if (v_1_17) {
byte angleYaw = (byte) (getYaw() * ROTATION_FACTOR);
byte anglePitch = (byte) (getPitch() * ROTATION_FACTOR);
return entityPacketConstructor.newInstance(getEntityId(),
(short) (getDeltaX() * dXYZDivisor), (short) (getDeltaY() * dXYZDivisor),
(short) (getDeltaZ() * dXYZDivisor),
getYaw(), getPitch(), isOnGround(), isRotating().get(), isMoving().get());
angleYaw, anglePitch, isOnGround(), isRotating().get(), isMoving().get());
} else {
Object packetInstance = entityPacketConstructor.newInstance(getEntityId());
WrappedPacketOutEntity wrapper = new WrappedPacketOutEntity(new NMSPacket(packetInstance));
@@ -343,7 +346,7 @@ public class WrappedPacketOutEntity extends WrappedPacketEntityAbstraction imple
super(packet);
}
public WrappedPacketOutEntityLook(int entityID, byte yaw, byte pitch, boolean onGround) {
public WrappedPacketOutEntityLook(int entityID, float yaw, float pitch, boolean onGround) {
super(entityID, 0, 0, 0, yaw, pitch, onGround, true);
}
@@ -366,7 +369,9 @@ public class WrappedPacketOutEntity extends WrappedPacketEntityAbstraction imple
public Object asNMSPacket() throws Exception {
Object packetInstance;
if (v_1_17) {
packetInstance = entityLookConstructor.newInstance(getEntityId(), getYaw(), getPitch(), isOnGround());
byte angleYaw = (byte) (getYaw() * ROTATION_FACTOR);
byte anglePitch = (byte) (getPitch() * ROTATION_FACTOR);
packetInstance = entityLookConstructor.newInstance(getEntityId(), angleYaw, anglePitch, isOnGround());
}
else {
packetInstance = entityLookConstructor.newInstance();
@@ -389,7 +394,7 @@ public class WrappedPacketOutEntity extends WrappedPacketEntityAbstraction imple
}
public WrappedPacketOutRelEntityMove(int entityID, double deltaX, double deltaY, double deltaZ, boolean onGround) {
super(entityID, deltaX, deltaY, deltaZ, (byte) 0, (byte) 0, onGround, false);
super(entityID, deltaX, deltaY, deltaZ, 0, 0, onGround, false);
}
@Override
@@ -438,7 +443,8 @@ public class WrappedPacketOutEntity extends WrappedPacketEntityAbstraction imple
super(packet);
}
public WrappedPacketOutRelEntityMoveLook(int entityID, double deltaX, double deltaY, double deltaZ, byte yaw, byte pitch, boolean onGround) {
public WrappedPacketOutRelEntityMoveLook(int entityID, double deltaX, double deltaY, double deltaZ,
float yaw, float pitch, boolean onGround) {
super(entityID, deltaX, deltaY, deltaZ, yaw, pitch, onGround, false);
}
@@ -464,7 +470,9 @@ public class WrappedPacketOutEntity extends WrappedPacketEntityAbstraction imple
short dx = (short) (getDeltaX() * dXYZDivisor);
short dy = (short) (getDeltaY() * dXYZDivisor);
short dz = (short) (getDeltaZ() * dXYZDivisor);
packetInstance = entityRelMoveLookConstructor.newInstance(getEntityId(), dx, dy, dz, getYaw(), getPitch(), isOnGround());
byte angleYaw = (byte) (getYaw() * ROTATION_FACTOR);
byte anglePitch = (byte) (getPitch() * ROTATION_FACTOR);
packetInstance = entityRelMoveLookConstructor.newInstance(getEntityId(), dx, dy, dz, angleYaw, anglePitch, isOnGround());
}
else {
packetInstance = entityRelMoveLookConstructor.newInstance();
@@ -20,26 +20,30 @@ package io.github.retrooper.packetevents.packetwrappers.play.out.entitydestroy;
import io.github.retrooper.packetevents.packettype.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.NMSPacket;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.packetwrappers.api.SendableWrapper;
import io.github.retrooper.packetevents.packetwrappers.api.helper.WrappedPacketEntityAbstraction;
import io.github.retrooper.packetevents.utils.nms.NMSUtils;
import io.github.retrooper.packetevents.utils.reflection.Reflection;
import io.github.retrooper.packetevents.utils.server.ServerVersion;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Constructor;
import java.util.Optional;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* @author yanjulang
* @author yanjulang, MWHunter
* @since 1.8
*/
public class WrappedPacketOutEntityDestroy extends WrappedPacketEntityAbstraction implements SendableWrapper {
private static Class<?> INT_COLLECTION_CLASS;
private static Class<?> INT_LIST_CLASS;
private static Class<?> INT_ARRAY_LIST_CLASS;
private static Constructor<?> INT_ARRAY_LIST_CONSTRUCTOR;
private static Method TO_INT_ARRAY_METHOD;
private static boolean v_1_17;
private static boolean v_1_17_1;
private static Constructor<?> packetConstructor;
private int[] entityIds;
private int[] entityIds = new int[0];
public WrappedPacketOutEntityDestroy(NMSPacket packet) {
super(packet);
@@ -60,13 +64,34 @@ public class WrappedPacketOutEntityDestroy extends WrappedPacketEntityAbstractio
@Override
protected void load() {
v_1_17 = version.isNewerThanOrEquals(ServerVersion.v_1_17);
v_1_17_1 = version.isNewerThanOrEquals(ServerVersion.v_1_17_1);
v_1_17 = version.equals(ServerVersion.v_1_17);
if (v_1_17_1) {
if (INT_COLLECTION_CLASS == null) {
INT_COLLECTION_CLASS = Reflection.getClassByNameWithoutException("it.unimi.dsi.fastutil.ints.IntCollection");
INT_LIST_CLASS = Reflection.getClassByNameWithoutException("it.unimi.dsi.fastutil.ints.IntList");
INT_ARRAY_LIST_CLASS = Reflection.getClassByNameWithoutException("it.unimi.dsi.fastutil.ints.IntArrayList");
try {
INT_ARRAY_LIST_CONSTRUCTOR = INT_ARRAY_LIST_CLASS.getConstructor(int[].class);
INT_ARRAY_LIST_CONSTRUCTOR.setAccessible(true);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
try {
TO_INT_ARRAY_METHOD = INT_COLLECTION_CLASS.getDeclaredMethod("toIntArray");
TO_INT_ARRAY_METHOD.setAccessible(true);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}
try {
if (v_1_17) {
packetConstructor =
PacketTypeClasses.Play.Server.ENTITY_DESTROY.getConstructor(int.class);
}
else {
} else {
packetConstructor =
PacketTypeClasses.Play.Server.ENTITY_DESTROY.getConstructor(int[].class);
}
@@ -77,21 +102,29 @@ public class WrappedPacketOutEntityDestroy extends WrappedPacketEntityAbstractio
@Override
public int getEntityId() {
if (entityID != -1 || packet == null) {
if (entityID != -1 || entityIds.length > 0 || packet == null) {
if (v_1_17) {
return entityID;
} else {
return entityIds[0];
}
else {
} else {
if (v_1_17_1) {
Object list = readObject(0, INT_LIST_CLASS);
try {
entityIds = (int[]) TO_INT_ARRAY_METHOD.invoke(list);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
return entityIds[0];
} else if (v_1_17) {
return entityID = readInt(0);
} else {
entityIds = readIntArray(0);
return entityIds[0];
}
}
if (v_1_17) {
entityID = readInt(0);
}
else {
entityID = readIntArray(0)[0];
}
return entityID;
}
@Override
@@ -99,36 +132,50 @@ public class WrappedPacketOutEntityDestroy extends WrappedPacketEntityAbstractio
if (packet != null) {
if (v_1_17) {
writeInt(0, this.entityID = entityID);
}
else {
this.entityIds = new int[] {entityID};
writeIntArray(0, new int[]{this.entityIds[0]});
} else {
this.entityIds = new int[]{entityID};
if (v_1_17_1) {
Object intArrayList = null;
try {
intArrayList = INT_ARRAY_LIST_CONSTRUCTOR.newInstance(this.entityIds);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
write(INT_LIST_CLASS, 0, intArrayList);
} else {
writeIntArray(0, new int[]{this.entityIds[0]});
}
}
} else {
if (v_1_17) {
this.entityID = entityID;
}
else {
this.entityIds = new int[] {entityID};
} else {
this.entityIds = new int[]{entityID};
}
}
this.entity = null;
}
public Optional<int[]> getEntityIds() {
public int[] getEntityIds() {
if (packet != null) {
if (v_1_17) {
return Optional.of(new int[] {getEntityId()});
}
else {
return Optional.of(readIntArray(0));
return new int[]{getEntityId()};
} else if (v_1_17_1) {
Object list = readObject(0, INT_LIST_CLASS);
try {
return (int[]) TO_INT_ARRAY_METHOD.invoke(list);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
return null;
} else {
return readIntArray(0);
}
} else {
if (v_1_17) {
return Optional.of(new int[] {entityID});
}
else {
return Optional.of(entityIds);
return new int[]{entityID};
} else {
return entityIds;
}
}
}
@@ -137,16 +184,21 @@ public class WrappedPacketOutEntityDestroy extends WrappedPacketEntityAbstractio
if (packet != null) {
if (v_1_17) {
setEntityId(entityIds[0]);
}
else {
} else if (v_1_17_1) {
Object intArrayList = null;
try {
intArrayList = INT_ARRAY_LIST_CONSTRUCTOR.newInstance(entityIds);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
write(INT_LIST_CLASS, 0, intArrayList);
} else {
writeIntArray(0, entityIds);
}
}
else {
} else {
if (v_1_17) {
this.entityID = entityIds[0];
}
else {
} else {
this.entityIds = entityIds;
}
}
@@ -158,7 +210,7 @@ public class WrappedPacketOutEntityDestroy extends WrappedPacketEntityAbstractio
if (v_1_17) {
return packetConstructor.newInstance(getEntityId());
} else {
return packetConstructor.newInstance(getEntityIds().get());
return packetConstructor.newInstance(getEntityIds());
}
}
}
@@ -33,7 +33,7 @@ import java.lang.reflect.Constructor;
import java.util.Optional;
public class WrappedPacketOutEntityEffect extends WrappedPacketEntityAbstraction implements SendableWrapper {
private static boolean v_1_7_10, v_1_17;
private static boolean v_1_7_10, v_1_17, v_1_18_2;
private static Constructor<?> packetConstructor;
private int effectID;
private int amplifier;
@@ -104,6 +104,7 @@ public class WrappedPacketOutEntityEffect extends WrappedPacketEntityAbstraction
protected void load() {
v_1_7_10 = version.isOlderThan(ServerVersion.v_1_8);
v_1_17 = version.isNewerThanOrEquals(ServerVersion.v_1_17);
v_1_18_2 = version.isNewerThanOrEquals(ServerVersion.v_1_18_2);
try {
if (v_1_17) {
packetConstructor = PacketTypeClasses.Play.Server.ENTITY_EFFECT.getConstructor(NMSUtils.packetDataSerializerClass);
@@ -117,7 +118,12 @@ public class WrappedPacketOutEntityEffect extends WrappedPacketEntityAbstraction
public int getEffectId() {
if (packet != null) {
return readByte(0);
if (v_1_18_2) {
return readInt(4);
}
else {
return readByte(0);
}
} else {
return effectID;
}
@@ -125,7 +131,12 @@ public class WrappedPacketOutEntityEffect extends WrappedPacketEntityAbstraction
public void setEffectId(int effectID) {
if (packet != null) {
writeByte(0, (byte) effectID);
if (v_1_18_2) {
writeInt(4, effectID);
}
else {
writeByte(0, (byte) effectID);
}
} else {
this.effectID = effectID;
}
@@ -133,7 +144,7 @@ public class WrappedPacketOutEntityEffect extends WrappedPacketEntityAbstraction
public int getAmplifier() {
if (packet != null) {
return readByte(1);
return readByte(v_1_18_2 ? 0 : 1);
} else {
return amplifier;
}
@@ -141,7 +152,7 @@ public class WrappedPacketOutEntityEffect extends WrappedPacketEntityAbstraction
public void setAmplifier(int amplifier) {
if (packet != null) {
writeByte(1, (byte) amplifier);
writeByte(v_1_18_2 ? 0 : 1, (byte) amplifier);
} else {
this.amplifier = amplifier;
}
@@ -149,9 +160,16 @@ public class WrappedPacketOutEntityEffect extends WrappedPacketEntityAbstraction
public int getDuration() {
if (packet != null) {
//1.7 and only 1.7
if (v_1_7_10) {
return readShort(1);
} else {
}
//1.18.2+
else if (v_1_18_2) {
return readInt(5);
}
//1.17 - 1.8
else {
return readInt(v_1_17 ? 4 : 1);
}
} else {
@@ -169,7 +187,11 @@ public class WrappedPacketOutEntityEffect extends WrappedPacketEntityAbstraction
duration = Short.MIN_VALUE;
}
writeShort(0, (short) duration);
} else {
}
else if (v_1_18_2) {
writeInt(5, duration);
}
else {
writeInt(v_1_17 ? 4 : 1, duration);
}
} else {
@@ -178,21 +200,21 @@ public class WrappedPacketOutEntityEffect extends WrappedPacketEntityAbstraction
}
private Optional<Byte> getByteMask() {
if (version.isOlderThan(ServerVersion.v_1_8)) {
if (v_1_7_10) {
return Optional.empty();
}
if (packet != null && !byteMaskInitialized) {
return Optional.of(byteMask = readByte(2));
return Optional.of(byteMask = readByte(v_1_18_2 ? 1 : 2));
} else {
return Optional.of(byteMask);
}
}
private void setByteMask(byte byteMask) {
if (version.isNewerThan(ServerVersion.v_1_7_10)) {
if (!v_1_7_10) {
this.byteMask = byteMask;
if (packet != null) {
writeByte(2, byteMask);
writeByte(v_1_18_2 ? 1 : 2, byteMask);
}
}
}
@@ -293,8 +315,10 @@ public class WrappedPacketOutEntityEffect extends WrappedPacketEntityAbstraction
public Object asNMSPacket() throws Exception {
Object packetInstance;
if (v_1_17) {
//Lazy, but smart way :)
Object packetDataSerializer = NMSUtils.generatePacketDataSerializer(PacketEvents.get().getByteBufUtil().newByteBuf(new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}));
//Lazy and stupid way
//was size 12
byte[] buffer = new byte[30];
Object packetDataSerializer = NMSUtils.generatePacketDataSerializer(PacketEvents.get().getByteBufUtil().newByteBuf(buffer));
packetInstance = packetConstructor.newInstance(packetDataSerializer);
} else {
packetInstance = packetConstructor.newInstance();
@@ -32,18 +32,19 @@ import java.lang.reflect.Constructor;
public class WrappedPacketOutEntityHeadRotation extends WrappedPacketEntityAbstraction implements SendableWrapper {
private static boolean v_1_17;
private static Constructor<?> packetConstructor;
private byte yaw;
private static final float ROTATION_FACTOR = 256.0F / 360.0F;
private float yaw;
public WrappedPacketOutEntityHeadRotation(NMSPacket packet) {
super(packet);
}
public WrappedPacketOutEntityHeadRotation(int entityID, byte yaw) {
public WrappedPacketOutEntityHeadRotation(int entityID, float yaw) {
this.entityID = entityID;
this.yaw = yaw;
}
public WrappedPacketOutEntityHeadRotation(Entity entity, byte yaw) {
public WrappedPacketOutEntityHeadRotation(Entity entity, float yaw) {
this.entityID = entity.getEntityId();
this.entity = entity;
this.yaw = yaw;
@@ -64,17 +65,17 @@ public class WrappedPacketOutEntityHeadRotation extends WrappedPacketEntityAbstr
}
}
public byte getYaw() {
public float getYaw() {
if (packet != null) {
return readByte(0);
return readByte(0) / ROTATION_FACTOR;
} else {
return yaw;
}
}
public void setYaw(byte yaw) {
public void setYaw(float yaw) {
if (packet != null) {
writeByte(0, yaw);
writeByte(0, (byte) (yaw * ROTATION_FACTOR));
} else {
this.yaw = yaw;
}
@@ -84,9 +84,9 @@ public final class WrappedPacketOutEntityVelocity extends WrappedPacketEntityAbs
public void setVelocity(Vector3d velocity) {
if (packet != null) {
writeInt(1, (int) (velocity.x));
writeInt(2, (int) (velocity.y));
writeInt(3, (int) (velocity.z));
writeInt(1, (int) (velocity.x * 8000.0));
writeInt(2, (int) (velocity.y * 8000.0));
writeInt(3, (int) (velocity.z * 8000.0));
}
else {
this.velocityX = velocity.x;
@@ -95,7 +95,6 @@ public final class WrappedPacketOutEntityVelocity extends WrappedPacketEntityAbs
}
}
//TODO Cut off at 1.8.1 and optimize the methods above.
@Deprecated
public double getVelocityX() {
if (packet != null) {
@@ -238,7 +238,6 @@ public class WrappedPacketOutExplosion extends WrappedPacket implements Sendable
}
}
//TODO Cut off at 1.8.1, and once you cut off, you can optimize the methods above. Also optimize the position part.
@Deprecated
public float getPlayerMotionX() {
if (packet != null) {
@@ -54,6 +54,7 @@ public class WrappedPacketOutGameStateChange extends WrappedPacket implements Se
@Override
protected void load() {
reasonClassType = SubclassUtil.getSubClass(PacketTypeClasses.Play.Server.GAME_STATE_CHANGE, 0);
net.minecraft.server.v1_8_R3.PacketPlayOutGameStateChange gsc;
if (reasonClassType != null) {
try {
reasonClassConstructor = reasonClassType.getConstructor(int.class);
@@ -140,7 +141,7 @@ public class WrappedPacketOutGameStateChange extends WrappedPacket implements Se
@Override
public Object asNMSPacket() throws Exception {
if (reasonClassType == null) {
if (reasonIntMode) {
if (valueFloatMode) {
return packetConstructor.newInstance(getReason(), (float) getValue());
} else {
@@ -21,6 +21,7 @@ package io.github.retrooper.packetevents.packetwrappers.play.out.mapchunk;
import io.github.retrooper.packetevents.packettype.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.NMSPacket;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.utils.reflection.Reflection;
import io.github.retrooper.packetevents.utils.reflection.SubclassUtil;
import io.github.retrooper.packetevents.utils.server.ServerVersion;
@@ -31,8 +32,8 @@ import java.util.Optional;
//TODO finish wrapper
public class WrappedPacketOutMapChunk extends WrappedPacket {
private static boolean v_1_8_x, v_1_17;
private static Class<?> chunkMapClass;
private static boolean v_1_8_x, v_1_17, v_1_18;
private static Class<?> chunkMapClass, chunkPacketDataClass;
private Constructor<?> chunkMapConstructor;
private Object nmsChunkMap;
@@ -44,6 +45,7 @@ public class WrappedPacketOutMapChunk extends WrappedPacket {
protected void load() {
v_1_8_x = version.isNewerThan(ServerVersion.v_1_7_10) && version.isOlderThan(ServerVersion.v_1_9);
v_1_17 = version.isNewerThanOrEquals(ServerVersion.v_1_17);
v_1_18 = version.isNewerThanOrEquals(ServerVersion.v_1_18);
if (v_1_8_x) {
chunkMapClass = SubclassUtil.getSubClass(PacketTypeClasses.Play.Server.MAP_CHUNK, 0);
try {
@@ -52,68 +54,68 @@ public class WrappedPacketOutMapChunk extends WrappedPacket {
e.printStackTrace();
}
}
chunkPacketDataClass = Reflection.getClassByNameWithoutException("net.minecraft.network.protocol.game.ClientboundLevelChunkPacketData");
}
public int getChunkX() {
return readInt(v_1_17 ? 1 : 0);
return readInt(v_1_17 && !v_1_18 ? 1 : 0);
}
public void setChunkX(int chunkX) {
writeInt(v_1_17 ? 1: 0, chunkX);
writeInt(v_1_17 && !v_1_18 ? 1 : 0, chunkX);
}
public int getChunkZ() {
return readInt(v_1_17 ? 2: 1);
return readInt(v_1_17 && !v_1_18 ? 2 : 1);
}
public void setChunkZ(int chunkZ) {
writeInt(v_1_17 ? 2: 1, chunkZ);
writeInt(v_1_17 && !v_1_18 ? 2 : 1, chunkZ);
}
public Optional<BitSet> getPrimaryBitMaskBitSet() {
public Optional<BitSet> getBitSet() {
if (v_1_18) { // Bitsets were removed in 1.18
return Optional.empty();
}
if (v_1_17) {
return Optional.of(readObject(0, BitSet.class));
}
else {
return Optional.empty();
}
}
public void setPrimaryBitMaskBitSet(BitSet bitMaskBitSet) {
if (v_1_17) {
writeObject(0, bitMaskBitSet);
}
}
@Deprecated
public Optional<Integer> getPrimaryBitMap() {
return getPrimaryBitMask();
}
@Deprecated
public void setPrimaryBitMap(int primaryBitMask) {
setPrimaryBitMask(primaryBitMask);
}
public Optional<Integer> getPrimaryBitMask() {
if (v_1_17) {
return Optional.of((int) readObject(0, BitSet.class).toLongArray()[0]);
}
if (v_1_8_x) {
if (nmsChunkMap == null) {
nmsChunkMap = readObject(0, chunkMapClass);
}
WrappedPacket nmsChunkMapWrapper = new WrappedPacket(new NMSPacket(nmsChunkMap));
return Optional.of(nmsChunkMapWrapper.readInt(0));
return Optional.of(BitSet.valueOf(new long[]{nmsChunkMapWrapper.readInt(0)}));
} else {
return Optional.of(readInt(2));
return Optional.of(BitSet.valueOf(new long[]{readInt(2)}));
}
}
public void setPrimaryBitMask(int primaryBitMask) {
/**
* @param bitSet Bitset that can hold multiple integer values to support the expanded world height on
* 1.17 and newer servers. This is due to 1.17 needing to support up to 127 chunk sections
* (2032 blocks) and an integer only being able to hold 32 bits to represent 32 chunk sections
*/
public void setPrimaryBitMask(BitSet bitSet) {
if (v_1_18) return; // Bitsets were removed in 1.18
if (v_1_17) {
writeObject(0, BitSet.valueOf(new long[] {primaryBitMask}));
writeObject(0, bitSet);
return;
}
setPrimaryBitMask((int) bitSet.toLongArray()[0]);
}
/**
* @param primaryBitMask Integer that determines which chunk sections the server is sending
* @deprecated Possible lossy conversion on 1.17 servers that could result in the client only reading 32
* out of the total possible 127 chunk sections. Safe to use on 1.16 and below servers
*/
@Deprecated
public void setPrimaryBitMask(int primaryBitMask) {
if (v_1_18) return; // Bitsets were removed in 1.18
if (v_1_17) {
writeObject(0, BitSet.valueOf(new long[]{primaryBitMask}));
return;
}
if (v_1_8_x) {
@@ -133,7 +135,9 @@ public class WrappedPacketOutMapChunk extends WrappedPacket {
}
}
//TODO Confirm if 1.17 support is possible
/**
* @return Whether the packet overwrites the entire chunk column or just the sections being sent
*/
public Optional<Boolean> isGroundUpContinuous() {
if (v_1_17) {
return Optional.empty();
@@ -141,7 +145,9 @@ public class WrappedPacketOutMapChunk extends WrappedPacket {
return Optional.of(readBoolean(0));
}
//TODO Confirm if 1.17 support is possible
/**
* @param groundUpContinuous Whether the packet overwrites the entire chunk column or just the sections being sent
*/
public void setGroundUpContinuous(boolean groundUpContinuous) {
if (v_1_17) {
return;
@@ -156,6 +162,8 @@ public class WrappedPacketOutMapChunk extends WrappedPacket {
}
WrappedPacket nmsChunkMapWrapper = new WrappedPacket(new NMSPacket(nmsChunkMap));
return nmsChunkMapWrapper.readByteArray(0);
} else if (v_1_18) {
return new WrappedPacket(new NMSPacket(readObject(0, chunkPacketDataClass))).readByteArray(0);
} else {
return readByteArray(0);
}
@@ -173,6 +181,8 @@ public class WrappedPacketOutMapChunk extends WrappedPacket {
WrappedPacket nmsChunkMapWrapper = new WrappedPacket(new NMSPacket(nmsChunkMap));
nmsChunkMapWrapper.writeByteArray(0, data);
write(chunkMapClass, 0, nmsChunkMap);
} else if (v_1_18) {
new WrappedPacket(new NMSPacket(readObject(0, chunkPacketDataClass))).writeByteArray(0, data);
} else {
writeByteArray(0, data);
}
@@ -1,43 +0,0 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2021 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 io.github.retrooper.packetevents.packetwrappers.play.out.multiblockchange;
import io.github.retrooper.packetevents.packetwrappers.NMSPacket;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
//TODO finish this wrapper
class WrappedPacketOutMultiBlockChange extends WrappedPacket {
public WrappedPacketOutMultiBlockChange(NMSPacket packet) {
super(packet);
}
@Override
protected void load() {
net.minecraft.server.v1_7_R4.PacketPlayOutMultiBlockChange a0;
net.minecraft.server.v1_8_R3.PacketPlayOutMultiBlockChange a1;
net.minecraft.server.v1_9_R1.PacketPlayOutMultiBlockChange a2;
net.minecraft.server.v1_9_R2.PacketPlayOutMultiBlockChange a3;
net.minecraft.server.v1_12_R1.PacketPlayOutMultiBlockChange a4;
net.minecraft.server.v1_13_R1.PacketPlayOutMultiBlockChange a5;
net.minecraft.server.v1_13_R2.PacketPlayOutMultiBlockChange a6;
net.minecraft.server.v1_16_R2.PacketPlayOutMultiBlockChange a7;
}
}
@@ -98,8 +98,7 @@ public class WrappedPacketOutNamedSoundEffect extends WrappedPacket implements S
if (soundEffectVarExists) {
Object soundEffect = readObject(0, NMSUtils.soundEffectClass);
WrappedPacket soundEffectWrapper = new WrappedPacket(new NMSPacket(soundEffect));
Object minecraftKey = soundEffectWrapper.readObject(0, NMSUtils.minecraftKeyClass);
return NMSUtils.getStringFromMinecraftKey(minecraftKey);
return soundEffectWrapper.readMinecraftKey(0);
} else {
return readString(0);
}
@@ -111,7 +110,7 @@ public class WrappedPacketOutNamedSoundEffect extends WrappedPacket implements S
public void setSoundEffectName(String name) {
if (packet != null) {
if (soundEffectVarExists) {
Object minecraftKey = NMSUtils.generateMinecraftKey(name);
Object minecraftKey = NMSUtils.generateMinecraftKeyNew(name);
Object soundEffect = null;
try {
soundEffect = soundEffectConstructor.newInstance(minecraftKey);
@@ -219,7 +218,7 @@ public class WrappedPacketOutNamedSoundEffect extends WrappedPacket implements S
public Object asNMSPacket() throws Exception {
Object packetInstance;
if (v_1_17) {
Object nmsSoundEffect = soundEffectConstructor.newInstance(NMSUtils.generateMinecraftKey(getSoundEffectName()));
Object nmsSoundEffect = soundEffectConstructor.newInstance(NMSUtils.generateMinecraftKeyNew(getSoundEffectName()));
Object nmsSoundCategory = EnumUtil.valueByIndex(enumSoundCategoryClass, getSoundCategory().get().ordinal());
Vector3d effectPos = getEffectPosition();
packetInstance = packetConstructor.newInstance(nmsSoundEffect, nmsSoundCategory, effectPos.x, effectPos.y, effectPos.z, getVolume(), getPitch());
@@ -1,21 +1,19 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2021 retrooper and contributors
*
* * This file is part of packetevents - https://github.com/retrooper/packetevents
* * Copyright (C) 2016-2021 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/>.
* 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 io.github.retrooper.packetevents.packetwrappers.play.out.ping;
@@ -43,7 +43,6 @@ public final class WrappedPacketOutPosition extends WrappedPacket implements Sen
private Set<PlayerTeleportFlags> relativeFlags;
private int teleportID;
@Deprecated
private boolean onGround;
public WrappedPacketOutPosition(NMSPacket packet) {
@@ -84,6 +83,15 @@ public final class WrappedPacketOutPosition extends WrappedPacket implements Sen
this.teleportID = teleportID;
}
public WrappedPacketOutPosition(Vector3d position, float yaw, float pitch, Set<PlayerTeleportFlags> relativeFlags, int teleportID, boolean onGround) {
this.position = position;
this.yaw = yaw;
this.pitch = pitch;
this.relativeFlags = relativeFlags;
this.teleportID = teleportID;
this.onGround= onGround;
}
@Override
protected void load() {
v_1_8 = version.isNewerThanOrEquals(ServerVersion.v_1_8);
@@ -116,7 +124,7 @@ public final class WrappedPacketOutPosition extends WrappedPacket implements Sen
}
public Optional<Boolean> isOnGround() {
//1.7.10 and 1.17 support this field
//1.7.10 and 1.17+ support this field
if (v_1_8 && !v_1_17) {
return Optional.empty();
}
@@ -317,8 +325,10 @@ public final class WrappedPacketOutPosition extends WrappedPacket implements Sen
//1.8 -> 1.8.8
return packetConstructor.newInstance(position.x, position.y, position.z, getYaw(), getPitch(), nmsRelativeFlags);
case 2:
return packetConstructor.newInstance(position.x, position.y, position.z, getYaw(), getPitch(), nmsRelativeFlags, getTeleportId());
//1.9 -> 1.16.5
return packetConstructor.newInstance(position.x, position.y, position.z, getYaw(), getPitch(), nmsRelativeFlags, getTeleportId().get());
case 3:
//1.17
return packetConstructor.newInstance(position.x, position.y, position.z, getYaw(), getPitch(), nmsRelativeFlags, getTeleportId(), isOnGround().get());
default:
return null;
@@ -66,9 +66,12 @@ public class WrappedPacketOutRemoveEntityEffect extends WrappedPacketEntityAbstr
public int getEffectId() {
if (packet != null) {
//1.7 and 1.8
if (v_1_8_x) {
return readInt(1);
} else {
}
//1.9+
else {
Object nmsMobEffectList = readObject(0, NMSUtils.mobEffectListClass);
return NMSUtils.getEffectId(nmsMobEffectList);
}
@@ -80,9 +83,12 @@ public class WrappedPacketOutRemoveEntityEffect extends WrappedPacketEntityAbstr
public void setEffectId(int effectID) {
if (packet != null) {
//1.7 and 1.8
if (v_1_8_x) {
writeInt(1, effectID);
} else {
}
//1.9+
else {
Object nmsMobEffectList = NMSUtils.getMobEffectListById(effectID);
write(NMSUtils.mobEffectListClass, 0, nmsMobEffectList);
}
@@ -1,109 +0,0 @@
/*
*
* * This file is part of packetevents - https://github.com/retrooper/packetevents
* * Copyright (C) 2016-2021 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 io.github.retrooper.packetevents.packetwrappers.play.out.scoreboardteam;
import io.github.retrooper.packetevents.packetwrappers.NMSPacket;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.utils.enums.EnumUtil;
import io.github.retrooper.packetevents.utils.nms.NMSUtils;
import io.github.retrooper.packetevents.utils.server.ServerVersion;
import org.bukkit.ChatColor;
//TODO FINISH WRAPPER
class WrappedPacketOutScoreboardTeam extends WrappedPacket {
private static Class<? extends Enum<?>> enumChatFormat;
public WrappedPacketOutScoreboardTeam(NMSPacket packet) {
super(packet);
}
@Override
protected void load() {
enumChatFormat = NMSUtils.getNMSEnumClassWithoutException("EnumChatFormat");
if (enumChatFormat == null) {
enumChatFormat= NMSUtils.getNMEnumClassWithoutException("EnumChatFormat");
}
net.minecraft.server.v1_7_R4.PacketPlayOutScoreboardTeam a0;
net.minecraft.server.v1_8_R3.PacketPlayOutScoreboardTeam a1;
net.minecraft.server.v1_9_R1.PacketPlayOutScoreboardTeam a2;
net.minecraft.server.v1_9_R2.PacketPlayOutScoreboardTeam a3;
net.minecraft.server.v1_12_R1.PacketPlayOutScoreboardTeam a4;
net.minecraft.server.v1_13_R1.PacketPlayOutScoreboardTeam a5;
net.minecraft.server.v1_13_R2.PacketPlayOutScoreboardTeam a6;
net.minecraft.server.v1_16_R2.PacketPlayOutScoreboardTeam a7;
//Add 1.17 support, its very diff
//net.minecraft.network.protocol.game.PacketPlayOutScoreboardTeam a8;
}
public String getTeamName() {
return readString(0);
}
public void setTeamName(String name) {
writeString(0, name);
}
public String getTeamPrefix() {
if (version.isNewerThanOrEquals(ServerVersion.v_1_13)) {
return readIChatBaseComponent(0);
}
else {
return readString(1);
}
}
public void setTeamPrefix(String teamPrefix) {
if (version.isNewerThanOrEquals(ServerVersion.v_1_13)) {
writeIChatBaseComponent(0, teamPrefix);
}
else {
writeString(1, teamPrefix);
}
}
public String getTeamSuffix() {
if (version.isNewerThanOrEquals(ServerVersion.v_1_13)) {
return readIChatBaseComponent(1);
}
else {
return readString(2);
}
}
public void setTeamSuffix(String teamSuffix) {
if (version.isNewerThanOrEquals(ServerVersion.v_1_13)) {
writeIChatBaseComponent(1, teamSuffix);
}
else {
writeString(2, teamSuffix);
}
}
public ChatColor getTeamColor() {
Enum<?> enumChatFormatConstant = readEnumConstant(0, enumChatFormat);
return ChatColor.values()[enumChatFormatConstant.ordinal()];
}
public void setTeamColor(ChatColor color) {
Enum<?> enumChatFormatConstant = EnumUtil.valueByIndex(enumChatFormat, color.ordinal());
writeEnumConstant(0, enumChatFormatConstant);
}
}
@@ -19,33 +19,33 @@
package io.github.retrooper.packetevents.packetwrappers.play.out.setcooldown;
import io.github.retrooper.packetevents.packettype.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.NMSPacket;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.packetwrappers.api.SendableWrapper;
import io.github.retrooper.packetevents.utils.nms.NMSUtils;
import io.github.retrooper.packetevents.utils.server.ServerVersion;
import org.bukkit.entity.EntityType;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import java.lang.reflect.Constructor;
import java.util.IdentityHashMap;
import java.util.Map;
import java.lang.reflect.InvocationTargetException;
//TODO TEST
public class WrappedPacketOutSetCooldown extends WrappedPacket implements SendableWrapper {
private static final Map<Short, EntityType> ID_MAP = new IdentityHashMap<>();
private static Constructor<?> packetConstructor;
private EntityType type;
private Object nmsItem;
private int cooldownTicks;
public WrappedPacketOutSetCooldown(EntityType type, int cooldownTicks) {
this.type = type;
public WrappedPacketOutSetCooldown(NMSPacket packet) {
super(packet);
}
public WrappedPacketOutSetCooldown(Object nmsItem, int cooldownTicks) {
this.nmsItem = nmsItem;
this.cooldownTicks = cooldownTicks;
}
@Override
protected void load() {
for (EntityType type : EntityType.values()) {
ID_MAP.put(type.getTypeId(), type);
}
try {
packetConstructor = PacketTypeClasses.Play.Server.SET_COOLDOWN.getConstructor(NMSUtils.nmsItemClass, int.class);
} catch (NoSuchMethodException e) {
@@ -53,23 +53,38 @@ public class WrappedPacketOutSetCooldown extends WrappedPacket implements Sendab
}
}
public EntityType getType() {
if (packet != null) {
@Override
public boolean isSupported() {
return version.isNewerThan(ServerVersion.v_1_8_8);
}
public ItemStack getItemStack() {
try {
Object nmsItem = readObject(0, NMSUtils.nmsItemClass);
short nmsItemID = (short) NMSUtils.getNMSItemId(nmsItem);
return ID_MAP.get(nmsItemID);
Object nmsItemStack = NMSUtils.itemStackConstructor.newInstance(nmsItem);
return NMSUtils.toBukkitItemStack(nmsItemStack);
} catch (InvocationTargetException | InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
return new ItemStack(Material.AIR);
}
public Object getNmsItem() {
return nmsItem;
}
public void setNMSItemStack(Object type) {
if (packet != null) {
write(NMSUtils.nmsItemClass, 0, type);
} else {
return type;
this.nmsItem = type;
}
}
public void setType(EntityType type) {
if (packet != null) {
Object nmsItem = NMSUtils.getNMSItemById(type.getTypeId());
write(NMSUtils.nmsItemClass, 0, nmsItem);
} else {
this.type = type;
}
@Override
public Object asNMSPacket() throws Exception {
return packetConstructor.newInstance(nmsItem, getCooldownTicks());
}
public int getCooldownTicks() {
@@ -87,15 +102,4 @@ public class WrappedPacketOutSetCooldown extends WrappedPacket implements Sendab
this.cooldownTicks = cooldownTicks;
}
}
@Override
public boolean isSupported() {
return version.isNewerThan(ServerVersion.v_1_8_8);
}
@Override
public Object asNMSPacket() throws Exception {
Object nmsItem = NMSUtils.getNMSItemById(getType().getTypeId());
return packetConstructor.newInstance(nmsItem, getCooldownTicks());
}
}
@@ -27,16 +27,18 @@ import io.github.retrooper.packetevents.utils.server.ServerVersion;
import org.bukkit.inventory.ItemStack;
import java.lang.reflect.Constructor;
import java.util.Optional;
/**
* @author AoElite
* @since 1.8
*/
public class WrappedPacketOutSetSlot extends WrappedPacket implements SendableWrapper {
private static boolean v_1_17;
private static boolean v_1_17, v_1_17_1;
private static Constructor<?> packetConstructor;
private int windowID;
private int stateID;
private int slot;
private ItemStack itemStack;
@@ -46,6 +48,14 @@ public class WrappedPacketOutSetSlot extends WrappedPacket implements SendableWr
public WrappedPacketOutSetSlot(int windowID, int slot, ItemStack itemstack) {
this.windowID = windowID;
this.stateID = 0;
this.slot = slot;
this.itemStack = itemstack;
}
public WrappedPacketOutSetSlot(int windowID, int stateID, int slot, ItemStack itemstack) {
this.windowID = windowID;
this.stateID = stateID;
this.slot = slot;
this.itemStack = itemstack;
}
@@ -54,8 +64,14 @@ public class WrappedPacketOutSetSlot extends WrappedPacket implements SendableWr
@Override
protected void load() {
v_1_17 = version.isNewerThanOrEquals(ServerVersion.v_1_17);
v_1_17_1 = version.isNewerThanOrEquals(ServerVersion.v_1_17_1);
try {
packetConstructor = PacketTypeClasses.Play.Server.SET_SLOT.getConstructor(int.class, int.class, NMSUtils.nmsItemStackClass);
if (v_1_17_1) {
packetConstructor = PacketTypeClasses.Play.Server.SET_SLOT.getConstructor(int.class, int.class, int.class, NMSUtils.nmsItemStackClass);
} else {
packetConstructor = PacketTypeClasses.Play.Server.SET_SLOT.getConstructor(int.class, int.class, NMSUtils.nmsItemStackClass);
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
@@ -64,7 +80,8 @@ public class WrappedPacketOutSetSlot extends WrappedPacket implements SendableWr
public int getWindowId() {
if (packet != null) {
return readInt(v_1_17 ? 2 : 0);
int index = v_1_17 ? 2 : 0;
return readInt(index);
} else {
return windowID;
}
@@ -72,15 +89,39 @@ public class WrappedPacketOutSetSlot extends WrappedPacket implements SendableWr
public void setWindowId(int windowID) {
if (packet != null) {
writeInt(v_1_17 ? 2 : 0, windowID);
int index = v_1_17 ? 2 : 0;
writeInt(index, windowID);
} else {
this.windowID = windowID;
}
}
public Optional<Integer> getStateId() {
if (v_1_17_1) {
if (packet != null) {
return Optional.of(readInt(4));
} else {
return Optional.of(stateID);
}
} else {
return Optional.empty();
}
}
public void setStateId(int stateID) {
if (v_1_17_1) {
if (packet != null) {
writeInt(4, stateID);
} else {
this.stateID = stateID;
}
}
}
public int getSlot() {
if (packet != null) {
return readInt(v_1_17 ? 3: 1);
int index = v_1_17_1 ? 4 : v_1_17 ? 3 : 1;
return readInt(index);
} else {
return slot;
}
@@ -88,7 +129,8 @@ public class WrappedPacketOutSetSlot extends WrappedPacket implements SendableWr
public void setSlot(int slot) {
if (packet != null) {
writeInt(v_1_17 ? 3: 1, slot);
int index = v_1_17_1 ? 4 : v_1_17 ? 3 : 1;
writeInt(index, slot);
} else {
this.slot = slot;
}
@@ -112,6 +154,11 @@ public class WrappedPacketOutSetSlot extends WrappedPacket implements SendableWr
@Override
public Object asNMSPacket() throws Exception {
return packetConstructor.newInstance(getWindowId(), getSlot(), NMSUtils.toNMSItemStack(getItemStack()));
if (v_1_17_1) {
return packetConstructor.newInstance(getWindowId(), getStateId(), getSlot(), NMSUtils.toNMSItemStack(getItemStack()));
}
else {
return packetConstructor.newInstance(getWindowId(), getSlot(), NMSUtils.toNMSItemStack(getItemStack()));
}
}
}
@@ -1,21 +1,19 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2021 retrooper and contributors
*
* * This file is part of packetevents - https://github.com/retrooper/packetevents
* * Copyright (C) 2016-2021 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/>.
* 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 io.github.retrooper.packetevents.packetwrappers.play.out.spawnentity;
@@ -29,8 +27,8 @@ import io.github.retrooper.packetevents.utils.vector.Vector3d;
import java.util.Optional;
import java.util.UUID;
//TODO Make this sendable and finish
class WrappedPacketOutSpawnEntity extends WrappedPacketEntityAbstraction {
//TODO Make this sendable
public class WrappedPacketOutSpawnEntity extends WrappedPacketEntityAbstraction {
private static boolean v_1_9, v_1_17;
private static final float rotationFactor = 256.0F / 360.0F;
private UUID uuid;
@@ -74,15 +72,16 @@ class WrappedPacketOutSpawnEntity extends WrappedPacketEntityAbstraction {
double x;
double y;
double z;
if (!v_1_9) {
x = readInt(1) / 32.0;
y = readInt(2) / 32.0;
z = readInt(3) / 32.0;
} else {
if (v_1_9) {
x = readDouble(v_1_17 ? 1 : 0);
y = readDouble(v_1_17 ? 2 : 1);
z = readDouble(v_1_17 ? 3 : 2);
}
else {
x = readInt(1) / 32.0;
y = readInt(2) / 32.0;
z = readInt(3) / 32.0;
}
return new Vector3d(x, y, z);
} else {
return position;
@@ -91,15 +90,16 @@ class WrappedPacketOutSpawnEntity extends WrappedPacketEntityAbstraction {
public void setPosition(Vector3d position) {
if (packet != null) {
if (!v_1_9) {
writeInt(1, MathUtils.floor(position.x * 32.0));
writeInt(2, MathUtils.floor(position.y * 32.0));
writeInt(3, MathUtils.floor(position.z * 32.0));
} else {
if (v_1_9) {
writeDouble(v_1_17 ? 1 : 0, position.x);
writeDouble(v_1_17 ? 2 : 1, position.y);
writeDouble(v_1_17 ? 3 : 2, position.z);
}
else {
writeInt(1, MathUtils.floor(position.x * 32.0));
writeInt(2, MathUtils.floor(position.y * 32.0));
writeInt(3, MathUtils.floor(position.z * 32.0));
}
} else {
this.position = position;
}
@@ -110,15 +110,16 @@ class WrappedPacketOutSpawnEntity extends WrappedPacketEntityAbstraction {
double velX;
double velY;
double velZ;
if (!v_1_9) {
velX = readInt(4) / 8000.0;
velY = readInt(5) / 8000.0;
velZ = readInt(6) / 8000.0;
} else {
if (v_1_9) {
velX = readInt(1) / 8000.0;
velY = readInt(2) / 8000.0;
velZ = readInt(3) / 8000.0;
}
else {
velX = readInt(4) / 8000.0;
velY = readInt(5) / 8000.0;
velZ = readInt(6) / 8000.0;
}
return new Vector3d(velX, velY, velZ);
} else {
return velocity;
@@ -130,15 +131,16 @@ class WrappedPacketOutSpawnEntity extends WrappedPacketEntityAbstraction {
int velX = (int) (velocity.x * 8000.0);
int velY = (int) (velocity.y * 8000.0);
int velZ = (int) (velocity.z * 8000.0);
if (!v_1_9) {
writeInt(4, velX);
writeInt(5, velY);
writeInt(6, velZ);
} else {
if (v_1_9) {
writeInt(1, velX);
writeInt(2, velY);
writeInt(3, velZ);
}
else {
writeInt(4, velX);
writeInt(5, velY);
writeInt(6, velZ);
}
} else {
this.velocity = velocity;
}
@@ -35,10 +35,10 @@ import java.util.Optional;
import java.util.UUID;
public class WrappedPacketOutSpawnEntityLiving extends WrappedPacketEntityAbstraction implements SendableWrapper {
private static boolean v_1_9, v_1_17;
private static final byte[] byteBufAllocation = new byte[48];
private static final float rotationFactor = 256.0F / 360.0F;
private static final double velocityFactor = 8000.0;
private static final float ROTATION_FACTOR = 256.0F / 360.0F;
private static final double VELOCITY_FACTOR = 8000.0;
private static boolean v_1_9, v_1_17;
private static Constructor<?> packetConstructor;
private Vector3d position, velocity;
@@ -79,8 +79,7 @@ public class WrappedPacketOutSpawnEntityLiving extends WrappedPacketEntityAbstra
v_1_17 = version.isNewerThanOrEquals(ServerVersion.v_1_17);
if (v_1_17) {
packetConstructor = PacketTypeClasses.Play.Server.SPAWN_ENTITY_LIVING.getConstructor(NMSUtils.packetDataSerializerClass);
}
else {
} else {
packetConstructor = PacketTypeClasses.Play.Server.SPAWN_ENTITY_LIVING.getConstructor();
}
} catch (NoSuchMethodException e) {
@@ -179,7 +178,7 @@ public class WrappedPacketOutSpawnEntityLiving extends WrappedPacketEntityAbstra
factoredVelY = readInt(3);
factoredVelZ = readInt(4);
}
return new Vector3d(factoredVelX / velocityFactor, factoredVelY / velocityFactor, factoredVelZ / velocityFactor);
return new Vector3d(factoredVelX / VELOCITY_FACTOR, factoredVelY / VELOCITY_FACTOR, factoredVelZ / VELOCITY_FACTOR);
} else {
return this.velocity;
}
@@ -187,9 +186,9 @@ public class WrappedPacketOutSpawnEntityLiving extends WrappedPacketEntityAbstra
public void setVelocity(Vector3d velocity) {
if (packet != null) {
int factoredVelX = (int) (velocity.x * velocityFactor);
int factoredVelY = (int) (velocity.y * velocityFactor);
int factoredVelZ = (int) (velocity.z * velocityFactor);
int factoredVelX = (int) (velocity.x * VELOCITY_FACTOR);
int factoredVelY = (int) (velocity.y * VELOCITY_FACTOR);
int factoredVelZ = (int) (velocity.z * VELOCITY_FACTOR);
if (!v_1_9) {
writeInt(5, factoredVelX);
writeInt(6, factoredVelY);
@@ -207,7 +206,7 @@ public class WrappedPacketOutSpawnEntityLiving extends WrappedPacketEntityAbstra
public float getYaw() {
if (packet != null) {
byte factoredYaw = readByte(0);
return factoredYaw / rotationFactor;
return factoredYaw / ROTATION_FACTOR;
} else {
return yaw;
}
@@ -215,7 +214,7 @@ public class WrappedPacketOutSpawnEntityLiving extends WrappedPacketEntityAbstra
public void setYaw(float yaw) {
if (packet != null) {
writeByte(0, (byte) ((int) (yaw * rotationFactor)));
writeByte(0, (byte) ((int) (yaw * ROTATION_FACTOR)));
} else {
this.yaw = yaw;
}
@@ -224,7 +223,7 @@ public class WrappedPacketOutSpawnEntityLiving extends WrappedPacketEntityAbstra
public float getPitch() {
if (packet != null) {
byte factoredPitch = readByte(1);
return factoredPitch / rotationFactor;
return factoredPitch / ROTATION_FACTOR;
} else {
return pitch;
}
@@ -232,7 +231,7 @@ public class WrappedPacketOutSpawnEntityLiving extends WrappedPacketEntityAbstra
public void setPitch(float pitch) {
if (packet != null) {
writeByte(1, (byte) ((int) (pitch * rotationFactor)));
writeByte(1, (byte) ((int) (pitch * ROTATION_FACTOR)));
} else {
this.pitch = pitch;
}
@@ -241,7 +240,7 @@ public class WrappedPacketOutSpawnEntityLiving extends WrappedPacketEntityAbstra
public float getHeadPitch() {
if (packet != null) {
byte factoredHeadPitch = readByte(2);
return factoredHeadPitch / rotationFactor;
return factoredHeadPitch / ROTATION_FACTOR;
} else {
return this.headPitch;
}
@@ -249,7 +248,7 @@ public class WrappedPacketOutSpawnEntityLiving extends WrappedPacketEntityAbstra
public void setHeadPitch(float headPitch) {
if (packet != null) {
writeByte(2, (byte) ((int) (headPitch * rotationFactor)));
writeByte(2, (byte) ((int) (headPitch * ROTATION_FACTOR)));
} else {
this.headPitch = headPitch;
}
@@ -262,8 +261,7 @@ public class WrappedPacketOutSpawnEntityLiving extends WrappedPacketEntityAbstra
Object byteBuf = PacketEvents.get().getByteBufUtil().newByteBuf(byteBufAllocation);
Object packetDataSerializer = NMSUtils.generatePacketDataSerializer(byteBuf);
packetInstance = packetConstructor.newInstance(packetDataSerializer);
}
else {
} else {
packetInstance = packetConstructor.newInstance();
}
WrappedPacketOutSpawnEntityLiving wrappedPacketOutSpawnEntityLiving = new WrappedPacketOutSpawnEntityLiving(new NMSPacket(packetInstance));
@@ -1,21 +1,19 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2021 retrooper and contributors
*
* * This file is part of packetevents - https://github.com/retrooper/packetevents
* * Copyright (C) 2016-2021 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/>.
* 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 io.github.retrooper.packetevents.packetwrappers.play.out.windowitems;
@@ -25,7 +23,6 @@ import io.github.retrooper.packetevents.packetwrappers.NMSPacket;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.packetwrappers.api.SendableWrapper;
import io.github.retrooper.packetevents.utils.nms.NMSUtils;
import io.github.retrooper.packetevents.utils.reflection.Reflection;
import io.github.retrooper.packetevents.utils.server.ServerVersion;
import org.bukkit.inventory.ItemStack;
@@ -33,36 +30,49 @@ import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
//TODO Test wrapper
public class WrappedPacketOutWindowItems extends WrappedPacket implements SendableWrapper {
private static boolean v_1_17;
private static boolean v_1_17, v_1_17_1;
private static Object nonNullListInstance;
private static Class<?> nonNullListClass;
private static Constructor<?> packetConstructor;
private int windowID;
private int stateID;
private List<ItemStack> slotData;
private ItemStack heldItem;
public WrappedPacketOutWindowItems(NMSPacket packet) {
super(packet);
}
public WrappedPacketOutWindowItems(int windowID, List<ItemStack> slots) {
public WrappedPacketOutWindowItems(int windowID, int stateID, List<ItemStack> slots, ItemStack heldItem) {
this.windowID = windowID;
this.stateID = stateID;
this.slotData = slots;
this.heldItem = heldItem;
}
@Override
protected void load() {
v_1_17 = version.isNewerThanOrEquals(ServerVersion.v_1_17);
v_1_17_1 = version.isNewerThanOrEquals(ServerVersion.v_1_17_1);
try {
if (v_1_17) {
nonNullListClass = NMSUtils.getNMClassWithoutException("core.NonNullList");
Constructor<?> nonNullListConstructor = nonNullListClass.getConstructor();
nonNullListConstructor.setAccessible(true);
nonNullListInstance = nonNullListConstructor.newInstance();
packetConstructor = PacketTypeClasses.Play.Server.WINDOW_ITEMS.getConstructor(int.class, nonNullListClass);
}
else {
if (v_1_17_1) {
Constructor<?> nonNullListConstructor = nonNullListClass.getDeclaredConstructors()[0];
nonNullListConstructor.setAccessible(true);
nonNullListInstance = nonNullListConstructor.newInstance(new ArrayList<>(), null);
packetConstructor = PacketTypeClasses.Play.Server.WINDOW_ITEMS.getConstructor(int.class, int.class, nonNullListClass, NMSUtils.nmsItemStackClass);
} else {
Constructor<?> nonNullListConstructor = nonNullListClass.getDeclaredConstructor();
nonNullListConstructor.setAccessible(true);
nonNullListInstance = nonNullListConstructor.newInstance();
packetConstructor = PacketTypeClasses.Play.Server.WINDOW_ITEMS.getConstructor(int.class, nonNullListClass);
}
} else {
packetConstructor = PacketTypeClasses.Play.Server.WINDOW_ITEMS.getConstructor();
}
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException e) {
@@ -86,6 +96,22 @@ public class WrappedPacketOutWindowItems extends WrappedPacket implements Sendab
}
}
public int getStateId() {
if (packet != null) {
return readInt(1);
} else {
return stateID;
}
}
public void setStateId(int stateID) {
if (packet != null) {
writeInt(1, stateID);
} else {
this.stateID = stateID;
}
}
public List<ItemStack> getSlots() {
if (packet != null) {
List<ItemStack> slots = new ArrayList<>();
@@ -101,8 +127,7 @@ public class WrappedPacketOutWindowItems extends WrappedPacket implements Sendab
}
}
return slots;
}
else {
} else {
return slotData;
}
}
@@ -122,21 +147,50 @@ public class WrappedPacketOutWindowItems extends WrappedPacket implements Sendab
}
writeAnyObject(1, nmsItemStacks);
}
}
else {
} else {
this.slotData = slots;
}
}
public Optional<ItemStack> getHeldItem() {
if (!v_1_17_1) return Optional.empty();
if (packet != null) {
return Optional.ofNullable(NMSUtils.toBukkitItemStack(readObject(0, NMSUtils.nmsItemStackClass)));
} else {
return Optional.of(heldItem);
}
}
public void setHeldItem(ItemStack heldItem) {
if (packet != null) {
writeObject(0, NMSUtils.toNMSItemStack(heldItem));
} else {
this.heldItem = heldItem;
}
}
private Object getNMSItemHeld() {
if (packet != null) {
return readObject(0, NMSUtils.nmsItemStackClass);
} else {
return NMSUtils.toNMSItemStack(heldItem);
}
}
@Override
public Object asNMSPacket() throws Exception {
Object packetInstance;
if (v_1_17) {
if (v_1_17_1) {
packetInstance = packetConstructor.newInstance(getWindowId(), stateID, nonNullListInstance, getNMSItemHeld());
WrappedPacketOutWindowItems wrappedPacketOutWindowItems = new WrappedPacketOutWindowItems(new NMSPacket(packetInstance));
wrappedPacketOutWindowItems.setSlots(getSlots());
} else if (v_1_17) {
packetInstance = packetConstructor.newInstance(getWindowId(), nonNullListInstance);
WrappedPacketOutWindowItems wrappedPacketOutWindowItems = new WrappedPacketOutWindowItems(new NMSPacket(packetInstance));
wrappedPacketOutWindowItems.setSlots(getSlots());
}
else {
} else {
packetInstance = packetConstructor.newInstance();
WrappedPacketOutWindowItems wrappedPacketOutWindowItems = new WrappedPacketOutWindowItems(new NMSPacket(packetInstance));
wrappedPacketOutWindowItems.setWindowId(getWindowId());
@@ -124,6 +124,7 @@ public class PacketEventsSettings {
* @param compatInjector Value
* @return Settings instance.
*/
@Deprecated
public PacketEventsSettings compatInjector(boolean compatInjector) {
if (!locked) {
this.compatInjector = compatInjector;
@@ -175,6 +176,7 @@ public class PacketEventsSettings {
*
* @return Getter for {@link #compatInjector}
*/
@Deprecated
public boolean shouldUseCompatibilityInjector() {
return compatInjector;
}
@@ -105,7 +105,7 @@ public class AttributeSnapshotWrapper extends WrappedPacket {
nmsAttributeSnapshot = attributeSnapshotConstructor.newInstance(key, value, nmsModifiers);
break;
case 2:
Object minecraftKey = NMSUtils.generateMinecraftKey(key);
Object minecraftKey = NMSUtils.generateMinecraftKeyNew(key);
Object attributeObj = iRegistryAttributeBaseField.get(null);
Object nmsAttributeBase = getiRegistryByMinecraftKeyMethod.invoke(attributeObj, minecraftKey);
nmsAttributeSnapshot = attributeSnapshotConstructor.newInstance(nmsAttributeBase, value, nmsModifiers);
@@ -170,7 +170,7 @@ public class AttributeSnapshotWrapper extends WrappedPacket {
if (stringKeyPresent) {
writeString(0, identifier);
} else {
Object minecraftKey = NMSUtils.generateMinecraftKey(identifier);
Object minecraftKey = NMSUtils.generateMinecraftKeyNew(identifier);
Object attributeObj = null;
try {
attributeObj = iRegistryAttributeBaseField.get(null);
@@ -0,0 +1,670 @@
/*
*
* This file is part of Bukkit - https://hub.spigotmc.org/stash/projects/SPIGOT/repos/bukkit/browse
* Copyright (C) 2011 Bukkit author 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 io.github.retrooper.packetevents.utils.boundingbox;
import org.apache.commons.lang.Validate;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.configuration.serialization.SerializableAs;
import org.bukkit.util.NumberConversions;
import org.bukkit.util.Vector;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
@SerializableAs("BoundingBox")
public class BoundingBox implements Cloneable, ConfigurationSerializable {
private double minX;
private double minY;
private double minZ;
private double maxX;
private double maxY;
private double maxZ;
@NotNull
public static BoundingBox of(@NotNull Vector corner1, @NotNull Vector corner2) {
Validate.notNull(corner1, "Corner1 is null!");
Validate.notNull(corner2, "Corner2 is null!");
return new BoundingBox(corner1.getX(), corner1.getY(), corner1.getZ(), corner2.getX(), corner2.getY(), corner2.getZ());
}
@NotNull
public static BoundingBox of(@NotNull Location corner1, @NotNull Location corner2) {
Validate.notNull(corner1, "Corner1 is null!");
Validate.notNull(corner2, "Corner2 is null!");
Validate.isTrue(Objects.equals(corner1.getWorld(), corner2.getWorld()), "Locations from different worlds!");
return new BoundingBox(corner1.getX(), corner1.getY(), corner1.getZ(), corner2.getX(), corner2.getY(), corner2.getZ());
}
@NotNull
public static BoundingBox of(@NotNull Block corner1, @NotNull Block corner2) {
Validate.notNull(corner1, "Corner1 is null!");
Validate.notNull(corner2, "Corner2 is null!");
Validate.isTrue(Objects.equals(corner1.getWorld(), corner2.getWorld()), "Blocks from different worlds!");
int x1 = corner1.getX();
int y1 = corner1.getY();
int z1 = corner1.getZ();
int x2 = corner2.getX();
int y2 = corner2.getY();
int z2 = corner2.getZ();
int minX = Math.min(x1, x2);
int minY = Math.min(y1, y2);
int minZ = Math.min(z1, z2);
int maxX = Math.max(x1, x2) + 1;
int maxY = Math.max(y1, y2) + 1;
int maxZ = Math.max(z1, z2) + 1;
return new BoundingBox((double) minX, (double) minY, (double) minZ, (double) maxX, (double) maxY, (double) maxZ);
}
@NotNull
public static BoundingBox of(@NotNull Block block) {
Validate.notNull(block, "Block is null!");
return new BoundingBox((double) block.getX(), (double) block.getY(), (double) block.getZ(), (double) (block.getX() + 1), (double) (block.getY() + 1), (double) (block.getZ() + 1));
}
@NotNull
public static BoundingBox of(@NotNull Vector center, double x, double y, double z) {
Validate.notNull(center, "Center is null!");
return new BoundingBox(center.getX() - x, center.getY() - y, center.getZ() - z, center.getX() + x, center.getY() + y, center.getZ() + z);
}
@NotNull
public static BoundingBox of(@NotNull Location center, double x, double y, double z) {
Validate.notNull(center, "Center is null!");
return new BoundingBox(center.getX() - x, center.getY() - y, center.getZ() - z, center.getX() + x, center.getY() + y, center.getZ() + z);
}
public BoundingBox() {
this.resize(0.0D, 0.0D, 0.0D, 0.0D, 0.0D, 0.0D);
}
public BoundingBox(double x1, double y1, double z1, double x2, double y2, double z2) {
this.resize(x1, y1, z1, x2, y2, z2);
}
@NotNull
public BoundingBox resize(double x1, double y1, double z1, double x2, double y2, double z2) {
NumberConversions.checkFinite(x1, "x1 not finite");
NumberConversions.checkFinite(y1, "y1 not finite");
NumberConversions.checkFinite(z1, "z1 not finite");
NumberConversions.checkFinite(x2, "x2 not finite");
NumberConversions.checkFinite(y2, "y2 not finite");
NumberConversions.checkFinite(z2, "z2 not finite");
this.minX = Math.min(x1, x2);
this.minY = Math.min(y1, y2);
this.minZ = Math.min(z1, z2);
this.maxX = Math.max(x1, x2);
this.maxY = Math.max(y1, y2);
this.maxZ = Math.max(z1, z2);
return this;
}
public double getMinX() {
return this.minX;
}
public double getMinY() {
return this.minY;
}
public double getMinZ() {
return this.minZ;
}
@NotNull
public Vector getMin() {
return new Vector(this.minX, this.minY, this.minZ);
}
public double getMaxX() {
return this.maxX;
}
public double getMaxY() {
return this.maxY;
}
public double getMaxZ() {
return this.maxZ;
}
@NotNull
public Vector getMax() {
return new Vector(this.maxX, this.maxY, this.maxZ);
}
public double getWidthX() {
return this.maxX - this.minX;
}
public double getWidthZ() {
return this.maxZ - this.minZ;
}
public double getHeight() {
return this.maxY - this.minY;
}
public double getVolume() {
return this.getHeight() * this.getWidthX() * this.getWidthZ();
}
public double getCenterX() {
return this.minX + this.getWidthX() * 0.5D;
}
public double getCenterY() {
return this.minY + this.getHeight() * 0.5D;
}
public double getCenterZ() {
return this.minZ + this.getWidthZ() * 0.5D;
}
@NotNull
public Vector getCenter() {
return new Vector(this.getCenterX(), this.getCenterY(), this.getCenterZ());
}
@NotNull
public BoundingBox copy(@NotNull BoundingBox other) {
Validate.notNull(other, "Other bounding box is null!");
return this.resize(other.getMinX(), other.getMinY(), other.getMinZ(), other.getMaxX(), other.getMaxY(), other.getMaxZ());
}
@NotNull
public BoundingBox expand(double negativeX, double negativeY, double negativeZ, double positiveX, double positiveY, double positiveZ) {
if (negativeX == 0.0D && negativeY == 0.0D && negativeZ == 0.0D && positiveX == 0.0D && positiveY == 0.0D && positiveZ == 0.0D) {
return this;
} else {
double newMinX = this.minX - negativeX;
double newMinY = this.minY - negativeY;
double newMinZ = this.minZ - negativeZ;
double newMaxX = this.maxX + positiveX;
double newMaxY = this.maxY + positiveY;
double newMaxZ = this.maxZ + positiveZ;
double centerZ;
if (newMinX > newMaxX) {
centerZ = this.getCenterX();
if (newMaxX >= centerZ) {
newMinX = newMaxX;
} else if (newMinX <= centerZ) {
newMaxX = newMinX;
} else {
newMinX = centerZ;
newMaxX = centerZ;
}
}
if (newMinY > newMaxY) {
centerZ = this.getCenterY();
if (newMaxY >= centerZ) {
newMinY = newMaxY;
} else if (newMinY <= centerZ) {
newMaxY = newMinY;
} else {
newMinY = centerZ;
newMaxY = centerZ;
}
}
if (newMinZ > newMaxZ) {
centerZ = this.getCenterZ();
if (newMaxZ >= centerZ) {
newMinZ = newMaxZ;
} else if (newMinZ <= centerZ) {
newMaxZ = newMinZ;
} else {
newMinZ = centerZ;
newMaxZ = centerZ;
}
}
return this.resize(newMinX, newMinY, newMinZ, newMaxX, newMaxY, newMaxZ);
}
}
@NotNull
public BoundingBox expand(double x, double y, double z) {
return this.expand(x, y, z, x, y, z);
}
@NotNull
public BoundingBox expand(@NotNull Vector expansion) {
Validate.notNull(expansion, "Expansion is null!");
double x = expansion.getX();
double y = expansion.getY();
double z = expansion.getZ();
return this.expand(x, y, z, x, y, z);
}
@NotNull
public BoundingBox expand(double expansion) {
return this.expand(expansion, expansion, expansion, expansion, expansion, expansion);
}
@NotNull
public BoundingBox expand(double dirX, double dirY, double dirZ, double expansion) {
if (expansion == 0.0D) {
return this;
} else if (dirX == 0.0D && dirY == 0.0D && dirZ == 0.0D) {
return this;
} else {
double negativeX = dirX < 0.0D ? -dirX * expansion : 0.0D;
double negativeY = dirY < 0.0D ? -dirY * expansion : 0.0D;
double negativeZ = dirZ < 0.0D ? -dirZ * expansion : 0.0D;
double positiveX = dirX > 0.0D ? dirX * expansion : 0.0D;
double positiveY = dirY > 0.0D ? dirY * expansion : 0.0D;
double positiveZ = dirZ > 0.0D ? dirZ * expansion : 0.0D;
return this.expand(negativeX, negativeY, negativeZ, positiveX, positiveY, positiveZ);
}
}
@NotNull
public BoundingBox expand(@NotNull Vector direction, double expansion) {
Validate.notNull(direction, "Direction is null!");
return this.expand(direction.getX(), direction.getY(), direction.getZ(), expansion);
}
@NotNull
public BoundingBox expand(@NotNull BlockFace blockFace, double expansion) {
Validate.notNull(blockFace, "Block face is null!");
return blockFace == BlockFace.SELF ? this : this.expand(blockFace.getDirection(), expansion);
}
@NotNull
public BoundingBox expandDirectional(double dirX, double dirY, double dirZ) {
return this.expand(dirX, dirY, dirZ, 1.0D);
}
@NotNull
public BoundingBox expandDirectional(@NotNull Vector direction) {
Validate.notNull(direction, "Expansion is null!");
return this.expand(direction.getX(), direction.getY(), direction.getZ(), 1.0D);
}
@NotNull
public BoundingBox union(double posX, double posY, double posZ) {
double newMinX = Math.min(this.minX, posX);
double newMinY = Math.min(this.minY, posY);
double newMinZ = Math.min(this.minZ, posZ);
double newMaxX = Math.max(this.maxX, posX);
double newMaxY = Math.max(this.maxY, posY);
double newMaxZ = Math.max(this.maxZ, posZ);
return newMinX == this.minX && newMinY == this.minY && newMinZ == this.minZ && newMaxX == this.maxX && newMaxY == this.maxY && newMaxZ == this.maxZ ? this : this.resize(newMinX, newMinY, newMinZ, newMaxX, newMaxY, newMaxZ);
}
@NotNull
public BoundingBox union(@NotNull Vector position) {
Validate.notNull(position, "Position is null!");
return this.union(position.getX(), position.getY(), position.getZ());
}
@NotNull
public BoundingBox union(@NotNull Location position) {
Validate.notNull(position, "Position is null!");
return this.union(position.getX(), position.getY(), position.getZ());
}
@NotNull
public BoundingBox union(@NotNull BoundingBox other) {
Validate.notNull(other, "Other bounding box is null!");
if (this.contains(other)) {
return this;
} else {
double newMinX = Math.min(this.minX, other.minX);
double newMinY = Math.min(this.minY, other.minY);
double newMinZ = Math.min(this.minZ, other.minZ);
double newMaxX = Math.max(this.maxX, other.maxX);
double newMaxY = Math.max(this.maxY, other.maxY);
double newMaxZ = Math.max(this.maxZ, other.maxZ);
return this.resize(newMinX, newMinY, newMinZ, newMaxX, newMaxY, newMaxZ);
}
}
@NotNull
public BoundingBox intersection(@NotNull BoundingBox other) {
Validate.notNull(other, "Other bounding box is null!");
Validate.isTrue(this.overlaps(other), "The bounding boxes do not overlap!");
double newMinX = Math.max(this.minX, other.minX);
double newMinY = Math.max(this.minY, other.minY);
double newMinZ = Math.max(this.minZ, other.minZ);
double newMaxX = Math.min(this.maxX, other.maxX);
double newMaxY = Math.min(this.maxY, other.maxY);
double newMaxZ = Math.min(this.maxZ, other.maxZ);
return this.resize(newMinX, newMinY, newMinZ, newMaxX, newMaxY, newMaxZ);
}
@NotNull
public BoundingBox shift(double shiftX, double shiftY, double shiftZ) {
return shiftX == 0.0D && shiftY == 0.0D && shiftZ == 0.0D ? this : this.resize(this.minX + shiftX, this.minY + shiftY, this.minZ + shiftZ, this.maxX + shiftX, this.maxY + shiftY, this.maxZ + shiftZ);
}
@NotNull
public BoundingBox shift(@NotNull Vector shift) {
Validate.notNull(shift, "Shift is null!");
return this.shift(shift.getX(), shift.getY(), shift.getZ());
}
@NotNull
public BoundingBox shift(@NotNull Location shift) {
Validate.notNull(shift, "Shift is null!");
return this.shift(shift.getX(), shift.getY(), shift.getZ());
}
private boolean overlaps(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) {
return this.minX < maxX && this.maxX > minX && this.minY < maxY && this.maxY > minY && this.minZ < maxZ && this.maxZ > minZ;
}
public boolean overlaps(@NotNull BoundingBox other) {
Validate.notNull(other, "Other bounding box is null!");
return this.overlaps(other.minX, other.minY, other.minZ, other.maxX, other.maxY, other.maxZ);
}
public boolean overlaps(@NotNull Vector min, @NotNull Vector max) {
Validate.notNull(min, "Min is null!");
Validate.notNull(max, "Max is null!");
double x1 = min.getX();
double y1 = min.getY();
double z1 = min.getZ();
double x2 = max.getX();
double y2 = max.getY();
double z2 = max.getZ();
return this.overlaps(Math.min(x1, x2), Math.min(y1, y2), Math.min(z1, z2), Math.max(x1, x2), Math.max(y1, y2), Math.max(z1, z2));
}
public boolean contains(double x, double y, double z) {
return x >= this.minX && x < this.maxX && y >= this.minY && y < this.maxY && z >= this.minZ && z < this.maxZ;
}
public boolean contains(@NotNull Vector position) {
Validate.notNull(position, "Position is null!");
return this.contains(position.getX(), position.getY(), position.getZ());
}
private boolean contains(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) {
return this.minX <= minX && this.maxX >= maxX && this.minY <= minY && this.maxY >= maxY && this.minZ <= minZ && this.maxZ >= maxZ;
}
public boolean contains(@NotNull BoundingBox other) {
Validate.notNull(other, "Other bounding box is null!");
return this.contains(other.minX, other.minY, other.minZ, other.maxX, other.maxY, other.maxZ);
}
public boolean contains(@NotNull Vector min, @NotNull Vector max) {
Validate.notNull(min, "Min is null!");
Validate.notNull(max, "Max is null!");
double x1 = min.getX();
double y1 = min.getY();
double z1 = min.getZ();
double x2 = max.getX();
double y2 = max.getY();
double z2 = max.getZ();
return this.contains(Math.min(x1, x2), Math.min(y1, y2), Math.min(z1, z2), Math.max(x1, x2), Math.max(y1, y2), Math.max(z1, z2));
}
@Nullable
public RayTraceResult rayTrace(@NotNull Vector start, @NotNull Vector direction, double maxDistance) {
Validate.notNull(start, "Start is null!");
start.checkFinite();
Validate.notNull(direction, "Direction is null!");
direction.checkFinite();
Validate.isTrue(direction.lengthSquared() > 0.0D, "Direction's magnitude is 0!");
if (maxDistance < 0.0D) {
return null;
} else {
double startX = start.getX();
double startY = start.getY();
double startZ = start.getZ();
Vector normalizedZeroDir = direction.clone();
if (normalizedZeroDir.getX() == -0.0D) {
normalizedZeroDir.setX(0.0D);
}
if (normalizedZeroDir.getY() == -0.0D) {
normalizedZeroDir.setY(0.0D);
}
if (normalizedZeroDir.getZ() == -0.0D) {
normalizedZeroDir.setZ(0.0D);
}
Vector dir = normalizedZeroDir.normalize();
double dirX = dir.getX();
double dirY = dir.getY();
double dirZ = dir.getZ();
double divX = 1.0D / dirX;
double divY = 1.0D / dirY;
double divZ = 1.0D / dirZ;
double tMin;
double tMax;
BlockFace hitBlockFaceMin;
BlockFace hitBlockFaceMax;
if (dirX >= 0.0D) {
tMin = (this.minX - startX) * divX;
tMax = (this.maxX - startX) * divX;
hitBlockFaceMin = BlockFace.WEST;
hitBlockFaceMax = BlockFace.EAST;
} else {
tMin = (this.maxX - startX) * divX;
tMax = (this.minX - startX) * divX;
hitBlockFaceMin = BlockFace.EAST;
hitBlockFaceMax = BlockFace.WEST;
}
double tyMin;
double tyMax;
BlockFace hitBlockFaceYMin;
BlockFace hitBlockFaceYMax;
if (dirY >= 0.0D) {
tyMin = (this.minY - startY) * divY;
tyMax = (this.maxY - startY) * divY;
hitBlockFaceYMin = BlockFace.DOWN;
hitBlockFaceYMax = BlockFace.UP;
} else {
tyMin = (this.maxY - startY) * divY;
tyMax = (this.minY - startY) * divY;
hitBlockFaceYMin = BlockFace.UP;
hitBlockFaceYMax = BlockFace.DOWN;
}
if (!(tMin > tyMax) && !(tMax < tyMin)) {
if (tyMin > tMin) {
tMin = tyMin;
hitBlockFaceMin = hitBlockFaceYMin;
}
if (tyMax < tMax) {
tMax = tyMax;
hitBlockFaceMax = hitBlockFaceYMax;
}
double tzMin;
double tzMax;
BlockFace hitBlockFaceZMin;
BlockFace hitBlockFaceZMax;
if (dirZ >= 0.0D) {
tzMin = (this.minZ - startZ) * divZ;
tzMax = (this.maxZ - startZ) * divZ;
hitBlockFaceZMin = BlockFace.NORTH;
hitBlockFaceZMax = BlockFace.SOUTH;
} else {
tzMin = (this.maxZ - startZ) * divZ;
tzMax = (this.minZ - startZ) * divZ;
hitBlockFaceZMin = BlockFace.SOUTH;
hitBlockFaceZMax = BlockFace.NORTH;
}
if (!(tMin > tzMax) && !(tMax < tzMin)) {
if (tzMin > tMin) {
tMin = tzMin;
hitBlockFaceMin = hitBlockFaceZMin;
}
if (tzMax < tMax) {
tMax = tzMax;
hitBlockFaceMax = hitBlockFaceZMax;
}
if (tMax < 0.0D) {
return null;
} else if (tMin > maxDistance) {
return null;
} else {
double t;
BlockFace hitBlockFace;
if (tMin < 0.0D) {
t = tMax;
hitBlockFace = hitBlockFaceMax;
} else {
t = tMin;
hitBlockFace = hitBlockFaceMin;
}
Vector hitPosition = dir.multiply(t).add(start);
return new RayTraceResult(hitPosition, hitBlockFace);
}
} else {
return null;
}
} else {
return null;
}
}
}
public int hashCode() {
long temp = Double.doubleToLongBits(this.maxX);
int result = 31 + (int) (temp ^ temp >>> 32);
temp = Double.doubleToLongBits(this.maxY);
result = 31 * result + (int) (temp ^ temp >>> 32);
temp = Double.doubleToLongBits(this.maxZ);
result = 31 * result + (int) (temp ^ temp >>> 32);
temp = Double.doubleToLongBits(this.minX);
result = 31 * result + (int) (temp ^ temp >>> 32);
temp = Double.doubleToLongBits(this.minY);
result = 31 * result + (int) (temp ^ temp >>> 32);
temp = Double.doubleToLongBits(this.minZ);
result = 31 * result + (int) (temp ^ temp >>> 32);
return result;
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
} else if (!(obj instanceof BoundingBox)) {
return false;
} else {
BoundingBox other = (BoundingBox) obj;
if (Double.doubleToLongBits(this.maxX) != Double.doubleToLongBits(other.maxX)) {
return false;
} else if (Double.doubleToLongBits(this.maxY) != Double.doubleToLongBits(other.maxY)) {
return false;
} else if (Double.doubleToLongBits(this.maxZ) != Double.doubleToLongBits(other.maxZ)) {
return false;
} else if (Double.doubleToLongBits(this.minX) != Double.doubleToLongBits(other.minX)) {
return false;
} else if (Double.doubleToLongBits(this.minY) != Double.doubleToLongBits(other.minY)) {
return false;
} else {
return Double.doubleToLongBits(this.minZ) == Double.doubleToLongBits(other.minZ);
}
}
}
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("BoundingBox [minX=");
builder.append(this.minX);
builder.append(", minY=");
builder.append(this.minY);
builder.append(", minZ=");
builder.append(this.minZ);
builder.append(", maxX=");
builder.append(this.maxX);
builder.append(", maxY=");
builder.append(this.maxY);
builder.append(", maxZ=");
builder.append(this.maxZ);
builder.append("]");
return builder.toString();
}
@NotNull
public BoundingBox clone() {
try {
return (BoundingBox) super.clone();
} catch (CloneNotSupportedException var2) {
throw new Error(var2);
}
}
@NotNull
public Map<String, Object> serialize() {
Map<String, Object> result = new LinkedHashMap();
result.put("minX", this.minX);
result.put("minY", this.minY);
result.put("minZ", this.minZ);
result.put("maxX", this.maxX);
result.put("maxY", this.maxY);
result.put("maxZ", this.maxZ);
return result;
}
@NotNull
public static BoundingBox deserialize(@NotNull Map<String, Object> args) {
double minX = 0.0D;
double minY = 0.0D;
double minZ = 0.0D;
double maxX = 0.0D;
double maxY = 0.0D;
double maxZ = 0.0D;
if (args.containsKey("minX")) {
minX = ((Number) args.get("minX")).doubleValue();
}
if (args.containsKey("minY")) {
minY = ((Number) args.get("minY")).doubleValue();
}
if (args.containsKey("minZ")) {
minZ = ((Number) args.get("minZ")).doubleValue();
}
if (args.containsKey("maxX")) {
maxX = ((Number) args.get("maxX")).doubleValue();
}
if (args.containsKey("maxY")) {
maxY = ((Number) args.get("maxY")).doubleValue();
}
if (args.containsKey("maxZ")) {
maxZ = ((Number) args.get("maxZ")).doubleValue();
}
return new BoundingBox(minX, minY, minZ, maxX, maxY, maxZ);
}
}
@@ -0,0 +1,128 @@
/*
*
* This file is part of Bukkit - https://hub.spigotmc.org/stash/projects/SPIGOT/repos/bukkit/browse
* Copyright (C) 2011 Bukkit author 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 io.github.retrooper.packetevents.utils.boundingbox;
import org.apache.commons.lang.Validate;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Entity;
import org.bukkit.util.Vector;
import java.util.Objects;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class RayTraceResult {
private final Vector hitPosition;
private final Block hitBlock;
private final BlockFace hitBlockFace;
private final Entity hitEntity;
private RayTraceResult(@NotNull Vector hitPosition, @Nullable Block hitBlock, @Nullable BlockFace hitBlockFace, @Nullable Entity hitEntity) {
Validate.notNull(hitPosition, "Hit position is null!");
this.hitPosition = hitPosition.clone();
this.hitBlock = hitBlock;
this.hitBlockFace = hitBlockFace;
this.hitEntity = hitEntity;
}
public RayTraceResult(@NotNull Vector hitPosition) {
this(hitPosition, (Block)null, (BlockFace)null, (Entity)null);
}
public RayTraceResult(@NotNull Vector hitPosition, @Nullable BlockFace hitBlockFace) {
this(hitPosition, (Block)null, hitBlockFace, (Entity)null);
}
public RayTraceResult(@NotNull Vector hitPosition, @Nullable Block hitBlock, @Nullable BlockFace hitBlockFace) {
this(hitPosition, hitBlock, hitBlockFace, (Entity)null);
}
public RayTraceResult(@NotNull Vector hitPosition, @Nullable Entity hitEntity) {
this(hitPosition, (Block)null, (BlockFace)null, hitEntity);
}
public RayTraceResult(@NotNull Vector hitPosition, @Nullable Entity hitEntity, @Nullable BlockFace hitBlockFace) {
this(hitPosition, (Block)null, hitBlockFace, hitEntity);
}
@NotNull
public Vector getHitPosition() {
return this.hitPosition.clone();
}
@Nullable
public Block getHitBlock() {
return this.hitBlock;
}
@Nullable
public BlockFace getHitBlockFace() {
return this.hitBlockFace;
}
@Nullable
public Entity getHitEntity() {
return this.hitEntity;
}
public int hashCode() {
int result = 31 + this.hitPosition.hashCode();
result = 31 * result + (this.hitBlock == null ? 0 : this.hitBlock.hashCode());
result = 31 * result + (this.hitBlockFace == null ? 0 : this.hitBlockFace.hashCode());
result = 31 * result + (this.hitEntity == null ? 0 : this.hitEntity.hashCode());
return result;
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
} else if (!(obj instanceof RayTraceResult)) {
return false;
} else {
RayTraceResult other = (RayTraceResult)obj;
if (!this.hitPosition.equals(other.hitPosition)) {
return false;
} else if (!Objects.equals(this.hitBlock, other.hitBlock)) {
return false;
} else if (!Objects.equals(this.hitBlockFace, other.hitBlockFace)) {
return false;
} else {
return Objects.equals(this.hitEntity, other.hitEntity);
}
}
}
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("RayTraceResult [hitPosition=");
builder.append(this.hitPosition);
builder.append(", hitBlock=");
builder.append(this.hitBlock);
builder.append(", hitBlockFace=");
builder.append(this.hitBlockFace);
builder.append(", hitEntity=");
builder.append(this.hitEntity);
builder.append("]");
return builder.toString();
}
}
@@ -50,9 +50,7 @@ public final class EntityFinderUtils {
try {
craftWorldGetHandle = NMSUtils.craftWorldClass.getMethod("getHandle");
String getEntityByIdMethodName = (version.getProtocolVersion() == (short) 47)
? "a" : "getEntity";
getEntityByIdMethod = worldServerClass.getMethod(getEntityByIdMethodName, int.class);
getEntityByIdMethod = worldServerClass.getMethod("a", int.class);
} catch (NoSuchMethodException e) {
try {
getEntityByIdMethod = worldServerClass.getMethod("getEntity", int.class);
@@ -1,31 +1,67 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2021 retrooper and contributors
*
* * This file is part of packetevents - https://github.com/retrooper/packetevents
* * Copyright (C) 2016-2021 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/>.
* 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 io.github.retrooper.packetevents.utils.geyser;
import org.geysermc.connector.GeyserConnector;
import io.github.retrooper.packetevents.utils.reflection.Reflection;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.UUID;
public class GeyserUtils {
private static Class<?> GEYSER_CLASS;
private static Class<?> GEYSER_API_CLASS;
private static Method GEYSER_API_METHOD;
private static Method CONNECTION_BY_UUID_METHOD;
public static boolean isGeyserPlayer(UUID uuid) {
return GeyserConnector.getInstance().getPlayerByUuid(uuid) != null;
if (GEYSER_CLASS == null) {
GEYSER_CLASS = Reflection.getClassByNameWithoutException("org.geysermc.api.Geyser");
}
if (GEYSER_CLASS == null) {
return false;
}
if (GEYSER_API_CLASS == null) {
GEYSER_API_CLASS = Reflection.getClassByNameWithoutException("org.geysermc.api.GeyserApiBase");
}
if (GEYSER_API_METHOD == null) {
GEYSER_API_METHOD = Reflection.getMethod(GEYSER_CLASS, "api", null, new Class<?>[]{});
}
if (CONNECTION_BY_UUID_METHOD == null) {
CONNECTION_BY_UUID_METHOD = Reflection.getMethod(GEYSER_API_CLASS, "connectionByUuid", 0);
}
Object apiInstance = null;
try {
apiInstance = GEYSER_API_METHOD.invoke(null);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
Object connection = null;
try {
if (apiInstance != null) {
connection = CONNECTION_BY_UUID_METHOD.invoke(apiInstance, uuid);
}
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
return connection != null;
}
}
@@ -1,21 +1,19 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2021 retrooper and contributors
*
* * This file is part of packetevents - https://github.com/retrooper/packetevents
* * Copyright (C) 2016-2021 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/>.
* 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 io.github.retrooper.packetevents.utils.guava;
@@ -1,21 +1,19 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2021 retrooper and contributors
*
* * This file is part of packetevents - https://github.com/retrooper/packetevents
* * Copyright (C) 2016-2021 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/>.
* 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 io.github.retrooper.packetevents.utils.guava;
@@ -1,21 +1,19 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2021 retrooper and contributors
*
* * This file is part of packetevents - https://github.com/retrooper/packetevents
* * Copyright (C) 2016-2021 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/>.
* 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 io.github.retrooper.packetevents.utils.guava;
@@ -1,6 +1,6 @@
/*
* This file is part of ViaVersion - https://github.com/ViaVersion/ViaVersion
* Copyright (C) 2016-2021 ViaVersion and contributors
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2021 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
@@ -1,21 +1,19 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2021 retrooper and contributors
*
* * This file is part of packetevents - https://github.com/retrooper/packetevents
* * Copyright (C) 2016-2021 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/>.
* 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 io.github.retrooper.packetevents.utils.math;
@@ -21,17 +21,13 @@ package io.github.retrooper.packetevents.utils.nms;
import io.github.retrooper.packetevents.PacketEvents;
import io.github.retrooper.packetevents.packetwrappers.NMSPacket;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.utils.entityfinder.EntityFinderUtils;
import io.github.retrooper.packetevents.utils.reflection.Reflection;
import io.github.retrooper.packetevents.utils.reflection.SubclassUtil;
import io.github.retrooper.packetevents.utils.server.ServerVersion;
import io.github.retrooper.packetevents.utils.vector.Vector3d;
import io.github.retrooper.packetevents.utils.vector.Vector3f;
import io.github.retrooper.packetevents.utils.vector.Vector3i;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.*;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
@@ -47,32 +43,29 @@ import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
public final class NMSUtils {
private static boolean v_1_17;
public static final String NMS_DIR = ServerVersion.getNMSDirectory() + ".";
public static final String OBC_DIR = ServerVersion.getOBCDirectory() + ".";
private static final ThreadLocal<Random> randomThreadLocal = ThreadLocal.withInitial(Random::new);
public static boolean legacyNettyImportMode;
public static ServerVersion version;
public static Constructor<?> blockPosConstructor, minecraftKeyConstructor, vec3DConstructor, dataWatcherConstructor, packetDataSerializerConstructor;
public static Constructor<?> blockPosConstructor, minecraftKeyConstructor, vec3DConstructor, dataWatcherConstructor, packetDataSerializerConstructor, itemStackConstructor;
public static Class<?> mobEffectListClass, nmsEntityClass, minecraftServerClass, craftWorldClass, playerInteractManagerClass, entityPlayerClass, playerConnectionClass, craftServerClass,
craftPlayerClass, serverConnectionClass, craftEntityClass, nmsItemStackClass, networkManagerClass, nettyChannelClass, gameProfileClass, iChatBaseComponentClass,
blockPosClass, vec3DClass, channelFutureClass, blockClass, iBlockDataClass, nmsWorldClass, craftItemStackClass,
blockPosClass, sectionPositionClass, vec3DClass, channelFutureClass, blockClass, iBlockDataClass, nmsWorldClass, craftItemStackClass,
soundEffectClass, minecraftKeyClass, chatSerializerClass, craftMagicNumbersClass, worldSettingsClass, worldServerClass, dataWatcherClass,
dedicatedServerClass, entityHumanClass, packetDataSerializerClass, byteBufClass, dimensionManagerClass, nmsItemClass;
public static Class<? extends Enum<?>> enumDirectionClass, enumHandClass, enumGameModeClass, enumDifficultyClass;
dedicatedServerClass, entityHumanClass, packetDataSerializerClass, byteBufClass, dimensionManagerClass, nmsItemClass, iMaterialClass, movingObjectPositionBlockClass, boundingBoxClass,
tileEntityCommandClass;
public static Class<? extends Enum<?>> enumDirectionClass, enumHandClass, enumGameModeClass, enumDifficultyClass, tileEntityCommandTypeClass;
public static Method getBlockPosX, getBlockPosY, getBlockPosZ;
private static String nettyPrefix;
private static Method getCraftPlayerHandle, getCraftEntityHandle, getCraftWorldHandle, asBukkitCopy,
asNMSCopy, getMessageMethod, chatFromStringMethod, getMaterialFromNMSBlock, getNMSBlockFromMaterial,
getMobEffectListId, getMobEffectListById, getItemId, getItemById, getBukkitEntity;
private static Field entityPlayerPingField;
private static Field entityPlayerPingField, entityBoundingBoxField;
private static Object minecraftServer;
private static Object minecraftServerConnection;
public static void load() {
if (version.isNewerThanOrEquals(ServerVersion.v_1_17)) {
v_1_17 = true;
}
String legacyNettyPrefix = "net.minecraft.util.io.netty.";
String newNettyPrefix = "io.netty.";
if (version.isNewerThan(ServerVersion.v_1_7_10)) {
@@ -82,12 +75,11 @@ public final class NMSUtils {
legacyNettyImportMode = true;
nettyPrefix = legacyNettyPrefix;
}
try {
//Test if the selected netty location is valid
getNettyClass("channel.Channel");
} catch (Exception ex) {
System.err.println("[packetevents] Failed to locate the netty package location for your server version. Searching...");
Bukkit.getConsoleSender().sendMessage(ChatColor.DARK_RED + "[packetevents] Failed to locate the netty package location for your server version. Searching...");
//Time to correct the netty location
if (legacyNettyImportMode) {
legacyNettyImportMode = false;
@@ -116,6 +108,13 @@ public final class NMSUtils {
nmsEntityClass = getNMClassWithoutException("world.entity.Entity");
}
boundingBoxClass = getNMSClassWithoutException("AxisAlignedBB");
if (boundingBoxClass == null) {
boundingBoxClass = getNMClassWithoutException("world.phys.AxisAlignedBB");
}
entityBoundingBoxField = Reflection.getField(nmsEntityClass, boundingBoxClass, 0, true);
if (nmsEntityClass != null) {
getBukkitEntity = Reflection.getMethod(nmsEntityClass, craftEntityClass, 0);
}
@@ -188,6 +187,10 @@ public final class NMSUtils {
if (nmsItemClass == null) {
nmsItemClass = getNMClassWithoutException("world.item.Item");
}
iMaterialClass = getNMSClassWithoutException("IMaterial");
if (iMaterialClass == null) {
iMaterialClass = getNMClassWithoutException("world.level.IMaterial");
}
dedicatedServerClass = getNMSClassWithoutException("DedicatedServer");
if (dedicatedServerClass == null) {
dedicatedServerClass = getNMClassWithoutException("server.dedicated.DedicatedServer");
@@ -220,6 +223,14 @@ public final class NMSUtils {
if (iChatBaseComponentClass == null) {
iChatBaseComponentClass = getNMClassWithoutException("network.chat.IChatBaseComponent");
}
tileEntityCommandClass = NMSUtils.getNMSClassWithoutException("TileEntityCommand");
if (tileEntityCommandClass == null) {
tileEntityCommandClass = NMSUtils.getNMClassWithoutException("world.level.block.entity.TileEntityCommand");
}
tileEntityCommandTypeClass = SubclassUtil.getEnumSubClass(tileEntityCommandClass, 0);
vec3DClass = NMSUtils.getNMSClassWithoutException("Vec3D");
if (vec3DClass == null) {
vec3DClass = getNMClassWithoutException("world.phys.Vec3D");
@@ -231,6 +242,19 @@ public final class NMSUtils {
blockPosClass = getNMClassWithoutException("core.BlockPosition");
}
}
sectionPositionClass = getNMSClassWithoutException("SectionPosition");
if (sectionPositionClass == null) {
sectionPositionClass = getNMClassWithoutException("core.SectionPosition");
}
if (version.isNewerThanOrEquals(ServerVersion.v_1_14)) {
movingObjectPositionBlockClass = NMSUtils.getNMSClassWithoutException("MovingObjectPositionBlock");
if (movingObjectPositionBlockClass == null) {
movingObjectPositionBlockClass = getNMClassWithoutException("world.phys.MovingObjectPositionBlock");
}
}
try {
//If null, it is 1.7.10
if (blockPosClass != null) {
@@ -244,6 +268,10 @@ public final class NMSUtils {
if (dataWatcherClass != null) {
dataWatcherConstructor = dataWatcherClass.getConstructor(nmsEntityClass);
}
if (nmsItemStackClass != null && iMaterialClass != null) {
itemStackConstructor = nmsItemStackClass.getDeclaredConstructor(iMaterialClass);
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
@@ -298,11 +326,11 @@ public final class NMSUtils {
try {
if (mobEffectListClass != null) {
getMobEffectListId = mobEffectListClass.getMethod("getId", mobEffectListClass);
getMobEffectListById = mobEffectListClass.getMethod("fromId", int.class);
getMobEffectListId = Reflection.getMethod(mobEffectListClass, 0, mobEffectListClass);
getMobEffectListById = Reflection.getMethod(mobEffectListClass, 0, int.class);
}
} catch (Exception ignored) {
} catch (Exception ex) {
ex.printStackTrace();
}
try {
entityPlayerPingField = entityPlayerClass.getField("ping");
@@ -311,9 +339,19 @@ public final class NMSUtils {
}
//In case its null, these methods are not needed and would cause errors
if (blockPosClass != null) {
getBlockPosX = Reflection.getMethod(NMSUtils.blockPosClass.getSuperclass(), "getX", 0);
getBlockPosY = Reflection.getMethod(NMSUtils.blockPosClass.getSuperclass(), "getY", 0);
getBlockPosZ = Reflection.getMethod(NMSUtils.blockPosClass.getSuperclass(), "getZ", 0);
getBlockPosX = Reflection.getMethod(NMSUtils.blockPosClass, "getX", int.class);
getBlockPosY = Reflection.getMethod(NMSUtils.blockPosClass, "getY", int.class);
getBlockPosZ = Reflection.getMethod(NMSUtils.blockPosClass, "getZ", int.class);
// Mappings changed with 1.18
if (getBlockPosX == null) {
getBlockPosX = Reflection.getMethod(NMSUtils.blockPosClass, "u", int.class);
}
if (getBlockPosY == null) {
getBlockPosY = Reflection.getMethod(NMSUtils.blockPosClass, "v", int.class);
}
if (getBlockPosZ == null) {
getBlockPosZ = Reflection.getMethod(NMSUtils.blockPosClass, "w", int.class);
}
}
worldSettingsClass = NMSUtils.getNMSClassWithoutException("WorldSettings");
if (worldServerClass == null) {
@@ -362,7 +400,10 @@ public final class NMSUtils {
}
public static double[] recentTPS() {
return new WrappedPacket(new NMSPacket(getMinecraftServerInstance(Bukkit.getServer())), minecraftServerClass).readDoubleArray(0);
WrappedPacket minecraftServerInstanceReader = new WrappedPacket(
new NMSPacket(getMinecraftServerInstance(Bukkit.getServer())),
minecraftServerClass);
return minecraftServerInstanceReader.readDoubleArray(0);
}
public static Class<?> getNMSClass(String name) throws ClassNotFoundException {
@@ -421,7 +462,7 @@ public final class NMSUtils {
@Nullable
@Deprecated
public static Entity getEntityById(@Nullable World world, int id) {
return PacketEvents.get().getServerUtils().getEntityById(world, id);
return PacketEvents.get().getServerUtils().getEntityById(world, id);
}
public static Entity getBukkitEntity(Object nmsEntity) {
@@ -444,6 +485,15 @@ public final class NMSUtils {
return null;
}
public static Object getNMSAxisAlignedBoundingBox(Object nmsEntity) {
try {
return entityBoundingBoxField.get(nmsEntityClass.cast(nmsEntity));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
public static Object getCraftPlayer(final Player player) {
return craftPlayerClass.cast(player);
}
@@ -499,7 +549,7 @@ public final class NMSUtils {
if (networkManager == null) {
return null;
}
WrappedPacket wrapper = new WrappedPacket(new NMSPacket(networkManager));
WrappedPacket wrapper = new WrappedPacket(new NMSPacket(networkManager), networkManagerClass);
return wrapper.readObject(0, nettyChannelClass);
}
@@ -636,7 +686,19 @@ public final class NMSUtils {
return minecraftKeyWrapper.readString(1);
}
public static Object generateMinecraftKey(String text) {
public static String[] splitMinecraftKey(String var0, char var1) {
String[] array = new String[]{"minecraft", var0};
int index = var0.indexOf(var1);
if (index >= 0) {
array[1] = var0.substring(index + 1);
if (index >= 1) {
array[0] = var0.substring(0, index);
}
}
return array;
}
public static Object generateMinecraftKeyNew(String text) {
try {
return minecraftKeyConstructor.newInstance(text);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
@@ -680,9 +742,9 @@ public final class NMSUtils {
return null;
}
public static Object generateDataWatcher(Entity entity) {
public static Object generateDataWatcher(Object nmsEntity) {
try {
return dataWatcherConstructor.newInstance(entity);
return dataWatcherConstructor.newInstance(nmsEntity);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
@@ -1,21 +1,19 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2021 retrooper and contributors
*
* * This file is part of packetevents - https://github.com/retrooper/packetevents
* * Copyright (C) 2016-2021 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/>.
* 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 io.github.retrooper.packetevents.utils.nms;
@@ -157,6 +157,15 @@ public class NPC {
return yaw;
}
public void teleport(Player player, Vector3d targetPosition, float yaw, float pitch) {
this.position = targetPosition;
this.yaw = yaw;
this.pitch = pitch;
if (hasSpawned(player)) {
PacketEvents.get().getPlayerUtils().sendPacket(player, new WrappedPacketOutEntityTeleport(entityID, position, yaw, pitch, onGround));
}
}
public void move(Player player, Vector3d targetPosition) {
this.position = targetPosition;
double distX = targetPosition.x - position.x;
@@ -166,8 +175,7 @@ public class NPC {
SendableWrapper sentPacket;
if (dist > 8) {
sentPacket = new WrappedPacketOutEntityTeleport(entityID, position, yaw, pitch, onGround);
}
else {
} else {
sentPacket = new WrappedPacketOutEntity.WrappedPacketOutRelEntityMove(entityID, distX, distY, distZ, onGround);
}
@@ -187,9 +195,8 @@ public class NPC {
SendableWrapper sentPacket;
if (dist > 8) {
sentPacket = new WrappedPacketOutEntityTeleport(entityID, position, yaw, pitch, onGround);
}
else {
sentPacket = new WrappedPacketOutEntity.WrappedPacketOutRelEntityMoveLook(entityID, distX, distY, distZ, (byte) yaw, (byte) pitch, onGround);
} else {
sentPacket = new WrappedPacketOutEntity.WrappedPacketOutRelEntityMoveLook(entityID, distX, distY, distZ, yaw, pitch, onGround);
}
if (hasSpawned(player)) {
PacketEvents.get().getPlayerUtils().sendPacket(player, sentPacket);
@@ -207,6 +214,17 @@ public class NPC {
}
}
public void teleport(List<Player> players, Vector3d targetPosition, float yaw, float pitch) {
this.position = targetPosition;
this.yaw = yaw;
this.pitch = pitch;
for (Player player : players) {
if (hasSpawned(player)) {
PacketEvents.get().getPlayerUtils().sendPacket(player, new WrappedPacketOutEntityTeleport(entityID, position, yaw, pitch, onGround));
}
}
}
public void move(List<Player> players, Vector3d targetPosition) {
double distX = targetPosition.x - position.x;
double distY = targetPosition.y - position.y;
@@ -216,8 +234,7 @@ public class NPC {
SendableWrapper sentPacket;
if (dist > 8) {
sentPacket = new WrappedPacketOutEntityTeleport(entityID, position, yaw, pitch, onGround);
}
else {
} else {
sentPacket = new WrappedPacketOutEntity.WrappedPacketOutRelEntityMove(entityID, distX, distY, distZ, onGround);
}
for (Player player : players) {
@@ -238,9 +255,8 @@ public class NPC {
SendableWrapper sentPacket;
if (dist > 8) {
sentPacket = new WrappedPacketOutEntityTeleport(entityID, position, yaw, pitch, onGround);
}
else {
sentPacket = new WrappedPacketOutEntity.WrappedPacketOutRelEntityMoveLook(entityID, distX, distY, distZ, (byte) yaw, (byte) pitch, onGround);
} else {
sentPacket = new WrappedPacketOutEntity.WrappedPacketOutRelEntityMoveLook(entityID, distX, distY, distZ, yaw, pitch, onGround);
}
for (Player player : players) {
if (hasSpawned(player)) {
@@ -274,7 +290,7 @@ public class NPC {
}
@Deprecated
public void moveDeltaAndRotate(List<Player> players, Vector3d deltaPosition, byte yaw, byte pitch) {
public void moveDeltaAndRotate(List<Player> players, Vector3d deltaPosition, float yaw, float pitch) {
this.position = this.position.add(deltaPosition);
this.yaw = yaw;
this.pitch = pitch;
@@ -87,11 +87,18 @@ public enum ClientVersion {
v_1_17_1(756),
/**
* 1.18 or 1.18.1 as they have the same protocol version.
*/
v_1_18(757),
v_1_18_2(758),
LOWER_THAN_SUPPORTED_VERSIONS(v_1_7_10.protocolVersion - 1),
HIGHER_THAN_SUPPORTED_VERSIONS(v_1_17_1.protocolVersion + 1),
HIGHER_THAN_SUPPORTED_VERSIONS(v_1_18_2.protocolVersion + 1),
/**
* Pre releases just aren't supported, we would end up with so many enum constants.
* This constant assures you they are on a pre release.
* This constant assures you they are on a pre-release.
*/
ANY_PRE_RELEASE_VERSION(0),
@@ -102,16 +109,17 @@ public enum ClientVersion {
UNKNOWN(-1);
private static final short LOWEST_SUPPORTED_PROTOCOL_VERSION = (short) (LOWER_THAN_SUPPORTED_VERSIONS.protocolVersion + 1);
private static final short HIGHEST_SUPPORTED_PROTOCOL_VERSION = (short) (HIGHER_THAN_SUPPORTED_VERSIONS.protocolVersion - 1);
private static final int LOWEST_SUPPORTED_PROTOCOL_VERSION = LOWER_THAN_SUPPORTED_VERSIONS.protocolVersion + 1;
private static final int HIGHEST_SUPPORTED_PROTOCOL_VERSION = HIGHER_THAN_SUPPORTED_VERSIONS.protocolVersion - 1;
private static final Map<Short, ClientVersion> CLIENT_VERSION_CACHE = new IdentityHashMap<>();
private static final short[] CLIENT_VERSIONS = new short[]{5, 47, 107, 108, 109, 110, 210, 315, 316, 335, 338,
340, 393, 401, 404, 477, 480, 485, 490, 498, 573, 575, 578, 735, 736, 751, 753, 754, 755, 756};
private short protocolVersion;
private static final Map<Integer, ClientVersion> CLIENT_VERSION_CACHE = new IdentityHashMap<>();
private static final int[] CLIENT_VERSIONS = new int[]{5, 47, 107, 108, 109, 110, 210, 315, 316, 335, 338,
340, 393, 401, 404, 477, 480, 485, 490, 498, 573,
575, 578, 735, 736, 751, 753, 754, 755, 756, 757, 758};
private int protocolVersion;
ClientVersion(int protocolVersion) {
this.protocolVersion = (short) protocolVersion;
this.protocolVersion = protocolVersion;
}
/**
@@ -129,19 +137,19 @@ public enum ClientVersion {
} else if (protocolVersion > HIGHEST_SUPPORTED_PROTOCOL_VERSION) {
return HIGHER_THAN_SUPPORTED_VERSIONS;
} else {
ClientVersion cached = CLIENT_VERSION_CACHE.get((short) protocolVersion);
ClientVersion cached = CLIENT_VERSION_CACHE.get(protocolVersion);
if (cached == null) {
for (ClientVersion version : values()) {
if (version.protocolVersion > protocolVersion) {
break;
} else if (version.protocolVersion == protocolVersion) {
//Cache for next time
CLIENT_VERSION_CACHE.put((short) protocolVersion, version);
CLIENT_VERSION_CACHE.put(protocolVersion, version);
return version;
}
}
cached = UNKNOWN;
cached.protocolVersion = (short) protocolVersion;
cached.protocolVersion = protocolVersion;
}
return cached;
}
@@ -152,7 +160,7 @@ public enum ClientVersion {
*
* @return Protocol version.
*/
public short getProtocolVersion() {
public int getProtocolVersion() {
return protocolVersion;
}
@@ -275,7 +283,7 @@ public enum ClientVersion {
*
* @return Is resolved
*/
public boolean isResoled() {
public boolean isResolved() {
return this != TEMP_UNRESOLVED && this != UNRESOLVED;
}
}
@@ -151,7 +151,8 @@ public final class PlayerUtils {
return ClientVersion.UNKNOWN;
}
ClientVersion version = clientVersionsMap.get(player.getAddress());
if (version == null) {
// If a player's version didn't resolve, we should try and resolve it again
if (version == null || !version.isResolved()) {
//Prioritize asking ViaVersion and ProtocolSupport as they modify the protocol version in the packet we access it from.
if (VersionLookupUtils.isDependencyAvailable()) {
try {
@@ -160,17 +161,17 @@ public final class PlayerUtils {
} catch (Exception ex) {
//Try ask the dependency again the next time, for now it is temporarily unresolved...
//Temporary unresolved means there is still hope, an exception was thrown on the dependency's end.
return ClientVersion.TEMP_UNRESOLVED;
}
return ClientVersion.TEMP_UNRESOLVED;
} else {
//We can trust the version we retrieved from the packet.
version = tempClientVersionMap.get(player.getAddress());
if (version == null) {
//We couldn't snatch that version from the packet.
short protocolVersion;
int protocolVersion;
//Handle 1.7.10, luckily 1.7.10 provides a method for us to access a player's protocol version(because 1.7.10 servers support 1.8 clients too)
if (PacketEvents.get().getServerUtils().getVersion().isOlderThan(ServerVersion.v_1_8)) {
protocolVersion = (short) SpigotVersionLookup_1_7.getProtocolVersion(player);
protocolVersion = SpigotVersionLookup_1_7.getProtocolVersion(player);
} else {
//No dependency available, couldn't snatch the version from the packet AND server version is not 1.7.10
//We are pretty safe to assume the version is the same as the server, as ViaVersion AND ProtocolSupport could not be found.
@@ -186,6 +187,25 @@ public final class PlayerUtils {
return version;
}
public void writePacket(Player player, SendableWrapper wrapper) {
try {
Object nmsPacket = wrapper.asNMSPacket();
PacketEvents.get().getInjector().writePacket(getChannel(player), nmsPacket);
}
catch (Exception ex) {
ex.printStackTrace();
}
}
public void flushPackets(Player player) {
try {
PacketEvents.get().getInjector().flushPackets(getChannel(player));
}
catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Send a client-bound(server-sided) wrapper that supports sending to a player.
*
@@ -201,12 +221,7 @@ public final class PlayerUtils {
}
}
/**
* Send a client-bound(server-sided) wrapper that supports sending to a netty channel.
*
* @param channel Netty channel as object(due to netty package changes)
* @param wrapper Client-bound raw NMS packet.
*/
@Deprecated
public void sendPacket(Object channel, SendableWrapper wrapper) {
try {
Object nmsPacket = wrapper.asNMSPacket();
@@ -226,12 +241,7 @@ public final class PlayerUtils {
PacketEvents.get().getInjector().sendPacket(getChannel(player), packet);
}
/**
* Send a client-bound(server-sided) raw NMS Packet without any wrapper to a netty channel.
*
* @param channel Netty channel as object(due to netty package changes)
* @param packet Client-bound raw NMS packet.
*/
@Deprecated
public void sendNMSPacket(Object channel, Object packet) {
PacketEvents.get().getInjector().sendPacket(channel, packet);
}
@@ -260,30 +270,6 @@ public final class PlayerUtils {
GameProfileUtil.setGameProfileSkin(gameProfile, skin);
}
//TODO FINISH APPLY SKIN. ITS NOT WORKING?
private void applySkinChangeAsync(Player player) {
Plugin plugin = PacketEvents.get().getPlugin();
CompletableFuture.runAsync(() -> {
System.out.println("STARTING");
}).thenRunAsync(() -> {
WrappedPacketOutEntityDestroy destroyPacket = new WrappedPacketOutEntityDestroy(player.getEntityId());
WrappedPacketOutNamedEntitySpawn spawnPacket = new WrappedPacketOutNamedEntitySpawn(player);
for (Player p : Bukkit.getOnlinePlayers()) {
if (p.getEntityId() != player.getEntityId()) {
PacketEvents.get().getPlayerUtils().sendPacket(p, destroyPacket);
PacketEvents.get().getPlayerUtils().sendPacket(p, spawnPacket);
Bukkit.getServer().getScheduler().runTask(plugin, () -> p.hidePlayer(plugin, player));
Bukkit.getServer().getScheduler().runTaskLater(plugin, () -> p.showPlayer(plugin, player), 4L);
}
}
}).thenRunAsync(() -> {
System.out.println("DONE");
});
}
public Skin getSkin(Player player) {
Object gameProfile = NMSUtils.getGameProfile(player);
return GameProfileUtil.getGameProfileSkin(gameProfile);
@@ -1,21 +1,19 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2021 retrooper and contributors
*
* * This file is part of packetevents - https://github.com/retrooper/packetevents
* * Copyright (C) 2016-2021 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/>.
* 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 io.github.retrooper.packetevents.utils.player;
@@ -23,6 +23,7 @@ import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@@ -67,6 +68,24 @@ public final class Reflection {
return null;
}
public static Field getField(final Class<?> cls, final Class<?> dataType, final int index, boolean ignoreStatic) {
if (dataType == null || cls == null) {
return null;
}
int currentIndex = 0;
for (final Field f : getFields(cls)) {
if (dataType.isAssignableFrom(f.getType()) && (!ignoreStatic || !Modifier.isStatic(f.getModifiers()))) {
if (currentIndex++ == index) {
return f;
}
}
}
if (cls.getSuperclass() != null) {
return getField(cls.getSuperclass(), dataType, index);
}
return null;
}
public static Field getField(final Class<?> cls, final int index) {
try {
return getFields(cls)[index];
@@ -21,6 +21,7 @@ package io.github.retrooper.packetevents.utils.server;
import io.github.retrooper.packetevents.PacketEvents;
import io.github.retrooper.packetevents.packetwrappers.NMSPacket;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.utils.boundingbox.BoundingBox;
import io.github.retrooper.packetevents.utils.entityfinder.EntityFinderUtils;
import io.github.retrooper.packetevents.utils.nms.NMSUtils;
import io.github.retrooper.packetevents.utils.npc.NPCManager;
@@ -28,6 +29,7 @@ import io.github.retrooper.packetevents.utils.reflection.Reflection;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.spigotmc.SpigotConfig;
@@ -97,6 +99,30 @@ public final class ServerUtils {
return SpigotConfig.bungee;
}
public BoundingBox getEntityBoundingBox(Entity entity) {
Object nmsEntity = NMSUtils.getNMSEntity(entity);
Object aabb = NMSUtils.getNMSAxisAlignedBoundingBox(nmsEntity);
WrappedPacket wrappedBoundingBox= new WrappedPacket(new NMSPacket(aabb));
double minX = wrappedBoundingBox.readDouble(0);
double minY = wrappedBoundingBox.readDouble(1);
double minZ = wrappedBoundingBox.readDouble(2);
double maxX = wrappedBoundingBox.readDouble(3);
double maxY = wrappedBoundingBox.readDouble(4);
double maxZ = wrappedBoundingBox.readDouble(5);
return new BoundingBox(minX, minY, minZ, maxX, maxY, maxZ);
}
@Nullable
private Entity getEntityByIdIterateWorld(@NotNull World world, int entityID) {
for (Entity entity : PacketEvents.get().getServerUtils().getEntityList(world)) {
if (entity.getEntityId() == entityID) {
entityCache.putIfAbsent(entity.getEntityId(), entity);
return entity;
}
}
return null;
}
@Nullable
public Entity getEntityById(@Nullable World world, int entityID) {
Entity e = entityCache.get(entityID);
@@ -109,22 +135,29 @@ public final class ServerUtils {
}
if (v_1_17 == 1) {
if (world != null) {
for (Entity entity : PacketEvents.get().getServerUtils().getEntityList(world)) {
if (entity.getEntityId() == entityID) {
entityCache.putIfAbsent(entity.getEntityId(), entity);
return entity;
try {
if (world != null) {
Entity newEntity = getEntityByIdIterateWorld(world, entityID);
if (newEntity != null) {
return newEntity;
}
}
}
for (World w : Bukkit.getWorlds()) {
for (Entity entity : PacketEvents.get().getServerUtils().getEntityList(w)) {
if (entity.getEntityId() == entityID) {
entityCache.putIfAbsent(entity.getEntityId(), entity);
return entity;
catch (Exception ex) {
//We are retrying below
}
try {
for (World w : Bukkit.getWorlds()) {
Entity newEntity = getEntityByIdIterateWorld(w, entityID);
if (newEntity != null) {
return newEntity;
}
}
}
catch (Exception ex) {
//No entity found
return null;
}
} else {
return EntityFinderUtils.getEntityByIdUnsafe(world, entityID);
}
@@ -31,28 +31,29 @@ import org.bukkit.Bukkit;
* @since 1.6.9
*/
public enum ServerVersion {
v_1_7_10((short) 5),
v_1_8((short) 47), v_1_8_1((short) 47), v_1_8_2((short) 47), v_1_8_3((short) 47),
v_1_8_4((short) 47), v_1_8_5((short) 47), v_1_8_6((short) 47), v_1_8_7((short) 47), v_1_8_8((short) 47),
v_1_9((short) 107), v_1_9_1((short) 108), v_1_9_2((short) 109), v_1_9_3((short) 110), v_1_9_4((short) 110),
v_1_10((short) 210), v_1_10_1((short) 210), v_1_10_2((short) 210),
v_1_11((short) 315), v_1_11_1((short) 316), v_1_11_2((short) 316),
v_1_12((short) 335), v_1_12_1((short) 338), v_1_12_2((short) 340),
v_1_13((short) 393), v_1_13_1((short) 401), v_1_13_2((short) 404),
v_1_14((short) 477), v_1_14_1((short) 480), v_1_14_2((short) 485), v_1_14_3((short) 490), v_1_14_4((short) 498),
v_1_15((short) 573), v_1_15_1((short) 575), v_1_15_2((short) 578),
v_1_16((short) 735), v_1_16_1((short) 736), v_1_16_2((short) 751), v_1_16_3((short) 753), v_1_16_4((short) 754), v_1_16_5((short) 754),
v_1_17((short) 755), v_1_17_1((short) 756),
ERROR((short) -1);
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_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),
v_1_12(335), v_1_12_1(338), v_1_12_2(340),
v_1_13(393), v_1_13_1(401), v_1_13_2(404),
v_1_14(477), v_1_14_1(480), v_1_14_2(485), v_1_14_3(490), v_1_14_4(498),
v_1_15(573), v_1_15_1(575), v_1_15_2(578),
v_1_16(735), v_1_16_1(736), v_1_16_2(751), v_1_16_3(753), v_1_16_4(754), v_1_16_5(754),
v_1_17(755), v_1_17_1(756),
v_1_18(757), v_1_18_1(757), v_1_18_2(758),
ERROR(-1);
private static final String NMS_VERSION_SUFFIX = Bukkit.getServer().getClass().getPackage().getName()
.replace(".", ",").split(",")[3];
private static final ServerVersion[] VALUES = values();
public static ServerVersion[] reversedValues = new ServerVersion[VALUES.length];
private static ServerVersion cachedVersion;
private final short protocolVersion;
private final int protocolVersion;
ServerVersion(short protocolId) {
ServerVersion(int protocolId) {
this.protocolVersion = protocolId;
}
@@ -60,9 +61,6 @@ public enum ServerVersion {
if (reversedValues[0] == null) {
reversedValues = ServerVersion.reverse();
}
if (reversedValues == null) {
throw new IllegalStateException("Failed to reverse the ServerVersion enum constant values.");
}
for (final ServerVersion val : reversedValues) {
String valName = val.name().substring(2).replace("_", ".");
if (Bukkit.getBukkitVersion().contains(valName)) {
@@ -74,13 +72,12 @@ public enum ServerVersion {
if (fallbackVersion == ServerVersion.v_1_7_10) {
try {
Class.forName("net.minecraft.util.io.netty.buffer.ByteBuf");
}
catch (Exception ex) {
} catch (Exception ex) {
//We will assume its 1.8.8
fallbackVersion = ServerVersion.v_1_8_8;
}
}
PacketEvents.get().getPlugin().getLogger().warning("[packetevents] Your server software is preventing us from checking the server version. We will assume the server version is " + fallbackVersion.name() + "...");
PacketEvents.get().getPlugin().getLogger().warning("[packetevents] Your server software is preventing us from checking the server version. This is what we found: " + Bukkit.getBukkitVersion() + ". We will assume the server version is " + fallbackVersion.name() + "...");
return fallbackVersion;
}
return ERROR;
@@ -91,7 +88,7 @@ public enum ServerVersion {
* If PacketEvents has already attempted resolving, return the cached version.
* If PacketEvents hasn't already attempted resolving, it will resolve it, cache it and return the version.
*
* @return Server Version. (possibly cached)
* @return Server Version. (always cached)
*/
public static ServerVersion getVersion() {
if (cachedVersion == null) {
@@ -143,7 +140,7 @@ public enum ServerVersion {
*
* @return Protocol version.
*/
public short getProtocolVersion() {
public int getProtocolVersion() {
return protocolVersion;
}
@@ -177,7 +174,9 @@ public enum ServerVersion {
if (version == target) {
return false;
}
if (version == this) return true;
}
return false;
}
@@ -160,12 +160,7 @@ public class Vector3d {
*/
@Override
public Vector3d clone() {
try {
super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return null;
return new Vector3d(getX(), getY(), getZ());
}
public Vector3d add(Vector3d target) {
@@ -151,13 +151,8 @@ public class Vector3f {
* @return Clone.
*/
@Override
public Vector3d clone() {
try {
super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return null;
public Vector3f clone() {
return new Vector3f(getX(), getY(), getZ());
}
@Override
@@ -161,12 +161,7 @@ public class Vector3i {
*/
@Override
public Vector3i clone() {
try {
super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return null;
return new Vector3i(getX(), getY(), getZ());
}
@Override
@@ -0,0 +1,25 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2021 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 io.github.retrooper.packetevents.utils.versionlookup.viaversion;
import org.bukkit.entity.Player;
public interface ViaVersionAccessor {
int getProtocolVersion(Player player);
}
@@ -0,0 +1,29 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2021 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 io.github.retrooper.packetevents.utils.versionlookup.viaversion;
import com.viaversion.viaversion.api.Via;
import org.bukkit.entity.Player;
public class ViaVersionAccessorImpl implements ViaVersionAccessor {
@Override
public int getProtocolVersion(Player player) {
return Via.getAPI().getPlayerVersion(player);
}
}
@@ -0,0 +1,52 @@
/*
* This file is part of packetevents - https://github.com/retrooper/packetevents
* Copyright (C) 2021 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 io.github.retrooper.packetevents.utils.versionlookup.viaversion;
import io.github.retrooper.packetevents.utils.reflection.Reflection;
import org.bukkit.entity.Player;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ViaVersionAccessorImplLegacy implements ViaVersionAccessor {
private static Class<?> viaClass;
private static Method apiAccessor;
private static Method getPlayerVersionMethod;
@Override
public int getProtocolVersion(Player player) {
if (viaClass == null) {
try {
viaClass = Class.forName("us.myles.ViaVersion.api.Via");
Class<?> viaAPIClass = Class.forName("us.myles.ViaVersion.api.ViaAPI");
apiAccessor = viaClass.getMethod("getAPI");
getPlayerVersionMethod = viaAPIClass.getMethod("getPlayerVersion", Object.class);
} catch (ClassNotFoundException | NoSuchMethodException e) {
e.printStackTrace();
}
}
try {
Object viaAPI = apiAccessor.invoke(null);
return (int) getPlayerVersionMethod.invoke(viaAPI, player);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
return -1;
}
}
@@ -20,14 +20,26 @@ package io.github.retrooper.packetevents.utils.versionlookup.viaversion;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import us.myles.ViaVersion.api.Via;
public class ViaVersionLookupUtils {
private ViaVersionLookupUtils() {
}
private static ViaVersionAccessor viaVersionAccessor;
public static boolean isAvailable() {
return Bukkit.getPluginManager().getPlugin("ViaVersion") != null;
}
public static int getProtocolVersion(Player player) {
return Via.getAPI().getPlayerVersion(player.getUniqueId());
if (viaVersionAccessor == null) {
try {
Class.forName("com.viaversion.viaversion.api.Via");
viaVersionAccessor = new ViaVersionAccessorImpl();
} catch (Exception e) {
viaVersionAccessor = new ViaVersionAccessorImplLegacy();
}
}
return viaVersionAccessor.getProtocolVersion(player);
}
}
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff. Show more