Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7e94b5ab84 | ||
|
|
2f34adeeb2 |
No files matched your search
@@ -1 +0,0 @@
|
||||
.gitea/CODEOWNERS linguist-detectable=false
|
||||
@@ -1,3 +0,0 @@
|
||||
# Pull requests request review from the eligible staff team(s).
|
||||
# One approval from either an Admin or Developer satisfies branch protection.
|
||||
* @trueog/Admins @trueog/Developers
|
||||
@@ -19,17 +19,17 @@ jobs:
|
||||
- name: Checkout main repository
|
||||
uses: actions/checkout@v2
|
||||
|
||||
# 2. Install JDK 21 – NO Gradle cache here
|
||||
- name: Set up JDK
|
||||
uses: actions/setup-java@v4
|
||||
uses: actions/setup-java@v2
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: 21
|
||||
cache: '' # ← disable Maven/Gradle cache
|
||||
java-version: '21'
|
||||
distribution: 'adopt'
|
||||
cache: gradle
|
||||
|
||||
# 3. Set up Gradle + dependency cache
|
||||
- name: Set up Gradle
|
||||
uses: gradle/actions/setup-gradle@v5
|
||||
- name: Setup Gradle 8.10
|
||||
uses: gradle/actions/setup-gradle@v4
|
||||
with:
|
||||
gradle-version: "8.10" # Quotes required to prevent YAML converting to number
|
||||
|
||||
- name: Generate build number
|
||||
id: buildnumber
|
||||
@@ -53,26 +53,39 @@ jobs:
|
||||
# Ensure snapshot is set to false
|
||||
sed -i "s/val snapshot = .*/val snapshot = false/" build.gradle.kts
|
||||
|
||||
- name: Build without PE shaded
|
||||
run: ./gradlew build -PshadePE=false -x test
|
||||
- name: Build with Gradle
|
||||
run: gradle clean build -x test
|
||||
env:
|
||||
GITHUB_REPOSITORY: ${{ github.repository }}
|
||||
|
||||
- name: Build with PE shaded Gradle
|
||||
run: ./gradlew build -PshadePE=true -x test
|
||||
env:
|
||||
GITHUB_REPOSITORY: ${{ github.repository }}
|
||||
- name: Rename shaded jar to overwrite non-shaded jar
|
||||
run: mv bukkit/build/libs/knockbacksync-bukkit-${{ env.NEW_VERSION }}-all.jar bukkit/build/libs/knockbacksync-bukkit-${{ env.NEW_VERSION }}.jar
|
||||
|
||||
# Get the Hashes of the Original and Lite JARs
|
||||
# Download PaperSpigot (Choose version for reproducibility
|
||||
- name: Download PaperSpigot
|
||||
run: |
|
||||
mkdir -p paper-server/plugins
|
||||
curl -o paperclip.jar https://api.papermc.io/v2/projects/paper/versions/1.21.1/builds/120/downloads/paper-1.21.1-120.jar
|
||||
mv paperclip.jar paper-server/
|
||||
|
||||
# Copy Plugin into Plugins Folder and Start Server
|
||||
- name: Copy Plugin and Start Paper Server
|
||||
run: |
|
||||
cp bukkit/build/libs/knockbacksync-bukkit-${{ env.NEW_VERSION }}.jar paper-server/plugins/
|
||||
cd paper-server
|
||||
# Start the server to remap the plugin
|
||||
timeout 60 java -Xms3G -Xmx3G -XX:+UseG1GC -XX:+ParallelRefProcEnabled -XX:MaxGCPauseMillis=200 -XX:+UnlockExperimentalVMOptions -XX:+DisableExplicitGC -XX:+AlwaysPreTouch -XX:G1NewSizePercent=30 -XX:G1MaxNewSizePercent=40 -XX:G1HeapRegionSize=8M -XX:G1ReservePercent=20 -XX:G1HeapWastePercent=5 -XX:G1MixedGCCountTarget=4 -XX:InitiatingHeapOccupancyPercent=15 -XX:G1MixedGCLiveThresholdPercent=90 -XX:G1RSetUpdatingPauseTimePercent=5 -XX:SurvivorRatio=32 -XX:+PerfDisableSharedMem -XX:MaxTenuringThreshold=1 -jar -Dcom.mojang.eula.agree=true paperclip.jar --nogui || true
|
||||
|
||||
# Get the Hashes of the Original and Remapped JARs
|
||||
- name: Calculate Hashes
|
||||
run: |
|
||||
# Calculate hash for the original JAR
|
||||
BUKKIT_HASH=$(sha256sum bukkit/build/libs/knockbacksync-bukkit-${{ env.NEW_VERSION }}.jar | awk '{print $1}')
|
||||
echo "BUKKIT_HASH=$BUKKIT_HASH" >> $GITHUB_ENV
|
||||
# Calculate hash for the lite JAR
|
||||
BUKKIT_LITE_HASH=$(sha256sum bukkit/build/libs/knockbacksync-bukkit-lite-${{ env.NEW_VERSION }}.jar | awk '{print $1}')
|
||||
echo "BUKKIT_LITE_HASH=$BUKKIT_LITE_HASH" >> $GITHUB_ENV
|
||||
# Calculate hash for the lite JAR
|
||||
ORIGINAL_HASH=$(sha256sum bukkit/build/libs/knockbacksync-bukkit-${{ env.NEW_VERSION }}.jar | awk '{print $1}')
|
||||
echo "ORIGINAL_HASH=$ORIGINAL_HASH" >> $GITHUB_ENV
|
||||
# Calculate hash for the remapped JAR
|
||||
REMAPPED_HASH=$(sha256sum paper-server/plugins/.paper-remapped/knockbacksync-bukkit-${{ env.NEW_VERSION }}.jar | awk '{print $1}')
|
||||
echo "REMAPPED_HASH=$REMAPPED_HASH" >> $GITHUB_ENV
|
||||
# Calculate hash for the remapped JAR
|
||||
FABRIC_HASH=$(sha256sum fabric/build/libs/knockbacksync-fabric-${{ env.NEW_VERSION }}.jar | awk '{print $1}')
|
||||
echo "FABRIC_HASH=$FABRIC_HASH" >> $GITHUB_ENV
|
||||
|
||||
@@ -98,8 +111,8 @@ jobs:
|
||||
}
|
||||
|
||||
# Add new hashes if they don't exist
|
||||
add_hash_if_new "${{ env.BUKKIT_HASH }}"
|
||||
add_hash_if_new "${{ env.BUKKIT_LITE_HASH }}"
|
||||
add_hash_if_new "${{ env.ORIGINAL_HASH }}"
|
||||
add_hash_if_new "${{ env.REMAPPED_HASH }}"
|
||||
add_hash_if_new "${{ env.FABRIC_HASH }}"
|
||||
|
||||
# Check if the file has changed
|
||||
@@ -130,25 +143,23 @@ jobs:
|
||||
# Clean up
|
||||
rm dev-builds.txt.original
|
||||
|
||||
- name: Upload Bukkit Artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: knockbacksync-bukkit-${{ env.NEW_VERSION }}.jar
|
||||
path: bukkit/build/libs/knockbacksync-bukkit-${{ env.NEW_VERSION }}.jar
|
||||
retention-days: 90
|
||||
- name: Create artifacts directory
|
||||
run: mkdir -p artifacts
|
||||
|
||||
- name: Upload Bukkit Lite Artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: knockbacksync-bukkit-lite-${{ env.NEW_VERSION }}.jar
|
||||
path: bukkit/build/libs/knockbacksync-bukkit-lite-${{ env.NEW_VERSION }}.jar
|
||||
retention-days: 90
|
||||
- name: Copy bukkit artifact
|
||||
run: cp bukkit/build/libs/knockbacksync-bukkit-${{ env.NEW_VERSION }}.jar artifacts/
|
||||
|
||||
- name: Upload Fabric Artifact
|
||||
- name: Copy fabric artifact
|
||||
run: cp fabric/build/libs/knockbacksync-fabric-${{ env.NEW_VERSION }}.jar artifacts/
|
||||
|
||||
- name: Zip the artifacts
|
||||
run: zip -r KnockbackSync-${{ env.NEW_VERSION }}.zip artifacts/*
|
||||
|
||||
- name: Upload artifacts zip
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: knockbacksync-fabric-${{ env.NEW_VERSION }}.jar
|
||||
path: fabric/build/libs/knockbacksync-fabric-${{ env.NEW_VERSION }}.jar
|
||||
name: KnockbackSync-${{ env.NEW_VERSION }}.zip
|
||||
path: KnockbackSync-${{ env.NEW_VERSION }}.zip
|
||||
retention-days: 90
|
||||
|
||||
- uses: Kir-Antipov/mc-publish@v3.3
|
||||
@@ -160,7 +171,6 @@ jobs:
|
||||
|
||||
files: |
|
||||
bukkit/build/libs/knockbacksync-bukkit-${{ env.NEW_VERSION }}.jar
|
||||
bukkit/build/libs/knockbacksync-bukkit-lite-${{ env.NEW_VERSION }}.jar
|
||||
|
||||
name: KnockbackSync-${{ env.NEW_VERSION }}
|
||||
version: ${{ env.NEW_VERSION }}
|
||||
@@ -198,10 +208,7 @@ jobs:
|
||||
fabric
|
||||
|
||||
game-versions: |
|
||||
1.21.11
|
||||
|
||||
dependencies: |
|
||||
fabric-api
|
||||
>=1.21
|
||||
|
||||
retry-attempts: 2
|
||||
retry-delay: 10000
|
||||
|
||||
+1
-5
@@ -7,12 +7,8 @@ dependency-reduced-pom.xml
|
||||
# Ignore maven build files
|
||||
target/
|
||||
|
||||
# Eclipse files
|
||||
.classpath
|
||||
.project
|
||||
.settings/
|
||||
|
||||
.gradle/
|
||||
build/
|
||||
|
||||
run/
|
||||
run/
|
||||
@@ -1,37 +0,0 @@
|
||||
KnockbackSync
|
||||
=============
|
||||
|
||||
KnockbackSync is licensed under the GNU General Public License v3.0 or later.
|
||||
See README.md (section "License") and https://www.gnu.org/licenses/gpl-3.0.en.html.
|
||||
|
||||
Bundled / ported third-party code
|
||||
----------------------------------
|
||||
|
||||
This distribution contains a port of the 1.8 melee knockback formula from:
|
||||
|
||||
BukkitOldCombatMechanics (OldCombatMechanics)
|
||||
Copyright (c) the OldCombatMechanics contributors (kernitus et al.)
|
||||
https://github.com/kernitus/BukkitOldCombatMechanics
|
||||
Licensed under the Mozilla Public License, Version 2.0 (MPL-2.0)
|
||||
https://mozilla.org/MPL/2.0/
|
||||
|
||||
The ported code lives in:
|
||||
|
||||
common/src/main/java/me/caseload/knockbacksync/util/LegacyKnockback.java
|
||||
|
||||
It is derived from OldCombatMechanics' module
|
||||
`kernitus.plugin.OldCombatMechanics.module.ModulePlayerKnockback`.
|
||||
|
||||
License compatibility
|
||||
---------------------
|
||||
|
||||
The OldCombatMechanics source files are distributed under the standard MPL-2.0
|
||||
notice (Exhibit A) and do NOT carry the "Incompatible With Secondary Licenses"
|
||||
notice (Exhibit B). Under MPL-2.0 section 3.3, such Covered Software may be
|
||||
distributed as part of a Larger Work governed by a "Secondary License" — which
|
||||
MPL-2.0 section 1.12 defines to include the GNU General Public License, Version
|
||||
3. Accordingly, the ported file may be combined with and distributed alongside
|
||||
the GPL-3.0-or-later code that makes up the rest of KnockbackSync.
|
||||
|
||||
The terms of the MPL-2.0 continue to govern the ported file itself; its MPL
|
||||
header is retained. The combined/Larger Work is offered under GPL-3.0-or-later.
|
||||
@@ -1,15 +1,169 @@
|
||||
# KnockbackSync-OG
|
||||
[](https://modrinth.com/plugin/knockbacksync)
|
||||
|
||||
Soft fork of KnockbackSync to ensure compatibility with OldCombatMechanics on Purpur 1.19.4.
|
||||
Tired of inconsistent knockback ruining your PvP experience? Our plugin recalculates knockback as if it were done clientside, leveling the playing field and ensuring every player enjoys a fair fight, no matter their connection quality.
|
||||
|
||||
Minecraft doesn’t factor in network latency when determining a player's actions on the server. This causes the server to receive outdated information that doesn’t reflect the player's clientside position, leading to varying knockback effects based on connection quality.
|
||||
|
||||
This plugin intercepts and adjusts knockback calculations to match what would occur clientside, effectively mitigating the disadvantages caused by high latency. By synchronizing knockback handling, we ensure that players experience consistent and fair knockback, providing a balanced and competitive environment for all."
|
||||
|
||||
Showcase: https://www.youtube.com/watch?v=SVokpr3v-TA
|
||||
|
||||
Official Discord: https://discord.gg/nnpqpAtyVW
|
||||
|
||||
## Frequently Asked Questions (FAQ)
|
||||
|
||||
### Does this change put high ping players at a disadvantage?
|
||||
**It depends on the player.** Some may notice a difference if they're used to relying on high ping to reduce knockback. For others, it could actually be an advantage.
|
||||
|
||||
### How does this change benefit high ping players?
|
||||
**Knockback control.** For example, it will be easier to escape crit chains and punish crit.
|
||||
|
||||
### Why was the configurability of ping offset removed?
|
||||
**It promotes consistency across all servers.** Extensive testing with top players has shown that an offset of 25 provides a balanced experience for everyone.
|
||||
|
||||
### How do I change the ping offset?
|
||||
**You must run a modified build of KnockbackSync.** The variable can be changed inside of the [PlayerData](common/src/main/java/me/caseload/knockbacksync/player/PlayerData.java) class.
|
||||
|
||||
## What servers are using this plugin?
|
||||
| IP | Location | Region | Ping Offset | spike_threshold |
|
||||
|------------------|-----------------------------------|--------|-------------|-----------------|
|
||||
| `pvparcade.club` | Ashburn, Virginia, United States | NA | 20 | 15 |
|
||||
| `stray.gg` | Ashburn, Virginia, United States | NA | 25 | 20 |
|
||||
| `eu.stray.gg` | Frankfurt, Hesse, Germany | EU | 25 | 20 |
|
||||
| `valed.gg` | Frankfurt, Hesse, Germany | EU | 25 | 20 |
|
||||
| `eu.catpvp.xyz` | Frankfurt, Hesse, Germany | EU | 25 | 20 |
|
||||
| `as.catpvp.xyz` | Singapore | AS | 25 | 20 |
|
||||
| `na.catpvp.xyz` | New York, New York, United States | NA | 25 | 20 |
|
||||
| `hyperium.pl` | Wrocław, Dolnośląskie, Poland | EU | 25 | 20 |
|
||||
|
||||
## Commands
|
||||
---
|
||||
### /knockbacksync ping [target]
|
||||
|
||||
**Description:**
|
||||
|
||||
This command allows you to check the ping of a player, including jitter. If no target is specified, it will check your own ping.
|
||||
|
||||
**Permissions:**
|
||||
|
||||
* `knockbacksync.ping` (defaults to true for players)
|
||||
|
||||
**Examples:**
|
||||
|
||||
* `/knockbacksync ping`: Checks your own ping.
|
||||
* `/knockbacksync ping Steve`: Checks the ping of a player named Steve.
|
||||
|
||||
**Output:**
|
||||
|
||||
* If a pong packet has been received: "Your last ping packet took [ping]ms. Jitter: [jitter]ms." or "[Player]'s last ping packet took [ping]ms. Jitter: [jitter]ms."
|
||||
* If a pong packet has not been received: "Pong not received. Your estimated ping is [estimated ping]ms." or "Pong not received. [Player]'s estimated ping is [estimated ping]ms."
|
||||
|
||||
**Notes:**
|
||||
|
||||
* The estimated ping is based on the player's platform reported ping.
|
||||
* Jitter represents the variation in ping over time.
|
||||
---
|
||||
### /knockbacksync status [target]
|
||||
|
||||
**Description:**
|
||||
|
||||
This command allows you to check the KnockbackSync status of a player or the server. If no target is specified, it will show both the global status and your own status.
|
||||
|
||||
**Permissions:**
|
||||
|
||||
* `knockbacksync.status.self` (defaults to true for players): Allows checking your own status.
|
||||
* `knockbacksync.status.other` (defaults to op only): Allows checking the status of other players.
|
||||
|
||||
**Examples:**
|
||||
|
||||
* `/knockbacksync status`: Shows the global status and your own status.
|
||||
* `/knockbacksync status Steve`: Shows the status of a player named Steve.
|
||||
|
||||
**Output:**
|
||||
|
||||
* **Global status:** "Global KnockbackSync status: [Enabled/Disabled]"
|
||||
* **Player status:** "[Player]'s KnockbackSync status: [Enabled/Disabled]" (or "Disabled (Global toggle is off)" if the global toggle is off)
|
||||
|
||||
**Notes:**
|
||||
|
||||
* The player status will be "Disabled" if the global toggle is off, even if the player has individually enabled KnockbackSync.
|
||||
* The messages displayed by this command are configurable in the `config.yml` file.
|
||||
---
|
||||
### /knockbacksync toggle [target]
|
||||
|
||||
**Description:**
|
||||
|
||||
This command allows you to toggle KnockbackSync for yourself, another player, or globally.
|
||||
|
||||
**Permissions:**
|
||||
|
||||
* `knockbacksync.toggle.self` (defaults to true for players): Allows toggling KnockbackSync for yourself.
|
||||
* `knockbacksync.toggle.other` (defaults to op only): Allows toggling KnockbackSync for other players.
|
||||
* `knockbacksync.toggle.global` (defaults to op only): Allows toggling KnockbackSync globally for the server.
|
||||
|
||||
**Examples:**
|
||||
|
||||
* `/knockbacksync toggle`: Toggles KnockbackSync globally (if you have permission) or for yourself.
|
||||
* `/knockbacksync toggle Steve`: Toggles KnockbackSync for a player named Steve.
|
||||
|
||||
**Output:**
|
||||
|
||||
* **Global toggle:** Sends a message indicating whether KnockbackSync has been enabled or disabled globally. The messages are configurable in the `config.yml` file.
|
||||
* **Player toggle:** Sends a message indicating whether KnockbackSync has been enabled or disabled for the specified player. The messages are configurable in the `config.yml` file.
|
||||
* **Ineligible player:** If a player is ineligible for KnockbackSync (e.g., due to permissions), a configurable message will be sent.
|
||||
* **KnockbackSync disabled:** If KnockbackSync is disabled globally and you try to toggle it for a player, a message will be sent indicating that KnockbackSync is disabled.
|
||||
|
||||
**Notes:**
|
||||
|
||||
* If KnockbackSync is disabled globally, toggling it for a player will have no effect until KnockbackSync is enabled globally.
|
||||
* Players can only toggle KnockbackSync for themselves if they have the `knockbacksync.toggle.self` permission.
|
||||
* Operators can toggle KnockbackSync for other players and globally.
|
||||
---
|
||||
### /knockbacksync reload
|
||||
|
||||
**Description:**
|
||||
|
||||
This command reloads the KnockbackSync plugin's configuration file.
|
||||
|
||||
**Permissions:**
|
||||
|
||||
* `knockbacksync.reload` (defaults to op only)
|
||||
|
||||
**Examples:**
|
||||
* `/knockbacksync reload`
|
||||
|
||||
**Output:**
|
||||
|
||||
* Sends a message to the command sender indicating that the configuration has been reloaded. The message is configurable in the `config.yml` file.
|
||||
|
||||
**Notes:**
|
||||
|
||||
* This command is useful for applying changes made to the configuration file without restarting the server.
|
||||
---
|
||||
### /knockbacksync toggleoffground
|
||||
|
||||
**Description:**
|
||||
|
||||
This command toggles the experimental off-ground knockback synchronization feature.
|
||||
|
||||
**Permissions:**
|
||||
|
||||
* `knockbacksync.toggleoffground` (defaults to op only)
|
||||
|
||||
**Examples:**
|
||||
|
||||
* `/knockbacksync toggleoffground`
|
||||
|
||||
**Output:**
|
||||
|
||||
* Sends a message indicating whether the experimental off-ground knockback synchronization has been enabled or disabled. The messages are configurable in the `config.yml` file.
|
||||
|
||||
**Notes:**
|
||||
|
||||
* **This command currently does not do anything as off-ground synchronization has yet to be implemented.**
|
||||
* This feature is experimental and may not work as expected.
|
||||
|
||||
## License
|
||||
GNU General Public License v3.0 or later
|
||||
|
||||
See [LICENSE](https://www.gnu.org/licenses/gpl-3.0.en.html) to see the full text.
|
||||
|
||||
The optional legacy (1.8) knockback formula
|
||||
(`common/src/main/java/me/caseload/knockbacksync/util/LegacyKnockback.java`) is a
|
||||
port from [OldCombatMechanics](https://github.com/kernitus/BukkitOldCombatMechanics),
|
||||
which is licensed under the Mozilla Public License 2.0 (MPL-2.0). MPL-2.0 permits
|
||||
combining that code into this GPL-3.0-or-later work as a Larger Work (MPL-2.0
|
||||
§3.3 / §1.12). See the [NOTICE](NOTICE) file for details.
|
||||
See [LICENSE](https://www.gnu.org/licenses/gpl-3.0.en.html) to see the full text.
|
||||
+12
-59
@@ -1,57 +1,28 @@
|
||||
import java.io.ByteArrayOutputStream
|
||||
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
|
||||
|
||||
plugins {
|
||||
id("java")
|
||||
eclipse
|
||||
id("com.gradleup.shadow") version "9.2.2" apply false
|
||||
}
|
||||
|
||||
fun getGitCommitHash(project: Project): String? {
|
||||
// Only try to get the hash if the .git directory exists
|
||||
if (!project.file(".git").isDirectory) {
|
||||
return null
|
||||
}
|
||||
return try {
|
||||
val process = ProcessBuilder("git", "rev-parse", "--short", "HEAD")
|
||||
.redirectOutput(ProcessBuilder.Redirect.PIPE)
|
||||
.redirectError(ProcessBuilder.Redirect.PIPE)
|
||||
.start()
|
||||
|
||||
process.waitFor(5, TimeUnit.SECONDS)
|
||||
|
||||
if (process.exitValue() == 0) {
|
||||
process.inputStream.bufferedReader().readText().trim().takeIf { it.isNotEmpty() }
|
||||
} else {
|
||||
null
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
}
|
||||
id("com.gradleup.shadow") version "8.3.3" apply false
|
||||
id("fabric-loom") version "1.7.4" apply false
|
||||
}
|
||||
|
||||
val fullVersion = "1.3.5"
|
||||
val snapshot = true
|
||||
val githubRepo = System.getenv("GITHUB_REPOSITORY") ?: project.findProperty("githubRepo").toString()
|
||||
|
||||
// Suite default external provider; shaded standalone via -PshadePE=true.
|
||||
extra["shadePE"] = project.findProperty("shadePE")?.toString()?.toBoolean()
|
||||
?: System.getenv("SHADE_PE")?.toBoolean()
|
||||
?: false
|
||||
|
||||
extra["relocate"] = project.findProperty("relocate")?.toString()?.toBoolean()
|
||||
?: System.getenv("RELOCATE_JAR")?.toBoolean()
|
||||
?: true
|
||||
|
||||
allprojects {
|
||||
fun getVersionMeta(includeHash: Boolean): String {
|
||||
if (!snapshot) {
|
||||
return ""
|
||||
}
|
||||
val commitHash = if (includeHash) {
|
||||
getGitCommitHash(project)?.let { "+$it" } ?: ""
|
||||
} else {
|
||||
""
|
||||
var commitHash = ""
|
||||
if (includeHash && file(".git").isDirectory) {
|
||||
val stdout = ByteArrayOutputStream()
|
||||
exec {
|
||||
commandLine("git", "rev-parse", "--short", "HEAD")
|
||||
standardOutput = stdout
|
||||
}
|
||||
commitHash = "+${stdout.toString().trim()}"
|
||||
}
|
||||
return "$commitHash-SNAPSHOT"
|
||||
}
|
||||
@@ -62,8 +33,7 @@ allprojects {
|
||||
ext["githubRepo"] = githubRepo
|
||||
|
||||
repositories {
|
||||
// mavenLocal()
|
||||
maven("https://repo.grim.ac/snapshots")
|
||||
mavenLocal()
|
||||
mavenCentral()
|
||||
maven("https://hub.spigotmc.org/nexus/content/repositories/snapshots/")
|
||||
maven("https://repo.codemc.io/repository/maven-releases/")
|
||||
@@ -74,6 +44,7 @@ allprojects {
|
||||
}
|
||||
maven("https://libraries.minecraft.net/")
|
||||
maven("https://maven.neoforged.net/releases")
|
||||
maven("https://repo.codemc.io/repository/maven-snapshots/")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,21 +56,3 @@ subprojects {
|
||||
targetCompatibility = JavaVersion.VERSION_1_8
|
||||
}
|
||||
}
|
||||
|
||||
tasks.jar {
|
||||
// The root project has no plugin entrypoint; do not emit an empty deployable-looking JAR.
|
||||
enabled = false
|
||||
}
|
||||
|
||||
val copyBukkitPluginJar by tasks.registering(Copy::class) {
|
||||
val bukkitShadowJar = project(":bukkit").tasks.named<ShadowJar>("shadowJar")
|
||||
|
||||
dependsOn(bukkitShadowJar)
|
||||
from(bukkitShadowJar.flatMap { it.archiveFile })
|
||||
into(layout.buildDirectory.dir("libs"))
|
||||
rename { "KnockbackSync-OG-$fullVersion${if (snapshot) "-SNAPSHOT" else ""}.jar" }
|
||||
}
|
||||
|
||||
tasks.assemble {
|
||||
dependsOn(copyBukkitPluginJar)
|
||||
}
|
||||
+6
-28
@@ -4,10 +4,8 @@ plugins {
|
||||
id("com.gradleup.shadow")
|
||||
}
|
||||
|
||||
val shadePE: Boolean by rootProject.extra
|
||||
|
||||
base {
|
||||
archivesName.set("${rootProject.property("archives_base_name")}-bukkit${if (shadePE) "" else "-lite"}")
|
||||
archivesName.set("${rootProject.property("archives_base_name")}-bukkit")
|
||||
}
|
||||
|
||||
val shadeThisThing: Configuration by configurations.creating {
|
||||
@@ -33,18 +31,14 @@ dependencies {
|
||||
|
||||
compileOnly("org.spigotmc:spigot-api:1.18.2-R0.1-SNAPSHOT")
|
||||
compileOnly("org.geysermc.floodgate:api:2.0-SNAPSHOT")
|
||||
compileOnly("io.netty:netty-all:4.1.72.Final")
|
||||
|
||||
compileOnly("org.projectlombok:lombok:1.18.34")
|
||||
annotationProcessor("org.projectlombok:lombok:1.18.34")
|
||||
|
||||
shadeThisThing(implementation("org.kohsuke:github-api:1.326")!!)
|
||||
if (shadePE) {
|
||||
shadeThisThing(implementation("com.github.retrooper:packetevents-spigot:2.11.2")!!)
|
||||
} else {
|
||||
compileOnly("com.github.retrooper:packetevents-spigot:2.11.2")
|
||||
}
|
||||
shadeThisThing(implementation("org.incendo:cloud-paper:2.0.0-beta.14")!!)
|
||||
shadeThisThing(implementation("com.github.retrooper:packetevents-spigot:2.5.0")!!)
|
||||
// shadeThisThing(implementation("net.kyori:adventure-platform-bukkit:4.3.4")!!)
|
||||
shadeThisThing(implementation("org.incendo:cloud-paper:2.0.0-beta.10")!!)
|
||||
shadeThisThing(implementation("org.incendo:cloud-core:2.0.0")!!)
|
||||
|
||||
// Required for 1.14.4 support because gson is too old to have JosnParser.parseString()
|
||||
@@ -52,23 +46,11 @@ dependencies {
|
||||
}
|
||||
|
||||
tasks.withType<ShadowJar> {
|
||||
manifest {
|
||||
attributes["paperweight-mappings-namespace"] = "mojang"
|
||||
}
|
||||
|
||||
// Remove the -all suffix from the output JAR file name
|
||||
archiveClassifier.set("")
|
||||
|
||||
configurations = listOf(shadeThisThing)
|
||||
enableAutoRelocation = true
|
||||
isEnableRelocation = false
|
||||
relocationPrefix = "${project.property("maven_group")}.${project.property("archives_base_name")}.shaded"
|
||||
}
|
||||
|
||||
tasks.jar {
|
||||
// The shaded archive is the runtime plugin; do not emit a misleading thin plugin JAR.
|
||||
enabled = false
|
||||
}
|
||||
|
||||
tasks.build {
|
||||
dependsOn(tasks.shadowJar)
|
||||
}
|
||||
@@ -76,15 +58,11 @@ tasks.build {
|
||||
tasks.processResources {
|
||||
from(project(":common").sourceSets.main.get().resources)
|
||||
inputs.property("version", project.version)
|
||||
inputs.property("shadePE", shadePE) // Add shadePE as an input to trigger reprocessing if it changes
|
||||
filteringCharset = "UTF-8"
|
||||
|
||||
|
||||
filesMatching("plugin.yml") {
|
||||
expand(
|
||||
"version" to project.version,
|
||||
// Bukkit accepts `depend` only; `depends` is silently ignored.
|
||||
"depend" to if (shadePE) "[]" else listOf("PacketEvents")
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,9 +2,7 @@ package me.caseload.knockbacksync;
|
||||
|
||||
import com.github.retrooper.packetevents.PacketEvents;
|
||||
import com.github.retrooper.packetevents.manager.server.ServerVersion;
|
||||
import com.github.retrooper.packetevents.protocol.world.Location;
|
||||
import io.github.retrooper.packetevents.factory.spigot.SpigotPacketEventsBuilder;
|
||||
import me.caseload.knockbacksync.common.BuildConfig;
|
||||
import me.caseload.knockbacksync.event.events.ConfigReloadEvent;
|
||||
import me.caseload.knockbacksync.event.KBSyncEventHandler;
|
||||
import me.caseload.knockbacksync.listener.bukkit.*;
|
||||
@@ -22,13 +20,10 @@ import me.caseload.knockbacksync.world.BukkitServer;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Server;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.plugin.PluginManager;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
import org.bukkit.util.Vector;
|
||||
import org.incendo.cloud.bukkit.CloudBukkitCapabilities;
|
||||
import org.incendo.cloud.execution.ExecutionCoordinator;
|
||||
import org.incendo.cloud.paper.LegacyPaperCommandManager;
|
||||
@@ -41,9 +36,6 @@ import java.lang.invoke.MethodType;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.net.URL;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Map;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
@@ -104,10 +96,6 @@ public class BukkitBase extends Base {
|
||||
|
||||
@Override
|
||||
public void load() {
|
||||
// External-provider mode delegates PacketEvents lifecycle to the installed PE plugin.
|
||||
if (!BuildConfig.SHADE_PE) {
|
||||
return;
|
||||
}
|
||||
PacketEvents.setAPI(SpigotPacketEventsBuilder.build(this.plugin));
|
||||
PacketEvents.getAPI().load();
|
||||
}
|
||||
@@ -116,7 +104,7 @@ public class BukkitBase extends Base {
|
||||
public void enable() {
|
||||
super.enable();
|
||||
super.eventBus.registerListeners(this);
|
||||
if (PacketEvents.getAPI().getServerManager().getVersion().isNewerThanOrEquals(ServerVersion.V_1_20_5) && this.getPlatform() == Platform.BUKKIT) {
|
||||
if (PacketEvents.getAPI().getServerManager().getVersion().isNewerThanOrEquals(ServerVersion.V_1_20_5)) {
|
||||
scheduler.runTaskTimerAsynchronously(this::setUpdateIntervals, 1, 1);
|
||||
}
|
||||
}
|
||||
@@ -138,11 +126,8 @@ public class BukkitBase extends Base {
|
||||
registerPluginListeners(
|
||||
new BukkitPlayerDamageListener(),
|
||||
new BukkitPlayerKnockbackListener(),
|
||||
new me.caseload.knockbacksync.listener.bukkit.KnockbackResistanceNullifier()
|
||||
new BukkitPlayerJoinQuitListener()
|
||||
);
|
||||
// Reconcile away any leftover owned knockback-resistance marker for players already
|
||||
// online (e.g. across a /reload), so none is stranded.
|
||||
me.caseload.knockbacksync.listener.bukkit.KnockbackResistanceNullifier.cleanupAll();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -190,18 +175,6 @@ public class BukkitBase extends Base {
|
||||
return 20.0f;
|
||||
}
|
||||
|
||||
public URL getJarURL() {
|
||||
try {
|
||||
String path = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
|
||||
File pluginJarFile = new File(path);
|
||||
|
||||
return Paths.get(getDataFolder().getParentFile().getAbsolutePath(), pluginJarFile.getName()).toUri().toURL();
|
||||
} catch (Exception e) {
|
||||
LOGGER.severe("Couldn't find plugin file: " + e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void registerPluginListeners(Listener... listeners) {
|
||||
PluginManager pluginManager = this.plugin.getServer().getPluginManager();
|
||||
for (Listener listener : listeners)
|
||||
@@ -252,21 +225,4 @@ public class BukkitBase extends Base {
|
||||
public void onConfigReload(ConfigReloadEvent event) {
|
||||
playerUpdateInterval = event.getConfigManager().getConfigWrapper().getInt("entity_tick_intervals.player", 2);
|
||||
}
|
||||
|
||||
public void restartServer() {
|
||||
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "restart");
|
||||
}
|
||||
|
||||
public boolean hasRestartScript() {
|
||||
File spigotFile = new File("spigot.yml");
|
||||
if (!spigotFile.exists())
|
||||
return false;
|
||||
|
||||
FileConfiguration spigotConfig = YamlConfiguration.loadConfiguration(spigotFile);
|
||||
String scriptValue = spigotConfig.getString("settings.restart-script");
|
||||
if (scriptValue == null || scriptValue.isEmpty())
|
||||
return false;
|
||||
|
||||
return Paths.get(scriptValue).toAbsolutePath().normalize().toFile().exists();
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
package me.caseload.knockbacksync;
|
||||
|
||||
import com.github.retrooper.packetevents.PacketEvents;
|
||||
import me.caseload.knockbacksync.common.BuildConfig;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
public final class BukkitLoaderPlugin extends JavaPlugin {
|
||||
@@ -20,14 +19,6 @@ public final class BukkitLoaderPlugin extends JavaPlugin {
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
// Reconcile away any leftover owned knockback-resistance marker so no player is left
|
||||
// with reduced resistance after the plugin unloads.
|
||||
me.caseload.knockbacksync.listener.bukkit.KnockbackResistanceNullifier.cleanupAll();
|
||||
// Drop listener handles before any lifecycle decision; the shared API may outlive this plugin.
|
||||
core.unregisterPacketListeners();
|
||||
// Terminate only when this plugin owns the PacketEvents lifecycle (shaded build).
|
||||
if (BuildConfig.SHADE_PE) {
|
||||
PacketEvents.getAPI().terminate();
|
||||
}
|
||||
PacketEvents.getAPI().terminate();
|
||||
}
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
package me.caseload.knockbacksync.api;
|
||||
|
||||
import com.github.retrooper.packetevents.protocol.player.User;
|
||||
import com.github.retrooper.packetevents.util.Vector3d;
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.manager.ConfigManager;
|
||||
import me.caseload.knockbacksync.manager.PlayerDataManager;
|
||||
import me.caseload.knockbacksync.player.BukkitPlayer;
|
||||
import me.caseload.knockbacksync.player.PlayerData;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.util.Vector;
|
||||
|
||||
/**
|
||||
* Stable, reflection-friendly entry point for other plugins (notably OldCombatMechanics'
|
||||
* old-fishing-knockback module) to hand KnockbackSync a pre-computed knockback vector, so that
|
||||
* KnockbackSync owns the final velocity and applies the same latency Y-correction it gives melee
|
||||
* knockback.
|
||||
*
|
||||
* <p>Why this exists: a fishing-rod hit reaches KnockbackSync as an ordinary player-vs-player
|
||||
* damage event. KnockbackSync cannot tell it apart from a sword hit, so it computes a melee vector
|
||||
* and the caller's own {@code setVelocity} either fights it or is re-corrected with melee-tuned
|
||||
* latency logic — the rod pop ends up flattened/inconsistent under latency. Routing the
|
||||
* bobber-direction vector through here makes the rod feel like 1.8, latency-synced like melee.</p>
|
||||
*
|
||||
* <p>Resolved by callers via reflection; keep the class name, package, and method signature
|
||||
* stable.</p>
|
||||
*/
|
||||
public final class KnockbackSyncRodApi {
|
||||
|
||||
private KnockbackSyncRodApi() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a fishing-rod knockback vector for {@code victim}, to be applied and latency-synced
|
||||
* by the {@code PlayerVelocityEvent} produced by the caller's subsequent damage tick.
|
||||
*
|
||||
* <p>MUST be called on the main thread, immediately before the caller deals the rod's damage.</p>
|
||||
*
|
||||
* @param victim the player being knocked back
|
||||
* @param rodKnockback the 1.8 bobber-direction knockback vector
|
||||
* @return {@code true} if KnockbackSync will own this knockback (caller must NOT also call
|
||||
* {@code setVelocity}); {@code false} if KnockbackSync is disabled or not tracking this
|
||||
* player, in which case the caller should apply the knockback itself.
|
||||
*/
|
||||
public static boolean applyRodKnockback(Player victim, Vector rodKnockback) {
|
||||
if (victim == null || rodKnockback == null) return false;
|
||||
|
||||
final Base base = Base.INSTANCE;
|
||||
if (base == null) return false;
|
||||
|
||||
final ConfigManager config = base.getConfigManager();
|
||||
if (config == null || !config.isToggled() || !config.isLegacyKnockbackEnabled())
|
||||
return false;
|
||||
|
||||
final User user = new BukkitPlayer(victim).getUser();
|
||||
if (user == null) return false;
|
||||
|
||||
final PlayerData playerData = PlayerDataManager.getPlayerData(user);
|
||||
if (playerData == null) return false; // not tracked (exempt/Geyser/etc.) — caller falls back
|
||||
|
||||
final Vector3d kb = new Vector3d(rodKnockback.getX(), rodKnockback.getY(), rodKnockback.getZ());
|
||||
playerData.setRodKnockback(kb);
|
||||
// On-ground sync should target the rod's vertical, mirroring the melee damage path.
|
||||
playerData.setVerticalVelocity(kb.getY());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
+1
-42
@@ -1,57 +1,16 @@
|
||||
package me.caseload.knockbacksync.listener.bukkit;
|
||||
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.listener.PlayerDamageListener;
|
||||
import me.caseload.knockbacksync.manager.ConfigManager;
|
||||
import me.caseload.knockbacksync.player.BukkitPlayer;
|
||||
import me.caseload.knockbacksync.util.MultiLibUtil;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.entity.EntityDamageByEntityEvent;
|
||||
|
||||
public class BukkitPlayerDamageListener extends PlayerDamageListener implements Listener {
|
||||
|
||||
/**
|
||||
* D3 — projectile PvP knockback-resistance nullification.
|
||||
*
|
||||
* <p>For a hit that {@link PvpSource} classifies as {@code PROJECTILE} PvP, zero the
|
||||
* victim's effective knockback resistance BEFORE vanilla computes the knockback, so a
|
||||
* netherite victim takes full (diamond-level) projectile knockback. Runs at {@code LOW}
|
||||
* so it precedes OCM's {@code projectile-knockback} damage raise ({@code NORMAL}) and
|
||||
* vanilla knockback. The decision is gated on classification + config only — never on the
|
||||
* current event damage, because OCM may not have raised snowball/egg/ender-pearl damage
|
||||
* yet at this priority.</p>
|
||||
*/
|
||||
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
|
||||
public void onProjectilePvpDamage(EntityDamageByEntityEvent event) {
|
||||
final ConfigManager config = Base.INSTANCE.getConfigManager();
|
||||
// Single source of truth: active only when toggled on, legacy knockback enabled,
|
||||
// and knockback resistance is NOT being kept (matching OCM's default).
|
||||
if (!config.isToggled() || !config.isLegacyKnockbackEnabled() || config.isLegacyKnockbackResistanceEnabled())
|
||||
return;
|
||||
|
||||
if (PvpSource.classify(event) != PvpSource.Type.PROJECTILE)
|
||||
return;
|
||||
|
||||
final Player victim = (Player) event.getEntity();
|
||||
if (MultiLibUtil.isExternalPlayer(victim))
|
||||
return;
|
||||
|
||||
KnockbackResistanceNullifier.nullify(victim);
|
||||
}
|
||||
|
||||
/**
|
||||
* Melee PvP: KnockbackSync owns the 1.8 melee velocity via {@code LegacyKnockback}
|
||||
* (applied at {@code PlayerVelocityEvent}), so melee already delivers full knockback
|
||||
* without touching the resistance attribute. The previous {@code stripKnockbackResistance()}
|
||||
* (which removed the victim's {@code KNOCKBACK_RESISTANCE} modifiers and never restored them,
|
||||
* leaking into PvE) has been deleted. Projectile/explosion/fishing hits are NOT routed
|
||||
* through this melee path (their damager is not a player), so no stale legacy-knockback
|
||||
* vector can be stored for them.
|
||||
*/
|
||||
@EventHandler(ignoreCancelled = true)
|
||||
public void onPlayerDamage(EntityDamageByEntityEvent event) {
|
||||
Entity victim = event.getEntity();
|
||||
@@ -64,4 +23,4 @@ public class BukkitPlayerDamageListener extends PlayerDamageListener implements
|
||||
|
||||
onPlayerDamage(new BukkitPlayer((Player) victim), new BukkitPlayer((Player) attacker));
|
||||
}
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package me.caseload.knockbacksync.listener.bukkit;
|
||||
|
||||
import com.github.retrooper.packetevents.PacketEvents;
|
||||
import com.github.retrooper.packetevents.manager.server.ServerVersion;
|
||||
import me.caseload.knockbacksync.listener.PlayerJoinQuitListener;
|
||||
import me.caseload.knockbacksync.player.BukkitPlayer;
|
||||
import me.caseload.knockbacksync.player.PlayerData;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class BukkitPlayerJoinQuitListener extends PlayerJoinQuitListener implements Listener {
|
||||
|
||||
public static List<Object> chunkMapList = new ArrayList<>();
|
||||
|
||||
@EventHandler
|
||||
public void onPlayerJoin(PlayerJoinEvent event) {
|
||||
onPlayerJoin(new PlayerData(new BukkitPlayer(event.getPlayer())));
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onPlayerQuit(PlayerQuitEvent event) {
|
||||
onPlayerQuit(event.getPlayer().getUniqueId());
|
||||
}
|
||||
}
|
||||
+4
-12
@@ -16,11 +16,7 @@ import org.bukkit.util.Vector;
|
||||
|
||||
public class BukkitPlayerKnockbackListener extends PlayerKnockbackListener implements Listener {
|
||||
|
||||
// HIGHEST so KnockbackSync is the last writer in the event chain: it owns the final
|
||||
// melee velocity. We read and write the EVENT velocity (not player.getVelocity()/
|
||||
// player.setVelocity()) so we integrate with the chain instead of fighting it. See
|
||||
// knockback-sync issue #7 (kernitus, Krymonota, Axionize).
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
|
||||
public void onPlayerVelocity(PlayerVelocityEvent event) {
|
||||
Player victim = event.getPlayer();
|
||||
EntityDamageEvent entityDamageEvent = victim.getLastDamageCause();
|
||||
@@ -38,11 +34,7 @@ public class BukkitPlayerKnockbackListener extends PlayerKnockbackListener imple
|
||||
if (MultiLibUtil.isExternalPlayer(victim))
|
||||
return;
|
||||
|
||||
Vector eventVelocity = event.getVelocity();
|
||||
Vector3d result = onPlayerVelocity(new BukkitPlayer(victim),
|
||||
new Vector3d(eventVelocity.getX(), eventVelocity.getY(), eventVelocity.getZ()));
|
||||
|
||||
if (result != null)
|
||||
event.setVelocity(new Vector(result.getX(), result.getY(), result.getZ()));
|
||||
Vector vector = victim.getVelocity();
|
||||
onPlayerVelocity(new BukkitPlayer(victim), new Vector3d(vector.getX(), vector.getY(), vector.getZ()));
|
||||
}
|
||||
}
|
||||
}
|
||||
-121
@@ -1,121 +0,0 @@
|
||||
package me.caseload.knockbacksync.listener.bukkit;
|
||||
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.attribute.Attribute;
|
||||
import org.bukkit.attribute.AttributeInstance;
|
||||
import org.bukkit.attribute.AttributeModifier;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* D3 — Resistance Nullification (M1).
|
||||
*
|
||||
* <p>For player-vs-player projectile hits (classified by {@link PvpSource}), forces the
|
||||
* victim's effective {@code generic.knockback_resistance} to 0 for the duration of the
|
||||
* hit by adding a single plugin-owned {@code MULTIPLY_SCALAR_1} {@code -1.0} modifier,
|
||||
* lets vanilla compute full knockback, then removes the owned marker on the next tick.
|
||||
* Equipment and other plugins' modifiers are never read, captured, or removed — only the
|
||||
* owned marker (identified by a constant UUID) is added/removed.</p>
|
||||
*
|
||||
* <p>Melee PvP is owned by {@code LegacyKnockback} (which already ignores resistance when
|
||||
* {@code enable_knockback_resistance=false}) and needs no attribute work; fishing PvP is
|
||||
* owned by OCM's {@code old-fishing-knockback}. Explosions are out of scope on 1.19.4.</p>
|
||||
*
|
||||
* <p>The marker is permanent NMS state until removed, so a leftover marker is reconciled
|
||||
* away on join/quit and on plugin enable/disable (see {@link #cleanupAll()}), guaranteeing
|
||||
* a player is never left permanently with reduced resistance.</p>
|
||||
*/
|
||||
public final class KnockbackResistanceNullifier implements Listener {
|
||||
|
||||
// Constant, plugin-owned modifier identity. Add skips if this UUID is already present;
|
||||
// removal matches by this UUID. Equipment/foreign modifiers are never touched.
|
||||
private static final UUID MODIFIER_UUID = UUID.fromString("7b2a1c84-4d3e-4f0a-9c6b-1e5a9d8c7f30");
|
||||
private static final String MODIFIER_NAME = "knockbacksync_pvp_kb_nullify";
|
||||
|
||||
// Mirrors the previous stripKnockbackResistance guard: if the attribute is unavailable
|
||||
// on this server version, disable for the session and warn once (no per-hit log spam).
|
||||
private static volatile boolean unsupported = false;
|
||||
|
||||
/**
|
||||
* Force the victim's effective knockback resistance to 0 for the current hit by adding the
|
||||
* owned marker, then schedule its removal on the next tick. Idempotent and re-entrancy safe:
|
||||
* if the marker is already present (e.g. a second hit in the same tick) the add is skipped.
|
||||
*
|
||||
* <p>Must be called before vanilla computes the hit's knockback (i.e. during the damage
|
||||
* event at an early priority).</p>
|
||||
*/
|
||||
public static void nullify(Player victim) {
|
||||
final AttributeInstance attribute = resolve(victim);
|
||||
if (attribute == null) return;
|
||||
if (hasOwnedModifier(attribute)) return;
|
||||
|
||||
try {
|
||||
attribute.addModifier(new AttributeModifier(
|
||||
MODIFIER_UUID, MODIFIER_NAME, -1.0, AttributeModifier.Operation.MULTIPLY_SCALAR_1));
|
||||
} catch (IllegalArgumentException alreadyApplied) {
|
||||
return; // raced — modifier already present; nothing to add
|
||||
}
|
||||
|
||||
// Remove on the NEXT tick. Same-event (MONITOR/finally) removal is forbidden: vanilla
|
||||
// computes the knockback after the event returns, so an in-event removal would restore
|
||||
// the attribute before vanilla reads it. On the non-Folia target this is a main-thread
|
||||
// next-tick task; it stays compile-safe (no Player#getScheduler()).
|
||||
Base.INSTANCE.getScheduler().runTaskLater(() -> remove(victim), 1L);
|
||||
}
|
||||
|
||||
/** Remove the owned marker if present. Idempotent; never touches foreign/equipment modifiers. */
|
||||
public static void remove(Player victim) {
|
||||
final AttributeInstance attribute = resolve(victim);
|
||||
if (attribute == null) return;
|
||||
for (AttributeModifier modifier : attribute.getModifiers()) {
|
||||
if (MODIFIER_UUID.equals(modifier.getUniqueId())) {
|
||||
attribute.removeModifier(modifier);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Strip the owned marker from every online player (plugin enable/disable reconciliation). */
|
||||
public static void cleanupAll() {
|
||||
for (Player player : Bukkit.getOnlinePlayers()) {
|
||||
remove(player);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean hasOwnedModifier(AttributeInstance attribute) {
|
||||
for (AttributeModifier modifier : attribute.getModifiers()) {
|
||||
if (MODIFIER_UUID.equals(modifier.getUniqueId())) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static AttributeInstance resolve(Player victim) {
|
||||
if (unsupported || victim == null) return null;
|
||||
try {
|
||||
return victim.getAttribute(Attribute.GENERIC_KNOCKBACK_RESISTANCE);
|
||||
} catch (Throwable t) {
|
||||
unsupported = true;
|
||||
Base.INSTANCE.getLogger().warning(
|
||||
"Could not access KNOCKBACK_RESISTANCE attribute; PvP knockback-resistance "
|
||||
+ "nullification disabled for this session: " + t.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ── R7 fail-safe: reconcile away any leftover owned marker ──────────────────────────────
|
||||
|
||||
@EventHandler
|
||||
public void onJoin(PlayerJoinEvent event) {
|
||||
remove(event.getPlayer());
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onQuit(PlayerQuitEvent event) {
|
||||
remove(event.getPlayer());
|
||||
}
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
package me.caseload.knockbacksync.listener.bukkit;
|
||||
|
||||
import com.github.retrooper.packetevents.protocol.player.User;
|
||||
import me.caseload.knockbacksync.manager.PlayerDataManager;
|
||||
import me.caseload.knockbacksync.player.BukkitPlayer;
|
||||
import me.caseload.knockbacksync.player.PlayerData;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.entity.Projectile;
|
||||
import org.bukkit.event.entity.EntityDamageByEntityEvent;
|
||||
import org.bukkit.projectiles.ProjectileSource;
|
||||
|
||||
/**
|
||||
* D1 — PvP Source Attribution.
|
||||
*
|
||||
* <p>Classifies a damage event on a player victim into a source class so the
|
||||
* knockback-resistance nullifier (D3) knows whether and how to act. Attribution is
|
||||
* self-inclusive: the victim's own projectile (e.g. their own arrow) still counts as
|
||||
* PvP. This classifier only answers "is this player-attributed, and by what source
|
||||
* class?" — it does not modify damage or knockback.</p>
|
||||
*
|
||||
* <p>Scope note (Purpur 1.19.4 target): netherite {@code generic.knockback_resistance}
|
||||
* only reduces knockback applied through {@code LivingEntity.knockback(...)} (melee and
|
||||
* projectile). Explosion knockback is not reduced by it on 1.19.4 (Blast Protection
|
||||
* governs that), and wind charges do not exist, so explosion/wind-charge sources are
|
||||
* classified {@link Type#NONE}.</p>
|
||||
*/
|
||||
public final class PvpSource {
|
||||
|
||||
public enum Type {
|
||||
/** Direct player melee. Owned by {@code LegacyKnockback}; no attribute nullification. */
|
||||
MELEE,
|
||||
/** Player-shot projectile (arrow, spectral arrow, trident, snowball, egg, ender pearl, ...). Nullified by D3. */
|
||||
PROJECTILE,
|
||||
/** Fishing-rod hit (OCM {@code old-fishing-knockback}); owned by the rod sync. No nullification. */
|
||||
FISHING,
|
||||
/** Not attributable to a player (mob, environment, explosion, ...). */
|
||||
NONE
|
||||
}
|
||||
|
||||
private PvpSource() {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param event a damage-by-entity event (the caller has not necessarily checked the victim type)
|
||||
* @return the PvP source class; {@link Type#NONE} when the damage is not attributable to a player
|
||||
*/
|
||||
public static Type classify(EntityDamageByEntityEvent event) {
|
||||
if (!(event.getEntity() instanceof Player)) return Type.NONE;
|
||||
final Player victim = (Player) event.getEntity();
|
||||
final Entity damager = event.getDamager();
|
||||
|
||||
// Direct player damager: either a melee hit, or an OCM fishing-rod hit.
|
||||
// old-fishing-knockback deals its damage via damage(victim, rodder), so the
|
||||
// damager is the rodding player (not the bobber). Distinguish the rod hit via
|
||||
// the rod-pending marker KnockbackSync stores for the rod path. Both MELEE and
|
||||
// FISHING are owned elsewhere and get no attribute nullification, so a mislabel
|
||||
// between the two cannot change knockback behaviour.
|
||||
if (damager instanceof Player) {
|
||||
return isRodPending(victim) ? Type.FISHING : Type.MELEE;
|
||||
}
|
||||
|
||||
// Player-shot projectile, resolved generically via ProjectileSource so any
|
||||
// player-shot projectile type is covered without a per-type list (including
|
||||
// types absent from the compile-time API). Self-inclusive: the shooter may be
|
||||
// the victim. A non-player projectile source (e.g. a dispenser's
|
||||
// BlockProjectileSource) or a null shooter is not PvP. Note: the ender pearl's
|
||||
// post-teleport fall damage is a separate non-by-entity event, so it never
|
||||
// reaches this projectile branch.
|
||||
if (damager instanceof Projectile) {
|
||||
final ProjectileSource shooter = ((Projectile) damager).getShooter();
|
||||
return (shooter instanceof Player) ? Type.PROJECTILE : Type.NONE;
|
||||
}
|
||||
|
||||
// Explosions (TNT, end crystal, fireball), mobs, environment: out of scope on 1.19.4.
|
||||
return Type.NONE;
|
||||
}
|
||||
|
||||
private static boolean isRodPending(Player victim) {
|
||||
final User user = new BukkitPlayer(victim).getUser();
|
||||
if (user == null) return false;
|
||||
final PlayerData data = PlayerDataManager.getPlayerData(user);
|
||||
return data != null && data.isRodKnockbackPending();
|
||||
}
|
||||
}
|
||||
@@ -5,10 +5,6 @@ import com.github.retrooper.packetevents.manager.server.ServerVersion;
|
||||
import com.github.retrooper.packetevents.protocol.player.User;
|
||||
import com.github.retrooper.packetevents.protocol.world.BoundingBox;
|
||||
import com.github.retrooper.packetevents.util.Vector3d;
|
||||
import com.google.common.base.Preconditions;
|
||||
import me.caseload.knockbacksync.BukkitBase;
|
||||
import me.caseload.knockbacksync.Platform;
|
||||
import me.caseload.knockbacksync.world.FoliaWorld;
|
||||
import me.caseload.knockbacksync.world.PlatformWorld;
|
||||
import me.caseload.knockbacksync.world.SpigotWorld;
|
||||
import org.bukkit.Bukkit;
|
||||
@@ -26,19 +22,18 @@ import java.util.UUID;
|
||||
|
||||
public class BukkitPlayer implements PlatformPlayer {
|
||||
public final Player bukkitPlayer;
|
||||
public final User user;
|
||||
private String clientBrand = "vanilla";
|
||||
|
||||
// Reflection variables
|
||||
private static Class<?> craftPlayerClass;
|
||||
private static Method getHandleMethod;
|
||||
private static Method getAttackStrengthScaleMethod;
|
||||
private static final ServerVersion currentVersion = PacketEvents.getAPI().getServerManager().getVersion();
|
||||
private static ServerVersion currentVersion = PacketEvents.getAPI().getServerManager().getVersion();
|
||||
|
||||
// 1.12.2 support
|
||||
static {
|
||||
try {
|
||||
// Check the current server version
|
||||
// Check the current server versio
|
||||
|
||||
// If the version is greater than 1.14.4, use the Player method directly
|
||||
if (currentVersion.isOlderThan(ServerVersion.V_1_15)) {
|
||||
@@ -75,9 +70,7 @@ public class BukkitPlayer implements PlatformPlayer {
|
||||
}
|
||||
|
||||
public BukkitPlayer(Player player) {
|
||||
Preconditions.checkArgument(player != null);
|
||||
this.bukkitPlayer = player;
|
||||
this.user = PacketEvents.getAPI().getPlayerManager().getUser(bukkitPlayer);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -142,7 +135,7 @@ public class BukkitPlayer implements PlatformPlayer {
|
||||
|
||||
@Override
|
||||
public PlatformWorld getWorld() {
|
||||
return BukkitBase.INSTANCE.getPlatform() == Platform.FOLIA ? new FoliaWorld(bukkitPlayer.getWorld()): new SpigotWorld(bukkitPlayer.getWorld());
|
||||
return new SpigotWorld(bukkitPlayer.getWorld());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -183,16 +176,6 @@ public class BukkitPlayer implements PlatformPlayer {
|
||||
return bukkitPlayer.getInventory().getItemInMainHand().getEnchantmentLevel(Enchantment.KNOCKBACK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getWeaponKnockbackLevel() {
|
||||
// OCM parity: use the main hand item, or the off hand when the main hand is empty.
|
||||
org.bukkit.inventory.ItemStack mainHand = bukkitPlayer.getInventory().getItemInMainHand();
|
||||
org.bukkit.inventory.ItemStack weapon = mainHand.getType() == org.bukkit.Material.AIR
|
||||
? bukkitPlayer.getInventory().getItemInOffHand()
|
||||
: mainHand;
|
||||
return weapon.getEnchantmentLevel(Enchantment.KNOCKBACK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable Integer getNoDamageTicks() {
|
||||
return bukkitPlayer.getNoDamageTicks();
|
||||
@@ -229,8 +212,8 @@ public class BukkitPlayer implements PlatformPlayer {
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable User getUser() {
|
||||
return this.user;
|
||||
public User getUser() {
|
||||
return PacketEvents.getAPI().getPlayerManager().getUser(bukkitPlayer);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+17
-8
@@ -1,46 +1,55 @@
|
||||
package me.caseload.knockbacksync.scheduler;
|
||||
|
||||
import io.github.retrooper.packetevents.util.folia.FoliaScheduler;
|
||||
import io.github.retrooper.packetevents.util.folia.GlobalRegionScheduler;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
public class FoliaSchedulerAdapter implements SchedulerAdapter {
|
||||
private final Plugin plugin;
|
||||
private GlobalRegionScheduler scheduler = null;
|
||||
|
||||
public FoliaSchedulerAdapter(Plugin plugin) {
|
||||
this.plugin = plugin;
|
||||
try {
|
||||
// Attempt to find and call the `getGlobalRegionScheduler` method
|
||||
Method getSchedulerMethod = Bukkit.getServer().getClass().getMethod("getGlobalRegionScheduler");
|
||||
scheduler = (GlobalRegionScheduler) getSchedulerMethod.invoke(Bukkit.getServer());
|
||||
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
|
||||
plugin.getLogger().severe("Failed to access GlobalRegionScheduler: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public AbstractTaskHandle runTask(Runnable task) {
|
||||
return new FoliaTaskHandle(FoliaScheduler.getGlobalRegionScheduler().run(plugin, scheduledTask -> task.run()));
|
||||
return new FoliaTaskHandle(scheduler.run(plugin, scheduledTask -> task.run()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public AbstractTaskHandle runTaskAsynchronously(Runnable task) {
|
||||
return new FoliaTaskHandle(FoliaScheduler.getAsyncScheduler().runNow(plugin, scheduledTask -> task.run()));
|
||||
return new FoliaTaskHandle(scheduler.run(plugin, scheduledTask -> task.run()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public AbstractTaskHandle runTaskLater(Runnable task, long delayTicks) {
|
||||
return new FoliaTaskHandle(FoliaScheduler.getGlobalRegionScheduler().runDelayed(plugin, scheduledTask -> task.run(), delayTicks));
|
||||
return new FoliaTaskHandle(scheduler.runDelayed(plugin, scheduledTask -> task.run(), delayTicks));
|
||||
}
|
||||
|
||||
@Override
|
||||
public AbstractTaskHandle runTaskTimer(Runnable task, long delayTicks, long periodTicks) {
|
||||
return new FoliaTaskHandle(FoliaScheduler.getGlobalRegionScheduler().runAtFixedRate(plugin, scheduledTask -> task.run(), delayTicks, periodTicks));
|
||||
return new FoliaTaskHandle(scheduler.runAtFixedRate(plugin, scheduledTask -> task.run(), delayTicks, periodTicks));
|
||||
}
|
||||
|
||||
@Override
|
||||
public AbstractTaskHandle runTaskLaterAsynchronously(Runnable task, long delay) {
|
||||
return new FoliaTaskHandle(FoliaScheduler.getAsyncScheduler().runDelayed(plugin, scheduledTask -> task.run(), delay * 50, TimeUnit.MILLISECONDS));
|
||||
return new FoliaTaskHandle(scheduler.runDelayed(plugin, scheduledTask -> task.run(), delay));
|
||||
}
|
||||
|
||||
@Override
|
||||
public AbstractTaskHandle runTaskTimerAsynchronously(Runnable task, long delay, long period) {
|
||||
return new FoliaTaskHandle(FoliaScheduler.getAsyncScheduler().runAtFixedRate(plugin, scheduledTask -> task.run(), delay, period));
|
||||
return new FoliaTaskHandle(scheduler.runAtFixedRate(plugin, scheduledTask -> task.run(), delay, period));
|
||||
}
|
||||
|
||||
// Folia takes care of this
|
||||
|
||||
@@ -1,19 +1,41 @@
|
||||
package me.caseload.knockbacksync.scheduler;
|
||||
|
||||
import io.github.retrooper.packetevents.util.folia.TaskWrapper;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
public class FoliaTaskHandle implements AbstractTaskHandle {
|
||||
|
||||
private final TaskWrapper scheduledTask; // Store as Object instead of ScheduledTask
|
||||
import java.lang.invoke.MethodHandle;
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.lang.invoke.MethodType;
|
||||
|
||||
public class FoliaTaskHandle implements AbstractTaskHandle {
|
||||
private static final MethodHandle GET_OWNING_PLUGIN;
|
||||
private static final MethodHandle CANCEL;
|
||||
|
||||
static {
|
||||
try {
|
||||
Class<?> scheduledTaskClass = Class.forName("io.papermc.paper.threadedregions.scheduler.ScheduledTask");
|
||||
MethodHandles.Lookup lookup = MethodHandles.lookup();
|
||||
|
||||
GET_OWNING_PLUGIN = lookup.findVirtual(scheduledTaskClass, "getOwningPlugin", MethodType.methodType(Plugin.class));
|
||||
CANCEL = lookup.findVirtual(scheduledTaskClass, "cancel", MethodType.methodType(void.class));
|
||||
} catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException e) {
|
||||
throw new RuntimeException("Failed to initialize FoliaTaskHandle reflection", e);
|
||||
}
|
||||
}
|
||||
|
||||
private final Object scheduledTask; // Store as Object instead of ScheduledTask
|
||||
private boolean cancelled;
|
||||
|
||||
public FoliaTaskHandle(@NotNull TaskWrapper scheduledTask) {
|
||||
public FoliaTaskHandle(@NotNull Object scheduledTask) {
|
||||
this.scheduledTask = scheduledTask;
|
||||
}
|
||||
|
||||
public Plugin getOwner() {
|
||||
return scheduledTask.getOwner();
|
||||
try {
|
||||
return (Plugin) GET_OWNING_PLUGIN.invoke(scheduledTask);
|
||||
} catch (Throwable e) {
|
||||
throw new RuntimeException("Failed to invoke getOwningPlugin", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -23,7 +45,11 @@ public class FoliaTaskHandle implements AbstractTaskHandle {
|
||||
|
||||
@Override
|
||||
public void cancel() {
|
||||
scheduledTask.cancel();
|
||||
try {
|
||||
CANCEL.invoke(scheduledTask);
|
||||
} catch (Throwable e) {
|
||||
throw new RuntimeException("Failed to invoke cancel", e);
|
||||
}
|
||||
this.cancelled = true;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
package me.caseload.knockbacksync.stats.custom;
|
||||
|
||||
|
||||
/*
|
||||
* This Metrics class was auto-generated and can be copied into your project if you are
|
||||
* not using a build tool like Gradle or Maven for dependency management.
|
||||
|
||||
@@ -3,7 +3,6 @@ package me.caseload.knockbacksync.world;
|
||||
import me.caseload.knockbacksync.player.BukkitPlayer;
|
||||
import me.caseload.knockbacksync.player.PlatformPlayer;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.UUID;
|
||||
@@ -20,9 +19,4 @@ public class BukkitServer implements PlatformServer {
|
||||
public PlatformPlayer getPlayer(UUID uuid) {
|
||||
return new BukkitPlayer(Bukkit.getPlayer(uuid));
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlatformPlayer getPlayer(Object nativePlatformPlayer) {
|
||||
return new BukkitPlayer((Player) nativePlatformPlayer);
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
package me.caseload.knockbacksync.world;
|
||||
|
||||
import com.github.retrooper.packetevents.protocol.world.states.WrappedBlockState;
|
||||
import io.github.retrooper.packetevents.util.SpigotConversionUtil;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.block.BlockState;
|
||||
|
||||
public class FoliaWorld extends SpigotWorld {
|
||||
public FoliaWorld(World world) {
|
||||
super(world);
|
||||
}
|
||||
|
||||
@Override
|
||||
public WrappedBlockState getBlockStateAt(int x, int y, int z) {
|
||||
BlockState block = this.world.getBlockState(x, y, z);
|
||||
return SpigotConversionUtil.fromBukkitBlockData(block.getBlockData());
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,7 @@ import org.bukkit.util.Vector;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
public class SpigotWorld implements PlatformWorld {
|
||||
protected final World world;
|
||||
private final World world;
|
||||
|
||||
// Reflection variables
|
||||
private static Class<?> craftWorldClass;
|
||||
@@ -85,7 +85,7 @@ public class SpigotWorld implements PlatformWorld {
|
||||
|
||||
@Override
|
||||
public WrappedBlockState getBlockStateAt(Vector3d loc) {
|
||||
return getBlockStateAt((int) Math.floor(loc.x), (int) Math.floor(loc.y), (int) Math.floor(loc.z));
|
||||
return getBlockStateAt((int) Math.floor(loc.x), (int) Math.floor(loc.x), (int) Math.floor(loc.x));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
name: KnockbackSync-OG
|
||||
name: KnockbackSync
|
||||
version: ${version}
|
||||
main: me.caseload.knockbacksync.BukkitLoaderPlugin
|
||||
api-version: '1.13' # We actually support 1.12.2, api-version was added later though
|
||||
authors: [ Caseload, Axionize ]
|
||||
description: Synchronizes player knockback for smoother gameplay.
|
||||
folia-supported: true
|
||||
depend: ${depend}
|
||||
permissions:
|
||||
knockbacksync.update:
|
||||
default: op
|
||||
|
||||
+19
-12
@@ -1,24 +1,25 @@
|
||||
plugins {
|
||||
id("fabric-loom")
|
||||
id("com.github.gmazzo.buildconfig") version "3.1.0"
|
||||
}
|
||||
|
||||
val shadePE: Boolean by rootProject.extra
|
||||
|
||||
dependencies {
|
||||
minecraft("com.mojang:minecraft:1.16.5")
|
||||
mappings(loom.layered {
|
||||
officialMojangMappings()
|
||||
parchment("org.parchmentmc.data:parchment-1.16.5:2022.03.06")
|
||||
})
|
||||
|
||||
// True compileOnly deps
|
||||
compileOnly("org.geysermc.floodgate:api:2.0-SNAPSHOT")
|
||||
compileOnly("io.netty:netty-all:4.1.72.Final")
|
||||
compileOnly("org.projectlombok:lombok:1.18.34")
|
||||
annotationProcessor("org.projectlombok:lombok:1.18.34")
|
||||
|
||||
// Upstream 2.11.2 API; runtime impl is the externally installed True-OG fork or the shaded bundle.
|
||||
if (shadePE) {
|
||||
implementation("com.github.retrooper:packetevents-api:2.11.2")
|
||||
} else {
|
||||
compileOnly("com.github.retrooper:packetevents-api:2.11.2")
|
||||
}
|
||||
|
||||
// Shaded in or bundled by platform-specific code
|
||||
implementation("com.github.retrooper:packetevents-api:2.5.0")
|
||||
implementation("org.yaml:snakeyaml:2.0")
|
||||
// implementation("com.fasterxml.jackson.core:jackson-databind:2.17.2")
|
||||
// implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.17.2")
|
||||
implementation("org.kohsuke:github-api:1.326") {
|
||||
exclude(group = "commons-io", module = "commons-io")
|
||||
exclude(group = "org.apache.commons", module = "commons-lang3")
|
||||
@@ -28,8 +29,14 @@ dependencies {
|
||||
implementation("org.incendo:cloud-minecraft-extras:2.0.0-beta.10")
|
||||
}
|
||||
|
||||
repositories {
|
||||
maven("https://maven.neoforged.net/releases")
|
||||
}
|
||||
|
||||
tasks.named("remapJar").configure {
|
||||
enabled = false
|
||||
}
|
||||
|
||||
buildConfig {
|
||||
buildConfigField("String", "GITHUB_REPO", "\"${project.rootProject.ext["githubRepo"]}\"")
|
||||
// Exposes shadePE to source code as a compile-time constant.
|
||||
buildConfigField("boolean", "SHADE_PE", shadePE.toString())
|
||||
}
|
||||
@@ -1,10 +1,8 @@
|
||||
package me.caseload.knockbacksync;
|
||||
|
||||
import com.github.retrooper.packetevents.PacketEvents;
|
||||
import com.github.retrooper.packetevents.event.PacketListenerCommon;
|
||||
import lombok.Getter;
|
||||
import me.caseload.knockbacksync.command.MainCommand;
|
||||
import me.caseload.knockbacksync.common.BuildConfig;
|
||||
import me.caseload.knockbacksync.command.generic.AbstractPlayerSelectorParser;
|
||||
import me.caseload.knockbacksync.command.generic.BuilderCommand;
|
||||
import me.caseload.knockbacksync.command.subcommand.PingCommand;
|
||||
@@ -15,7 +13,9 @@ import me.caseload.knockbacksync.command.subcommand.ToggleOffGroundSubcommand;
|
||||
import me.caseload.knockbacksync.event.Event;
|
||||
import me.caseload.knockbacksync.event.EventBus;
|
||||
import me.caseload.knockbacksync.event.OptimizedEventBus;
|
||||
import me.caseload.knockbacksync.listener.packetevents.*;
|
||||
import me.caseload.knockbacksync.listener.packetevents.AttributeChangeListener;
|
||||
import me.caseload.knockbacksync.listener.packetevents.ClientBrandListener;
|
||||
import me.caseload.knockbacksync.listener.packetevents.PingReceiveListener;
|
||||
import me.caseload.knockbacksync.manager.ConfigManager;
|
||||
import me.caseload.knockbacksync.permission.PermissionChecker;
|
||||
import me.caseload.knockbacksync.scheduler.SchedulerAdapter;
|
||||
@@ -27,14 +27,8 @@ import me.caseload.knockbacksync.world.PlatformServer;
|
||||
import org.incendo.cloud.CommandManager;
|
||||
import org.kohsuke.github.GitHub;
|
||||
|
||||
import java.io.DataInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.InputStream;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.*;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
@@ -55,9 +49,6 @@ public abstract class Base {
|
||||
@Getter
|
||||
protected AbstractPlayerSelectorParser<Sender> playerSelectorParser;
|
||||
|
||||
// Tracked so onDisable can unregister exactly the listeners registered against the shared provider.
|
||||
private final java.util.List<PacketListenerCommon> peListenerHandles = new java.util.ArrayList<>();
|
||||
|
||||
protected Base() {
|
||||
this.platform = detectPlatform();
|
||||
INSTANCE = this;
|
||||
@@ -110,10 +101,6 @@ public abstract class Base {
|
||||
public abstract void initializeScheduler();
|
||||
|
||||
public void initializePacketEvents() {
|
||||
// External-provider mode skips lifecycle ownership entirely.
|
||||
if (!BuildConfig.SHADE_PE) {
|
||||
return;
|
||||
}
|
||||
PacketEvents.getAPI().getSettings()
|
||||
.checkForUpdates(false)
|
||||
.debug(false);
|
||||
@@ -122,34 +109,14 @@ public abstract class Base {
|
||||
}
|
||||
|
||||
protected void registerCommonListeners() {
|
||||
registerTrackedPacketListener(new AttributeChangeListener());
|
||||
registerTrackedPacketListener(new PingSendListener());
|
||||
registerTrackedPacketListener(new PingReceiveListener());
|
||||
registerTrackedPacketListener(new PacketPlayerJoinQuit());
|
||||
registerTrackedPacketListener(new ClientBrandListener());
|
||||
PacketEvents.getAPI().getEventManager().registerListeners(
|
||||
new AttributeChangeListener(),
|
||||
new PingReceiveListener(),
|
||||
new ClientBrandListener()
|
||||
);
|
||||
Event.setEventBus(eventBus);
|
||||
}
|
||||
|
||||
/** Register a PacketEvents listener and remember its handle for unregister on disable. */
|
||||
protected void registerTrackedPacketListener(PacketListenerCommon listener) {
|
||||
PacketEvents.getAPI().getEventManager().registerListener(listener);
|
||||
peListenerHandles.add(listener);
|
||||
}
|
||||
|
||||
/** Unregister every tracked PacketEvents listener. */
|
||||
public void unregisterPacketListeners() {
|
||||
for (PacketListenerCommon handle : peListenerHandles) {
|
||||
try {
|
||||
PacketEvents.getAPI().getEventManager().unregisterListener(handle);
|
||||
} catch (Throwable t) {
|
||||
if (LOGGER != null) {
|
||||
LOGGER.warning("Failed to unregister PE listener: " + t.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
peListenerHandles.clear();
|
||||
}
|
||||
|
||||
protected abstract void registerPlatformListeners();
|
||||
|
||||
protected void registerCommands() {
|
||||
@@ -164,6 +131,7 @@ public abstract class Base {
|
||||
list.forEach(command -> command.register(commandManager));
|
||||
}
|
||||
|
||||
|
||||
protected abstract String getVersion();
|
||||
|
||||
protected void checkForUpdates() {
|
||||
@@ -184,25 +152,15 @@ public abstract class Base {
|
||||
LOGGER.warning("You are running an older version. A new update is available for download at: https://github.com/CASELOAD7000/knockback-sync/releases/latest");
|
||||
configManager.setUpdateAvailable(true);
|
||||
} else if (comparisonResult > 0) {
|
||||
if (currentVersion.contains("-dev"))
|
||||
if (currentVersion.contains("-dev")) {
|
||||
LOGGER.info("You are running a development build newer than the latest release.");
|
||||
else {
|
||||
} else {
|
||||
LOGGER.info("You are running a version newer than the latest release.");
|
||||
}
|
||||
configManager.setUpdateAvailable(false);
|
||||
} else {
|
||||
LOGGER.info("You are running the latest release.");
|
||||
}
|
||||
|
||||
if (configManager.isUpdateAvailable() && configManager.isAutoUpdate()) {
|
||||
LOGGER.info("Updating...");
|
||||
byte[] bytes = downloadLatestRelease(github);
|
||||
updatePlugin(bytes);
|
||||
|
||||
if (hasRestartScript())
|
||||
scheduler.runTask(this::restartServer);
|
||||
else {
|
||||
// Yeah
|
||||
}
|
||||
configManager.setUpdateAvailable(false);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOGGER.severe("Failed to check for updates: " + e.getMessage());
|
||||
@@ -210,44 +168,6 @@ public abstract class Base {
|
||||
});
|
||||
}
|
||||
|
||||
private void updatePlugin(byte[] pluginBytes) throws URISyntaxException {
|
||||
File file = new File(getJarURL().toURI());
|
||||
|
||||
try (FileOutputStream outputStream = new FileOutputStream(file)) {
|
||||
outputStream.write(pluginBytes);
|
||||
LOGGER.info("Successfully updated the plugin!");
|
||||
} catch (Exception e) {
|
||||
LOGGER.severe("Failed to update: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] downloadLatestRelease(GitHub github) {
|
||||
try {
|
||||
return github.getRepository("CASELOAD7000/knockback-sync")
|
||||
.getLatestRelease()
|
||||
.getAssets().stream()
|
||||
.filter(asset -> asset.getName().endsWith(".jar")
|
||||
&& asset.getName().contains(platform.equals(Platform.FABRIC)
|
||||
? "fabric" : "bukkit"))
|
||||
.findFirst()
|
||||
.map(asset -> {
|
||||
try (InputStream inputStream = new URL(asset.getBrowserDownloadUrl()).openStream()) {
|
||||
inputStream.reset();
|
||||
byte[] bytes = new byte[inputStream.available()];
|
||||
DataInputStream dataInputStream = new DataInputStream(inputStream);
|
||||
dataInputStream.readFully(bytes);
|
||||
return bytes;
|
||||
} catch (Exception e) {
|
||||
LOGGER.severe("Failed to download latest release: " + e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}).orElse(null);
|
||||
} catch (Exception e) {
|
||||
LOGGER.severe("Failed to locate latest release: " + e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private int compareVersions(String version1, String version2) {
|
||||
String[] v1Parts = version1.split("[-.]");
|
||||
String[] v2Parts = version2.split("[-.]");
|
||||
@@ -308,12 +228,6 @@ public abstract class Base {
|
||||
public abstract PermissionChecker getPermissionChecker();
|
||||
|
||||
public abstract float getTickRate();
|
||||
|
||||
public abstract URL getJarURL();
|
||||
|
||||
public abstract void restartServer();
|
||||
|
||||
public abstract boolean hasRestartScript();
|
||||
}
|
||||
|
||||
|
||||
@@ -34,19 +34,6 @@ public class ConfigWrapper {
|
||||
return NumberConversions.toLong(value, def);
|
||||
}
|
||||
|
||||
public double getDouble(String path, double def) {
|
||||
Object value = getValue(path);
|
||||
if (value instanceof Number) return ((Number) value).doubleValue();
|
||||
if (value instanceof String) {
|
||||
try {
|
||||
return Double.parseDouble((String) value);
|
||||
} catch (NumberFormatException ignored) {
|
||||
return def;
|
||||
}
|
||||
}
|
||||
return def;
|
||||
}
|
||||
|
||||
public void set(String path, Object value) {
|
||||
setValue(path, value);
|
||||
}
|
||||
|
||||
+19
-24
@@ -1,13 +1,11 @@
|
||||
package me.caseload.knockbacksync.command.subcommand;
|
||||
|
||||
import com.github.retrooper.packetevents.protocol.player.User;
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.ConfigWrapper;
|
||||
import me.caseload.knockbacksync.command.generic.BuilderCommand;
|
||||
import me.caseload.knockbacksync.command.generic.PlayerSelector;
|
||||
import me.caseload.knockbacksync.event.KBSyncEventHandler;
|
||||
import me.caseload.knockbacksync.event.events.ConfigReloadEvent;
|
||||
import me.caseload.knockbacksync.manager.ConfigManager;
|
||||
import me.caseload.knockbacksync.manager.PlayerDataManager;
|
||||
import me.caseload.knockbacksync.player.PlayerData;
|
||||
import me.caseload.knockbacksync.sender.Sender;
|
||||
@@ -20,8 +18,6 @@ import java.util.function.Predicate;
|
||||
|
||||
public class PingCommand implements BuilderCommand {
|
||||
|
||||
private static final ConfigManager configManager = Base.INSTANCE.getConfigManager();
|
||||
|
||||
private String pingSelfAvailableMessage;
|
||||
private String pingSelfUnavailableMessage;
|
||||
private String pingOtherAvailableMessage;
|
||||
@@ -55,17 +51,17 @@ public class PingCommand implements BuilderCommand {
|
||||
if (context.sender().isConsole()) {
|
||||
context.sender().sendMessage(ChatUtil.translateAlternateColorCodes('&', mustSpecifyPlayerFromConsoleMessage));
|
||||
} else {
|
||||
context.sender().sendMessage(getPingMessage(context.sender().getUniqueId(), context.sender().getName(), null, null));
|
||||
context.sender().sendMessage(getPingMessage(context.sender().getUniqueId(), null));
|
||||
}
|
||||
} else {
|
||||
context.sender().sendMessage(getPingMessage(context.sender().getUniqueId(), context.sender().getName(), targetSelector.getSinglePlayer().getUUID(), targetSelector.getSinglePlayer().getName()));
|
||||
context.sender().sendMessage(getPingMessage(context.sender().getUniqueId(), targetSelector.getSinglePlayer().getUUID()));
|
||||
}
|
||||
})
|
||||
);
|
||||
Base.INSTANCE.getEventBus().registerListeners(this);
|
||||
}
|
||||
private void loadConfig() {
|
||||
ConfigWrapper configWrapper = configManager.getConfigWrapper();
|
||||
ConfigWrapper configWrapper = Base.INSTANCE.getConfigManager().getConfigWrapper();
|
||||
pingSelfAvailableMessage = configWrapper.getString("messages.ping.self.available",
|
||||
"Your real ping is &b%ping%&rms. Jitter: &b%jitter%&rms. Spike: &b%spike%&r. Compensated ping: &b%compensated%&rms.");
|
||||
pingSelfUnavailableMessage = configWrapper.getString("messages.ping.self.unavailable",
|
||||
@@ -82,26 +78,25 @@ public class PingCommand implements BuilderCommand {
|
||||
"&cKnockback synchronization is currently disabled for the target player.");
|
||||
}
|
||||
|
||||
private String getPingMessage(UUID senderUUID, String senderName, UUID targetUUID, String targetName) {
|
||||
private String getPingMessage(UUID senderUUID, UUID targetUUID) {
|
||||
PlayerData playerData = null;
|
||||
boolean isSelf = senderUUID.equals(targetUUID) || targetUUID == null;
|
||||
String message;
|
||||
if (isSelf) {
|
||||
message = knockbacksyncDisabledForYouMessage;
|
||||
targetUUID = senderUUID;
|
||||
targetName = senderName;
|
||||
} else {
|
||||
message = knockbacksyncDisabledForTargetMessage;
|
||||
|
||||
if (senderUUID == null) {
|
||||
senderUUID = targetUUID;
|
||||
}
|
||||
|
||||
User targetUser = Base.INSTANCE.getPlatformServer().getPlayer(targetUUID).getUser();
|
||||
if (targetUser == null)
|
||||
return ChatUtil.translateAlternateColorCodes('&',
|
||||
configManager.getPlayerDisconnectedWhileExecutingCommand()
|
||||
).replace("%player%", targetName);
|
||||
|
||||
PlayerData playerData = PlayerDataManager.getPlayerData(targetUser);
|
||||
if (playerData == null)
|
||||
return ChatUtil.translateAlternateColorCodes('&', message);
|
||||
if (isSelf) {
|
||||
playerData = PlayerDataManager.getPlayerData(senderUUID);
|
||||
if (playerData == null) {
|
||||
return ChatUtil.translateAlternateColorCodes('&', knockbacksyncDisabledForYouMessage);
|
||||
}
|
||||
} else {
|
||||
playerData = PlayerDataManager.getPlayerData(targetUUID);
|
||||
if (playerData == null) {
|
||||
return ChatUtil.translateAlternateColorCodes('&', knockbacksyncDisabledForTargetMessage);
|
||||
}
|
||||
}
|
||||
|
||||
String rawReturnString;
|
||||
if (playerData.getPing() == null) {
|
||||
|
||||
+1
-1
@@ -14,7 +14,7 @@ import java.util.function.Predicate;
|
||||
|
||||
public class ReloadCommand implements BuilderCommand {
|
||||
|
||||
private static final ConfigManager configManager = Base.INSTANCE.getConfigManager();
|
||||
private final ConfigManager configManager = Base.INSTANCE.getConfigManager();
|
||||
private String rawReloadMessage = configManager.getConfigWrapper().getString("messages.reload.success", "&aSuccessfully reloaded KnockbackSync.");
|
||||
|
||||
public void register(CommandManager<Sender> manager) {
|
||||
|
||||
+4
-9
@@ -14,6 +14,7 @@ import me.caseload.knockbacksync.util.ChatUtil;
|
||||
import org.incendo.cloud.CommandManager;
|
||||
import org.incendo.cloud.permission.PredicatePermission;
|
||||
|
||||
import java.util.UUID;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
public class StatusCommand implements BuilderCommand {
|
||||
@@ -59,7 +60,7 @@ public class StatusCommand implements BuilderCommand {
|
||||
(globalStatus ? globalStatusEnabledMessage : globalStatusDisabledMessage))
|
||||
+ "\n"
|
||||
+ ChatUtil.translateAlternateColorCodes('&',
|
||||
ToggleOffGroundSubcommand.offGroundSyncEnabled ? globalOffGroundStatusEnabledMessage : globalOffGroundStatusDisabledMessage)
|
||||
globalStatus ? globalOffGroundStatusEnabledMessage : globalOffGroundStatusDisabledMessage)
|
||||
);
|
||||
|
||||
if (sender.hasPermission(STATUS_SELF_PERMISSION, true)) {
|
||||
@@ -84,15 +85,9 @@ public class StatusCommand implements BuilderCommand {
|
||||
}
|
||||
|
||||
private void showPlayerStatus(Sender sender, PlatformPlayer target) {
|
||||
if (target.getUser() == null) {
|
||||
String message = ChatUtil.translateAlternateColorCodes('&',
|
||||
configManager.getPlayerDisconnectedWhileExecutingCommand()
|
||||
).replace("%player%", target.getName());
|
||||
sender.sendMessage(message);
|
||||
}
|
||||
|
||||
boolean globalStatus = configManager.isToggled();
|
||||
boolean playerStatus = PlayerDataManager.containsPlayerData(target.getUser());
|
||||
UUID uuid = target.getUUID();
|
||||
boolean playerStatus = PlayerDataManager.containsPlayerData(uuid);
|
||||
|
||||
String statusMessage;
|
||||
if (!globalStatus) {
|
||||
|
||||
+15
-24
@@ -1,20 +1,20 @@
|
||||
package me.caseload.knockbacksync.command.subcommand;
|
||||
import com.github.retrooper.packetevents.protocol.player.User;
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.ConfigWrapper;
|
||||
import me.caseload.knockbacksync.command.generic.BuilderCommand;
|
||||
import me.caseload.knockbacksync.command.generic.PlayerSelector;
|
||||
import me.caseload.knockbacksync.event.events.ToggleOnOffEvent;
|
||||
import me.caseload.knockbacksync.manager.CombatManager;
|
||||
import me.caseload.knockbacksync.manager.ConfigManager;
|
||||
import me.caseload.knockbacksync.manager.PlayerDataManager;
|
||||
import me.caseload.knockbacksync.permission.PermissionChecker;
|
||||
import me.caseload.knockbacksync.player.PlatformPlayer;
|
||||
import me.caseload.knockbacksync.player.PlayerData;
|
||||
import me.caseload.knockbacksync.sender.Sender;
|
||||
import me.caseload.knockbacksync.util.ChatUtil;
|
||||
import org.incendo.cloud.CommandManager;
|
||||
import org.incendo.cloud.permission.PredicatePermission;
|
||||
|
||||
import java.util.UUID;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
public class ToggleCommand implements BuilderCommand {
|
||||
@@ -67,7 +67,7 @@ public class ToggleCommand implements BuilderCommand {
|
||||
if (targetSelector == null) {
|
||||
// Global toggle
|
||||
if (permissionChecker.hasPermission(sender, TOGGLE_GLOBAL_PERMISSION, false)) {
|
||||
toggleGlobalKnockback(sender);
|
||||
toggleGlobalKnockback(configManager, sender);
|
||||
} else {
|
||||
sender.sendMessage(ChatUtil.translateAlternateColorCodes('&', noGlobalPermissionMessage));
|
||||
}
|
||||
@@ -85,7 +85,7 @@ public class ToggleCommand implements BuilderCommand {
|
||||
if (!configManager.isToggled()) {
|
||||
sender.sendMessage(ChatUtil.translateAlternateColorCodes('&', serverDisabledMessage));
|
||||
} else {
|
||||
togglePlayerKnockback(target, sender);
|
||||
togglePlayerKnockback(target, configManager, sender);
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -93,7 +93,7 @@ public class ToggleCommand implements BuilderCommand {
|
||||
}
|
||||
|
||||
|
||||
private static void toggleGlobalKnockback(Sender sender) {
|
||||
private static void toggleGlobalKnockback(ConfigManager configManager, Sender sender) {
|
||||
boolean toggledState = !configManager.isToggled();
|
||||
ToggleOnOffEvent toggleOnOffEvent = new ToggleOnOffEvent(toggledState);
|
||||
toggleOnOffEvent.post();
|
||||
@@ -103,8 +103,8 @@ public class ToggleCommand implements BuilderCommand {
|
||||
toggledState = toggleOnOffEvent.getStatus();
|
||||
configManager.setToggled(toggledState);
|
||||
|
||||
configManager.getConfigWrapper().set("enabled", toggledState);
|
||||
configManager.saveConfig();
|
||||
Base.INSTANCE.getConfigManager().getConfigWrapper().set("enabled", toggledState);
|
||||
Base.INSTANCE.getConfigManager().saveConfig();
|
||||
|
||||
String message = ChatUtil.translateAlternateColorCodes('&',
|
||||
toggledState ? configManager.getEnableMessage() : configManager.getDisableMessage()
|
||||
@@ -112,16 +112,10 @@ public class ToggleCommand implements BuilderCommand {
|
||||
sender.sendMessage(ChatUtil.translateAlternateColorCodes('&', message));
|
||||
}
|
||||
|
||||
private static void togglePlayerKnockback(PlatformPlayer target, Sender sender) {
|
||||
User user = target.getUser();
|
||||
if (user == null) {
|
||||
String message = ChatUtil.translateAlternateColorCodes('&',
|
||||
configManager.getPlayerDisconnectedWhileExecutingCommand()
|
||||
).replace("%player%", target.getName());
|
||||
sender.sendMessage(message);
|
||||
}
|
||||
private static void togglePlayerKnockback(PlatformPlayer target, ConfigManager configManager, Sender sender) {
|
||||
UUID uuid = target.getUUID();
|
||||
|
||||
if (PlayerDataManager.shouldExempt(target.getUUID())) {
|
||||
if (PlayerDataManager.shouldExempt(uuid)) {
|
||||
String message = ChatUtil.translateAlternateColorCodes('&',
|
||||
configManager.getPlayerIneligibleMessage()
|
||||
).replace("%player%", target.getName());
|
||||
@@ -130,14 +124,11 @@ public class ToggleCommand implements BuilderCommand {
|
||||
return;
|
||||
}
|
||||
|
||||
boolean hasPlayerData = PlayerDataManager.containsPlayerData(user);
|
||||
if (hasPlayerData) {
|
||||
if (CombatManager.getPlayers().contains(user)) {
|
||||
CombatManager.removePlayer(user);
|
||||
}
|
||||
PlayerDataManager.removePlayerData(user);
|
||||
} else {
|
||||
PlayerDataManager.addPlayerData(user, target);
|
||||
boolean hasPlayerData = PlayerDataManager.containsPlayerData(uuid);
|
||||
if (hasPlayerData)
|
||||
PlayerDataManager.removePlayerData(uuid);
|
||||
else {
|
||||
PlayerDataManager.addPlayerData(uuid, new PlayerData(Base.INSTANCE.getPlatformServer().getPlayer(uuid)));
|
||||
}
|
||||
|
||||
String message = ChatUtil.translateAlternateColorCodes('&',
|
||||
|
||||
+2
-2
@@ -52,10 +52,10 @@ public class ToggleOffGroundSubcommand implements BuilderCommand {
|
||||
|
||||
private void loadConfigSettings() {
|
||||
ConfigWrapper configWrapper = Base.INSTANCE.getConfigManager().getConfigWrapper();
|
||||
offGroundSyncEnabled = configWrapper.getBoolean("enable_offground_synchronization", true);
|
||||
offGroundSyncEnabled = configWrapper.getBoolean("settings.offground.enabled", true);
|
||||
this.offGroundSyncEnableMessage = configWrapper.getString("messages.offground.enable",
|
||||
"&aSuccessfully enabled offground synchronization.");
|
||||
this.offGroundSyncDisableMessage = configWrapper.getString("messages.offground.disable",
|
||||
"&cSuccessfully disabled offground synchronization.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,12 +8,9 @@ import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
public class OptimizedEventBus implements EventBus {
|
||||
// ordinarily this would just be a hashmap since we don't modify it on different threads, but Folia forces us to make it concurrent
|
||||
private final Map<Class<? extends Event>, List<OptimizedListener>> listenerMap = new ConcurrentHashMap<>();
|
||||
private final Map<Class<? extends Event>, List<OptimizedListener>> listenerMap = new HashMap<>();
|
||||
private final MethodHandles.Lookup lookup = MethodHandles.lookup();
|
||||
|
||||
@Override
|
||||
@@ -40,8 +37,7 @@ public class OptimizedEventBus implements EventBus {
|
||||
|
||||
MethodHandle handle = lookup.unreflect(method);
|
||||
OptimizedListener optimizedListener = new OptimizedListener(instance, handle, annotation.priority(), method.getDeclaringClass());
|
||||
// Yes the CopyOnWriteArrayList is slow, yes we need to for thread safety on Folia, we'll replace when performance problems actually crop up
|
||||
listenerMap.computeIfAbsent((Class<? extends Event>) eventType, k -> new CopyOnWriteArrayList<>()).add(optimizedListener);
|
||||
listenerMap.computeIfAbsent((Class<? extends Event>) eventType, k -> new ArrayList<>()).add(optimizedListener);
|
||||
} catch (IllegalAccessException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
@@ -1,47 +1,24 @@
|
||||
package me.caseload.knockbacksync.listener;
|
||||
|
||||
import com.github.retrooper.packetevents.protocol.player.User;
|
||||
import com.github.retrooper.packetevents.util.Vector3d;
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.manager.ConfigManager;
|
||||
import me.caseload.knockbacksync.manager.PlayerDataManager;
|
||||
import me.caseload.knockbacksync.player.PlatformPlayer;
|
||||
import me.caseload.knockbacksync.player.PlayerData;
|
||||
import me.caseload.knockbacksync.util.LegacyKnockback;
|
||||
|
||||
public abstract class PlayerDamageListener {
|
||||
public void onPlayerDamage(PlatformPlayer victim, PlatformPlayer attacker) {
|
||||
ConfigManager config = Base.INSTANCE.getConfigManager();
|
||||
if (!config.isToggled())
|
||||
if (!Base.INSTANCE.getConfigManager().isToggled())
|
||||
return;
|
||||
|
||||
User user = victim.getUser();
|
||||
if (user == null) return; // Prevent errors with players disconnecting while this is running (or with fake player?)
|
||||
|
||||
PlayerData playerData = PlayerDataManager.getPlayerData(user);
|
||||
PlayerData playerData = PlayerDataManager.getPlayerData(victim.getUUID());
|
||||
if (playerData == null)
|
||||
return;
|
||||
|
||||
if (config.isLegacyKnockbackEnabled()) {
|
||||
if (playerData.isRodKnockbackPending()) {
|
||||
// A fishing-rod (bobber-direction) knockback was already supplied for this hit via
|
||||
// the rod API. Keep it instead of overwriting with the melee formula; the velocity
|
||||
// event still owns + latency-syncs it. Its vertical was set by the API call.
|
||||
} else {
|
||||
// KnockbackSync owns the full 1.8 melee velocity. Compute it now (we have the
|
||||
// attacker here) and store it for the PlayerVelocityEvent to apply + sync.
|
||||
Vector3d legacy = LegacyKnockback.compute(victim, attacker, playerData, config);
|
||||
playerData.setLegacyKnockback(legacy);
|
||||
// On-ground sync should target the legacy vertical value, not the 1.9 one.
|
||||
playerData.setVerticalVelocity(legacy.getY());
|
||||
}
|
||||
} else {
|
||||
playerData.setVerticalVelocity(playerData.calculateVerticalVelocity(attacker)); // do not move this calculation
|
||||
}
|
||||
playerData.setVerticalVelocity(playerData.calculateVerticalVelocity(attacker)); // do not move this calculation
|
||||
playerData.setLastDamageTicks(victim.getNoDamageTicks());
|
||||
playerData.updateCombat();
|
||||
|
||||
if (!Base.INSTANCE.getConfigManager().isRunnableEnabled())
|
||||
playerData.sendPing(true);
|
||||
playerData.sendPing(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package me.caseload.knockbacksync.listener;
|
||||
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.manager.PlayerDataManager;
|
||||
import me.caseload.knockbacksync.player.PlatformPlayer;
|
||||
import me.caseload.knockbacksync.player.PlayerData;
|
||||
import me.caseload.knockbacksync.util.ChatUtil;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public abstract class PlayerJoinQuitListener {
|
||||
public void onPlayerJoin(PlayerData player) {
|
||||
PlayerDataManager.addPlayerData(player.getUuid(), player);
|
||||
PlatformPlayer platformPlayer = player.getPlatformPlayer();
|
||||
|
||||
if (Base.INSTANCE.getConfigManager().isUpdateAvailable() && Base.INSTANCE.getConfigManager().isNotifyUpdate() && Base.INSTANCE.getPermissionChecker().hasPermission(platformPlayer, "knockbacksync.update"))
|
||||
platformPlayer.sendMessage(ChatUtil.translateAlternateColorCodes(
|
||||
'&',
|
||||
"&6An updated version of &eKnockbackSync &6is now available for download at: &bhttps://github.com/CASELOAD7000/knockback-sync/releases/latest"
|
||||
));
|
||||
}
|
||||
|
||||
public void onPlayerQuit(UUID uuid) {
|
||||
PlayerData playerData = PlayerDataManager.getPlayerData(uuid);
|
||||
if (playerData == null)
|
||||
return;
|
||||
|
||||
if (playerData.isInCombat())
|
||||
playerData.quitCombat();
|
||||
|
||||
PlayerDataManager.removePlayerData(uuid);
|
||||
}
|
||||
}
|
||||
+19
-49
@@ -1,60 +1,33 @@
|
||||
package me.caseload.knockbacksync.listener;
|
||||
|
||||
import com.github.retrooper.packetevents.protocol.player.User;
|
||||
import com.github.retrooper.packetevents.protocol.world.states.WrappedBlockState;
|
||||
import com.github.retrooper.packetevents.protocol.world.states.type.StateTypes;
|
||||
import com.github.retrooper.packetevents.util.Vector3d;
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.manager.ConfigManager;
|
||||
import me.caseload.knockbacksync.manager.PlayerDataManager;
|
||||
import me.caseload.knockbacksync.player.PlatformPlayer;
|
||||
import me.caseload.knockbacksync.player.PlayerData;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public abstract class PlayerKnockbackListener {
|
||||
|
||||
/**
|
||||
* Computes the melee velocity to apply to the victim.
|
||||
*
|
||||
* <p>The returned value, when non-null, MUST be written back by the platform layer.
|
||||
* Bukkit writes it to the {@code PlayerVelocityEvent} (so KnockbackSync is the last,
|
||||
* authoritative writer in the event chain rather than reading/writing the player's
|
||||
* live velocity out-of-band — see issue #7).</p>
|
||||
*
|
||||
* <p>When legacy (1.8) knockback is enabled, the 1.8 vector computed at damage time
|
||||
* replaces vanilla X/Z/Y, and latency Y-correction is applied on top of it. In that
|
||||
* mode this method always returns a velocity (the raw 1.8 vector when no correction
|
||||
* applies), so KnockbackSync owns the final melee velocity.</p>
|
||||
*
|
||||
* @return the velocity to apply, or {@code null} to leave the velocity unchanged.
|
||||
*/
|
||||
@Nullable
|
||||
public Vector3d onPlayerVelocity(PlatformPlayer victim, Vector3d velocity) {
|
||||
ConfigManager config = Base.INSTANCE.getConfigManager();
|
||||
if (!config.isToggled())
|
||||
return null;
|
||||
public void onPlayerVelocity(PlatformPlayer victim, Vector3d velocity) {
|
||||
if (!Base.INSTANCE.getConfigManager().isToggled())
|
||||
return;
|
||||
|
||||
User user = victim.getUser();
|
||||
if (user == null) return null; // Prevent errors with players disconnecting while this is running (or with fake player?)
|
||||
|
||||
PlayerData victimPlayerData = PlayerDataManager.getPlayerData(user);
|
||||
PlayerData victimPlayerData = PlayerDataManager.getPlayerData(victim.getUUID());
|
||||
if (victimPlayerData == null)
|
||||
return null;
|
||||
return;
|
||||
|
||||
// Legacy 1.8 knockback: KnockbackSync owns the melee velocity. The 1.8 vector
|
||||
// (computed at damage time) replaces vanilla X/Z/Y. We still apply latency
|
||||
// Y-correction on top when conditions allow; otherwise the raw 1.8 vector is
|
||||
// applied. legacyKb == null means either legacy is off or none is pending, in
|
||||
// which case behaviour falls back to the original (Y-sync of the event velocity).
|
||||
Vector3d legacyKb = config.isLegacyKnockbackEnabled() ? victimPlayerData.consumeLegacyKnockback() : null;
|
||||
Vector3d base = (legacyKb != null) ? legacyKb : velocity;
|
||||
/* Integer damageTicks = playerData.getLastDamageTicks();
|
||||
if (damageTicks != null && damageTicks > 8)
|
||||
return;*/
|
||||
|
||||
if (victimPlayerData.getNotNullPing() < PlayerData.PING_OFFSET)
|
||||
return legacyKb;
|
||||
return;
|
||||
|
||||
double distanceToGround = victimPlayerData.getDistanceToGround();
|
||||
if (distanceToGround <= 0)
|
||||
return legacyKb; // minecraft already does the work for us
|
||||
return; // minecraft already does the work for us
|
||||
|
||||
WrappedBlockState blockState = victim.getWorld().getBlockStateAt(victim.getLocation());
|
||||
if (victim.isGliding() ||
|
||||
@@ -62,21 +35,18 @@ public abstract class PlayerKnockbackListener {
|
||||
blockState.getType() == StateTypes.LAVA ||
|
||||
blockState.getType() == StateTypes.COBWEB ||
|
||||
blockState.getType() == StateTypes.SCAFFOLDING)
|
||||
return legacyKb;
|
||||
return;
|
||||
|
||||
Vector3d adjustedVelocity;
|
||||
if (victimPlayerData.isOnGroundClientSide(base.getY(), distanceToGround)) {
|
||||
Integer damageTicks = victimPlayerData.getLastDamageTicks();
|
||||
if (damageTicks != null && damageTicks > 8)
|
||||
return legacyKb;
|
||||
|
||||
adjustedVelocity = base.withY(victimPlayerData.getVerticalVelocity()); // Should be impossible to produce a NPE in this context
|
||||
}
|
||||
if (victimPlayerData.isOnGroundClientSide(velocity.getY(), distanceToGround))
|
||||
adjustedVelocity = velocity.withY(victimPlayerData.getVerticalVelocity()); // Should be impossible to produce a NPE in this context
|
||||
// Todo FIX
|
||||
// This can be spoofed! Clients can just say they're onGround to take less KB!
|
||||
else if (victimPlayerData.isOffGroundSyncEnabled())
|
||||
adjustedVelocity = base.withY(victimPlayerData.getCompensatedOffGroundVelocity());
|
||||
adjustedVelocity = velocity.withY(victimPlayerData.getCompensatedOffGroundVelocity());
|
||||
else
|
||||
return legacyKb;
|
||||
return;
|
||||
|
||||
return adjustedVelocity;
|
||||
victim.setVelocity(adjustedVelocity);
|
||||
}
|
||||
}
|
||||
}
|
||||
+9
-9
@@ -5,7 +5,6 @@ import com.github.retrooper.packetevents.event.PacketSendEvent;
|
||||
import com.github.retrooper.packetevents.protocol.attribute.Attributes;
|
||||
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
|
||||
import com.github.retrooper.packetevents.protocol.player.ClientVersion;
|
||||
import com.github.retrooper.packetevents.protocol.player.User;
|
||||
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerUpdateAttributes;
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.manager.PlayerDataManager;
|
||||
@@ -37,16 +36,17 @@ public class AttributeChangeListener extends PacketListenerAbstract {
|
||||
|
||||
WrapperPlayServerUpdateAttributes packet = new WrapperPlayServerUpdateAttributes(event);
|
||||
|
||||
User user = event.getUser();
|
||||
if (!PlayerDataManager.containsPlayerData(user)) return;
|
||||
UUID uuid = event.getUser().getUUID();
|
||||
if (!PlayerDataManager.containsPlayerData(uuid))
|
||||
return;
|
||||
|
||||
// Get the attributes from the packet
|
||||
for (WrapperPlayServerUpdateAttributes.Property property : packet.getProperties()) {
|
||||
// You can now check for specific attributes
|
||||
if (property.getAttribute().equals(Attributes.GENERIC_GRAVITY)) {
|
||||
onPlayerGravityChange(user, calculateValueWithModifiers(property));
|
||||
onPlayerGravityChange(uuid, calculateValueWithModifiers(property));
|
||||
} else if (property.getAttribute().equals(Attributes.GENERIC_KNOCKBACK_RESISTANCE)) {
|
||||
onPlayerKnockBackChange(user, calculateValueWithModifiers(property));
|
||||
onPlayerKnockBackChange(uuid, calculateValueWithModifiers(property));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -87,8 +87,8 @@ public class AttributeChangeListener extends PacketListenerAbstract {
|
||||
|
||||
// Yes this is not properly latency compensated, that would require including a proper simulation engine
|
||||
// Laggy players will just have to deal with being on the wrong gravity for a few hundred ms, too bad!
|
||||
public void onPlayerGravityChange(User user, double newGravity) {
|
||||
PlayerData playerData = PlayerDataManager.getPlayerData(user);
|
||||
public void onPlayerGravityChange(UUID uuid, double newGravity) {
|
||||
PlayerData playerData = PlayerDataManager.getPlayerData(uuid);
|
||||
if (playerData.getClientVersion().isNewerThanOrEquals(ClientVersion.V_1_20_5)) {
|
||||
playerData.setGravityAttribute(newGravity);
|
||||
} else {
|
||||
@@ -96,8 +96,8 @@ public class AttributeChangeListener extends PacketListenerAbstract {
|
||||
}
|
||||
}
|
||||
|
||||
private void onPlayerKnockBackChange(User user, double newKnockbackResistance) {
|
||||
PlayerData playerData = PlayerDataManager.getPlayerData(user);
|
||||
private void onPlayerKnockBackChange(UUID uuid, double newKnockbackResistance) {
|
||||
PlayerData playerData = PlayerDataManager.getPlayerData(uuid);
|
||||
playerData.setKnockbackResistanceAttribute(newKnockbackResistance);
|
||||
}
|
||||
}
|
||||
+1
-5
@@ -5,8 +5,6 @@ import com.github.retrooper.packetevents.event.PacketReceiveEvent;
|
||||
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
|
||||
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientPluginMessage;
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.manager.PlayerDataManager;
|
||||
import me.caseload.knockbacksync.player.PlayerData;
|
||||
|
||||
public class ClientBrandListener extends PacketListenerAbstract {
|
||||
String brand = "vanilla";
|
||||
@@ -18,9 +16,7 @@ public class ClientBrandListener extends PacketListenerAbstract {
|
||||
WrapperPlayClientPluginMessage packet = new WrapperPlayClientPluginMessage(event);
|
||||
String channelName = packet.getChannelName();
|
||||
handle(channelName, packet.getData());
|
||||
PlayerData playerData = PlayerDataManager.getPlayerData(event.getUser());
|
||||
if (playerData == null) return;
|
||||
playerData.getPlatformPlayer().setClientBrand(brand);
|
||||
Base.INSTANCE.getPlatformServer().getPlayer(event.getUser().getUUID()).setClientBrand(brand);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
-51
@@ -1,51 +0,0 @@
|
||||
package me.caseload.knockbacksync.listener.packetevents;
|
||||
|
||||
import com.github.retrooper.packetevents.event.PacketListenerAbstract;
|
||||
import com.github.retrooper.packetevents.event.UserDisconnectEvent;
|
||||
import com.github.retrooper.packetevents.event.UserLoginEvent;
|
||||
import com.github.retrooper.packetevents.protocol.player.User;
|
||||
import com.google.common.base.Preconditions;
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.manager.PlayerDataManager;
|
||||
import me.caseload.knockbacksync.player.PlatformPlayer;
|
||||
import me.caseload.knockbacksync.player.PlayerData;
|
||||
import me.caseload.knockbacksync.util.ChatUtil;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public class PacketPlayerJoinQuit extends PacketListenerAbstract {
|
||||
@Override
|
||||
public void onUserLogin(UserLoginEvent event) {
|
||||
Object nativePlayerObject = event.getPlayer();
|
||||
Preconditions.checkArgument(nativePlayerObject != null);
|
||||
|
||||
@NotNull PlatformPlayer platformPlayer = Base.INSTANCE.getPlatformServer().getPlayer(nativePlayerObject);
|
||||
onPlayerJoin(event.getUser(), platformPlayer);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onUserDisconnect(UserDisconnectEvent event) {
|
||||
onPlayerQuit(event.getUser());
|
||||
}
|
||||
|
||||
public void onPlayerJoin(User user, PlatformPlayer player) {
|
||||
PlayerDataManager.addPlayerData(user, player);
|
||||
|
||||
if (Base.INSTANCE.getConfigManager().isUpdateAvailable() && Base.INSTANCE.getConfigManager().isNotifyUpdate() && Base.INSTANCE.getPermissionChecker().hasPermission(player, "knockbacksync.update"))
|
||||
player.sendMessage(ChatUtil.translateAlternateColorCodes(
|
||||
'&',
|
||||
"&6An updated version of &eKnockbackSync &6is now available for download at: &bhttps://github.com/CASELOAD7000/knockback-sync/releases/latest"
|
||||
));
|
||||
}
|
||||
|
||||
public void onPlayerQuit(@NotNull User user) {
|
||||
PlayerData playerData = PlayerDataManager.getPlayerData(user);
|
||||
if (playerData == null)
|
||||
return;
|
||||
|
||||
playerData.quitCombat(true);
|
||||
PlayerDataManager.removePlayerData(user);
|
||||
}
|
||||
}
|
||||
+67
-56
@@ -1,25 +1,55 @@
|
||||
package me.caseload.knockbacksync.listener.packetevents;
|
||||
|
||||
import com.github.retrooper.packetevents.event.*;
|
||||
import com.github.retrooper.packetevents.event.PacketListenerAbstract;
|
||||
import com.github.retrooper.packetevents.event.PacketReceiveEvent;
|
||||
import com.github.retrooper.packetevents.event.PacketSendEvent;
|
||||
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
|
||||
import com.github.retrooper.packetevents.protocol.packettype.PacketTypeCommon;
|
||||
import com.github.retrooper.packetevents.protocol.player.User;
|
||||
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientKeepAlive;
|
||||
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientPong;
|
||||
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientWindowConfirmation;
|
||||
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerKeepAlive;
|
||||
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPing;
|
||||
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerWindowConfirmation;
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.manager.PlayerDataManager;
|
||||
import me.caseload.knockbacksync.player.PingStrategy;
|
||||
import me.caseload.knockbacksync.player.PlayerData;
|
||||
import me.caseload.knockbacksync.util.data.Pair;
|
||||
|
||||
import java.util.Queue;
|
||||
import java.util.UUID;
|
||||
import java.util.List;
|
||||
|
||||
public class PingReceiveListener extends PacketListenerAbstract {
|
||||
|
||||
public PingReceiveListener() {
|
||||
super(PacketListenerPriority.LOWEST);
|
||||
@Override
|
||||
public void onPacketSend(PacketSendEvent event) {
|
||||
if (!Base.INSTANCE.getConfigManager().isToggled()) return;
|
||||
|
||||
PacketTypeCommon packetType = event.getPacketType();
|
||||
if (packetType.equals(PacketType.Play.Server.KEEP_ALIVE)) {
|
||||
WrapperPlayServerKeepAlive keepAlive = new WrapperPlayServerKeepAlive(event);
|
||||
long id = keepAlive.getId();
|
||||
|
||||
PlayerData playerData = PlayerDataManager.getPlayerData(event.getUser().getUUID());
|
||||
if (playerData == null) return;
|
||||
|
||||
playerData.keepaliveMap.add(new Pair<>(id, System.nanoTime()));
|
||||
} else if (packetType.equals(PacketType.Play.Server.PING)) {
|
||||
WrapperPlayServerPing ping = new WrapperPlayServerPing(event);
|
||||
int id = ping.getId();
|
||||
|
||||
PlayerData playerData = PlayerDataManager.getPlayerData(event.getUser().getUUID());
|
||||
if (playerData == null) return;
|
||||
|
||||
playerData.transactionsSent.add(new Pair<>(id, System.nanoTime()));
|
||||
} else if (packetType.equals(PacketType.Play.Server.WINDOW_CONFIRMATION)) {
|
||||
WrapperPlayServerWindowConfirmation confirmation = new WrapperPlayServerWindowConfirmation(event);
|
||||
int id = confirmation.getActionId();
|
||||
|
||||
PlayerData playerData = PlayerDataManager.getPlayerData(event.getUser().getUUID());
|
||||
if (playerData == null) return;
|
||||
|
||||
playerData.transactionsSent.add(new Pair<>(id, System.nanoTime()));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -28,74 +58,55 @@ public class PingReceiveListener extends PacketListenerAbstract {
|
||||
// And then receive a response we have to ensure that if the packet was sent by us we cancel it
|
||||
// otherwise the server will likely kick the player
|
||||
PacketTypeCommon packetType = event.getPacketType();
|
||||
User user = event.getUser();
|
||||
if (user == null) return;
|
||||
PlayerData playerData = PlayerDataManager.getPlayerData(user);
|
||||
if (playerData == null) return;
|
||||
|
||||
// Cancel echoes of injected packets before any strategy check: on 1.20.2+ an unexpected keepalive is an instant "Timed out" kick, so a strategy switch mid-flight must not leak one.
|
||||
if (packetType == PacketType.Play.Client.KEEP_ALIVE) {
|
||||
|
||||
WrapperPlayClientKeepAlive keepAlive = new WrapperPlayClientKeepAlive(event);
|
||||
PlayerData playerData = PlayerDataManager.getPlayerData(event.getUser().getUUID());
|
||||
if (playerData == null) return;
|
||||
|
||||
long receivedId = keepAlive.getId();
|
||||
|
||||
if (playerData.didWeSendThatPacket(receivedId))
|
||||
event.setCancelled(true);
|
||||
|
||||
if (playerData.pingStrategy == PingStrategy.KEEPALIVE)
|
||||
handlePingCalculationPackets(playerData, receivedId, playerData.keepaliveMap);
|
||||
handlePingCalculationPackets(event, playerData, receivedId, playerData.keepaliveMap);
|
||||
} else if (packetType == PacketType.Play.Client.PONG) {
|
||||
WrapperPlayClientPong pong = new WrapperPlayClientPong(event);
|
||||
PlayerData playerData = PlayerDataManager.getPlayerData(event.getUser().getUUID());
|
||||
if (playerData == null) return;
|
||||
|
||||
int id = pong.getId();
|
||||
|
||||
if (playerData.didWeSendThatPacket(id))
|
||||
event.setCancelled(true);
|
||||
|
||||
if (playerData.pingStrategy == PingStrategy.TRANSACTION)
|
||||
handlePingCalculationPackets(playerData, id, playerData.transactionsSent);
|
||||
handlePingCalculationPackets(event, playerData, id, playerData.transactionsSent);
|
||||
} else if (packetType == PacketType.Play.Client.WINDOW_CONFIRMATION) {
|
||||
WrapperPlayClientWindowConfirmation windowConfirmation = new WrapperPlayClientWindowConfirmation(event);
|
||||
PlayerData playerData = PlayerDataManager.getPlayerData(event.getUser().getUUID());
|
||||
if (playerData == null) return;
|
||||
|
||||
int id = windowConfirmation.getActionId();
|
||||
|
||||
if (playerData.didWeSendThatPacket(id))
|
||||
event.setCancelled(true);
|
||||
|
||||
if (playerData.pingStrategy == PingStrategy.TRANSACTION)
|
||||
handlePingCalculationPackets(playerData, id, playerData.transactionsSent);
|
||||
handlePingCalculationPackets(event, playerData, id, playerData.transactionsSent);
|
||||
}
|
||||
}
|
||||
|
||||
private <T extends Number> void handlePingCalculationPackets(PlayerData playerData, long id, Queue<Pair<T, Long>> packetSentList) {
|
||||
// System.out.println("Received response ID: " + id + " Queue size before: " + packetSentList.size());
|
||||
// System.out.println("Current queue contents: " + packetSentList.toString());
|
||||
private <T extends Number> void handlePingCalculationPackets(PacketReceiveEvent event, PlayerData playerData, long id, List<Pair<T, Long>> packetSentList) {
|
||||
// We can cancel for all 3 cases
|
||||
if (playerData.didWeSendThatPacket(id)) {
|
||||
// Pong not needed as vanilla ignores the packet, its needed for packet limiters
|
||||
// We want to cancel Window Confirmations that we send, and ...
|
||||
// Minecraft kicks players that send invalid keepAliveID packets
|
||||
// Since Minecraft doesn't know we just sent a keepalive, we gotta cancel it
|
||||
// To stop MC from processing it and kicking the player
|
||||
event.setCancelled(true);
|
||||
}
|
||||
|
||||
if (!Base.INSTANCE.getConfigManager().isToggled()) return;
|
||||
|
||||
Pair<T, Long> data = null;
|
||||
int cleared = 0;
|
||||
// Keep polling until we find the matching ID
|
||||
do {
|
||||
data = packetSentList.poll();
|
||||
cleared++;
|
||||
long pingNanos = (System.nanoTime() - packetSentList.remove(0).getSecond());
|
||||
double diffMillisDouble = pingNanos / 1_000_000.0;
|
||||
|
||||
if (data == null) {
|
||||
// System.out.println("No data found in queue!");
|
||||
break;
|
||||
}
|
||||
playerData.setPreviousPing(playerData.getPing());
|
||||
playerData.setPing(diffMillisDouble);
|
||||
|
||||
// System.out.println("Cleared entry " + cleared + ": ID=" + data.getFirst() + " Time=" + data.getSecond());
|
||||
|
||||
long pingNanos = (System.nanoTime() - data.getSecond());
|
||||
double diffMillisDouble = pingNanos / 1_000_000.0;
|
||||
|
||||
playerData.setPreviousPing(playerData.getPing());
|
||||
playerData.setPing(diffMillisDouble);
|
||||
|
||||
playerData.getJitterCalculator().addPing(pingNanos);
|
||||
double jitter = playerData.getJitterCalculator().calculateJitter();
|
||||
playerData.setJitter(jitter);
|
||||
|
||||
} while (data.getFirst().longValue() != id);
|
||||
|
||||
// System.out.println("Finished processing - Cleared " + cleared + " entries. Queue size after: " + packetSentList.size());
|
||||
playerData.getJitterCalculator().addPing(pingNanos);
|
||||
double jitter = playerData.getJitterCalculator().calculateJitter();
|
||||
playerData.setJitter(jitter);
|
||||
}
|
||||
}
|
||||
-57
@@ -1,57 +0,0 @@
|
||||
package me.caseload.knockbacksync.listener.packetevents;
|
||||
|
||||
import com.github.retrooper.packetevents.event.*;
|
||||
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
|
||||
import com.github.retrooper.packetevents.protocol.packettype.PacketTypeCommon;
|
||||
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientKeepAlive;
|
||||
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientPong;
|
||||
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientWindowConfirmation;
|
||||
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerKeepAlive;
|
||||
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPing;
|
||||
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerWindowConfirmation;
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.manager.PlayerDataManager;
|
||||
import me.caseload.knockbacksync.player.PingStrategy;
|
||||
import me.caseload.knockbacksync.player.PlayerData;
|
||||
import me.caseload.knockbacksync.util.data.Pair;
|
||||
|
||||
import java.util.Queue;
|
||||
import java.util.UUID;
|
||||
|
||||
public class PingSendListener extends PacketListenerAbstract {
|
||||
|
||||
public PingSendListener() {
|
||||
// See all actually outgoing, not cancelled, ping packets
|
||||
super(PacketListenerPriority.MONITOR);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPacketSend(PacketSendEvent event) {
|
||||
if (!Base.INSTANCE.getConfigManager().isToggled()) return;
|
||||
if (event.isCancelled()) return;
|
||||
|
||||
PacketTypeCommon packetType = event.getPacketType();
|
||||
UUID playerUUID = event.getUser().getUUID();
|
||||
if (playerUUID == null) return;
|
||||
PlayerData playerData = PlayerDataManager.getPlayerData(event.getUser());
|
||||
if (playerData == null) return;
|
||||
|
||||
if (playerData.pingStrategy == PingStrategy.KEEPALIVE && packetType.equals(PacketType.Play.Server.KEEP_ALIVE)) {
|
||||
WrapperPlayServerKeepAlive keepAlive = new WrapperPlayServerKeepAlive(event);
|
||||
long id = keepAlive.getId();
|
||||
|
||||
// System.out.println("Adding ping to queue - ID: " + id + " Time: " + System.nanoTime() + " Queue size before: " + playerData.keepaliveMap.size());
|
||||
playerData.keepaliveMap.add(new Pair<>(id, System.nanoTime()));
|
||||
} else if (playerData.pingStrategy == PingStrategy.TRANSACTION && packetType.equals(PacketType.Play.Server.PING)) {
|
||||
WrapperPlayServerPing ping = new WrapperPlayServerPing(event);
|
||||
int id = ping.getId();
|
||||
|
||||
playerData.transactionsSent.add(new Pair<>(id, System.nanoTime()));
|
||||
} else if (playerData.pingStrategy == PingStrategy.TRANSACTION && packetType.equals(PacketType.Play.Server.WINDOW_CONFIRMATION)) {
|
||||
WrapperPlayServerWindowConfirmation confirmation = new WrapperPlayServerWindowConfirmation(event);
|
||||
int id = confirmation.getActionId();
|
||||
|
||||
playerData.transactionsSent.add(new Pair<>(id, System.nanoTime()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
package me.caseload.knockbacksync.manager;
|
||||
|
||||
import com.github.retrooper.packetevents.protocol.player.User;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.Set;
|
||||
@@ -9,17 +8,17 @@ import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public class CombatManager {
|
||||
|
||||
private static final Set<@NotNull User> combatPlayers = ConcurrentHashMap.newKeySet();
|
||||
private static final Set<UUID> combatPlayers = ConcurrentHashMap.newKeySet();
|
||||
|
||||
public static @NotNull Set<@NotNull User> getPlayers() {
|
||||
public static @NotNull Set<UUID> getPlayers() {
|
||||
return combatPlayers;
|
||||
}
|
||||
|
||||
public static void addPlayer(@NotNull User user) {
|
||||
combatPlayers.add(user);
|
||||
public static void addPlayer(UUID uuid) {
|
||||
combatPlayers.add(uuid);
|
||||
}
|
||||
|
||||
public static void removePlayer(@NotNull User user) {
|
||||
combatPlayers.remove(user);
|
||||
public static void removePlayer(UUID uuid) {
|
||||
combatPlayers.remove(uuid);
|
||||
}
|
||||
}
|
||||
@@ -19,23 +19,12 @@ import java.util.Map;
|
||||
@Setter
|
||||
public class ConfigManager {
|
||||
|
||||
public static final long CONFIG_VERSION = 9;
|
||||
public static final long CONFIG_VERSION = 6;
|
||||
|
||||
private boolean toggled;
|
||||
private boolean runnableEnabled;
|
||||
private boolean updateAvailable;
|
||||
private boolean notifyUpdate;
|
||||
private boolean autoUpdate;
|
||||
|
||||
// Legacy (1.8) knockback: makes KnockbackSync the single owner of melee velocity,
|
||||
// reproducing OldCombatMechanics' old-player-knockback values while still latency-syncing.
|
||||
private boolean legacyKnockbackEnabled;
|
||||
private double legacyKnockbackHorizontal;
|
||||
private double legacyKnockbackVertical;
|
||||
private double legacyKnockbackVerticalLimit;
|
||||
private double legacyKnockbackExtraHorizontal;
|
||||
private double legacyKnockbackExtraVertical;
|
||||
private boolean legacyKnockbackResistanceEnabled;
|
||||
|
||||
private long runnableInterval;
|
||||
private long combatTimer;
|
||||
@@ -46,7 +35,6 @@ public class ConfigManager {
|
||||
private String playerEnableMessage;
|
||||
private String playerDisableMessage;
|
||||
private String playerIneligibleMessage;
|
||||
private String playerDisconnectedWhileExecutingCommand;
|
||||
|
||||
private AbstractTaskHandle pingTask;
|
||||
|
||||
@@ -103,11 +91,11 @@ public class ConfigManager {
|
||||
|
||||
toggled = configWrapper.getBoolean("enabled", true);
|
||||
|
||||
// Checks to see if the runnable was enabled...
|
||||
// and if we now want to disable it
|
||||
boolean newRunnableEnabled = configWrapper.getBoolean("runnable.enabled", true);
|
||||
// Always stop the previous ping task on reload (reschedule below only if still enabled); gating the cancel on staying enabled leaked the task when disabling via reload.
|
||||
if (pingTask != null) { // null on first startup
|
||||
if (runnableEnabled && newRunnableEnabled && pingTask != null) { // null check for first startup
|
||||
pingTask.cancel();
|
||||
pingTask = null;
|
||||
}
|
||||
|
||||
runnableEnabled = newRunnableEnabled;
|
||||
@@ -124,24 +112,14 @@ public class ConfigManager {
|
||||
pingTask = Base.INSTANCE.getScheduler().runTaskTimerAsynchronously(new PingRunnable(), initialDelay, pingTaskRunnableInterval);
|
||||
}
|
||||
|
||||
legacyKnockbackEnabled = configWrapper.getBoolean("legacy_knockback.enabled", false);
|
||||
legacyKnockbackHorizontal = configWrapper.getDouble("legacy_knockback.horizontal", 0.4);
|
||||
legacyKnockbackVertical = configWrapper.getDouble("legacy_knockback.vertical", 0.4);
|
||||
legacyKnockbackVerticalLimit = configWrapper.getDouble("legacy_knockback.vertical_limit", 0.4);
|
||||
legacyKnockbackExtraHorizontal = configWrapper.getDouble("legacy_knockback.extra_horizontal", 0.5);
|
||||
legacyKnockbackExtraVertical = configWrapper.getDouble("legacy_knockback.extra_vertical", 0.1);
|
||||
legacyKnockbackResistanceEnabled = configWrapper.getBoolean("legacy_knockback.enable_knockback_resistance", false);
|
||||
|
||||
notifyUpdate = configWrapper.getBoolean("notify_updates", true);
|
||||
autoUpdate = configWrapper.getBoolean("auto_update", true);
|
||||
combatTimer = configWrapper.getLong("runnable.combat_timer", 30L);
|
||||
combatTimer = configWrapper.getLong("runnable.timer", 30L);
|
||||
spikeThreshold = configWrapper.getLong("spike_threshold", 20L);
|
||||
enableMessage = configWrapper.getString("messages.toggle.global.enable", "&aSuccessfully enabled KnockbackSync.");
|
||||
disableMessage = configWrapper.getString("messages.toggle.global.disable", "&cSuccessfully disabled KnockbackSync.");
|
||||
playerEnableMessage = configWrapper.getString("messages.toggle.player.enable", "&aSuccessfully enabled KnockbackSync for %player%.");
|
||||
playerDisableMessage = configWrapper.getString("messages.toggle.player.disable", "&aSuccessfully &cdisabled &aKnockbackSync for %player%.");
|
||||
playerIneligibleMessage = configWrapper.getString("messages.toggle.player.ineligible", "&c%player% is ineligible for KnockbackSync. If you believe this is in error, please contact your server administrators.");
|
||||
playerDisconnectedWhileExecutingCommand = configWrapper.getString("messages.toggle.player.disconnected-while-executing-command", "&c%player% disconnected while executing command.");
|
||||
}
|
||||
|
||||
public void updateConfig() {
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
package me.caseload.knockbacksync.manager;
|
||||
|
||||
import com.github.retrooper.packetevents.protocol.player.User;
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.player.PlatformPlayer;
|
||||
import me.caseload.knockbacksync.player.PlayerData;
|
||||
import me.caseload.knockbacksync.util.FloodgateUtil;
|
||||
import me.caseload.knockbacksync.util.GeyserUtil;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
@@ -15,28 +12,27 @@ import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public class PlayerDataManager {
|
||||
|
||||
private static final Map<User, PlayerData> playerDataMap = new ConcurrentHashMap<>();
|
||||
private static final Map<UUID, PlayerData> playerDataMap = new ConcurrentHashMap<>();
|
||||
|
||||
public static @Nullable PlayerData getPlayerData(@NotNull User user) {
|
||||
return playerDataMap.get(user);
|
||||
public static PlayerData getPlayerData(@NotNull UUID uuid) {
|
||||
return playerDataMap.get(uuid);
|
||||
}
|
||||
|
||||
public static void addPlayerData(@NotNull User user, @NotNull PlatformPlayer platformPlayer) {
|
||||
if (!shouldExempt(platformPlayer.getUUID())) {
|
||||
PlayerData playerData = new PlayerData(user, platformPlayer);
|
||||
playerDataMap.put(user, playerData);
|
||||
public static void addPlayerData(@NotNull UUID uuid, @NotNull PlayerData playerData) {
|
||||
if (!shouldExempt(uuid)) {
|
||||
playerDataMap.put(uuid, playerData);
|
||||
Base.INSTANCE.getEventBus().registerListeners(playerData);
|
||||
}
|
||||
}
|
||||
|
||||
public static void removePlayerData(@NotNull User user) {
|
||||
PlayerData playerData = playerDataMap.remove(user);
|
||||
public static void removePlayerData(@NotNull UUID uuid) {
|
||||
PlayerData playerData = playerDataMap.remove(uuid);
|
||||
if (playerData != null)
|
||||
Base.INSTANCE.getEventBus().unregisterListeners(playerData);
|
||||
}
|
||||
|
||||
public static boolean containsPlayerData(@NotNull User user) {
|
||||
return playerDataMap.containsKey(user);
|
||||
public static boolean containsPlayerData(@NotNull UUID uuid) {
|
||||
return playerDataMap.containsKey(uuid);
|
||||
}
|
||||
|
||||
public static boolean shouldExempt(@NotNull UUID uuid) {
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
package me.caseload.knockbacksync.player;
|
||||
|
||||
public enum PingStrategy {
|
||||
KEEPALIVE,
|
||||
TRANSACTION
|
||||
}
|
||||
@@ -42,16 +42,6 @@ public interface PlatformPlayer {
|
||||
|
||||
int getMainHandKnockbackLevel();
|
||||
|
||||
/**
|
||||
* Knockback enchant level used for legacy (1.8) knockback bonus calculation.
|
||||
* Mirrors OldCombatMechanics: the main hand item, or the off hand item when the
|
||||
* main hand is empty. Defaults to the main hand level for platforms that do not
|
||||
* override it.
|
||||
*/
|
||||
default int getWeaponKnockbackLevel() {
|
||||
return getMainHandKnockbackLevel();
|
||||
}
|
||||
|
||||
@Nullable Integer getNoDamageTicks();
|
||||
|
||||
void setVelocity(Vector3d adjustedVelocity);
|
||||
@@ -62,12 +52,7 @@ public interface PlatformPlayer {
|
||||
|
||||
BoundingBox getBoundingBox();
|
||||
|
||||
/**
|
||||
* If a player disconnects while we are running the constructor of a PlatformPlayer
|
||||
* PacketEvents.getAPI().getPlayerManager().getUser(bukkitPlayer) may return null
|
||||
* This will make the internal field null and thus this function may return null.
|
||||
*/
|
||||
@Nullable User getUser();
|
||||
User getUser();
|
||||
|
||||
void setClientBrand(String brand);
|
||||
|
||||
|
||||
@@ -8,6 +8,8 @@ import com.github.retrooper.packetevents.protocol.ConnectionState;
|
||||
import com.github.retrooper.packetevents.protocol.player.ClientVersion;
|
||||
import com.github.retrooper.packetevents.protocol.player.User;
|
||||
import com.github.retrooper.packetevents.protocol.world.BoundingBox;
|
||||
import com.github.retrooper.packetevents.protocol.world.states.WrappedBlockState;
|
||||
import com.github.retrooper.packetevents.protocol.world.states.type.StateTypes;
|
||||
import com.github.retrooper.packetevents.util.Vector3d;
|
||||
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
|
||||
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerKeepAlive;
|
||||
@@ -21,9 +23,7 @@ import me.caseload.knockbacksync.event.KBSyncEventHandler;
|
||||
import me.caseload.knockbacksync.event.events.ConfigReloadEvent;
|
||||
import me.caseload.knockbacksync.event.events.ToggleOnOffEvent;
|
||||
import me.caseload.knockbacksync.manager.CombatManager;
|
||||
import me.caseload.knockbacksync.manager.ConfigManager;
|
||||
import me.caseload.knockbacksync.scheduler.AbstractTaskHandle;
|
||||
import me.caseload.knockbacksync.scheduler.NettyTaskHandle;
|
||||
import me.caseload.knockbacksync.util.MathUtil;
|
||||
import me.caseload.knockbacksync.util.data.Pair;
|
||||
import me.caseload.knockbacksync.world.PlatformWorld;
|
||||
@@ -33,10 +33,9 @@ import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import io.netty.channel.Channel;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Getter
|
||||
public class PlayerData {
|
||||
@@ -48,8 +47,11 @@ public class PlayerData {
|
||||
|
||||
private static Field playerField;
|
||||
|
||||
public final Queue<Pair<Integer, Long>> transactionsSent = new ConcurrentLinkedQueue<>();
|
||||
public final Queue<Pair<Long, Long>> keepaliveMap = new ConcurrentLinkedQueue<>();
|
||||
public final List<Pair<Integer, Long>> transactionsSent = new LinkedList<>();
|
||||
public final List<Pair<Long, Long>> keepaliveMap = new LinkedList<>();
|
||||
|
||||
private static Object grimPlayerDataManager = null;
|
||||
private static Method getGrimPlayerFromUserMethod = null;
|
||||
|
||||
static {
|
||||
try {
|
||||
@@ -66,10 +68,24 @@ public class PlayerData {
|
||||
default:
|
||||
throw new IllegalStateException("Unexpected platform: " + Base.INSTANCE.getPlatform());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
playerField.setAccessible(true);
|
||||
|
||||
// Step 1: Get the GrimAPI enum class dynamically
|
||||
Class<?> grimAPIClass = Class.forName("ac.grim.grimac.GrimAPI");
|
||||
|
||||
// Step 2: Access the INSTANCE of GrimAPI (it's a singleton enum)
|
||||
Object grimAPIInstance = Enum.valueOf((Class<? extends Enum>) grimAPIClass, "INSTANCE");
|
||||
|
||||
// Step 3: Get the PlayerDataManager instance
|
||||
Method getPlayerDataManagerMethod = grimAPIClass.getDeclaredMethod("getPlayerDataManager");
|
||||
grimPlayerDataManager = getPlayerDataManagerMethod.invoke(grimAPIInstance);
|
||||
|
||||
// Step 4: Get the getPlayer method from PlayerDataManager
|
||||
Class<?> playerDataManagerClass = grimPlayerDataManager.getClass();
|
||||
getGrimPlayerFromUserMethod = playerDataManagerClass.getDeclaredMethod("getPlayer", Class.forName("org.bukkit.entity.Player"));
|
||||
} catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException | NoSuchFieldException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
playerField.setAccessible(true); // May not be needed since it's already public
|
||||
}
|
||||
|
||||
public final User user;
|
||||
@@ -80,84 +96,31 @@ public class PlayerData {
|
||||
@Getter private final JitterCalculator jitterCalculator = new JitterCalculator();
|
||||
@Setter private double jitter;
|
||||
@Nullable private AbstractTaskHandle combatTask;
|
||||
@NotNull private final Object combatTaskLock = new Object(); // Lock object for synchronization
|
||||
@Nullable @Setter private Double ping, previousPing;
|
||||
@Nullable @Setter private Double verticalVelocity;
|
||||
@Nullable @Setter private Integer lastDamageTicks;
|
||||
// Legacy (1.8) knockback computed at damage time, consumed by the next PlayerVelocityEvent.
|
||||
// Guarded by a short expiry so a stale value never affects an unrelated velocity event.
|
||||
@Nullable private Vector3d legacyKnockback;
|
||||
private long legacyKnockbackExpiryNanos;
|
||||
// True when the pending legacyKnockback is a fishing-rod (bobber-direction) vector supplied
|
||||
// via the rod API rather than the melee formula. Lets the damage listener keep the rod vector
|
||||
// instead of overwriting it with melee, while still latency-syncing it. See api.KnockbackSyncRodApi.
|
||||
private boolean legacyKnockbackIsRod;
|
||||
@Setter private double gravityAttribute = 0.08;
|
||||
@Setter private double knockbackResistanceAttribute = 0.0;
|
||||
public PingStrategy pingStrategy; // this is currently shared between all instances, but can be made per-player later
|
||||
|
||||
public PlayerData(User user, PlatformPlayer platformPlayer) {
|
||||
public PlayerData(PlatformPlayer platformPlayer) {
|
||||
this.uuid = platformPlayer.getUUID();
|
||||
this.user = user;
|
||||
this.platformPlayer = platformPlayer;
|
||||
this.pingStrategy = loadPingStrategy(Base.INSTANCE.getConfigManager());
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores the legacy (1.8) knockback to apply on the next PlayerVelocityEvent.
|
||||
* Expires shortly after so it can never be applied to an unrelated velocity event
|
||||
* (explosions, other plugins, etc.) if the expected velocity event never fires.
|
||||
*/
|
||||
public void setLegacyKnockback(@Nullable Vector3d legacyKnockback) {
|
||||
this.legacyKnockback = legacyKnockback;
|
||||
this.legacyKnockbackIsRod = false;
|
||||
// 100ms window: damage and the resulting velocity event fire in the same tick.
|
||||
this.legacyKnockbackExpiryNanos = System.nanoTime() + 100_000_000L;
|
||||
}
|
||||
User tempUser = null;
|
||||
|
||||
/**
|
||||
* Stores a fishing-rod (bobber-direction) knockback to apply + latency-sync on the next
|
||||
* PlayerVelocityEvent, flagged so the damage listener keeps it instead of overwriting it with
|
||||
* the melee formula. Must be set immediately before the rod's damage tick. See
|
||||
* {@code api.KnockbackSyncRodApi}.
|
||||
*/
|
||||
public void setRodKnockback(@NotNull Vector3d rodKnockback) {
|
||||
this.legacyKnockback = rodKnockback;
|
||||
this.legacyKnockbackIsRod = true;
|
||||
this.legacyKnockbackExpiryNanos = System.nanoTime() + 100_000_000L;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return true if an unexpired fishing-rod knockback is pending (so the damage listener must
|
||||
* not overwrite it with melee knockback).
|
||||
*/
|
||||
public boolean isRodKnockbackPending() {
|
||||
return peekLegacyKnockback() != null && legacyKnockbackIsRod;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the pending legacy knockback if present and not expired, otherwise {@code null}.
|
||||
*/
|
||||
@Nullable
|
||||
public Vector3d peekLegacyKnockback() {
|
||||
if (legacyKnockback == null) return null;
|
||||
if (System.nanoTime() > legacyKnockbackExpiryNanos) {
|
||||
legacyKnockback = null;
|
||||
legacyKnockbackIsRod = false;
|
||||
return null;
|
||||
PlayerManager playerManager = PacketEvents.getAPI().getPlayerManager();
|
||||
Object player = null;
|
||||
try {
|
||||
player = playerField.get(platformPlayer);
|
||||
} catch (IllegalAccessException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
return legacyKnockback;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns and clears the pending legacy knockback (if present and not expired).
|
||||
*/
|
||||
@Nullable
|
||||
public Vector3d consumeLegacyKnockback() {
|
||||
Vector3d v = peekLegacyKnockback();
|
||||
legacyKnockback = null;
|
||||
legacyKnockbackIsRod = false;
|
||||
return v;
|
||||
if (player != null) {
|
||||
tempUser = playerManager.getUser(player);
|
||||
}
|
||||
|
||||
this.user = tempUser;
|
||||
}
|
||||
|
||||
public double getNotNullPing() {
|
||||
@@ -198,8 +161,9 @@ public class PlayerData {
|
||||
public void sendPing(boolean async) {
|
||||
if (user == null || user.getEncoderState() != ConnectionState.PLAY) return;
|
||||
|
||||
String pingStrategy = Base.INSTANCE.getConfigManager().getConfigWrapper().getString("ping_strategy", "KEEPALIVE");
|
||||
switch (pingStrategy) {
|
||||
case KEEPALIVE:
|
||||
case "KEEPALIVE":
|
||||
long keepAliveID = async ? NETTY_THREAD_TRANSACTION_ID : MAIN_THREAD_TRANSACTION_ID;
|
||||
if (async) {
|
||||
ChannelHelper.runInEventLoop(user.getChannel(), () -> {
|
||||
@@ -212,7 +176,8 @@ public class PlayerData {
|
||||
user.sendPacket(new WrapperPlayServerKeepAlive(keepAliveID));
|
||||
}
|
||||
break;
|
||||
case TRANSACTION:
|
||||
case "PING":
|
||||
case "TRANSACTION":
|
||||
PacketWrapper<?> packet;
|
||||
short pingTransactionID = async ? NETTY_THREAD_TRANSACTION_ID : MAIN_THREAD_TRANSACTION_ID;
|
||||
if (PacketEvents.getAPI().getServerManager().getVersion().isNewerThanOrEquals(ServerVersion.V_1_17)) {
|
||||
@@ -221,13 +186,12 @@ public class PlayerData {
|
||||
packet = new WrapperPlayServerWindowConfirmation((byte) 0, pingTransactionID, false);
|
||||
}
|
||||
|
||||
// sendPacket (write + flush) rather than writePacket: an unflushed write sits in the channel until the next flush and inflates the measured ping.
|
||||
if (async) {
|
||||
ChannelHelper.runInEventLoop(user.getChannel(), () -> {
|
||||
user.sendPacket(packet);
|
||||
user.writePacket(packet);
|
||||
});
|
||||
} else {
|
||||
user.sendPacket(packet);
|
||||
user.writePacket(packet);
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -250,17 +214,35 @@ public class PlayerData {
|
||||
* @return <code>true</code> if the Player is on the ground; <code>false</code> otherwise.
|
||||
*/
|
||||
public boolean isOnGroundClientSide(double verticalVelocity, double distanceToGround) {
|
||||
try {
|
||||
if (getGrimPlayerFromUserMethod != null) {
|
||||
// Step 5: Invoke getPlayer to get PlayerData
|
||||
Object playerData = getGrimPlayerFromUserMethod.invoke(grimPlayerDataManager, playerField.get(platformPlayer));
|
||||
|
||||
// Step 6: Access the 'onGround' field in PlayerData
|
||||
Field onGroundField = playerData.getClass().getDeclaredField("onGround");
|
||||
onGroundField.setAccessible(true); // Bypass private access
|
||||
|
||||
System.out.println(this.platformPlayer.getName() + " is located at " + platformPlayer.getX() + ", " + platformPlayer.getY() + ", " + platformPlayer.getZ() + " serverside");
|
||||
System.out.println("Grim onGround for player " + this.platformPlayer.getName() + " is " + onGroundField.get(playerData));
|
||||
|
||||
// Step 7: Get the value of the 'onGround' field
|
||||
return (boolean) onGroundField.get(playerData);
|
||||
}
|
||||
} catch (NoSuchFieldException | IllegalAccessException | InvocationTargetException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
int tMax = verticalVelocity > 0 ? MathUtil.calculateTimeToMaxVelocity(verticalVelocity, gravityAttribute) : 0;
|
||||
if (tMax == -1)
|
||||
return false; // reached the max tick limit, not safe to predict
|
||||
if (tMax == -1)
|
||||
return false; // reached the max tick limit, not safe to predict
|
||||
|
||||
double mH = verticalVelocity > 0 ? MathUtil.calculateDistanceTraveled(verticalVelocity, tMax, gravityAttribute) : 0;
|
||||
int tFall = MathUtil.calculateFallTime(verticalVelocity, mH + distanceToGround, gravityAttribute);
|
||||
double mH = verticalVelocity > 0 ? MathUtil.calculateDistanceTraveled(verticalVelocity, tMax, gravityAttribute) : 0;
|
||||
int tFall = MathUtil.calculateFallTime(verticalVelocity, mH + distanceToGround, gravityAttribute);
|
||||
|
||||
if (tFall == -1)
|
||||
return false; // reached the max tick limit, not safe to predict
|
||||
if (tFall == -1)
|
||||
return false; // reached the max tick limit, not safe to predict
|
||||
|
||||
return (tMax + tFall) - getCompensatedTicks() <= 0 && distanceToGround <= 1.3;
|
||||
return (tMax + tFall) - getCompensatedTicks() <= 0 && distanceToGround <= 1.3;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -347,41 +329,28 @@ public class PlayerData {
|
||||
return yAxis;
|
||||
}
|
||||
|
||||
public void updateCombat() {
|
||||
Channel channel = (Channel) user.getChannel();
|
||||
channel.eventLoop().execute(() -> {
|
||||
if (combatTask != null) {
|
||||
combatTask.cancel();
|
||||
}
|
||||
combatTask = newCombatTask(channel);
|
||||
CombatManager.addPlayer(user);
|
||||
});
|
||||
public boolean isInCombat() {
|
||||
return combatTask != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancels the combatTask quit task. This prevents quitCombat() from being called later against a new combat task
|
||||
* Or against a player that has disconnected already
|
||||
* @param async Whether we are already in the players netty thread
|
||||
*/
|
||||
public void quitCombat(boolean async) {
|
||||
Channel channel = (Channel) user.getChannel();
|
||||
Runnable runnable = () -> {
|
||||
if (combatTask != null) {
|
||||
combatTask.cancel();
|
||||
combatTask = null;
|
||||
}
|
||||
CombatManager.removePlayer(user);
|
||||
};
|
||||
if (async) {
|
||||
channel.eventLoop().execute(runnable);
|
||||
} else {
|
||||
runnable.run();
|
||||
}
|
||||
public void updateCombat() {
|
||||
if (isInCombat())
|
||||
combatTask.cancel();
|
||||
|
||||
combatTask = newCombatTask();
|
||||
CombatManager.addPlayer(uuid);
|
||||
}
|
||||
|
||||
public void quitCombat() {
|
||||
combatTask.cancel(); // should do nothing
|
||||
combatTask = null;
|
||||
CombatManager.removePlayer(uuid);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private AbstractTaskHandle newCombatTask(Channel channel) {
|
||||
return new NettyTaskHandle(channel.eventLoop().schedule(() -> quitCombat(false), convertTicksToMilliseconds(Base.INSTANCE.getConfigManager().getCombatTimer()), TimeUnit.MILLISECONDS));
|
||||
private AbstractTaskHandle newCombatTask() {
|
||||
return Base.INSTANCE.getScheduler().runTaskLaterAsynchronously(
|
||||
this::quitCombat, Base.INSTANCE.getConfigManager().getCombatTimer());
|
||||
}
|
||||
|
||||
public ClientVersion getClientVersion() {
|
||||
@@ -405,32 +374,9 @@ public class PlayerData {
|
||||
|
||||
@KBSyncEventHandler
|
||||
public void onToggledEvent(ToggleOnOffEvent event) {
|
||||
if (!event.getStatus()) {
|
||||
if (event.getStatus() == false) {
|
||||
transactionsSent.clear();
|
||||
keepaliveMap.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@KBSyncEventHandler
|
||||
public void onConfigReloadEvent(ConfigReloadEvent event) {
|
||||
this.pingStrategy = loadPingStrategy(event.getConfigManager());
|
||||
}
|
||||
|
||||
private PingStrategy loadPingStrategy(ConfigManager configManager) {
|
||||
// Default PING: vanilla ignores unintercepted pong echoes, while unintercepted keepalive echoes kick ("Timed out") on 1.20.2+.
|
||||
String pingStrategy = configManager.getConfigWrapper().getString("ping_strategy", "PING");
|
||||
switch (pingStrategy) {
|
||||
case "KEEPALIVE":
|
||||
return PingStrategy.KEEPALIVE;
|
||||
case "PING":
|
||||
case "TRANSACTION":
|
||||
return PingStrategy.TRANSACTION;
|
||||
default:
|
||||
throw new IllegalStateException("Unknown ping_strategy: " + pingStrategy);
|
||||
}
|
||||
}
|
||||
|
||||
private long convertTicksToMilliseconds(long ticks) {
|
||||
return ticks * 50;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
package me.caseload.knockbacksync.runnable;
|
||||
|
||||
import com.github.retrooper.packetevents.protocol.player.User;
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.manager.CombatManager;
|
||||
import me.caseload.knockbacksync.manager.PlayerDataManager;
|
||||
@@ -15,10 +14,9 @@ public class PingRunnable implements Runnable {
|
||||
if (!Base.INSTANCE.getConfigManager().isToggled())
|
||||
return;
|
||||
|
||||
for (User user : CombatManager.getPlayers()) {
|
||||
PlayerData playerData = PlayerDataManager.getPlayerData(user);
|
||||
if (playerData != null)
|
||||
playerData.sendPing(true);
|
||||
for (UUID uuid : CombatManager.getPlayers()) {
|
||||
PlayerData playerData = PlayerDataManager.getPlayerData(uuid);
|
||||
playerData.sendPing(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package me.caseload.knockbacksync.scheduler;
|
||||
|
||||
import io.netty.util.concurrent.ScheduledFuture;
|
||||
|
||||
public class NettyTaskHandle implements AbstractTaskHandle {
|
||||
|
||||
private final ScheduledFuture scheduledFuture;
|
||||
|
||||
public NettyTaskHandle(ScheduledFuture<?> scheduledFuture) {
|
||||
this.scheduledFuture = scheduledFuture;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean getCancelled() {
|
||||
return scheduledFuture.isCancelled();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cancel() {
|
||||
scheduledFuture.cancel(true);
|
||||
}
|
||||
}
|
||||
@@ -19,9 +19,18 @@ public class GeyserUtil {
|
||||
public static boolean isGeyserPlayer(UUID uuid) {
|
||||
if (!CHECKED_FOR_GEYSER) {
|
||||
try {
|
||||
ClassLoader classLoader = PacketEvents.getAPI().getPlugin().getClass().getClassLoader();
|
||||
GEYSER_CLASS = classLoader.loadClass("org.geysermc.api.Geyser");
|
||||
GEYSER_PRESENT = true;
|
||||
switch (Base.INSTANCE.getPlatform()) {
|
||||
case BUKKIT:
|
||||
case FOLIA:
|
||||
ClassLoader classLoader = PacketEvents.getAPI().getPlugin().getClass().getClassLoader();
|
||||
GEYSER_CLASS = classLoader.loadClass("org.geysermc.api.Geyser");
|
||||
break;
|
||||
case FABRIC:
|
||||
GEYSER_CLASS = Class.forName("org.geysermc.api.Geyser");
|
||||
GEYSER_PRESENT = true;
|
||||
break;
|
||||
}
|
||||
|
||||
} catch (ClassNotFoundException e) {
|
||||
GEYSER_PRESENT = false;
|
||||
}
|
||||
@@ -31,8 +40,17 @@ public class GeyserUtil {
|
||||
if (GEYSER_PRESENT) {
|
||||
if (GEYSER_API_CLASS == null) {
|
||||
try {
|
||||
ClassLoader classLoader = PacketEvents.getAPI().getPlugin().getClass().getClassLoader();
|
||||
GEYSER_API_CLASS = classLoader.loadClass("org.geysermc.api.GeyserApiBase");
|
||||
switch (Base.INSTANCE.getPlatform()) {
|
||||
case BUKKIT:
|
||||
case FOLIA:
|
||||
ClassLoader classLoader = PacketEvents.getAPI().getPlugin().getClass().getClassLoader();
|
||||
GEYSER_API_CLASS = classLoader.loadClass("org.geysermc.api.GeyserApiBase");
|
||||
break;
|
||||
case FABRIC:
|
||||
GEYSER_CLASS = Class.forName("org.geysermc.api.GeyserApiBase");
|
||||
GEYSER_PRESENT = true;
|
||||
break;
|
||||
}
|
||||
} catch (ClassNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
@@ -1,101 +0,0 @@
|
||||
/*
|
||||
* Legacy (Minecraft 1.8) melee knockback formula.
|
||||
*
|
||||
* This file is a port of the knockback calculation from BukkitOldCombatMechanics
|
||||
* (kernitus/BukkitOldCombatMechanics), module ModulePlayerKnockback, which is
|
||||
* licensed under the Mozilla Public License, v. 2.0:
|
||||
*
|
||||
* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*
|
||||
* The MPL-2.0 does not carry the "Incompatible With Secondary Licenses" notice
|
||||
* (Exhibit B), so per MPL-2.0 §3.3 this Covered Software may be distributed as
|
||||
* part of a Larger Work under the GNU General Public License v3.0-or-later that
|
||||
* governs the rest of KnockbackSync. The terms of the MPL continue to apply to
|
||||
* this file. See the NOTICE file at the project root for attribution details.
|
||||
*/
|
||||
package me.caseload.knockbacksync.util;
|
||||
|
||||
import com.github.retrooper.packetevents.util.Vector3d;
|
||||
import me.caseload.knockbacksync.manager.ConfigManager;
|
||||
import me.caseload.knockbacksync.player.PlatformPlayer;
|
||||
import me.caseload.knockbacksync.player.PlayerData;
|
||||
|
||||
/**
|
||||
* Computes the exact 1.8-style melee knockback vector applied to a victim, so that
|
||||
* KnockbackSync can own the final melee velocity (horizontal + vertical) and then
|
||||
* latency-correct it, rather than letting vanilla knockback win.
|
||||
*
|
||||
* <p>The math is a faithful reproduction of OldCombatMechanics' legacy player
|
||||
* knockback so that values are identical to running OCM's old-player-knockback
|
||||
* module, while KnockbackSync remains the single writer of the velocity.</p>
|
||||
*/
|
||||
public final class LegacyKnockback {
|
||||
|
||||
private LegacyKnockback() {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param victim the player receiving knockback
|
||||
* @param attacker the attacking player
|
||||
* @param victimData the victim's tracked data (for knockback resistance attribute)
|
||||
* @param config the plugin configuration (legacy knockback tunables)
|
||||
* @return the 1.8-style velocity to apply to the victim, before latency Y-correction
|
||||
*/
|
||||
public static Vector3d compute(PlatformPlayer victim, PlatformPlayer attacker,
|
||||
PlayerData victimData, ConfigManager config) {
|
||||
final double knockbackHorizontal = config.getLegacyKnockbackHorizontal();
|
||||
final double knockbackVertical = config.getLegacyKnockbackVertical();
|
||||
final double knockbackVerticalLimit = config.getLegacyKnockbackVerticalLimit();
|
||||
final double knockbackExtraHorizontal = config.getLegacyKnockbackExtraHorizontal();
|
||||
final double knockbackExtraVertical = config.getLegacyKnockbackExtraVertical();
|
||||
final boolean netheriteKnockbackResistance = config.isLegacyKnockbackResistanceEnabled();
|
||||
|
||||
// Figure out base knockback direction (attacker -> victim) with vanilla jitter
|
||||
// when the two are stacked on the exact same column.
|
||||
double d0 = attacker.getX() - victim.getX();
|
||||
double d1;
|
||||
for (d1 = attacker.getZ() - victim.getZ(); d0 * d0 + d1 * d1 < 1.0E-4D;
|
||||
d1 = (Math.random() - Math.random()) * 0.01D) {
|
||||
d0 = (Math.random() - Math.random()) * 0.01D;
|
||||
}
|
||||
|
||||
final double magnitude = Math.sqrt(d0 * d0 + d1 * d1);
|
||||
|
||||
// Player velocity before any friction is applied (pre-knockback motion).
|
||||
final Vector3d v = victim.getVelocity();
|
||||
|
||||
// Apply friction (halve), then add base knockback.
|
||||
double vx = (v.getX() / 2) - (d0 / magnitude * knockbackHorizontal);
|
||||
double vy = (v.getY() / 2) + knockbackVertical;
|
||||
double vz = (v.getZ() / 2) - (d1 / magnitude * knockbackHorizontal);
|
||||
|
||||
// Bonus knockback for sprinting and the Knockback enchantment.
|
||||
int bonusKnockback = attacker.getWeaponKnockbackLevel();
|
||||
if (attacker.isSprinting()) {
|
||||
bonusKnockback++;
|
||||
}
|
||||
|
||||
// NOTE: vanilla caps vertical BEFORE adding the sprint/enchant bonus vertical.
|
||||
if (vy > knockbackVerticalLimit) {
|
||||
vy = knockbackVerticalLimit;
|
||||
}
|
||||
|
||||
if (bonusKnockback > 0) {
|
||||
final float yaw = attacker.getYaw();
|
||||
vx += -Math.sin(yaw * 3.1415927F / 180.0F) * (float) bonusKnockback * knockbackExtraHorizontal;
|
||||
vy += knockbackExtraVertical;
|
||||
vz += Math.cos(yaw * 3.1415927F / 180.0F) * (float) bonusKnockback * knockbackExtraHorizontal;
|
||||
}
|
||||
|
||||
if (netheriteKnockbackResistance) {
|
||||
// Each piece of netherite armour yields 10% horizontal resistance.
|
||||
final double resistance = 1 - victimData.getKnockbackResistanceAttribute();
|
||||
vx *= resistance;
|
||||
vz *= resistance;
|
||||
}
|
||||
|
||||
return new Vector3d(vx, vy, vz);
|
||||
}
|
||||
}
|
||||
@@ -10,5 +10,18 @@ public interface PlatformServer {
|
||||
|
||||
PlatformPlayer getPlayer(UUID uuid);
|
||||
|
||||
PlatformPlayer getPlayer(Object nativePlatformPlayer);
|
||||
// switch (KnockbackSyncBase.INSTANCE.platform) {
|
||||
// case BUKKIT:
|
||||
// case FOLIA:
|
||||
// return Bukkit.getOnlinePlayers().stream()
|
||||
// .map(BukkitPlayer::new)
|
||||
// .collect(Collectors.toList());
|
||||
// case FABRIC:
|
||||
// MinecraftServer server = (MinecraftServer) FabricLoader.getInstance().getGameInstance();
|
||||
// return server.getPlayerList().getPlayers().stream()
|
||||
// .map(FabricPlayer::new)
|
||||
// .collect(Collectors.toList());
|
||||
// default:
|
||||
// throw new IllegalStateException("Unexpected platform: " + KnockbackSyncBase.INSTANCE.platform);
|
||||
// }
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
#########################################
|
||||
|
||||
# Do not modify!
|
||||
config_version: 9
|
||||
config_version: 6
|
||||
|
||||
# Plugin enabled state
|
||||
# Toggleable using /knockbacksync toggle
|
||||
@@ -14,10 +14,6 @@ enabled: true
|
||||
# Required permission: knockbacksync.update
|
||||
notify_updates: true
|
||||
|
||||
# Automatically updates the plugin
|
||||
# Only servers with restart compatibility can use this feature
|
||||
auto_update: false
|
||||
|
||||
# Grabs the ping of combat-tagged players every x ticks
|
||||
# Disabling this may lead to inaccuracies in calculations
|
||||
runnable:
|
||||
@@ -30,46 +26,21 @@ runnable:
|
||||
# the threshold, the previous ping value is used to avoid calculation inaccuracies.
|
||||
spike_threshold: 20
|
||||
|
||||
# OPTIONS: PING, TRANSACTION (aliases), KEEPALIVE. PING is safe (vanilla ignores unexpected pongs, ViaVersion translates for 1.8-1.16, ± 5ms); KEEPALIVE is slightly more precise but any unintercepted echo kicks ("Timed out") on 1.20.2+ and anticheat NET checks may kick for the extra traffic.
|
||||
ping_strategy: "PING"
|
||||
# OPTIONS: KEEPALIVE, PING, TRANSACTION - PING and TRANSACTION are aliases for each other and are effectively the same
|
||||
# The packet type used to measure ping by the runnable.
|
||||
# KEEPALIVE is the most accurate however sending too many of them too often (such as using a runnable with a low interval)
|
||||
# - May disconnect players, especially laggy ones if sent too often
|
||||
# - The default interval of 20 ticks or 1 second
|
||||
# means it is in theory possible for a player to have a ping spike in-between two sword attacks
|
||||
# and have it immediately spike back down, slightly throwing off knockback synchronization
|
||||
# in practice this is very rare and the extra ping accuracy and precision is more valued
|
||||
# PING/TRANSACTION can be sent more often (and therefore better detect ping spikes) but are less precise
|
||||
# ping measured in ms with PING/TRANSACTION is typically within ± 5ms of actual but can be up to 50ms off
|
||||
ping_strategy: "KEEPALIVE"
|
||||
|
||||
# Whether to try to detect when player is offground and apply less kb
|
||||
enable_offground_synchronization: true
|
||||
|
||||
# Legacy (1.8) melee knockback.
|
||||
# When enabled, KnockbackSync computes the exact 1.8 player-vs-player knockback
|
||||
# (horizontal + vertical) itself and becomes the single owner of melee velocity,
|
||||
# then latency-syncs it as usual. This reproduces OldCombatMechanics'
|
||||
# old-player-knockback values for ALL clients 1.8+ while keeping them synced.
|
||||
#
|
||||
# IMPORTANT: if you enable this, DISABLE OldCombatMechanics' old-player-knockback
|
||||
# module (remove it from the active modeset). Running both at once makes two
|
||||
# plugins fight over PlayerVelocityEvent. KnockbackSync owns the velocity here.
|
||||
# OCM can still provide its other features (attack cooldown removal, etc.).
|
||||
legacy_knockback:
|
||||
enabled: true # Master toggle for legacy knockback
|
||||
horizontal: 0.4 # Base horizontal knockback (OCM: knockback-horizontal)
|
||||
vertical: 0.4 # Base vertical knockback (OCM: knockback-vertical)
|
||||
vertical_limit: 0.4 # Vertical cap before sprint/enchant bonus (OCM: knockback-vertical-limit)
|
||||
extra_horizontal: 0.5 # Bonus horizontal per sprint/Knockback level (OCM: knockback-extra-horizontal)
|
||||
extra_vertical: 0.1 # Bonus vertical when sprint/Knockback applies (OCM: knockback-extra-vertical)
|
||||
# When false (default, matching OCM), netherite/armour knockback resistance is
|
||||
# ignored so the velocity event always fires and full 1.8 knockback is applied.
|
||||
# When true, horizontal knockback is reduced by the victim's resistance attribute.
|
||||
#
|
||||
# Scope of the false setting:
|
||||
# - Melee PvP: LegacyKnockback already ignores resistance (it owns the velocity).
|
||||
# - Projectile PvP (bow/arrow, trident, and snowball/egg/ender pearl once
|
||||
# OldCombatMechanics' projectile-knockback gives them damage): KnockbackSync
|
||||
# temporarily nullifies the victim's knockback-resistance attribute for the hit
|
||||
# so vanilla applies full knockback, then restores it (PvE is unaffected).
|
||||
# - Fishing-rod PvP: owned by OCM old-fishing-knockback + the rod API (already 1.8).
|
||||
# - Explosions are NOT affected by knockback resistance on 1.19.4, so they are
|
||||
# out of scope here.
|
||||
# Ownership: KnockbackSync owns player knockback; keep OCM's old-player-knockback
|
||||
# module DISABLED (see the IMPORTANT note above).
|
||||
enable_knockback_resistance: false
|
||||
|
||||
# This is the rate the server will use for (amongst other things) sending packets about entities to players
|
||||
# In other words it defines how often clients get updated velocity for other entities in the world
|
||||
# Note that certain events mark velocity as dirty and causes it to be immediately updated for 1 tick regardless of the tick interval
|
||||
@@ -219,7 +190,6 @@ messages:
|
||||
enable: "&aSuccessfully enabled KnockbackSync for %player%."
|
||||
disable: "&aSuccessfully &cdisabled &aKnockbackSync for %player%."
|
||||
ineligible: "&c%player% is ineligible for KnockbackSync. If you believe this is in error, please contact your server administrators."
|
||||
disconnected-while-executing-command: "&c%player% disconnected while executing command."
|
||||
permission:
|
||||
no_global: "&cYou don't have permission to toggle the global setting."
|
||||
no_self: "&cYou do not have permission to toggle your knockback."
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
plugins {
|
||||
id("fabric-loom")
|
||||
id("com.gradleup.shadow")
|
||||
}
|
||||
|
||||
loom {
|
||||
accessWidenerPath = file("src/main/resources/knockbacksync.accesswidener")
|
||||
}
|
||||
|
||||
base {
|
||||
archivesName.set("${rootProject.property("archives_base_name")}-fabric")
|
||||
}
|
||||
|
||||
val shadeThisThing: Configuration by configurations.creating {
|
||||
isCanBeConsumed = true
|
||||
isTransitive = true
|
||||
}
|
||||
|
||||
// TODO migrate to only including sourceset for compile, test and javadoc tasks
|
||||
// Currently must build with gradle build -x test to skip test
|
||||
tasks.withType<JavaCompile>().configureEach {
|
||||
source(project(":common").sourceSets.main.get().allSource)
|
||||
}
|
||||
|
||||
tasks.withType<Javadoc>().configureEach {
|
||||
source(project(":common").sourceSets.main.get().allJava)
|
||||
}
|
||||
|
||||
tasks.named<JavaCompile>("compileTestJava") {
|
||||
exclude("**/*")
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(project(":common"))
|
||||
|
||||
minecraft("com.mojang:minecraft:${rootProject.property("minecraft_version")}")
|
||||
mappings(loom.layered {
|
||||
officialMojangMappings()
|
||||
parchment("org.parchmentmc.data:parchment-1.21:${rootProject.property("parchment_mappings")}")
|
||||
})
|
||||
modImplementation("net.fabricmc:fabric-loader:${rootProject.property("loader_version")}")
|
||||
modImplementation("net.fabricmc.fabric-api:fabric-api:${rootProject.property("fabric_version")}")
|
||||
|
||||
include(modImplementation("me.lucko:fabric-permissions-api:0.3.1")!!)
|
||||
include(modImplementation("com.github.retrooper:packetevents-fabric:2.6.0-SNAPSHOT")!!)
|
||||
include(modImplementation("org.incendo:cloud-fabric:2.0.0-beta.9")!!)
|
||||
|
||||
include(implementation("org.yaml:snakeyaml:2.0")!!)
|
||||
include(implementation("org.kohsuke:github-api:1.326")!!)
|
||||
// Required for org.kohsuke.github
|
||||
include(implementation("com.fasterxml.jackson.core:jackson-databind:2.17.2")!!)
|
||||
include(implementation("com.fasterxml.jackson.core:jackson-annotations:2.17.2")!!)
|
||||
include(implementation("com.fasterxml.jackson.core:jackson-core:2.17.2")!!)
|
||||
// Not requires in modern Minecraft. May be needed if fabric version is backported to older versions
|
||||
// include(implementation("org.apache.commons:commons-lang3:3.17.0")!!)
|
||||
// include(implementation("commons-io:commons-io:2.16.1")!!)
|
||||
|
||||
compileOnly("org.geysermc.floodgate:api:2.0-SNAPSHOT")
|
||||
compileOnly("org.projectlombok:lombok:1.18.34")
|
||||
annotationProcessor("org.projectlombok:lombok:1.18.34")
|
||||
}
|
||||
|
||||
tasks.shadowJar {
|
||||
archiveClassifier.set("dev")
|
||||
configurations = listOf(shadeThisThing)
|
||||
isEnableRelocation = true
|
||||
relocationPrefix = "${project.property("maven_group")}.${project.property("archives_base_name")}.shaded"
|
||||
finalizedBy(tasks.remapJar)
|
||||
}
|
||||
tasks.remapJar {
|
||||
archiveClassifier.set(null as String?)
|
||||
dependsOn(tasks.shadowJar)
|
||||
inputFile = tasks.shadowJar.get().archiveFile
|
||||
}
|
||||
|
||||
tasks.processResources {
|
||||
from(project(":common").sourceSets.main.get().resources)
|
||||
|
||||
inputs.property("version", project.version)
|
||||
inputs.property("minecraft_version", rootProject.property("minecraft_version"))
|
||||
inputs.property("loader_version", rootProject.property("loader_version"))
|
||||
filteringCharset = "UTF-8"
|
||||
|
||||
filesMatching("fabric.mod.json") {
|
||||
expand(
|
||||
"version" to project.version,
|
||||
"minecraft_version" to rootProject.property("minecraft_version"),
|
||||
"loader_version" to rootProject.property("loader_version")
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
java {
|
||||
sourceCompatibility = JavaVersion.VERSION_21
|
||||
targetCompatibility = JavaVersion.VERSION_21
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package me.caseload.knockbacksync;
|
||||
|
||||
import com.github.retrooper.packetevents.PacketEvents;
|
||||
import io.github.retrooper.packetevents.factory.fabric.FabricPacketEventsAPI;
|
||||
import lombok.Getter;
|
||||
import me.caseload.knockbacksync.entity.EntityTickManager;
|
||||
import me.caseload.knockbacksync.listener.fabric.FabricPlayerDamageListener;
|
||||
import me.caseload.knockbacksync.listener.fabric.FabricPlayerJoinQuitListener;
|
||||
import me.caseload.knockbacksync.listener.fabric.FabricPlayerKnockbackListener;
|
||||
import me.caseload.knockbacksync.listener.fabric.FabricTickRateChangeListener;
|
||||
import me.caseload.knockbacksync.manager.ConfigManager;
|
||||
import me.caseload.knockbacksync.permission.FabricPermissionChecker;
|
||||
import me.caseload.knockbacksync.permission.PermissionChecker;
|
||||
import me.caseload.knockbacksync.scheduler.FabricSchedulerAdapter;
|
||||
import me.caseload.knockbacksync.sender.FabricPlayerSelectorParser;
|
||||
import me.caseload.knockbacksync.sender.FabricSenderFactory;
|
||||
import me.caseload.knockbacksync.stats.custom.FabricStatsManager;
|
||||
import me.caseload.knockbacksync.stats.custom.PluginJarHashProvider;
|
||||
import me.caseload.knockbacksync.world.FabricServer;
|
||||
import net.fabricmc.api.EnvType;
|
||||
import net.fabricmc.loader.api.FabricLoader;
|
||||
import net.fabricmc.loader.api.ModContainer;
|
||||
import org.incendo.cloud.execution.ExecutionCoordinator;
|
||||
import org.incendo.cloud.fabric.FabricServerCommandManager;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.nio.file.Files;
|
||||
import java.util.Optional;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class FabricBase extends Base {
|
||||
|
||||
private final Logger logger = Logger.getLogger(FabricLoaderMod.class.getName());
|
||||
private final FabricPermissionChecker permissionChecker = new FabricPermissionChecker();
|
||||
@Getter
|
||||
private final FabricSenderFactory fabricSenderFactory = new FabricSenderFactory(this);
|
||||
private float tickRate = 20.0F;
|
||||
|
||||
public FabricBase() {
|
||||
super.configManager = new ConfigManager();
|
||||
super.playerSelectorParser = new FabricPlayerSelectorParser<>();
|
||||
super.commandManager = new FabricServerCommandManager<>(
|
||||
ExecutionCoordinator.simpleCoordinator(),
|
||||
fabricSenderFactory
|
||||
);
|
||||
super.statsManager = new FabricStatsManager();
|
||||
super.platformServer = new FabricServer();
|
||||
super.pluginJarHashProvider = new PluginJarHashProvider(getJarURL());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Logger getLogger() {
|
||||
return logger;
|
||||
}
|
||||
|
||||
@Override
|
||||
public File getDataFolder() {
|
||||
return FabricLoader.getInstance().getConfigDir().toFile();
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream getResource(String filename) {
|
||||
return getClass().getResourceAsStream("/config.yml");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load() {
|
||||
PacketEvents.setAPI(new FabricPacketEventsAPI("knockbacksync", EnvType.SERVER));
|
||||
PacketEvents.getAPI().load();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void enable() {
|
||||
super.enable();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initializeScheduler() {
|
||||
scheduler = new FabricSchedulerAdapter();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void registerPlatformListeners() {
|
||||
new FabricPlayerJoinQuitListener().register();
|
||||
new FabricPlayerDamageListener().register();
|
||||
new FabricPlayerKnockbackListener().register();
|
||||
new FabricTickRateChangeListener().register();
|
||||
super.eventBus.registerStaticListeners(EntityTickManager.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getVersion() {
|
||||
return FabricLoader.getInstance().getModContainer("knockbacksync")
|
||||
.map(modContainer -> modContainer.getMetadata().getVersion().getFriendlyString())
|
||||
.orElse("unknown");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void saveDefaultConfig() {
|
||||
File configFile = new File(FabricLoader.getInstance().getConfigDir().toFile(), "config.yml");
|
||||
if (!configFile.exists()) {
|
||||
try (InputStream inputStream = getClass().getResourceAsStream("/config.yml")) {
|
||||
if (inputStream != null) {
|
||||
Files.copy(inputStream, configFile.toPath());
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public PermissionChecker getPermissionChecker() {
|
||||
return permissionChecker;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getTickRate() {
|
||||
return this.tickRate;
|
||||
}
|
||||
|
||||
public void setTickRate(float tickRate) {
|
||||
this.tickRate = tickRate;
|
||||
}
|
||||
|
||||
private URL getJarURL() {
|
||||
URL jarUrl = null;
|
||||
Optional<ModContainer> modContainer = FabricLoader.getInstance().getModContainer("knockbacksync");
|
||||
if (modContainer.isPresent()) {
|
||||
String jarPath = modContainer.get().getRootPath().getFileSystem().toString();
|
||||
jarPath = jarPath.replaceAll("^jar:", "").replaceAll("!/$", "");
|
||||
try {
|
||||
jarUrl = new File(jarPath).toURI().toURL();
|
||||
} catch (MalformedURLException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
return jarUrl;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package me.caseload.knockbacksync;
|
||||
|
||||
import net.fabricmc.api.ModInitializer;
|
||||
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
|
||||
import net.fabricmc.loader.api.FabricLoader;
|
||||
import net.fabricmc.loader.api.entrypoint.PreLaunchEntrypoint;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
|
||||
public class FabricLoaderMod implements PreLaunchEntrypoint, ModInitializer {
|
||||
|
||||
private final Base core = new FabricBase();
|
||||
|
||||
public static MinecraftServer getServer() {
|
||||
return (MinecraftServer) FabricLoader.getInstance().getGameInstance();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPreLaunch() {
|
||||
core.load();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onInitialize() {
|
||||
core.enable();
|
||||
ServerLifecycleEvents.SERVER_STOPPING.register((server) -> {
|
||||
core.scheduler.shutdown();
|
||||
core.statsManager.getMetrics().shutdown();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package me.caseload.knockbacksync.callback;
|
||||
|
||||
import net.fabricmc.fabric.api.event.Event;
|
||||
import net.fabricmc.fabric.api.event.EventFactory;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.world.InteractionResult;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
public interface PlayerVelocityEvent {
|
||||
Event<PlayerVelocityEvent> EVENT = EventFactory.createArrayBacked(PlayerVelocityEvent.class,
|
||||
(listeners) -> (player, velocity) -> {
|
||||
for (PlayerVelocityEvent listener : listeners) {
|
||||
InteractionResult result = listener.onVelocityChange(player, velocity);
|
||||
|
||||
if (result != InteractionResult.PASS) {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
return InteractionResult.PASS;
|
||||
});
|
||||
|
||||
InteractionResult onVelocityChange(ServerPlayer player, Vec3 velocity);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package me.caseload.knockbacksync.callback;
|
||||
|
||||
import net.fabricmc.fabric.api.event.Event;
|
||||
import net.fabricmc.fabric.api.event.EventFactory;
|
||||
|
||||
public interface TickRateChangeEvent {
|
||||
Event<TickRateChangeEvent> EVENT = EventFactory.createArrayBacked(TickRateChangeEvent.class,
|
||||
(listeners) -> (oldTickRate, newTickRate) -> {
|
||||
for (TickRateChangeEvent listener : listeners) {
|
||||
listener.onTickRateChange(oldTickRate, newTickRate);
|
||||
}
|
||||
});
|
||||
|
||||
void onTickRateChange(float oldTickRate, float newTickRate);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package me.caseload.knockbacksync.entity;
|
||||
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.ConfigWrapper;
|
||||
import me.caseload.knockbacksync.event.events.ConfigReloadEvent;
|
||||
import me.caseload.knockbacksync.event.KBSyncEventHandler;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
public class EntityTickManager {
|
||||
private static final Map<EntityType<?>, Integer> customTickIntervals = new HashMap<>();
|
||||
|
||||
static {
|
||||
updateTickIntervals(Base.INSTANCE.getConfigManager().getConfigWrapper());
|
||||
}
|
||||
|
||||
@KBSyncEventHandler
|
||||
public static void updateTickIntervals(ConfigReloadEvent event) {
|
||||
ConfigWrapper configWrapper = event.getConfigManager().getConfigWrapper();
|
||||
updateTickIntervals(configWrapper);
|
||||
|
||||
// Map<String, Integer> entityIntervals = CustomUpdateIntervals.loadEntityIntervalsFromConfig();
|
||||
// for (ServerLevel level : FabricLoaderMod.getServer().getAllLevels()) {
|
||||
// CustomUpdateIntervals.updateIntervals(level, entityIntervals);
|
||||
// }
|
||||
}
|
||||
|
||||
private static void updateTickIntervals(ConfigWrapper configWrapper) {
|
||||
customTickIntervals.clear();
|
||||
for (String entityKey : configWrapper.getKeys("entity_tick_intervals")) {
|
||||
try {
|
||||
Optional<EntityType<?>> entityType = EntityType.byString(entityKey.toLowerCase());
|
||||
if (entityType.isPresent()) {
|
||||
int interval = configWrapper.getInt("entity_tick_intervals." + entityKey, entityType.get().updateInterval());
|
||||
customTickIntervals.put(entityType.get(), interval);
|
||||
}
|
||||
} catch (IllegalArgumentException e) {
|
||||
System.err.println("Invalid entity type in config: " + entityKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static int getCustomUpdateInterval(EntityType<?> entityType) {
|
||||
return customTickIntervals.getOrDefault(entityType, entityType.updateInterval());
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package me.caseload.knockbacksync.listener.fabric;
|
||||
|
||||
|
||||
import me.caseload.knockbacksync.listener.PlayerDamageListener;
|
||||
import me.caseload.knockbacksync.player.FabricPlayer;
|
||||
import me.caseload.knockbacksync.player.PlatformPlayer;
|
||||
import net.fabricmc.fabric.api.event.player.AttackEntityCallback;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.world.InteractionResult;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
|
||||
public class FabricPlayerDamageListener extends PlayerDamageListener {
|
||||
|
||||
public void register() {
|
||||
AttackEntityCallback.EVENT.register((player, world, hand, entity, source) -> {
|
||||
onPlayerDamage((ServerPlayer) player, entity);
|
||||
return InteractionResult.PASS;
|
||||
});
|
||||
}
|
||||
|
||||
private void onPlayerDamage(ServerPlayer attacker, Entity victimEntity) {
|
||||
if (victimEntity instanceof Player victim) {
|
||||
PlatformPlayer platformAttacker = new FabricPlayer(attacker);
|
||||
PlatformPlayer platformVictim = new FabricPlayer((ServerPlayer) victim);
|
||||
super.onPlayerDamage(platformVictim, platformAttacker); // Call the shared method
|
||||
}
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package me.caseload.knockbacksync.listener.fabric;
|
||||
|
||||
import me.caseload.knockbacksync.listener.PlayerJoinQuitListener;
|
||||
import me.caseload.knockbacksync.player.FabricPlayer;
|
||||
import me.caseload.knockbacksync.player.PlayerData;
|
||||
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
|
||||
|
||||
public class FabricPlayerJoinQuitListener extends PlayerJoinQuitListener {
|
||||
public void register() {
|
||||
ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> {
|
||||
onPlayerJoin(new PlayerData(new FabricPlayer(handler.player)));
|
||||
});
|
||||
ServerPlayConnectionEvents.DISCONNECT.register(((handler, server) -> {
|
||||
onPlayerQuit(handler.player.getUUID());
|
||||
}));
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package me.caseload.knockbacksync.listener.fabric;
|
||||
|
||||
import com.github.retrooper.packetevents.util.Vector3d;
|
||||
import me.caseload.knockbacksync.callback.PlayerVelocityEvent;
|
||||
import me.caseload.knockbacksync.listener.PlayerKnockbackListener;
|
||||
import me.caseload.knockbacksync.player.FabricPlayer;
|
||||
import net.minecraft.world.InteractionResult;
|
||||
import net.minecraft.world.damagesource.DamageSource;
|
||||
import net.minecraft.world.damagesource.DamageTypes;
|
||||
|
||||
public class FabricPlayerKnockbackListener extends PlayerKnockbackListener {
|
||||
|
||||
public void register() {
|
||||
PlayerVelocityEvent.EVENT.register((player, velocity) -> {
|
||||
DamageSource lastDamageSource = player.getLastDamageSource();
|
||||
if (lastDamageSource == null)
|
||||
return InteractionResult.PASS;
|
||||
|
||||
// Check if the damage is from a player attack
|
||||
if (!lastDamageSource.is(DamageTypes.PLAYER_ATTACK))
|
||||
return InteractionResult.PASS;
|
||||
|
||||
onPlayerVelocity(new FabricPlayer(player), new Vector3d(velocity.x, velocity.y, velocity.z));
|
||||
// This SHOULD mean we return original velocity for Fabric (no modification here)
|
||||
// But since we set it ourselves due to following bukkit's design patterns and doing victim
|
||||
// We return a pass so velocity isn't set twice
|
||||
return InteractionResult.PASS;
|
||||
});
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package me.caseload.knockbacksync.listener.fabric;
|
||||
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.FabricBase;
|
||||
import me.caseload.knockbacksync.callback.TickRateChangeEvent;
|
||||
|
||||
public class FabricTickRateChangeListener {
|
||||
public void register() {
|
||||
TickRateChangeEvent.EVENT.register((oldTickRate, newTickRate) -> {
|
||||
if (oldTickRate != newTickRate) {
|
||||
((FabricBase) Base.INSTANCE).setTickRate(newTickRate);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package me.caseload.knockbacksync.mixin;
|
||||
|
||||
import me.caseload.knockbacksync.entity.EntityTickManager;
|
||||
import net.minecraft.server.level.ChunkMap;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.Redirect;
|
||||
|
||||
@Mixin(ChunkMap.class)
|
||||
public abstract class ChunkMapMixin {
|
||||
|
||||
@Redirect(method = "addEntity", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/EntityType;updateInterval()I"))
|
||||
private int getCustomUpdateInterval(EntityType<?> entityType) {
|
||||
return EntityTickManager.getCustomUpdateInterval(entityType);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
//package me.caseload.knockbacksync.mixin;
|
||||
//
|
||||
//import me.caseload.knockbacksync.ConfigWrapper;
|
||||
//import me.caseload.knockbacksync.KnockbackSyncBase;
|
||||
//import me.caseload.knockbacksync.event.ConfigReloadEvent;
|
||||
//import me.caseload.knockbacksync.event.KBSyncEventHandler;
|
||||
//import me.caseload.knockbacksync.util.CustomUpdateIntervals;
|
||||
//import net.minecraft.Util;
|
||||
//import net.minecraft.server.level.ChunkMap;
|
||||
//import net.minecraft.server.level.ServerLevel;
|
||||
//import net.minecraft.server.level.ServerPlayer;
|
||||
//import net.minecraft.world.entity.Entity;
|
||||
//import net.minecraft.world.entity.EntityType;
|
||||
//import net.minecraft.world.entity.boss.EnderDragonPart;
|
||||
//import org.spongepowered.asm.mixin.Final;
|
||||
//import org.spongepowered.asm.mixin.Mixin;
|
||||
//import org.spongepowered.asm.mixin.Shadow;
|
||||
//import org.spongepowered.asm.mixin.injection.At;
|
||||
//import org.spongepowered.asm.mixin.injection.Inject;
|
||||
//import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
//
|
||||
//import java.util.HashMap;
|
||||
//import java.util.Map;
|
||||
//
|
||||
//@Mixin(ChunkMap.class)
|
||||
//public class ChunkMapMixin {
|
||||
//
|
||||
// @Shadow @Final
|
||||
// private Map<Integer, ChunkMap.TrackedEntity> entityMap;
|
||||
// @Shadow @Final private ServerLevel level;
|
||||
//
|
||||
// @Inject(method = "addEntity", at = @At("HEAD"), cancellable = true)
|
||||
// private void onAddEntity(Entity entity, CallbackInfo ci) {
|
||||
// if (!(entity instanceof EnderDragonPart)) {
|
||||
// EntityType<?> entityType = entity.getType();
|
||||
// int trackingRange = entityType.clientTrackingRange() * 16;
|
||||
//
|
||||
// if (trackingRange != 0) {
|
||||
// String entityTypeName = entityType.builtInRegistryHolder().getRegisteredName();
|
||||
// ConfigWrapper config = KnockbackSyncBase.INSTANCE.getConfigManager().getConfigWrapper();
|
||||
//
|
||||
// int defaultInterval = entityType.updateInterval();
|
||||
// int customInterval = config.getInt("entity_update_intervals." + entityTypeName, defaultInterval);
|
||||
//
|
||||
// if (this.entityMap.containsKey(entity.getId())) {
|
||||
// throw (IllegalStateException) Util.pauseInIde(new IllegalStateException("Entity is already tracked!"));
|
||||
// } else {
|
||||
// ChunkMap.TrackedEntity trackedEntity = new ChunkMap.TrackedEntity(entity, trackingRange, customInterval, entityType.trackDeltas());
|
||||
// this.entityMap.put(entity.getId(), trackedEntity);
|
||||
// trackedEntity.updatePlayers(this.level.players());
|
||||
//
|
||||
// if (entity instanceof ServerPlayer serverPlayer) {
|
||||
// this.updatePlayerStatus(serverPlayer, true);
|
||||
//
|
||||
// for (ChunkMap.TrackedEntity trackedEntity2 : this.entityMap.values()) {
|
||||
// if (trackedEntity2.entity != serverPlayer) {
|
||||
// trackedEntity2.updatePlayer(serverPlayer);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// ci.cancel();
|
||||
// }
|
||||
//
|
||||
// @Shadow
|
||||
// private void updatePlayerStatus(ServerPlayer player, boolean track) {
|
||||
// // This is a shadow method, implementation is provided by Minecraft
|
||||
// }
|
||||
//
|
||||
// @KBSyncEventHandler
|
||||
// public void onConfigReload(ConfigReloadEvent event) {
|
||||
// Map<String, Integer> newIntervals = CustomUpdateIntervals.loadEntityIntervalsFromConfig();
|
||||
//
|
||||
// for (ChunkMap.TrackedEntity trackedEntity : this.entityMap.values()) {
|
||||
// Entity entity = trackedEntity.entity;
|
||||
// String entityTypeName = entity.getType().builtInRegistryHolder().getRegisteredName();
|
||||
// int newInterval = newIntervals.getOrDefault(entityTypeName, entity.getType().updateInterval());
|
||||
//
|
||||
// // Assuming TrackedEntity has a method to update its update interval
|
||||
// trackedEntity.setUpdateInterval(newInterval);
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
@@ -0,0 +1,14 @@
|
||||
package me.caseload.knockbacksync.mixin;
|
||||
|
||||
import net.minecraft.commands.CommandSource;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.gen.Accessor;
|
||||
|
||||
@Mixin(CommandSourceStack.class)
|
||||
public interface CommandStackSourceAccessor {
|
||||
|
||||
@Accessor("source")
|
||||
CommandSource getSource();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package me.caseload.knockbacksync.mixin;
|
||||
|
||||
import me.caseload.knockbacksync.callback.PlayerVelocityEvent;
|
||||
import net.minecraft.network.protocol.game.ClientboundSetEntityMotionPacket;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.world.InteractionResult;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.Inject;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
|
||||
@Mixin(Player.class)
|
||||
public class PlayerMixin {
|
||||
|
||||
@Inject(method = "attack", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/protocol/game/ClientboundSetEntityMotionPacket;<init>(Lnet/minecraft/world/entity/Entity;)V"), cancellable = true)
|
||||
private void onAttack(Entity target, CallbackInfo ci) {
|
||||
if (target instanceof ServerPlayer serverPlayer && target.hurtMarked) {
|
||||
Vec3 velocity = target.getDeltaMovement();
|
||||
|
||||
InteractionResult result = PlayerVelocityEvent.EVENT.invoker().onVelocityChange(serverPlayer, velocity);
|
||||
|
||||
if (result == InteractionResult.FAIL) {
|
||||
target.hurtMarked = false;
|
||||
ci.cancel(); // Prevent sending the velocity packet
|
||||
} else if (result == InteractionResult.SUCCESS) {
|
||||
// Currently unnecessary since we do this in the handler, will move later
|
||||
target.setDeltaMovement(velocity);
|
||||
serverPlayer.connection.send(new ClientboundSetEntityMotionPacket(target));
|
||||
target.hurtMarked = false;
|
||||
ci.cancel(); // Prevent sending the original velocity packet
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package me.caseload.knockbacksync.mixin;
|
||||
|
||||
import me.caseload.knockbacksync.callback.PlayerVelocityEvent;
|
||||
import net.minecraft.server.level.ServerEntity;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.world.InteractionResult;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
import org.spongepowered.asm.mixin.Final;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.Shadow;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.Inject;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
|
||||
@Mixin(ServerEntity.class)
|
||||
public class ServerEntityMixin {
|
||||
|
||||
@Shadow
|
||||
@Final
|
||||
private Entity entity;
|
||||
|
||||
// Velocity event
|
||||
@Inject(method = "sendChanges", at = @At(value = "FIELD", target = "Lnet/minecraft/world/entity/Entity;hurtMarked:Z", ordinal = 1), cancellable = true)
|
||||
private void onSendChanges(CallbackInfo ci) {
|
||||
if (this.entity.hurtMarked && this.entity instanceof ServerPlayer player) {
|
||||
Vec3 velocity = player.getDeltaMovement();
|
||||
|
||||
InteractionResult result = PlayerVelocityEvent.EVENT.invoker().onVelocityChange(player, velocity);
|
||||
|
||||
if (result == InteractionResult.FAIL) {
|
||||
this.entity.hurtMarked = false;
|
||||
ci.cancel();
|
||||
} else if (result == InteractionResult.SUCCESS) {
|
||||
// Currently unnecessary since we do this in the handler, will move later
|
||||
player.setDeltaMovement(velocity);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Custom tick intervals
|
||||
// @Shadow
|
||||
// private int updateInterval;
|
||||
|
||||
// @Accessor("entity")
|
||||
// Entity getEntity() {
|
||||
// return null;
|
||||
// }
|
||||
|
||||
// @Invoker("sendChanges")
|
||||
// void invokeSendChanges() {
|
||||
//
|
||||
// }
|
||||
|
||||
// @Override
|
||||
// public void setUpdateInterval(int interval) {
|
||||
// this.updateInterval = interval;
|
||||
// }
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package me.caseload.knockbacksync.mixin;
|
||||
|
||||
import me.caseload.knockbacksync.callback.TickRateChangeEvent;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.world.TickRateManager;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.Shadow;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.Inject;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
|
||||
@Mixin(TickRateManager.class)
|
||||
public class TickRateManagerMixin {
|
||||
@Shadow
|
||||
protected float tickrate;
|
||||
|
||||
@Inject(method = "setTickRate", at = @At("HEAD"))
|
||||
private void onSetTickRate(float tickRate, CallbackInfo ci) {
|
||||
float oldTickRate = this.tickrate;
|
||||
TickRateChangeEvent.EVENT.invoker().onTickRateChange(oldTickRate, tickRate);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
//package me.caseload.knockbacksync.mixin;
|
||||
//
|
||||
//import me.caseload.knockbacksync.ConfigWrapper;
|
||||
//import me.caseload.knockbacksync.KnockbackSyncBase;
|
||||
//import net.minecraft.core.SectionPos;
|
||||
//import net.minecraft.server.level.ChunkMap;
|
||||
//import net.minecraft.server.level.ServerEntity;
|
||||
//import net.minecraft.world.entity.Entity;
|
||||
//import org.spongepowered.asm.mixin.Mixin;
|
||||
//import org.spongepowered.asm.mixin.Shadow;
|
||||
//import org.spongepowered.asm.mixin.gen.Accessor;
|
||||
//import org.spongepowered.asm.mixin.injection.At;
|
||||
//import org.spongepowered.asm.mixin.injection.Inject;
|
||||
//import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
//
|
||||
//@Mixin(ChunkMap.TrackedEntity.class)
|
||||
//public class TrackedEntityMixin {
|
||||
// @Shadow
|
||||
// ServerEntity serverEntity;
|
||||
// Entity entity;
|
||||
// int range;
|
||||
// SectionPos lastSectionPos;
|
||||
//
|
||||
// @Inject(method = "<init>", at = @At("HEAD"))
|
||||
// private void onInit(ChunkMap outer, Entity entity, int range, int updateInterval, boolean trackDelta, CallbackInfo ci) {
|
||||
//
|
||||
// String entityTypeName = entity.getType().builtInRegistryHolder().getRegisteredName();
|
||||
// ConfigWrapper config = KnockbackSyncBase.INSTANCE.getConfigManager().getConfigWrapper();
|
||||
// int customInterval = config.getInt("entity_update_intervals." + entityTypeName, updateInterval);
|
||||
//
|
||||
// this.serverEntity = new ServerEntity(ChunkMap.this.level, entity, customInterval, trackDelta, this::broadcast);
|
||||
// this.entity = entity;
|
||||
// this.range = range;
|
||||
// this.lastSectionPos = SectionPos.of(entity);
|
||||
// }
|
||||
//
|
||||
//// @Accessor("updateInterval")
|
||||
//// public void setUpdateInterval(int interval) {
|
||||
// // This method will be implemented by the mixin system
|
||||
//// }
|
||||
//}
|
||||
@@ -0,0 +1,5 @@
|
||||
package me.caseload.knockbacksync.mixin;
|
||||
|
||||
public interface UpdateIntervalAccessor {
|
||||
void setUpdateInterval(int interval);
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package me.caseload.knockbacksync.permission;
|
||||
|
||||
import me.caseload.knockbacksync.player.FabricPlayer;
|
||||
import me.caseload.knockbacksync.player.PlatformPlayer;
|
||||
import me.caseload.knockbacksync.sender.Sender;
|
||||
import me.lucko.fabric.api.permissions.v0.Permissions;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
|
||||
public class FabricPermissionChecker implements PermissionChecker {
|
||||
|
||||
public boolean hasPermission(CommandSourceStack source, String permission) {
|
||||
return Permissions.check(source, permission, false);
|
||||
}
|
||||
|
||||
public boolean hasPermission(CommandSourceStack source, String permission, boolean defaultIfUnset) {
|
||||
return Permissions.check(source, permission, defaultIfUnset);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasPermission(Object nativeType, String s, boolean defaultIfUnset) {
|
||||
if (nativeType instanceof CommandSourceStack commandSourceStack) {
|
||||
return Permissions.check(commandSourceStack, s, defaultIfUnset);
|
||||
}
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasPermission(Sender source, String s, boolean defaultIfUnset) {
|
||||
return source.hasPermission(s);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasPermission(PlatformPlayer platformPlayer, String s) {
|
||||
return Permissions.check(((FabricPlayer) platformPlayer).fabricPlayer, s);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package me.caseload.knockbacksync.player;
|
||||
|
||||
import com.github.retrooper.packetevents.PacketEvents;
|
||||
import com.github.retrooper.packetevents.protocol.player.User;
|
||||
import com.github.retrooper.packetevents.protocol.world.BoundingBox;
|
||||
import com.github.retrooper.packetevents.protocol.world.Location;
|
||||
import com.github.retrooper.packetevents.util.Vector3d;
|
||||
import me.caseload.knockbacksync.world.FabricWorld;
|
||||
import me.caseload.knockbacksync.world.PlatformWorld;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.data.registries.VanillaRegistries;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.world.effect.MobEffectInstance;
|
||||
import net.minecraft.world.effect.MobEffects;
|
||||
import net.minecraft.world.item.enchantment.Enchantment;
|
||||
import net.minecraft.world.item.enchantment.EnchantmentHelper;
|
||||
import net.minecraft.world.item.enchantment.Enchantments;
|
||||
import net.minecraft.world.phys.AABB;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public class FabricPlayer implements PlatformPlayer {
|
||||
public final ServerPlayer fabricPlayer;
|
||||
private String clientBrand = "fabric";
|
||||
|
||||
public FabricPlayer(ServerPlayer player) {
|
||||
this.fabricPlayer = player;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getUUID() {
|
||||
return fabricPlayer.getUUID();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return fabricPlayer.getName().getString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public double getX() {
|
||||
return fabricPlayer.getX();
|
||||
}
|
||||
|
||||
@Override
|
||||
public double getY() {
|
||||
return fabricPlayer.getY();
|
||||
}
|
||||
|
||||
@Override
|
||||
public double getZ() {
|
||||
return fabricPlayer.getZ();
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getPitch() {
|
||||
return fabricPlayer.getXRot();
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getYaw() {
|
||||
return fabricPlayer.getYRot();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isOnGround() {
|
||||
return fabricPlayer.onGround();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getPing() {
|
||||
return fabricPlayer.connection.latency();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isGliding() {
|
||||
return fabricPlayer.isFallFlying();
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlatformWorld getWorld() {
|
||||
return new FabricWorld(fabricPlayer.level());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Vector3d getLocation() {
|
||||
return new Vector3d(fabricPlayer.getX(), fabricPlayer.getY(), fabricPlayer.getZ());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendMessage(@NotNull String s) {
|
||||
fabricPlayer.sendSystemMessage(Component.literal(s));
|
||||
}
|
||||
|
||||
@Override
|
||||
public double getAttackCooldown() {
|
||||
// this is what paper does I have no idea how this works
|
||||
return fabricPlayer.getAttackStrengthScale(0.5f);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSprinting() {
|
||||
return fabricPlayer.isSprinting();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getMainHandKnockbackLevel() {
|
||||
Optional<Holder.Reference<Enchantment>>
|
||||
entry = VanillaRegistries.createLookup().asGetterLookup().get(
|
||||
Registries.ENCHANTMENT, Enchantments.KNOCKBACK
|
||||
);
|
||||
Holder<Enchantment> registryEntry1 = entry.orElseThrow(); // Reference implements RegistryEntry, this is fine
|
||||
return EnchantmentHelper.getItemEnchantmentLevel(registryEntry1, fabricPlayer.getMainHandItem());
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable Integer getNoDamageTicks() {
|
||||
return fabricPlayer.invulnerableTime;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setVelocity(Vector3d adjustedVelocity) {
|
||||
fabricPlayer.setDeltaMovement(adjustedVelocity.x, adjustedVelocity.y, adjustedVelocity.z);
|
||||
// TODO
|
||||
// fix paper-ism? for some reason setVelocity() in paper marks the entity as hurt marked every time its called?
|
||||
fabricPlayer.hurtMarked = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Vector3d getVelocity() {
|
||||
final Vec3 fabricVelocity = fabricPlayer.getDeltaMovement();
|
||||
return new Vector3d(fabricVelocity.x, fabricVelocity.y, fabricVelocity.z);
|
||||
}
|
||||
|
||||
@Override
|
||||
public double getJumpPower() {
|
||||
double jumpVelocity = 0.42;
|
||||
MobEffectInstance jumpEffect = fabricPlayer.getEffect(MobEffects.JUMP);
|
||||
if (jumpEffect != null) {
|
||||
int amplifier = jumpEffect.getAmplifier();
|
||||
jumpVelocity += (amplifier + 1) * 0.1F;
|
||||
}
|
||||
|
||||
return jumpVelocity;
|
||||
}
|
||||
@Override
|
||||
public BoundingBox getBoundingBox() {
|
||||
AABB boundingBox = fabricPlayer.getBoundingBox();
|
||||
return new BoundingBox(boundingBox.minX, boundingBox.minY, boundingBox.minZ, boundingBox.maxX, boundingBox.minY, boundingBox.maxZ);
|
||||
}
|
||||
|
||||
@Override
|
||||
public User getUser() {
|
||||
return PacketEvents.getAPI().getPlayerManager().getUser(fabricPlayer);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setClientBrand(String brand) {
|
||||
this.clientBrand = brand;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getClientBrand() {
|
||||
return this.clientBrand;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package me.caseload.knockbacksync.scheduler;
|
||||
|
||||
import me.caseload.knockbacksync.FabricLoaderMod;
|
||||
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerTickEvents;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class FabricSchedulerAdapter implements SchedulerAdapter {
|
||||
// private final MinecraftServer server;
|
||||
private final Map<ScheduledTask, Runnable> taskMap = new HashMap<>();
|
||||
private final Map<Thread, Runnable> asyncTasks = new HashMap<>();
|
||||
|
||||
public FabricSchedulerAdapter() {
|
||||
ServerTickEvents.END_SERVER_TICK.register(this::handleTasks);
|
||||
}
|
||||
|
||||
private void handleTasks(MinecraftServer server) {
|
||||
Iterator<ScheduledTask> iterator = taskMap.keySet().iterator();
|
||||
while (iterator.hasNext()) {
|
||||
ScheduledTask task = iterator.next();
|
||||
if (server.getTickCount() >= task.nextRunTick) {
|
||||
task.task.run();
|
||||
if (task.isPeriodic) {
|
||||
task.nextRunTick = server.getTickCount() + task.period;
|
||||
} else {
|
||||
iterator.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public AbstractTaskHandle runTask(Runnable task) {
|
||||
ScheduledTask scheduledTask = new ScheduledTask(task, FabricLoaderMod.getServer().getTickCount(), 0, false);
|
||||
Runnable cancellationTask = () -> taskMap.remove(scheduledTask);
|
||||
taskMap.put(scheduledTask, cancellationTask);
|
||||
return new FabricTaskHandle(cancellationTask);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AbstractTaskHandle runTaskAsynchronously(Runnable task) {
|
||||
Thread thread = new Thread(task);
|
||||
Runnable cancellationTask = () -> {
|
||||
thread.interrupt();
|
||||
asyncTasks.remove(thread);
|
||||
};
|
||||
asyncTasks.put(thread, cancellationTask);
|
||||
thread.start();
|
||||
return new FabricTaskHandle(cancellationTask);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AbstractTaskHandle runTaskLater(Runnable task, long delayTicks) {
|
||||
ScheduledTask scheduledTask = new ScheduledTask(task, FabricLoaderMod.getServer().getTickCount() + delayTicks, 0, false);
|
||||
Runnable cancellationTask = () -> taskMap.remove(scheduledTask);
|
||||
taskMap.put(scheduledTask, cancellationTask);
|
||||
return new FabricTaskHandle(cancellationTask);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AbstractTaskHandle runTaskTimer(Runnable task, long delayTicks, long periodTicks) {
|
||||
ScheduledTask scheduledTask = new ScheduledTask(task, FabricLoaderMod.getServer().getTickCount() + delayTicks, periodTicks, true);
|
||||
Runnable cancellationTask = () -> taskMap.remove(scheduledTask);
|
||||
taskMap.put(scheduledTask, cancellationTask);
|
||||
return new FabricTaskHandle(cancellationTask);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AbstractTaskHandle runTaskLaterAsynchronously(Runnable task, long delay) {
|
||||
Thread thread = new Thread(() -> {
|
||||
try {
|
||||
Thread.sleep(delay * 50); // Convert ticks to milliseconds
|
||||
task.run();
|
||||
} catch (InterruptedException e) {
|
||||
// Handle interruption
|
||||
}
|
||||
});
|
||||
Runnable cancellationTask = () -> {
|
||||
thread.interrupt();
|
||||
asyncTasks.remove(thread);
|
||||
};
|
||||
asyncTasks.put(thread, cancellationTask);
|
||||
thread.start();
|
||||
return new FabricTaskHandle(cancellationTask);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AbstractTaskHandle runTaskTimerAsynchronously(Runnable task, long delay, long period) {
|
||||
Thread thread = new Thread(() -> {
|
||||
try {
|
||||
Thread.sleep(delay * 50); // Convert ticks to milliseconds
|
||||
while (!Thread.currentThread().isInterrupted()) {
|
||||
task.run();
|
||||
Thread.sleep(period * 50); // Convert ticks to milliseconds
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
// Handle interruption
|
||||
}
|
||||
});
|
||||
Runnable cancellationTask = () -> {
|
||||
thread.interrupt();
|
||||
asyncTasks.remove(thread);
|
||||
};
|
||||
asyncTasks.put(thread, cancellationTask);
|
||||
thread.start();
|
||||
return new FabricTaskHandle(cancellationTask);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdown() {
|
||||
// Create a new list to store the tasks that need to be executed
|
||||
List<Runnable> tasksToExecute = new ArrayList<>();
|
||||
|
||||
// Add the tasks from the taskMap to the tasksToExecute list
|
||||
tasksToExecute.addAll(taskMap.values());
|
||||
|
||||
// Add the tasks from the asyncTasks to the tasksToExecute list
|
||||
tasksToExecute.addAll(asyncTasks.values());
|
||||
|
||||
// Clear the taskMap and asyncTasks to avoid further modifications
|
||||
taskMap.clear();
|
||||
asyncTasks.clear();
|
||||
|
||||
// Execute the tasks in the tasksToExecute list
|
||||
for (Runnable task : tasksToExecute) {
|
||||
task.run();
|
||||
}
|
||||
}
|
||||
|
||||
private static class ScheduledTask {
|
||||
final Runnable task;
|
||||
final long period;
|
||||
final boolean isPeriodic;
|
||||
long nextRunTick;
|
||||
|
||||
ScheduledTask(Runnable task, long nextRunTick, long period, boolean isPeriodic) {
|
||||
this.task = task;
|
||||
this.nextRunTick = nextRunTick;
|
||||
this.period = period;
|
||||
this.isPeriodic = isPeriodic;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package me.caseload.knockbacksync.scheduler;
|
||||
|
||||
public class FabricTaskHandle implements AbstractTaskHandle {
|
||||
private final Runnable cancellationTask;
|
||||
private boolean cancelled = false;
|
||||
|
||||
public FabricTaskHandle(Runnable cancellationTask) {
|
||||
this.cancellationTask = cancellationTask;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean getCancelled() {
|
||||
return this.cancelled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cancel() {
|
||||
this.cancellationTask.run();
|
||||
this.cancelled = true;
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package me.caseload.knockbacksync.sender;
|
||||
|
||||
import me.caseload.knockbacksync.command.generic.PlayerSelector;
|
||||
import me.caseload.knockbacksync.player.FabricPlayer;
|
||||
import me.caseload.knockbacksync.player.PlatformPlayer;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
|
||||
public class FabricPlayerSelectorAdapter implements PlayerSelector {
|
||||
private final org.incendo.cloud.minecraft.modded.data.SinglePlayerSelector fabricSelector;
|
||||
|
||||
public FabricPlayerSelectorAdapter(org.incendo.cloud.minecraft.modded.data.SinglePlayerSelector fabricSelector) {
|
||||
this.fabricSelector = fabricSelector;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSingle() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlatformPlayer getSinglePlayer() {
|
||||
return new FabricPlayer(fabricSelector.single()); // Assuming your ServerPlayer can be cast to Player
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<PlatformPlayer> getPlayers() {
|
||||
return Collections.singletonList(new FabricPlayer(fabricSelector.single())); // Assuming your ServerPlayer can be cast to Player
|
||||
}
|
||||
|
||||
@Override
|
||||
public String inputString() {
|
||||
return fabricSelector.inputString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package me.caseload.knockbacksync.sender;
|
||||
|
||||
import me.caseload.knockbacksync.command.generic.AbstractPlayerSelectorParser;
|
||||
import me.caseload.knockbacksync.command.generic.PlayerSelector;
|
||||
import org.incendo.cloud.context.CommandContext;
|
||||
import org.incendo.cloud.minecraft.modded.parser.VanillaArgumentParsers;
|
||||
import org.incendo.cloud.parser.ParserDescriptor;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
public class FabricPlayerSelectorParser<C> extends AbstractPlayerSelectorParser<C> {
|
||||
|
||||
@Override
|
||||
public ParserDescriptor<C, PlayerSelector> descriptor() {
|
||||
return createDescriptor();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ParserDescriptor<C, ?> getPlatformSpecificDescriptor() {
|
||||
return VanillaArgumentParsers.singlePlayerSelectorParser();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected CompletableFuture<PlayerSelector> adaptToCommonSelector(CommandContext<C> context, Object platformSpecificSelector) {
|
||||
return CompletableFuture.completedFuture(new FabricPlayerSelectorAdapter((org.incendo.cloud.minecraft.modded.data.SinglePlayerSelector) platformSpecificSelector));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package me.caseload.knockbacksync.sender;
|
||||
|
||||
import me.caseload.knockbacksync.FabricBase;
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.mixin.CommandStackSourceAccessor;
|
||||
import me.caseload.knockbacksync.permission.FabricPermissionChecker;
|
||||
import net.minecraft.commands.CommandSource;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.server.rcon.RconConsoleSource;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.incendo.cloud.SenderMapper;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public class FabricSenderFactory extends SenderFactory<FabricBase, CommandSourceStack> implements SenderMapper<CommandSourceStack, Sender> {
|
||||
private final FabricBase plugin;
|
||||
|
||||
public FabricSenderFactory(FabricBase kbSyncFabricBase) {
|
||||
super(kbSyncFabricBase);
|
||||
this.plugin = kbSyncFabricBase;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected FabricBase getPlugin() {
|
||||
return this.plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected UUID getUniqueId(CommandSourceStack commandSource) {
|
||||
if (commandSource.getEntity() != null) {
|
||||
return commandSource.getEntity().getUUID();
|
||||
}
|
||||
return Sender.CONSOLE_UUID;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getName(CommandSourceStack commandSource) {
|
||||
String name = commandSource.getTextName();
|
||||
if (commandSource.getEntity() != null && name.equals("Server")) {
|
||||
return Sender.CONSOLE_NAME;
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void sendMessage(CommandSourceStack sender, String message) {
|
||||
// final Locale locale;
|
||||
// if (sender.getEntity() instanceof ServerPlayer) {
|
||||
// String language = ((ServerPlayer) sender.getEntity()).clientInformation().language();
|
||||
// locale = language == null ? null : TranslationManager.parseLocale(language);
|
||||
// } else {
|
||||
// locale = null;
|
||||
// }
|
||||
// sender.sendFeedback(() -> toNativeText(TranslationManager.render(message, locale)), false);
|
||||
sender.sendSuccess(() -> Component.literal(message), false);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean hasPermission(CommandSourceStack commandSource, String node) {
|
||||
return ((FabricPermissionChecker) Base.INSTANCE.getPermissionChecker()).hasPermission(commandSource, node);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean hasPermission(CommandSourceStack commandSource, String node, boolean defaultIfUnset) {
|
||||
return ((FabricPermissionChecker) Base.INSTANCE.getPermissionChecker()).hasPermission(commandSource, node, defaultIfUnset);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void performCommand(CommandSourceStack sender, String command) {
|
||||
// sender.getServer().getCommandManager().executeWithPrefix(sender, command);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean isConsole(CommandSourceStack sender) {
|
||||
CommandSource output = ((CommandStackSourceAccessor) sender).getSource();
|
||||
return output == sender.getServer() || // Console
|
||||
output.getClass() == RconConsoleSource.class || // Rcon
|
||||
(output == CommandSource.NULL && sender.getTextName().equals("")); // Functions
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Sender map(@NonNull CommandSourceStack base) {
|
||||
return this.wrap(base);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull CommandSourceStack reverse(@NonNull Sender mapped) {
|
||||
return this.unwrap(mapped);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws Exception {
|
||||
|
||||
}
|
||||
|
||||
// public static Text toNativeText(Component component) {
|
||||
// return Text.Serialization.fromJsonTree(GsonComponentSerializer.gson().serializeToTree(component), DynamicRegistryManager.EMPTY);
|
||||
// }
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package me.caseload.knockbacksync.stats.custom;
|
||||
|
||||
import org.yaml.snakeyaml.DumperOptions;
|
||||
import org.yaml.snakeyaml.Yaml;
|
||||
import net.fabricmc.loader.api.FabricLoader;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
public class BStatsConfig {
|
||||
private static final String HEADER = """
|
||||
# bStats (https://bStats.org) collects some basic information for plugin authors, like how
|
||||
# many people use their plugin and their total player count. It's recommended to keep bStats
|
||||
# enabled, but if you're not comfortable with this, you can turn this setting off. There is no
|
||||
# performance penalty associated with having metrics enabled, and data sent to bStats is fully
|
||||
# anonymous.
|
||||
""";
|
||||
|
||||
public static Config loadConfig() {
|
||||
File bStatsFolder = new File(FabricLoader.getInstance().getConfigDir().toString(), "bStats");
|
||||
File configFile = new File(bStatsFolder, "config.yml");
|
||||
|
||||
DumperOptions options = new DumperOptions();
|
||||
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
|
||||
options.setPrettyFlow(true);
|
||||
Yaml yaml = new Yaml(options);
|
||||
|
||||
Map<String, Object> data;
|
||||
Config config = new Config();
|
||||
|
||||
try {
|
||||
if (!configFile.exists()) {
|
||||
bStatsFolder.mkdirs();
|
||||
|
||||
// Create default config
|
||||
data = new LinkedHashMap<>();
|
||||
data.put("enabled", true);
|
||||
data.put("serverUuid", UUID.randomUUID().toString());
|
||||
data.put("logFailedRequests", false);
|
||||
data.put("logSentData", false);
|
||||
data.put("logResponseStatusText", false);
|
||||
|
||||
// Write config with header
|
||||
try (Writer writer = new OutputStreamWriter(new FileOutputStream(configFile), StandardCharsets.UTF_8)) {
|
||||
writer.write(HEADER);
|
||||
yaml.dump(data, writer);
|
||||
}
|
||||
} else {
|
||||
// Load existing config
|
||||
data = yaml.load(new FileInputStream(configFile));
|
||||
if (data == null) {
|
||||
data = new LinkedHashMap<>();
|
||||
}
|
||||
}
|
||||
|
||||
// Map the data to Config object
|
||||
config.enabled = getBoolean(data, "enabled", true);
|
||||
config.serverUuid = getString(data, "serverUuid", UUID.randomUUID().toString());
|
||||
config.logFailedRequests = getBoolean(data, "logFailedRequests", false);
|
||||
config.logSentData = getBoolean(data, "logSentData", false);
|
||||
config.logResponseStatusText = getBoolean(data, "logResponseStatusText", false);
|
||||
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
// Fallback to default values
|
||||
config.enabled = true;
|
||||
config.serverUuid = UUID.randomUUID().toString();
|
||||
config.logFailedRequests = false;
|
||||
config.logSentData = false;
|
||||
config.logResponseStatusText = false;
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
private static boolean getBoolean(Map<String, Object> map, String key, boolean defaultValue) {
|
||||
Object value = map.get(key);
|
||||
return value instanceof Boolean ? (Boolean) value : defaultValue;
|
||||
}
|
||||
|
||||
private static String getString(Map<String, Object> map, String key, String defaultValue) {
|
||||
Object value = map.get(key);
|
||||
return value instanceof String ? (String) value : defaultValue;
|
||||
}
|
||||
|
||||
// Your existing Config class
|
||||
public static class Config {
|
||||
public boolean enabled = true;
|
||||
public String serverUuid;
|
||||
public boolean logFailedRequests = false;
|
||||
public boolean logSentData = false;
|
||||
public boolean logResponseStatusText = false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package me.caseload.knockbacksync.stats.custom;
|
||||
|
||||
import me.caseload.knockbacksync.Base;
|
||||
|
||||
public class FabricStatsManager extends StatsManager {
|
||||
public FabricStatsManager() {
|
||||
super(new MetricsFabric(23568));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package me.caseload.knockbacksync.stats.custom;
|
||||
|
||||
/*
|
||||
* This Metrics class was auto-generated and can be copied into your project if you are
|
||||
* not using a build tool like Gradle or Maven for dependency management.
|
||||
*
|
||||
* IMPORTANT: You are not allowed to modify this class, except changing the package.
|
||||
*
|
||||
* Disallowed modifications include but are not limited to:
|
||||
* - Remove the option for users to opt-out
|
||||
* - Change the frequency for data submission
|
||||
* - Obfuscate the code (every obfuscator should allow you to make an exception for specific files)
|
||||
* - Reformat the code (if you use a linter, add an exception)
|
||||
*
|
||||
* Violations will result in a ban of your plugin and account from bStats.
|
||||
*/
|
||||
|
||||
import me.caseload.knockbacksync.FabricLoaderMod;
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.stats.CustomChart;
|
||||
import me.caseload.knockbacksync.stats.JsonObjectBuilder;
|
||||
import net.fabricmc.loader.api.FabricLoader;
|
||||
|
||||
import java.util.logging.Level;
|
||||
|
||||
public class MetricsFabric implements Metrics {
|
||||
|
||||
private final MetricsBase metricsBase;
|
||||
|
||||
/**
|
||||
* Creates a new Metrics instance.
|
||||
*
|
||||
* @param serviceId The id of the service. It can be found at <a
|
||||
* href="https://bstats.org/what-is-my-plugin-id">What is my plugin id?</a>
|
||||
*/
|
||||
public MetricsFabric(int serviceId) {
|
||||
// Get the config file
|
||||
BStatsConfig.Config config = BStatsConfig.loadConfig();
|
||||
|
||||
// Load the data
|
||||
boolean enabled = config.enabled;
|
||||
String serverUUID = config.serverUuid;
|
||||
boolean logErrors = config.logFailedRequests;
|
||||
boolean logSentData = config.logSentData;
|
||||
boolean logResponseStatusText = config.logResponseStatusText;
|
||||
|
||||
metricsBase =
|
||||
new // See https://github.com/Bastian/bstats-metrics/pull/126
|
||||
// See https://github.com/Bastian/bstats-metrics/pull/126
|
||||
// See https://github.com/Bastian/bstats-metrics/pull/126
|
||||
// See https://github.com/Bastian/bstats-metrics/pull/126
|
||||
// See https://github.com/Bastian/bstats-metrics/pull/126
|
||||
// See https://github.com/Bastian/bstats-metrics/pull/126
|
||||
// See https://github.com/Bastian/bstats-metrics/pull/126
|
||||
MetricsBase(
|
||||
"fabric",
|
||||
serverUUID,
|
||||
serviceId,
|
||||
enabled,
|
||||
this::appendPlatformData,
|
||||
this::appendServiceData,
|
||||
submitDataTask -> Base.INSTANCE.getScheduler().runTask(submitDataTask),
|
||||
() -> true,
|
||||
(message, error) -> Base.INSTANCE.getLogger().log(Level.WARNING, message, error),
|
||||
(message) -> Base.INSTANCE.getLogger().log(Level.INFO, message),
|
||||
logErrors,
|
||||
logSentData,
|
||||
logResponseStatusText,
|
||||
false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shuts down the underlying scheduler service.
|
||||
*/
|
||||
public void shutdown() {
|
||||
metricsBase.shutdown();
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a custom chart.
|
||||
*
|
||||
* @param chart The chart to add.
|
||||
*/
|
||||
public void addCustomChart(CustomChart chart) {
|
||||
metricsBase.addCustomChart(chart);
|
||||
}
|
||||
|
||||
private void appendPlatformData(JsonObjectBuilder builder) {
|
||||
builder.appendField("playerAmount", getPlayerAmount());
|
||||
builder.appendField("onlineMode", FabricLoaderMod.getServer().usesAuthentication() ? 0 : 1);
|
||||
builder.appendField("bukkitVersion", "Fabric " + FabricLoader.getInstance().getModContainer("fabricloader").get().getMetadata().getVersion().getFriendlyString() + " (MC: " + FabricLoaderMod.getServer().getServerVersion() + ")");
|
||||
builder.appendField("bukkitName", "Fabric");
|
||||
builder.appendField("javaVersion", System.getProperty("java.version"));
|
||||
builder.appendField("osName", System.getProperty("os.name"));
|
||||
builder.appendField("osArch", System.getProperty("os.arch"));
|
||||
builder.appendField("osVersion", System.getProperty("os.version"));
|
||||
builder.appendField("coreCount", Runtime.getRuntime().availableProcessors());
|
||||
}
|
||||
|
||||
private void appendServiceData(JsonObjectBuilder builder) {
|
||||
builder.appendField("pluginVersion", FabricLoader.getInstance().getModContainer("knockbacksync").get().getMetadata().getVersion().getFriendlyString());
|
||||
}
|
||||
|
||||
private int getPlayerAmount() {
|
||||
if (FabricLoaderMod.getServer().isRunning()) {
|
||||
return FabricLoaderMod.getServer().getPlayerCount();
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package me.caseload.knockbacksync.util;
|
||||
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.network.chat.Component;
|
||||
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class CommandUtil {
|
||||
|
||||
public static void sendSuccessMessage(CommandContext<CommandSourceStack> context, String message) {
|
||||
sendSuccessMessage(context, () -> getComponent(message), false);
|
||||
}
|
||||
|
||||
public static void sendSuccessMessage(CommandContext<CommandSourceStack> context, String message, boolean allowLogging) {
|
||||
sendSuccessMessage(context, () -> getComponent(message), allowLogging);
|
||||
}
|
||||
|
||||
public static void sendSuccessMessage(CommandContext<CommandSourceStack> context, Component message) {
|
||||
sendSuccessMessage(context, () -> message, false);
|
||||
}
|
||||
|
||||
public static void sendSuccessMessage(CommandContext<CommandSourceStack> context, Component message, boolean allowLogging) {
|
||||
sendSuccessMessage(context, () -> message, allowLogging);
|
||||
}
|
||||
|
||||
public static void sendSuccessMessage(CommandContext<CommandSourceStack> context, Supplier<Component> messageSupplier) {
|
||||
sendSuccessMessage(context, messageSupplier, false);
|
||||
}
|
||||
|
||||
public static void sendSuccessMessage(CommandContext<CommandSourceStack> context, Supplier<Component> messageSupplier, boolean allowLogging) {
|
||||
context.getSource().sendSuccess(messageSupplier, allowLogging);
|
||||
}
|
||||
|
||||
public static void sendFailureMessage(CommandContext<CommandSourceStack> context, String message) {
|
||||
sendFailureMessage(context, getComponent(message));
|
||||
}
|
||||
|
||||
public static void sendFailureMessage(CommandContext<CommandSourceStack> context, Component message) {
|
||||
context.getSource().sendFailure(message);
|
||||
}
|
||||
|
||||
public static Component getComponent(String message) {
|
||||
return Component.literal(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package me.caseload.knockbacksync.util;
|
||||
|
||||
import me.caseload.knockbacksync.Base;
|
||||
import me.caseload.knockbacksync.ConfigWrapper;
|
||||
import me.caseload.knockbacksync.mixin.UpdateIntervalAccessor;
|
||||
import net.minecraft.server.level.ChunkMap;
|
||||
import net.minecraft.server.level.ServerChunkCache;
|
||||
import net.minecraft.server.level.ServerEntity;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class CustomUpdateIntervals {
|
||||
private static final Map<String, Integer> entityIntervals = new HashMap<>();
|
||||
|
||||
public static void setInterval(String entityType, int interval) {
|
||||
entityIntervals.put(entityType, interval);
|
||||
}
|
||||
|
||||
public static int getInterval(String entityType, int defaultInterval) {
|
||||
return entityIntervals.getOrDefault(entityType, defaultInterval);
|
||||
}
|
||||
|
||||
public static void clear() {
|
||||
entityIntervals.clear();
|
||||
}
|
||||
|
||||
public static void updateIntervals(ServerLevel level, Map<String, Integer> entityIntervals) {
|
||||
for (Entity entity : level.getAllEntities()) {
|
||||
String entityType = entity.getType().builtInRegistryHolder().getRegisteredName();
|
||||
if (entityIntervals.containsKey(entityType)) {
|
||||
ChunkMap.TrackedEntity serverEntity = ((ServerChunkCache) entity.level().getChunkSource()).chunkMap.entityMap.get(entity.getId());
|
||||
if (serverEntity != null) {
|
||||
((UpdateIntervalAccessor) serverEntity).setUpdateInterval(entityIntervals.get(entityType));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static Map<String, Integer> loadEntityIntervalsFromConfig() {
|
||||
Map<String, Integer> intervals = new HashMap<>();
|
||||
ConfigWrapper config = Base.INSTANCE.getConfigManager().getConfigWrapper();
|
||||
|
||||
String basePath = "entity_update_intervals";
|
||||
if (config.contains(basePath)) {
|
||||
for (String entityType : config.getKeys(basePath)) {
|
||||
int interval = config.getInt(basePath + "." + entityType, -1);
|
||||
if (interval > 0) {
|
||||
intervals.put(entityType, interval);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return intervals;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package me.caseload.knockbacksync.world;
|
||||
|
||||
import me.caseload.knockbacksync.FabricLoaderMod;
|
||||
import me.caseload.knockbacksync.player.FabricPlayer;
|
||||
import me.caseload.knockbacksync.player.PlatformPlayer;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class FabricServer implements PlatformServer {
|
||||
public Collection<PlatformPlayer> getOnlinePlayers() {
|
||||
return FabricLoaderMod.getServer().getPlayerList().getPlayers().stream()
|
||||
.map(FabricPlayer::new)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlatformPlayer getPlayer(UUID uuid) {
|
||||
return new FabricPlayer(FabricLoaderMod.getServer().getPlayerList().getPlayer(uuid));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package me.caseload.knockbacksync.world;
|
||||
|
||||
import com.github.retrooper.packetevents.protocol.world.BlockFace;
|
||||
import com.github.retrooper.packetevents.protocol.world.states.WrappedBlockState;
|
||||
import com.github.retrooper.packetevents.util.Vector3d;
|
||||
import com.github.retrooper.packetevents.util.Vector3i;
|
||||
import me.caseload.knockbacksync.world.raytrace.FluidHandling;
|
||||
import me.caseload.knockbacksync.world.raytrace.RayTraceResult;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.level.ClipContext;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.phys.BlockHitResult;
|
||||
import net.minecraft.world.phys.HitResult;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
import net.minecraft.world.phys.shapes.CollisionContext;
|
||||
|
||||
public class FabricWorld implements PlatformWorld {
|
||||
private final Level world;
|
||||
|
||||
public FabricWorld(Level world) {
|
||||
this.world = world;
|
||||
}
|
||||
|
||||
@Override
|
||||
public WrappedBlockState getBlockStateAt(int x, int y, int z) {
|
||||
BlockState blockState = this.world.getBlockState(new BlockPos(x, y, z));
|
||||
return WrappedBlockState.getByGlobalId(Block.BLOCK_STATE_REGISTRY.getId(blockState));
|
||||
}
|
||||
|
||||
@Override
|
||||
public WrappedBlockState getBlockStateAt(Vector3d loc) {
|
||||
return getBlockStateAt((int) Math.floor(loc.x), (int) Math.floor(loc.x), (int) Math.floor(loc.x));
|
||||
}
|
||||
|
||||
@Override
|
||||
public RayTraceResult rayTraceBlocks(Vector3d start, Vector3d direction, double maxDistance, FluidHandling fluidHandling, boolean ignorePassableBlocks) {
|
||||
Vec3 startVec = new Vec3(start.getX(), start.getY(), start.getZ());
|
||||
Vec3 endVec = startVec.add(direction.getX() * maxDistance, direction.getY() * maxDistance, direction.getZ() * maxDistance);
|
||||
|
||||
BlockHitResult result = world.clip(new ClipContext(
|
||||
startVec,
|
||||
endVec,
|
||||
ClipContext.Block.OUTLINE,
|
||||
fluidHandling == FluidHandling.NONE ? ClipContext.Fluid.NONE :
|
||||
fluidHandling == FluidHandling.SOURCE_ONLY ? ClipContext.Fluid.SOURCE_ONLY :
|
||||
ClipContext.Fluid.ANY,
|
||||
CollisionContext.empty()
|
||||
));
|
||||
|
||||
if (result.getType() == HitResult.Type.MISS) return null;
|
||||
|
||||
Vec3 hitLocation = result.getLocation();
|
||||
BlockPos blockPos = result.getBlockPos();
|
||||
return new RayTraceResult(
|
||||
new Vector3d(hitLocation.x, hitLocation.y, hitLocation.z),
|
||||
BlockFace.getBlockFaceByValue(result.getDirection().ordinal()),
|
||||
new Vector3i(blockPos.getX(), blockPos.getY(), blockPos.getZ()),
|
||||
getBlockStateAt(blockPos.getX(), blockPos.getY(), blockPos.getZ())
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"id": "knockbacksync",
|
||||
"version": "${version}",
|
||||
"name": "Knockback Sync",
|
||||
"description": "",
|
||||
"authors": [],
|
||||
"contact": {},
|
||||
"license": "All-Rights-Reserved",
|
||||
"icon": "assets/knockbacksync/icon.png",
|
||||
"environment": "*",
|
||||
"entrypoints": {
|
||||
"main": [
|
||||
"me.caseload.knockbacksync.FabricLoaderMod"
|
||||
]
|
||||
},
|
||||
"mixins": [
|
||||
"knockbacksync.mixins.json"
|
||||
],
|
||||
"depends": {
|
||||
"fabricloader": ">=${loader_version}",
|
||||
"fabric": "*",
|
||||
"minecraft": "~${minecraft_version}",
|
||||
"packetevents": "*"
|
||||
},
|
||||
"accessWidener": "knockbacksync.accesswidener"
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
accessWidener v2 named
|
||||
|
||||
# We don't actually need this right now, but it's useful to keep an access widener around for when we do need one
|
||||
accessible field net/minecraft/server/level/ChunkMap entityMap Lit/unimi/dsi/fastutil/ints/Int2ObjectMap;
|
||||
accessible class net/minecraft/server/level/ChunkMap$TrackedEntity
|
||||
accessible method net/minecraft/server/level/ChunkMap$TrackedEntity updatePlayers (Ljava/util/List;)V
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"required": true,
|
||||
"minVersion": "0.8",
|
||||
"package": "me.caseload.knockbacksync.mixin",
|
||||
"compatibilityLevel": "JAVA_21",
|
||||
"mixins": [
|
||||
"ChunkMapMixin",
|
||||
"CommandStackSourceAccessor",
|
||||
"PlayerMixin",
|
||||
"ServerEntityMixin",
|
||||
"TickRateManagerMixin"
|
||||
],
|
||||
"injectors": {
|
||||
"defaultRequire": 1
|
||||
}
|
||||
}
|
||||
+16
-4
@@ -2,8 +2,20 @@
|
||||
org.gradle.jvmargs=-Xmx3G
|
||||
org.gradle.parallel=true
|
||||
|
||||
# Plugin Properties
|
||||
maven_group=me.caseload
|
||||
archives_base_name=knockbacksync-og
|
||||
# Fabric Properties
|
||||
# check these on https://modmuss50.me/fabric.html
|
||||
minecraft_version=1.21
|
||||
parchment_mappings=2024.07.28
|
||||
parchment_minecraft_version=1.21
|
||||
yarn_mappings=1.21+build.9
|
||||
loader_version=0.15.11
|
||||
|
||||
githubRepo=CASELOAD7000/knockback-sync
|
||||
# Mod Properties
|
||||
maven_group=me.caseload
|
||||
archives_base_name=knockbacksync
|
||||
|
||||
# Dependencies
|
||||
# check this on https://modmuss50.me/fabric.html
|
||||
fabric_version=0.102.0+1.21
|
||||
|
||||
githubRepo=CASELOAD7000/knockback-sync
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.0-bin.zip
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
|
||||
+2
-2
@@ -7,6 +7,6 @@ pluginManagement {
|
||||
}
|
||||
}
|
||||
|
||||
include("common", "bukkit")
|
||||
include("common", "fabric", "bukkit")
|
||||
|
||||
rootProject.name = "KnockbackSync-OG"
|
||||
rootProject.name = "KnockbackSync"
|
||||
Reference in new issue
Block a user