232 Commits
Author SHA1 Message Date
Axionize f6e2498722 Fix queue erorr 2024-10-19 19:08:48 -04:00
Axionize e6367842ed Fix loading on Bukkit 2024-10-19 18:44:26 -04:00
Axionize 380174dade Temporarily do not shade in adventure 2024-10-19 18:08:40 -04:00
Axionize dab6b7a85b Remove CommandAPI 2024-10-19 18:07:06 -04:00
Axionize 4124c3ade3 Fix NPE on startup 2024-10-19 18:06:16 -04:00
Axionize 9abe7259a2 Refactor command system to be cleaner; shade in cloud into bukkit 2024-10-19 17:50:02 -04:00
Axionize 79656875c3 Mark Purpur support in github actions on Modrinth 2024-10-19 15:59:18 -04:00
Axionize bc6872d56f Config update 2024-10-19 14:54:53 -04:00
Axionize fb24f31146 Code Cleanup 2024-10-19 14:04:08 -04:00
Axionize 4df4b6c637 Remove use of > Java 8 features in code 2024-10-19 13:46:36 -04:00
Axionize c15caa32e3 Unify command system and more code cleanup 2024-10-19 13:46:02 -04:00
Axionize 833559eec9 Cleanup buildscripts 2024-10-19 11:11:44 -04:00
Axionize c3e6f06b9f Init and command cleanup and refactor 2024-10-19 11:04:39 -04:00
Axionize af39cda3b8 Command port checkpoint 2024-10-19 10:20:15 -04:00
Axionize 98d39570d8 Initial work to abstract sender and command port 2024-10-19 06:21:28 -04:00
Axionize 1250cc1abc Revert changes from fork to upstream
Represents most of the differences between my fork and upstream. Reapply this commit if changes are accidentally reversed.

All dev work should be done and then applied to upstream, but for the most part not the other way around.
2024-10-18 16:43:41 -04:00
Axionize 4cacf2f4af Updated servers 2024-10-18 14:45:26 -04:00
Axionize 3d8545f7f5 README changes 2024-10-18 14:32:54 -04:00
Axionize f2ac1b961e Use reflection to remove Folia dependency 2024-10-18 13:50:08 -04:00
Axionize 3474351e9d More buildscript patches 2024-10-18 13:35:09 -04:00
Axionize c66057c601 Remove Java 16 toolchain requiremnt from bukkit module 2024-10-18 13:31:16 -04:00
Axionize c6342981ee Fix buildscript adding resources 2024-10-18 13:24:11 -04:00
Axionize 5ce4a98434 Fix buildscript uploading non-shaded bukkit jar 2024-10-18 13:04:40 -04:00
Axionize 80d2017f4d Mark dev builds as alphas 2024-10-18 13:02:00 -04:00
Axionize 309044ec67 Enable relocation to library conflict issues 2024-10-18 13:00:55 -04:00
Axionize 136e1073af Finish adding 1.16.5 Bukkit support 2024-10-18 12:41:25 -04:00
Axionize 1ecb17c0ed Version Bump 2024-10-18 12:35:26 -04:00
Axionize c011c10637 Fix minor command bugs 2024-10-18 12:32:07 -04:00
Axionize 098a2aa9bb Code Cleanup 2024-10-18 11:02:56 -04:00
Axionize a5a469bc23 Internal rework
New build structure, builds slightly faster and safer at compiletime

- Refactor KnockBackSyncBase implementations out per-platform from platform intializers
- More work on attempting to make commands platform and version independent
- Almost complete 1.16.5 backport
2024-10-18 11:00:15 -04:00
Axionize 1d887ab9d3 Temporarily give up on unifying command systems 2024-10-18 08:53:23 -04:00
Axionize a7a8b2e5e2 Color code ping messages 2024-10-18 01:49:09 -04:00
Axionize be6da424c0 Remove debugging code; print ping and jitter accuately to 3rd decimal in ms 2024-10-18 01:43:32 -04:00
Axionize 04da1ad403 Architectural reworK 2024-10-18 01:22:13 -04:00
Axionize 216d7e437c New build systeM 2024-10-17 03:42:14 -04:00
Axionize 52fb9038ac Merge branch 'dev-upstream' into dev 2024-10-16 07:18:51 -04:00
Axionize 715f74a746 Use keepalives for much better ping resolution; Minor refactor & optimization 2024-10-16 07:13:14 -04:00
Axionize 0ec8906310 Update docs to reflect configurable ping offset 2024-10-16 04:15:21 -04:00
Axionize be2d955872 Merge branch 'dev-upstream' into dev 2024-10-16 04:14:29 -04:00
Axionize 6cfd096e5e Update docs 2024-10-16 04:14:09 -04:00
Axionize 37bc75c9c8 GitHub Actions Update 2024-10-16 03:28:04 -04:00
Axionize c59e147e6d MultiPaper support 2024-10-16 03:01:06 -04:00
Axionize ae3df3bf98 MultiPaper support 2024-10-16 03:00:17 -04:00
Axionize 71bda96939 Re-add ping offset configureability 2024-10-16 02:41:53 -04:00
Axionize 331807fdf3 Merge branch 'dev-upstream' into dev
# Conflicts:
#	common/src/main/java/me/caseload/knockbacksync/player/PlayerData.java
2024-10-16 02:39:58 -04:00
Axionize 70aac14038 Delete pom.xml 2024-10-16 02:39:14 -04:00
Axionize 4fe39867c6 Make Ping Offset configurable 2024-10-16 02:36:44 -04:00
Axionize 50a7b75898 Add support for /tick rate on Fabric 2024-10-16 02:35:09 -04:00
Axionize 90d9ac81a6 Only call reflective player code once 2024-10-16 02:35:08 -04:00
Axionize 8d1f0ad288 Code Cleanup 2024-10-16 02:34:21 -04:00
Axionize 6d2253d3d4 Fix JitterCalculator being unitialized 2024-10-16 02:33:06 -04:00
Axionize 033ba3fafa Cleanup unused code 2024-10-16 02:33:06 -04:00
Axionize 51d4f63850 Add support for /tick rate on Fabric 2024-10-16 02:27:51 -04:00
Axionize 10877e1a0a Only call reflective player code once 2024-10-16 01:57:59 -04:00
Axionize aa3721a60c Remove ping offset configureability 2024-10-16 01:50:36 -04:00
Axionize 4ecd3418d2 Code Cleanup 2024-10-16 01:43:24 -04:00
Axionize aa505c87bc Fix JitterCalculator being unitialized 2024-10-16 01:41:41 -04:00
Axionize 941b9da0a1 Cleanup unused code 2024-10-16 01:35:15 -04:00
Axionize 55697f267f Refactor commands 2024-10-15 22:57:30 -04:00
Axionize 42c0dad6a8 Refactor commands 2024-10-15 22:56:08 -04:00
Axionize eb150040b8 Add jitter calculations 2024-10-15 22:51:54 -04:00
Axionize 9c5f4f4054 Add jitter calculations 2024-10-15 22:49:56 -04:00
Axionize d69814d1af Prevent ping packet id conflicts 2024-10-15 22:25:06 -04:00
Axionize 0e324d5308 Prevent ping packet id conflicts 2024-10-15 21:51:27 -04:00
Axionize 9f981aaebb Remove unncessary github actions file 2024-10-15 21:12:54 -04:00
Axionize 68f580ef8f Merge branch 'fabric-experimental-gradle' into dev
# Conflicts:
#	.github/workflows/build.yml
#	pom.xml
2024-10-15 21:12:39 -04:00
Axionize c338222583 Remove unncessary gradle property 2024-10-15 21:12:17 -04:00
Axionize 495f4346d4 Better update version checking 2024-10-15 21:11:51 -04:00
Axionize ec43afa356 Better update version checking 2024-10-15 21:10:02 -04:00
Axionize 55c7e61c7c Fix buildscript 2024-10-15 20:51:27 -04:00
Axionize d798768768 Download hashlist from official repo 2024-10-15 20:46:51 -04:00
Axionize 25b77fee08 Remove -axionize from build 2024-10-15 20:46:13 -04:00
Axionize 390d827354 Remove unncessary gradle property 2024-10-15 20:45:34 -04:00
Axionize 38f641aea5 Remove ping offset configureability 2024-10-15 20:43:59 -04:00
Axionize 1a95a1d38c Remove unncessary code from merge 2024-10-15 20:42:28 -04:00
Axionize 8207e7e859 merge fabric and new github actions workflow 2024-10-15 20:38:14 -04:00
Axionize 8301b50368 GitHub Actions workflow 2024-10-15 13:27:20 -04:00
Axionize 538b2bf431 Fix fabric server hanging on shutdown 2024-10-15 11:12:11 -04:00
Axionize 808514541f Change server branch name 2024-10-15 08:50:17 -04:00
Axionize 5d7b5b7277 Fix checking enchantment level on fabric 2024-10-15 08:34:17 -04:00
Axionize fac3a55086 Fix metrics on Fabric 2024-10-15 08:19:21 -04:00
Axionize 84cbcc9559 Fix metrics on Fabric 2024-10-15 07:39:34 -04:00
Axionize 561021e899 Fix bstats config 2024-10-15 07:31:31 -04:00
Axionize 55c57292d9 Build jars are not working unless I do this awfullness 2024-10-15 07:00:06 -04:00
Axionize 522e88e89d Temporarily disable remapping 2024-10-15 06:17:39 -04:00
Axionize 313f21fbd7 Attempt to fix relocations 2024-10-15 06:08:38 -04:00
Axionize 3ba46fd780 Seperate projects shading works 2024-10-15 05:47:34 -04:00
Axionize 6f6b844455 Fix fabric errors 2024-10-15 04:01:18 -04:00
Axionize 3d246efded Add build scripts 2024-10-15 03:38:21 -04:00
Axionize a2d9249bd1 Migrate to subproject setup
- Improve ping measurement on fabric with no runnable
- Better replicate bukkit kb sync behaviour
2024-10-15 03:36:29 -04:00
Axionize 0f915ba4c5 Work around packetevents user being null 2024-10-14 12:33:35 -04:00
Axionize bad1202fe6 Implement getBlockStateAt() on Fabric 2024-10-14 12:25:27 -04:00
Axionize 38999ccf77 Complete adding mixins 2024-10-14 11:32:52 -04:00
Axionize 1a6d5c6b0d Fix registering Fabric players 2024-10-14 09:33:36 -04:00
Axionize 1a98728cce Merge remote-tracking branch 'origin/main' into fabric-experimental-gradle
# Conflicts:
#	src/main/java/me/caseload/knockbacksync/KnockbackSync.java
#	src/main/java/me/caseload/knockbacksync/command/subcommand/StatusSubcommand.java
2024-10-14 09:25:55 -04:00
Axionize 90c469b699 Optimization 2024-10-14 09:19:50 -04:00
Axionize 65f6f882b0 Update command syntax 2024-10-14 07:30:14 -04:00
Axionize 6038d9696a Fix listeners 2024-10-14 07:17:23 -04:00
Axionize e848fd6f95 Fix metrics 2024-10-14 07:00:54 -04:00
Axionize 3b909f6f60 Cross-platform metrics 2024-10-14 06:42:03 -04:00
Axionize a726a24549 Fix build hashing on Fabric 2024-10-14 05:14:02 -04:00
Axionize 291be9edb6 Better ping message 2024-10-14 04:36:35 -04:00
Axionize 7d172cf57b Fabric Support Minimum Viable Product
Wohoo!

- Not in same jar, use non-dev jar for Fabric and -dev for Bukkit/Spigot/Paper/Purpur/Pufferfish + Folia
- Does not account for knockback enchantment on Fabric
- Ping runnable does nothing on fabric (less accurate ping measurements)
- Probably lots of hidden bugs/gotchas
2024-10-14 04:30:42 -04:00
Axionize 6f11dadf30 KB change on fabric 2024-10-14 04:07:59 -04:00
Axionize bbf4d0dfb2 Packetevents fabric rework, temporarily exclude from fabric jar 2024-10-14 03:16:51 -04:00
Axionize 5c2458cc9f Stash changes 2024-10-13 22:30:22 -04:00
Axionize 5287ba7007 Remove bukkit dependencies from command, make messages more configurable 2024-10-13 09:36:38 -04:00
Axionize 6627c5c07f Brigadier Command port 2024-10-13 09:21:41 -04:00
Axionize 136d4fb99b Fix command loading on Spigot 2024-10-13 08:45:51 -04:00
Axionize fadd63ffbc Uncomment permission cehck 2024-10-13 06:12:29 -04:00
Axionize 0430f7d403 Stash current state 2024-10-13 06:09:40 -04:00
Axionize aef8d13335 port over default and reload commands 2024-10-13 04:23:51 -04:00
Axionize aeac386099 Register fabric commands; port commands and listeners is all remaining 2024-10-13 04:01:35 -04:00
Axionize c4863498ec Implement Fabric init point 2024-10-13 03:57:17 -04:00
Axionize 72627d1435 Checkpoint 2024-10-13 02:19:25 -04:00
Axionize 18c8f0ce87 Make config fully cross-platform 2024-10-12 19:34:32 -04:00
Axionize e839c7dc00 Fix logic bug in showing player status 2024-10-12 17:52:45 -04:00
Axionize adede4bc99 Make config platform-agnostic 2024-10-12 10:21:28 -04:00
Axionize 2646a3216b Basic Fabric Command 2024-10-12 09:08:27 -04:00
Axionize 6020acfd36 Merge pull request #2 from Erdragh/fix/exclude-brigadier
Fix exclusion of brigadier in shadow
2024-10-12 07:31:28 -04:00
Erdragh 42020bd637 Fix exclusion of brigadier in shadow 2024-10-12 13:30:00 +02:00
Axionize 88d85ad2f5 Add brigadier 2024-10-12 07:11:38 -04:00
Axionize 723d7abce7 Downgrade versions to min possible 2024-10-12 05:08:44 -04:00
Axionize ff7e36c043 Merge remote-tracking branch 'fork/fabric-experimental-gradle' into fabric-experimental-gradle 2024-10-12 04:51:02 -04:00
Axionize 94201ae9f6 Implement tasks on fabric 2024-10-12 04:50:03 -04:00
Axionize b2d2158b61 Merge pull request #1 from Erdragh/chore/gradle-shadow-setup
Improve gradle shadow setup
2024-10-12 04:49:27 -04:00
Erdragh 370815562a Improve gradle shadow setup 2024-10-12 10:38:11 +02:00
Axionize 431cd82e33 Broken need help 2024-10-12 04:08:02 -04:00
Axionize f66a9ff3a3 Initial work for Fabric support 2024-10-11 07:05:48 -04:00
Axionize bfee35d523 Mark Folia as supported on Modrinth 2024-10-11 06:09:26 -04:00
Axionize 377f7bbe0a Folia Support minTick patch 2024-10-11 06:07:39 -04:00
Axionize 03785ea481 Folia Support minTick patch 2024-10-11 06:04:01 -04:00
Axionize 08f1c06940 Folia Support 2024-10-11 05:41:19 -04:00
BuildTools 0ae1eccaf9 Refractor
(cherry picked from commit d54d2a199e)
2024-10-11 05:40:37 -04:00
Axionize a1404bb21d Folia Support 2024-10-11 05:37:52 -04:00
Axionize 34be127621 Update build.yml 2024-10-11 04:07:26 -04:00
Axionize a4488ce79f Update build.yml 2024-10-11 04:06:14 -04:00
Axionize 178f5edd88 Update build.yml 2024-10-11 03:16:18 -04:00
Axionize 772b61655e Update build.yml 2024-10-11 03:03:05 -04:00
BuildTools d54d2a199e Refractor 2024-10-11 01:56:24 -05:00
Axionize b7f795fa9e Update build.yml 2024-10-11 02:50:20 -04:00
Axionize 1a39152144 Update build.yml 2024-10-11 02:42:27 -04:00
Axionize 071a39e576 Update build.yml 2024-10-11 02:40:11 -04:00
Axionize 1f192d528d Update build.yml 2024-10-11 02:37:41 -04:00
Axionize b107f70fd7 Update build.yml 2024-10-11 02:06:04 -04:00
Axionize 77c8258831 Update build.yml 2024-10-11 01:47:41 -04:00
Axionize e762cdd554 Update build.yml 2024-10-11 01:15:28 -04:00
Axionize 20c9f4c7ac Update build.yml 2024-10-11 01:09:15 -04:00
Axionize 7d2b370aec Update build.yml 2024-10-11 01:07:17 -04:00
Axionize fea4e861a1 Update build.yml 2024-10-11 00:51:38 -04:00
Axionize ec58be55ec Update build.yml 2024-10-11 00:49:51 -04:00
Axionize d10d332ab3 Update build.yml 2024-10-11 00:46:58 -04:00
Axionize 0d72bd811f Update build.yml 2024-10-11 00:41:23 -04:00
Axionize 9feeadd70c Update build.yml 2024-10-11 00:37:37 -04:00
Axionize fd94fb5898 Update artifact 2024-10-11 00:30:37 -04:00
Axionize 02c17dcf69 GitHub Actions workflow 2024-10-10 23:29:41 -04:00
Axionize b670047b03 Define which repositories exist for what dependency 2024-10-10 23:29:03 -04:00
Axionize 6132352be1 Define which repositories exist for what dependency 2024-10-10 23:29:03 -04:00
Axionize 5afa9456f9 Make Maven Build Reproducible 2024-10-10 23:29:03 -04:00
Axionize 4bea90dc0f Cleanup imports 2024-10-10 23:26:16 -04:00
Axionize 610f683e4a Merge remote-tracking branch 'origin/main' into merge
# Conflicts:
#	src/main/java/me/caseload/knockbacksync/KnockbackSync.java
#	src/main/resources/config.yml
2024-10-10 23:22:46 -04:00
Axionize 502e121bd2 Update dev build script 2024-10-10 22:54:25 -04:00
Axionize 4afce35695 Update artifacts 2024-10-10 22:46:38 -04:00
Axionize 254641d184 Change branches 2024-10-10 22:44:25 -04:00
Axionize 647d5da395 Setup GitHub Actions 2024-10-10 22:36:33 -04:00
Axionize 2ef0405d69 Define which repositories exist for what dependency 2024-10-10 22:36:04 -04:00
Axionize 55b7158f9d Define which repositories exist for what dependency 2024-10-10 22:24:58 -04:00
Axionize 361dea9a18 Make Maven Build Reproducible 2024-10-10 22:19:02 -04:00
caseload b6cf670fe0 Merge pull request #20 from Axionize/bstats
Add Bstats
2024-10-09 14:46:37 -05:00
caseload decbe90910 Merge pull request #19 from Axionize/status-command
Add new /kbsync status command
2024-10-09 14:41:42 -05:00
caseload 6891b96895 Merge pull request #17 from Axionize/main
Add toggle.self and toggle.other permissions.
2024-10-09 14:40:37 -05:00
Axionize c14926037a Clarify needed permissions 2024-10-09 01:46:40 -04:00
Axionize 77198d5ed8 bStats 2024-10-09 01:04:25 -04:00
Axionize d7a262741d Disable packetevents update checks and debug mode 2024-10-08 22:58:03 -04:00
Axionize a8143785d0 Relocate all bundled deps 2024-10-08 22:49:25 -04:00
Axionize 22e5684f49 Add bStats 2024-10-08 22:47:01 -04:00
Axionize 469c2cd901 Clarify that global being off disables for everyone 2024-10-08 21:01:05 -04:00
Axionize b4f6c45704 New status command 2024-10-08 20:56:26 -04:00
Axionize 23c3e65cfb Add new toggle.self, other, and global permisssions 2024-10-08 20:50:08 -04:00
Axionize 985689c52a Merge remote-tracking branch 'origin/main'
# Conflicts:
#	src/main/java/me/caseload/knockbacksync/command/subcommand/ToggleSubcommand.java
2024-10-08 20:43:23 -04:00
Axionize 0176376776 Add toggle.self and toggle.other permissions. Inform users when per-player toggling if global toggle = off 2024-10-08 13:10:29 -04:00
caseload a67fdd2426 Merge pull request #15 from Axionize/main
Add .gitignore
2024-10-08 02:18:04 -05:00
Axionize 7c1155c02c Add .gitignore 2024-10-08 03:16:25 -04:00
caseload 8e5998c2c9 Multiple important changes
Fix possible server crashes due to thread blocking
Fix NPCs being treated as real players
Reduce memory usage and increase performance
2024-10-08 01:58:55 -05:00
Axionize 7a266053dc Merge branch 'CASELOAD7000:main' into merge 2024-10-08 01:50:49 -04:00
caseload 6543c43d7d Merge pull request #13 from Axionize/main
Prevent rare race condition from causing NPE
2024-10-07 21:07:18 -05:00
Axionize b123eb4800 Prevent rare race condition from causing NPE 2024-10-07 22:03:18 -04:00
Axionize fe5ceff991 Update README.md 2024-10-07 03:37:00 -04:00
Axionize e420d47298 Merge remote-tracking branch 'origin/main' into merge
# Conflicts:
#	src/main/resources/config.yml
2024-10-07 03:32:06 -04:00
caseload f1d74ba6ec Remove test command one more time... 2024-10-06 19:07:37 -05:00
caseload 977b9e1925 Remove test command again... 2024-10-06 19:06:55 -05:00
caseload b20eabaa0e Fix per player toggle message 2024-10-06 19:05:51 -05:00
caseload 2ebadb5d47 Delete test command 2024-10-06 17:43:08 -05:00
caseload a24466898f Delete test command 2024-10-06 17:42:51 -05:00
caseload a43d7d1543 Add per player toggle feature 2024-10-06 17:40:26 -05:00
Axionize af8119749b Re-Add ping offset configurability 2024-10-06 17:25:55 -04:00
Axionize 5d3f1a2940 Merge branch 'main' into merge
# Conflicts:
#	src/main/java/me/caseload/knockbacksync/KnockbackSync.java
#	src/main/java/me/caseload/knockbacksync/manager/PlayerDataManager.java
2024-10-06 17:18:33 -04:00
caseload babc5fbd84 Remove debug 2024-10-06 16:06:13 -05:00
caseload bebee4f1bd Add damage ticks check 2024-10-06 05:13:32 -05:00
caseload 879c2a566a Update AttributeChangeListener.java 2024-10-06 03:53:36 -05:00
caseload 2ffa941550 Delete src/main/java/me/caseload/knockbacksync/config directory 2024-10-06 03:52:59 -05:00
caseload 6f9afb4d77 Remove unused method 2024-10-06 03:50:57 -05:00
caseload 14064d378c Delete CombatManager.java 2024-10-06 03:49:42 -05:00
caseload 3407b2165d Remove unused method 2024-10-06 03:49:22 -05:00
caseload 23d5305d42 Remove last adjustment check 2024-10-06 03:18:46 -05:00
caseload 6eaf09eeb6 remove debug 2024-10-06 03:14:21 -05:00
caseload 8b565a42e7 Add config manager 2024-10-06 03:04:31 -05:00
caseload 38723ce66b Merge pull request #11 from Axionize/exempt-support
Geyser/Floodgate support; add knockbacksync.exempt permission
2024-10-05 20:11:44 -05:00
Axionize 5d1e010df5 Update Server list 2024-10-05 20:56:54 -04:00
Axionize 4ce9aaeb5a Geyser/Floodgate support; add knockbacksync.exempt permission 2024-10-05 19:39:09 -04:00
Axionize d898d5cfeb Geyser/Floodgate support; add knockbacksync.exempt permission 2024-10-05 19:38:30 -04:00
Axionize 3875f34988 Update README.md 2024-10-05 19:24:22 -04:00
caseload 7acc3551ee Merge pull request #10 from Axionize/gravity-optimization
Gravity optimization
2024-10-05 17:51:21 -05:00
Axionize 913303a6dc Fix gravity clamping 2024-10-05 18:18:27 -04:00
Axionize 16b122450f Optimize gravity calculation 2024-10-05 18:17:17 -04:00
caseload d0c796ef60 Merge pull request #9 from Axionize/gravity-attribute
Account for gravity attribute in 1.20.5 and newer
2024-10-05 12:01:59 -05:00
caseload fd56ae1e36 Merge pull request #8 from Axionize/reload-command
Add reload command
2024-10-05 11:56:11 -05:00
Axionize 88b7c40567 Update README.md 2024-10-05 04:44:49 -04:00
Axionize d217d53ee0 Disable update checks 2024-10-05 04:17:26 -04:00
Axionize 2513368cdd Update README.md 2024-10-05 04:12:49 -04:00
Axionize a52c3ca659 Optimize reloading PING_OFFSET 2024-10-05 03:53:16 -04:00
Axionize 3289884136 Merge branch 'configureable-ping-offset' into merge
# Conflicts:
#	src/main/resources/config.yml
2024-10-05 03:50:48 -04:00
Axionize 4a5dc408df Merge branch 'gravity-attribute' 2024-10-05 03:12:48 -04:00
Axionize e9b2c40fac Account for gravity attribute in 1.20.5 and newer 2024-10-05 03:10:08 -04:00
Axionize f8a20b16e9 Add reload command 2024-10-05 00:54:58 -04:00
Axionize 0b1add6cb3 Add configurable ping offset 2024-10-05 00:01:32 -04:00
caseload 02ce284fb2 Update README.md 2024-10-04 16:48:40 -05:00
caseload 81fa80c736 Update README.md 2024-10-04 16:33:55 -05:00
caseload 81003411a0 Update README.md 2024-10-04 16:33:47 -05:00
caseload 109137a5cd Update README.md 2024-10-04 12:39:51 -05:00
caseload ba062e6f02 Update README.md 2024-10-03 22:37:53 -05:00
caseload e635d42c9a update 1.3.2 2024-10-03 21:57:54 -05:00
132 changed files with 6807 additions and 1401 deletions

No files matched your search

+235
View File
@@ -0,0 +1,235 @@
name: Build and Version Update
permissions:
contents: write
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 -x test
- 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-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 -x test
- 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: alpha
loaders: |
bukkit
spigot
paper
folia
purpur
game-versions: |
>=1.16.5
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
+15
View File
@@ -0,0 +1,15 @@
# Ignores all of the Intellij Project settings
.idea/
# Ignore maven reduced POM built when importing/packaging project
dependency-reduced-pom.xml
# Ignore maven build files
target/
.gradle/
gradle/
build/
run/
-674
View File
@@ -1,674 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <https://www.gnu.org/licenses/>.
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:
<program> Copyright (C) <year> <name of author>
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
<https://www.gnu.org/licenses/>.
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
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+39
View File
@@ -0,0 +1,39 @@
Project Structure
- `common` submodule contains shared code for all platforms.
- It contains the interfaces and abstractions for
- Permissions
- Scheduling
- Players
- Blocks
- World
- The Server
- In addition to the interfaces, the code also contains the implementations for
- Commands
- Commands use Brigadier with Reflection to handle version differences. Simply call our command code in common by registering KnockBackSyncCommand.build() and implementing CommandOperations
- Handling Events
- Gathering Statistics
- `fabric` contains code for latest fabric version (currently 1.21)
- `bukkit` contains bukkit-specific code
If you want to add support for a new platform, simply make a new submodule and implement the interfaces for.
- Scheduling Tasks
- Checking for Permissions
- Listening for events and calling the right handler
- Players + Blocks + World + Server
You will need to handle events when Players:
- join/leave
- are damaged
- take velocity (knock back)
If you find your platform is lacking events, take a look at how the PlayerVelocityEvent is implemented fabric for some direction of what to do
## List of version and platform-specific caveats
- Runnable and manual ping does not work on fabric right now due b/c packetevents. Ping measurement will be less accurate
- Command System
- context.getSource().sendSuccess() takes a Supplier<Component> in > 1.19.4
- context.getSource().sendSuccess() takes a Component in <= 1.19.4
- Component.literal() does not exist in <= 1.18.2
+1
View File
@@ -5,6 +5,7 @@
<configuration>
<autoDetectTypes>
<platformType>SPIGOT</platformType>
<platformType>ADVENTURE</platformType>
</autoDetectTypes>
<projectReimportVersion>1</projectReimportVersion>
</configuration>
+164 -8
View File
@@ -1,9 +1,14 @@
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.
Minecraft doesn’t factor in network latency when determining a player's actions on the server. This causes the server to receive outdated information that doesn’t reflect the player's clientside position, leading to varying knockback effects based on connection quality.
This plugin intercepts and adjusts knockback calculations to match what would occur clientside, effectively mitigating the disadvantages caused by high latency. By synchronizing knockback handling, we ensure that players experience consistent and fair knockback, providing a balanced and competitive environment for all."
Showcase: https://www.youtube.com/watch?v=SVokpr3v-TA
Official Discord: https://discord.gg/nnpqpAtyVW
## Frequently Asked Questions (FAQ)
@@ -13,13 +18,164 @@ regardless of their own or their opponent’s connection.
### How does this change benefit high ping players?
**Knockback control.** For example, it will be easier to escape crit chains and punish crit.
<<<<<<< Updated upstream
### How do I change the ping offset?
Open up `config.yml` and edit the line that says `ping_offset: 25`. Replace 25 with your desired ping offset.
;
Then just type
```
/knockbacksync reload
```
or restart your server.
=======
### 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 20 provides a balanced experience for everyone.
**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 must run a modified build of KnockbackSync.** The variable can be changed inside of the [PlayerData](common/src/main/java/me/caseload/knockbacksync/player/PlayerData.java) class.
>>>>>>> Stashed changes
## What servers are using this plugin?
| IP | Location | Region | Ping Offset | spike_threshold |
|------------------|-----------------------------------|--------|-------------|-----------------|
| `pvparcade.club` | Ashburn, Virginia, United States | NA | 20 | 15 |
| `stray.gg` | Ashburn, Virginia, United States | NA | 25 | 20 |
| `eu.stray.gg` | Frankfurt, Hesse, Germany | EU | 25 | 20 |
| `valed.gg` | Frankfurt, Hesse, Germany | EU | 25 | 20 |
| `eu.catpvp.xyz` | Frankfurt, Hesse, Germany | EU | 25 | 20 |
| `as.catpvp.xyz` | Singapore | AS | 25 | 20 |
| `na.catpvp.xyz` | New York, New York, United States | NA | 25 | 20 |
| `hyperium.pl` | Wrocław, Dolnośląskie, Poland | EU | 25 | 20 |
## Commands
---
### /knockbacksync ping [target]
**Description:**
This command allows you to check the ping of a player, including jitter. If no target is specified, it will check your own ping.
**Permissions:**
* `knockbacksync.ping` (defaults to true for players)
**Examples:**
* `/knockbacksync ping`: Checks your own ping.
* `/knockbacksync ping Steve`: Checks the ping of a player named Steve.
**Output:**
* If a pong packet has been received: "Your last ping packet took [ping]ms. Jitter: [jitter]ms." or "[Player]'s last ping packet took [ping]ms. Jitter: [jitter]ms."
* If a pong packet has not been received: "Pong not received. Your estimated ping is [estimated ping]ms." or "Pong not received. [Player]'s estimated ping is [estimated ping]ms."
**Notes:**
* The estimated ping is based on the player's platform reported ping.
* Jitter represents the variation in ping over time.
---
### /knockbacksync status [target]
**Description:**
This command allows you to check the KnockbackSync status of a player or the server. If no target is specified, it will show both the global status and your own status.
**Permissions:**
* `knockbacksync.status.self` (defaults to true for players): Allows checking your own status.
* `knockbacksync.status.other` (defaults to op only): Allows checking the status of other players.
**Examples:**
* `/knockbacksync status`: Shows the global status and your own status.
* `/knockbacksync status Steve`: Shows the status of a player named Steve.
**Output:**
* **Global status:** "Global KnockbackSync status: [Enabled/Disabled]"
* **Player status:** "[Player]'s KnockbackSync status: [Enabled/Disabled]" (or "Disabled (Global toggle is off)" if the global toggle is off)
**Notes:**
* The player status will be "Disabled" if the global toggle is off, even if the player has individually enabled KnockbackSync.
* The messages displayed by this command are configurable in the `config.yml` file.
---
### /knockbacksync toggle [target]
**Description:**
This command allows you to toggle KnockbackSync for yourself, another player, or globally.
**Permissions:**
* `knockbacksync.toggle.self` (defaults to true for players): Allows toggling KnockbackSync for yourself.
* `knockbacksync.toggle.other` (defaults to op only): Allows toggling KnockbackSync for other players.
* `knockbacksync.toggle.global` (defaults to op only): Allows toggling KnockbackSync globally for the server.
**Examples:**
* `/knockbacksync toggle`: Toggles KnockbackSync globally (if you have permission) or for yourself.
* `/knockbacksync toggle Steve`: Toggles KnockbackSync for a player named Steve.
**Output:**
* **Global toggle:** Sends a message indicating whether KnockbackSync has been enabled or disabled globally. The messages are configurable in the `config.yml` file.
* **Player toggle:** Sends a message indicating whether KnockbackSync has been enabled or disabled for the specified player. The messages are configurable in the `config.yml` file.
* **Ineligible player:** If a player is ineligible for KnockbackSync (e.g., due to permissions), a configurable message will be sent.
* **KnockbackSync disabled:** If KnockbackSync is disabled globally and you try to toggle it for a player, a message will be sent indicating that KnockbackSync is disabled.
**Notes:**
* If KnockbackSync is disabled globally, toggling it for a player will have no effect until KnockbackSync is enabled globally.
* Players can only toggle KnockbackSync for themselves if they have the `knockbacksync.toggle.self` permission.
* Operators can toggle KnockbackSync for other players and globally.
---
### /knockbacksync reload
**Description:**
This command reloads the KnockbackSync plugin's configuration file.
**Permissions:**
* `knockbacksync.reload` (defaults to op only)
**Examples:**
* `/knockbacksync reload`
**Output:**
* Sends a message to the command sender indicating that the configuration has been reloaded. The message is configurable in the `config.yml` file.
**Notes:**
* This command is useful for applying changes made to the configuration file without restarting the server.
---
### /knockbacksync toggleoffground
**Description:**
This command toggles the experimental off-ground knockback synchronization feature.
**Permissions:**
* `knockbacksync.toggleoffground` (defaults to op only)
**Examples:**
* `/knockbacksync toggleoffground`
**Output:**
* Sends a message indicating whether the experimental off-ground knockback synchronization has been enabled or disabled. The messages are configurable in the `config.yml` file.
**Notes:**
* **This command currently does not do anything as off-ground synchronization has yet to be implemented.**
* This feature is experimental and may not work as expected.
## License
GNU General Public License v3.0 or later
See [COPYING](COPYING) to see the full text.
See [LICENSE](https://www.gnu.org/licenses/gpl-3.0.en.html) to see the full text.
+55
View File
@@ -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.5"
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_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
}
+67
View File
@@ -0,0 +1,67 @@
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
plugins {
id("com.gradleup.shadow")
}
base {
archivesName.set("${rootProject.property("archives_base_name")}-bukkit")
}
val shadeThisThing: Configuration by configurations.creating {
isCanBeConsumed = true
isTransitive = true
}
// TODO migrate to only including sources sets for compile, test and javadoc tasks
tasks.withType<JavaCompile>().configureEach {
source(project(":common").sourceSets.main.get().allSource)
}
tasks.withType<Javadoc>().configureEach {
source(project(":common").sourceSets.main.get().allJava)
}
tasks.named<JavaCompile>("compileTestJava") {
exclude("**/*")
}
dependencies {
implementation(project(":common"))
compileOnly("org.spigotmc:spigot-api:1.16.5-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")
shadeThisThing(implementation("org.kohsuke:github-api:1.326")!!)
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("net.kyori:adventure-platform-bukkit:4.3.4")!!)
shadeThisThing(implementation("org.incendo:cloud-paper:2.0.0-beta.10")!!)
shadeThisThing(implementation("org.incendo:cloud-core:2.0.0")!!)
}
tasks.withType<ShadowJar> {
configurations = listOf(shadeThisThing)
isEnableRelocation = true
relocationPrefix = "${project.property("maven_group")}.${project.property("archives_base_name")}.shaded"
}
tasks.build {
dependsOn(tasks.shadowJar)
}
tasks.processResources {
from(project(":common").sourceSets.main.get().resources)
inputs.property("version", project.version)
filteringCharset = "UTF-8"
filesMatching("plugin.yml") {
expand(
"version" to project.version,
)
}
}
@@ -0,0 +1,138 @@
package me.caseload.knockbacksync;
import com.github.retrooper.packetevents.PacketEvents;
import io.github.retrooper.packetevents.factory.spigot.SpigotPacketEventsBuilder;
import me.caseload.knockbacksync.listener.bukkit.BukkitPlayerDamageListener;
import me.caseload.knockbacksync.listener.bukkit.BukkitPlayerJoinQuitListener;
import me.caseload.knockbacksync.listener.bukkit.BukkitPlayerKnockbackListener;
import me.caseload.knockbacksync.manager.ConfigManager;
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.sender.BukkitPlayerSelectorParser;
import me.caseload.knockbacksync.sender.BukkitSenderFactory;
import me.caseload.knockbacksync.sender.Sender;
import me.caseload.knockbacksync.stats.custom.BukkitStatsManager;
import me.caseload.knockbacksync.stats.custom.PluginJarHashProvider;
import me.caseload.knockbacksync.world.BukkitServer;
import org.bukkit.event.Listener;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.incendo.cloud.bukkit.CloudBukkitCapabilities;
import org.incendo.cloud.execution.ExecutionCoordinator;
import org.incendo.cloud.paper.LegacyPaperCommandManager;
import java.io.File;
import java.io.InputStream;
import java.util.logging.Logger;
public class KBSyncBukkitBase extends KnockbackSyncBase {
private final JavaPlugin plugin;
private final BukkitSenderFactory bukkitSenderFactory = new BukkitSenderFactory(this);
private final PluginPermissionChecker permissionChecker = new PluginPermissionChecker();
public KBSyncBukkitBase(JavaPlugin plugin) {
this.plugin = plugin;
super.configManager = new ConfigManager();
super.playerSelectorParser = new BukkitPlayerSelectorParser<>();
super.statsManager = new BukkitStatsManager();
super.platformServer = new BukkitServer();
super.pluginJarHashProvider = new PluginJarHashProvider(this.getClass().getProtectionDomain().getCodeSource().getLocation());
}
@Override
public Logger getLogger() {
return this.plugin.getLogger();
}
@Override
public File getDataFolder() {
return this.plugin.getDataFolder();
}
@Override
public InputStream getResource(String filename) {
return this.plugin.getResource(filename);
}
@Override
public void load() {
PacketEvents.setAPI(SpigotPacketEventsBuilder.build(this.plugin));
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(this.plugin);
break;
case FOLIA:
super.scheduler = new FoliaSchedulerAdapter(this.plugin);
break;
}
}
@Override
protected void registerPlatformListeners() {
registerPluginListeners(
new BukkitPlayerDamageListener(),
new BukkitPlayerKnockbackListener(),
new BukkitPlayerJoinQuitListener()
);
}
@Override
protected void registerCommands() {
super.commandManager = new LegacyPaperCommandManager<>(
this.plugin,
ExecutionCoordinator.simpleCoordinator(),
bukkitSenderFactory
);
if (commandManager instanceof LegacyPaperCommandManager) {
LegacyPaperCommandManager<Sender> legacyPaperCommandManager = (LegacyPaperCommandManager<Sender>) commandManager;
if (legacyPaperCommandManager.hasCapability(CloudBukkitCapabilities.NATIVE_BRIGADIER)) {
legacyPaperCommandManager.registerBrigadier();
} else if (commandManager.hasCapability(CloudBukkitCapabilities.ASYNCHRONOUS_COMPLETION)) {
legacyPaperCommandManager.registerAsynchronousCompletions();
}
}
super.registerCommands();
}
@Override
protected String getVersion() {
return this.plugin.getDescription().getVersion();
}
@Override
public void saveDefaultConfig() {
this.plugin.saveDefaultConfig();
}
@Override
public PermissionChecker getPermissionChecker() {
return permissionChecker;
}
private void registerPluginListeners(Listener... listeners) {
PluginManager pluginManager = this.plugin.getServer().getPluginManager();
for (Listener listener : listeners)
pluginManager.registerEvents(listener, this.plugin);
}
public BukkitSenderFactory getSenderFactory() {
return this.bukkitSenderFactory;
}
}
@@ -0,0 +1,24 @@
package me.caseload.knockbacksync;
import com.github.retrooper.packetevents.PacketEvents;
import org.bukkit.plugin.java.JavaPlugin;
public final class KBSyncBukkitLoaderPlugin extends JavaPlugin {
private final KnockbackSyncBase core = new KBSyncBukkitBase(this);
@Override
public void onLoad() {
core.load();
}
@Override
public void onEnable() {
core.enable();
}
@Override
public void onDisable() {
PacketEvents.getAPI().terminate();
}
}
@@ -0,0 +1,23 @@
package me.caseload.knockbacksync.listener.bukkit;
import me.caseload.knockbacksync.listener.PlayerDamageListener;
import me.caseload.knockbacksync.player.BukkitPlayer;
import me.caseload.knockbacksync.util.MultiLibUtil;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
public class BukkitPlayerDamageListener extends PlayerDamageListener implements Listener {
@EventHandler(ignoreCancelled = true)
public void onPlayerDamage(EntityDamageByEntityEvent event) {
Entity victim = event.getEntity();
Entity attacker = event.getDamager();
if ((victim instanceof Player) && (attacker instanceof Player))
if (!MultiLibUtil.isExternalPlayer((Player) victim)) {
onPlayerDamage(new BukkitPlayer((Player) victim), new BukkitPlayer((Player) attacker));
}
}
}
@@ -0,0 +1,22 @@
package me.caseload.knockbacksync.listener.bukkit;
import me.caseload.knockbacksync.listener.PlayerJoinQuitListener;
import me.caseload.knockbacksync.player.BukkitPlayer;
import me.caseload.knockbacksync.player.PlayerData;
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());
}
}
@@ -0,0 +1,41 @@
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 me.caseload.knockbacksync.util.MultiLibUtil;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
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;
if (MultiLibUtil.isExternalPlayer(victim))
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
}
}
@@ -0,0 +1,39 @@
package me.caseload.knockbacksync.permission;
import me.caseload.knockbacksync.player.BukkitPlayer;
import me.caseload.knockbacksync.player.PlatformPlayer;
import me.caseload.knockbacksync.sender.Sender;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class PluginPermissionChecker implements PermissionChecker {
// Method getBukkitSenderMethod;
//
// public PluginPermissionChecker() {
// try {
// getBukkitSenderMethod = CommandSourceStack.class.getMethod("getBukkitSender");
// } catch (NoSuchMethodException e) {
// e.printStackTrace();
// }
// }
// Currently shouldn't be called
@Override
public boolean hasPermission(Object nativeType, String s, boolean defaultIfUnset) {
if (nativeType instanceof CommandSender) {
return ((CommandSender) nativeType).hasPermission(s);
}
throw new IllegalArgumentException("Attempted to check permission of an object that wasn't a platformplayer or Sender. This should never happen on Bukkit!");
}
@Override
public boolean hasPermission(Sender source, String s, boolean defaultIfUnset) {
return source.hasPermission(s, defaultIfUnset);
}
@Override
public boolean hasPermission(PlatformPlayer platformPlayer, String s) {
return ((BukkitPlayer) platformPlayer).bukkitPlayer.hasPermission(s);
}
}
@@ -0,0 +1,118 @@
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() {
/* Inconsistent with Entity.isOnGround()
/ Checks to see if this player is currently standing on a block.
/ This information may not be reliable, as it is a state provided by the client, and may therefore not be accurate.
/ It can also easily be spoofed. We may want to cast to LivingEntity and call isOnGround() instead
*/
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));
}
}
@@ -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() {
}
}
@@ -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 final 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;
}
}
@@ -0,0 +1,60 @@
package me.caseload.knockbacksync.scheduler;
import io.github.retrooper.packetevents.util.folia.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) {
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() {
}
}
@@ -0,0 +1,55 @@
package me.caseload.knockbacksync.scheduler;
import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.NotNull;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
public class FoliaTaskHandle implements AbstractTaskHandle {
private static final MethodHandle GET_OWNING_PLUGIN;
private static final MethodHandle CANCEL;
static {
try {
Class<?> scheduledTaskClass = Class.forName("io.papermc.paper.threadedregions.scheduler.ScheduledTask");
MethodHandles.Lookup lookup = MethodHandles.lookup();
GET_OWNING_PLUGIN = lookup.findVirtual(scheduledTaskClass, "getOwningPlugin", MethodType.methodType(Plugin.class));
CANCEL = lookup.findVirtual(scheduledTaskClass, "cancel", MethodType.methodType(void.class));
} catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException e) {
throw new RuntimeException("Failed to initialize FoliaTaskHandle reflection", e);
}
}
private final Object scheduledTask; // Store as Object instead of ScheduledTask
private boolean cancelled;
public FoliaTaskHandle(@NotNull Object scheduledTask) {
this.scheduledTask = scheduledTask;
}
public Plugin getOwner() {
try {
return (Plugin) GET_OWNING_PLUGIN.invoke(scheduledTask);
} catch (Throwable e) {
throw new RuntimeException("Failed to invoke getOwningPlugin", e);
}
}
@Override
public boolean getCancelled() {
return this.cancelled;
}
@Override
public void cancel() {
try {
CANCEL.invoke(scheduledTask);
} catch (Throwable e) {
throw new RuntimeException("Failed to invoke cancel", e);
}
this.cancelled = true;
}
}
@@ -0,0 +1,36 @@
package me.caseload.knockbacksync.sender;
import me.caseload.knockbacksync.command.generic.PlayerSelector;
import me.caseload.knockbacksync.player.BukkitPlayer;
import me.caseload.knockbacksync.player.PlatformPlayer;
import java.util.Collection;
import java.util.Collections;
public class BukkitPlayerSelectorAdapter implements PlayerSelector {
private final org.incendo.cloud.bukkit.data.SinglePlayerSelector bukkitSelector;
public BukkitPlayerSelectorAdapter(org.incendo.cloud.bukkit.data.SinglePlayerSelector bukkitSelector) {
this.bukkitSelector = bukkitSelector;
}
@Override
public boolean isSingle() {
return true;
}
@Override
public PlatformPlayer getSinglePlayer() {
return new BukkitPlayer(bukkitSelector.single());
}
@Override
public Collection<PlatformPlayer> getPlayers() {
return Collections.singletonList(new BukkitPlayer(bukkitSelector.single()));
}
@Override
public String inputString() {
return bukkitSelector.inputString();
}
}
@@ -0,0 +1,28 @@
package me.caseload.knockbacksync.sender;
import me.caseload.knockbacksync.command.generic.AbstractPlayerSelectorParser;
import me.caseload.knockbacksync.command.generic.PlayerSelector;
import org.incendo.cloud.bukkit.parser.selector.SinglePlayerSelectorParser;
import org.incendo.cloud.context.CommandContext;
import org.incendo.cloud.parser.ParserDescriptor;
import java.util.concurrent.CompletableFuture;
public class BukkitPlayerSelectorParser<C> extends AbstractPlayerSelectorParser<C> {
@Override
public ParserDescriptor<C, PlayerSelector> descriptor() {
return createDescriptor();
}
@Override
protected ParserDescriptor<C, ?> getPlatformSpecificDescriptor() {
return SinglePlayerSelectorParser.singlePlayerSelectorParser();
}
@Override
protected CompletableFuture<PlayerSelector> adaptToCommonSelector(CommandContext<C> context, Object platformSpecificSelector) {
return CompletableFuture.completedFuture(new BukkitPlayerSelectorAdapter((org.incendo.cloud.bukkit.data.SinglePlayerSelector) platformSpecificSelector));
}
}
@@ -0,0 +1,88 @@
package me.caseload.knockbacksync.sender;
import me.caseload.knockbacksync.KBSyncBukkitBase;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.command.RemoteConsoleCommandSender;
import org.bukkit.entity.Player;
import org.bukkit.permissions.Permission;
import org.bukkit.permissions.PermissionDefault;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.incendo.cloud.SenderMapper;
import java.util.UUID;
public class BukkitSenderFactory extends SenderFactory<KBSyncBukkitBase, CommandSender> implements SenderMapper<CommandSender, Sender> {
// private final BukkitAudiences audiences;
public BukkitSenderFactory(KBSyncBukkitBase kbSyncBukkitBase) {
super(kbSyncBukkitBase);
// this.audiences = BukkitAudiences.create(kbSyncBukkitBase.getLoader());
}
@Override
protected String getName(CommandSender sender) {
if (sender instanceof Player) {
return sender.getName();
}
return Sender.CONSOLE_NAME;
}
@Override
protected UUID getUniqueId(CommandSender sender) {
if (sender instanceof Player) {
return ((Player) sender).getUniqueId();
}
return Sender.CONSOLE_UUID;
}
@Override
protected void sendMessage(CommandSender sender, String message) {
sender.sendMessage(message);
}
// @Override
// protected void sendMessage(CommandSender sender, Component message) {
// // we can safely send async for players and the console - otherwise, send it sync
// if (sender instanceof Player || sender instanceof ConsoleCommandSender || sender instanceof RemoteConsoleCommandSender) {
// this.audiences.sender(sender).sendMessage(message);
// } else {
// getPlugin().getBootstrap().getScheduler().executeSync(() -> this.audiences.sender(sender).sendMessage(message));
// }
// }
@Override
protected boolean hasPermission(CommandSender sender, String node) {
return sender.hasPermission(node);
}
@Override
protected boolean hasPermission(CommandSender sender, String node, boolean defaultIfUnset) {
return sender.hasPermission(new Permission(node, defaultIfUnset ? PermissionDefault.TRUE : PermissionDefault.FALSE));
}
@Override
protected void performCommand(CommandSender sender, String command) {
//
}
@Override
protected boolean isConsole(CommandSender sender) {
return sender instanceof ConsoleCommandSender || sender instanceof RemoteConsoleCommandSender;
}
@Override
public @NonNull Sender map(@NonNull CommandSender base) {
return this.wrap(base);
}
@Override
public @NonNull CommandSender reverse(@NonNull Sender mapped) {
return this.unwrap(mapped);
}
@Override
public void close() throws Exception {
}
}
@@ -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;
});
}
}
@@ -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 me.caseload.knockbacksync.KBSyncBukkitLoaderPlugin;
import me.caseload.knockbacksync.KnockbackSyncBase;
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;
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;
public class MetricsBukkit implements Metrics {
private final Plugin plugin;
private final MetricsBase metricsBase;
public MetricsBukkit(int serviceId) {
this.plugin = KBSyncBukkitLoaderPlugin.getPlugin(KBSyncBukkitLoaderPlugin.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();
}
}
}
@@ -0,0 +1,32 @@
package me.caseload.knockbacksync.util;
import com.github.retrooper.packetevents.PacketEvents;
import com.github.retrooper.packetevents.manager.server.ServerVersion;
import org.bukkit.entity.Player;
import java.lang.reflect.Method;
public class MultiLibUtil {
public final static Method externalPlayerMethod = getMethod(Player.class, "isExternalPlayer");
public static Method getMethod(Class<?> clazz, String methodName) {
try {
return clazz.getMethod(methodName);
} catch (NoSuchMethodException e) {
return null;
}
}
// TODO: cache external players for better performance, but this only matters for people using multi-lib
public static boolean isExternalPlayer(Player player) {
if (externalPlayerMethod == null || (PacketEvents.getAPI().getServerManager().getVersion().isOlderThan(ServerVersion.V_1_18)))
return false;
try {
return (boolean) externalPlayerMethod.invoke(player);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
@@ -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<PlatformPlayer> getOnlinePlayers() {
return Bukkit.getOnlinePlayers().stream()
.map(BukkitPlayer::new)
.collect(Collectors.toList());
}
@Override
public PlatformPlayer getPlayer(UUID uuid) {
return new BukkitPlayer(Bukkit.getPlayer(uuid));
}
}
@@ -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;
}
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;
}
}
@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
);
}
}
+18
View File
@@ -0,0 +1,18 @@
name: KnockbackSync
version: ${version}
main: me.caseload.knockbacksync.KBSyncBukkitLoaderPlugin
api-version: '1.16'
authors: [ Caseload ]
description: Synchronizes player knockback for smoother gameplay.
folia-supported: true
permissions:
knockbacksync.update:
default: op
knockbacksync.toggle.global:
default: op
knockbacksync.toggle.other:
default: op
knockbacksync.toggle.self:
default: op
knockbacksync.ping:
default: op
+69
View File
@@ -0,0 +1,69 @@
plugins {
id("fabric-loom")
// id("net.neoforged.moddev") version "1.0.11"
}
dependencies {
minecraft("com.mojang:minecraft:1.16.5")
mappings(loom.layered {
officialMojangMappings()
parchment("org.parchmentmc.data:parchment-1.16.5:2022.03.06")
})
// True compileOnly deps
compileOnly("org.geysermc.floodgate:api:2.0-SNAPSHOT")
compileOnly("org.projectlombok:lombok:1.18.34")
annotationProcessor("org.projectlombok:lombok:1.18.34")
// Shaded in or bundled by platform-specific code
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")
}
api("net.kyori:adventure-api:4.11.0") {
exclude(module = "adventure-bom")
exclude(module = "checker-qual")
exclude(module = "annotations")
}
api("net.kyori:adventure-text-serializer-gson:4.11.0") {
exclude(module = "adventure-bom")
exclude(module = "adventure-api")
exclude(module = "gson")
}
api("net.kyori:adventure-text-serializer-legacy:4.11.0") {
exclude(module = "adventure-bom")
exclude(module = "adventure-api")
}
api("net.kyori:adventure-text-serializer-plain:4.11.0") {
exclude(module = "adventure-bom")
exclude(module = "adventure-api")
}
api("net.kyori:adventure-text-minimessage:4.11.0") {
exclude(module = "adventure-bom")
exclude(module = "adventure-api")
}
api("net.kyori:event-api:3.0.0") {
exclude(module = "checker-qual")
exclude(module = "guava")
}
implementation("org.incendo:cloud-core:2.0.0")
implementation("org.incendo:cloud-minecraft-extras:2.0.0-beta.10")
}
repositories {
maven("https://maven.neoforged.net/releases")
}
tasks.named("remapJar").configure {
enabled = false
}
@@ -0,0 +1,82 @@
package me.caseload.knockbacksync;
import me.caseload.knockbacksync.util.NumberConversions;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class ConfigWrapper {
private final Map<String, Object> configMap;
public ConfigWrapper(Map<String, Object> configMap) {
this.configMap = configMap;
}
public String getString(String path, String def) {
Object value = getValue(path);
return value instanceof String ? (String) value : def;
}
public boolean getBoolean(String path, boolean def) {
Object value = getValue(path);
return value instanceof Boolean ? (Boolean) value : def;
}
public int getInt(String path, int def) {
Object value = getValue(path);
return NumberConversions.toInt(value, def);
}
public long getLong(String path, long def) {
Object value = getValue(path);
return NumberConversions.toLong(value, def);
}
public void set(String path, Object value) {
setValue(path, value);
}
private Object getValue(String path) {
String[] parts = path.split("\\.");
Object current = configMap;
for (String part : parts) {
if (current instanceof Map) {
current = ((Map<?, ?>) current).get(part);
} else {
return null; // Path not found
}
}
return current;
}
private void setValue(String path, Object value) {
String[] parts = path.split("\\.");
Map<String, Object> current = configMap;
for (int i = 0; i < parts.length - 1; i++) {
String part = parts[i];
if (!current.containsKey(part) || !(current.get(part) instanceof Map)) {
current.put(part, new HashMap<>());
}
current = (Map<String, Object>) current.get(part);
}
current.put(parts[parts.length - 1], value);
}
public boolean contains(String path) {
return getValue(path) != null;
}
public Object get(String path) {
return getValue(path);
}
public Set<String> getKeys(String path) {
Object value = getValue(path);
if (value instanceof Map) {
return ((Map<String, Object>) value).keySet();
}
return new HashSet<>();
}
}
@@ -0,0 +1,218 @@
package me.caseload.knockbacksync;
import com.github.retrooper.packetevents.PacketEvents;
import lombok.Getter;
import me.caseload.knockbacksync.command.MainCommand;
import me.caseload.knockbacksync.command.generic.AbstractPlayerSelectorParser;
import me.caseload.knockbacksync.command.generic.BuilderCommand;
import me.caseload.knockbacksync.command.subcommand.PingCommand;
import me.caseload.knockbacksync.command.subcommand.ReloadCommand;
import me.caseload.knockbacksync.command.subcommand.StatusCommand;
import me.caseload.knockbacksync.command.subcommand.ToggleCommand;
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.sender.Sender;
import me.caseload.knockbacksync.stats.custom.PluginJarHashProvider;
import me.caseload.knockbacksync.stats.custom.StatsManager;
import me.caseload.knockbacksync.world.PlatformServer;
import org.incendo.cloud.CommandManager;
import org.kohsuke.github.GitHub;
import java.io.File;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;
// Base class
public abstract class KnockbackSyncBase {
public static Logger LOGGER;
public static KnockbackSyncBase INSTANCE;
public final Platform platform;
public StatsManager statsManager;
public PlatformServer platformServer;
@Getter protected PluginJarHashProvider pluginJarHashProvider;
@Getter protected SchedulerAdapter scheduler;
@Getter protected ConfigManager configManager;
protected CommandManager<Sender> commandManager;
@Getter
protected AbstractPlayerSelectorParser<Sender> playerSelectorParser;
protected KnockbackSyncBase() {
this.platform = getPlatform();
INSTANCE = this;
}
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 void registerCommands() {
List<BuilderCommand> list = Arrays.asList(
new MainCommand(),
new ReloadCommand(),
new PingCommand(),
new StatusCommand(),
new ToggleCommand()
);
list.forEach(command -> command.register(commandManager));
}
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();
int comparisonResult = compareVersions(currentVersion, latestVersion);
if (comparisonResult < 0) {
LOGGER.warning("You are running an older version. A new update is available for download at: https://github.com/CASELOAD7000/knockback-sync/releases/latest");
configManager.setUpdateAvailable(true);
} else if (comparisonResult > 0) {
if (currentVersion.contains("-dev")) {
LOGGER.info("You are running a development build newer than the latest release.");
} else {
LOGGER.info("You are running a version newer than the latest release.");
}
configManager.setUpdateAvailable(false);
} else {
LOGGER.info("You are running the latest release.");
configManager.setUpdateAvailable(false);
}
} catch (Exception e) {
LOGGER.severe("Failed to check for updates: " + e.getMessage());
}
});
}
private int compareVersions(String version1, String version2) {
String[] v1Parts = version1.split("[-.]");
String[] v2Parts = version2.split("[-.]");
int length = Math.min(v1Parts.length, v2Parts.length);
for (int i = 0; i < length; i++) {
int comparison = compareVersionPart(v1Parts[i], v2Parts[i]);
if (comparison != 0) {
return comparison;
}
}
// If we're here, all compared parts are equal
if (v1Parts.length != v2Parts.length) {
return compareSpecialVersions(v1Parts, v2Parts);
}
return 0; // Versions are equal
}
private int compareVersionPart(String part1, String part2) {
try {
int v1 = Integer.parseInt(part1);
int v2 = Integer.parseInt(part2);
return Integer.compare(v1, v2);
} catch (NumberFormatException e) {
// If parts are not numbers, compare them based on dev < snapshot < release
return compareSpecialPart(part1, part2);
}
}
private int compareSpecialPart(String part1, String part2) {
if (part1.equals(part2)) return 0;
if (part1.startsWith("dev")) return part2.startsWith("dev") ? 0 : -1;
if (part2.startsWith("dev")) return 1;
if (part1.equals("SNAPSHOT")) return part2.equals("SNAPSHOT") ? 0 : -1;
if (part2.equals("SNAPSHOT")) return 1;
return part1.compareTo(part2);
}
private int compareSpecialVersions(String[] v1Parts, String[] v2Parts) {
if (v1Parts.length > v2Parts.length) {
String specialPart = v1Parts[v2Parts.length];
if (specialPart.startsWith("dev")) return -1;
if (specialPart.equals("SNAPSHOT")) return -1;
return 1; // Assume it's a release version part
} else {
String specialPart = v2Parts[v1Parts.length];
if (specialPart.startsWith("dev")) return 1;
if (specialPart.equals("SNAPSHOT")) return 1;
return -1; // Assume it's a release version part
}
}
public abstract void saveDefaultConfig();
public abstract PermissionChecker getPermissionChecker();
}
@@ -0,0 +1,7 @@
package me.caseload.knockbacksync;
public enum Platform {
FABRIC,
BUKKIT,
FOLIA
}
@@ -0,0 +1,22 @@
package me.caseload.knockbacksync.command;
import me.caseload.knockbacksync.command.generic.BuilderCommand;
import me.caseload.knockbacksync.sender.Sender;
import me.caseload.knockbacksync.util.ChatUtil;
import org.incendo.cloud.CommandManager;
public class MainCommand implements BuilderCommand {
public void register(CommandManager<Sender> manager) {
manager.command(
manager.commandBuilder("knockbacksync", "kbsync", "kbs")
.handler(context -> {
context.sender().sendMessage(
ChatUtil.translateAlternateColorCodes(
'&',
"&6This server is running the &eKnockbackSync &6plugin. &bhttps://github.com/CASELOAD7000/knockback-sync"
)
);
})
);
}
}
@@ -0,0 +1,23 @@
package me.caseload.knockbacksync.command.generic;
import org.incendo.cloud.context.CommandContext;
import org.incendo.cloud.parser.ParserDescriptor;
import java.util.concurrent.CompletableFuture;
public abstract class AbstractPlayerSelectorParser<C> {
public abstract ParserDescriptor<C, PlayerSelector> descriptor();
protected abstract ParserDescriptor<C, ?> getPlatformSpecificDescriptor();
protected abstract CompletableFuture<PlayerSelector> adaptToCommonSelector(CommandContext<C> context, Object platformSpecificSelector);
// Helper method to create the ParserDescriptor
protected ParserDescriptor<C, PlayerSelector> createDescriptor() {
return ParserDescriptor.of(
getPlatformSpecificDescriptor().parser().mapSuccess(this::adaptToCommonSelector),
PlayerSelector.class
);
}
}
@@ -0,0 +1,9 @@
package me.caseload.knockbacksync.command.generic;
import me.caseload.knockbacksync.sender.Sender;
import org.incendo.cloud.CommandManager;
public interface BuilderCommand {
void register(CommandManager<Sender> manager);
}
@@ -0,0 +1,15 @@
package me.caseload.knockbacksync.command.generic;
import me.caseload.knockbacksync.player.PlatformPlayer;
import java.util.Collection;
public interface PlayerSelector {
boolean isSingle();
PlatformPlayer getSinglePlayer(); // Throws an exception if not a single selection
Collection<PlatformPlayer> getPlayers();
String inputString();
}
@@ -0,0 +1,42 @@
package me.caseload.knockbacksync.command.subcommand;
import me.caseload.knockbacksync.KnockbackSyncBase;
import me.caseload.knockbacksync.command.generic.BuilderCommand;
import me.caseload.knockbacksync.command.generic.PlayerSelector;
import me.caseload.knockbacksync.sender.Sender;
import me.caseload.knockbacksync.util.ChatUtil;
import org.incendo.cloud.CommandManager;
import org.incendo.cloud.permission.PredicatePermission;
import java.util.function.Predicate;
public class PingCommand implements BuilderCommand {
public void register(CommandManager<Sender> manager) {
manager.command(
manager.commandBuilder("knockbacksync", "kbsync", "kbs")
.permission((sender -> {
final String permission = "knockbacksync.ping";
Predicate<Sender> senderPredicate = (s) -> {
return s.hasPermission(permission, true);
};
return PredicatePermission.of(senderPredicate).testPermission(sender);
}))
.literal("ping")
.optional("target", KnockbackSyncBase.INSTANCE.getPlayerSelectorParser().descriptor())
.handler(context -> {
PlayerSelector targetSelector = context.getOrDefault("target", null);
if (targetSelector == null) {
if (context.sender().isConsole()) {
context.sender().sendMessage("You must specify a player to use this command from the console.");
} else {
context.sender().sendMessage(ChatUtil.getPingMessage(context.sender().getUniqueId(), null));
}
} else {
context.sender().sendMessage(ChatUtil.getPingMessage(context.sender().getUniqueId(), targetSelector.getSinglePlayer().getUUID()));
}
})
);
}
}
@@ -0,0 +1,37 @@
package me.caseload.knockbacksync.command.subcommand;
import me.caseload.knockbacksync.KnockbackSyncBase;
import me.caseload.knockbacksync.command.generic.BuilderCommand;
import me.caseload.knockbacksync.manager.ConfigManager;
import me.caseload.knockbacksync.sender.Sender;
import me.caseload.knockbacksync.util.ChatUtil;
import org.incendo.cloud.CommandManager;
import org.incendo.cloud.permission.PredicatePermission;
import java.util.function.Predicate;
public class ReloadCommand implements BuilderCommand {
public void register(CommandManager<Sender> manager) {
manager.command(
manager.commandBuilder("knockbacksync", "kbsync", "kbs")
.literal("reload")
.permission((sender -> {
final String permission = "knockbacksync.reload";
Predicate<Sender> senderPredicate = (s) -> {
return s.hasPermission(permission, false);
};
return PredicatePermission.of(senderPredicate).testPermission(sender);
}))
.handler(context -> {
ConfigManager configManager = KnockbackSyncBase.INSTANCE.getConfigManager();
configManager.loadConfig(true);
String rawReloadMessage = configManager.getReloadMessage();
String reloadMessage = ChatUtil.translateAlternateColorCodes('&', rawReloadMessage);
context.sender().sendMessage(reloadMessage);
})
);
}
}
@@ -0,0 +1,87 @@
package me.caseload.knockbacksync.command.subcommand;
import me.caseload.knockbacksync.KnockbackSyncBase;
import me.caseload.knockbacksync.command.generic.BuilderCommand;
import me.caseload.knockbacksync.command.generic.PlayerSelector;
import me.caseload.knockbacksync.manager.ConfigManager;
import me.caseload.knockbacksync.manager.PlayerDataManager;
import me.caseload.knockbacksync.player.PlatformPlayer;
import me.caseload.knockbacksync.sender.Sender;
import me.caseload.knockbacksync.util.ChatUtil;
import org.incendo.cloud.CommandManager;
import org.incendo.cloud.permission.PredicatePermission;
import java.util.UUID;
import java.util.function.Predicate;
public class StatusCommand implements BuilderCommand {
private static final ConfigManager configManager = KnockbackSyncBase.INSTANCE.getConfigManager();
private static final String STATUS_SELF_PERMISSION = "knockbacksync.status.self";
private static final String STATUS_OTHER_PERMISSION = "knockbacksync.status.other";
public void register(CommandManager<Sender> manager) {
manager.command(
manager.commandBuilder("knockbacksync", "kbsync", "kbs")
.literal("status")
.optional("target", KnockbackSyncBase.INSTANCE.getPlayerSelectorParser().descriptor())
.permission((sender -> {
Predicate<Sender> senderPredicate = (s) -> {
return s.hasPermission(STATUS_SELF_PERMISSION, true) || sender.hasPermission(STATUS_OTHER_PERMISSION, false);
};
return PredicatePermission.of(senderPredicate).testPermission(sender);
}))
.handler(context -> {
Sender sender = context.sender();
PlayerSelector targetSelector = context.getOrDefault("target", null);
if (targetSelector == null) {
// Show global status
boolean globalStatus = configManager.isToggled();
sender.sendMessage(ChatUtil.translateAlternateColorCodes('&',
configManager.getConfigWrapper().getString("global_status_message", "&eGlobal KnockbackSync status: ")) +
(globalStatus
? ChatUtil.translateAlternateColorCodes('&', "&aEnabled")
: ChatUtil.translateAlternateColorCodes('&', "&cDisabled")));
if (sender.hasPermission(STATUS_SELF_PERMISSION, true)) {
// Show player status for the sender (no target specified)
if (!sender.isConsole()) {
showPlayerStatus(sender, KnockbackSyncBase.INSTANCE.platformServer.getPlayer(sender.getUniqueId()), configManager);
}
} else {
sender.sendMessage(ChatUtil.translateAlternateColorCodes('&', "&cYou do not have permisssion to check your knockbacksync status."));
}
} else {
if (sender.hasPermission(STATUS_OTHER_PERMISSION)) {
PlatformPlayer target = targetSelector.getSinglePlayer();
showPlayerStatus(sender, target, configManager);
} else {
sender.sendMessage(ChatUtil.translateAlternateColorCodes('&', "&cYou do not have permisssion to check the status of other players!"));
}
}
})
);
}
private static void showPlayerStatus(Sender sender, PlatformPlayer target, ConfigManager configManager) {
boolean globalStatus = configManager.isToggled();
UUID uuid = target.getUUID();
boolean playerStatus = PlayerDataManager.containsPlayerData(uuid);
if (!globalStatus) {
sender.sendMessage(ChatUtil.translateAlternateColorCodes('&',
configManager.getConfigWrapper().getString("player_status_message", "&e%player%'s KnockbackSync status: ")
.replace("%player%", target.getName()) +
ChatUtil.translateAlternateColorCodes('&',
configManager.getConfigWrapper().getString("player_disabled_global_message", "&cDisabled (Global toggle is off)"))));
} else {
sender.sendMessage(ChatUtil.translateAlternateColorCodes('&',
configManager.getConfigWrapper().getString("player_status_message", "&e%player%'s KnockbackSync status: ")
.replace("%player%", target.getName()) +
(playerStatus
? ChatUtil.translateAlternateColorCodes('&', "&aEnabled")
: ChatUtil.translateAlternateColorCodes('&', "&cDisabled"))));
}
}
}
@@ -0,0 +1,114 @@
package me.caseload.knockbacksync.command.subcommand;
import me.caseload.knockbacksync.KnockbackSyncBase;
import me.caseload.knockbacksync.command.generic.BuilderCommand;
import me.caseload.knockbacksync.command.generic.PlayerSelector;
import me.caseload.knockbacksync.manager.ConfigManager;
import me.caseload.knockbacksync.manager.PlayerDataManager;
import me.caseload.knockbacksync.permission.PermissionChecker;
import me.caseload.knockbacksync.player.PlatformPlayer;
import me.caseload.knockbacksync.player.PlayerData;
import me.caseload.knockbacksync.sender.Sender;
import me.caseload.knockbacksync.util.ChatUtil;
import org.incendo.cloud.CommandManager;
import org.incendo.cloud.permission.Permission;
import org.incendo.cloud.permission.PredicatePermission;
import java.util.UUID;
import java.util.function.Predicate;
public class ToggleCommand implements BuilderCommand {
private static final ConfigManager configManager = KnockbackSyncBase.INSTANCE.getConfigManager();
private static final PermissionChecker permissionChecker = KnockbackSyncBase.INSTANCE.getPermissionChecker();
private static final String TOGGLE_GLOBAL_PERMISSION = "knockbacksync.toggle.global";
private static final String TOGGLE_SELF_PERMISSION = "knockbacksync.toggle.self";
private static final String TOGGLE_OTHER_PERMISSION = "knockbacksync.toggle.other";
@Override
public void register(CommandManager<Sender> manager) {
manager.command(
manager.commandBuilder("knockbacksync", "kbsync", "kbs")
.literal("toggle")
.optional("target", KnockbackSyncBase.INSTANCE.getPlayerSelectorParser().descriptor())
.permission((sender -> {
Predicate<Sender> senderPredicate = (s) -> {
return s.hasPermission(TOGGLE_GLOBAL_PERMISSION, false)
|| sender.hasPermission(TOGGLE_SELF_PERMISSION, true)
|| sender.hasPermission(TOGGLE_OTHER_PERMISSION, false);
};
return PredicatePermission.of(senderPredicate).testPermission(sender);
}))
.handler(context -> {
Sender sender = context.sender();
PlayerSelector targetSelector = context.getOrDefault("target", null);
if (targetSelector == null) {
// Global toggle
if (permissionChecker.hasPermission(sender, TOGGLE_GLOBAL_PERMISSION, false)) {
toggleGlobalKnockback(configManager, sender);
} else {
sender.sendMessage(ChatUtil.translateAlternateColorCodes('&', "&cYou don't have permission to toggle the global setting."));
}
} else {
PlatformPlayer target = targetSelector.getSinglePlayer();
boolean senderIsTarget = sender.getUniqueId() == target.getUUID();
if (!senderIsTarget && !permissionChecker.hasPermission(sender, TOGGLE_OTHER_PERMISSION, false)) {
sender.sendMessage("You do not have permission to toggle the knockback of other player's.");
return;
} else if (senderIsTarget && !permissionChecker.hasPermission(sender, TOGGLE_SELF_PERMISSION, true)) {
sender.sendMessage("You do not have permission to toggle your knockback.");
return;
}
if (!configManager.isToggled()) {
sender.sendMessage(ChatUtil.translateAlternateColorCodes('&', "&cKnockbacksync is currently disabled on this server. Contact your server administrator for more information."));
} else {
togglePlayerKnockback(target, configManager, sender);
}
}
})
);
}
private static void toggleGlobalKnockback(ConfigManager configManager, Sender sender) {
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()
);
sender.sendMessage(ChatUtil.translateAlternateColorCodes('&', message));
}
private static void togglePlayerKnockback(PlatformPlayer target, ConfigManager configManager, Sender sender) {
UUID uuid = target.getUUID();
if (PlayerDataManager.shouldExempt(uuid)) {
String message = ChatUtil.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(KnockbackSyncBase.INSTANCE.platformServer.getPlayer(uuid)));
}
String message = ChatUtil.translateAlternateColorCodes('&',
hasPlayerData ? configManager.getPlayerDisableMessage() : configManager.
getPlayerEnableMessage()
).replace("%player%", target.getName());
sender.sendMessage(message);
}
}
@@ -0,0 +1,39 @@
package me.caseload.knockbacksync.command.subcommand;
import me.caseload.knockbacksync.KnockbackSyncBase;
import me.caseload.knockbacksync.command.generic.BuilderCommand;
import me.caseload.knockbacksync.permission.PermissionChecker;
import me.caseload.knockbacksync.sender.Sender;
import me.caseload.knockbacksync.util.ChatUtil;
import org.incendo.cloud.CommandManager;
import org.incendo.cloud.permission.PredicatePermission;
import java.util.function.Predicate;
public class ToggleOffGroundSubcommand implements BuilderCommand {
@Override
public void register(CommandManager<Sender> manager) {
manager.command(
manager.commandBuilder("knockbacksync", "kbsync", "kbs")
.literal("toggleoffground")
.permission((sender -> {
final String permission = "knockbacksync.toggleoffground";
Predicate<Sender> senderPredicate = (s) -> {
return s.hasPermission(permission, false);
};
return PredicatePermission.of(senderPredicate).testPermission(sender);
}))
.handler(commandContext -> {
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."));
commandContext.sender().sendMessage(message);
}));
}
}
@@ -0,0 +1,24 @@
package me.caseload.knockbacksync.listener;
import me.caseload.knockbacksync.KnockbackSyncBase;
import me.caseload.knockbacksync.manager.PlayerDataManager;
import me.caseload.knockbacksync.player.PlatformPlayer;
import me.caseload.knockbacksync.player.PlayerData;
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(false);
}
}
@@ -0,0 +1,33 @@
package me.caseload.knockbacksync.listener;
import me.caseload.knockbacksync.KnockbackSyncBase;
import me.caseload.knockbacksync.manager.PlayerDataManager;
import me.caseload.knockbacksync.player.PlatformPlayer;
import me.caseload.knockbacksync.player.PlayerData;
import me.caseload.knockbacksync.util.ChatUtil;
import java.util.UUID;
public abstract class PlayerJoinQuitListener {
public void onPlayerJoin(PlayerData player) {
PlayerDataManager.addPlayerData(player.getUuid(), player);
PlatformPlayer platformPlayer = player.getPlatformPlayer();
if (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);
}
}
@@ -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.PlayerDataManager;
import me.caseload.knockbacksync.player.PlatformPlayer;
import me.caseload.knockbacksync.player.PlayerData;
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
}
}
@@ -0,0 +1,100 @@
package me.caseload.knockbacksync.listener.packetevents;
import com.github.retrooper.packetevents.event.PacketListenerAbstract;
import com.github.retrooper.packetevents.event.PacketSendEvent;
import com.github.retrooper.packetevents.protocol.attribute.Attributes;
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
import com.github.retrooper.packetevents.protocol.player.ClientVersion;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerUpdateAttributes;
import me.caseload.knockbacksync.manager.PlayerDataManager;
import me.caseload.knockbacksync.player.PlayerData;
import me.caseload.knockbacksync.util.MathUtil;
import java.util.List;
import java.util.UUID;
public class AttributeChangeListener extends PacketListenerAbstract {
public static final UUID SPRINTING_MODIFIER_UUID =
UUID.fromString("662A6B8D-DA3E-4C1C-8813-96EA6097278D");
final double minGravity = -1;
final double maxGravity = 1;
final double defaultGravity = 0.08;
double currentGravity;
public AttributeChangeListener() {
currentGravity = defaultGravity;
}
@Override
public void onPacketSend(PacketSendEvent event) {
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));
}
}
}
}
public double calculateValueWithModifiers(WrapperPlayServerUpdateAttributes.Property property) {
double baseValue = property.getValue();
double additionSum = 0;
double multiplyBaseSum = 0;
double multiplyTotalProduct = 1.0;
List<WrapperPlayServerUpdateAttributes.PropertyModifier> modifiers = property.getModifiers();
// TODO, account for https://bugs.mojang.com/browse/MC-69459 ?
// modifiers.removeIf(modifier -> modifier.getUUID().equals(SPRINTING_MODIFIER_UUID) || modifier.getName().getKey().equals("sprinting"));
for (WrapperPlayServerUpdateAttributes.PropertyModifier modifier : modifiers) {
switch (modifier.getOperation()) {
case ADDITION:
additionSum += modifier.getAmount();
break;
case MULTIPLY_BASE:
multiplyBaseSum += modifier.getAmount();
break;
case MULTIPLY_TOTAL:
multiplyTotalProduct *= (1.0 + modifier.getAmount());
break;
}
}
double newValue = (baseValue + additionSum) * (1 + multiplyBaseSum) * multiplyTotalProduct;
newValue = MathUtil.clamp(newValue, minGravity, maxGravity);
if (newValue < minGravity || newValue > maxGravity)
throw new IllegalArgumentException("New value must be between min and max!");
return this.currentGravity = newValue;
}
// 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(UUID uuid, double newGravity) {
PlayerData playerData = PlayerDataManager.getPlayerData(uuid);
if (playerData.getClientVersion().isNewerThanOrEquals(ClientVersion.V_1_20_5)) {
playerData.setGravityAttribute(newGravity);
} else {
currentGravity = defaultGravity;
}
}
private void onPlayerKnockBackChange(UUID uuid, double newKnockbackResistance) {
PlayerData playerData = PlayerDataManager.getPlayerData(uuid);
playerData.setKnockbackResistanceAttribute(newKnockbackResistance);
}
}
@@ -0,0 +1,107 @@
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.event.PacketSendEvent;
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
import com.github.retrooper.packetevents.protocol.packettype.PacketTypeCommon;
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientKeepAlive;
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientPong;
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientWindowConfirmation;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerKeepAlive;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPing;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerWindowConfirmation;
import me.caseload.knockbacksync.KnockbackSyncBase;
import me.caseload.knockbacksync.manager.PlayerDataManager;
import me.caseload.knockbacksync.player.PlayerData;
import me.caseload.knockbacksync.util.data.Pair;
import java.util.List;
public class PingReceiveListener extends PacketListenerAbstract {
// TODO supplment our own ping calculations with over keepalive sent by the server with
@Override
public void onPacketSend(PacketSendEvent event) {
PacketTypeCommon packetType = event.getPacketType();
if (packetType.equals(PacketType.Play.Server.KEEP_ALIVE)) {
WrapperPlayServerKeepAlive keepAlive = new WrapperPlayServerKeepAlive(event);
long id = keepAlive.getId();
PlayerData playerData = PlayerDataManager.getPlayerData(event.getUser().getUUID());
if (playerData == null) return;
playerData.keepaliveMap.add(new Pair<>(id, System.nanoTime()));
} else if (packetType.equals(PacketType.Play.Server.PING)) {
WrapperPlayServerPing ping = new WrapperPlayServerPing(event);
int id = ping.getId();
PlayerData playerData = PlayerDataManager.getPlayerData(event.getUser().getUUID());
if (playerData == null) return;
playerData.transactionsSent.add(new Pair<>(id, System.nanoTime()));
} else if (packetType.equals(PacketType.Play.Server.WINDOW_CONFIRMATION)) {
WrapperPlayServerWindowConfirmation confirmation = new WrapperPlayServerWindowConfirmation(event);
int id = confirmation.getActionId();
PlayerData playerData = PlayerDataManager.getPlayerData(event.getUser().getUUID());
if (playerData == null) return;
playerData.transactionsSent.add(new Pair<>(id, System.nanoTime()));
}
}
@Override
public void onPacketReceive(PacketReceiveEvent event) {
if (!KnockbackSyncBase.INSTANCE.getConfigManager().isToggled()) return;
PacketTypeCommon packetType = event.getPacketType();
if (packetType == PacketType.Play.Client.KEEP_ALIVE) {
WrapperPlayClientKeepAlive keepAlive = new WrapperPlayClientKeepAlive(event);
PlayerData playerData = PlayerDataManager.getPlayerData(event.getUser().getUUID());
if (playerData == null) return;
long receivedId = keepAlive.getId();
handlePingCalculationPackets(event, playerData, receivedId, playerData.keepaliveMap);
} else if (packetType == PacketType.Play.Client.PONG) {
WrapperPlayClientPong pong = new WrapperPlayClientPong(event);
PlayerData playerData = PlayerDataManager.getPlayerData(event.getUser().getUUID());
if (playerData == null) return;
int id = pong.getId();
handlePingCalculationPackets(event, playerData, id, playerData.transactionsSent);
} else if (packetType == PacketType.Play.Client.WINDOW_CONFIRMATION) {
WrapperPlayClientWindowConfirmation windowConfirmation = new WrapperPlayClientWindowConfirmation(event);
PlayerData playerData = PlayerDataManager.getPlayerData(event.getUser().getUUID());
if (playerData == null) return;
int id = windowConfirmation.getActionId();
handlePingCalculationPackets(event, playerData, id, playerData.transactionsSent);
}
}
private <T extends Number> void handlePingCalculationPackets(PacketReceiveEvent event, PlayerData playerData, long id, List<Pair<T, Long>> packetSentList) {
long pingNanos = (System.nanoTime() - packetSentList.remove(0).getSecond());
double diffMillisDouble = pingNanos / 1_000_000.0;
playerData.setPreviousPing(playerData.getPing());
playerData.setPing(diffMillisDouble);
playerData.getJitterCalculator().addPing(pingNanos);
double jitter = playerData.getJitterCalculator().calculateJitter();
playerData.setJitter(jitter);
// We can cancel for all 3 cases
if (playerData.didWeSendThatPacket(id)) {
// Pong not needed as vanilla ignores the packet, its needed for packet limiters
// We want to cancel Window Confirmations that we send, and ...
// Minecraft kicks players that send invalid keepAliveID packets
// Since Minecraft doesn't know we just sent a keepalive, we gotta cancel it
// To stop MC from processing it and kicking the player
event.setCancelled(true);
}
}
}
@@ -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<UUID> combatPlayers = ConcurrentHashMap.newKeySet();
public static @NotNull Set<UUID> 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<UUID> combatPlayers = ConcurrentHashMap.newKeySet();
public static @NotNull Set<UUID> getPlayers() {
return combatPlayers;
}
public static void addPlayer(UUID uuid) {
combatPlayers.add(uuid);
}
public static void removePlayer(UUID uuid) {
combatPlayers.remove(uuid);
}
}
@@ -0,0 +1,171 @@
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 {
public static final long CONFIG_VERSION = 2;
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<String, Object> 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;
runnableInterval = config.getLong("runnable.interval", 5L);
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);
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.");
}
public void updateConfig() {
ConfigWrapper oldConfig = getConfigWrapper();
long oldConfigVersion = oldConfig.getLong("config_version", 0);
if (oldConfigVersion < CONFIG_VERSION) {
// Backup old config
File backupFile = new File(configFile.getParentFile(), "config-version-" + oldConfigVersion + ".yml");
if (configFile.renameTo(backupFile)) {
KnockbackSyncBase.INSTANCE.getLogger().info("Backed up old config to " + backupFile.getName());
} else {
KnockbackSyncBase.INSTANCE.getLogger().warning("Failed to backup old config");
}
// Create new config with default values
KnockbackSyncBase.INSTANCE.saveDefaultConfig();
reloadConfig();
// Transfer existing settings
ConfigWrapper newConfig = getConfigWrapper();
transferAllSettings(oldConfig, newConfig);
// Set new config version
newConfig.set("config_version", CONFIG_VERSION);
// Save updated config
saveConfig();
KnockbackSyncBase.INSTANCE.getLogger().info("Config updated to version " + CONFIG_VERSION);
}
}
private void transferAllSettings(ConfigWrapper oldConfig, ConfigWrapper newConfig) {
transferSettingsRecursive(oldConfig, newConfig, "");
}
private void transferSettingsRecursive(ConfigWrapper oldConfig, ConfigWrapper newConfig, String currentPath) {
for (String key : oldConfig.getKeys(currentPath)) {
String fullPath = currentPath.isEmpty() ? key : currentPath + "." + key;
if (newConfig.contains(fullPath)) {
Object value = oldConfig.get(fullPath);
if (value instanceof Map) {
transferSettingsRecursive(oldConfig, newConfig, fullPath);
} else {
newConfig.set(fullPath, value);
}
}
}
}
}
@@ -0,0 +1,42 @@
package me.caseload.knockbacksync.manager;
import me.caseload.knockbacksync.player.PlayerData;
import me.caseload.knockbacksync.util.FloodgateUtil;
import me.caseload.knockbacksync.util.GeyserUtil;
import org.jetbrains.annotations.NotNull;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
public class PlayerDataManager {
private static final Map<UUID, PlayerData> 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");
}
}
@@ -0,0 +1,12 @@
package me.caseload.knockbacksync.permission;
import me.caseload.knockbacksync.player.PlatformPlayer;
import me.caseload.knockbacksync.sender.Sender;
public interface PermissionChecker {
boolean hasPermission(Object nativeType, String s, boolean defaultIfUnset);
boolean hasPermission(Sender source, String s, boolean defaultIfUnset);
boolean hasPermission(PlatformPlayer platform, String s);
}
@@ -0,0 +1,58 @@
package me.caseload.knockbacksync.player;
import java.util.*;
import java.util.stream.Collectors;
public class JitterCalculator {
private final int SAMPLE_SIZE = 15;
private final Queue<Long> pings = new LinkedList<>();
public void addPing(long pingTime) {
pings.offer(pingTime);
if (pings.size() > SAMPLE_SIZE) {
pings.poll();
}
}
public double calculateJitter() {
if (pings.size() < 2) return 0;
List<Long> sortedPings = new ArrayList<>(pings);
Collections.sort(sortedPings);
// Calculate IQR
int q1Index = sortedPings.size() / 4;
int q3Index = q1Index * 3;
long q1 = sortedPings.get(q1Index);
long q3 = sortedPings.get(q3Index);
long iqr = q3 - q1;
// Filter outliers
double lowerBound = q1 - 1.5 * iqr;
double upperBound = q3 + 1.5 * iqr;
List<Long> filteredPings = sortedPings.stream()
.filter(p -> p >= lowerBound && p <= upperBound)
.collect(Collectors.toList());
// Calculate standard deviation
double mean = filteredPings.stream().mapToLong(Long::longValue).average().orElse(0);
double variance = filteredPings.stream()
.mapToDouble(p -> Math.pow(p - mean, 2))
.average().orElse(0);
double stdDev = Math.sqrt(variance);
// Calculate mean jitter
double meanJitter = 0;
Long prevPing = null;
for (Long ping : filteredPings) {
if (prevPing != null) {
meanJitter += Math.abs(ping - prevPing);
}
prevPing = ping;
}
meanJitter /= (filteredPings.size() - 1);
// You can return different jitter metrics based on your needs
return stdDev / 1_000_000.0; // or meanJitter, or both
}
}
@@ -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
}
@@ -0,0 +1,47 @@
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
}
@@ -0,0 +1,330 @@
package me.caseload.knockbacksync.player;
import com.github.retrooper.packetevents.PacketEvents;
import com.github.retrooper.packetevents.manager.player.PlayerManager;
import com.github.retrooper.packetevents.manager.server.ServerVersion;
import com.github.retrooper.packetevents.netty.channel.ChannelHelper;
import com.github.retrooper.packetevents.protocol.ConnectionState;
import com.github.retrooper.packetevents.protocol.player.ClientVersion;
import com.github.retrooper.packetevents.protocol.player.User;
import com.github.retrooper.packetevents.protocol.world.states.WrappedBlockState;
import com.github.retrooper.packetevents.protocol.world.states.type.StateTypes;
import com.github.retrooper.packetevents.util.Vector3d;
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerKeepAlive;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPing;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerWindowConfirmation;
import lombok.Getter;
import lombok.Setter;
import me.caseload.knockbacksync.KnockbackSyncBase;
import me.caseload.knockbacksync.manager.CombatManager;
import me.caseload.knockbacksync.scheduler.AbstractTaskHandle;
import me.caseload.knockbacksync.util.MathUtil;
import me.caseload.knockbacksync.util.data.Pair;
import me.caseload.knockbacksync.world.PlatformWorld;
import me.caseload.knockbacksync.world.raytrace.FluidHandling;
import me.caseload.knockbacksync.world.raytrace.RayTraceResult;
import org.incendo.cloud.CloudCapability;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
@Getter
public class PlayerData {
// Please read the GitHub FAQ before adjusting.
public static final long PING_OFFSET = 25;
public static float TICK_RATE = 20.0F;
private static Field playerField;
public final List<Pair<Integer, Long>> transactionsSent = new LinkedList<>();
public final List<Pair<Long, Long>> keepaliveMap = new LinkedList<>();
private static final short MAIN_THREAD_TRANSACTION_ID = -1;
private static final short NETTY_THREAD_TRANSACTION_ID = -2;
static {
try {
switch (KnockbackSyncBase.INSTANCE.platform) {
case BUKKIT:
case FOLIA:
Class<?> bukkitPlayerClass = Class.forName("me.caseload.knockbacksync.player.BukkitPlayer");
playerField = bukkitPlayerClass.getDeclaredField("bukkitPlayer");
break;
case FABRIC:
Class<?> fabricPlayerClass = Class.forName("me.caseload.knockbacksync.player.FabricPlayer");
playerField = fabricPlayerClass.getDeclaredField("fabricPlayer");
break;
default:
throw new IllegalStateException("Unexpected platform: " + KnockbackSyncBase.INSTANCE.platform);
}
} catch (Exception e) {
e.printStackTrace();
}
playerField.setAccessible(true); // May not be needed since it's already public
}
public final User user;
private final PlatformPlayer platformPlayer;
private final UUID uuid;
@NotNull private final Random random = new Random();
public long lastKeepAliveID = 0;
@Getter private final JitterCalculator jitterCalculator = new JitterCalculator();
@Setter private double jitter;
@Nullable private AbstractTaskHandle combatTask;
@Nullable @Setter private Double 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;
PlayerManager playerManager = PacketEvents.getAPI().getPlayerManager();
Object player = null;
try {
player = playerField.get(platformPlayer);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
if (player != null) {
tempUser = playerManager.getUser(player);
}
this.user = tempUser;
}
/**
* 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 double getEstimatedPing() {
double currentPing = (ping != null) ? ping : platformPlayer.getPing();
double lastPing = (previousPing != null) ? previousPing : platformPlayer.getPing();
double ping = (currentPing - lastPing > KnockbackSyncBase.INSTANCE.getConfigManager().getSpikeThreshold()) ? lastPing : currentPing;
return Math.max(1, ping - PING_OFFSET);
}
// public boolean isKeepAliveIDOurs(long id) {
// return id == lastKeepAliveID;
// }
public void sendPing(boolean async) {
if (user == null || user.getEncoderState() != ConnectionState.PLAY) return;
String pingStrategy = KnockbackSyncBase.INSTANCE.getConfigManager().getConfigWrapper().getString("ping_strategy", "KEEPALIVE");
switch (pingStrategy) {
case "KEEPALIVE":
long keepAliveID = async ? NETTY_THREAD_TRANSACTION_ID : MAIN_THREAD_TRANSACTION_ID;
if (async) {
ChannelHelper.runInEventLoop(user.getChannel(), () -> {
// We call sendPacket instead of writePacket because it flushes immediately
// Making our time measurement more accurate since we don't call, System.nanoTime(), wait until flush
// And then actually send packet
user.sendPacket(new WrapperPlayServerKeepAlive(keepAliveID));
});
} else {
user.sendPacket(new WrapperPlayServerKeepAlive(keepAliveID));
}
break;
case "PING":
case "TRANSACTION":
PacketWrapper<?> packet;
short pingTransactionID = async ? NETTY_THREAD_TRANSACTION_ID : MAIN_THREAD_TRANSACTION_ID;
if (PacketEvents.getAPI().getServerManager().getVersion().isNewerThanOrEquals(ServerVersion.V_1_17)) {
packet = new WrapperPlayServerPing(pingTransactionID);
} else {
packet = new WrapperPlayServerWindowConfirmation((byte) 0, pingTransactionID, false);
}
if (async) {
ChannelHelper.runInEventLoop(user.getChannel(), () -> {
user.writePacket(packet);
});
} else {
user.writePacket(packet);
}
break;
}
}
/**
* Determines if the Player is on the ground clientside, but not serverside
* <p>
* Returns <code>ping ≥ (tMax + tFall)</code> and <code>gDist ≤ 1.3</code>
* <p>
* Where:
* <ul>
* <li><code>ping</code>: Estimated latency</li>
* <li><code>tMax</code>: Time to reach maximum upward velocity</li>
* <li><code>tFall</code>: Time to fall to the ground</li>
* <li><code>gDist</code>: Distance to the ground</li>
* </ul>
*
* @param verticalVelocity The Player's current vertical velocity.
* @return <code>true</code> if the Player is on the ground; <code>false</code> 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 / TICK_RATE * 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);
}
@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;
}
public long getKeepAliveSendTime() {
return lastKeepAliveID;
}
public boolean didWeSendThatPacket(long receivedId) {
return receivedId == NETTY_THREAD_TRANSACTION_ID || receivedId == MAIN_THREAD_TRANSACTION_ID;
}
}
@@ -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 extends BukkitRunnable {
@Override
public void run() {
if (!KnockbackSync.getInstance().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.PlayerDataManager;
import me.caseload.knockbacksync.player.PlayerData;
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(true);
}
}
}
@@ -0,0 +1,8 @@
package me.caseload.knockbacksync.scheduler;
public interface AbstractTaskHandle {
boolean getCancelled();
void cancel();
}
@@ -0,0 +1,17 @@
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();
}
@@ -0,0 +1,93 @@
package me.caseload.knockbacksync.sender;
import me.caseload.knockbacksync.KnockbackSyncBase;
import java.util.UUID;
/**
* Simple implementation of {@link Sender} using a {@link SenderFactory}
*
* @param <T> the command sender type
*/
public final class AbstractSender<T> implements Sender {
private final KnockbackSyncBase plugin;
private final SenderFactory<?, T> factory;
private final T sender;
private final UUID uniqueId;
private final String name;
private final boolean isConsole;
AbstractSender(KnockbackSyncBase plugin, SenderFactory<?, T> factory, T sender) {
this.plugin = plugin;
this.factory = factory;
this.sender = sender;
this.uniqueId = factory.getUniqueId(this.sender);
this.name = factory.getName(this.sender);
this.isConsole = this.factory.isConsole(this.sender);
}
@Override
public KnockbackSyncBase getPlugin() {
return this.plugin;
}
@Override
public UUID getUniqueId() {
return this.uniqueId;
}
@Override
public String getName() {
return this.name;
}
@Override
public void sendMessage(String message) {
this.factory.sendMessage(this.sender, message);
}
@Override
public boolean hasPermission(String permission) {
return isConsole() || this.factory.hasPermission(this.sender, permission);
}
@Override
public boolean hasPermission(String permission, boolean defaultIfUnset) {
return isConsole() || this.factory.hasPermission(this.sender, permission, defaultIfUnset);
}
@Override
public void performCommand(String commandLine) {
this.factory.performCommand(this.sender, commandLine);
}
@Override
public boolean isConsole() {
return this.isConsole;
}
@Override
public boolean isValid() {
return true;
// return isConsole() || this.plugin.getBootstrap().isPlayerOnline(this.uniqueId);
}
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof AbstractSender)) return false;
final AbstractSender<?> that = (AbstractSender<?>) o;
return this.getUniqueId().equals(that.getUniqueId());
}
@Override
public int hashCode() {
return this.uniqueId.hashCode();
}
@Override
public T getSender() {
return sender;
}
}
@@ -0,0 +1,92 @@
package me.caseload.knockbacksync.sender;
import me.caseload.knockbacksync.KnockbackSyncBase;
import java.util.UUID;
/**
* Wrapper interface to represent a CommandSender/CommandSource within the common command implementations.
*/
public interface Sender {
/**
* The uuid used by the console sender.
*/
UUID CONSOLE_UUID = new UUID(0, 0); // 00000000-0000-0000-0000-000000000000
/**
* The name used by the console sender.
*/
String CONSOLE_NAME = "Console";
/**
* Gets the plugin instance the sender is from.
*
* @return the plugin
*/
KnockbackSyncBase getPlugin();
/**
* Gets the sender's username
*
* @return a friendly username for the sender
*/
String getName();
/**
* Gets a string representing the senders username, and their current location
* within the network.
*
* @return a friendly identifier for the sender
*/
/**
* Gets the sender's unique id.
*
* <p>See {@link #CONSOLE_UUID} for the console's UUID representation.</p>
*
* @return the sender's uuid
*/
UUID getUniqueId();
/**
* Send a json message to the Sender.
*
* @param message the message to send.
*/
void sendMessage(String message);
/**
* Check if the Sender has a permission.
*
* @param permission the permission to check for
* @return true if the sender has the permission
*/
boolean hasPermission(String permission);
boolean hasPermission(String permission, boolean defaultIfUnset);
/**
* Makes the sender perform a command.
*
* @param commandLine the command
*/
void performCommand(String commandLine);
/**
* Gets whether this sender is the console
*
* @return if the sender is the console
*/
boolean isConsole();
/**
* Gets whether this sender is still valid & receiving messages.
*
* @return if this sender is valid
*/
default boolean isValid() {
return true;
}
Object getSender();
}
@@ -0,0 +1,53 @@
package me.caseload.knockbacksync.sender;
import me.caseload.knockbacksync.KnockbackSyncBase;
import java.util.Objects;
import java.util.UUID;
/**
* Factory class to make a thread-safe sender instance
*
* @param <P> the plugin type
* @param <T> the command sender type
*/
public abstract class SenderFactory<P extends KnockbackSyncBase, T> implements AutoCloseable {
private final P plugin;
public SenderFactory(P plugin) {
this.plugin = plugin;
}
protected P getPlugin() {
return this.plugin;
}
protected abstract UUID getUniqueId(T sender);
protected abstract String getName(T sender);
protected abstract void sendMessage(T sender, String message);
protected abstract boolean hasPermission(T sender, String node);
protected abstract boolean hasPermission(T sender, String node, boolean defaultIfUnset);
protected abstract void performCommand(T sender, String command);
protected abstract boolean isConsole(T sender);
protected boolean shouldSplitNewlines(T sender) {
return isConsole(sender);
}
public final Sender wrap(T sender) {
Objects.requireNonNull(sender, "sender");
return new AbstractSender<>(this.plugin, this, sender);
}
@SuppressWarnings("unchecked")
public final T unwrap(Sender sender) {
Objects.requireNonNull(sender, "sender");
return (T) sender.getSender();
}
}
@@ -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<Map<String, int[]>> 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<Map<String, int[]>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();
Map<String, int[]> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, int[]> 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();
}
}
@@ -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<Map<String, Integer>> 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<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, Integer> 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();
}
}
@@ -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<String, Throwable> 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;
}
@@ -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<Map<String, Map<String, Integer>>> 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<Map<String, Map<String, Integer>>> callable) {
super(chartId);
this.callable = callable;
}
@Override
public JsonObjectBuilder.JsonObject getChartData() throws Exception {
JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();
Map<String, Map<String, Integer>> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean reallyAllSkipped = true;
for (Map.Entry<String, Map<String, Integer>> entryValues : map.entrySet()) {
JsonObjectBuilder valueBuilder = new JsonObjectBuilder();
boolean allSkipped = true;
for (Map.Entry<String, Integer> 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();
}
}
@@ -0,0 +1,210 @@
package me.caseload.knockbacksync.stats;
import java.util.Arrays;
import java.util.stream.Collectors;
/**
* An extremely simple JSON builder.
*
* <p>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("{");
}
/**
* Escapes the given string like stated in https://www.ietf.org/rfc/rfc4627.txt.
*
* <p>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();
}
/**
* 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;
}
/**
* A super simple representation of a JSON object.
*
* <p>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;
}
}
}
@@ -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<Map<String, Integer>> 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<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, Integer> 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();
}
}
@@ -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<Map<String, Integer>> 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<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
valuesBuilder.appendField(entry.getKey(), new int[]{entry.getValue()});
}
return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build();
}
}
@@ -0,0 +1,29 @@
package me.caseload.knockbacksync.stats;
import java.util.concurrent.Callable;
public class SimplePie extends CustomChart {
private final Callable<String> 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<String> 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();
}
}
@@ -0,0 +1,29 @@
package me.caseload.knockbacksync.stats;
import java.util.concurrent.Callable;
public class SingleLineChart extends CustomChart {
private final Callable<Integer> 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<Integer> 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();
}
}
@@ -0,0 +1,99 @@
package me.caseload.knockbacksync.stats.custom;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
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;
import java.io.*;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
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 = KnockbackSyncBase.INSTANCE.getDataFolder();
public static URL jarUrl;
private static String cachedBuildType = null;
public BuildTypePie() {
super("build_type", BuildTypePie::determineBuildType);
}
public static String determineBuildType() {
if (cachedBuildType == null) {
cachedBuildType = calculateBuildType();
}
return cachedBuildType;
}
private static String calculateBuildType() {
try {
String currentHash = KnockbackSyncBase.INSTANCE.getPluginJarHashProvider().getPluginJarHash();
downloadBuildFiles();
if (isHashInFile(currentHash, new File(dataFolder, RELEASES_FILE))) {
return "release";
} else if (isHashInFile(currentHash, new File(dataFolder, DEV_BUILDS_FILE))) {
return "dev";
} else {
return "fork";
}
} catch (Exception e) {
e.printStackTrace();
return "unknown";
}
}
private static void downloadBuildFiles() throws IOException {
GitHub gitHub = GitHub.connectAnonymously();
GHRelease latestRelease = gitHub.getRepository("CASELOAD7000/knockback-sync")
.getLatestRelease();
List<GHAsset> assets = latestRelease.listAssets().toList();
for (GHAsset asset : assets) {
if (asset.getName().equals(RELEASES_FILE) || asset.getName().equals(DEV_BUILDS_FILE)) {
KnockbackSyncBase.INSTANCE.getLogger().info("Downloading: " + asset.getName());
String jsonContent = readStringFromURL(asset.getUrl().toString());
JsonObject jsonObject = JsonParser.parseString(jsonContent).getAsJsonObject();
String downloadUrl = jsonObject.get("browser_download_url").getAsString();
try (InputStream inputStream = new URL(downloadUrl).openStream(); FileOutputStream outputStream = new FileOutputStream(new File(dataFolder, asset.getName()))) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
}
KnockbackSyncBase.INSTANCE.getLogger().info("Downloaded: " + asset.getName());
}
}
}
private static boolean isHashInFile(String hash, File file) throws IOException {
if (!file.exists()) {
return false;
}
List<String> lines = Files.readAllLines(Paths.get(file.getPath()));
return lines.contains(hash);
}
private static String readStringFromURL(String urlString) throws IOException {
try (InputStream inputStream = new URL(urlString).openStream()) {
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
result.write(buffer, 0, bytesRead);
}
return result.toString("UTF-8");
}
}
}
@@ -0,0 +1,5 @@
package me.caseload.knockbacksync.stats.custom;
public interface Metrics {
void shutdown();
}
@@ -0,0 +1,276 @@
package me.caseload.knockbacksync.stats.custom;
import me.caseload.knockbacksync.stats.CustomChart;
import me.caseload.knockbacksync.stats.JsonObjectBuilder;
import org.jetbrains.annotations.NotNull;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
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<JsonObjectBuilder> appendPlatformDataConsumer;
private final Consumer<JsonObjectBuilder> appendServiceDataConsumer;
private final Consumer<Runnable> submitTaskConsumer;
private final Supplier<Boolean> checkServiceEnabledSupplier;
private final BiConsumer<String, Throwable> errorLogger;
private final Consumer<String> infoLogger;
private final boolean logErrors;
private final boolean logSentData;
private final boolean logResponseStatusText;
private final Set<CustomChart> 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<JsonObjectBuilder> appendPlatformDataConsumer,
Consumer<JsonObjectBuilder> appendServiceDataConsumer,
Consumer<Runnable> submitTaskConsumer,
Supplier<Boolean> checkServiceEnabledSupplier,
BiConsumer<String, Throwable> errorLogger,
Consumer<String> infoLogger,
boolean logErrors,
boolean logSentData,
boolean logResponseStatusText,
boolean skipRelocateCheck) {
this.scheduler = getScheduledThreadPoolExecutor();
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();
}
}
private static @NotNull ScheduledThreadPoolExecutor getScheduledThreadPoolExecutor() {
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);
return scheduler;
}
/**
* 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();
}
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!");
}
}
}
}
@@ -0,0 +1,25 @@
package me.caseload.knockbacksync.stats.custom;
import me.caseload.knockbacksync.KnockbackSyncBase;
import me.caseload.knockbacksync.manager.PlayerDataManager;
import me.caseload.knockbacksync.player.PlatformPlayer;
import me.caseload.knockbacksync.player.PlayerData;
import me.caseload.knockbacksync.stats.AdvancedPie;
import java.util.HashMap;
import java.util.Map;
public class PlayerVersionsPie extends AdvancedPie {
// Gets the client versions of players online
public PlayerVersionsPie() {
super("player_version", () -> {
Map<String, Integer> valueMap = new HashMap<>();
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;
});
}
}
@@ -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 final 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();
}
}
@@ -0,0 +1,13 @@
package me.caseload.knockbacksync.stats.custom;
import lombok.Getter;
@Getter
public abstract class StatsManager {
Metrics metrics;
public void init() {
throw new IllegalStateException("Empty stats class!");
}
}
@@ -0,0 +1,56 @@
package me.caseload.knockbacksync.util;
import com.google.common.base.Preconditions;
import me.caseload.knockbacksync.manager.PlayerDataManager;
import me.caseload.knockbacksync.player.PlayerData;
import org.jetbrains.annotations.NotNull;
import java.util.UUID;
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);
}
public static String getPingMessage(UUID senderUUID, UUID targetUUID) {
String noun = "";
PlayerData playerData = null;
if (senderUUID == null) {
senderUUID = targetUUID;
}
if (senderUUID.equals(targetUUID) || targetUUID == null) {
playerData = PlayerDataManager.getPlayerData(senderUUID);
if (playerData == null) {
return ChatUtil.translateAlternateColorCodes('&', "&cKnockback synchronization is currently disabled for you!");
}
noun = "Your";
} else {
playerData = PlayerDataManager.getPlayerData(targetUUID);
if (playerData == null) {
return ChatUtil.translateAlternateColorCodes('&', "&cKnockback synchronization is currently disabled for the target player.");
}
noun = playerData.getPlatformPlayer().getName() + "'s";
}
String rawReturnString = null;
if (playerData.getPing() == null) {
rawReturnString = String.format("Pong not received. %s estimated ping is &b" + playerData.getPlatformPlayer().getPing() + "&rms.", noun);
} else {
rawReturnString = String.format("%s last ping packet took &b %.3f&rms. Jitter: &b%.3f&rms.", noun, playerData.getPing(), playerData.getJitter());
}
return ChatUtil.translateAlternateColorCodes('&', rawReturnString);
}
}
@@ -0,0 +1,31 @@
package me.caseload.knockbacksync.util;
import org.geysermc.floodgate.api.FloodgateApi;
import java.util.UUID;
public class FloodgateUtil {
private static boolean CHECKED_FOR_FLOODGATE;
private static boolean FLOODGATE_PRESENT;
public static boolean isFloodgatePlayer(UUID uuid) {
if (!CHECKED_FOR_FLOODGATE) {
try {
Class.forName("org.geysermc.floodgate.api.FloodgateApi");
FLOODGATE_PRESENT = true;
} catch (ClassNotFoundException e) {
FLOODGATE_PRESENT = false;
}
CHECKED_FOR_FLOODGATE = true;
}
if (FLOODGATE_PRESENT) {
return FloodgateApi.getInstance().isFloodgatePlayer(uuid);
} else {
return false;
}
}
}
@@ -0,0 +1,82 @@
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;
}
}
@@ -1,50 +1,58 @@
package me.caseload.knockbacksync.util;
public class MathUtil {
private static final double TERMINAL_VELOCITY = 3.92;
private static final double GRAVITY = 0.08;
private static final double MULTIPLIER = 0.98;
public static double calculateDistanceTraveled(double velocity, int time)
{
double totalDistance = 0;
for (int i = 0; i < time; i++)
{
totalDistance += velocity;
velocity = ((velocity - GRAVITY) * MULTIPLIER);
velocity = Math.min(velocity, TERMINAL_VELOCITY);
}
return totalDistance;
}
public static int calculateFallTime(double initialVelocity, double distance) {
double velocity = Math.abs(initialVelocity);
int ticks = 0;
while (distance > 0) {
velocity += GRAVITY;
velocity = Math.min(velocity, TERMINAL_VELOCITY);
velocity *= MULTIPLIER;
distance -= velocity;
ticks++;
}
return ticks;
}
public static int calculateTimeToMaxVelocity(double targetVerticalVelocity) {
double a = -GRAVITY * MULTIPLIER;
double b = GRAVITY + 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);
}
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);
}
}
@@ -0,0 +1,31 @@
package me.caseload.knockbacksync.util;
import org.jetbrains.annotations.Nullable;
public class NumberConversions {
public static long toLong(@Nullable Object object, long defaultValue) {
if (object instanceof Number) {
return ((Number) object).longValue();
} else {
try {
return Long.parseLong(object.toString());
} catch (NumberFormatException | NullPointerException ignored) {
}
return defaultValue;
}
}
public static int toInt(@Nullable Object object, int def) {
if (object instanceof Number) {
return ((Number) object).intValue();
} else {
try {
return Integer.parseInt(object.toString());
} catch (NumberFormatException | NullPointerException ignored) {
}
return def;
}
}
}
@@ -0,0 +1,4 @@
package me.caseload.knockbacksync.util.data;
public interface MethodFinder {
}
@@ -0,0 +1,29 @@
package me.caseload.knockbacksync.util.data;
import lombok.Getter;
import java.util.Objects;
@Getter
public class Pair<A, B> {
private final A first;
private final B second;
public Pair(A first, B second) {
this.first = first;
this.second = second;
}
public static <T, K> Pair<T, K> of(T a, K b) {
return new Pair<T, K>(a, b);
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Pair)) {
return false;
}
Pair b = (Pair) o;
return Objects.equals(this.first, b.first) && Objects.equals(this.second, b.second);
}
}
@@ -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<PlatformPlayer> 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);
// }
}
@@ -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);
}
@@ -0,0 +1,5 @@
package me.caseload.knockbacksync.world.raytrace;
public enum FluidHandling {
NONE, SOURCE_ONLY, ALWAYS
}
@@ -0,0 +1,5 @@
package me.caseload.knockbacksync.world.raytrace;
public enum RayTraceOption {
BLOCK, FLUID, NONE
}
@@ -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;
}
}
+54
View File
@@ -0,0 +1,54 @@
#########################################
# KnockbackSync Configuration #
#########################################
# Do not modify!
config-version: 2
# 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: 20 # 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
# OPTIONS: KEEPALIVE, PING, TRANSACTION - PING and TRANSACTION are aliases for each other and are effectively the same
# The packet type used to measure ping by the runnable.
# KEEPALIVE is the most accurate however sending too many of them too often (such as using a runnable with a low interval)
# - May disconnect players, especially laggy ones if sent too often
# - The default interval of 20 ticks or 1 second
# means it is in theory possible for a player to have a ping spike in-between two sword attacks
# and have it immediately spike back down, slightly throwing off knockback synchronization
# in practice this is very rare and the extra ping accuracy and precision is more valued
# PING/TRANSACTION can be sent more often (and therefore better detect ping spikes) but are less precise
# ping measured in ms with PING/TRANSACTION is typically within ± 5ms of actual but can be up to 50ms off
ping_strategy: "KEEPALIVE"
# This setting has yet to be implemented. Enable if you want it to be enabled as soon as the next update add support
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: "&aSuccessfully &cdisabled &aKnockbackSync 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."
+86
View File
@@ -0,0 +1,86 @@
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
}
// TODO migrate to only including sourceset for compile, test and javadoc tasks
// Currently must build with gradle build -x test to skip test
tasks.withType<JavaCompile>().configureEach {
source(project(":common").sourceSets.main.get().allSource)
}
tasks.withType<Javadoc>().configureEach {
source(project(":common").sourceSets.main.get().allJava)
}
tasks.named<JavaCompile>("compileTestJava") {
exclude("**/*")
}
dependencies {
implementation(project(":common"))
minecraft("com.mojang:minecraft:${rootProject.property("minecraft_version")}")
mappings(loom.layered {
officialMojangMappings()
parchment("org.parchmentmc.data:parchment-1.21:${rootProject.property("parchment_mappings")}")
})
modImplementation("net.fabricmc:fabric-loader:${rootProject.property("loader_version")}")
modImplementation("net.fabricmc.fabric-api:fabric-api:${rootProject.property("fabric_version")}")
include(modImplementation("me.lucko:fabric-permissions-api:0.3.1")!!)
include(modImplementation("com.github.retrooper:packetevents-fabric:2.5.8-SNAPSHOT")!!)
include(modImplementation("org.incendo:cloud-fabric:2.0.0-beta.9")!!)
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")!!)
compileOnly("org.geysermc.floodgate:api:2.0-SNAPSHOT")
compileOnly("org.projectlombok:lombok:1.18.34")
annotationProcessor("org.projectlombok:lombok:1.18.34")
}
tasks.shadowJar {
archiveClassifier.set("dev")
configurations = listOf(shadeThisThing)
isEnableRelocation = true
relocationPrefix = "${project.property("maven_group")}.${project.property("archives_base_name")}.shaded"
finalizedBy(tasks.remapJar)
}
tasks.remapJar {
archiveClassifier.set(null as String?)
dependsOn(tasks.shadowJar)
inputFile = tasks.shadowJar.get().archiveFile
}
tasks.processResources {
from(project(":common").sourceSets.main.get().resources)
inputs.property("version", project.version)
inputs.property("minecraft_version", rootProject.property("minecraft_version"))
inputs.property("loader_version", rootProject.property("loader_version"))
filteringCharset = "UTF-8"
filesMatching("fabric.mod.json") {
expand(
"version" to project.version,
"minecraft_version" to rootProject.property("minecraft_version"),
"loader_version" to rootProject.property("loader_version")
)
}
}
java {
sourceCompatibility = JavaVersion.VERSION_21
targetCompatibility = JavaVersion.VERSION_21
}
@@ -0,0 +1,126 @@
package me.caseload.knockbacksync;
import com.github.retrooper.packetevents.PacketEvents;
import io.github.retrooper.packetevents.factory.fabric.FabricPacketEventsBuilder;
import lombok.Getter;
import me.caseload.knockbacksync.listener.fabric.FabricPlayerDamageListener;
import me.caseload.knockbacksync.listener.fabric.FabricPlayerJoinQuitListener;
import me.caseload.knockbacksync.listener.fabric.FabricPlayerKnockbackListener;
import me.caseload.knockbacksync.listener.fabric.FabricTickRateChangeListener;
import me.caseload.knockbacksync.manager.ConfigManager;
import me.caseload.knockbacksync.permission.FabricPermissionChecker;
import me.caseload.knockbacksync.permission.PermissionChecker;
import me.caseload.knockbacksync.scheduler.FabricSchedulerAdapter;
import me.caseload.knockbacksync.sender.FabricPlayerSelectorParser;
import me.caseload.knockbacksync.sender.FabricSenderFactory;
import me.caseload.knockbacksync.stats.custom.FabricStatsManager;
import me.caseload.knockbacksync.stats.custom.PluginJarHashProvider;
import me.caseload.knockbacksync.world.FabricServer;
import net.fabricmc.loader.api.FabricLoader;
import net.fabricmc.loader.api.ModContainer;
import org.incendo.cloud.execution.ExecutionCoordinator;
import org.incendo.cloud.fabric.FabricServerCommandManager;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.util.Optional;
import java.util.logging.Logger;
public class KBSyncFabricBase extends KnockbackSyncBase {
private final Logger logger = Logger.getLogger(KBSyncFabricLoaderMod.class.getName());
private final FabricPermissionChecker permissionChecker = new FabricPermissionChecker();
@Getter
private final FabricSenderFactory fabricSenderFactory = new FabricSenderFactory(this);
public KBSyncFabricBase() {
super.configManager = new ConfigManager();
super.playerSelectorParser = new FabricPlayerSelectorParser<>();
super.commandManager = new FabricServerCommandManager<>(
ExecutionCoordinator.simpleCoordinator(),
fabricSenderFactory
);
super.statsManager = new FabricStatsManager();
super.platformServer = new FabricServer();
super.pluginJarHashProvider = new PluginJarHashProvider(getJarURL());
}
@Override
public Logger getLogger() {
return logger;
}
@Override
public File getDataFolder() {
return FabricLoader.getInstance().getConfigDir().toFile();
}
@Override
public InputStream getResource(String filename) {
return getClass().getResourceAsStream("/config.yml");
}
@Override
public void load() {
PacketEvents.setAPI(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();
new FabricTickRateChangeListener().register();
}
@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;
}
private URL getJarURL() {
URL jarUrl = null;
Optional<ModContainer> modContainer = FabricLoader.getInstance().getModContainer("knockbacksync");
if (modContainer.isPresent()) {
String jarPath = modContainer.get().getRootPath().getFileSystem().toString();
jarPath = jarPath.replaceAll("^jar:", "").replaceAll("!/$", "");
try {
jarUrl = new File(jarPath).toURI().toURL();
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
return jarUrl;
}
}
@@ -0,0 +1,34 @@
package me.caseload.knockbacksync;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
import net.fabricmc.loader.api.FabricLoader;
import net.fabricmc.loader.api.entrypoint.PreLaunchEntrypoint;
import net.minecraft.server.MinecraftServer;
public class KBSyncFabricLoaderMod implements PreLaunchEntrypoint, ModInitializer {
private final KnockbackSyncBase core = new KBSyncFabricBase();
public static MinecraftServer getServer() {
return (MinecraftServer) FabricLoader.getInstance().getGameInstance();
}
@Override
public void onPreLaunch() {
core.load();
}
@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();
});
}
}
@@ -0,0 +1,24 @@
package me.caseload.knockbacksync.callback;
import net.fabricmc.fabric.api.event.Event;
import net.fabricmc.fabric.api.event.EventFactory;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.phys.Vec3;
public interface PlayerVelocityEvent {
Event<PlayerVelocityEvent> EVENT = EventFactory.createArrayBacked(PlayerVelocityEvent.class,
(listeners) -> (player, velocity) -> {
for (PlayerVelocityEvent listener : listeners) {
InteractionResult result = listener.onVelocityChange(player, velocity);
if (result != InteractionResult.PASS) {
return result;
}
}
return InteractionResult.PASS;
});
InteractionResult onVelocityChange(ServerPlayer player, Vec3 velocity);
}
@@ -0,0 +1,15 @@
package me.caseload.knockbacksync.callback;
import net.fabricmc.fabric.api.event.Event;
import net.fabricmc.fabric.api.event.EventFactory;
public interface TickRateChangeEvent {
Event<TickRateChangeEvent> EVENT = EventFactory.createArrayBacked(TickRateChangeEvent.class,
(listeners) -> (oldTickRate, newTickRate) -> {
for (TickRateChangeEvent listener : listeners) {
listener.onTickRateChange(oldTickRate, newTickRate);
}
});
void onTickRateChange(float oldTickRate, float newTickRate);
}
@@ -0,0 +1,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
}
}
}
@@ -0,0 +1,17 @@
package me.caseload.knockbacksync.listener.fabric;
import me.caseload.knockbacksync.listener.PlayerJoinQuitListener;
import me.caseload.knockbacksync.player.FabricPlayer;
import me.caseload.knockbacksync.player.PlayerData;
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
public class FabricPlayerJoinQuitListener extends PlayerJoinQuitListener {
public void register() {
ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> {
onPlayerJoin(new PlayerData(new FabricPlayer(handler.player)));
});
ServerPlayConnectionEvents.DISCONNECT.register(((handler, server) -> {
onPlayerQuit(handler.player.getUUID());
}));
}
}
@@ -0,0 +1,30 @@
package me.caseload.knockbacksync.listener.fabric;
import com.github.retrooper.packetevents.util.Vector3d;
import me.caseload.knockbacksync.callback.PlayerVelocityEvent;
import me.caseload.knockbacksync.listener.PlayerKnockbackListener;
import me.caseload.knockbacksync.player.FabricPlayer;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.damagesource.DamageTypes;
public class FabricPlayerKnockbackListener extends PlayerKnockbackListener {
public void register() {
PlayerVelocityEvent.EVENT.register((player, velocity) -> {
DamageSource lastDamageSource = player.getLastDamageSource();
if (lastDamageSource == null)
return InteractionResult.PASS;
// Check if the damage is from a player attack
if (!lastDamageSource.is(DamageTypes.PLAYER_ATTACK))
return InteractionResult.PASS;
onPlayerVelocity(new FabricPlayer(player), new Vector3d(velocity.x, velocity.y, velocity.z));
// This SHOULD mean we return original velocity for Fabric (no modification here)
// But since we set it ourselves due to following bukkit's design patterns and doing victim
// We return a pass so velocity isn't set twice
return InteractionResult.PASS;
});
}
}
@@ -0,0 +1,14 @@
package me.caseload.knockbacksync.listener.fabric;
import me.caseload.knockbacksync.callback.TickRateChangeEvent;
import me.caseload.knockbacksync.player.PlayerData;
public class FabricTickRateChangeListener {
public void register() {
TickRateChangeEvent.EVENT.register((oldTickRate, newTickRate) -> {
if (oldTickRate != newTickRate) {
PlayerData.TICK_RATE = newTickRate;
}
});
}
}
@@ -0,0 +1,14 @@
package me.caseload.knockbacksync.mixin;
import net.minecraft.commands.CommandSource;
import net.minecraft.commands.CommandSourceStack;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
@Mixin(CommandSourceStack.class)
public interface CommandStackSourceAccessor {
@Accessor("source")
CommandSource getSource();
}
@@ -0,0 +1,37 @@
package me.caseload.knockbacksync.mixin;
import me.caseload.knockbacksync.callback.PlayerVelocityEvent;
import net.minecraft.network.protocol.game.ClientboundSetEntityMotionPacket;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.phys.Vec3;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(Player.class)
public class PlayerMixin {
@Inject(method = "attack", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/protocol/game/ClientboundSetEntityMotionPacket;<init>(Lnet/minecraft/world/entity/Entity;)V"), cancellable = true)
private void onAttack(Entity target, CallbackInfo ci) {
if (target instanceof ServerPlayer serverPlayer && target.hurtMarked) {
Vec3 velocity = target.getDeltaMovement();
InteractionResult result = PlayerVelocityEvent.EVENT.invoker().onVelocityChange(serverPlayer, velocity);
if (result == InteractionResult.FAIL) {
target.hurtMarked = false;
ci.cancel(); // Prevent sending the velocity packet
} else if (result == InteractionResult.SUCCESS) {
// Currently unnecessary since we do this in the handler, will move later
target.setDeltaMovement(velocity);
serverPlayer.connection.send(new ClientboundSetEntityMotionPacket(target));
target.hurtMarked = false;
ci.cancel(); // Prevent sending the original velocity packet
}
}
}
}
@@ -0,0 +1,40 @@
package me.caseload.knockbacksync.mixin;
import me.caseload.knockbacksync.callback.PlayerVelocityEvent;
import net.minecraft.server.level.ServerEntity;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.phys.Vec3;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(ServerEntity.class)
public class ServerEntityMixin {
@Shadow
@Final
private Entity entity;
@Inject(method = "sendChanges", at = @At(value = "FIELD", target = "Lnet/minecraft/world/entity/Entity;hurtMarked:Z", ordinal = 1), cancellable = true)
private void onSendChanges(CallbackInfo ci) {
if (this.entity.hurtMarked && this.entity instanceof ServerPlayer player) {
Vec3 velocity = player.getDeltaMovement();
InteractionResult result = PlayerVelocityEvent.EVENT.invoker().onVelocityChange(player, velocity);
if (result == InteractionResult.FAIL) {
this.entity.hurtMarked = false;
ci.cancel();
} else if (result == InteractionResult.SUCCESS) {
// Currently unnecessary since we do this in the handler, will move later
player.setDeltaMovement(velocity);
}
}
}
}
Loaded 100 of 132 files, more files were not shown because too many files have changed in this diff. Show more