diff --git a/.github/workflows/build-dev.yml b/.github/workflows/build-dev.yml deleted file mode 100644 index 0d1e17f..0000000 --- a/.github/workflows/build-dev.yml +++ /dev/null @@ -1,137 +0,0 @@ -name: Build and Version Update - -on: - push: - branches: - - dev - -jobs: - build: - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v2 - - - name: Set up JDK - uses: actions/setup-java@v2 - with: - java-version: '21' # or your preferred Java version - distribution: 'adopt' - - - name: Generate build number - id: buildnumber - uses: einaregilsson/build-number@v3 - with: - token: ${{ secrets.GITHUB_TOKEN }} - - - name: Update version in pom.xml and plugin.yml - id: update_version - run: | - VERSION=$(mvn help:evaluate -Dexpression=project.version -q -DforceStdout) - IFS='.' read -ra VERSION_PARTS <<< "$VERSION" - PATCH=$((VERSION_PARTS[2] + 1)) - NEW_VERSION="${VERSION_PARTS[0]}.${VERSION_PARTS[1]}.$PATCH-dev-axionize-b${{ steps.buildnumber.outputs.build_number }}" - echo "NEW_VERSION=${NEW_VERSION}" >> $GITHUB_ENV - - # Extract the current timestamp - CURRENT_TIMESTAMP=$(mvn help:evaluate -Dexpression=project.build.outputTimestamp -q -DforceStdout) - - # Update version while preserving the timestamp - mvn versions:set -DnewVersion=$NEW_VERSION -DgenerateBackupPoms=false \ - -DprocessAllModules=true -DupdateMatchingVersions=true \ - -DoldProperty=project.version -DnewProperty=project.version - - # Manually update the outputTimestamp to preserve it - mvn versions:set-property -Dproperty=project.build.outputTimestamp -DnewVersion="$CURRENT_TIMESTAMP" -DgenerateBackupPoms=false - - sed -i "s/^version: .*$/version: $NEW_VERSION/" src/main/resources/plugin.yml - - - name: Build with Maven - run: mvn clean package - - # 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 target/KnockbackSync-${{ 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 - ORIGINAL_HASH=$(sha256sum target/KnockbackSync-${{ 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-${{ env.NEW_VERSION }}.jar | awk '{print $1}') - echo "REMAPPED_HASH=$REMAPPED_HASH" >> $GITHUB_ENV - - # Download, update, and re-upload dev-builds.txt - - name: Update dev-builds.txt - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - # Get the latest release information - LATEST_RELEASE=$(curl -s -H "Authorization: token $GITHUB_TOKEN" \ - "https://api.github.com/repos/CASELOAD7000/knockback-sync/releases/latest") - RELEASE_ID=$(echo $LATEST_RELEASE | jq -r .id) - RELEASE_TAG=$(echo $LATEST_RELEASE | jq -r .tag_name) - - # Download the current dev-builds.txt - curl -L -o dev-builds.txt "https://github.com/CASELOAD7000/knockback-sync/releases/download/$RELEASE_TAG/dev-builds.txt" - - # Ensure the file ends with a newline, then append new information - sed -i -e '$a\' dev-builds.txt - echo "KnockBackSync-${{ env.NEW_VERSION }}.jar" >> dev-builds.txt - echo "${{ env.ORIGINAL_HASH }}" >> dev-builds.txt - echo "KnockBackSync-${{ env.NEW_VERSION }}-remapped.jar" >> dev-builds.txt - echo "${{ env.REMAPPED_HASH }}" >> dev-builds.txt - - # Delete the old dev-builds.txt asset - ASSET_ID=$(echo $LATEST_RELEASE | jq -r '.assets[] | select(.name == "dev-builds.txt") | .id') - if [ ! -z "$ASSET_ID" ]; then - curl -X DELETE -H "Authorization: token $GITHUB_TOKEN" \ - "https://api.github.com/repos/CASELOAD7000/knockback-sync/releases/assets/$ASSET_ID" - fi - - # Upload the new dev-builds.txt - curl -X POST -H "Authorization: token $GITHUB_TOKEN" \ - -H "Content-Type: application/octet-stream" \ - --data-binary @dev-builds.txt \ - "https://uploads.github.com/repos/CASELOAD7000/knockback-sync/releases/$RELEASE_ID/assets?name=dev-builds.txt" - - - name: Upload artifact - uses: actions/upload-artifact@v4 - with: - name: KnockbackSync-${{ env.NEW_VERSION }}.jar - path: target/KnockbackSync-${{ env.NEW_VERSION }}.jar - retention-days: 90 - - - uses: Kir-Antipov/mc-publish@v3.3 - with: - github-tag: dev - github-generate-changelog: true - github-draft: false - github-prerelease: true - github-commitish: dev - github-discussion: Announcements - github-token: ${{ secrets.GITHUB_TOKEN }} - - files: | - target/KnockbackSync-${{ env.NEW_VERSION }}.jar - - name: KnockbackSync-${{ env.NEW_VERSION }} - version: ${{ env.NEW_VERSION }} - version-type: beta - - retry-attempts: 2 - retry-delay: 10000 - fail-mode: fail \ No newline at end of file diff --git a/.github/workflows/build-gradle.yml b/.github/workflows/build-gradle.yml new file mode 100644 index 0000000..fddcfb7 --- /dev/null +++ b/.github/workflows/build-gradle.yml @@ -0,0 +1,231 @@ +name: Build and Version Update + +on: + push: + branches: + - main + - merge + - dev + - fabric-experimental-gradle + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - name: Checkout main repository + uses: actions/checkout@v2 + + - name: Set up JDK + uses: actions/setup-java@v2 + with: + java-version: '21' + distribution: 'adopt' + + - name: Setup Gradle + uses: gradle/gradle-build-action@v2 + with: + gradle-version: 8.8 + + # Temporary workaround to packetevents bugs, use custom fork build + - name: Checkout packetevents repository + uses: actions/checkout@v3 + with: + repository: Axionize/packetevents + ref: 2.0-fabric-serverside-fix + path: packetevents + + - name: Update version in packetevents + run: | + cd packetevents + sed -i 's/val fullVersion = ".*"/val fullVersion = "2.5.8"/' build.gradle.kts + + - name: Build packetevents with Gradle + run: | + cd packetevents + gradle build + + - name: Publish packetevents to Maven Local + run: | + cd packetevents + gradle publishToMavenLocal + + - name: Generate build number + id: buildnumber + uses: einaregilsson/build-number@v3 + with: + token: ${{ secrets.GITHUB_TOKEN }} + + - name: Update version in build.gradle.kts + id: update_version + run: | + # Read current fullVersion from build.gradle.kts + FULL_VERSION=$(grep 'val fullVersion =' build.gradle.kts | awk -F '"' '{print $2}') + IFS='.' read -ra VERSION_PARTS <<< "$FULL_VERSION" + PATCH=$((VERSION_PARTS[2] + 1)) + NEW_VERSION="${VERSION_PARTS[0]}.${VERSION_PARTS[1]}.$PATCH-dev-axionize-b${{ steps.buildnumber.outputs.build_number }}" + echo "NEW_VERSION=${NEW_VERSION}" >> $GITHUB_ENV + + # Update fullVersion in build.gradle + sed -i "s/val fullVersion = \".*\"/val fullVersion = \"$NEW_VERSION\"/" build.gradle.kts + + # Ensure snapshot is set to false + sed -i "s/val snapshot = .*/val snapshot = false/" build.gradle.kts + + - name: Build with Gradle + run: gradle clean build + + - 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 + + # 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 + 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 + + # Download, update, and re-upload dev-builds.txt + - name: Update dev-builds.txt + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + # Download the current dev-builds.txt + curl -L -o dev-builds.txt https://github.com/CASELOAD7000/knockback-sync/releases/latest/download/dev-builds.txt + + # Create a copy of the original file + cp dev-builds.txt dev-builds.txt.original + + # Ensure the file ends with a newline + sed -i -e '$a\' dev-builds.txt + + # Function to add hash if it doesn't exist + add_hash_if_new() { + if ! grep -q "$1" dev-builds.txt; then + echo "$1" >> dev-builds.txt + fi + } + + # Add new hashes if they don't exist + 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 + if cmp -s dev-builds.txt dev-builds.txt.original; then + echo "No changes to dev-builds.txt, skipping upload." + else + echo "Changes detected in dev-builds.txt, uploading new version." + + # Get the latest release ID + RELEASE_ID=$(curl -s "https://api.github.com/repos/CASELOAD7000/knockback-sync/releases/latest" | jq -r .id) + + # Delete the old dev-builds.txt asset + ASSET_ID=$(curl -s -H "Authorization: token $GITHUB_TOKEN" \ + "https://api.github.com/repos/CASELOAD7000/knockback-sync/releases/$RELEASE_ID/assets" | \ + jq -r '.[] | select(.name == "dev-builds.txt") | .id') + if [ ! -z "$ASSET_ID" ]; then + curl -X DELETE -H "Authorization: token $GITHUB_TOKEN" \ + "https://api.github.com/repos/CASELOAD7000/knockback-sync/releases/assets/$ASSET_ID" + fi + + # Upload the new dev-builds.txt + curl -X POST -H "Authorization: token $GITHUB_TOKEN" \ + -H "Content-Type: application/octet-stream" \ + --data-binary @dev-builds.txt \ + "https://uploads.github.com/repos/CASELOAD7000/knockback-sync/releases/$RELEASE_ID/assets?name=dev-builds.txt" + fi + + # Clean up + rm dev-builds.txt.original + + - name: Create artifacts directory + run: mkdir -p artifacts + + - name: Copy bukkit artifact + run: cp bukkit/build/libs/knockbacksync-bukkit-${{ env.NEW_VERSION }}.jar artifacts/ + + - 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-${{ env.NEW_VERSION }}.zip + path: KnockbackSync-${{ env.NEW_VERSION }}.zip + retention-days: 90 + +# - uses: Kir-Antipov/mc-publish@v3.3 +# with: +# modrinth-id: wGTbjSTq +# modrinth-featured: true +# modrinth-unfeature-mode: subset +# modrinth-token: ${{ secrets.MODRINTH_TOKEN }} +# +# files: | +# bukkit/build/libs/knockbacksync-bukkit-${{ env.NEW_VERSION }}.jar +# +# name: KnockbackSync-${{ env.NEW_VERSION }} +# version: ${{ env.NEW_VERSION }} +# version-type: beta +# +# loaders: | +# bukkit +# spigot +# paper +# folia +# +# game-versions: | +# >=1.18.2 +# +# retry-attempts: 2 +# retry-delay: 10000 +# fail-mode: fail +# +# - uses: Kir-Antipov/mc-publish@v3.3 +# with: +# modrinth-id: wGTbjSTq +# modrinth-featured: true +# modrinth-unfeature-mode: subset +# modrinth-token: ${{ secrets.MODRINTH_TOKEN }} +# +# files: | +# fabric/build/libs/knockbacksync-fabric-${{ env.NEW_VERSION }}.jar +# +# name: KnockbackSync-${{ env.NEW_VERSION }} +# version: ${{ env.NEW_VERSION }} +# version-type: beta +# +# loaders: | +# fabric +# +# game-versions: | +# >=1.21 +# +# retry-attempts: 2 +# retry-delay: 10000 +# fail-mode: fail \ No newline at end of file diff --git a/.gitignore b/.gitignore index 05e99bf..fe87af2 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,10 @@ dependency-reduced-pom.xml # Ignore maven build files target/ + + +.gradle/ +gradle/ +build/ + +run/ \ No newline at end of file diff --git a/COPYING b/COPYING deleted file mode 100644 index 871ce8e..0000000 --- a/COPYING +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. \ No newline at end of file diff --git a/KnockbackSync.iml b/KnockbackSync.iml index f553dad..eba7f7e 100644 --- a/KnockbackSync.iml +++ b/KnockbackSync.iml @@ -5,6 +5,7 @@ SPIGOT + ADVENTURE 1 diff --git a/README.md b/README.md index f1f74ba..e7ce4ca 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,10 @@ -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. -As a result, players take negative velocity when they're on the ground clientside, but not serverside. +[![Get it on Modrinth](https://img.shields.io/badge/Get%20it%20on-Modrinth-green?style=for-the-badge&logo=modrinth)](https://modrinth.com/plugin/knockbacksync) -This plugin handles knockback as if it were calculated clientside, ensuring that no player is at a disadvantage, -regardless of their own or their opponent’s connection. +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. -Showcase: https://www.youtube.com/watch?v=SVokpr3v-TA - -Official Discord: https://discord.gg/nnpqpAtyVW +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." ## Frequently Asked Questions (FAQ) ### Does this change put high ping players at a disadvantage? @@ -17,13 +13,63 @@ Official Discord: https://discord.gg/nnpqpAtyVW ### 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](src/main/java/me/caseload/knockbacksync/manager/PlayerData.java) class. +You can edit the ping offset in the `config.yml` for this plugin. +```yml: +ping_offset: 25 # Change to the offset your want +``` +Then just type +``` +/knockbacksync reload +``` +or restart your server. + +## What servers are using this plugin? +| IP | Location | Region | Ping Offset | spike_threshold | +|------------------|------------------------------------------|--------|-------------|-----------------| +| `pvparcade.club` | Ashburn, Virginia, United States | NA | 20 | 30 | +| `stray.gg` | San Francisco, California, United States | NA | 25 | 20 | +| `eu.stray.gg` | Limburg an der Lahn, Hesse, Germany | EU | 25 | 20 | +| `valed.gg` | Frankfurt, Hesse, Germany | EU | 25 | 20 | +| `eu.catpvp.xyz` | | EU | 25 | 20 | +| `as.catpvp.xyz` | | AS | 25 | 20 | +| `na.catpvp.xyz` | | NA | 25 | 20 | +| `hyperium.pl` | Wrocław, Dolnośląskie, Poland | EU | 25 | 20 | + +## Documentation +### Commands +#### **`/knockbacksync ping `** +**Description:** Displays the last ping packet time for a specified player. +**Usage:** `/knockbacksync ping ` +**Permission:** `knockbacksync.ping` +**Example:** `/knockbacksync ping Notch` +Outputs: `Notch's last ping packet took ms.` + +#### **`/knockbacksync reload`** +**Description:** Reloads the KnockbackSync configuration file. +**Usage:** `/knockbacksync reload` +**Permission:** `knockbacksync.reload` +**Example:** `/knockbacksync reload` +Outputs: `Successfully reloaded KnockbackSync config.` (or custom message from `reload_message` config) + +#### **`/knockbacksync toggle`** +**Description:** Toggles the KnockbackSync plugin on or off. Optional argument to toggle off only for a specific player. +**Usage:** `/knockbacksync toggle ` +**Permission:** `knockbacksync.toggle` +**Example 1:** `/knockbacksync toggle` +Outputs: +- Enabled: `Successfully enabled KnockbackSync.` (or custom message from `enable_message` config) +- Disabled: `Successfully disabled KnockbackSync.` (or custom message from `disable_message` config) + +**Example 2:** `/knockbacksync toggle Notch` + Outputs: +- Enabled: `Successfully enabled KnockbackSync for Notch` (or custom message from `enable_player_message` config) +- Disabled: `Successfully disabled KnockbackSync for NOtch` (or custom message from `disable_player_message` config) + +### Event Listeners +- **`KnockbackSyncConfigReloadEvent`**: Updates messages in `reload` and `toggle` commands based on the latest configuration settings. ## License GNU General Public License v3.0 or later -See [COPYING](COPYING) to see the full text. +See [LICENSE](LICENSE) to see the full text. \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..edb2175 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,55 @@ +import java.io.ByteArrayOutputStream + +plugins { + id("java") + id("com.gradleup.shadow") version "8.3.3" apply false + id("fabric-loom") version "1.7.4" apply false +} + +val fullVersion = "1.3.4" +val snapshot = true + +allprojects { + fun getVersionMeta(includeHash: Boolean): String { + if (!snapshot) { + return "" + } + 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" + } + + group = "me.caseload.knockbacksync" + version = "$fullVersion${getVersionMeta(true)}" + ext["versionNoHash"] = "$fullVersion${getVersionMeta(false)}" + + repositories { + mavenLocal() + mavenCentral() + maven("https://hub.spigotmc.org/nexus/content/repositories/snapshots/") + maven("https://repo.codemc.io/repository/maven-releases/") + maven("https://repo.opencollab.dev/maven-snapshots/") + maven("https://repo.papermc.io/repository/maven-public/") + maven(url = "https://maven.fabricmc.net/") { + name = "Fabric" + } + maven("https://libraries.minecraft.net/") + maven("https://maven.neoforged.net/releases") + } +} + +subprojects { + apply(plugin = "java") + + java { + sourceCompatibility = JavaVersion.VERSION_21 + targetCompatibility = JavaVersion.VERSION_21 + } +} diff --git a/bukkit/build.gradle.kts b/bukkit/build.gradle.kts new file mode 100644 index 0000000..a8e8765 --- /dev/null +++ b/bukkit/build.gradle.kts @@ -0,0 +1,62 @@ +plugins { + id("com.gradleup.shadow") + id("net.neoforged.moddev") version "1.0.11" +} + +base { + archivesName.set("${rootProject.property("archives_base_name")}-bukkit") +} + +val shadeThisThing: Configuration by configurations.creating { + isCanBeConsumed = true + isTransitive = true +} + +dependencies { + shadeThisThing(implementation(project(":common"))!!) + + compileOnly("org.spigotmc:spigot-api:1.18.2-R0.1-SNAPSHOT") + compileOnly("org.geysermc.floodgate:api:2.0-SNAPSHOT") + compileOnly("dev.folia:folia-api:1.20.4-R0.1-SNAPSHOT") + + compileOnly("org.projectlombok:lombok:1.18.34") + annotationProcessor("org.projectlombok:lombok:1.18.34") + + shadeThisThing(implementation("org.kohsuke:github-api:1.326") { + exclude(group = "commons-io", module = "commons-io") + exclude(group = "org.apache.commons", module = "commons-lang3") + }) + + + shadeThisThing(implementation("com.fasterxml.jackson.core:jackson-databind:2.17.2")!!) + shadeThisThing(implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.17.2")!!) + shadeThisThing(implementation("com.github.retrooper:packetevents-spigot:2.5.0")!!) + shadeThisThing(implementation("dev.jorel:commandapi-bukkit-shade:9.5.3")!!) +} + +tasks.shadowJar { +// archiveClassifier.set("dev") + configurations = listOf(shadeThisThing) + isEnableRelocation = false + relocationPrefix = "${project.property("maven_group")}.${project.property("archives_base_name")}.shaded" +} + +tasks.build { + dependsOn(tasks.shadowJar) +} + +tasks.processResources { + inputs.property("version", project.version) + filteringCharset = "UTF-8" + + filesMatching("plugin.yml") { + expand( + "version" to project.version, + ) + } +} + +neoForge { + // Look for versions on https://projects.neoforged.net/neoforged/neoform + neoFormVersion.set("1.21-20240613.152323") +} \ No newline at end of file diff --git a/bukkit/src/main/java/me/caseload/knockbacksync/KnockbackSyncPlugin.java b/bukkit/src/main/java/me/caseload/knockbacksync/KnockbackSyncPlugin.java new file mode 100644 index 0000000..ce0eb4f --- /dev/null +++ b/bukkit/src/main/java/me/caseload/knockbacksync/KnockbackSyncPlugin.java @@ -0,0 +1,140 @@ +package me.caseload.knockbacksync; + +import com.github.retrooper.packetevents.PacketEvents; +import com.mojang.brigadier.CommandDispatcher; +import dev.jorel.commandapi.*; +import io.github.retrooper.packetevents.factory.spigot.SpigotPacketEventsBuilder; +import me.caseload.knockbacksync.command.KnockbackSyncCommand; +import me.caseload.knockbacksync.listener.bukkit.BukkitPlayerJoinQuitListener; +import me.caseload.knockbacksync.listener.bukkit.BukkitPlayerDamageListener; +import me.caseload.knockbacksync.listener.bukkit.BukkitPlayerKnockbackListener; +import me.caseload.knockbacksync.permission.PermissionChecker; +import me.caseload.knockbacksync.permission.PluginPermissionChecker; +import me.caseload.knockbacksync.scheduler.BukkitSchedulerAdapter; +import me.caseload.knockbacksync.scheduler.FoliaSchedulerAdapter; +import me.caseload.knockbacksync.stats.custom.BukkitStatsManager; +import me.caseload.knockbacksync.stats.custom.PluginJarHashProvider; +import me.caseload.knockbacksync.world.BukkitServer; +import net.minecraft.commands.Commands; +import org.bukkit.Bukkit; +import org.bukkit.event.Listener; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + +import java.io.File; +import java.io.InputStream; +import java.util.logging.Logger; + +public final class KnockbackSyncPlugin extends JavaPlugin { + + private final KnockbackSyncBase core = new KnockbackSyncBase() { + + { + statsManager = new BukkitStatsManager(); + platformServer = new BukkitServer(); + pluginJarHashProvider = new PluginJarHashProvider(this.getClass().getProtectionDomain().getCodeSource().getLocation()); + } + + private final PluginPermissionChecker permissionChecker = new PluginPermissionChecker(); + + @Override + public Logger getLogger() { + return KnockbackSyncPlugin.this.getLogger(); + } + + @Override + public File getDataFolder() { + return KnockbackSyncPlugin.this.getDataFolder(); + } + + @Override + public InputStream getResource(String filename) { + return KnockbackSyncPlugin.this.getResource(filename); + } + + @Override + public void load() { + PacketEvents.setAPI(SpigotPacketEventsBuilder.build(KnockbackSyncPlugin.this)); + PacketEvents.getAPI().load(); + } + + @Override + public void enable() { + super.enable(); + initializeScheduler(); + configManager.loadConfig(false); + statsManager.init(); + checkForUpdates(); + } + + @Override + public void initializeScheduler() { + switch (platform) { + case BUKKIT: + super.scheduler = new BukkitSchedulerAdapter(KnockbackSyncPlugin.this); + break; + case FOLIA: + super.scheduler = new FoliaSchedulerAdapter(KnockbackSyncPlugin.this); + break; + } + } + + @Override + protected void registerPlatformListeners() { + registerPluginListeners( + new BukkitPlayerDamageListener(), + new BukkitPlayerKnockbackListener(), + new BukkitPlayerJoinQuitListener() + ); + } + + @Override + protected void registerCommands() { + CommandDispatcher dispatcher = Brigadier.getCommandDispatcher(); + dispatcher.register(KnockbackSyncCommand.build()); + dispatcher.register( + Commands.literal("kbsync") + .redirect(dispatcher.getRoot().getChild("knockbacksync")) + ); + } + + @Override + protected String getVersion() { + return getDescription().getVersion(); + } + + @Override + public void saveDefaultConfig() { + KnockbackSyncPlugin.this.saveDefaultConfig(); + } + + @Override + public PermissionChecker getPermissionChecker() { + return permissionChecker; + } + }; + + @Override + public void onLoad() { + CommandAPI.onLoad(new CommandAPIBukkitConfig(this)); + core.load(); + } + + @Override + public void onEnable() { + CommandAPI.onEnable(); + core.enable(); + } + + @Override + public void onDisable() { + CommandAPI.onDisable(); + PacketEvents.getAPI().terminate(); + } + + private void registerPluginListeners(Listener... listeners) { + PluginManager pluginManager = getServer().getPluginManager(); + for (Listener listener : listeners) + pluginManager.registerEvents(listener, this); + } +} \ No newline at end of file diff --git a/bukkit/src/main/java/me/caseload/knockbacksync/listener/bukkit/BukkitPlayerDamageListener.java b/bukkit/src/main/java/me/caseload/knockbacksync/listener/bukkit/BukkitPlayerDamageListener.java new file mode 100644 index 0000000..eecd984 --- /dev/null +++ b/bukkit/src/main/java/me/caseload/knockbacksync/listener/bukkit/BukkitPlayerDamageListener.java @@ -0,0 +1,18 @@ +package me.caseload.knockbacksync.listener.bukkit; + +import me.caseload.knockbacksync.listener.PlayerDamageListener; +import me.caseload.knockbacksync.player.BukkitPlayer; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class BukkitPlayerDamageListener extends PlayerDamageListener implements Listener { + + @EventHandler(ignoreCancelled = true) + public void onPlayerDamage(EntityDamageByEntityEvent event) { + if ((event.getEntity() instanceof Player victim) && (event.getDamager() instanceof Player attacker)) + onPlayerDamage(new BukkitPlayer(victim), new BukkitPlayer(attacker)); + + } +} \ No newline at end of file diff --git a/bukkit/src/main/java/me/caseload/knockbacksync/listener/bukkit/BukkitPlayerJoinQuitListener.java b/bukkit/src/main/java/me/caseload/knockbacksync/listener/bukkit/BukkitPlayerJoinQuitListener.java new file mode 100644 index 0000000..809cd89 --- /dev/null +++ b/bukkit/src/main/java/me/caseload/knockbacksync/listener/bukkit/BukkitPlayerJoinQuitListener.java @@ -0,0 +1,22 @@ +package me.caseload.knockbacksync.listener.bukkit; + +import me.caseload.knockbacksync.listener.PlayerJoinQuitListener; +import me.caseload.knockbacksync.manager.PlayerData; +import me.caseload.knockbacksync.player.BukkitPlayer; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerQuitEvent; + +public class BukkitPlayerJoinQuitListener extends PlayerJoinQuitListener implements Listener { + + @EventHandler + public void onPlayerJoin(PlayerJoinEvent event) { + onPlayerJoin(new PlayerData(new BukkitPlayer(event.getPlayer()))); + } + + @EventHandler + public void onPlayerQuit(PlayerQuitEvent event) { + onPlayerQuit(event.getPlayer().getUniqueId()); + } +} diff --git a/bukkit/src/main/java/me/caseload/knockbacksync/listener/bukkit/BukkitPlayerKnockbackListener.java b/bukkit/src/main/java/me/caseload/knockbacksync/listener/bukkit/BukkitPlayerKnockbackListener.java new file mode 100644 index 0000000..eeaae41 --- /dev/null +++ b/bukkit/src/main/java/me/caseload/knockbacksync/listener/bukkit/BukkitPlayerKnockbackListener.java @@ -0,0 +1,37 @@ +package me.caseload.knockbacksync.listener.bukkit; + +import com.github.retrooper.packetevents.util.Vector3d; +import me.caseload.knockbacksync.listener.PlayerKnockbackListener; +import me.caseload.knockbacksync.player.BukkitPlayer; +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; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.player.PlayerVelocityEvent; +import org.bukkit.util.Vector; + +public class BukkitPlayerKnockbackListener extends PlayerKnockbackListener implements Listener { + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onPlayerVelocity(PlayerVelocityEvent event) { + Player victim = event.getPlayer(); + EntityDamageEvent entityDamageEvent = victim.getLastDamageCause(); + if (entityDamageEvent == null) + return; + + EntityDamageEvent.DamageCause damageCause = entityDamageEvent.getCause(); + if (damageCause != EntityDamageEvent.DamageCause.ENTITY_ATTACK) + return; + + Entity attacker = ((EntityDamageByEntityEvent) entityDamageEvent).getDamager(); + if (!(attacker instanceof Player)) + return; + + Vector vector = event.getVelocity(); + onPlayerVelocity(new BukkitPlayer(victim), new Vector3d(vector.getX(), vector.getY(), vector.getZ())); +// callback.setVelocity(victim.getVelocity()); // Update the callback's velocity in Spigot + } +} \ No newline at end of file diff --git a/bukkit/src/main/java/me/caseload/knockbacksync/permission/PluginPermissionChecker.java b/bukkit/src/main/java/me/caseload/knockbacksync/permission/PluginPermissionChecker.java new file mode 100644 index 0000000..0fe88b3 --- /dev/null +++ b/bukkit/src/main/java/me/caseload/knockbacksync/permission/PluginPermissionChecker.java @@ -0,0 +1,33 @@ +package me.caseload.knockbacksync.permission; + +import lombok.SneakyThrows; +import me.caseload.knockbacksync.player.BukkitPlayer; +import me.caseload.knockbacksync.player.PlatformPlayer; +import net.minecraft.commands.CommandSourceStack; +import org.bukkit.command.CommandSender; + +import java.lang.reflect.Method; + +public class PluginPermissionChecker implements PermissionChecker { + + Method getBukkitSenderMethod; + + public PluginPermissionChecker() { + try { + getBukkitSenderMethod = CommandSourceStack.class.getMethod("getBukkitSender"); + } catch (NoSuchMethodException e) { + e.printStackTrace(); + } + } + + @SneakyThrows + @Override + public boolean hasPermission(CommandSourceStack source, String s, boolean defaultIfUnset) { + return ((CommandSender) getBukkitSenderMethod.invoke(source)).hasPermission(s); + } + + @Override + public boolean hasPermission(PlatformPlayer platformPlayer, String s) { + return ((BukkitPlayer) platformPlayer).bukkitPlayer.hasPermission(s); + } +} diff --git a/bukkit/src/main/java/me/caseload/knockbacksync/player/BukkitPlayer.java b/bukkit/src/main/java/me/caseload/knockbacksync/player/BukkitPlayer.java new file mode 100644 index 0000000..8dd2b7c --- /dev/null +++ b/bukkit/src/main/java/me/caseload/knockbacksync/player/BukkitPlayer.java @@ -0,0 +1,112 @@ +package me.caseload.knockbacksync.player; + +import com.github.retrooper.packetevents.util.Vector3d; +import me.caseload.knockbacksync.world.PlatformWorld; +import me.caseload.knockbacksync.world.SpigotWorld; +import org.bukkit.Location; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.UUID; + +public class BukkitPlayer implements PlatformPlayer { + public final Player bukkitPlayer; + + public BukkitPlayer(Player player) { + this.bukkitPlayer = player; + } + + @Override + public UUID getUUID() { + return bukkitPlayer.getUniqueId(); + } + + @Override + public String getName() { + return bukkitPlayer.getName(); + } + + @Override + public double getX() { + return bukkitPlayer.getLocation().getX(); + } + + @Override + public double getY() { + return bukkitPlayer.getLocation().getY(); + } + + @Override + public double getZ() { + return bukkitPlayer.getLocation().getZ(); + } + + @Override + public float getPitch() { + return bukkitPlayer.getLocation().getPitch(); + } + + @Override + public float getYaw() { + return bukkitPlayer.getLocation().getYaw(); + } + + @Override + public boolean isOnGround() { + return bukkitPlayer.isOnGround(); + } + + @Override + public int getPing() { + return bukkitPlayer.getPing(); + } + + @Override + public boolean isGliding() { + return bukkitPlayer.isGliding(); + } + + @Override + public PlatformWorld getWorld() { + return new SpigotWorld(bukkitPlayer.getWorld()); + } + + @Override + public Vector3d getLocation() { + Location location = bukkitPlayer.getLocation(); + return new Vector3d(location.getX(), location.getY(), location.getZ()); + } + + @Override + public void sendMessage(@NotNull String s) { + bukkitPlayer.sendMessage(s); + } + + @Override + public double getAttackCooldown() { + return bukkitPlayer.getAttackCooldown(); + } + + @Override + public boolean isSprinting() { + return bukkitPlayer.isSprinting(); + } + + @Override + public int getMainHandKnockbackLevel() { + return bukkitPlayer.getInventory().getItemInMainHand().getEnchantmentLevel(Enchantment.KNOCKBACK); + } + + @Override + public @Nullable Integer getNoDamageTicks() { + return bukkitPlayer.getNoDamageTicks(); + } + + @Override + public void setVelocity(Vector3d adjustedVelocity) { + bukkitPlayer.setVelocity(new Vector(adjustedVelocity.x, adjustedVelocity.y, adjustedVelocity.z)); + } +} \ No newline at end of file diff --git a/bukkit/src/main/java/me/caseload/knockbacksync/scheduler/BukkitSchedulerAdapter.java b/bukkit/src/main/java/me/caseload/knockbacksync/scheduler/BukkitSchedulerAdapter.java new file mode 100644 index 0000000..5caa325 --- /dev/null +++ b/bukkit/src/main/java/me/caseload/knockbacksync/scheduler/BukkitSchedulerAdapter.java @@ -0,0 +1,51 @@ +package me.caseload.knockbacksync.scheduler; + +import org.bukkit.Bukkit; +import org.bukkit.plugin.Plugin; +import org.bukkit.scheduler.BukkitScheduler; + +public class BukkitSchedulerAdapter implements SchedulerAdapter { + private final Plugin plugin; + private final BukkitScheduler scheduler; + + public BukkitSchedulerAdapter(Plugin plugin) { + this.plugin = plugin; + this.scheduler = Bukkit.getScheduler(); + } + + @Override + public AbstractTaskHandle runTask(Runnable task) { + return new BukkitTaskHandle(scheduler.runTask(plugin, task)); + } + + @Override + public AbstractTaskHandle runTaskAsynchronously(Runnable task) { + return new BukkitTaskHandle(scheduler.runTaskAsynchronously(plugin, task)); + } + + @Override + public AbstractTaskHandle runTaskLater(Runnable task, long delayTicks) { + return new BukkitTaskHandle(scheduler.runTaskLater(plugin, task, delayTicks)); + } + + @Override + public AbstractTaskHandle runTaskTimer(Runnable task, long delayTicks, long periodTicks) { + return new BukkitTaskHandle(scheduler.runTaskTimer(plugin, task, delayTicks, periodTicks)); + } + + @Override + public AbstractTaskHandle runTaskLaterAsynchronously(Runnable task, long delay) { + return new BukkitTaskHandle(scheduler.runTaskLaterAsynchronously(plugin, task, delay)); + } + + @Override + public AbstractTaskHandle runTaskTimerAsynchronously(Runnable task, long delay, long period) { + return new BukkitTaskHandle(scheduler.runTaskTimerAsynchronously(plugin, task, delay, period)); + } + + // Bukkit should take care of this for us automatically + @Override + public void shutdown() { + + } +} \ No newline at end of file diff --git a/bukkit/src/main/java/me/caseload/knockbacksync/scheduler/BukkitTaskHandle.java b/bukkit/src/main/java/me/caseload/knockbacksync/scheduler/BukkitTaskHandle.java new file mode 100644 index 0000000..5c089f8 --- /dev/null +++ b/bukkit/src/main/java/me/caseload/knockbacksync/scheduler/BukkitTaskHandle.java @@ -0,0 +1,29 @@ +package me.caseload.knockbacksync.scheduler; + +import org.bukkit.plugin.Plugin; +import org.bukkit.scheduler.BukkitTask; +import org.jetbrains.annotations.NotNull; + +public class BukkitTaskHandle implements AbstractTaskHandle { + private BukkitTask bukkitTask; + private boolean cancelled; + + public BukkitTaskHandle(@NotNull BukkitTask bukkitTask) { + this.bukkitTask = bukkitTask; + } + + public Plugin getOwner() { + return this.bukkitTask.getOwner(); + } + + @Override + public boolean getCancelled() { + return this.cancelled; + } + + @Override + public void cancel() { + this.bukkitTask.cancel(); + this.cancelled = true; + } +} diff --git a/bukkit/src/main/java/me/caseload/knockbacksync/scheduler/FoliaSchedulerAdapter.java b/bukkit/src/main/java/me/caseload/knockbacksync/scheduler/FoliaSchedulerAdapter.java new file mode 100644 index 0000000..a71999a --- /dev/null +++ b/bukkit/src/main/java/me/caseload/knockbacksync/scheduler/FoliaSchedulerAdapter.java @@ -0,0 +1,62 @@ +// FoliaSchedulerAdapter.java +package me.caseload.knockbacksync.scheduler; + +import io.papermc.paper.threadedregions.scheduler.GlobalRegionScheduler; +import org.bukkit.Bukkit; +import org.bukkit.plugin.Plugin; + +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) { +// scheduler.execute(plugin, task); + return new FoliaTaskHandle(scheduler.run(plugin, scheduledTask -> task.run())); + } + + @Override + public AbstractTaskHandle runTaskAsynchronously(Runnable task) { + return new FoliaTaskHandle(scheduler.run(plugin, scheduledTask -> task.run())); + } + + @Override + public AbstractTaskHandle runTaskLater(Runnable task, long delayTicks) { + return new FoliaTaskHandle(scheduler.runDelayed(plugin, scheduledTask -> task.run(), delayTicks)); + } + + @Override + public AbstractTaskHandle runTaskTimer(Runnable task, long delayTicks, long periodTicks) { + return new FoliaTaskHandle(scheduler.runAtFixedRate(plugin, scheduledTask -> task.run(), delayTicks, periodTicks)); + } + + @Override + public AbstractTaskHandle runTaskLaterAsynchronously(Runnable task, long delay) { + return new FoliaTaskHandle(scheduler.runDelayed(plugin, scheduledTask -> task.run(), delay)); + } + + @Override + public AbstractTaskHandle runTaskTimerAsynchronously(Runnable task, long delay, long period) { + return new FoliaTaskHandle(scheduler.runAtFixedRate(plugin, scheduledTask -> task.run(), delay, period)); + } + + // Folia takes care of this + @Override + public void shutdown() { + + } +} \ No newline at end of file diff --git a/bukkit/src/main/java/me/caseload/knockbacksync/scheduler/FoliaTaskHandle.java b/bukkit/src/main/java/me/caseload/knockbacksync/scheduler/FoliaTaskHandle.java new file mode 100644 index 0000000..1a391f1 --- /dev/null +++ b/bukkit/src/main/java/me/caseload/knockbacksync/scheduler/FoliaTaskHandle.java @@ -0,0 +1,29 @@ +package me.caseload.knockbacksync.scheduler; + +import io.papermc.paper.threadedregions.scheduler.ScheduledTask; +import org.bukkit.plugin.Plugin; +import org.jetbrains.annotations.NotNull; + +public class FoliaTaskHandle implements AbstractTaskHandle { + private final ScheduledTask scheduledTask; + private boolean cancelled; + + public FoliaTaskHandle(@NotNull ScheduledTask scheduledTask) { + this.scheduledTask = scheduledTask; + } + + public Plugin getOwner() { + return this.scheduledTask.getOwningPlugin(); + } + + @Override + public boolean getCancelled() { + return this.cancelled; + } + + @Override + public void cancel() { + this.scheduledTask.cancel(); + this.cancelled = true; + } +} diff --git a/bukkit/src/main/java/me/caseload/knockbacksync/stats/custom/BukkitStatsManager.java b/bukkit/src/main/java/me/caseload/knockbacksync/stats/custom/BukkitStatsManager.java new file mode 100644 index 0000000..4c804dc --- /dev/null +++ b/bukkit/src/main/java/me/caseload/knockbacksync/stats/custom/BukkitStatsManager.java @@ -0,0 +1,17 @@ +package me.caseload.knockbacksync.stats.custom; + +import me.caseload.knockbacksync.KnockbackSyncBase; + +public class BukkitStatsManager extends StatsManager { + + @Override + public void init() { + KnockbackSyncBase.INSTANCE.getScheduler().runTaskAsynchronously(() -> { + BuildTypePie.determineBuildType(); // Function to calculate hash + MetricsBukkit metrics = new MetricsBukkit(23568); + metrics.addCustomChart(new PlayerVersionsPie()); + metrics.addCustomChart(new BuildTypePie()); + super.metrics = metrics; + }); + } +} diff --git a/bukkit/src/main/java/me/caseload/knockbacksync/stats/custom/MetricsBukkit.java b/bukkit/src/main/java/me/caseload/knockbacksync/stats/custom/MetricsBukkit.java new file mode 100644 index 0000000..a1f623e --- /dev/null +++ b/bukkit/src/main/java/me/caseload/knockbacksync/stats/custom/MetricsBukkit.java @@ -0,0 +1,156 @@ +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 java.io.File; +import java.io.IOException; +import java.lang.reflect.Method; +import java.util.Collection; +import java.util.UUID; +import java.util.logging.Level; + +import me.caseload.knockbacksync.KnockbackSyncBase; +import me.caseload.knockbacksync.KnockbackSyncPlugin; +import me.caseload.knockbacksync.stats.CustomChart; +import me.caseload.knockbacksync.stats.JsonObjectBuilder; +import org.bukkit.Bukkit; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + +public class MetricsBukkit implements Metrics { + + private final Plugin plugin; + + private final MetricsBase metricsBase; + + + public MetricsBukkit(int serviceId) { + this.plugin = KnockbackSyncPlugin.getPlugin(KnockbackSyncPlugin.class); + // Get the config file + File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); + File configFile = new File(bStatsFolder, "config.yml"); + YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); + if (!config.isSet("serverUuid")) { + config.addDefault("enabled", true); + config.addDefault("serverUuid", UUID.randomUUID().toString()); + config.addDefault("logFailedRequests", false); + config.addDefault("logSentData", false); + config.addDefault("logResponseStatusText", false); + // Inform the server owners about bStats + config + .options() + .header( + "bStats (https://bStats.org) collects some basic information for plugin authors, like how\n" + + "many people use their plugin and their total player count. It's recommended to keep bStats\n" + + "enabled, but if you're not comfortable with this, you can turn this setting off. There is no\n" + + "performance penalty associated with having metrics enabled, and data sent to bStats is fully\n" + + "anonymous.") + .copyDefaults(true); + try { + config.save(configFile); + } catch (IOException ignored) { + } + } + // Load the data + boolean enabled = config.getBoolean("enabled", true); + String serverUUID = config.getString("serverUuid"); + boolean logErrors = config.getBoolean("logFailedRequests", false); + boolean logSentData = config.getBoolean("logSentData", false); + boolean logResponseStatusText = config.getBoolean("logResponseStatusText", false); +// boolean isFolia = false; +// try { +// isFolia = Class.forName("io.papermc.paper.threadedregions.RegionizedServer") != null; +// } catch (Exception e) { +// } + 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( + "bukkit", + serverUUID, + serviceId, + enabled, + this::appendPlatformData, + this::appendServiceData, + submitDataTask -> KnockbackSyncBase.INSTANCE.getScheduler().runTask(submitDataTask), +// isFolia +// ? null +// : submitDataTask -> Bukkit.getScheduler().runTask(plugin, submitDataTask), + plugin::isEnabled, + (message, error) -> this.plugin.getLogger().log(Level.WARNING, message, error), + (message) -> this.plugin.getLogger().log(Level.INFO, message), + logErrors, + logSentData, + logResponseStatusText, + false); + } + + /** + * Shuts down the underlying scheduler service. + */ + @Override + 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", Bukkit.getOnlineMode() ? 1 : 0); + builder.appendField("bukkitVersion", Bukkit.getVersion()); + builder.appendField("bukkitName", Bukkit.getName()); + 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", plugin.getDescription().getVersion()); + } + + private int getPlayerAmount() { + try { + // Around MC 1.8 the return type was changed from an array to a collection, + // This fixes java.lang.NoSuchMethodError: + // org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; + Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); + return onlinePlayersMethod.getReturnType().equals(Collection.class) + ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() + : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; + } catch (Exception e) { + // Just use the new method if the reflection failed + return Bukkit.getOnlinePlayers().size(); + } + } +} + + diff --git a/bukkit/src/main/java/me/caseload/knockbacksync/world/BukkitServer.java b/bukkit/src/main/java/me/caseload/knockbacksync/world/BukkitServer.java new file mode 100644 index 0000000..9b31c74 --- /dev/null +++ b/bukkit/src/main/java/me/caseload/knockbacksync/world/BukkitServer.java @@ -0,0 +1,22 @@ +package me.caseload.knockbacksync.world; + +import me.caseload.knockbacksync.player.BukkitPlayer; +import me.caseload.knockbacksync.player.PlatformPlayer; +import org.bukkit.Bukkit; + +import java.util.Collection; +import java.util.UUID; +import java.util.stream.Collectors; + +public class BukkitServer implements PlatformServer { + public Collection getOnlinePlayers() { + return Bukkit.getOnlinePlayers().stream() + .map(BukkitPlayer::new) + .collect(Collectors.toList()); + } + + @Override + public PlatformPlayer getPlayer(UUID uuid) { + return new BukkitPlayer(Bukkit.getPlayer(uuid)); + } +} diff --git a/bukkit/src/main/java/me/caseload/knockbacksync/world/SpigotWorld.java b/bukkit/src/main/java/me/caseload/knockbacksync/world/SpigotWorld.java new file mode 100644 index 0000000..4c21140 --- /dev/null +++ b/bukkit/src/main/java/me/caseload/knockbacksync/world/SpigotWorld.java @@ -0,0 +1,71 @@ +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 org.bukkit.FluidCollisionMode; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.util.Vector; + +public class SpigotWorld implements PlatformWorld { + private final World world; + + public SpigotWorld(World world) { + this.world = world; + } + + @Override + public WrappedBlockState getBlockStateAt(int x, int y, int z) { + Block block = world.getBlockAt(x, y, z); + return WrappedBlockState.getByString(block.getType().name()); + } + + @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) { + Vector startVec = new Vector(start.getX(), start.getY(), start.getZ()); + Vector directionVec = new Vector(direction.getX(), direction.getY(), direction.getZ()); + + FluidCollisionMode fluidMode = (fluidHandling == FluidHandling.NONE) ? FluidCollisionMode.NEVER : + (fluidHandling == FluidHandling.SOURCE_ONLY) ? FluidCollisionMode.SOURCE_ONLY : + FluidCollisionMode.ALWAYS; + + org.bukkit.util.RayTraceResult result = world.rayTraceBlocks(startVec.toLocation(world), directionVec, maxDistance, fluidMode, ignorePassableBlocks); + + if (result == null) return null; + + return new RayTraceResult( + new Vector3d(result.getHitPosition().getX(), result.getHitPosition().getY(), result.getHitPosition().getZ()), + getBlockFaceFrom(result.getHitBlockFace()), + new Vector3i(result.getHitBlock().getX(),result.getHitBlock().getY(),result.getHitBlock().getZ()), + result.getHitBlock() != null ? WrappedBlockState.getByString(result.getHitBlock().getType().name()) : null + ); + } + + private static BlockFace getBlockFaceFrom(org.bukkit.block.BlockFace direction) { + switch (direction) { + case NORTH: + return BlockFace.NORTH; + case SOUTH: + return BlockFace.SOUTH; + case EAST: + return BlockFace.EAST; + case WEST: + return BlockFace.WEST; + case UP: + return BlockFace.UP; + case DOWN: + return BlockFace.DOWN; + default: + return null; + } + } +} \ No newline at end of file diff --git a/src/main/resources/plugin.yml b/bukkit/src/main/resources/plugin.yml similarity index 84% rename from src/main/resources/plugin.yml rename to bukkit/src/main/resources/plugin.yml index eb21a51..c0a1a08 100644 --- a/src/main/resources/plugin.yml +++ b/bukkit/src/main/resources/plugin.yml @@ -1,6 +1,6 @@ name: KnockbackSync -version: '1.3.2' -main: me.caseload.knockbacksync.KnockbackSync +version: ${version} +main: me.caseload.knockbacksync.KnockbackSyncPlugin api-version: '1.18' authors: [ Caseload ] description: Synchronizes player knockback for smoother gameplay. diff --git a/common/build.gradle.kts b/common/build.gradle.kts new file mode 100644 index 0000000..28e8074 --- /dev/null +++ b/common/build.gradle.kts @@ -0,0 +1,43 @@ +plugins { + id("net.neoforged.moddev") version "1.0.11" +} + +dependencies { + // True compileOnly deps + compileOnly("org.spigotmc:spigot-api:1.18.2-R0.1-SNAPSHOT") + compileOnly("org.geysermc.floodgate:api:2.0-SNAPSHOT") + compileOnly("org.projectlombok:lombok:1.18.34") + annotationProcessor("org.projectlombok:lombok:1.18.34") + + // Shadded in or bundled by platform-specific code +// compileOnly("net.fabricmc:fabric-loader:${rootProject.property("loader_version")}") + implementation("com.github.retrooper:packetevents-api:2.5.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") + } +} + +repositories { + maven("https://maven.neoforged.net/releases") +} + +// Using neoforge in vanilla mode so common code compiles +neoForge { + // Look for versions on https://projects.neoforged.net/neoforged/neoform + neoFormVersion.set("1.21-20240613.152323") + +// runs { +// create("client") { +// client() +// } +// create("server") { +// server() +// } +// create("data") { +// data() +// } +// } +} \ No newline at end of file diff --git a/common/src/main/java/me/caseload/knockbacksync/ConfigWrapper.java b/common/src/main/java/me/caseload/knockbacksync/ConfigWrapper.java new file mode 100644 index 0000000..c3eaa9b --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/ConfigWrapper.java @@ -0,0 +1,37 @@ +package me.caseload.knockbacksync; + +import java.util.Map; + +public class ConfigWrapper { + private final Map configMap; + + public ConfigWrapper(Map configMap) { + this.configMap = configMap; + } + + public String getString(String path, String def) { + Object value = configMap.get(path); + return value instanceof String ? (String) value : def; + } + + public boolean getBoolean(String path, boolean def) { + Object value = configMap.get(path); + return value instanceof Boolean ? (Boolean) value : def; + } + + public int getInt(String path, int def) { + Object value = configMap.get(path); + return value instanceof Integer ? (Integer) value : def; + } + + public long getLong(String path, long def) { + Object value = configMap.get(path); + return value instanceof Long ? (Long) value : def; + } + + public void set(String path, Object value) { + configMap.put(path, value); + } + + // Add other methods as needed (getDouble, getList, etc.) +} \ No newline at end of file diff --git a/common/src/main/java/me/caseload/knockbacksync/KnockbackSyncBase.java b/common/src/main/java/me/caseload/knockbacksync/KnockbackSyncBase.java new file mode 100644 index 0000000..6c0ab6e --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/KnockbackSyncBase.java @@ -0,0 +1,127 @@ +package me.caseload.knockbacksync; + +import com.github.retrooper.packetevents.PacketEvents; +import lombok.Getter; +import me.caseload.knockbacksync.listener.packetevents.AttributeChangeListener; +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; +import me.caseload.knockbacksync.stats.custom.PluginJarHashProvider; +import me.caseload.knockbacksync.stats.custom.StatsManager; +import me.caseload.knockbacksync.world.PlatformServer; +import org.kohsuke.github.GitHub; + +import java.io.File; +import java.io.InputStream; +import java.util.logging.Logger; + +// Base class +public abstract class KnockbackSyncBase { + public static Logger LOGGER; + public static KnockbackSyncBase INSTANCE; + + @Getter + protected SchedulerAdapter scheduler; + public Platform platform; + public StatsManager statsManager; + public PlatformServer platformServer; + public PluginJarHashProvider pluginJarHashProvider; + + @Getter + protected ConfigManager configManager; + + protected KnockbackSyncBase() { + this.platform = getPlatform(); + INSTANCE = this; + configManager = new ConfigManager(); + } + + private Platform getPlatform() { + try { + Class.forName("io.papermc.paper.threadedregions.RegionizedServer"); + return Platform.FOLIA; // Paper (Folia) detected + } catch (ClassNotFoundException ignored1) {} + + try { + Class.forName("org.bukkit.Bukkit"); + return Platform.BUKKIT; // Bukkit (Spigot/Paper without Folia) detected + } catch (ClassNotFoundException ignored2) {} + + try { + Class.forName("net.fabricmc.loader.api.FabricLoader"); + return Platform.FABRIC; // Fabric detected + } catch (ClassNotFoundException ignored3) {} + + throw new IllegalStateException("Unknown platform!"); + } + + public abstract Logger getLogger(); + public abstract File getDataFolder(); + public abstract InputStream getResource(String filename); + + public abstract void load(); + + public void enable() { + LOGGER = getLogger(); + saveDefaultConfig(); + initializePacketEvents(); + registerCommonListeners(); + registerPlatformListeners(); + registerCommands(); + } + + public abstract void initializeScheduler(); + + public void initializePacketEvents() { + PacketEvents.getAPI().getSettings() + .checkForUpdates(false) + .debug(false); + + PacketEvents.getAPI().init(); + } + + protected void registerCommonListeners() { + PacketEvents.getAPI().getEventManager().registerListeners( + new AttributeChangeListener(), + new PingReceiveListener() + ); + } + + protected abstract void registerPlatformListeners(); + protected abstract void registerCommands(); + protected abstract String getVersion(); + + protected void checkForUpdates() { + getLogger().info("Checking for updates..."); + + scheduler.runTaskAsynchronously(() -> { + try { + GitHub github = GitHub.connectAnonymously(); + String latestVersion = github.getRepository("CASELOAD7000/knockback-sync") + .getLatestRelease() + .getTagName(); + + String currentVersion = getVersion(); + boolean updateAvailable = !currentVersion.equalsIgnoreCase(latestVersion); + + if (updateAvailable) { + LOGGER.warning("A new update is available for download at: https://github.com/CASELOAD7000/knockback-sync/releases/latest"); + } else { + LOGGER.info("You are running the latest release."); + } + + configManager.setUpdateAvailable(updateAvailable); + } catch (Exception e) { + LOGGER.severe("Failed to check for updates: " + e.getMessage()); + } + }); + } + + public abstract void saveDefaultConfig(); + + public abstract PermissionChecker getPermissionChecker(); + +} + + diff --git a/common/src/main/java/me/caseload/knockbacksync/Platform.java b/common/src/main/java/me/caseload/knockbacksync/Platform.java new file mode 100644 index 0000000..9f60d66 --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/Platform.java @@ -0,0 +1,7 @@ +package me.caseload.knockbacksync; + +public enum Platform { + FABRIC, + BUKKIT, + FOLIA +} diff --git a/common/src/main/java/me/caseload/knockbacksync/command/KnockbackSyncCommand.java b/common/src/main/java/me/caseload/knockbacksync/command/KnockbackSyncCommand.java new file mode 100644 index 0000000..cf16186 --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/command/KnockbackSyncCommand.java @@ -0,0 +1,109 @@ +package me.caseload.knockbacksync.command; + +import com.mojang.brigadier.Command; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import me.caseload.knockbacksync.KnockbackSyncBase; +import me.caseload.knockbacksync.command.subcommand.StatusSubCommand; +import me.caseload.knockbacksync.command.subcommand.ToggleOffGroundSubcommand; +import me.caseload.knockbacksync.command.subcommand.ToggleSubCommand; +import me.caseload.knockbacksync.manager.ConfigManager; +import me.caseload.knockbacksync.manager.PlayerData; +import me.caseload.knockbacksync.manager.PlayerDataManager; +import me.caseload.knockbacksync.permission.PermissionChecker; +import me.caseload.knockbacksync.util.ChatUtil; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.Commands; +import net.minecraft.commands.arguments.EntityArgument; +import net.minecraft.commands.arguments.selector.EntitySelector; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.MutableComponent; +import net.minecraft.network.chat.Style; +import net.minecraft.network.chat.TextColor; +import net.minecraft.server.level.ServerPlayer; + +public class KnockbackSyncCommand implements Command { + + private static final PermissionChecker permissionChecker = KnockbackSyncBase.INSTANCE.getPermissionChecker(); + + @Override + public int run(CommandContext context) throws CommandSyntaxException { + // Use the builder pattern to create a styled message + MutableComponent message = Component.literal("This server is running the ") + .withStyle(Style.EMPTY.withColor(TextColor.fromRgb(0xFFAA00))) // Gold color + + .append(Component.literal("KnockbackSync") + .withStyle(Style.EMPTY.withColor(TextColor.fromRgb(0xFFFF55)))) // Yellow color + + .append(Component.literal(" plugin. ") + .withStyle(Style.EMPTY.withColor(TextColor.fromRgb(0xFFAA00)))) // Gold color + + .append(Component.literal("https://github.com/CASELOAD7000/knockback-sync") + .withStyle(Style.EMPTY.withColor(TextColor.fromRgb(0x55FFFF)))); // Aqua color + + // Send the styled message + context.getSource().sendSuccess(() -> message, false); + return 1; + } + + public static LiteralArgumentBuilder build() { + return Commands.literal("knockbacksync") + .then(Commands.literal("ping") + .requires(source -> permissionChecker.hasPermission(source, "knockbacksync.ping", true)) + .executes(context -> { // Added .executes() here to handle no target + if (context.getSource().getEntity() instanceof ServerPlayer) { + ServerPlayer sender = (ServerPlayer) context.getSource().getEntity(); + PlayerData playerData = PlayerDataManager.getPlayerData(sender.getUUID()); + context.getSource().sendSuccess(() -> { + if (playerData.getPing() == null) { + return Component.literal("Pong not received. Your estimated ping is " + playerData.getPlatformPlayer().getPing() + "ms."); + } else { + return Component.literal("Your last ping packet took " + playerData.getPing() + "ms."); + } + }, false); + } else { + context.getSource().sendFailure(Component.literal("This command can only be used by players.")); + } + return 1; + }) + .then(Commands.argument("target", EntityArgument.player()) + .executes(context -> { + EntitySelector selector = context.getArgument("target", EntitySelector.class); + ServerPlayer target = selector.findSinglePlayer(context.getSource()); + PlayerData playerData = PlayerDataManager.getPlayerData(target.getUUID()); + context.getSource().sendSuccess(() -> { + if (playerData.getPing() == null) { + return Component.literal("Pong not received. " + target.getDisplayName().getString() + "’s estimated ping is " + playerData.getEstimatedPing() + "ms."); + } else { + return Component.literal(target.getDisplayName().getString() + "’s last ping packet took " + playerData.getPing() + "ms."); + } + }, false); + return 1; + }) + ) + ) + .then(Commands.literal("reload") + .requires(source -> permissionChecker.hasPermission(source, "knockbacksync.reload", false)) + .executes(context -> { + ConfigManager configManager = KnockbackSyncBase.INSTANCE.getConfigManager(); + configManager.loadConfig(true); + + String rawReloadMessage = configManager.getReloadMessage(); + String reloadMessage = ChatUtil.translateAlternateColorCodes('&', rawReloadMessage); + + // Send the message to the command source (the player or console that executed the command) + context.getSource().sendSuccess(() -> + Component.literal(reloadMessage), + false + ); + + return Command.SINGLE_SUCCESS; + }) + ) + .then(StatusSubCommand.build()) + .then(ToggleSubCommand.build()) + .then(ToggleOffGroundSubcommand.build()) + .executes(new KnockbackSyncCommand()); + } +} \ No newline at end of file diff --git a/common/src/main/java/me/caseload/knockbacksync/command/subcommand/StatusSubCommand.java b/common/src/main/java/me/caseload/knockbacksync/command/subcommand/StatusSubCommand.java new file mode 100644 index 0000000..7985656 --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/command/subcommand/StatusSubCommand.java @@ -0,0 +1,85 @@ +package me.caseload.knockbacksync.command.subcommand; + +import com.mojang.brigadier.Command; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import me.caseload.knockbacksync.KnockbackSyncBase; +import me.caseload.knockbacksync.manager.ConfigManager; +import me.caseload.knockbacksync.manager.PlayerDataManager; +import me.caseload.knockbacksync.permission.PermissionChecker; +import me.caseload.knockbacksync.util.ChatUtil; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.Commands; +import net.minecraft.commands.arguments.EntityArgument; +import net.minecraft.commands.arguments.selector.EntitySelector; +import net.minecraft.network.chat.Component; +import net.minecraft.server.level.ServerPlayer; + +import java.util.UUID; + +public class StatusSubCommand implements Command { + + private static final PermissionChecker permissionChecker = KnockbackSyncBase.INSTANCE.getPermissionChecker(); + + @Override + public int run(CommandContext context) throws CommandSyntaxException { + ConfigManager configManager = KnockbackSyncBase.INSTANCE.getConfigManager(); + + // Show global status + boolean globalStatus = configManager.isToggled(); + sendMessage(context, ChatUtil.translateAlternateColorCodes('&', + configManager.getConfigWrapper().getString("global_status_message", "&eGlobal KnockbackSync status: ")) + + (globalStatus + ? ChatUtil.translateAlternateColorCodes('&',"&aEnabled") + : ChatUtil.translateAlternateColorCodes('&', "&cDisabled"))); + + // Show player status for the sender (no target specified) + if (context.getSource().getEntity() instanceof ServerPlayer sender) { + showPlayerStatus(context, sender, sender, configManager); + } + + return Command.SINGLE_SUCCESS; + } + + public static LiteralArgumentBuilder build() { + return Commands.literal("status") + .requires(source -> permissionChecker.hasPermission(source, "knockbacksync.status.self", true)) // Requires at least self permission + .executes(new StatusSubCommand()) // Execute for self status + .then(Commands.argument("target", EntityArgument.player()) + .requires(source -> permissionChecker.hasPermission(source, "knockbacksync.status.other", true)) // Requires other permission for target + .executes(context -> { + ConfigManager configManager = KnockbackSyncBase.INSTANCE.getConfigManager(); + EntitySelector selector = context.getArgument("target", EntitySelector.class); + ServerPlayer target = selector.findSinglePlayer(context.getSource()); + ServerPlayer sender = context.getSource().getPlayer(); + showPlayerStatus(context, sender, target, configManager); + return Command.SINGLE_SUCCESS; + })); + } + + private static void showPlayerStatus(CommandContext context, ServerPlayer sender, ServerPlayer target, ConfigManager configManager) { + boolean globalStatus = configManager.isToggled(); + UUID uuid = target.getUUID(); + boolean playerStatus = PlayerDataManager.containsPlayerData(uuid); + + if (!globalStatus) { + sendMessage(context, ChatUtil.translateAlternateColorCodes('&', + configManager.getConfigWrapper().getString("player_status_message", "&e%player%'s KnockbackSync status: ") + .replace("%player%", target.getDisplayName().getString())) + + ChatUtil.translateAlternateColorCodes('&', + configManager.getConfigWrapper().getString("player_disabled_global_message", "&cDisabled (Global toggle is off)"))); + } else { + sendMessage(context, ChatUtil.translateAlternateColorCodes('&', + configManager.getConfigWrapper().getString("player_status_message", "&e%player%'s KnockbackSync status: ") + .replace("%player%", target.getDisplayName().getString())) + + (playerStatus + ? ChatUtil.translateAlternateColorCodes('&', "&aEnabled") + : ChatUtil.translateAlternateColorCodes('&', "&cDisabled"))); + } + } + + private static void sendMessage(CommandContext context, String message) { + context.getSource().sendSuccess(() -> Component.literal(message), false); + } +} diff --git a/common/src/main/java/me/caseload/knockbacksync/command/subcommand/ToggleOffGroundSubcommand.java b/common/src/main/java/me/caseload/knockbacksync/command/subcommand/ToggleOffGroundSubcommand.java new file mode 100644 index 0000000..84b5c72 --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/command/subcommand/ToggleOffGroundSubcommand.java @@ -0,0 +1,40 @@ +package me.caseload.knockbacksync.command.subcommand; +import me.caseload.knockbacksync.KnockbackSyncBase; + +import com.mojang.brigadier.Command; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.context.CommandContext; +import me.caseload.knockbacksync.permission.PermissionChecker; +import me.caseload.knockbacksync.util.ChatUtil; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.Commands; +import net.minecraft.network.chat.Component; + +public class ToggleOffGroundSubcommand implements Command { + + private static final PermissionChecker permissionChecker = KnockbackSyncBase.INSTANCE.getPermissionChecker(); + + @Override + public int run(CommandContext context) { + boolean toggledState = !KnockbackSyncBase.INSTANCE.getConfigManager().getConfigWrapper().getBoolean("enable_experimental_offground", false); + KnockbackSyncBase.INSTANCE.getConfigManager().getConfigWrapper().set("enable_experimental_offground", toggledState); + KnockbackSyncBase.INSTANCE.getConfigManager().saveConfig(); + String message = ChatUtil.translateAlternateColorCodes('&', + toggledState ? + KnockbackSyncBase.INSTANCE.getConfigManager().getConfigWrapper().getString("enable_experimental_offground_message", "&aSuccessfully enabled offground experiment.") : + KnockbackSyncBase.INSTANCE.getConfigManager().getConfigWrapper().getString("disable_experimental_offground_message", "&cSuccessfully disabled offground experiment.") + ); + sendMessage(context, message); + return Command.SINGLE_SUCCESS; + } + + public static LiteralArgumentBuilder build() { + return Commands.literal("toggleoffground") + .requires(source -> permissionChecker.hasPermission(source, "knockbacksync.toggleoffground", false)) + .executes(new ToggleOffGroundSubcommand()); + } + + private static void sendMessage(CommandContext context, String message) { + context.getSource().sendSuccess(() -> Component.literal(message), false); + } +} \ No newline at end of file diff --git a/common/src/main/java/me/caseload/knockbacksync/command/subcommand/ToggleSubCommand.java b/common/src/main/java/me/caseload/knockbacksync/command/subcommand/ToggleSubCommand.java new file mode 100644 index 0000000..51e068d --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/command/subcommand/ToggleSubCommand.java @@ -0,0 +1,115 @@ +package me.caseload.knockbacksync.command.subcommand; + +import com.mojang.brigadier.Command; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import me.caseload.knockbacksync.KnockbackSyncBase; +import me.caseload.knockbacksync.manager.ConfigManager; +import me.caseload.knockbacksync.manager.PlayerData; +import me.caseload.knockbacksync.manager.PlayerDataManager; +import me.caseload.knockbacksync.permission.PermissionChecker; +import me.caseload.knockbacksync.util.ChatUtil; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.Commands; +import net.minecraft.commands.arguments.EntityArgument; +import net.minecraft.commands.arguments.selector.EntitySelector; +import net.minecraft.network.chat.Component; +import net.minecraft.server.level.ServerPlayer; + +import java.util.UUID; + +public class ToggleSubCommand implements Command { + + private static final PermissionChecker permissionChecker = KnockbackSyncBase.INSTANCE.getPermissionChecker(); + + @Override + public int run(CommandContext context) throws CommandSyntaxException { + ConfigManager configManager = KnockbackSyncBase.INSTANCE.getConfigManager(); + ServerPlayer sender = context.getSource().getPlayerOrException(); + + // Global toggle + if (permissionChecker.hasPermission(context.getSource(), "knockbacksync.toggle.global", false)) { + toggleGlobalKnockback(configManager, context); + } else { + sendMessage(context, ChatUtil.translateAlternateColorCodes('&', "&cYou don't have permission to toggle the global setting.")); + } + + return Command.SINGLE_SUCCESS; + } + + public static LiteralArgumentBuilder build() { + return Commands.literal("toggle") + .requires(source -> permissionChecker.hasPermission(source, "knockbacksync.toggle.self", true)) // Requires at least self permission + .executes(new ToggleSubCommand()) // Execute for self toggle + .then(Commands.argument("target", EntityArgument.player()) + .requires(source -> permissionChecker.hasPermission(source, "knockbacksync.toggle.other", true)) // Requires other permission for target + .executes(context -> { + ConfigManager configManager = KnockbackSyncBase.INSTANCE.getConfigManager(); + EntitySelector selector = context.getArgument("target", EntitySelector.class); + ServerPlayer target = selector.findSinglePlayer(context.getSource()); + ServerPlayer sender = context.getSource().getPlayerOrException(); + + if (!configManager.isToggled()) { + sendMessage(context, ChatUtil.translateAlternateColorCodes('&',"&cKnockbacksync is currently disabled on this server. Contact your server administrator for more information.")); + } else { + togglePlayerKnockback(target, configManager, context); + } + + return Command.SINGLE_SUCCESS; + })); + } + + private static void toggleGlobalKnockback(ConfigManager configManager, CommandContext context) { + boolean toggledState = !configManager.isToggled(); + configManager.setToggled(toggledState); + + KnockbackSyncBase.INSTANCE.getConfigManager().getConfigWrapper().set("enabled", toggledState); + KnockbackSyncBase.INSTANCE.getConfigManager().saveConfig(); + + String message = ChatUtil.translateAlternateColorCodes('&', + toggledState ? configManager.getEnableMessage() : configManager.getDisableMessage() + ); + sendMessage(context, message); + } + + private static void togglePlayerKnockback(ServerPlayer target, ConfigManager configManager, CommandContext context) { + UUID uuid = target.getUUID(); + + if (PlayerDataManager.shouldExempt(uuid)) { + String message = ChatUtil.translateAlternateColorCodes('&', + configManager.getPlayerIneligibleMessage() + ).replace("%player%", target.getDisplayName().getString()); + + sendMessage(context, message); + return; + } + + boolean hasPlayerData = PlayerDataManager.containsPlayerData(uuid); + if (hasPlayerData) + PlayerDataManager.removePlayerData(uuid); + else { + PlayerDataManager.addPlayerData(uuid, new PlayerData(KnockbackSyncBase.INSTANCE.platformServer.getPlayer(uuid))); +// switch (KnockbackSyncBase.INSTANCE.platform) { +// case BUKKIT: +// case FOLIA: +// org.bukkit.entity.Player player = org.bukkit.Bukkit.getPlayer(target.getUUID()); +// PlayerDataManager.addPlayerData(uuid, new PlayerData(target.getUUID()); +// case FABRIC: +// PlayerDataManager.addPlayerData(uuid, new PlayerData(target)); +// } + + } + + String message = ChatUtil.translateAlternateColorCodes('&', + hasPlayerData ? configManager.getPlayerDisableMessage() : configManager. + getPlayerEnableMessage() + ).replace("%player%", target.getDisplayName().getString()); + + sendMessage(context, message); + } + + private static void sendMessage(CommandContext context, String message) { + context.getSource().sendSuccess(() -> Component.literal(message), false); + } +} \ No newline at end of file diff --git a/common/src/main/java/me/caseload/knockbacksync/listener/PlayerDamageListener.java b/common/src/main/java/me/caseload/knockbacksync/listener/PlayerDamageListener.java new file mode 100644 index 0000000..c1d59b0 --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/listener/PlayerDamageListener.java @@ -0,0 +1,24 @@ +package me.caseload.knockbacksync.listener; + +import me.caseload.knockbacksync.KnockbackSyncBase; +import me.caseload.knockbacksync.manager.PlayerData; +import me.caseload.knockbacksync.manager.PlayerDataManager; +import me.caseload.knockbacksync.player.PlatformPlayer; + +public abstract class PlayerDamageListener { + public void onPlayerDamage(PlatformPlayer victim, PlatformPlayer attacker) { + if (!KnockbackSyncBase.INSTANCE.getConfigManager().isToggled()) + return; + + PlayerData playerData = PlayerDataManager.getPlayerData(victim.getUUID()); + if (playerData == null) + return; + + playerData.setVerticalVelocity(playerData.calculateVerticalVelocity(attacker)); // do not move this calculation + playerData.setLastDamageTicks(victim.getNoDamageTicks()); + playerData.updateCombat(); + + if (!KnockbackSyncBase.INSTANCE.getConfigManager().isRunnableEnabled()) + playerData.sendPing(); + } +} diff --git a/common/src/main/java/me/caseload/knockbacksync/listener/PlayerJoinQuitListener.java b/common/src/main/java/me/caseload/knockbacksync/listener/PlayerJoinQuitListener.java new file mode 100644 index 0000000..1597496 --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/listener/PlayerJoinQuitListener.java @@ -0,0 +1,33 @@ +package me.caseload.knockbacksync.listener; + +import me.caseload.knockbacksync.KnockbackSyncBase; +import me.caseload.knockbacksync.manager.PlayerData; +import me.caseload.knockbacksync.manager.PlayerDataManager; +import me.caseload.knockbacksync.player.PlatformPlayer; +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 (KnockbackSyncBase.INSTANCE.getConfigManager().isUpdateAvailable() && KnockbackSyncBase.INSTANCE.getConfigManager().isNotifyUpdate() && KnockbackSyncBase.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(true); + + PlayerDataManager.removePlayerData(uuid); + } +} diff --git a/common/src/main/java/me/caseload/knockbacksync/listener/PlayerKnockbackListener.java b/common/src/main/java/me/caseload/knockbacksync/listener/PlayerKnockbackListener.java new file mode 100644 index 0000000..45413ea --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/listener/PlayerKnockbackListener.java @@ -0,0 +1,32 @@ +package me.caseload.knockbacksync.listener; + +import com.github.retrooper.packetevents.util.Vector3d; +import me.caseload.knockbacksync.KnockbackSyncBase; +import me.caseload.knockbacksync.manager.PlayerData; +import me.caseload.knockbacksync.manager.PlayerDataManager; +import me.caseload.knockbacksync.player.PlatformPlayer; + +public abstract class PlayerKnockbackListener { + + public void onPlayerVelocity(PlatformPlayer victim, Vector3d velocity) { + if (!KnockbackSyncBase.INSTANCE.getConfigManager().isToggled()) + return; + + PlayerData playerData = PlayerDataManager.getPlayerData(victim.getUUID()); + if (playerData == null) + return; + + Integer damageTicks = playerData.getLastDamageTicks(); + if (damageTicks != null && damageTicks > 8) + return; + + Double verticalVelocity = playerData.getVerticalVelocity(); + if (verticalVelocity == null || !playerData.isOnGround(velocity.getY())) + return; + + // Since we're already changing types do we need to use withY to get a new object + // Or can we just go velcoity.y = verticalVelocity ? + Vector3d adjustedVelocity = velocity.withY(verticalVelocity); + victim.setVelocity(adjustedVelocity); // Use PlatformPlayer's setVelocity + } +} \ No newline at end of file diff --git a/src/main/java/me/caseload/knockbacksync/listener/AttributeChangeListener.java b/common/src/main/java/me/caseload/knockbacksync/listener/packetevents/AttributeChangeListener.java similarity index 69% rename from src/main/java/me/caseload/knockbacksync/listener/AttributeChangeListener.java rename to common/src/main/java/me/caseload/knockbacksync/listener/packetevents/AttributeChangeListener.java index 7532905..ae5f99c 100644 --- a/src/main/java/me/caseload/knockbacksync/listener/AttributeChangeListener.java +++ b/common/src/main/java/me/caseload/knockbacksync/listener/packetevents/AttributeChangeListener.java @@ -1,4 +1,4 @@ -package me.caseload.knockbacksync.listener; +package me.caseload.knockbacksync.listener.packetevents; import com.github.retrooper.packetevents.event.PacketListenerAbstract; import com.github.retrooper.packetevents.event.PacketSendEvent; @@ -9,7 +9,6 @@ import me.caseload.knockbacksync.manager.PlayerData; import me.caseload.knockbacksync.manager.PlayerDataManager; import me.caseload.knockbacksync.util.MathUtil; -import org.bukkit.entity.Player; import java.util.List; import java.util.UUID; @@ -30,23 +29,22 @@ public AttributeChangeListener() { @Override public void onPacketSend(PacketSendEvent event) { - // Intercept the packet that updates entity properties (attributes) - if (event.getPacketType() != PacketType.Play.Server.UPDATE_ATTRIBUTES) - return; - - WrapperPlayServerUpdateAttributes packet = new WrapperPlayServerUpdateAttributes(event); - - // Check if the entity is a player - Player player = event.getPlayer(); - if (player == null || !PlayerDataManager.containsPlayerData(player.getUniqueId())) - 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(player, calculateValueWithModifiers(property)); - break; + if (event.getPacketType() == PacketType.Play.Server.UPDATE_ATTRIBUTES) { + + WrapperPlayServerUpdateAttributes packet = new WrapperPlayServerUpdateAttributes(event); + + 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(uuid, calculateValueWithModifiers(property)); + } else if (property.getAttribute().equals(Attributes.GENERIC_KNOCKBACK_RESISTANCE)) { + onPlayerKnockBackChange(uuid, calculateValueWithModifiers(property)); + } } } } @@ -86,12 +84,17 @@ public double calculateValueWithModifiers(WrapperPlayServerUpdateAttributes.Prop // 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(Player player, double newGravity) { - PlayerData playerData = PlayerDataManager.getPlayerData(player.getUniqueId()); + public void onPlayerGravityChange(UUID uuid, double newGravity) { + PlayerData playerData = PlayerDataManager.getPlayerData(uuid); if (playerData.getClientVersion().isNewerThanOrEquals(ClientVersion.V_1_20_5)) { - playerData.setGravity(newGravity); + playerData.setGravityAttribute(newGravity); } else { currentGravity = defaultGravity; } } + + private void onPlayerKnockBackChange(UUID uuid, double newKnockbackResistance) { + PlayerData playerData = PlayerDataManager.getPlayerData(uuid); + playerData.setKnockbackResistanceAttribute(newKnockbackResistance); + } } \ No newline at end of file diff --git a/src/main/java/me/caseload/knockbacksync/listener/PingReceiveListener.java b/common/src/main/java/me/caseload/knockbacksync/listener/packetevents/PingReceiveListener.java similarity index 82% rename from src/main/java/me/caseload/knockbacksync/listener/PingReceiveListener.java rename to common/src/main/java/me/caseload/knockbacksync/listener/packetevents/PingReceiveListener.java index aec8e5a..0ceb9e7 100644 --- a/src/main/java/me/caseload/knockbacksync/listener/PingReceiveListener.java +++ b/common/src/main/java/me/caseload/knockbacksync/listener/packetevents/PingReceiveListener.java @@ -1,43 +1,44 @@ -package me.caseload.knockbacksync.listener; - -import com.github.retrooper.packetevents.event.PacketListenerAbstract; -import com.github.retrooper.packetevents.event.PacketReceiveEvent; -import com.github.retrooper.packetevents.protocol.packettype.PacketType; -import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientPong; -import me.caseload.knockbacksync.KnockbackSync; -import me.caseload.knockbacksync.manager.PlayerData; -import me.caseload.knockbacksync.manager.PlayerDataManager; -import org.bukkit.entity.Player; - -public class PingReceiveListener extends PacketListenerAbstract { - - @Override - public void onPacketReceive(PacketReceiveEvent event) { - if (!KnockbackSync.getInstance().getConfigManager().isToggled()) - return; - - if (event.getPacketType() != PacketType.Play.Client.PONG) - return; - - Player player = event.getPlayer(); - PlayerData playerData = PlayerDataManager.getPlayerData(player.getUniqueId()); - - // If player is timed out by the server and removed from the map on the main thread - // The server can still receive ping packets from the disconnected client - // At which point the entry will no longer be in the map but this code will be processed! - if (playerData == null) - return; - - int packetId = new WrapperPlayClientPong(event).getId(); - - Long sendTime = playerData.getTimeline().get(packetId); - if (sendTime == null) - return; - - long ping = System.currentTimeMillis() - sendTime; - - playerData.getTimeline().remove(packetId); - playerData.setPreviousPing(playerData.getPing() != null ? playerData.getPing() : ping); - playerData.setPing(ping); - } +package me.caseload.knockbacksync.listener.packetevents; + +import com.github.retrooper.packetevents.event.PacketListenerAbstract; +import com.github.retrooper.packetevents.event.PacketReceiveEvent; +import com.github.retrooper.packetevents.protocol.packettype.PacketType; +import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientPong; +import me.caseload.knockbacksync.KnockbackSyncBase; +import me.caseload.knockbacksync.manager.PlayerData; +import me.caseload.knockbacksync.manager.PlayerDataManager; + +import java.util.UUID; + +public class PingReceiveListener extends PacketListenerAbstract { + + @Override + public void onPacketReceive(PacketReceiveEvent event) { + if (!KnockbackSyncBase.INSTANCE.getConfigManager().isToggled()) + return; + + if (event.getPacketType() != PacketType.Play.Client.PONG) + return; + + UUID uuid = event.getUser().getUUID(); + PlayerData playerData = PlayerDataManager.getPlayerData(uuid); + + // If player is timed out by the server and removed from the map on the main thread + // The server can still receive ping packets from the disconnected client + // At which point the entry will no longer be in the map but this code will be processed! + if (playerData == null) + return; + + int packetId = new WrapperPlayClientPong(event).getId(); + + Long sendTime = playerData.getTimeline().get(packetId); + if (sendTime == null) + return; + + long ping = System.currentTimeMillis() - sendTime; + + playerData.getTimeline().remove(packetId); + playerData.setPreviousPing(playerData.getPing() != null ? playerData.getPing() : ping); + playerData.setPing(ping); + } } \ No newline at end of file diff --git a/src/main/java/me/caseload/knockbacksync/manager/CombatManager.java b/common/src/main/java/me/caseload/knockbacksync/manager/CombatManager.java similarity index 95% rename from src/main/java/me/caseload/knockbacksync/manager/CombatManager.java rename to common/src/main/java/me/caseload/knockbacksync/manager/CombatManager.java index 366f52c..9dbd6f2 100644 --- a/src/main/java/me/caseload/knockbacksync/manager/CombatManager.java +++ b/common/src/main/java/me/caseload/knockbacksync/manager/CombatManager.java @@ -1,24 +1,24 @@ -package me.caseload.knockbacksync.manager; - -import org.jetbrains.annotations.NotNull; - -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; - -public class CombatManager { - - private static final Set combatPlayers = ConcurrentHashMap.newKeySet(); - - public static @NotNull Set getPlayers() { - return combatPlayers; - } - - public static void addPlayer(UUID uuid) { - combatPlayers.add(uuid); - } - - public static void removePlayer(UUID uuid) { - combatPlayers.remove(uuid); - } -} +package me.caseload.knockbacksync.manager; + +import org.jetbrains.annotations.NotNull; + +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +public class CombatManager { + + private static final Set combatPlayers = ConcurrentHashMap.newKeySet(); + + public static @NotNull Set getPlayers() { + return combatPlayers; + } + + public static void addPlayer(UUID uuid) { + combatPlayers.add(uuid); + } + + public static void removePlayer(UUID uuid) { + combatPlayers.remove(uuid); + } +} diff --git a/common/src/main/java/me/caseload/knockbacksync/manager/ConfigManager.java b/common/src/main/java/me/caseload/knockbacksync/manager/ConfigManager.java new file mode 100644 index 0000000..e3a9c13 --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/manager/ConfigManager.java @@ -0,0 +1,121 @@ +package me.caseload.knockbacksync.manager; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; +import lombok.Getter; +import lombok.Setter; +import me.caseload.knockbacksync.ConfigWrapper; +import me.caseload.knockbacksync.KnockbackSyncBase; +import me.caseload.knockbacksync.Platform; +import me.caseload.knockbacksync.runnable.PingRunnable; +import me.caseload.knockbacksync.scheduler.AbstractTaskHandle; + +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +@Getter +@Setter +public class ConfigManager { + + private boolean toggled; + private boolean runnableEnabled; + private boolean updateAvailable; + private boolean notifyUpdate; + + private long runnableInterval; + private long combatTimer; + private long spikeThreshold; + + private String enableMessage; + private String disableMessage; + private String playerEnableMessage; + private String playerDisableMessage; + private String playerIneligibleMessage; + private String reloadMessage; + + private AbstractTaskHandle pingTask; + + private Map config; + private File configFile; + private ObjectMapper mapper; + private ConfigWrapper configWrapper; // Cache the ConfigWrapper instance + + public ConfigManager() { + mapper = new ObjectMapper(new YAMLFactory()); + KnockbackSyncBase instance = KnockbackSyncBase.INSTANCE; + configFile = new File(instance.getDataFolder(), "config.yml"); + } + + public ConfigWrapper getConfigWrapper() { + if (configWrapper == null) { + reloadConfig(); + } + return configWrapper; + } + + public void reloadConfig() { + try { + if (!configFile.exists()) { + KnockbackSyncBase.INSTANCE.saveDefaultConfig(); + } + config = mapper.readValue(configFile, Map.class); + configWrapper = new ConfigWrapper(config); + } catch (IOException e) { + e.printStackTrace(); + config = new HashMap<>(); + configWrapper = new ConfigWrapper(config); + } + } + + public void saveConfig() { + try { + mapper.writeValue(configFile, config); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void loadConfig(boolean reloadConfig) { + if (reloadConfig || config == null) { + reloadConfig(); + } + + ConfigWrapper config = getConfigWrapper(); // Use cached ConfigWrapper + + toggled = config.getBoolean("enabled", true); + + // Checks to see if the runnable was enabled... + // and if we now want to disable it + boolean newRunnableEnabled = config.getBoolean("runnable.enabled", true); + if (runnableEnabled && newRunnableEnabled && pingTask != null) { // null check for first startup + pingTask.cancel(); + } + + runnableEnabled = newRunnableEnabled; + + if (runnableEnabled) { + long initialDelay = 0L; + long pingTaskRunnableInterval = runnableInterval; + // Folia does not allow 0 ticks of wait time + if (KnockbackSyncBase.INSTANCE.platform == Platform.FOLIA) { + initialDelay = 1L; + pingTaskRunnableInterval = Math.max(pingTaskRunnableInterval, 1L); + } + pingTask = KnockbackSyncBase.INSTANCE.getScheduler().runTaskTimerAsynchronously(new PingRunnable(), initialDelay, pingTaskRunnableInterval); + } + + notifyUpdate = config.getBoolean("notify_updates", true); + runnableInterval = config.getLong("runnable.interval", 5L); + combatTimer = config.getLong("runnable.timer", 30L); + spikeThreshold = config.getLong("spike_threshold", 20L); + enableMessage = config.getString("enable_message", "&aSuccessfully enabled KnockbackSync."); + disableMessage = config.getString("disable_message", "&cSuccessfully disabled KnockbackSync."); + playerEnableMessage = config.getString("player_enable_message", "&aSuccessfully enabled KnockbackSync for %player%."); + playerDisableMessage = config.getString("player_disable_message", "&cSuccessfully disabled KnockbackSync for %player%."); + playerIneligibleMessage = config.getString("player_ineligible_message", "&c%player% is ineligible for KnockbackSync. If you believe this is an error, please open an issue on the github page."); + reloadMessage = config.getString("reload_message", "&aSuccessfully reloaded KnockbackSync."); + PlayerData.PING_OFFSET = config.getInt("ping_offset", 25); + } +} \ No newline at end of file diff --git a/common/src/main/java/me/caseload/knockbacksync/manager/PlayerData.java b/common/src/main/java/me/caseload/knockbacksync/manager/PlayerData.java new file mode 100644 index 0000000..850723c --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/manager/PlayerData.java @@ -0,0 +1,313 @@ +package me.caseload.knockbacksync.manager; + +import com.github.retrooper.packetevents.PacketEvents; +import com.github.retrooper.packetevents.manager.player.PlayerManager; +import com.github.retrooper.packetevents.protocol.player.ClientVersion; +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 com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPing; +import io.netty.channel.Channel; +import lombok.Getter; +import lombok.Setter; +import me.caseload.knockbacksync.KnockbackSyncBase; +//import me.caseload.knockbacksync.player.BukkitPlayer; +//import me.caseload.knockbacksync.player.FabricPlayer; +import me.caseload.knockbacksync.player.PlatformPlayer; +import me.caseload.knockbacksync.world.PlatformWorld; +import me.caseload.knockbacksync.scheduler.AbstractTaskHandle; +import me.caseload.knockbacksync.util.MathUtil; +import me.caseload.knockbacksync.world.raytrace.FluidHandling; +import me.caseload.knockbacksync.world.raytrace.RayTraceResult; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.lang.reflect.Field; +import java.util.HashMap; +import java.util.Map; +import java.util.Random; +import java.util.UUID; + +@Getter +public class PlayerData { + + private final PlatformPlayer platformPlayer; + private final UUID uuid; + + public final User user; + + // Please read the GitHub FAQ before adjusting. + public static long PING_OFFSET; + + @NotNull + private final Map timeline = new HashMap<>(); + + @NotNull + private final Random random = new Random(); + + @Nullable + private AbstractTaskHandle combatTask; + + @Nullable + @Setter + private Long ping, previousPing; + + @Nullable + @Setter + private Double verticalVelocity; + + @Nullable + @Setter + private Integer lastDamageTicks; + + @Setter + private double gravityAttribute = 0.08; + + @Setter + private double knockbackResistanceAttribute = 0.0; + + public PlayerData(PlatformPlayer platformPlayer) { + this.uuid = platformPlayer.getUUID(); + this.platformPlayer = platformPlayer; + + User tempUser = null; + try { + PlayerManager playerManager = PacketEvents.getAPI().getPlayerManager(); + Object player = null; + + switch (KnockbackSyncBase.INSTANCE.platform) { + case BUKKIT: + case FOLIA: + Class bukkitPlayerClass = Class.forName("me.caseload.knockbacksync.player.BukkitPlayer"); + Field bukkitPlayerField = bukkitPlayerClass.getDeclaredField("bukkitPlayer"); + bukkitPlayerField.setAccessible(true); + player = bukkitPlayerField.get(platformPlayer); + break; + case FABRIC: + Class fabricPlayerClass = Class.forName("me.caseload.knockbacksync.player.FabricPlayer"); + Field fabricPlayerField = fabricPlayerClass.getDeclaredField("fabricPlayer"); + fabricPlayerField.setAccessible(true); + player = fabricPlayerField.get(platformPlayer); + break; + default: + throw new IllegalStateException("Unexpected platform: " + KnockbackSyncBase.INSTANCE.platform); + } + + if (player != null) { + tempUser = playerManager.getUser(player); + } + } catch (Exception e) { + e.printStackTrace(); + // Handle the exception appropriately + } + + this.user = tempUser; + PING_OFFSET = KnockbackSyncBase.INSTANCE.getConfigManager().getConfigWrapper().getInt("ping_offset", 25); + } + +// public PlayerData(Player player) { +// this.uuid = player.getUniqueId(); +// this.user = PacketEvents.getAPI().getPlayerManager().getUser(player); +// this.platformPlayer = new BukkitPlayer(player); +// PING_OFFSET = KnockbackSyncBase.INSTANCE.getConfigManager().getConfigWrapper().getInt("ping_offset", 25); +// } + +// public PlayerData(ServerPlayer player) { +// this.uuid = player.getUUID(); + // ping listener doesn't work beause I can't get the user + // this exists temporarily until I fix packetevents +// Channel channel = (Channel) PacketEvents.getAPI().getProtocolManager().getChannel(uuid); +// this.user = PacketEvents.getAPI().getProtocolManager().getUser(channel); +// this.user = null; // PacketEvents.getAPI().getPlayerManager().getUser(player); +// this.platformPlayer = new FabricPlayer(player); +// PING_OFFSET = KnockbackSyncBase.INSTANCE.getConfigManager().getConfigWrapper().getInt("ping_offset", 25); +// } + + /** + * Calculates the player's ping with compensation for lag spikes. + * A hardcoded offset is applied for several reasons, + * read the GitHub FAQ before adjusting. + * + * @return The compensated ping, with a minimum of 1. + */ + public long getEstimatedPing() { + long currentPing = (ping != null) ? ping : platformPlayer.getPing(); + long lastPing = (previousPing != null) ? previousPing : platformPlayer.getPing(); + long ping = (currentPing - lastPing > KnockbackSyncBase.INSTANCE.getConfigManager().getSpikeThreshold()) ? lastPing : currentPing; + + return Math.max(1, ping - PING_OFFSET); + } + + public void sendPing() { + if (user != null) { + int packetId = random.nextInt(1, 10000); + + timeline.put(packetId, System.currentTimeMillis()); + + WrapperPlayServerPing packet = new WrapperPlayServerPing(packetId); + user.sendPacket(packet); + } + } + + /** + * Determines if the Player is on the ground clientside, but not serverside + *

+ * Returns ping ≥ (tMax + tFall) and gDist ≤ 1.3 + *

+ * Where: + *

    + *
  • ping: Estimated latency
  • + *
  • tMax: Time to reach maximum upward velocity
  • + *
  • tFall: Time to fall to the ground
  • + *
  • gDist: Distance to the ground
  • + *
+ * + * @param verticalVelocity The Player's current vertical velocity. + * @return true if the Player is on the ground; false otherwise. + */ + public boolean isOnGround(double verticalVelocity) { + WrappedBlockState blockState = platformPlayer.getWorld().getBlockStateAt(platformPlayer.getLocation()); + + if (platformPlayer.isGliding() || + blockState.getType() == StateTypes.WATER || + blockState.getType() == StateTypes.LAVA || + blockState.getType() == StateTypes.COBWEB || + blockState.getType() == StateTypes.SCAFFOLDING) { + return false; + } + + if (ping == null || ping < PING_OFFSET) + return false; + + double gDist = getDistanceToGround(); + if (gDist <= 0) + return false; // prevent player from taking adjusted knockback when on ground serverside + + int tMax = verticalVelocity > 0 ? MathUtil.calculateTimeToMaxVelocity(verticalVelocity, gravityAttribute) : 0; + double mH = verticalVelocity > 0 ? MathUtil.calculateDistanceTraveled(verticalVelocity, tMax, gravityAttribute) : 0; + int tFall = MathUtil.calculateFallTime(verticalVelocity, mH + gDist, gravityAttribute); + + if (tFall == -1) + return false; // reached the max tick limit, not safe to predict + + return getEstimatedPing() >= tMax + tFall / 20.0 * 1000 && gDist <= 1.3; + } + + /** + * Ray traces from each corner of the player's bounding box to the ground, + * returning the smallest distance, with a maximum limit of 5 blocks. + * + * @return The distance to the ground in blocks + */ + public double getDistanceToGround() { + double collisionDist = 5; + + PlatformWorld world = platformPlayer.getWorld(); + + for (Vector3d corner : getBBCorners()) { + RayTraceResult result = world.rayTraceBlocks(corner, new Vector3d(0, -1, 0), 5, FluidHandling.NONE, true); + + if (result == null || result.getHitPosition() == null) + continue; + + collisionDist = Math.min(collisionDist, corner.getY() - result.getHitPosition().getY()); + } + + return collisionDist - 1; + } + + /** + * Gets the corners of the Player's bounding box. + * + * @return An array of locations representing the corners of the bounding box. + */ + private Vector3d[] getBBCorners() { + Vector3d playerPos = platformPlayer.getLocation(); + double width = 0.6; // typical player width +// double height = 1.8; // typical player height + double adjustment = 0.01; + + return new Vector3d[] { + new Vector3d(playerPos.getX() - width/2 + adjustment, playerPos.getY(), playerPos.getZ() - width/2 + adjustment), + new Vector3d(playerPos.getX() - width/2 + adjustment, playerPos.getY(), playerPos.getZ() + width/2 - adjustment), + new Vector3d(playerPos.getX() + width/2 - adjustment, playerPos.getY(), playerPos.getZ() - width/2 + adjustment), + new Vector3d(playerPos.getX() + width/2 - adjustment, playerPos.getY(), playerPos.getZ() + width/2 - adjustment) + }; + } + + /** + * Calculates the positive vertical velocity. + * This is used to switch falling knockback to rising knockback. + * + * @param attacker The player who is attacking. + * @return The calculated positive vertical velocity, consistent with vanilla behavior. + */ + public double calculateVerticalVelocity(PlatformPlayer attacker) { + double yAxis = attacker.getAttackCooldown() > 0.848 ? 0.4 : 0.36080000519752503; + + if (!attacker.isSprinting()) { + yAxis = 0.36080000519752503; +// double knockbackResistance = knockbackResistanceAttribute; + double resistanceFactor = 0.04000000119 * knockbackResistanceAttribute * 10; + yAxis -= resistanceFactor; + } + + // vertical velocity is always 0.4 when you have knockback level higher than 0 + if (attacker.getMainHandKnockbackLevel() > 0) + yAxis = 0.4; + + return yAxis; + } + + // might need soon +// public double calculateJumpVelocity() { +// double jumpVelocity = 0.42; +// +// PotionEffect jumpEffect = player.getPotionEffect(PotionEffectType.JUMP); +// if (jumpEffect != null) { +// int amplifier = jumpEffect.getAmplifier(); +// jumpVelocity += (amplifier + 1) * 0.1F; +// } +// +// return jumpVelocity; +// } + + public boolean isInCombat() { + return combatTask != null; + } + + public void updateCombat() { + if (isInCombat()) + combatTask.cancel(); + + combatTask = newCombatTask(); + CombatManager.addPlayer(uuid); + } + + public void quitCombat(boolean cancelTask) { + if (cancelTask) + combatTask.cancel(); + + combatTask = null; + CombatManager.removePlayer(uuid); + timeline.clear(); // failsafe for packet loss idk + } + + @NotNull + private AbstractTaskHandle newCombatTask() { + return KnockbackSyncBase.INSTANCE.getScheduler().runTaskLaterAsynchronously( + () -> quitCombat(false), KnockbackSyncBase.INSTANCE.getConfigManager().getCombatTimer()); + } + + public ClientVersion getClientVersion() { + if (user == null) + return ClientVersion.UNKNOWN; + ClientVersion ver = user.getClientVersion(); + if (ver == null) { + // If temporarily null, assume server version... + return ClientVersion.getById(PacketEvents.getAPI().getServerManager().getVersion().getProtocolVersion()); + } + return ver; + } +} \ No newline at end of file diff --git a/src/main/java/me/caseload/knockbacksync/manager/PlayerDataManager.java b/common/src/main/java/me/caseload/knockbacksync/manager/PlayerDataManager.java similarity index 90% rename from src/main/java/me/caseload/knockbacksync/manager/PlayerDataManager.java rename to common/src/main/java/me/caseload/knockbacksync/manager/PlayerDataManager.java index b4973d8..b79f745 100644 --- a/src/main/java/me/caseload/knockbacksync/manager/PlayerDataManager.java +++ b/common/src/main/java/me/caseload/knockbacksync/manager/PlayerDataManager.java @@ -1,42 +1,40 @@ -package me.caseload.knockbacksync.manager; - -import io.github.retrooper.packetevents.util.GeyserUtil; -import me.caseload.knockbacksync.util.FloodgateUtil; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; - -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; - -public class PlayerDataManager { - - private static final Map playerDataMap = new ConcurrentHashMap<>(); - - public static PlayerData getPlayerData(@NotNull UUID uuid) { - return playerDataMap.get(uuid); - } - - public static void addPlayerData(@NotNull UUID uuid, @NotNull PlayerData playerData) { - if (!shouldExempt(uuid)) - playerDataMap.put(uuid, playerData); - } - - public static void removePlayerData(@NotNull UUID uuid) { - playerDataMap.remove(uuid); - } - - public static boolean containsPlayerData(@NotNull UUID uuid) { - return playerDataMap.containsKey(uuid); - } - - public static boolean shouldExempt(@NotNull UUID uuid) { - // Geyser players don't have Java movement - return GeyserUtil.isGeyserPlayer(uuid) - // Floodgate is the authentication system for Geyser on servers that use Geyser as a proxy instead of installing it as a plugin directly on the server - || FloodgateUtil.isFloodgatePlayer(uuid) - // Geyser formatted player string - // This will never happen for Java players, as the first character in the 3rd group is always 4 (xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx) - || uuid.toString().startsWith("00000000-0000-0000-0009"); - } -} +package me.caseload.knockbacksync.manager; + +import me.caseload.knockbacksync.util.FloodgateUtil; +import me.caseload.knockbacksync.util.GeyserUtil; +import org.jetbrains.annotations.NotNull; + +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; + +public class PlayerDataManager { + + private static final Map playerDataMap = new ConcurrentHashMap<>(); + + public static PlayerData getPlayerData(@NotNull UUID uuid) { + return playerDataMap.get(uuid); + } + + public static void addPlayerData(@NotNull UUID uuid, @NotNull PlayerData playerData) { + if (!shouldExempt(uuid)) + playerDataMap.put(uuid, playerData); + } + + public static void removePlayerData(@NotNull UUID uuid) { + playerDataMap.remove(uuid); + } + + public static boolean containsPlayerData(@NotNull UUID uuid) { + return playerDataMap.containsKey(uuid); + } + + public static boolean shouldExempt(@NotNull UUID uuid) { + // Geyser players don't have Java movement + return GeyserUtil.isGeyserPlayer(uuid) + // Floodgate is the authentication system for Geyser on servers that use Geyser as a proxy instead of installing it as a plugin directly on the server + || FloodgateUtil.isFloodgatePlayer(uuid) + // Geyser formatted player string + // This will never happen for Java players, as the first character in the 3rd group is always 4 (xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx) + || uuid.toString().startsWith("00000000-0000-0000-0009"); + } +} diff --git a/common/src/main/java/me/caseload/knockbacksync/permission/PermissionChecker.java b/common/src/main/java/me/caseload/knockbacksync/permission/PermissionChecker.java new file mode 100644 index 0000000..f35e3c6 --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/permission/PermissionChecker.java @@ -0,0 +1,9 @@ +package me.caseload.knockbacksync.permission; + +import me.caseload.knockbacksync.player.PlatformPlayer; +import net.minecraft.commands.CommandSourceStack; + +public interface PermissionChecker { + boolean hasPermission(CommandSourceStack source, String s, boolean defaultIfUnset); + boolean hasPermission(PlatformPlayer platform, String s); +} diff --git a/common/src/main/java/me/caseload/knockbacksync/player/PlatformBlock.java b/common/src/main/java/me/caseload/knockbacksync/player/PlatformBlock.java new file mode 100644 index 0000000..7ac7d35 --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/player/PlatformBlock.java @@ -0,0 +1,8 @@ +package me.caseload.knockbacksync.player; + +import com.github.retrooper.packetevents.protocol.world.states.WrappedBlockState; + +public interface PlatformBlock { + WrappedBlockState getMaterial(); + // Add more methods as needed +} diff --git a/common/src/main/java/me/caseload/knockbacksync/player/PlatformPlayer.java b/common/src/main/java/me/caseload/knockbacksync/player/PlatformPlayer.java new file mode 100644 index 0000000..061423e --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/player/PlatformPlayer.java @@ -0,0 +1,39 @@ +package me.caseload.knockbacksync.player; + +import com.github.retrooper.packetevents.util.Vector3d; +import me.caseload.knockbacksync.world.PlatformWorld; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.UUID; + +public interface PlatformPlayer { + UUID getUUID(); + String getName(); + double getX(); + double getY(); + double getZ(); + float getPitch(); + float getYaw(); + boolean isOnGround(); + int getPing(); + + boolean isGliding(); + + PlatformWorld getWorld(); + + Vector3d getLocation(); + + void sendMessage(@NotNull String s); + + double getAttackCooldown(); + + boolean isSprinting(); + + int getMainHandKnockbackLevel(); + + @Nullable Integer getNoDamageTicks(); + + void setVelocity(Vector3d adjustedVelocity); + // Add more methods as needed +} diff --git a/src/main/java/me/caseload/knockbacksync/runnable/PingRunnable.java b/common/src/main/java/me/caseload/knockbacksync/runnable/PingRunnable.java similarity index 73% rename from src/main/java/me/caseload/knockbacksync/runnable/PingRunnable.java rename to common/src/main/java/me/caseload/knockbacksync/runnable/PingRunnable.java index 778d80c..deaa128 100644 --- a/src/main/java/me/caseload/knockbacksync/runnable/PingRunnable.java +++ b/common/src/main/java/me/caseload/knockbacksync/runnable/PingRunnable.java @@ -1,23 +1,22 @@ -package me.caseload.knockbacksync.runnable; - -import me.caseload.knockbacksync.KnockbackSync; -import me.caseload.knockbacksync.manager.CombatManager; -import me.caseload.knockbacksync.manager.PlayerData; -import me.caseload.knockbacksync.manager.PlayerDataManager; -import org.bukkit.scheduler.BukkitRunnable; - -import java.util.UUID; - -public class PingRunnable implements Runnable { - - @Override - public void run() { - if (!KnockbackSync.getInstance().getConfigManager().isToggled()) - return; - - for (UUID uuid : CombatManager.getPlayers()) { - PlayerData playerData = PlayerDataManager.getPlayerData(uuid); - playerData.sendPing(); - } - } -} +package me.caseload.knockbacksync.runnable; + +import me.caseload.knockbacksync.KnockbackSyncBase; +import me.caseload.knockbacksync.manager.CombatManager; +import me.caseload.knockbacksync.manager.PlayerData; +import me.caseload.knockbacksync.manager.PlayerDataManager; + +import java.util.UUID; + +public class PingRunnable implements Runnable { + + @Override + public void run() { + if (!KnockbackSyncBase.INSTANCE.getConfigManager().isToggled()) + return; + + for (UUID uuid : CombatManager.getPlayers()) { + PlayerData playerData = PlayerDataManager.getPlayerData(uuid); + playerData.sendPing(); + } + } +} diff --git a/common/src/main/java/me/caseload/knockbacksync/scheduler/AbstractTaskHandle.java b/common/src/main/java/me/caseload/knockbacksync/scheduler/AbstractTaskHandle.java new file mode 100644 index 0000000..17e82fd --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/scheduler/AbstractTaskHandle.java @@ -0,0 +1,8 @@ +package me.caseload.knockbacksync.scheduler; + +public interface AbstractTaskHandle { + + public boolean getCancelled(); + + public void cancel(); +} \ No newline at end of file diff --git a/common/src/main/java/me/caseload/knockbacksync/scheduler/SchedulerAdapter.java b/common/src/main/java/me/caseload/knockbacksync/scheduler/SchedulerAdapter.java new file mode 100644 index 0000000..40b2d03 --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/scheduler/SchedulerAdapter.java @@ -0,0 +1,11 @@ +package me.caseload.knockbacksync.scheduler; + +public interface SchedulerAdapter { + AbstractTaskHandle runTask(Runnable task); + AbstractTaskHandle runTaskAsynchronously(Runnable task); + AbstractTaskHandle runTaskLater(Runnable task, long delayTicks); + AbstractTaskHandle runTaskTimer(Runnable task, long delayTicks, long periodTicks); + AbstractTaskHandle runTaskLaterAsynchronously(Runnable task, long delay); + AbstractTaskHandle runTaskTimerAsynchronously(Runnable task, long delay, long period); + void shutdown(); +} \ No newline at end of file diff --git a/common/src/main/java/me/caseload/knockbacksync/stats/AdvancedBarChart.java b/common/src/main/java/me/caseload/knockbacksync/stats/AdvancedBarChart.java new file mode 100644 index 0000000..46fdd61 --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/stats/AdvancedBarChart.java @@ -0,0 +1,44 @@ +package me.caseload.knockbacksync.stats; + +import java.util.Map; +import java.util.concurrent.Callable; + +public class AdvancedBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObjectBuilder.JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue().length == 0) { + // Skip this invalid + continue; + } + allSkipped = false; + valuesBuilder.appendField(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } +} diff --git a/common/src/main/java/me/caseload/knockbacksync/stats/AdvancedPie.java b/common/src/main/java/me/caseload/knockbacksync/stats/AdvancedPie.java new file mode 100644 index 0000000..0aa98aa --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/stats/AdvancedPie.java @@ -0,0 +1,44 @@ +package me.caseload.knockbacksync.stats; + +import java.util.Map; +import java.util.concurrent.Callable; + +public class AdvancedPie extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedPie(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObjectBuilder.JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + // Skip this invalid + continue; + } + allSkipped = false; + valuesBuilder.appendField(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } +} diff --git a/common/src/main/java/me/caseload/knockbacksync/stats/CustomChart.java b/common/src/main/java/me/caseload/knockbacksync/stats/CustomChart.java new file mode 100644 index 0000000..9c2f2dc --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/stats/CustomChart.java @@ -0,0 +1,37 @@ +package me.caseload.knockbacksync.stats; + +import java.util.function.BiConsumer; + +public abstract class CustomChart { + + private final String chartId; + + protected CustomChart(String chartId) { + if (chartId == null) { + throw new IllegalArgumentException("chartId must not be null"); + } + this.chartId = chartId; + } + + public JsonObjectBuilder.JsonObject getRequestJsonObject( + BiConsumer errorLogger, boolean logErrors) { + JsonObjectBuilder builder = new JsonObjectBuilder(); + builder.appendField("chartId", chartId); + try { + JsonObjectBuilder.JsonObject data = getChartData(); + if (data == null) { + // If the data is null we don't send the chart. + return null; + } + builder.appendField("data", data); + } catch (Throwable t) { + if (logErrors) { + errorLogger.accept("Failed to get data for custom chart with id " + chartId, t); + } + return null; + } + return builder.build(); + } + + protected abstract JsonObjectBuilder.JsonObject getChartData() throws Exception; +} diff --git a/common/src/main/java/me/caseload/knockbacksync/stats/DrilldownPie.java b/common/src/main/java/me/caseload/knockbacksync/stats/DrilldownPie.java new file mode 100644 index 0000000..daa5fbc --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/stats/DrilldownPie.java @@ -0,0 +1,48 @@ +package me.caseload.knockbacksync.stats; + +import java.util.Map; +import java.util.concurrent.Callable; + +public class DrilldownPie extends CustomChart { + + private final Callable>> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public DrilldownPie(String chartId, Callable>> callable) { + super(chartId); + this.callable = callable; + } + + @Override + public JsonObjectBuilder.JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map> map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean reallyAllSkipped = true; + for (Map.Entry> entryValues : map.entrySet()) { + JsonObjectBuilder valueBuilder = new JsonObjectBuilder(); + boolean allSkipped = true; + for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { + valueBuilder.appendField(valueEntry.getKey(), valueEntry.getValue()); + allSkipped = false; + } + if (!allSkipped) { + reallyAllSkipped = false; + valuesBuilder.appendField(entryValues.getKey(), valueBuilder.build()); + } + } + if (reallyAllSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } +} diff --git a/common/src/main/java/me/caseload/knockbacksync/stats/JsonObjectBuilder.java b/common/src/main/java/me/caseload/knockbacksync/stats/JsonObjectBuilder.java new file mode 100644 index 0000000..5388784 --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/stats/JsonObjectBuilder.java @@ -0,0 +1,208 @@ +package me.caseload.knockbacksync.stats; + +import java.util.Arrays; +import java.util.stream.Collectors; /** + * An extremely simple JSON builder. + * + *

While this class is neither feature-rich nor the most performant one, it's sufficient enough + * for its use-case. + */ +public class JsonObjectBuilder { + + private StringBuilder builder = new StringBuilder(); + + private boolean hasAtLeastOneField = false; + + public JsonObjectBuilder() { + builder.append("{"); + } + + /** + * Appends a null field to the JSON. + * + * @param key The key of the field. + * @return A reference to this object. + */ + public JsonObjectBuilder appendNull(String key) { + appendFieldUnescaped(key, "null"); + return this; + } + + /** + * Appends a string field to the JSON. + * + * @param key The key of the field. + * @param value The value of the field. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, String value) { + if (value == null) { + throw new IllegalArgumentException("JSON value must not be null"); + } + appendFieldUnescaped(key, "\"" + escape(value) + "\""); + return this; + } + + /** + * Appends an integer field to the JSON. + * + * @param key The key of the field. + * @param value The value of the field. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, int value) { + appendFieldUnescaped(key, String.valueOf(value)); + return this; + } + + /** + * Appends an object to the JSON. + * + * @param key The key of the field. + * @param object The object. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, JsonObject object) { + if (object == null) { + throw new IllegalArgumentException("JSON object must not be null"); + } + appendFieldUnescaped(key, object.toString()); + return this; + } + + /** + * Appends a string array to the JSON. + * + * @param key The key of the field. + * @param values The string array. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, String[] values) { + if (values == null) { + throw new IllegalArgumentException("JSON values must not be null"); + } + String escapedValues = + Arrays.stream(values) + .map(value -> "\"" + escape(value) + "\"") + .collect(Collectors.joining(",")); + appendFieldUnescaped(key, "[" + escapedValues + "]"); + return this; + } + + /** + * Appends an integer array to the JSON. + * + * @param key The key of the field. + * @param values The integer array. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, int[] values) { + if (values == null) { + throw new IllegalArgumentException("JSON values must not be null"); + } + String escapedValues = + Arrays.stream(values).mapToObj(String::valueOf).collect(Collectors.joining(",")); + appendFieldUnescaped(key, "[" + escapedValues + "]"); + return this; + } + + /** + * Appends an object array to the JSON. + * + * @param key The key of the field. + * @param values The integer array. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, JsonObject[] values) { + if (values == null) { + throw new IllegalArgumentException("JSON values must not be null"); + } + String escapedValues = + Arrays.stream(values).map(JsonObject::toString).collect(Collectors.joining(",")); + appendFieldUnescaped(key, "[" + escapedValues + "]"); + return this; + } + + /** + * Appends a field to the object. + * + * @param key The key of the field. + * @param escapedValue The escaped value of the field. + */ + private void appendFieldUnescaped(String key, String escapedValue) { + if (builder == null) { + throw new IllegalStateException("JSON has already been built"); + } + if (key == null) { + throw new IllegalArgumentException("JSON key must not be null"); + } + if (hasAtLeastOneField) { + builder.append(","); + } + builder.append("\"").append(escape(key)).append("\":").append(escapedValue); + hasAtLeastOneField = true; + } + + /** + * Builds the JSON string and invalidates this builder. + * + * @return The built JSON string. + */ + public JsonObject build() { + if (builder == null) { + throw new IllegalStateException("JSON has already been built"); + } + JsonObject object = new JsonObject(builder.append("}").toString()); + builder = null; + return object; + } + + /** + * Escapes the given string like stated in https://www.ietf.org/rfc/rfc4627.txt. + * + *

This method escapes only the necessary characters '"', '\'. and '\u0000' - '\u001F'. + * Compact escapes are not used (e.g., '\n' is escaped as "\u000a" and not as "\n"). + * + * @param value The value to escape. + * @return The escaped value. + */ + private static String escape(String value) { + final StringBuilder builder = new StringBuilder(); + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + if (c == '"') { + builder.append("\\\""); + } else if (c == '\\') { + builder.append("\\\\"); + } else if (c <= '\u000F') { + builder.append("\\u000").append(Integer.toHexString(c)); + } else if (c <= '\u001F') { + builder.append("\\u00").append(Integer.toHexString(c)); + } else { + builder.append(c); + } + } + return builder.toString(); + } + + /** + * A super simple representation of a JSON object. + * + *

This class only exists to make methods of the {@link JsonObjectBuilder} type-safe and not + * allow a raw string inputs for methods like {@link JsonObjectBuilder#appendField(String, + * JsonObject)}. + */ + public static class JsonObject { + + private final String value; + + private JsonObject(String value) { + this.value = value; + } + + @Override + public String toString() { + return value; + } + } +} diff --git a/common/src/main/java/me/caseload/knockbacksync/stats/MultiLineChart.java b/common/src/main/java/me/caseload/knockbacksync/stats/MultiLineChart.java new file mode 100644 index 0000000..1d868f0 --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/stats/MultiLineChart.java @@ -0,0 +1,44 @@ +package me.caseload.knockbacksync.stats; + +import java.util.Map; +import java.util.concurrent.Callable; + +public class MultiLineChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public MultiLineChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObjectBuilder.JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + // Skip this invalid + continue; + } + allSkipped = false; + valuesBuilder.appendField(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } +} diff --git a/common/src/main/java/me/caseload/knockbacksync/stats/SimpleBarChart.java b/common/src/main/java/me/caseload/knockbacksync/stats/SimpleBarChart.java new file mode 100644 index 0000000..6da7833 --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/stats/SimpleBarChart.java @@ -0,0 +1,34 @@ +package me.caseload.knockbacksync.stats; + +import java.util.Map; +import java.util.concurrent.Callable; + +public class SimpleBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimpleBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObjectBuilder.JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + for (Map.Entry entry : map.entrySet()) { + valuesBuilder.appendField(entry.getKey(), new int[] {entry.getValue()}); + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } +} diff --git a/common/src/main/java/me/caseload/knockbacksync/stats/SimplePie.java b/common/src/main/java/me/caseload/knockbacksync/stats/SimplePie.java new file mode 100644 index 0000000..4b9b4e6 --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/stats/SimplePie.java @@ -0,0 +1,29 @@ +package me.caseload.knockbacksync.stats; + +import java.util.concurrent.Callable; + +public class SimplePie extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimplePie(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObjectBuilder.JsonObject getChartData() throws Exception { + String value = callable.call(); + if (value == null || value.isEmpty()) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("value", value).build(); + } +} diff --git a/common/src/main/java/me/caseload/knockbacksync/stats/SingleLineChart.java b/common/src/main/java/me/caseload/knockbacksync/stats/SingleLineChart.java new file mode 100644 index 0000000..0320cea --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/stats/SingleLineChart.java @@ -0,0 +1,29 @@ +package me.caseload.knockbacksync.stats; + +import java.util.concurrent.Callable; + +public class SingleLineChart extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SingleLineChart(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObjectBuilder.JsonObject getChartData() throws Exception { + int value = callable.call(); + if (value == 0) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("value", value).build(); + } +} diff --git a/src/main/java/me/caseload/knockbacksync/stats/BuildTypePie.java b/common/src/main/java/me/caseload/knockbacksync/stats/custom/BuildTypePie.java similarity index 69% rename from src/main/java/me/caseload/knockbacksync/stats/BuildTypePie.java rename to common/src/main/java/me/caseload/knockbacksync/stats/custom/BuildTypePie.java index a0785ec..e3b0b56 100644 --- a/src/main/java/me/caseload/knockbacksync/stats/BuildTypePie.java +++ b/common/src/main/java/me/caseload/knockbacksync/stats/custom/BuildTypePie.java @@ -1,10 +1,9 @@ -package me.caseload.knockbacksync.stats; +package me.caseload.knockbacksync.stats.custom; import com.google.gson.JsonObject; import com.google.gson.JsonParser; -import me.caseload.knockbacksync.KnockbackSync; -import org.bstats.charts.SimplePie; -import org.bukkit.Bukkit; +import me.caseload.knockbacksync.KnockbackSyncBase; +import me.caseload.knockbacksync.stats.SimplePie; import org.kohsuke.github.GHAsset; import org.kohsuke.github.GHRelease; import org.kohsuke.github.GitHub; @@ -24,8 +23,9 @@ public class BuildTypePie extends SimplePie { private static final String RELEASES_FILE = "releases.txt"; private static final String DEV_BUILDS_FILE = "dev-builds.txt"; - private static final File dataFolder = KnockbackSync.INSTANCE.getDataFolder(); + private static final File dataFolder = KnockbackSyncBase.INSTANCE.getDataFolder(); private static String cachedBuildType = null; + public static URL jarUrl; public BuildTypePie() { super("build_type", BuildTypePie::determineBuildType); @@ -40,7 +40,7 @@ public static String determineBuildType() { private static String calculateBuildType() { try { - String currentHash = getPluginJarHash(); + String currentHash = KnockbackSyncBase.INSTANCE.pluginJarHashProvider.getPluginJarHash(); downloadBuildFiles(); if (isHashInFile(currentHash, new File(dataFolder, RELEASES_FILE))) { @@ -63,7 +63,7 @@ private static void downloadBuildFiles() throws IOException { List assets = latestRelease.listAssets().toList(); for (GHAsset asset : assets) { if (asset.getName().equals(RELEASES_FILE) || asset.getName().equals(DEV_BUILDS_FILE)) { - KnockbackSync.INSTANCE.getLogger().info("Downloading: " + asset.getName()); + KnockbackSyncBase.INSTANCE.getLogger().info("Downloading: " + asset.getName()); String jsonContent = readStringFromURL(asset.getUrl().toString()); JsonObject jsonObject = JsonParser.parseString(jsonContent).getAsJsonObject(); @@ -74,7 +74,7 @@ private static void downloadBuildFiles() throws IOException { inputStream.transferTo(outputStream); } - KnockbackSync.INSTANCE.getLogger().info("Downloaded: " + asset.getName()); + KnockbackSyncBase.INSTANCE.getLogger().info("Downloaded: " + asset.getName()); } } } @@ -87,26 +87,6 @@ private static boolean isHashInFile(String hash, File file) throws IOException { return lines.contains(hash); } - private static String getPluginJarHash() throws Exception { - URL jarUrl = Bukkit.getPluginManager().getPlugin("KnockbackSync").getClass().getProtectionDomain().getCodeSource().getLocation(); - MessageDigest digest = MessageDigest.getInstance("SHA-256"); - try (InputStream is = jarUrl.openStream()) { - byte[] buffer = new byte[8192]; - int read; - while ((read = is.read(buffer)) > 0) { - digest.update(buffer, 0, read); - } - } - byte[] hash = digest.digest(); - StringBuilder hexString = new StringBuilder(); - for (byte b : hash) { - String hex = Integer.toHexString(0xff & b); - if (hex.length() == 1) hexString.append('0'); - hexString.append(hex); - } - return hexString.toString(); - } - private static String readStringFromURL(String urlString) throws IOException { try (InputStream inputStream = new URL(urlString).openStream()) { return new String(inputStream.readAllBytes(), StandardCharsets.UTF_8); diff --git a/common/src/main/java/me/caseload/knockbacksync/stats/custom/Metrics.java b/common/src/main/java/me/caseload/knockbacksync/stats/custom/Metrics.java new file mode 100644 index 0000000..16cb658 --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/stats/custom/Metrics.java @@ -0,0 +1,5 @@ +package me.caseload.knockbacksync.stats.custom; + +public interface Metrics { + public void shutdown(); +} diff --git a/common/src/main/java/me/caseload/knockbacksync/stats/custom/MetricsBase.java b/common/src/main/java/me/caseload/knockbacksync/stats/custom/MetricsBase.java new file mode 100644 index 0000000..069597e --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/stats/custom/MetricsBase.java @@ -0,0 +1,265 @@ +package me.caseload.knockbacksync.stats.custom; + +import me.caseload.knockbacksync.stats.CustomChart; +import me.caseload.knockbacksync.stats.JsonObjectBuilder; + +import javax.net.ssl.HttpsURLConnection; +import java.io.*; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Supplier; +import java.util.zip.GZIPOutputStream; + +public class MetricsBase { + + /** The version of the Metrics class. */ + public static final String METRICS_VERSION = "3.1.0"; + + private static final String REPORT_URL = "https://bStats.org/api/v2/data/%s"; + + private final ScheduledExecutorService scheduler; + + private final String platform; + + private final String serverUuid; + + private final int serviceId; + + private final Consumer appendPlatformDataConsumer; + + private final Consumer appendServiceDataConsumer; + + private final Consumer submitTaskConsumer; + + private final Supplier checkServiceEnabledSupplier; + + private final BiConsumer errorLogger; + + private final Consumer infoLogger; + + private final boolean logErrors; + + private final boolean logSentData; + + private final boolean logResponseStatusText; + + private final Set customCharts = new HashSet<>(); + + private final boolean enabled; + + /** + * Creates a new MetricsBase class instance. + * + * @param platform The platform of the service. + * @param serviceId The id of the service. + * @param serverUuid The server uuid. + * @param enabled Whether or not data sending is enabled. + * @param appendPlatformDataConsumer A consumer that receives a {@code JsonObjectBuilder} and + * appends all platform-specific data. + * @param appendServiceDataConsumer A consumer that receives a {@code JsonObjectBuilder} and + * appends all service-specific data. + * @param submitTaskConsumer A consumer that takes a runnable with the submit task. This can be + * used to delegate the data collection to a another thread to prevent errors caused by + * concurrency. Can be {@code null}. + * @param checkServiceEnabledSupplier A supplier to check if the service is still enabled. + * @param errorLogger A consumer that accepts log message and an error. + * @param infoLogger A consumer that accepts info log messages. + * @param logErrors Whether or not errors should be logged. + * @param logSentData Whether or not the sent data should be logged. + * @param logResponseStatusText Whether or not the response status text should be logged. + * @param skipRelocateCheck Whether or not the relocate check should be skipped. + */ + public MetricsBase( + String platform, + String serverUuid, + int serviceId, + boolean enabled, + Consumer appendPlatformDataConsumer, + Consumer appendServiceDataConsumer, + Consumer submitTaskConsumer, + Supplier checkServiceEnabledSupplier, + BiConsumer errorLogger, + Consumer infoLogger, + boolean logErrors, + boolean logSentData, + boolean logResponseStatusText, + boolean skipRelocateCheck) { + ScheduledThreadPoolExecutor scheduler = + new ScheduledThreadPoolExecutor( + 1, + task -> { + Thread thread = new Thread(task, "bStats-Metrics"); + thread.setDaemon(true); + return thread; + }); + // We want delayed tasks (non-periodic) that will execute in the future to be + // cancelled when the scheduler is shutdown. + // Otherwise, we risk preventing the server from shutting down even when + // MetricsBase#shutdown() is called + scheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); + this.scheduler = scheduler; + this.platform = platform; + this.serverUuid = serverUuid; + this.serviceId = serviceId; + this.enabled = enabled; + this.appendPlatformDataConsumer = appendPlatformDataConsumer; + this.appendServiceDataConsumer = appendServiceDataConsumer; + this.submitTaskConsumer = submitTaskConsumer; + this.checkServiceEnabledSupplier = checkServiceEnabledSupplier; + this.errorLogger = errorLogger; + this.infoLogger = infoLogger; + this.logErrors = logErrors; + this.logSentData = logSentData; + this.logResponseStatusText = logResponseStatusText; + if (!skipRelocateCheck) { + checkRelocation(); + } + if (enabled) { + // WARNING: Removing the option to opt-out will get your plugin banned from + // bStats + startSubmitting(); + } + } + + public void addCustomChart(CustomChart chart) { + this.customCharts.add(chart); + } + + public void shutdown() { + scheduler.shutdown(); + } + + private void startSubmitting() { + final Runnable submitTask = + () -> { + if (!enabled || !checkServiceEnabledSupplier.get()) { + // Submitting data or service is disabled + scheduler.shutdown(); + return; + } + if (submitTaskConsumer != null) { + submitTaskConsumer.accept(this::submitData); + } else { + this.submitData(); + } + }; + // Many servers tend to restart at a fixed time at xx:00 which causes an uneven + // distribution of requests on the + // bStats backend. To circumvent this problem, we introduce some randomness into + // the initial and second delay. + // WARNING: You must not modify and part of this Metrics class, including the + // submit delay or frequency! + // WARNING: Modifying this code will get your plugin banned on bStats. Just + // don't do it! + long initialDelay = (long) (1000 * 60 * (3 + Math.random() * 3)); + long secondDelay = (long) (1000 * 60 * (Math.random() * 30)); + scheduler.schedule(submitTask, initialDelay, TimeUnit.MILLISECONDS); + scheduler.scheduleAtFixedRate( + submitTask, initialDelay + secondDelay, 1000 * 60 * 30, TimeUnit.MILLISECONDS); + } + + private void submitData() { + final JsonObjectBuilder baseJsonBuilder = new JsonObjectBuilder(); + appendPlatformDataConsumer.accept(baseJsonBuilder); + final JsonObjectBuilder serviceJsonBuilder = new JsonObjectBuilder(); + appendServiceDataConsumer.accept(serviceJsonBuilder); + JsonObjectBuilder.JsonObject[] chartData = + customCharts.stream() + .map(customChart -> customChart.getRequestJsonObject(errorLogger, logErrors)) + .filter(Objects::nonNull) + .toArray(JsonObjectBuilder.JsonObject[]::new); + serviceJsonBuilder.appendField("id", serviceId); + serviceJsonBuilder.appendField("customCharts", chartData); + baseJsonBuilder.appendField("service", serviceJsonBuilder.build()); + baseJsonBuilder.appendField("serverUUID", serverUuid); + baseJsonBuilder.appendField("metricsVersion", METRICS_VERSION); + JsonObjectBuilder.JsonObject data = baseJsonBuilder.build(); + scheduler.execute( + () -> { + try { + // Send the data + sendData(data); + } catch (Exception e) { + // Something went wrong! :( + if (logErrors) { + errorLogger.accept("Could not submit bStats metrics data", e); + } + } + }); + } + + private void sendData(JsonObjectBuilder.JsonObject data) throws Exception { + if (logSentData) { + infoLogger.accept("Sent bStats metrics data: " + data.toString()); + } + String url = String.format(REPORT_URL, platform); + HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection(); + // Compress the data to save bandwidth + byte[] compressedData = compress(data.toString()); + connection.setRequestMethod("POST"); + connection.addRequestProperty("Accept", "application/json"); + connection.addRequestProperty("Connection", "close"); + connection.addRequestProperty("Content-Encoding", "gzip"); + connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); + connection.setRequestProperty("Content-Type", "application/json"); + connection.setRequestProperty("User-Agent", "Metrics-Service/1"); + connection.setDoOutput(true); + try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { + outputStream.write(compressedData); + } + StringBuilder builder = new StringBuilder(); + try (BufferedReader bufferedReader = + new BufferedReader(new InputStreamReader(connection.getInputStream()))) { + String line; + while ((line = bufferedReader.readLine()) != null) { + builder.append(line); + } + } + if (logResponseStatusText) { + infoLogger.accept("Sent data to bStats and received response: " + builder); + } + } + + /** Checks that the class was properly relocated. */ + private void checkRelocation() { + // You can use the property to disable the check in your test environment + if (System.getProperty("bstats.relocatecheck") == null + || !System.getProperty("bstats.relocatecheck").equals("false")) { + // Maven's Relocate is clever and changes strings, too. So we have to use this + // little "trick" ... :D + final String defaultPackage = + new String(new byte[] {'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's'}); + final String examplePackage = + new String(new byte[] {'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); + // We want to make sure no one just copy & pastes the example and uses the wrong + // package names + if (MetricsBase.class.getPackage().getName().startsWith(defaultPackage) + || MetricsBase.class.getPackage().getName().startsWith(examplePackage)) { + throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); + } + } + } + + /** + * Gzips the given string. + * + * @param str The string to gzip. + * @return The gzipped string. + */ + private static byte[] compress(final String str) throws IOException { + if (str == null) { + return null; + } + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) { + gzip.write(str.getBytes(StandardCharsets.UTF_8)); + } + return outputStream.toByteArray(); + } +} \ No newline at end of file diff --git a/src/main/java/me/caseload/knockbacksync/stats/PlayerVersionsPie.java b/common/src/main/java/me/caseload/knockbacksync/stats/custom/PlayerVersionsPie.java similarity index 63% rename from src/main/java/me/caseload/knockbacksync/stats/PlayerVersionsPie.java rename to common/src/main/java/me/caseload/knockbacksync/stats/custom/PlayerVersionsPie.java index 9c0447b..d9816a5 100644 --- a/src/main/java/me/caseload/knockbacksync/stats/PlayerVersionsPie.java +++ b/common/src/main/java/me/caseload/knockbacksync/stats/custom/PlayerVersionsPie.java @@ -1,10 +1,11 @@ -package me.caseload.knockbacksync.stats; +package me.caseload.knockbacksync.stats.custom; +import me.caseload.knockbacksync.KnockbackSyncBase; import me.caseload.knockbacksync.manager.PlayerData; import me.caseload.knockbacksync.manager.PlayerDataManager; -import org.bstats.charts.AdvancedPie; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; +import me.caseload.knockbacksync.player.PlatformPlayer; +import me.caseload.knockbacksync.world.PlatformServer; +import me.caseload.knockbacksync.stats.AdvancedPie; import java.util.HashMap; import java.util.Map; @@ -15,8 +16,8 @@ public class PlayerVersionsPie extends AdvancedPie { public PlayerVersionsPie() { super("player_version", () -> { Map valueMap = new HashMap<>(); - for (Player player : Bukkit.getOnlinePlayers()) { - PlayerData playerData = PlayerDataManager.getPlayerData(player.getUniqueId()); + for (PlatformPlayer player : KnockbackSyncBase.INSTANCE.platformServer.getOnlinePlayers()) { + PlayerData playerData = PlayerDataManager.getPlayerData(player.getUUID()); valueMap.put(playerData.getClientVersion().toString(), valueMap.getOrDefault(playerData.getClientVersion().toString(), 0) + 1); } return valueMap; diff --git a/common/src/main/java/me/caseload/knockbacksync/stats/custom/PluginJarHashProvider.java b/common/src/main/java/me/caseload/knockbacksync/stats/custom/PluginJarHashProvider.java new file mode 100644 index 0000000..cafdd10 --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/stats/custom/PluginJarHashProvider.java @@ -0,0 +1,33 @@ +package me.caseload.knockbacksync.stats.custom; + +import java.io.InputStream; +import java.net.URL; +import java.security.MessageDigest; + +public class PluginJarHashProvider { + + protected URL jarURL; + + public PluginJarHashProvider(URL jarURL) { + this.jarURL = jarURL; + } + + public String getPluginJarHash() throws Exception { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + try (InputStream is = jarURL.openStream()) { + byte[] buffer = new byte[8192]; + int read; + while ((read = is.read(buffer)) > 0) { + digest.update(buffer, 0, read); + } + } + byte[] hash = digest.digest(); + StringBuilder hexString = new StringBuilder(); + for (byte b : hash) { + String hex = Integer.toHexString(0xff & b); + if (hex.length() == 1) hexString.append('0'); + hexString.append(hex); + } + return hexString.toString(); + } +} \ No newline at end of file diff --git a/common/src/main/java/me/caseload/knockbacksync/stats/custom/StatsManager.java b/common/src/main/java/me/caseload/knockbacksync/stats/custom/StatsManager.java new file mode 100644 index 0000000..d5da44b --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/stats/custom/StatsManager.java @@ -0,0 +1,16 @@ +package me.caseload.knockbacksync.stats.custom; + +import me.caseload.knockbacksync.KnockbackSyncBase; + +public abstract class StatsManager { + + Metrics metrics; + + public Metrics getMetrics() { + return metrics; + } + + public void init() { + throw new IllegalStateException("Empty stats class!"); + } +} diff --git a/common/src/main/java/me/caseload/knockbacksync/util/BlockFaceUtil.java b/common/src/main/java/me/caseload/knockbacksync/util/BlockFaceUtil.java new file mode 100644 index 0000000..2381b98 --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/util/BlockFaceUtil.java @@ -0,0 +1,44 @@ +package me.caseload.knockbacksync.util; + +import com.github.retrooper.packetevents.protocol.world.BlockFace; +import com.github.retrooper.packetevents.protocol.world.Direction; + +public class BlockFaceUtil { +// public static BlockFace getFrom(Direction direction) { +// switch (direction) { +// case NORTH: +// return BlockFace.NORTH; +// case SOUTH: +// return BlockFace.SOUTH; +// case EAST: +// return BlockFace.EAST; +// case WEST: +// return BlockFace.WEST; +// case UP: +// return BlockFace.UP; +// case DOWN: +// return BlockFace.DOWN; +// default: +// return null; +// } +// } + +// public static BlockFace getFrom(org.bukkit.block.BlockFace direction) { +// switch (direction) { +// case NORTH: +// return BlockFace.NORTH; +// case SOUTH: +// return BlockFace.SOUTH; +// case EAST: +// return BlockFace.EAST; +// case WEST: +// return BlockFace.WEST; +// case UP: +// return BlockFace.UP; +// case DOWN: +// return BlockFace.DOWN; +// default: +// return null; +// } +// } +} diff --git a/common/src/main/java/me/caseload/knockbacksync/util/ChatUtil.java b/common/src/main/java/me/caseload/knockbacksync/util/ChatUtil.java new file mode 100644 index 0000000..f5c041e --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/util/ChatUtil.java @@ -0,0 +1,20 @@ +package me.caseload.knockbacksync.util; + +import com.google.common.base.Preconditions; +import org.jetbrains.annotations.NotNull; + +public class ChatUtil { + public static @NotNull String translateAlternateColorCodes(char altColorChar, @NotNull String textToTranslate) { + Preconditions.checkArgument(textToTranslate != null, "Cannot translate null text"); + char[] b = textToTranslate.toCharArray(); + + for(int i = 0; i < b.length - 1; ++i) { + if (b[i] == altColorChar && "0123456789AaBbCcDdEeFfKkLlMmNnOoRrXx".indexOf(b[i + 1]) > -1) { + b[i] = 167; + b[i + 1] = Character.toLowerCase(b[i + 1]); + } + } + + return new String(b); + } +} diff --git a/src/main/java/me/caseload/knockbacksync/util/FloodgateUtil.java b/common/src/main/java/me/caseload/knockbacksync/util/FloodgateUtil.java similarity index 100% rename from src/main/java/me/caseload/knockbacksync/util/FloodgateUtil.java rename to common/src/main/java/me/caseload/knockbacksync/util/FloodgateUtil.java diff --git a/common/src/main/java/me/caseload/knockbacksync/util/GeyserUtil.java b/common/src/main/java/me/caseload/knockbacksync/util/GeyserUtil.java new file mode 100644 index 0000000..9bd706c --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/util/GeyserUtil.java @@ -0,0 +1,83 @@ +package me.caseload.knockbacksync.util; + +import com.github.retrooper.packetevents.PacketEvents; +import com.github.retrooper.packetevents.util.reflection.Reflection; +import me.caseload.knockbacksync.KnockbackSyncBase; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.UUID; + +public class GeyserUtil { + private static boolean CHECKED_FOR_GEYSER = false; + private static boolean GEYSER_PRESENT = false; + private static Class GEYSER_CLASS; + private static Class GEYSER_API_CLASS; + private static Method GEYSER_API_METHOD; + private static Method CONNECTION_BY_UUID_METHOD; + + public static boolean isGeyserPlayer(UUID uuid) { + if (!CHECKED_FOR_GEYSER) { + try { + switch (KnockbackSyncBase.INSTANCE.platform) { + 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; + } + CHECKED_FOR_GEYSER = true; + } + + if (GEYSER_PRESENT) { + if (GEYSER_API_CLASS == null) { + try { + switch (KnockbackSyncBase.INSTANCE.platform) { + 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(); + } + } + if (GEYSER_API_METHOD == null) { + GEYSER_API_METHOD = Reflection.getMethodExact(GEYSER_CLASS, "api", null); + } + if (CONNECTION_BY_UUID_METHOD == null) { + CONNECTION_BY_UUID_METHOD = Reflection.getMethod(GEYSER_API_CLASS, "connectionByUuid", 0); + } + Object apiInstance = null; + try { + apiInstance = GEYSER_API_METHOD.invoke(null); + } catch (IllegalAccessException | InvocationTargetException e) { + e.printStackTrace(); + } + Object connection = null; + try { + if (apiInstance != null) { + connection = CONNECTION_BY_UUID_METHOD.invoke(apiInstance, uuid); + } + } catch (IllegalAccessException | InvocationTargetException e) { + e.printStackTrace(); + } + return connection != null; + } + return false; + } +} diff --git a/src/main/java/me/caseload/knockbacksync/util/MathUtil.java b/common/src/main/java/me/caseload/knockbacksync/util/MathUtil.java similarity index 96% rename from src/main/java/me/caseload/knockbacksync/util/MathUtil.java rename to common/src/main/java/me/caseload/knockbacksync/util/MathUtil.java index d8ec238..ece9899 100644 --- a/src/main/java/me/caseload/knockbacksync/util/MathUtil.java +++ b/common/src/main/java/me/caseload/knockbacksync/util/MathUtil.java @@ -1,60 +1,60 @@ -package me.caseload.knockbacksync.util; - -public class MathUtil { - - private static final double TERMINAL_VELOCITY = 3.92; - private static final double MULTIPLIER = 0.98; - private static final int MAX_TICKS = 20; - - public static double calculateDistanceTraveled(double velocity, int time, double acceleration) - { - double totalDistance = 0; - - for (int i = 0; i < time; i++) - { - totalDistance += velocity; - velocity = ((velocity - acceleration) * MULTIPLIER); - velocity = Math.min(velocity, TERMINAL_VELOCITY); - } - - return totalDistance; - } - - public static int calculateFallTime(double initialVelocity, double distance, double acceleration) { - double velocity = Math.abs(initialVelocity); - int ticks = 0; - - while (distance > 0) { - if (ticks > MAX_TICKS) - return -1; - - velocity += acceleration; - velocity = Math.min(velocity, TERMINAL_VELOCITY); - velocity *= MULTIPLIER; - distance -= velocity; - ticks++; - } - - return ticks; - } - - public static int calculateTimeToMaxVelocity(double targetVerticalVelocity, double acceleration) { - double a = -acceleration * MULTIPLIER; - double b = acceleration + TERMINAL_VELOCITY * MULTIPLIER; - double c = -2 * targetVerticalVelocity; - - double discriminant = b * b - 4 * a * c; - if (discriminant < 0) - return 0; - - double positiveRoot = (-b + Math.sqrt(discriminant)) / (2 * a); - return (int) Math.ceil(positiveRoot * 20); - } - - public static double clamp(double num, double min, double max) { - if (num < min) - return min; - - return Math.min(num, max); - } +package me.caseload.knockbacksync.util; + +public class MathUtil { + + private static final double TERMINAL_VELOCITY = 3.92; + private static final double MULTIPLIER = 0.98; + private static final int MAX_TICKS = 20; + + public static double calculateDistanceTraveled(double velocity, int time, double acceleration) + { + double totalDistance = 0; + + for (int i = 0; i < time; i++) + { + totalDistance += velocity; + velocity = ((velocity - acceleration) * MULTIPLIER); + velocity = Math.min(velocity, TERMINAL_VELOCITY); + } + + return totalDistance; + } + + public static int calculateFallTime(double initialVelocity, double distance, double acceleration) { + double velocity = Math.abs(initialVelocity); + int ticks = 0; + + while (distance > 0) { + if (ticks > MAX_TICKS) + return -1; + + velocity += acceleration; + velocity = Math.min(velocity, TERMINAL_VELOCITY); + velocity *= MULTIPLIER; + distance -= velocity; + ticks++; + } + + return ticks; + } + + public static int calculateTimeToMaxVelocity(double targetVerticalVelocity, double acceleration) { + double a = -acceleration * MULTIPLIER; + double b = acceleration + TERMINAL_VELOCITY * MULTIPLIER; + double c = -2 * targetVerticalVelocity; + + double discriminant = b * b - 4 * a * c; + if (discriminant < 0) + return 0; + + double positiveRoot = (-b + Math.sqrt(discriminant)) / (2 * a); + return (int) Math.ceil(positiveRoot * 20); + } + + public static double clamp(double num, double min, double max) { + if (num < min) + return min; + + return Math.min(num, max); + } } \ No newline at end of file diff --git a/common/src/main/java/me/caseload/knockbacksync/util/PlatformUtil.java b/common/src/main/java/me/caseload/knockbacksync/util/PlatformUtil.java new file mode 100644 index 0000000..21604a7 --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/util/PlatformUtil.java @@ -0,0 +1,4 @@ +package me.caseload.knockbacksync.util; + +public class PlatformUtil { +} diff --git a/common/src/main/java/me/caseload/knockbacksync/world/PlatformServer.java b/common/src/main/java/me/caseload/knockbacksync/world/PlatformServer.java new file mode 100644 index 0000000..6536a6a --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/world/PlatformServer.java @@ -0,0 +1,27 @@ +package me.caseload.knockbacksync.world; + +import me.caseload.knockbacksync.player.PlatformPlayer; + +import java.util.Collection; +import java.util.UUID; + +public interface PlatformServer { + Collection getOnlinePlayers(); + + PlatformPlayer getPlayer(UUID uuid); + +// 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); +// } +} \ No newline at end of file diff --git a/common/src/main/java/me/caseload/knockbacksync/world/PlatformWorld.java b/common/src/main/java/me/caseload/knockbacksync/world/PlatformWorld.java new file mode 100644 index 0000000..91b20dc --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/world/PlatformWorld.java @@ -0,0 +1,14 @@ +package me.caseload.knockbacksync.world; + +import com.github.retrooper.packetevents.protocol.world.states.WrappedBlockState; +import com.github.retrooper.packetevents.util.Vector3d; +import me.caseload.knockbacksync.world.raytrace.FluidHandling; +import me.caseload.knockbacksync.world.raytrace.RayTraceResult; + +public interface PlatformWorld { + WrappedBlockState getBlockStateAt(int x, int y, int z); + + WrappedBlockState getBlockStateAt(Vector3d loc); + + RayTraceResult rayTraceBlocks(Vector3d start, Vector3d direction, double maxDistance, FluidHandling fluidHandling, boolean ignorePassableBlocks); +} diff --git a/common/src/main/java/me/caseload/knockbacksync/world/raytrace/FluidHandling.java b/common/src/main/java/me/caseload/knockbacksync/world/raytrace/FluidHandling.java new file mode 100644 index 0000000..a639056 --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/world/raytrace/FluidHandling.java @@ -0,0 +1,5 @@ +package me.caseload.knockbacksync.world.raytrace; + +public enum FluidHandling { + NONE, SOURCE_ONLY, ALWAYS +} diff --git a/common/src/main/java/me/caseload/knockbacksync/world/raytrace/RayTraceOption.java b/common/src/main/java/me/caseload/knockbacksync/world/raytrace/RayTraceOption.java new file mode 100644 index 0000000..30c4466 --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/world/raytrace/RayTraceOption.java @@ -0,0 +1,5 @@ +package me.caseload.knockbacksync.world.raytrace; + +public enum RayTraceOption { + BLOCK, FLUID, NONE +} \ No newline at end of file diff --git a/common/src/main/java/me/caseload/knockbacksync/world/raytrace/RayTraceResult.java b/common/src/main/java/me/caseload/knockbacksync/world/raytrace/RayTraceResult.java new file mode 100644 index 0000000..b9322fd --- /dev/null +++ b/common/src/main/java/me/caseload/knockbacksync/world/raytrace/RayTraceResult.java @@ -0,0 +1,23 @@ +package me.caseload.knockbacksync.world.raytrace; + +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 lombok.Getter; + +@Getter +public class RayTraceResult { + private final Vector3d hitPosition; + private final BlockFace blockFace; + private final Vector3i hitBlockPosition; + private final WrappedBlockState hitBlock; + + public RayTraceResult(Vector3d hitPosition, BlockFace blockFace, Vector3i hitBlockPosition, WrappedBlockState hitBlock) { + this.hitPosition = hitPosition; + this.blockFace = blockFace; + this.hitBlockPosition = hitBlockPosition; + this.hitBlock = hitBlock; + } + +} \ No newline at end of file diff --git a/src/main/resources/config.yml b/common/src/main/resources/config.yml similarity index 73% rename from src/main/resources/config.yml rename to common/src/main/resources/config.yml index 14bae41..8953a49 100644 --- a/src/main/resources/config.yml +++ b/common/src/main/resources/config.yml @@ -1,31 +1,41 @@ -######################################### -# KnockbackSync Configuration # -######################################### - -# Plugin enabled state -# Toggleable using /knockbacksync toggle -# Required permission: knockbacksync.toggle -enabled: true - -# Notify staff about update availability -# Required permission: knockbacksync.update -notify_updates: true - -# Grabs the ping of combat-tagged players every x ticks -# Disabling this may lead to inaccuracies in calculations -runnable: - enabled: true # Runnable enabled state - interval: 5 # The interval in ticks between sending out pings to players - combat_timer: 30 # The timer in ticks before being considered out of combat - -# The minimum change in ping required for it to be considered a lag spike. -# If the difference between the latest and previous ping is greater than or equal to -# the threshold, the previous ping value is used to avoid calculation inaccuracies. -spike_threshold: 20 - -enable_message: "&aSuccessfully enabled KnockbackSync." -disable_message: "&cSuccessfully disabled KnockbackSync." -player_enable_message: "&aSuccessfully enabled KnockbackSync for %player%." -player_disable_message: "&cSuccessfully disabled KnockbackSync for %player%." -player_ineligible_message: "&c%player% is ineligible for KnockbackSync. If you believe this is an error, please open an issue on the github page." -reload_message: "&aSuccessfully reloaded KnockbackSync config." \ No newline at end of file +######################################### +# KnockbackSync Configuration # +######################################### + +# Plugin enabled state +# Toggleable using /knockbacksync toggle +# Required permission: knockbacksync.toggle +enabled: true + +# Notify staff about update availability +# Required permission: knockbacksync.update +notify_updates: true + +# Grabs the ping of combat-tagged players every x ticks +# Disabling this may lead to inaccuracies in calculations +runnable: + enabled: true # Runnable enabled state + interval: 5 # The interval in ticks between sending out pings to players + combat_timer: 30 # The timer in ticks before being considered out of combat + +# The minimum change in ping required for it to be considered a lag spike. +# If the difference between the latest and previous ping is greater than or equal to +# the threshold, the previous ping value is used to avoid calculation inaccuracies. +spike_threshold: 20 + +enable_experimental_offground: false + +enable_message: "&aSuccessfully enabled KnockbackSync." +disable_message: "&cSuccessfully disabled KnockbackSync." +player_enable_message: "&aSuccessfully enabled KnockbackSync for %player%." +player_disable_message: "&cSuccessfully disabled KnockbackSync for %player%." +player_ineligible_message: "&c%player% is ineligible for KnockbackSync. If you believe this is an error, please open an issue on the github page." +reload_message: "&aSuccessfully reloaded KnockbackSync config." +global_status_message: "&eGlobal KnockbackSync status: " +player_status_message: "&e%player%'s KnockbackSync status: " +player_disabled_global_message: "&cDisabled (Global toggle is off)" +enable_experimental_offground_message: "&aSuccessfully enabled offground experiment." +disable_experimental_offground_message: "&cSuccessfully disabled offground experiment." + +# Read FAQ! +ping_offset: 25 \ No newline at end of file diff --git a/fabric/build.gradle.kts b/fabric/build.gradle.kts new file mode 100644 index 0000000..d5d52ee --- /dev/null +++ b/fabric/build.gradle.kts @@ -0,0 +1,77 @@ +plugins { + id("fabric-loom") + id("com.gradleup.shadow") +} + +base { + archivesName.set("${rootProject.property("archives_base_name")}-fabric") +} + +val shadeThisThing: Configuration by configurations.creating { + isCanBeConsumed = true + isTransitive = true +} + +tasks.jar { + from(project(":common").sourceSets.named("main").get().output) +} + +dependencies { + shadeThisThing(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.5.8-SNAPSHOT")!!) + + shadeThisThing(implementation("com.fasterxml.jackson.core:jackson-databind:2.17.2")!!) + shadeThisThing(implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.17.2")!!) + shadeThisThing(implementation("org.kohsuke:github-api:1.326")!!) + +// include(implementation("com.fasterxml.jackson.core:jackson-databind:2.17.2")!!) +// include(implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.17.2")!!) +// include(implementation("org.kohsuke:github-api:1.326")!!) + +// include(implementation("org.kohsuke:github-api:1.326") { +// exclude(group = "commons-io", module = "commons-io") +// exclude(group = "org.apache.commons", module = "commons-lang3") +// }) + + 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 = false + 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 { + 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") + ) + } +} \ No newline at end of file diff --git a/fabric/src/main/java/me/caseload/knockbacksync/KnockbackSyncFabric.java b/fabric/src/main/java/me/caseload/knockbacksync/KnockbackSyncFabric.java new file mode 100644 index 0000000..107ea1e --- /dev/null +++ b/fabric/src/main/java/me/caseload/knockbacksync/KnockbackSyncFabric.java @@ -0,0 +1,171 @@ +package me.caseload.knockbacksync; + +import com.github.retrooper.packetevents.PacketEvents; +import io.github.retrooper.packetevents.factory.fabric.FabricPacketEventsBuilder; +import me.caseload.knockbacksync.command.KnockbackSyncCommand; +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.permission.FabricPermissionChecker; +import me.caseload.knockbacksync.permission.PermissionChecker; +import me.caseload.knockbacksync.scheduler.FabricSchedulerAdapter; +import me.caseload.knockbacksync.stats.custom.FabricStatsManager; +import me.caseload.knockbacksync.stats.custom.PluginJarHashProvider; +import me.caseload.knockbacksync.world.FabricServer; +import net.fabricmc.api.ModInitializer; +import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback; +import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents; +import net.fabricmc.loader.api.FabricLoader; +import net.fabricmc.loader.api.ModContainer; +import net.fabricmc.loader.api.entrypoint.PreLaunchEntrypoint; +import net.minecraft.commands.Commands; +import net.minecraft.server.MinecraftServer; + +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.security.MessageDigest; +import java.util.Optional; +import java.util.logging.Logger; + +public class KnockbackSyncFabric implements PreLaunchEntrypoint, ModInitializer { + +// private static MinecraftServer SERVER; + + private final KnockbackSyncBase core = new KnockbackSyncBase() { + + { + statsManager = new FabricStatsManager(); + platformServer = new FabricServer(); + URL jarUrl = null; + Optional 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); + } + } + pluginJarHashProvider = new PluginJarHashProvider(jarUrl); + } + + private final Logger logger = Logger.getLogger(KnockbackSyncFabric.class.getName()); + private final FabricPermissionChecker permissionChecker = new FabricPermissionChecker(); + + @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(FabricPacketEventsBuilder.build("knockbacksync")); + PacketEvents.getAPI().load(); + } + + @Override + public void initializeScheduler() { + scheduler = new FabricSchedulerAdapter(); + } + + @Override + protected void registerPlatformListeners() { + new FabricPlayerJoinQuitListener().register(); + new FabricPlayerDamageListener().register(); + new FabricPlayerKnockbackListener().register(); + } + + @Override + protected void registerCommands() { +// ServerLifecycleEvents.SERVER_STARTED.register(server -> { +// CommandDispatcher dispatcher = server.getCommands().getDispatcher(); +// dispatcher.register(KnockbackSyncCommand.build()); +// }); + CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> { + dispatcher.register(KnockbackSyncCommand.build()); + dispatcher.register( + Commands.literal("kbsync") + .redirect(dispatcher.getRoot().getChild("knockbacksync"))); + }); + } + + @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 void initializePacketEvents() { + PacketEvents.getAPI().getSettings() + .checkForUpdates(false) + .debug(false); + + PacketEvents.getAPI().init(); + } + }; + + @Override + public void onPreLaunch() { + core.load(); +// ServerLifecycleEvents.SERVER_STARTING.register((minecraftServer -> { +// SERVER = minecraftServer; +// core.initializeScheduler(); +// core.configManager.loadConfig(false); +// core.statsManager.init(); +// core.checkForUpdates(); +// })); + } + + @Override + public void onInitialize() { + core.enable(); + core.initializeScheduler(); + core.configManager.loadConfig(false); + core.statsManager.init(); + core.checkForUpdates(); + ServerLifecycleEvents.SERVER_STOPPING.register((server) -> { + core.scheduler.shutdown(); + core.statsManager.getMetrics().shutdown(); + }); + } + + public static MinecraftServer getServer() { + return (MinecraftServer) FabricLoader.getInstance().getGameInstance(); + } +} diff --git a/fabric/src/main/java/me/caseload/knockbacksync/callback/PlayerVelocityCallback.java b/fabric/src/main/java/me/caseload/knockbacksync/callback/PlayerVelocityCallback.java new file mode 100644 index 0000000..179b550 --- /dev/null +++ b/fabric/src/main/java/me/caseload/knockbacksync/callback/PlayerVelocityCallback.java @@ -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 PlayerVelocityCallback { + Event EVENT = EventFactory.createArrayBacked(PlayerVelocityCallback.class, + (listeners) -> (player, velocity) -> { + for (PlayerVelocityCallback listener : listeners) { + InteractionResult result = listener.onVelocityChange(player, velocity); + + if (result != InteractionResult.PASS) { + return result; + } + } + + return InteractionResult.PASS; + }); + + InteractionResult onVelocityChange(ServerPlayer player, Vec3 velocity); +} \ No newline at end of file diff --git a/fabric/src/main/java/me/caseload/knockbacksync/listener/fabric/FabricPlayerDamageListener.java b/fabric/src/main/java/me/caseload/knockbacksync/listener/fabric/FabricPlayerDamageListener.java new file mode 100644 index 0000000..d961969 --- /dev/null +++ b/fabric/src/main/java/me/caseload/knockbacksync/listener/fabric/FabricPlayerDamageListener.java @@ -0,0 +1,41 @@ +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; + }); + + // Sending ping packets on tick if runnable is disabled +// ServerTickEvents.END_SERVER_TICK.register(server -> { +// if (!KnockbackSyncBase.INSTANCE.getConfigManager().isRunnableEnabled()) { +// for (ServerPlayerEntity player : server.getPlayerList()) { +// PlayerData playerData = PlayerDataManager.getPlayerData(player); +// if (playerData != null) { +// playerData.sendPing(); +// } +// } +// } +// }); + } + + 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 + } + } +} \ No newline at end of file diff --git a/fabric/src/main/java/me/caseload/knockbacksync/listener/fabric/FabricPlayerJoinQuitListener.java b/fabric/src/main/java/me/caseload/knockbacksync/listener/fabric/FabricPlayerJoinQuitListener.java new file mode 100644 index 0000000..5201878 --- /dev/null +++ b/fabric/src/main/java/me/caseload/knockbacksync/listener/fabric/FabricPlayerJoinQuitListener.java @@ -0,0 +1,17 @@ +package me.caseload.knockbacksync.listener.fabric; + +import me.caseload.knockbacksync.listener.PlayerJoinQuitListener; +import me.caseload.knockbacksync.manager.PlayerData; +import me.caseload.knockbacksync.player.FabricPlayer; +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()); + })); + } +} diff --git a/fabric/src/main/java/me/caseload/knockbacksync/listener/fabric/FabricPlayerKnockbackListener.java b/fabric/src/main/java/me/caseload/knockbacksync/listener/fabric/FabricPlayerKnockbackListener.java new file mode 100644 index 0000000..cd5dd1b --- /dev/null +++ b/fabric/src/main/java/me/caseload/knockbacksync/listener/fabric/FabricPlayerKnockbackListener.java @@ -0,0 +1,33 @@ +package me.caseload.knockbacksync.listener.fabric; + +import com.github.retrooper.packetevents.util.Vector3d; +import me.caseload.knockbacksync.callback.PlayerVelocityCallback; +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.DamageSources; +import net.minecraft.world.damagesource.DamageTypes; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.player.Player; + +public class FabricPlayerKnockbackListener extends PlayerKnockbackListener { + + public void register() { + PlayerVelocityCallback.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; + }); + } +} \ No newline at end of file diff --git a/fabric/src/main/java/me/caseload/knockbacksync/mixin/PlayerMixin.java b/fabric/src/main/java/me/caseload/knockbacksync/mixin/PlayerMixin.java new file mode 100644 index 0000000..03adc35 --- /dev/null +++ b/fabric/src/main/java/me/caseload/knockbacksync/mixin/PlayerMixin.java @@ -0,0 +1,37 @@ +package me.caseload.knockbacksync.mixin; + +import me.caseload.knockbacksync.callback.PlayerVelocityCallback; +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;(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 = PlayerVelocityCallback.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 + } + } + } +} diff --git a/fabric/src/main/java/me/caseload/knockbacksync/mixin/ServerEntityMixin.java b/fabric/src/main/java/me/caseload/knockbacksync/mixin/ServerEntityMixin.java new file mode 100644 index 0000000..e1e3f4c --- /dev/null +++ b/fabric/src/main/java/me/caseload/knockbacksync/mixin/ServerEntityMixin.java @@ -0,0 +1,40 @@ +package me.caseload.knockbacksync.mixin; + +import me.caseload.knockbacksync.callback.PlayerVelocityCallback; +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; + + @Inject(method = "sendChanges", at = @At(value = "FIELD", target = "Lnet/minecraft/world/entity/Entity;hurtMarked:Z", ordinal = 1)) + private void onSendChanges(CallbackInfo ci) { + if (this.entity.hurtMarked && this.entity instanceof ServerPlayer) { + ServerPlayer player = (ServerPlayer) this.entity; + Vec3 velocity = player.getDeltaMovement(); + + InteractionResult result = PlayerVelocityCallback.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); + } + } + } +} \ No newline at end of file diff --git a/fabric/src/main/java/me/caseload/knockbacksync/permission/FabricPermissionChecker.java b/fabric/src/main/java/me/caseload/knockbacksync/permission/FabricPermissionChecker.java new file mode 100644 index 0000000..7f464e1 --- /dev/null +++ b/fabric/src/main/java/me/caseload/knockbacksync/permission/FabricPermissionChecker.java @@ -0,0 +1,18 @@ +package me.caseload.knockbacksync.permission; + +import me.caseload.knockbacksync.player.FabricPlayer; +import me.caseload.knockbacksync.player.PlatformPlayer; +import me.lucko.fabric.api.permissions.v0.Permissions; +import net.minecraft.commands.CommandSourceStack; + +public class FabricPermissionChecker implements PermissionChecker { + @Override + public boolean hasPermission(CommandSourceStack source, String s, boolean defaultIfUnset) { + return Permissions.check(source, s, defaultIfUnset); + } + + @Override + public boolean hasPermission(PlatformPlayer platformPlayer, String s) { + return Permissions.check(((FabricPlayer) platformPlayer).fabricPlayer, s); + } +} diff --git a/fabric/src/main/java/me/caseload/knockbacksync/player/FabricPlayer.java b/fabric/src/main/java/me/caseload/knockbacksync/player/FabricPlayer.java new file mode 100644 index 0000000..f5f8af4 --- /dev/null +++ b/fabric/src/main/java/me/caseload/knockbacksync/player/FabricPlayer.java @@ -0,0 +1,129 @@ +package me.caseload.knockbacksync.player; + +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.item.enchantment.Enchantment; +import net.minecraft.world.item.enchantment.EnchantmentHelper; +import net.minecraft.world.item.enchantment.Enchantments; +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; + + public FabricPlayer(ServerPlayer player) { + this.fabricPlayer = player; + } + + @Override + public UUID getUUID() { + return fabricPlayer.getUUID(); + } + + @Override + public String getName() { + return fabricPlayer.getName().toString(); + } + + @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() { + Vec3 pos = fabricPlayer.position(); + return new Vector3d(pos.x, pos.y, pos.z); + } + + @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> + entry = VanillaRegistries.createLookup().asGetterLookup().get( + Registries.ENCHANTMENT, Enchantments.KNOCKBACK + ); + Holder 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; + } + + // Implement other methods +} diff --git a/fabric/src/main/java/me/caseload/knockbacksync/scheduler/FabricSchedulerAdapter.java b/fabric/src/main/java/me/caseload/knockbacksync/scheduler/FabricSchedulerAdapter.java new file mode 100644 index 0000000..1c39a2b --- /dev/null +++ b/fabric/src/main/java/me/caseload/knockbacksync/scheduler/FabricSchedulerAdapter.java @@ -0,0 +1,145 @@ +package me.caseload.knockbacksync.scheduler; + +import me.caseload.knockbacksync.KnockbackSyncBase; +import me.caseload.knockbacksync.KnockbackSyncFabric; +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 taskMap = new HashMap<>(); + private final Map asyncTasks = new HashMap<>(); + + public FabricSchedulerAdapter() { + ServerTickEvents.END_SERVER_TICK.register(this::handleTasks); + } + + private void handleTasks(MinecraftServer server) { + Iterator 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, KnockbackSyncFabric.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, KnockbackSyncFabric.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, KnockbackSyncFabric.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 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; + long nextRunTick; + final long period; + final boolean isPeriodic; + + ScheduledTask(Runnable task, long nextRunTick, long period, boolean isPeriodic) { + this.task = task; + this.nextRunTick = nextRunTick; + this.period = period; + this.isPeriodic = isPeriodic; + } + } +} \ No newline at end of file diff --git a/fabric/src/main/java/me/caseload/knockbacksync/scheduler/FabricTaskHandle.java b/fabric/src/main/java/me/caseload/knockbacksync/scheduler/FabricTaskHandle.java new file mode 100644 index 0000000..f004e57 --- /dev/null +++ b/fabric/src/main/java/me/caseload/knockbacksync/scheduler/FabricTaskHandle.java @@ -0,0 +1,21 @@ +package me.caseload.knockbacksync.scheduler; + +public class FabricTaskHandle implements AbstractTaskHandle { + private 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; + } +} diff --git a/fabric/src/main/java/me/caseload/knockbacksync/stats/custom/FabricStatsManager.java b/fabric/src/main/java/me/caseload/knockbacksync/stats/custom/FabricStatsManager.java new file mode 100644 index 0000000..5b3ea4d --- /dev/null +++ b/fabric/src/main/java/me/caseload/knockbacksync/stats/custom/FabricStatsManager.java @@ -0,0 +1,16 @@ +package me.caseload.knockbacksync.stats.custom; + +import me.caseload.knockbacksync.KnockbackSyncBase; + +public class FabricStatsManager extends StatsManager { + @Override + public void init() { + KnockbackSyncBase.INSTANCE.getScheduler().runTaskAsynchronously(() -> { + BuildTypePie.determineBuildType(); // Function to calculate hash + MetricsFabric metrics = new MetricsFabric(23568); + metrics.addCustomChart(new PlayerVersionsPie()); + metrics.addCustomChart(new BuildTypePie()); + super.metrics = metrics; + }); + } +} diff --git a/fabric/src/main/java/me/caseload/knockbacksync/stats/custom/MetricsFabric.java b/fabric/src/main/java/me/caseload/knockbacksync/stats/custom/MetricsFabric.java new file mode 100644 index 0000000..b0b33d9 --- /dev/null +++ b/fabric/src/main/java/me/caseload/knockbacksync/stats/custom/MetricsFabric.java @@ -0,0 +1,149 @@ +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 com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; +import me.caseload.knockbacksync.KnockbackSyncBase; +import me.caseload.knockbacksync.KnockbackSyncFabric; +import me.caseload.knockbacksync.stats.CustomChart; +import me.caseload.knockbacksync.stats.JsonObjectBuilder; +import net.fabricmc.loader.api.FabricLoader; +import net.minecraft.server.MinecraftServer; + +import java.io.*; +import java.util.UUID; +import java.util.logging.Level; + +public class MetricsFabric implements Metrics { + + private final MetricsBase metricsBase; + + private static class Config { + public boolean enabled = true; + public String serverUuid; + public boolean logFailedRequests = false; + public boolean logSentData = false; + public boolean logResponseStatusText = false; + } + + /** + * Creates a new Metrics instance. + * + * @param serviceId The id of the service. It can be found at What is my plugin id? + */ + public MetricsFabric(int serviceId) { + // Get the config file + File bStatsFolder = new File(FabricLoader.getInstance().getConfigDir().toString(), "bStats"); + File configFile = new File(bStatsFolder, "config.yml"); + ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); + Config config; + + try { + if (!configFile.exists()) { + bStatsFolder.mkdirs(); // Ensure the directory exists + + config = new Config(); + config.serverUuid = UUID.randomUUID().toString(); + + // Add header as a comment +// mapper.writeValue(configFile, +// "# bStats (https://bStats.org) collects some basic information for plugin authors, like how\n" +// + "# many people use their plugin and their total player count. It's recommended to keep bStats\n" +// + "# enabled, but if you're not comfortable with this, you can turn this setting off. There is no\n" +// + "# performance penalty associated with having metrics enabled, and data sent to bStats is fully\n" +// + "# anonymous.\n"); + mapper.writeValue(configFile, config); // Write the config object as YAML + } else { + config = mapper.readValue(configFile, Config.class); + } + } catch (IOException ignored) { + // Handle the exception appropriately (e.g., log an error) + config = new Config(); // Fallback to default values + config.serverUuid = UUID.randomUUID().toString(); + } + + // 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 -> KnockbackSyncBase.INSTANCE.getScheduler().runTask(submitDataTask), + () -> true, + (message, error) -> KnockbackSyncBase.INSTANCE.getLogger().log(Level.WARNING, message, error), + (message) -> KnockbackSyncBase.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", KnockbackSyncFabric.getServer().usesAuthentication() ? 0 : 1); + builder.appendField("bukkitVersion", "Fabric " + FabricLoader.getInstance().getModContainer("fabricloader").get().getMetadata().getVersion().getFriendlyString() + " (MC: " + KnockbackSyncFabric.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 (KnockbackSyncFabric.getServer().isRunning()) { + return KnockbackSyncFabric.getServer().getPlayerCount(); + } else { + return 0; + } + } +} diff --git a/fabric/src/main/java/me/caseload/knockbacksync/world/FabricServer.java b/fabric/src/main/java/me/caseload/knockbacksync/world/FabricServer.java new file mode 100644 index 0000000..6eec2f8 --- /dev/null +++ b/fabric/src/main/java/me/caseload/knockbacksync/world/FabricServer.java @@ -0,0 +1,23 @@ +package me.caseload.knockbacksync.world; + +import me.caseload.knockbacksync.KnockbackSyncFabric; +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 getOnlinePlayers() { + return KnockbackSyncFabric.getServer().getPlayerList().getPlayers().stream() + .map(FabricPlayer::new) + .collect(Collectors.toList()); + } + + @Override + public PlatformPlayer getPlayer(UUID uuid) { + return new FabricPlayer(KnockbackSyncFabric.getServer().getPlayerList().getPlayer(uuid)); + } + +} diff --git a/fabric/src/main/java/me/caseload/knockbacksync/world/FabricWorld.java b/fabric/src/main/java/me/caseload/knockbacksync/world/FabricWorld.java new file mode 100644 index 0000000..e7d2b16 --- /dev/null +++ b/fabric/src/main/java/me/caseload/knockbacksync/world/FabricWorld.java @@ -0,0 +1,61 @@ +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.state.BlockState; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.Vec3; + +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.getByString(blockState.getBlock().getName().toString()); + } + + @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, + (Entity) null + )); + + if (result.getType() == HitResult.Type.MISS) return null; + + BlockPos blockPos = result.getBlockPos(); + return new RayTraceResult( + new Vector3d(result.getLocation().x, result.getLocation().y, result.getLocation().z), + BlockFace.getBlockFaceByValue(result.getDirection().ordinal()), + new Vector3i(result.getBlockPos().getX(), result.getBlockPos().getY(), result.getBlockPos().getZ()), + WrappedBlockState.getByString(world.getBlockState(blockPos).getBlock().toString()) + ); + } +} \ No newline at end of file diff --git a/fabric/src/main/resources/fabric.mod.json b/fabric/src/main/resources/fabric.mod.json new file mode 100644 index 0000000..74f0154 --- /dev/null +++ b/fabric/src/main/resources/fabric.mod.json @@ -0,0 +1,25 @@ +{ + "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.KnockbackSyncFabric" + ] + }, + "mixins": [ + "knockbacksync.mixins.json" + ], + "depends": { + "fabricloader": ">=${loader_version}", + "fabric": "*", + "minecraft": "~${minecraft_version}" + } +} diff --git a/fabric/src/main/resources/knockbacksync.mixins.json b/fabric/src/main/resources/knockbacksync.mixins.json new file mode 100644 index 0000000..c52225a --- /dev/null +++ b/fabric/src/main/resources/knockbacksync.mixins.json @@ -0,0 +1,13 @@ +{ + "required": true, + "minVersion": "0.8", + "package": "me.caseload.knockbacksync.mixin", + "compatibilityLevel": "JAVA_21", + "mixins": [ + "PlayerMixin", + "ServerEntityMixin" + ], + "injectors": { + "defaultRequire": 1 + } +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..581251b --- /dev/null +++ b/gradle.properties @@ -0,0 +1,20 @@ +# Gradle Properties +org.gradle.jvmargs=-Xmx3G +org.gradle.parallel=true + +# 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 + +# Mod Properties +mod_version=1.3.3-dev-axionize-b23 +maven_group=me.caseload +archives_base_name=knockbacksync + +# Dependencies +# check this on https://modmuss50.me/fabric.html +fabric_version=0.102.0+1.21 diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..b740cf1 --- /dev/null +++ b/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..25da30d --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..aa35a8e --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,16 @@ +enableFeaturePreview("TYPESAFE_PROJECT_ACCESSORS") + +pluginManagement { + repositories { + gradlePluginPortal() + maven("https://maven.fabricmc.net/") + } +} + +include("common", "fabric", "bukkit") + +rootProject.name = "KnockbackSync" + +plugins { + id("org.gradle.toolchains.foojay-resolver-convention") version "0.8.0" +} \ No newline at end of file diff --git a/src/main/java/me/caseload/knockbacksync/KnockbackSync.java b/src/main/java/me/caseload/knockbacksync/KnockbackSync.java deleted file mode 100644 index f08d6c8..0000000 --- a/src/main/java/me/caseload/knockbacksync/KnockbackSync.java +++ /dev/null @@ -1,116 +0,0 @@ -package me.caseload.knockbacksync; - -import com.github.retrooper.packetevents.PacketEvents; -import dev.jorel.commandapi.CommandAPI; -import dev.jorel.commandapi.CommandAPIBukkitConfig; -import io.github.retrooper.packetevents.factory.spigot.SpigotPacketEventsBuilder; -import lombok.Getter; -import me.caseload.knockbacksync.command.MainCommand; -import me.caseload.knockbacksync.listener.*; -import me.caseload.knockbacksync.manager.ConfigManager; -import me.caseload.knockbacksync.scheduler.BukkitSchedulerAdapter; -import me.caseload.knockbacksync.scheduler.FoliaSchedulerAdapter; -import me.caseload.knockbacksync.scheduler.SchedulerAdapter; -import me.caseload.knockbacksync.stats.StatsManager; -import org.bukkit.event.Listener; -import org.bukkit.plugin.PluginManager; -import org.bukkit.plugin.java.JavaPlugin; -import org.kohsuke.github.GitHub; - -import java.util.logging.Logger; - -public final class KnockbackSync extends JavaPlugin { - - public static Logger LOGGER; - public static KnockbackSync INSTANCE; - @Getter - private SchedulerAdapter scheduler; - public final boolean isFolia = io.github.retrooper.packetevents.util.folia.FoliaScheduler.isFolia(); - - @Getter - private final ConfigManager configManager = new ConfigManager(); - - @Override - public void onLoad() { - CommandAPI.onLoad(new CommandAPIBukkitConfig(this)); - PacketEvents.setAPI(SpigotPacketEventsBuilder.build(this)); - PacketEvents.getAPI().load(); - } - - @Override - public void onEnable() { - LOGGER = getLogger(); - INSTANCE = this; - checkForUpdates(); - - scheduler = isFolia ? new FoliaSchedulerAdapter(this) : new BukkitSchedulerAdapter(this); - - saveDefaultConfig(); - configManager.loadConfig(false); - - CommandAPI.onEnable(); - new MainCommand().register(); - - registerListeners( - new PlayerDamageListener(), - new PlayerKnockbackListener(), - new PlayerJoinQuitListener() - ); - - PacketEvents.getAPI().getEventManager().registerListeners( - new AttributeChangeListener(), - new PingReceiveListener() - ); - - PacketEvents.getAPI().getSettings() - .checkForUpdates(false) - .debug(false); - - PacketEvents.getAPI().load(); - PacketEvents.getAPI().init(); - - StatsManager.init(); - } - - @Override - public void onDisable() { - CommandAPI.onDisable(); - PacketEvents.getAPI().terminate(); - } - - public static KnockbackSync getInstance() { - return getPlugin(KnockbackSync.class); - } - - private void registerListeners(Listener... listeners) { - PluginManager pluginManager = getServer().getPluginManager(); - for (Listener listener : listeners) - pluginManager.registerEvents(listener, this); - } - - private void checkForUpdates() { - getLogger().info("Checking for updates..."); - - scheduler.runTaskAsynchronously(() -> { - try { - GitHub github = GitHub.connectAnonymously(); - String latestVersion = github.getRepository("CASELOAD7000/knockback-sync") - .getLatestRelease() - .getTagName(); - - String currentVersion = getDescription().getVersion(); - boolean updateAvailable = !currentVersion.equalsIgnoreCase(latestVersion); - - if (updateAvailable) { - LOGGER.warning("A new update is available for download at: https://github.com/CASELOAD7000/knockback-sync/releases/latest"); - } else { - LOGGER.info("You are running the latest release."); - } - - configManager.setUpdateAvailable(updateAvailable); - } catch (Exception e) { - LOGGER.severe("Failed to check for updates: " + e.getMessage()); - } - }); - } -} \ No newline at end of file diff --git a/src/main/java/me/caseload/knockbacksync/command/MainCommand.java b/src/main/java/me/caseload/knockbacksync/command/MainCommand.java deleted file mode 100644 index 8823165..0000000 --- a/src/main/java/me/caseload/knockbacksync/command/MainCommand.java +++ /dev/null @@ -1,27 +0,0 @@ -package me.caseload.knockbacksync.command; - -import dev.jorel.commandapi.CommandAPICommand; -import me.caseload.knockbacksync.command.subcommand.PingSubcommand; -import me.caseload.knockbacksync.command.subcommand.ReloadSubcommand; -import me.caseload.knockbacksync.command.subcommand.StatusSubcommand; -import me.caseload.knockbacksync.command.subcommand.ToggleSubcommand; -import org.bukkit.ChatColor; - -public class MainCommand { - - public void register() { - new CommandAPICommand("knockbacksync") - .withAliases("kbsync") - .withSubcommand(new PingSubcommand().getCommand()) - .withSubcommand(new ToggleSubcommand().getCommand()) - .withSubcommand(new ReloadSubcommand().getCommand()) - .withSubcommand(new StatusSubcommand().getCommand()) - .executes((sender, args) -> { - sender.sendMessage(ChatColor.translateAlternateColorCodes( - '&', - "&6This server is running the &eKnockbackSync &6plugin. &bhttps://github.com/CASELOAD7000/knockback-sync" - )); - }) - .register(); - } -} \ No newline at end of file diff --git a/src/main/java/me/caseload/knockbacksync/command/subcommand/PingSubcommand.java b/src/main/java/me/caseload/knockbacksync/command/subcommand/PingSubcommand.java deleted file mode 100644 index 15a1539..0000000 --- a/src/main/java/me/caseload/knockbacksync/command/subcommand/PingSubcommand.java +++ /dev/null @@ -1,23 +0,0 @@ -package me.caseload.knockbacksync.command.subcommand; - -import dev.jorel.commandapi.CommandAPICommand; -import dev.jorel.commandapi.arguments.PlayerArgument; -import me.caseload.knockbacksync.manager.PlayerData; -import me.caseload.knockbacksync.manager.PlayerDataManager; -import org.bukkit.entity.Player; - -public class PingSubcommand { - - public CommandAPICommand getCommand() { - return new CommandAPICommand("ping") - .withPermission("knockbacksync.ping") - .withArguments(new PlayerArgument("target")) - .executes((sender, args) -> { - Player target = (Player) args.get("target"); - assert target != null; - - PlayerData playerData = PlayerDataManager.getPlayerData(target.getUniqueId()); - sender.sendMessage(target.getName() + "'s last ping packet took " + playerData.getPing() + "ms."); - }); - } -} \ No newline at end of file diff --git a/src/main/java/me/caseload/knockbacksync/command/subcommand/ReloadSubcommand.java b/src/main/java/me/caseload/knockbacksync/command/subcommand/ReloadSubcommand.java deleted file mode 100644 index 4e703a5..0000000 --- a/src/main/java/me/caseload/knockbacksync/command/subcommand/ReloadSubcommand.java +++ /dev/null @@ -1,25 +0,0 @@ -package me.caseload.knockbacksync.command.subcommand; - -import dev.jorel.commandapi.CommandAPICommand; -import me.caseload.knockbacksync.KnockbackSync; -import me.caseload.knockbacksync.manager.ConfigManager; -import org.bukkit.ChatColor; -import org.bukkit.event.Listener; - -public class ReloadSubcommand implements Listener { - - public CommandAPICommand getCommand() { - return new CommandAPICommand("reload") - .withPermission("knockbacksync.reload") - .executes((sender, args) -> { - ConfigManager configManager = KnockbackSync.getInstance().getConfigManager(); - configManager.loadConfig(true); - - String reloadMessage = ChatColor.translateAlternateColorCodes('&', - configManager.getReloadMessage() - ); - - sender.sendMessage(reloadMessage); - }); - } -} \ No newline at end of file diff --git a/src/main/java/me/caseload/knockbacksync/command/subcommand/StatusSubcommand.java b/src/main/java/me/caseload/knockbacksync/command/subcommand/StatusSubcommand.java deleted file mode 100644 index fdab98b..0000000 --- a/src/main/java/me/caseload/knockbacksync/command/subcommand/StatusSubcommand.java +++ /dev/null @@ -1,58 +0,0 @@ -package me.caseload.knockbacksync.command.subcommand; - -import dev.jorel.commandapi.CommandAPICommand; -import dev.jorel.commandapi.CommandPermission; -import dev.jorel.commandapi.arguments.PlayerArgument; -import me.caseload.knockbacksync.KnockbackSync; -import me.caseload.knockbacksync.manager.ConfigManager; -import me.caseload.knockbacksync.manager.PlayerDataManager; -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; -import org.bukkit.event.Listener; - -import java.util.UUID; - -public class StatusSubcommand implements Listener { - - public CommandAPICommand getCommand() { - return new CommandAPICommand("status") - .withPermission(CommandPermission.NONE) - .withOptionalArguments(new PlayerArgument("target")) - .executes((sender, args) -> { - ConfigManager configManager = KnockbackSync.getInstance().getConfigManager(); - Player target = (Player) args.get("target"); - - // Show global status - boolean globalStatus = configManager.isToggled(); - sender.sendMessage(ChatColor.YELLOW + "Global KnockbackSync status: " + - (globalStatus ? ChatColor.GREEN + "Enabled" : ChatColor.RED + "Disabled")); - - // Show player status - if (target == null && sender instanceof Player) - target = (Player) sender; - - if (target == null) - return; - - if (sender.hasPermission("knockbacksync.status.self") || - (sender.hasPermission("knockbacksync.status.other") && !sender.equals(target))) { - - UUID uuid = target.getUniqueId(); - boolean playerStatus = !PlayerDataManager.containsPlayerData(uuid); - - if (!globalStatus) { - sender.sendMessage(ChatColor.YELLOW + target.getName() + "'s KnockbackSync status: " + - ChatColor.RED + "Disabled (Global toggle is off)"); - } else { - sender.sendMessage(ChatColor.YELLOW + target.getName() + "'s KnockbackSync status: " + - (playerStatus ? ChatColor.GREEN + "Enabled" : ChatColor.RED + "Disabled")); - } - } else { - sender.sendMessage(ChatColor.RED + "You don't have the " - + (sender.equals(target) ? "knockbacksync.status.self" : "knockbacksync.status.other") + - " permission needed to check status for " + - (sender.equals(target) ? "yourself" : "other players") + "."); - } - }); - } -} \ No newline at end of file diff --git a/src/main/java/me/caseload/knockbacksync/command/subcommand/ToggleSubcommand.java b/src/main/java/me/caseload/knockbacksync/command/subcommand/ToggleSubcommand.java deleted file mode 100644 index 2751e86..0000000 --- a/src/main/java/me/caseload/knockbacksync/command/subcommand/ToggleSubcommand.java +++ /dev/null @@ -1,86 +0,0 @@ -package me.caseload.knockbacksync.command.subcommand; - -import dev.jorel.commandapi.CommandAPICommand; -import dev.jorel.commandapi.CommandPermission; -import dev.jorel.commandapi.arguments.PlayerArgument; -import me.caseload.knockbacksync.KnockbackSync; -import me.caseload.knockbacksync.manager.ConfigManager; -import me.caseload.knockbacksync.manager.PlayerData; -import me.caseload.knockbacksync.manager.PlayerDataManager; -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; -import org.bukkit.command.CommandSender; -import org.bukkit.event.Listener; - -import java.util.UUID; - -public class ToggleSubcommand implements Listener { - - public CommandAPICommand getCommand() { - return new CommandAPICommand("toggle") - .withPermission(CommandPermission.NONE) - .withOptionalArguments(new PlayerArgument("target")) - .executes((sender, args) -> { - ConfigManager configManager = KnockbackSync.getInstance().getConfigManager(); - Player target = (Player) args.get("target"); - String message; - - if (target == null) { - // Global toggle - if (sender.hasPermission("knockbacksync.toggle.global")) { - boolean toggledState = !configManager.isToggled(); - configManager.setToggled(toggledState); - - KnockbackSync.getInstance().getConfig().set("enabled", toggledState); - KnockbackSync.getInstance().saveConfig(); - - message = ChatColor.translateAlternateColorCodes('&', - toggledState ? configManager.getEnableMessage() : configManager.getDisableMessage() - ); - } else { - message = ChatColor.RED + "You don't have permission to toggle the global setting."; - } - sender.sendMessage(message); - } else { - // Player-specific toggle - if (!configManager.isToggled()) { - message = ChatColor.RED + "Knockbacksync is currently disabled on this server. Contact your server administrator for more information."; - sender.sendMessage(message); - } else if (sender instanceof Player && sender.equals(target) && sender.hasPermission("knockbacksync.toggle.self")) { - togglePlayerKnockback(target, configManager, sender); - } else if (sender.hasPermission("knockbacksync.toggle.other")) { - togglePlayerKnockback(target, configManager, sender); - } else { - message = ChatColor.RED + "You don't have permission to toggle knockback for " + - (sender.equals(target) ? "yourself" : "other players") + "."; - sender.sendMessage(message); - } - } - }); - } - - private void togglePlayerKnockback(Player target, ConfigManager configManager, CommandSender sender) { - UUID uuid = target.getUniqueId(); - - if (PlayerDataManager.shouldExempt(uuid)) { - String message = ChatColor.translateAlternateColorCodes('&', - configManager.getPlayerIneligibleMessage() - ).replace("%player%", target.getName()); - - sender.sendMessage(message); - return; - } - - boolean hasPlayerData = PlayerDataManager.containsPlayerData(uuid); - if (hasPlayerData) - PlayerDataManager.removePlayerData(uuid); - else - PlayerDataManager.addPlayerData(uuid, new PlayerData(target)); - - String message = ChatColor.translateAlternateColorCodes('&', - hasPlayerData ? configManager.getPlayerDisableMessage() : configManager.getPlayerEnableMessage() - ).replace("%player%", target.getName()); - - sender.sendMessage(message); - } -} \ No newline at end of file diff --git a/src/main/java/me/caseload/knockbacksync/listener/PlayerDamageListener.java b/src/main/java/me/caseload/knockbacksync/listener/PlayerDamageListener.java deleted file mode 100644 index 00b14f7..0000000 --- a/src/main/java/me/caseload/knockbacksync/listener/PlayerDamageListener.java +++ /dev/null @@ -1,32 +0,0 @@ -package me.caseload.knockbacksync.listener; - -import me.caseload.knockbacksync.KnockbackSync; -import me.caseload.knockbacksync.manager.PlayerData; -import me.caseload.knockbacksync.manager.PlayerDataManager; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageByEntityEvent; - -public class PlayerDamageListener implements Listener { - - @EventHandler(ignoreCancelled = true) - public void onPlayerDamage(EntityDamageByEntityEvent event) { - if (!KnockbackSync.getInstance().getConfigManager().isToggled()) - return; - - if (!(event.getEntity() instanceof Player victim) || !(event.getDamager() instanceof Player attacker)) - return; - - PlayerData playerData = PlayerDataManager.getPlayerData(victim.getUniqueId()); - if (playerData == null) - return; - - playerData.setVerticalVelocity(playerData.calculateVerticalVelocity(attacker)); // do not move this calculation - playerData.setLastDamageTicks(victim.getNoDamageTicks()); - playerData.updateCombat(); - - if (!KnockbackSync.getInstance().getConfigManager().isRunnableEnabled()) - playerData.sendPing(); - } -} \ No newline at end of file diff --git a/src/main/java/me/caseload/knockbacksync/listener/PlayerJoinQuitListener.java b/src/main/java/me/caseload/knockbacksync/listener/PlayerJoinQuitListener.java deleted file mode 100644 index 3f0bb5c..0000000 --- a/src/main/java/me/caseload/knockbacksync/listener/PlayerJoinQuitListener.java +++ /dev/null @@ -1,41 +0,0 @@ -package me.caseload.knockbacksync.listener; - -import me.caseload.knockbacksync.KnockbackSync; -import me.caseload.knockbacksync.manager.PlayerData; -import me.caseload.knockbacksync.manager.PlayerDataManager; -import org.bukkit.ChatColor; -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; - -public class PlayerJoinQuitListener implements Listener { - - @EventHandler - public void onPlayerJoin(PlayerJoinEvent event) { - Player player = event.getPlayer(); - PlayerDataManager.addPlayerData(player.getUniqueId(), new PlayerData(player)); - - if (KnockbackSync.getInstance().getConfigManager().isUpdateAvailable() && KnockbackSync.getInstance().getConfigManager().isNotifyUpdate() && player.hasPermission("knockbacksync.update")) - player.sendMessage(ChatColor.translateAlternateColorCodes( - '&', - "&6An updated version of &eKnockbackSync &6is now available for download at: &bhttps://github.com/CASELOAD7000/knockback-sync/releases/latest" - )); - } - - @EventHandler - public void onPlayerQuit(PlayerQuitEvent event) { - UUID uuid = event.getPlayer().getUniqueId(); - PlayerData playerData = PlayerDataManager.getPlayerData(uuid); - if (playerData == null) - return; - - if (playerData.isInCombat()) - playerData.quitCombat(true); - - PlayerDataManager.removePlayerData(uuid); - } -} diff --git a/src/main/java/me/caseload/knockbacksync/listener/PlayerKnockbackListener.java b/src/main/java/me/caseload/knockbacksync/listener/PlayerKnockbackListener.java deleted file mode 100644 index b815671..0000000 --- a/src/main/java/me/caseload/knockbacksync/listener/PlayerKnockbackListener.java +++ /dev/null @@ -1,55 +0,0 @@ -package me.caseload.knockbacksync.listener; - -import me.caseload.knockbacksync.KnockbackSync; -import me.caseload.knockbacksync.manager.PlayerData; -import me.caseload.knockbacksync.manager.PlayerDataManager; -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; -import org.bukkit.event.entity.EntityDamageEvent; -import org.bukkit.event.player.PlayerVelocityEvent; -import org.bukkit.util.Vector; - -public class PlayerKnockbackListener implements Listener { - - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onPlayerVelocity(PlayerVelocityEvent event) { - if (!KnockbackSync.getInstance().getConfigManager().isToggled()) - return; - - Player victim = event.getPlayer(); - EntityDamageEvent entityDamageEvent = victim.getLastDamageCause(); - if (entityDamageEvent == null) - return; - - EntityDamageEvent.DamageCause damageCause = entityDamageEvent.getCause(); - if (damageCause != EntityDamageEvent.DamageCause.ENTITY_ATTACK) - return; - - Entity attacker = ((EntityDamageByEntityEvent) entityDamageEvent).getDamager(); - if (!(attacker instanceof Player)) - return; - - PlayerData playerData = PlayerDataManager.getPlayerData(victim.getUniqueId()); - if (playerData == null) - return; - - Integer damageTicks = playerData.getLastDamageTicks(); - if (damageTicks != null && damageTicks > 8) - return; - - Vector velocity = victim.getVelocity(); - Double verticalVelocity = playerData.getVerticalVelocity(); - if (verticalVelocity == null || !playerData.isOnGround(velocity.getY())) - return; - - Vector adjustedVelocity = velocity.clone().setY( - verticalVelocity - ); - - victim.setVelocity(adjustedVelocity); - } -} \ No newline at end of file diff --git a/src/main/java/me/caseload/knockbacksync/manager/ConfigManager.java b/src/main/java/me/caseload/knockbacksync/manager/ConfigManager.java index d3c1db4..e69de29 100644 --- a/src/main/java/me/caseload/knockbacksync/manager/ConfigManager.java +++ b/src/main/java/me/caseload/knockbacksync/manager/ConfigManager.java @@ -1,70 +0,0 @@ -package me.caseload.knockbacksync.manager; - -import lombok.Getter; -import lombok.Setter; -import me.caseload.knockbacksync.KnockbackSync; -import me.caseload.knockbacksync.runnable.PingRunnable; -import me.caseload.knockbacksync.scheduler.AbstractTaskHandle; -import org.bukkit.scheduler.BukkitTask; - -@Getter -@Setter -public class ConfigManager { - - private boolean toggled; - private boolean runnableEnabled; - private boolean updateAvailable; - private boolean notifyUpdate; - - private long runnableInterval; - private long combatTimer; - private long spikeThreshold; - - private String enableMessage; - private String disableMessage; - private String playerEnableMessage; - private String playerDisableMessage; - private String playerIneligibleMessage; - private String reloadMessage; - - private AbstractTaskHandle pingTask; - - public void loadConfig(boolean reloadConfig) { - KnockbackSync instance = KnockbackSync.getInstance(); - - if (reloadConfig) - instance.reloadConfig(); - - toggled = instance.getConfig().getBoolean("enabled", true); - - // Checks to see if the runnable was enabled... - // and if we now want to disable it - boolean newRunnableEnabled = instance.getConfig().getBoolean("runnable.enabled", true); - if (runnableEnabled && newRunnableEnabled && pingTask != null) // null check for first startup - pingTask.cancel(); - - runnableEnabled = newRunnableEnabled; - - if (runnableEnabled) { - long initialDelay = 0L; - long pingTaskRunnableInterval = runnableInterval; - // Folia does not allow 0 ticks of wait time - if (KnockbackSync.INSTANCE.isFolia) { - initialDelay = 1L; - pingTaskRunnableInterval = Math.max(pingTaskRunnableInterval, 1L); - } - pingTask = KnockbackSync.INSTANCE.getScheduler().runTaskTimerAsynchronously(new PingRunnable(), initialDelay, pingTaskRunnableInterval); - } - - notifyUpdate = instance.getConfig().getBoolean("notify_updates", true); - runnableInterval = instance.getConfig().getLong("runnable.interval", 5L); - combatTimer = instance.getConfig().getLong("runnable.timer", 30L); - spikeThreshold = instance.getConfig().getLong("spike_threshold", 20L); - enableMessage = instance.getConfig().getString("enable_message", "&aSuccessfully enabled KnockbackSync."); - disableMessage = instance.getConfig().getString("disable_message", "&cSuccessfully disabled KnockbackSync."); - playerEnableMessage = instance.getConfig().getString("player_enable_message", "&aSuccessfully enabled KnockbackSync for %player%."); - playerDisableMessage = instance.getConfig().getString("player_disable_message", "&cSuccessfully disabled KnockbackSync for %player%."); - playerIneligibleMessage = instance.getConfig().getString("player_ineligible_message", "&c%player% is ineligible for KnockbackSync. If you believe this is an error, please open an issue on the github page."); - reloadMessage = instance.getConfig().getString("reload_message", "&aSuccessfully reloaded KnockbackSync."); - } -}