mirror of
https://github.com/Cubicake/RaycastedAntiESP.git
synced 2026-11-17 06:26:04 -05:00
Compare commits
428
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5b207a9ecd | ||
|
|
d90ac06a63 | ||
|
|
77237fde49 | ||
|
|
40ae58b7ee | ||
|
|
02c24527ef | ||
|
|
c9f374e074 | ||
|
|
2cb0a46917 | ||
|
|
d6818e579d | ||
|
|
807477712d | ||
|
|
6073e634c4 | ||
|
|
ad707b7158 | ||
|
|
3ebb4a9138 | ||
|
|
ca8bb02010 | ||
|
|
c393d502bd | ||
|
|
f032a12a66 | ||
|
|
fd343fc9b3 | ||
|
|
21653da4f9 | ||
|
|
c42f008fa0 | ||
|
|
1fcec23a57 | ||
|
|
37c905eb8c | ||
|
|
516b5df1d3 | ||
|
|
914779f3e0 | ||
|
|
7c16afccb3 | ||
|
|
a49213e054 | ||
|
|
6877911210 | ||
|
|
006ac0ba7a | ||
|
|
f92de7631b | ||
|
|
a6903ebffd | ||
|
|
d01e202401 | ||
|
|
71406b5803 | ||
|
|
30a9a73e25 | ||
|
|
e982cb4550 | ||
|
|
37514fa879 | ||
|
|
6eee4351ab | ||
|
|
1f0cb15714 | ||
|
|
367976e51f | ||
|
|
c4c3c498c2 | ||
|
|
c29667aae0 | ||
|
|
558e773085 | ||
|
|
30b123ba3c | ||
|
|
87fd94baf4 | ||
|
|
1e5a4eb95b | ||
|
|
981b375d6d | ||
|
|
6de11030b0 | ||
|
|
d445aa58ba | ||
|
|
49311be791 | ||
|
|
0b4df5124b | ||
|
|
4435058373 | ||
|
|
4dfed55d48 | ||
|
|
c2b6941922 | ||
|
|
feb80bf678 | ||
|
|
c4fd919a08 | ||
|
|
40f91482d4 | ||
|
|
3f82330433 | ||
|
|
8cfe2b0a2e | ||
|
|
f2c1d01051 | ||
|
|
e1d0db9d5f | ||
|
|
a86a9bc4c0 | ||
|
|
377c12a00a | ||
|
|
9bc14b2097 | ||
|
|
02f9df6643 | ||
|
|
e2af9f65c1 | ||
|
|
0eb1766a4a | ||
|
|
4a3f25045f | ||
|
|
0c80348416 | ||
|
|
4295d2fe8a | ||
|
|
3f8ccff505 | ||
|
|
bc440490f9 | ||
|
|
5527e38ea4 | ||
|
|
244fde97c0 | ||
|
|
8b3a62f1f5 | ||
|
|
45d0e0581c | ||
|
|
aa7934f258 | ||
|
|
cfdb255b56 | ||
|
|
14e6aaaae6 | ||
|
|
d7cc7abd8c | ||
|
|
73e58e191e | ||
|
|
e5a591af1a | ||
|
|
9951b5d7a1 | ||
|
|
e99c3b9de2 | ||
|
|
0500f4bd5f | ||
|
|
9a841308ff | ||
|
|
c4bf1cbf0b | ||
|
|
db22c675db | ||
|
|
5a42fd74ad | ||
|
|
85b788742c | ||
|
|
20f660b8a3 | ||
|
|
4d17483a5a | ||
|
|
274b081c78 | ||
|
|
45e14637e0 | ||
|
|
b007735636 | ||
|
|
bb7275a618 | ||
|
|
853fa1531a | ||
|
|
396382bcc2 | ||
|
|
aae6bdb53c | ||
|
|
2f8f698069 | ||
|
|
fc3badb90a | ||
|
|
7aab3b60e8 | ||
|
|
2ab157bd4a | ||
|
|
3227c63e2e | ||
|
|
1dc77b3e6f | ||
|
|
cb044f789d | ||
|
|
c110aab634 | ||
|
|
5d407afbdf | ||
|
|
a8f12c9a24 | ||
|
|
0e4c251c6c | ||
|
|
e2b598a361 | ||
|
|
8c140cf8b6 | ||
|
|
4fe9ab02ef | ||
|
|
a21102d04f | ||
|
|
22488e9e71 | ||
|
|
bc40438cb3 | ||
|
|
3f633710e7 | ||
|
|
8de5d53198 | ||
|
|
53650f9b63 | ||
|
|
ba812bce3a | ||
|
|
42932abaa5 | ||
|
|
290749dde8 | ||
|
|
e19808fb4b | ||
|
|
691d429652 | ||
|
|
1575091d12 | ||
|
|
4919383c73 | ||
|
|
5293db6c86 | ||
|
|
c5f17a7b12 | ||
|
|
ddafbd0c25 | ||
|
|
8d9a354154 | ||
|
|
64bfcccde5 | ||
|
|
e91dc4647d | ||
|
|
96601efed5 | ||
|
|
c63a194ea9 | ||
|
|
71cde26cb9 | ||
|
|
33ab1cd234 | ||
|
|
e1c96d87ff | ||
|
|
3d8686e1ae | ||
|
|
971a648ad8 | ||
|
|
b0f05eaf4f | ||
|
|
bc9fcd6d7a | ||
|
|
a631c57465 | ||
|
|
9f9fb7f021 | ||
|
|
903e7c84bc | ||
|
|
ae75c37d90 | ||
|
|
17f5040c49 | ||
|
|
c04cf7558e | ||
|
|
11358badac | ||
|
|
008e62eee2 | ||
|
|
409261000e | ||
|
|
4854b1f88b | ||
|
|
e384ea0775 | ||
|
|
61df3f4f2d | ||
|
|
9f3eec6f09 | ||
|
|
4361276070 | ||
|
|
5d852cd6d3 | ||
|
|
2b2c7b9108 | ||
|
|
93949b7906 | ||
|
|
cee4d4b6f9 | ||
|
|
9fed35527d | ||
|
|
d101ba9b99 | ||
|
|
4527a9dd02 | ||
|
|
8aefd39d65 | ||
|
|
ccbed56a99 | ||
|
|
5e4692c753 | ||
|
|
5d05ac00b7 | ||
|
|
7d611ffdcb | ||
|
|
f3ff087874 | ||
|
|
a11711e06f | ||
|
|
30286928b2 | ||
|
|
5fdf26f624 | ||
|
|
f72da61436 | ||
|
|
980cc33e7b | ||
|
|
d873c7b1ff | ||
|
|
f67b0b2ae7 | ||
|
|
c047ed08e1 | ||
|
|
e886efa823 | ||
|
|
740974f17c | ||
|
|
f38bda6993 | ||
|
|
61e7cac35f | ||
|
|
8f61e203f8 | ||
|
|
751398eaaa | ||
|
|
736ccab3e0 | ||
|
|
32a8d92df4 | ||
|
|
af0d887e14 | ||
|
|
f32c8ec9fa | ||
|
|
858c4d4340 | ||
|
|
274d437525 | ||
|
|
c610bc42a6 | ||
|
|
ae8905ed46 | ||
|
|
dcaed38f4d | ||
|
|
512a4db255 | ||
|
|
4fd8954fea | ||
|
|
1b5db5edca | ||
|
|
a08a477176 | ||
|
|
f4f3ca4d63 | ||
|
|
ab537e777b | ||
|
|
02938e3b57 | ||
|
|
e4b488eb69 | ||
|
|
e55b685ce2 | ||
|
|
6fd6d9bc04 | ||
|
|
d1244be5d1 | ||
|
|
dd9db4211d | ||
|
|
162bd3cf20 | ||
|
|
f78c3d1243 | ||
|
|
3feff5eb8a | ||
|
|
a47dcb94a8 | ||
|
|
65b6dbc44a | ||
|
|
a87a403e2d | ||
|
|
ddfb1748f7 | ||
|
|
c4669494b4 | ||
|
|
d340702530 | ||
|
|
fd8aa8a82a | ||
|
|
39f17f92a5 | ||
|
|
f47ef79707 | ||
|
|
f8a3f09c07 | ||
|
|
18c8dd11f5 | ||
|
|
7fccdb6e53 | ||
|
|
769c13db81 | ||
|
|
65bdc8fa7d | ||
|
|
f94c2053eb | ||
|
|
7cb16521a2 | ||
|
|
4dff4245f0 | ||
|
|
5472af1191 | ||
|
|
a7d2c953bc | ||
|
|
f565ea0fe1 | ||
|
|
b4430b70df | ||
|
|
28b3cff770 | ||
|
|
1d4f452098 | ||
|
|
2e7d35bc1a | ||
|
|
1be44580c0 | ||
|
|
a0aba0d37b | ||
|
|
1cc87b5b9e | ||
|
|
dfcfe3576f | ||
|
|
1d15c21200 | ||
|
|
c56aab576b | ||
|
|
c73b9abb6e | ||
|
|
9e9d880691 | ||
|
|
2773b98ef1 | ||
|
|
5f7a247224 | ||
|
|
ae852ae4c7 | ||
|
|
0325ee118e | ||
|
|
55ba8e5b9e | ||
|
|
c7705d8217 | ||
|
|
94ea345614 | ||
|
|
5ebfb36f4b | ||
|
|
4770f22770 | ||
|
|
6451771f1d | ||
|
|
038768adda | ||
|
|
e5338bbc34 | ||
|
|
cfbb6a54aa | ||
|
|
89a2a1cf32 | ||
|
|
955e24da66 | ||
|
|
152dcbc4db | ||
|
|
04d85e843a | ||
|
|
fb28453f4f | ||
|
|
53a60be932 | ||
|
|
284233e1b2 | ||
|
|
6e2a110380 | ||
|
|
dddbaee001 | ||
|
|
958756df2d | ||
|
|
371c9c8155 | ||
|
|
3f212e8766 | ||
|
|
4f086b4d6a | ||
|
|
b97d938425 | ||
|
|
f93723a0a4 | ||
|
|
93e0b54ff4 | ||
|
|
e77d450053 | ||
|
|
50acc8e66c | ||
|
|
fea6800269 | ||
|
|
9e742e62b5 | ||
|
|
0ab820fcd9 | ||
|
|
b07de426a4 | ||
|
|
316c2ec10f | ||
|
|
a7465f9d59 | ||
|
|
332f0becb4 | ||
|
|
3cc6b43999 | ||
|
|
d8daf0dd7a | ||
|
|
b189e576c0 | ||
|
|
165f30e339 | ||
|
|
5d00ae3a02 | ||
|
|
d04a0903bd | ||
|
|
50d1d359c4 | ||
|
|
3e33722426 | ||
|
|
84eb5fc888 | ||
|
|
2923125933 | ||
|
|
812ef94284 | ||
|
|
e47f788086 | ||
|
|
254c86919b | ||
|
|
d42ab704d6 | ||
|
|
f226b53bb0 | ||
|
|
400a5b96eb | ||
|
|
e1d737c67b | ||
|
|
6c5fcc35e8 | ||
|
|
a2094ebac5 | ||
|
|
3250ea4b33 | ||
|
|
df6537b12d | ||
|
|
7a5794efee | ||
|
|
89c07d5b53 | ||
|
|
15132e4825 | ||
|
|
db48f8fe08 | ||
|
|
6dfb7c3715 | ||
|
|
9fc793b761 | ||
|
|
160597a5a0 | ||
|
|
75957b9081 | ||
|
|
da344c7962 | ||
|
|
ba08b02975 | ||
|
|
328de7f129 | ||
|
|
c814e1e0b6 | ||
|
|
50b259ed5b | ||
|
|
f7d21a716d | ||
|
|
ce8ce72151 | ||
|
|
02253fd487 | ||
|
|
b5540006e3 | ||
|
|
344f259f95 | ||
|
|
331310ddd1 | ||
|
|
d35adc6f5f | ||
|
|
8afb1d10e9 | ||
|
|
e963a69f64 | ||
|
|
d66bf182b9 | ||
|
|
ea36d636e9 | ||
|
|
d3a2b43ba3 | ||
|
|
26ce1ff826 | ||
|
|
563f19e4a3 | ||
|
|
bdf22111ad | ||
|
|
b4e65f9653 | ||
|
|
de3ddd88da | ||
|
|
d5a55ef393 | ||
|
|
7dd2d204ce | ||
|
|
b3a418482b | ||
|
|
77c391996e | ||
|
|
5d3fbb92a0 | ||
|
|
30e26de415 | ||
|
|
ff7e71087b | ||
|
|
9221ea87fa | ||
|
|
e72440051c | ||
|
|
7edf021f33 | ||
|
|
e785d2c7d3 | ||
|
|
6b3177175f | ||
|
|
d90f3e4389 | ||
|
|
f733ee6ff6 | ||
|
|
868b41ea02 | ||
|
|
3076fccbea | ||
|
|
f637ac5607 | ||
|
|
da8db38d51 | ||
|
|
cf92d3817b | ||
|
|
dac5d8597d | ||
|
|
e0029df844 | ||
|
|
07865ea73b | ||
|
|
0622ad6f83 | ||
|
|
33863642de | ||
|
|
0c22c40d3e | ||
|
|
4e9d88dc08 | ||
|
|
a2a96a3353 | ||
|
|
e4c8ac11dc | ||
|
|
fda6d08e9a | ||
|
|
db7032b5b2 | ||
|
|
a46746d5cf | ||
|
|
35a42a49a9 | ||
|
|
cf953eb3c8 | ||
|
|
92f4b9ac45 | ||
|
|
b0f0e1a8f5 | ||
|
|
ca9da23ceb | ||
|
|
25295627cc | ||
|
|
090b96ac81 | ||
|
|
63efc23203 | ||
|
|
e57238897a | ||
|
|
a870d24c31 | ||
|
|
c895787ce2 | ||
|
|
91ab493a77 | ||
|
|
b6ac0d54be | ||
|
|
63c7b398c1 | ||
|
|
acf9c27c86 | ||
|
|
422a189069 | ||
|
|
80ac9d287f | ||
|
|
d2dff3de3c | ||
|
|
30dc0f420e | ||
|
|
bae7feea94 | ||
|
|
c5c5d12002 | ||
|
|
75d50eecbc | ||
|
|
c9e8b9b1c0 | ||
|
|
59e42d75f6 | ||
|
|
aa0d909505 | ||
|
|
7339d64322 | ||
|
|
6a4c344143 | ||
|
|
eba11b6717 | ||
|
|
05e7a4295a | ||
|
|
1d2c7d2afb | ||
|
|
60913b3c13 | ||
|
|
d3da22dfa9 | ||
|
|
7f836b85bf | ||
|
|
d8fc2bfc93 | ||
|
|
ccb4672da6 | ||
|
|
0bdd1fe61c | ||
|
|
da07fa063b | ||
|
|
1f3ac0e2a5 | ||
|
|
c498cfa634 | ||
|
|
3c28104ba4 | ||
|
|
cdca05ca32 | ||
|
|
fb83bbbf4a | ||
|
|
9f860c1a40 | ||
|
|
dcca2d4733 | ||
|
|
e53c51002b | ||
|
|
c58b19d411 | ||
|
|
f243c305b1 | ||
|
|
a9d6679c45 | ||
|
|
ede8662f79 | ||
|
|
7f9d543339 | ||
|
|
868776bd04 | ||
|
|
fc819abb2c | ||
|
|
e35f32705b | ||
|
|
f15a571c1d | ||
|
|
b5179739dc | ||
|
|
1e7a7cf02a | ||
|
|
4a63e0420d | ||
|
|
fea9794a01 | ||
|
|
3b53334f1a | ||
|
|
4e9b43d2d3 | ||
|
|
2ba7a24f19 | ||
|
|
61e550894f | ||
|
|
545a0eae2a | ||
|
|
c56edb67ac | ||
|
|
cbe6bf2635 | ||
|
|
8b84d6e43a | ||
|
|
ad3d06f1aa | ||
|
|
4a8fb2ca53 | ||
|
|
912523aba9 | ||
|
|
71cf2f4657 | ||
|
|
bbdd4982a0 | ||
|
|
1ea51136ce | ||
|
|
2fb8b0e92a | ||
|
|
c3ebfbbcd0 |
No files matched your search
+2
-2
@@ -3,7 +3,7 @@
|
||||
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
|
||||
patreon: # Replace with a single Patreon username
|
||||
open_collective: # Replace with a single Open Collective username
|
||||
ko_fi: cubicake
|
||||
ko_fi: #cubicake
|
||||
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
|
||||
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
|
||||
liberapay: # Replace with a single Liberapay username
|
||||
@@ -12,4 +12,4 @@ lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cl
|
||||
polar: # Replace with a single Polar username
|
||||
buy_me_a_coffee: # Replace with a single Buy Me a Coffee username
|
||||
thanks_dev: # Replace with a single thanks.dev username
|
||||
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
|
||||
custom: ['https://cubi.games/donate/variable']# Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
|
||||
+5
-3
@@ -3,6 +3,7 @@
|
||||
|
||||
README.md
|
||||
*.md
|
||||
*.toml
|
||||
|
||||
*.iml
|
||||
*.ipr
|
||||
@@ -105,6 +106,7 @@ $RECYCLE.BIN/
|
||||
*.lnk
|
||||
|
||||
.gradle
|
||||
.gradle-user/
|
||||
build/
|
||||
|
||||
# Ignore Gradle GUI config
|
||||
@@ -116,9 +118,9 @@ gradle-app.setting
|
||||
**/build/
|
||||
|
||||
# Common working directory
|
||||
run/
|
||||
runs/
|
||||
run-1-21-11/
|
||||
run*/
|
||||
|
||||
# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
|
||||
!gradle-wrapper.jar
|
||||
# Libraries are supposed to be committed
|
||||
!libraries/*/*
|
||||
@@ -1,3 +1,10 @@
|
||||
[submodule "logging"]
|
||||
path = logging
|
||||
url = https://github.com/Cubicake/CubiLogging.git
|
||||
[submodule "leafpile"]
|
||||
path = leafpile
|
||||
url = https://github.com/Cubicake/ParallelepipedLeafPile.git
|
||||
branch = java-21-main
|
||||
[submodule "locatables"]
|
||||
path = locatables
|
||||
url = https://github.com/Cubicake/Locatables.git
|
||||
+15
-2
@@ -1,6 +1,19 @@
|
||||
## Contributions
|
||||
Contributions via pull requests are welcome. Please join our [discord](https://discord.cubi.games) or make an `issue` to discuss any contributions beforehand to make sure they will not conflict with or hinder existing plans.
|
||||
|
||||
A good place to start with contributions is to look for `issue`s flagged with the label `help wanted`.
|
||||
A good place to start with contributions is to look for `issue`s flagged with the label `Outside Help Welcome`. These have been deemed as uninvasive changes, typically not requiring a complete understanding of the project. You are welcome to send a PR resolving these issues without first discussing changes with a maintainer.
|
||||
|
||||
You must hold the rights to any code you contribute, and must agree to licence it under the same licence as the rest of the project in perpetuity, explicitly including any and all changes to the project's licence by project maintainers in the future. The project's licence can always be found at [LICENSE.md](LICENSE.md).
|
||||
You must hold the rights to any code you contribute, and must agree to licence it under the same licence as the rest of the project in perpetuity, explicitly including any and all changes to the project's licence by project maintainers in the future. The project's licence can always be found at [LICENSE](LICENSE).
|
||||
|
||||
### Attribution
|
||||
Code files may have a copyright notice at the head of the file as follows.
|
||||
```java
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP.
|
||||
* RaycastedAntiESP is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at https://www.gnu.org/licenses/agpl-3.0.html.
|
||||
* See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
```
|
||||
If you made a significant contribution to a file with such a header, you may add your name to the list of names in the copyright notice. Contributing project maintainers should be listed first. All other names should be listed in descending order of contribution to the file, adjudicated by `Cubicake` if necessary. If the list of contributors reaches six names, do not add any more names to the list. You may instead append the text `and other contributors`.
|
||||
@@ -1,30 +1,40 @@
|
||||
### Latest stable version: v1.6.5
|
||||
RaycastedAntiESP is a packet-based plugin for Paper, Folia, and its forks that hides entities (including players) and tile entities (blocks such as chests, banners, signs, etc) from players if they would not be visible to a legitimate player. It is **unbypassable** by design, as packets sent by the server are blocked from reaching the client unless the block/entity has been confirmed to be visible.
|
||||
This limits the usefulness of unfair advantages such as cheat clients, freecam, and x-ray, and completely blocks pie-ray.
|
||||
|
||||
The latest stable version can currently only be found on Modrinth https://modrinth.com/plugin/raycasted-anti-esp/ or by compiling from `v1.6.x`. The latest alpha version can be found on the [Discord](https://discord.gg/hGTRAK2hNM) or by compiling from `main`.
|
||||
### Supported Versions
|
||||
While the current "stable" plugin version is v1.6.5, it is strongly recommended that you use the [alpha-channel builds](https://modrinth.com/plugin/raycasted-anti-esp/versions?c=alpha) instead. Since v1.6.5, RaycastedAntiESP has been:
|
||||
- Renamed from RaycastedEntityOcclusions to RaycastedAntiESP
|
||||
- Been almost completely rewritten to be faster and more correct
|
||||
|
||||
This is a predominantly async plugin for PaperMC and its forks that hides/culls entities (and tile entities) from players if they do not have line-of-sight.
|
||||
|
||||
The supported versions are 1.21.x PaperMC and Pufferfish. Other server versions and software may work too. v2 alpha builds support 26.x.
|
||||
The supported minecraft versions are 1.21.4+. Only Paper and derivative software (including Folia/Canvas) is supported, not Spigot.
|
||||
|
||||
## Use cases:
|
||||
|
||||
- Prevent cheating (anti-esp hacks)
|
||||
- Block usage of pie-ray to locate underground bases
|
||||
- Prevent mods such as mini-maps or cheat clients from displaying the locations of hidden entities
|
||||
- This is the plugin's primary purpose.
|
||||
- Block usage of pie-ray to locate underground bases or farms.
|
||||
- Prevent mods such as mini-maps or cheat clients from displaying the locations of entities which would not be visible to vanilla players.
|
||||
- Increase client-side performance for low-end devices
|
||||
- Massive megabases containing hundreds of armour stands, item frames, banners etc can cause performance issues on low-end devices unable to process so many entities. REO will cull those entities for the client, reducing the number of entities to process.
|
||||
- Massive megabases containing hundreds of armour stands, item frames, banners etc can cause performance issues on low-end devices unable to process so many entities. Raycasted AntiESP will cull those entities for the client, reducing the number of entities to process.
|
||||
- Reduce network load by limiting packets
|
||||
- With `keep-client-entity-when-hidden` set to true, running RaycastedAntiESP will significantly reduce the number of entity packets sent to the client.
|
||||
- While entity packets are only a small portion of network bandwidth, this will still have a measurable impact and may be useful on extremely bandwidth-limited servers.
|
||||
- Unless you are extremely limited by bandwidth, this will probably be unnoticeable.
|
||||
- Hide nametags behind walls
|
||||
- Yes, this plugin is a bit overkill for doing that, yes you can do it anyways.
|
||||
- Yes, this plugin is overkill for doing that, yes you can do it anyways.
|
||||
|
||||
## Configuration
|
||||
RaycastedAntiESP has many configuration options. A full list with explanations can be found at https://raycastedantiesp.cubi.games/config/.
|
||||
|
||||
## Dependencies:
|
||||
- Packetevents (soft depend)
|
||||
- Only needed if you are using the cull-players option and wish for the players to remain in the tablist
|
||||
- Packetevents
|
||||
- Required for all features, as packets are intercepted and rewritten to make sure that clients never learn about anything they should not be able to see.
|
||||
|
||||
## Known issues:
|
||||
- Due to the nature of the plugin, there will be a short delay once an entity should be visible before it appears, causing it to appear like it "popped" into view. This issue is partially resolved by turning engine-mode to 2, and is worse for players with higher ping.
|
||||
- There will be a short delay once an entity should be visible before it appears, causing it to appear like it "popped" into view. Various config options exist to partially address this issue, though all such options necessarily weaken the plugin's ability to block cheaters.
|
||||
|
||||
## Versioning:
|
||||
Note that the following versioning information only applies to v2 and beyond.
|
||||
Note that the following versioning information only applies to v2 and beyond, and alpha versions of v2 start with a major version number of 0 rather than 2.
|
||||
|
||||
RaycastedAntiESP binaries are composed of four distinct modules: the core, Locatable-lib (used for platform-independent location objects), [CubiLogging](https://github.com/Cubicake/CubiLogging/tree/main), and a platform adapter.
|
||||
|
||||
@@ -32,5 +42,55 @@ Each of these has its own versioning system. Locatable-lib and the logging api b
|
||||
|
||||
In addition to the versions for each module, there is also an overall version for each platform binary, which is the version that is advertised in the description and file name, and is used for update checks. This version is a combination of the core and platform adapter versions, in the format `{core version}-PlatformName-{platform adapter version}`. This allows all platforms to share the same first three version numbers, while still allowing for differences in the platform adapter versions.
|
||||
|
||||
## Credits:
|
||||
|
||||
- Cubicake (Sole developer and maintainer of RaycastedAntiESP)
|
||||
|
||||
### Special mentions:
|
||||
|
||||
- Strokkur424 and other contributors to [StrokkCommands](https://github.com/Strokkur424/StrokkCommands), an LGPL-licensed open-source annotation-based brigadier command tree generator.
|
||||
- While StrokkCommands is not essential for the functioning of the project, it makes handling commands infinitely easier.
|
||||
- Retrooper, Booky10, and all other contributors to [PacketEvents](https://github.com/retrooper/packetevents), a GPL-licensed open-source library for handling minecraft packets.
|
||||
- PacketEvents is essential for the functioning of the plugin, as it allows for handling of packets across multiple platforms and Minecraft versions.
|
||||
- All contributors to Paper and its upstream projects Spigot and Bukkit, without which none of this would be possible.
|
||||
|
||||
### Note about in-game attributions and other (A)GPL requirements:
|
||||
The plugin includes the command `/raycastedantiespCredits`, which displays a list of all authors and contributors, the license and a link to the source code. It can be run by all players. This command is intended to satisfy the "preservation of specified reasonable legal notices or author attributions" requirement of the AGPLv3 license in an easily accessible way for all users of the plugin, including players on a multiplayer server. If you fork this repository and remove the command you must include some other easily accessible way for all users of your fork to view the same information, as required by the AGPLv3.
|
||||
|
||||
This command has been deliberately named a long and unwieldy name to avoid clashing with any commands your server may wish to add, and does not pose any risks to your server as there is no unfair advantage which can be gained due to knowledge of the plugin's existence on your server.
|
||||
|
||||
It is **illegal** to remove the credits without providing an alternative, equally prominent way for users to view the same information. If for some reason crediting people who have worked on a feature for your server for free is a problem for you, you can contact Cubicake on discord (@cubicake) or make an issue to discuss receiving a specially licensed version with all attributions, credits, and source code links removed.
|
||||
|
||||
Using external software such as a command-hiding plugin to hide the command is **still illegal**, so please do not try to circumvent the requirement to provide attributions, credits, and source code links to users of your server.
|
||||
|
||||
Requesting a custom license is also required if you wish to link (as defined by the AGPL) a closed source project to this project.
|
||||
|
||||
An example of a suitable alternative to the command would be a single book-gui or dialog which contains all attributions, licenses, disclaimers, and source code links for all programs used by the server as long as the gui is easily accessible to all users of the server. Another example would be an NPC placed somewhere at your server's spawn which provides the information, as long as the NPC is not hidden somewhere difficult to access.
|
||||
|
||||
## Contributions:
|
||||
Contributions via pull requests are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md) for details.
|
||||
|
||||
## Forking:
|
||||
|
||||
Please see the [AGPLv3 license](LICENSE)—especially section 5, section 7, and section 13—before forking this repository, as there are some specific legal requirements for forks.
|
||||
|
||||
In summary, translated into layman, plugin-specific terms, the most important requirements for forks are as follows:
|
||||
1. Forks must not remove any names currently present in the authors/contributors list in the plugin's description, as this falls under the "preservation of specified reasonable legal notices or author attributions".
|
||||
2. Forks must not claim to be the original software, as this falls under the "no misrepresentation of the origin of the material".
|
||||
3. Per section 5 subsection c, derivative works such as forks must remain licenced under AGPLv3, and must include a copy of the license with the work. To be clear, copying any non-trivial amount of code from this repository into your own repository, whether via making a fork, directly copying and pasting or other means, makes it a derivative work and obligates you to license your derivative work under the AGPL v3. You must then include a copy of the license and make the source code (not decompiled code) accessible to all users of your program, explicitly including players on a multiplayer server as well as the server owners.
|
||||
4. "Appropriate Legal Notices" such as the copyright notice, license notice, disclaimer, and link to the source code must be preserved. Currently this is implemented via the `/raycastedantiespCredits` command, and while you are not obligated to keep this specific implementation, if you remove the command you must provide an equally prominent way for all users of the plugin (including players on a multiplayer server) to easily view the same information.
|
||||
|
||||
`games.cubi.raycastedantiesp.paper.commands.Attribution` has been written with forks in mind, and a template has been left for forks to modify so that the AGPLv3 license can be obeyed with minimal effort.
|
||||
|
||||
## Copyright and Disclaimer:
|
||||
Copyright © 2025-2026 Cubicake
|
||||
|
||||
This project is licensed under the GNU Affero General Public License v3.0 only (AGPLv3). You may copy, modify, and redistribute this software only in compliance with the terms of that licence. A copy of the licence is provided in the [LICENSE](LICENSE) file.
|
||||
|
||||
If you modify and deploy this software for remote network interaction, including operating a public multiplayer server, you must make the complete corresponding source code of the modified version available to all users interacting with the software over the network, as required by section 13 of the AGPLv3.
|
||||
|
||||
Any modified versions must be clearly marked as modified and must not be misrepresented as the original project.
|
||||
|
||||
This software is provided “as is”, without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages, or other liability arising from, out of, or in connection with the software or the use of the software.
|
||||
|
||||
The AGPL is the sole license this program is governed by. All statements found in this copyright notice and disclaimer, the above forking guidelines, or anywhere else in this program should only be considered guidelines and interpretations of the AGPL unless they are direct extracts of the AGPL. If any statement conflicts with the AGPL, the AGPL takes legal precedence over any such statement. However, any such conflicting statements should be taken as good-faith non-binding requests by the authors.
|
||||
@@ -0,0 +1 @@
|
||||
extra["patchedConfigurateYaml"] = files("libraries/configurate-yaml/yaml-4.3.0-SNAPSHOT-cubi.jar")
|
||||
+31
-3
@@ -1,9 +1,20 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
import java.time.Instant
|
||||
import org.gradle.api.file.FileCollection
|
||||
|
||||
plugins {
|
||||
id("java-library")
|
||||
}
|
||||
|
||||
val patchedConfigurateYaml = rootProject.extra["patchedConfigurateYaml"] as FileCollection
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
maven { url = uri("https://repo.codemc.io/repository/maven-releases/") }
|
||||
@@ -12,13 +23,26 @@ repositories {
|
||||
|
||||
dependencies {
|
||||
compileOnly("org.spongepowered:configurate-core:4.2.0")
|
||||
compileOnly("org.spongepowered:configurate-yaml:4.2.0")
|
||||
compileOnly(patchedConfigurateYaml)
|
||||
compileOnly("it.unimi.dsi:fastutil:8.5.18")
|
||||
implementation(project(":locatable-lib"))
|
||||
|
||||
implementation(project(":locatables"))
|
||||
|
||||
compileOnly(project(":leafpile"))
|
||||
compileOnly(project(":logging"))
|
||||
|
||||
testImplementation(platform("org.junit:junit-bom:5.10.2"))
|
||||
testImplementation("org.junit.jupiter:junit-jupiter-api")
|
||||
testImplementation(project(":leafpile"))
|
||||
testImplementation(project(":logging"))
|
||||
testImplementation("org.spongepowered:configurate-core:4.2.0")
|
||||
testImplementation(patchedConfigurateYaml)
|
||||
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine")
|
||||
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
|
||||
testImplementation("it.unimi.dsi:fastutil:8.5.18")
|
||||
}
|
||||
|
||||
val coreVersion = "0.4.1-SNAPSHOT"
|
||||
val coreVersion = "0.7.2-SNAPSHOT"
|
||||
|
||||
val isRelease = gradle.startParameter.taskNames.any {
|
||||
it.contains("buildRelease")
|
||||
@@ -67,6 +91,10 @@ tasks {
|
||||
expand(gitProps)
|
||||
}
|
||||
}
|
||||
|
||||
test {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
}
|
||||
|
||||
java {
|
||||
|
||||
@@ -1,3 +1,11 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core;
|
||||
|
||||
import games.cubi.logs.PlatformLogger;
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core;
|
||||
|
||||
import java.util.function.IntSupplier;
|
||||
|
||||
/**
|
||||
* Implementations should increment (starting from 0) once a tick, and should call AsyncEngine's tick method each time the tick increments.
|
||||
*/
|
||||
public interface Ticker extends IntSupplier {
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.chunks;
|
||||
|
||||
import games.cubi.raycastedantiesp.core.chunks.blocks.BlockChunkDataBuilder;
|
||||
import games.cubi.raycastedantiesp.core.chunks.blocks.SingleBlockChunkData;
|
||||
|
||||
import java.util.function.IntUnaryOperator;
|
||||
|
||||
public interface BlockChunkData extends ChunkOcclusionView {
|
||||
/**
|
||||
* char is used to denote an unsigned 16-bit integer.
|
||||
*/
|
||||
char getBlockID(int x, int y, int z);
|
||||
|
||||
/**
|
||||
* char is used to denote an unsigned 16-bit integer.
|
||||
*/
|
||||
BlockChunkData setBlockID(int x, int y, int z, char blockID, BlockInfoResolver blockInfoResolver);
|
||||
|
||||
static BlockChunkData filled(char blockID, BlockInfoResolver blockInfoResolver) {
|
||||
return new SingleBlockChunkData(blockID, blockInfoResolver.isOccluding(blockID));
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds chunk data from a source palette. The index reader receives core-packed positions and returns an index into {@code sourcePalette}.
|
||||
* Unused source entries are discarded before choosing the smallest representation.
|
||||
*/
|
||||
static BlockChunkData copyOfPalette(char[] sourcePalette, IntUnaryOperator paletteIndexAtPacked, BlockInfoResolver blockInfoResolver) {
|
||||
return BlockChunkDataBuilder.copyOfPalette(sourcePalette, paletteIndexAtPacked, blockInfoResolver);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds chunk data from a block-state reader. The reader receives core-packed positions.
|
||||
*/
|
||||
static BlockChunkData copyOfStates(IntUnaryOperator blockStateAtPacked, BlockInfoResolver blockInfoResolver) {
|
||||
return BlockChunkDataBuilder.copyOfStates(blockStateAtPacked, blockInfoResolver);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.chunks;
|
||||
|
||||
import org.jetbrains.annotations.Contract;
|
||||
|
||||
public interface BlockInfoResolver {
|
||||
@Contract(pure = true)
|
||||
boolean isOccluding(int blockStateID);
|
||||
|
||||
/**
|
||||
* Anti-ESP managed tile entity state after config exemptions and force-includes.
|
||||
*/
|
||||
@Contract(pure = true)
|
||||
boolean isTileEntity(int blockStateID);
|
||||
|
||||
/**
|
||||
* Raw block entity capability before anti-ESP config overrides.
|
||||
*/
|
||||
@Contract(pure = true)
|
||||
boolean hasBlockEntityData(int blockStateID);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.chunks;
|
||||
|
||||
public final class ChunkData {
|
||||
public static final int CHUNK_SIZE = 16;
|
||||
public static final int LOCAL_MASK = CHUNK_SIZE - 1;
|
||||
public static final int BLOCK_COUNT = CHUNK_SIZE * CHUNK_SIZE * CHUNK_SIZE;
|
||||
public static final int WORD_COUNT = BLOCK_COUNT / Long.SIZE;
|
||||
|
||||
private ChunkData() {
|
||||
}
|
||||
|
||||
public static int packLocalChecked(int x, int y, int z) {
|
||||
checkLocalCoordinate(x, "x");
|
||||
checkLocalCoordinate(y, "y");
|
||||
checkLocalCoordinate(z, "z");
|
||||
return packUncheckedGuarded(x, y, z);
|
||||
}
|
||||
|
||||
/**
|
||||
* Packs the local coordinates into a single integer without checking bounds. Coordinates outside the range will be correctly packed.
|
||||
*/
|
||||
public static int packUncheckedGuarded(int x, int y, int z) {
|
||||
return (z & LOCAL_MASK) << 8 | (y & LOCAL_MASK) << 4 | (x & LOCAL_MASK);
|
||||
}
|
||||
|
||||
public static int unpackX(int packed) {
|
||||
checkPacked(packed);
|
||||
return packed & LOCAL_MASK;
|
||||
}
|
||||
|
||||
public static int unpackY(int packed) {
|
||||
checkPacked(packed);
|
||||
return packed >> 4 & LOCAL_MASK;
|
||||
}
|
||||
|
||||
public static int unpackZ(int packed) {
|
||||
checkPacked(packed);
|
||||
return packed >> 8 & LOCAL_MASK;
|
||||
}
|
||||
|
||||
public static void checkPacked(int packed) {
|
||||
if (packed < 0 || packed >= BLOCK_COUNT) {
|
||||
throw new IllegalArgumentException("packed local block index must be in [0, " + (BLOCK_COUNT - 1) + "], but was " + packed);
|
||||
}
|
||||
}
|
||||
|
||||
private static void checkLocalCoordinate(int coordinate, String name) {
|
||||
if (coordinate < 0 || coordinate >= CHUNK_SIZE) {
|
||||
throw new IllegalArgumentException(name + " local coordinate must be in [0, " + LOCAL_MASK + "], but was " + coordinate);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.chunks;
|
||||
|
||||
import org.jetbrains.annotations.Range;
|
||||
|
||||
import static games.cubi.raycastedantiesp.core.chunks.ChunkData.LOCAL_MASK;
|
||||
|
||||
public interface ChunkOcclusionView {
|
||||
/**
|
||||
* The parameters here are local coordinates within the chunk section, so they must be in the range [0, 15].
|
||||
*
|
||||
* @return true if the block at the given local coordinates is occluding, false otherwise.
|
||||
*/
|
||||
boolean isOccludingLocal(@Range(from = 0, to = 15) int x, @Range(from = 0, to = 15) int y, @Range(from = 0, to = 15) int z);
|
||||
|
||||
default boolean isOccludingGlobal(int x, int y, int z) {
|
||||
return isOccludingLocal(x & LOCAL_MASK, y & LOCAL_MASK, z & LOCAL_MASK);
|
||||
}
|
||||
|
||||
default boolean isSolid() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.chunks;
|
||||
|
||||
import org.jetbrains.annotations.Range;
|
||||
|
||||
import java.util.BitSet;
|
||||
|
||||
public sealed interface OccludingChunkData extends ChunkOcclusionView permits OccludingChunkData.Solid, OccludingChunkDataImpl {
|
||||
/**
|
||||
* The parameters here are local coordinates within the chunk, so they should be in the range [0, 15].
|
||||
* @return The object to be stored. Mutations may require upgrading the object to a more complex implementation, so the returned object may not be the same as the current one.
|
||||
*/
|
||||
OccludingChunkData setOccluding(@Range(from = 0, to = 15) int x, @Range(from = 0, to = 15) int y, @Range(from = 0, to = 15) int z, boolean occluding);
|
||||
|
||||
static OccludingChunkDataImpl empty() {
|
||||
return new OccludingChunkDataImpl();
|
||||
}
|
||||
|
||||
static OccludingChunkData filled() {
|
||||
return OccludingChunkDataImpl.solid();
|
||||
}
|
||||
|
||||
OccludingChunkData SOLID = new Solid();
|
||||
|
||||
static OccludingChunkData solid() {
|
||||
return SOLID;
|
||||
}
|
||||
|
||||
static OccludingChunkData copyOf(BitSet bitSet) {
|
||||
long[] words = bitSet.toLongArray();
|
||||
if (words.length != ChunkData.WORD_COUNT) {
|
||||
long[] resized = new long[ChunkData.WORD_COUNT];
|
||||
System.arraycopy(words, 0, resized, 0, Math.min(words.length, resized.length));
|
||||
words = resized;
|
||||
}
|
||||
return new OccludingChunkDataImpl(words);
|
||||
}
|
||||
|
||||
final class Solid implements OccludingChunkData {
|
||||
@Override
|
||||
public boolean isOccludingLocal(int x, int y, int z) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public OccludingChunkData setOccluding(int x, int y, int z, boolean occluding) {
|
||||
return filled().setOccluding(x, y, z, occluding);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSolid() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.chunks;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import static games.cubi.utils.VarHandler.LONG_ARRAY_HANDLE;
|
||||
|
||||
/**
|
||||
* A 4096-bit bitset, where 1 indicates occluding and 0 indicates not occluding.
|
||||
* Safe for single-writer, multiple-reader setups
|
||||
*/
|
||||
public final class OccludingChunkDataImpl implements OccludingChunkData {
|
||||
// Plain reads/writes would probably be fine as occluding state being stale for a few seconds causes no issues, and tearing is a non-issue as this is a bitset, so only a single bit value matters at a time.
|
||||
// However, plain reads can technically be cached indefinitely, so opaque reads are more correct.
|
||||
|
||||
private final long[] occlusionData;
|
||||
|
||||
public OccludingChunkDataImpl() {
|
||||
this.occlusionData = new long[ChunkData.WORD_COUNT];
|
||||
}
|
||||
|
||||
public OccludingChunkDataImpl(long[] occlusionData) {
|
||||
if (occlusionData.length != ChunkData.WORD_COUNT) {
|
||||
throw new IllegalArgumentException("occlusionData must contain " + ChunkData.WORD_COUNT + " longs");
|
||||
}
|
||||
this.occlusionData = Arrays.copyOf(occlusionData, occlusionData.length);
|
||||
}
|
||||
|
||||
static OccludingChunkDataImpl solid() {
|
||||
// Make every bit 1, which is the same as making every long -1
|
||||
long[] solidData = new long[ChunkData.WORD_COUNT];
|
||||
Arrays.fill(solidData, -1L);
|
||||
return new OccludingChunkDataImpl(solidData);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isOccludingLocal(int x, int y, int z) {
|
||||
int packed = ChunkData.packLocalChecked(x, y, z);
|
||||
// >>> 6 divides the packed block index by 64 to select the containing long.
|
||||
int wordIndex = packed >>> 6;
|
||||
// 1L << packed creates a mask with only the packed block's bit set.
|
||||
long mask = 1L << packed;
|
||||
long word = (long) LONG_ARRAY_HANDLE.getOpaque(occlusionData, wordIndex);
|
||||
// & keeps only the target bit; non-zero means that bit is set.
|
||||
return (word & mask) != 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public OccludingChunkData setOccluding(int x, int y, int z, boolean occluding) {
|
||||
int packed = ChunkData.packLocalChecked(x, y, z);
|
||||
// >>> 6 divides the packed block index by 64 to select the containing long. Avoids signed division; probably an unnecessary optimisation but why not
|
||||
int wordIndex = packed >>> 6;
|
||||
// 1L << packed creates a mask for only the packed block's bit.
|
||||
long mask = 1L << packed;
|
||||
long word = (long) LONG_ARRAY_HANDLE.getOpaque(occlusionData, wordIndex);
|
||||
// If occluding is true, OR the mask in to set the bit; otherwise AND with ~mask to clear it.
|
||||
// ~ flips all bits, so mask becomes all 1 except for the bit being set to 0. ANDing this means that anything in word which was already true stays true and already false stays false, except for the bit being set to false.
|
||||
long updated = occluding ? word | mask : word & ~mask;
|
||||
// Not an atomicity issue since writes are single-threaded
|
||||
LONG_ARRAY_HANDLE.setOpaque(occlusionData, wordIndex, updated);
|
||||
return this;
|
||||
}
|
||||
}
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.chunks.blocks;
|
||||
|
||||
import games.cubi.raycastedantiesp.core.chunks.BlockChunkData;
|
||||
import games.cubi.raycastedantiesp.core.chunks.BlockInfoResolver;
|
||||
import games.cubi.raycastedantiesp.core.chunks.ChunkData;
|
||||
import java.util.Arrays;
|
||||
|
||||
import static games.cubi.utils.VarHandler.CHAR_ARRAY_HANDLE;
|
||||
import static games.cubi.utils.VarHandler.LONG_ARRAY_HANDLE;
|
||||
|
||||
abstract class AbstractPalettedBlockChunkData implements BlockChunkData {
|
||||
// Each concrete palette store allocates its maximum palette size up front. Adding a block only fills another slot in this array.
|
||||
// When the palette is full, the chunk upgrades to the next implementation.
|
||||
protected final char[] palette;
|
||||
protected final long[] occlusionData;
|
||||
private int paletteSize; //netty reads only
|
||||
|
||||
protected AbstractPalettedBlockChunkData(char blockID, int paletteCapacity, BlockInfoResolver blockInfoResolver) {
|
||||
if (paletteCapacity < 1 || paletteCapacity > 256) {
|
||||
throw new IllegalArgumentException("paletteCapacity must be in [1, 256]");
|
||||
}
|
||||
this.palette = new char[paletteCapacity];
|
||||
this.occlusionData = new long[ChunkData.WORD_COUNT];
|
||||
setPaletteBlock(0, blockID);
|
||||
paletteSize = 1;
|
||||
if (blockInfoResolver.isOccluding(blockID)) {
|
||||
Arrays.fill(this.occlusionData, -1L);
|
||||
}
|
||||
}
|
||||
|
||||
protected AbstractPalettedBlockChunkData(char[] palette, int paletteSize, int paletteCapacity, long[] occlusionData) {
|
||||
if (paletteCapacity < 1 || paletteCapacity > 256) {
|
||||
throw new IllegalArgumentException("paletteCapacity must be in [1, 256]");
|
||||
}
|
||||
if (paletteSize < 1 || paletteSize > paletteCapacity || palette.length < paletteSize) {
|
||||
throw new IllegalArgumentException("paletteSize must be in [1, paletteCapacity]");
|
||||
}
|
||||
if (occlusionData.length != ChunkData.WORD_COUNT) {
|
||||
throw new IllegalArgumentException("occlusionData must contain " + ChunkData.WORD_COUNT + " longs");
|
||||
}
|
||||
this.palette = new char[paletteCapacity];
|
||||
for (int i = 0; i < paletteSize; i++) {
|
||||
setPaletteBlock(i, palette[i]);
|
||||
}
|
||||
this.occlusionData = Arrays.copyOf(occlusionData, occlusionData.length);
|
||||
this.paletteSize = paletteSize;
|
||||
}
|
||||
|
||||
protected AbstractPalettedBlockChunkData(AbstractPalettedBlockChunkData source, int paletteCapacity) {
|
||||
this(source.palette, source.paletteSize, paletteCapacity, source.occlusionData);
|
||||
}
|
||||
|
||||
@Override
|
||||
public final char getBlockID(int x, int y, int z) {
|
||||
return getBlockIDPackedUnchecked(ChunkData.packLocalChecked(x, y, z));
|
||||
}
|
||||
|
||||
protected final char getBlockIDPacked(int packed) {
|
||||
ChunkData.checkPacked(packed);
|
||||
return paletteBlock(getPaletteIndex(packed));
|
||||
}
|
||||
|
||||
private char getBlockIDPackedUnchecked(int packed) {
|
||||
return paletteBlock(getPaletteIndex(packed));
|
||||
}
|
||||
|
||||
@Override
|
||||
public final boolean isOccludingLocal(int x, int y, int z) {
|
||||
int packed = ChunkData.packLocalChecked(x, y, z);
|
||||
return isOccludingPacked(packed);
|
||||
}
|
||||
|
||||
@Override
|
||||
public final BlockChunkData setBlockID(int x, int y, int z, char blockID, BlockInfoResolver blockInfoResolver) {
|
||||
int packed = ChunkData.packLocalChecked(x, y, z);
|
||||
int paletteIndex = indexOf(blockID);
|
||||
if (paletteIndex >= 0) {
|
||||
setPaletteIndex(packed, paletteIndex);
|
||||
setOccludingPacked(packed, blockInfoResolver.isOccluding(blockID));
|
||||
return this;
|
||||
}
|
||||
|
||||
if (!canAddPaletteEntry()) {
|
||||
return upgrade().setBlockID(x, y, z, blockID, blockInfoResolver);
|
||||
}
|
||||
|
||||
paletteIndex = addPaletteEntry(blockID);
|
||||
setPaletteIndex(packed, paletteIndex);
|
||||
setOccludingPacked(packed, blockInfoResolver.isOccluding(blockID));
|
||||
return this;
|
||||
}
|
||||
|
||||
protected abstract int getPaletteIndex(int packed);
|
||||
|
||||
protected abstract void setPaletteIndex(int packed, int paletteIndex);
|
||||
|
||||
protected abstract BlockChunkData upgrade();
|
||||
|
||||
private int indexOf(char blockID) {
|
||||
int size = paletteSize;
|
||||
for (int i = 0; i < size; i++) {
|
||||
if (paletteBlock(i) == blockID) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private boolean canAddPaletteEntry() {
|
||||
return paletteSize < palette.length;
|
||||
}
|
||||
|
||||
private int addPaletteEntry(char blockID) {
|
||||
int size = paletteSize;
|
||||
setPaletteBlock(size, blockID);
|
||||
paletteSize = size + 1;
|
||||
return size;
|
||||
}
|
||||
|
||||
protected final boolean isOccludingPacked(int packed) {
|
||||
ChunkData.checkPacked(packed);
|
||||
int wordIndex = packed >>> 6;
|
||||
long mask = 1L << packed;
|
||||
long word = (long) LONG_ARRAY_HANDLE.getOpaque(occlusionData, wordIndex);
|
||||
return (word & mask) != 0;
|
||||
}
|
||||
|
||||
protected final void setOccludingPacked(int packed, boolean occluding) {
|
||||
ChunkData.checkPacked(packed);
|
||||
int wordIndex = packed >>> 6;
|
||||
long mask = 1L << packed;
|
||||
long word = (long) LONG_ARRAY_HANDLE.getOpaque(occlusionData, wordIndex);
|
||||
long updated = occluding ? word | mask : word & ~mask;
|
||||
LONG_ARRAY_HANDLE.setOpaque(occlusionData, wordIndex, updated);
|
||||
}
|
||||
|
||||
protected final char paletteBlock(int index) {
|
||||
return (char) CHAR_ARRAY_HANDLE.getAcquire(palette, index);
|
||||
}
|
||||
|
||||
protected final void setPaletteBlock(int index, char blockID) {
|
||||
CHAR_ARRAY_HANDLE.setRelease(palette, index, blockID);
|
||||
}
|
||||
}
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.chunks.blocks;
|
||||
|
||||
import games.cubi.raycastedantiesp.core.chunks.BlockChunkData;
|
||||
import games.cubi.raycastedantiesp.core.chunks.BlockInfoResolver;
|
||||
import games.cubi.raycastedantiesp.core.chunks.ChunkData;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.function.IntUnaryOperator;
|
||||
|
||||
public final class BlockChunkDataBuilder {
|
||||
private static final int BYTE_PALETTE_LIMIT = 256;
|
||||
|
||||
private BlockChunkDataBuilder() {
|
||||
}
|
||||
|
||||
public static BlockChunkData copyOfPalette(char[] sourcePalette, IntUnaryOperator sourceIndexAtPacked, BlockInfoResolver blockInfoResolver) {
|
||||
if (sourcePalette.length == 0 || sourcePalette.length > BYTE_PALETTE_LIMIT) {
|
||||
throw new IllegalArgumentException("sourcePalette must contain between 1 and " + BYTE_PALETTE_LIMIT + " entries");
|
||||
}
|
||||
|
||||
// First compact only the source entries actually referenced by the 4,096 blocks.
|
||||
int[] remap = new int[sourcePalette.length];
|
||||
Arrays.fill(remap, -1);
|
||||
char[] compactPalette = new char[sourcePalette.length];
|
||||
int compactSize = 0;
|
||||
for (int packed = 0; packed < ChunkData.BLOCK_COUNT; packed++) {
|
||||
int sourceIndex = checkedPaletteIndex(sourceIndexAtPacked.applyAsInt(packed), sourcePalette.length);
|
||||
if (remap[sourceIndex] == -1) {
|
||||
remap[sourceIndex] = compactSize;
|
||||
compactPalette[compactSize++] = sourcePalette[sourceIndex];
|
||||
}
|
||||
}
|
||||
|
||||
final int usedPaletteSize = compactSize;
|
||||
// Readers are intentionally invoked again below; rescanning avoids a 4,096-entry temporary index array.
|
||||
IntUnaryOperator compactIndexAtPacked = packed -> {
|
||||
int sourceIndex = checkedPaletteIndex(sourceIndexAtPacked.applyAsInt(packed), sourcePalette.length);
|
||||
return remap[sourceIndex];
|
||||
};
|
||||
char[] usedPalette = Arrays.copyOf(compactPalette, usedPaletteSize);
|
||||
if (usedPaletteSize == 1) {
|
||||
return new SingleBlockChunkData(usedPalette[0], blockInfoResolver.isOccluding(usedPalette[0]));
|
||||
}
|
||||
if (usedPaletteSize == 2) {
|
||||
long[] bitData = new long[ChunkData.WORD_COUNT];
|
||||
for (int packed = 0; packed < ChunkData.BLOCK_COUNT; packed++) {
|
||||
if (compactIndexAtPacked.applyAsInt(packed) == 1) {
|
||||
setPackedBit(bitData, packed);
|
||||
}
|
||||
}
|
||||
return new TwoBlockChunkData(usedPalette[1], usedPalette[0], blockInfoResolver.isOccluding(usedPalette[1]), blockInfoResolver.isOccluding(usedPalette[0]), bitData);
|
||||
}
|
||||
if (usedPaletteSize <= 4) {
|
||||
return new FourBlockChunkData(usedPalette, usedPaletteSize, compactIndexAtPacked, blockInfoResolver);
|
||||
}
|
||||
if (usedPaletteSize <= 16) {
|
||||
return new SixteenBlockChunkData(usedPalette, usedPaletteSize, compactIndexAtPacked, blockInfoResolver);
|
||||
}
|
||||
return new ByteArrayBlockChunkData(usedPalette, usedPaletteSize, compactIndexAtPacked, blockInfoResolver);
|
||||
}
|
||||
|
||||
public static BlockChunkData copyOfStates(IntUnaryOperator blockStateAtPacked, BlockInfoResolver blockInfoResolver) {
|
||||
char[] palette = new char[BYTE_PALETTE_LIMIT];
|
||||
int paletteSize = 0;
|
||||
boolean overflow = false;
|
||||
// Global palettes have no local index table. Discover whether a byte palette is possible without storing 4,096 indices.
|
||||
for (int packed = 0; packed < ChunkData.BLOCK_COUNT; packed++) {
|
||||
char blockID = checkedBlockID(blockStateAtPacked.applyAsInt(packed));
|
||||
if (!overflow && indexOf(palette, paletteSize, blockID) < 0) {
|
||||
if (paletteSize == BYTE_PALETTE_LIMIT) {
|
||||
overflow = true;
|
||||
} else {
|
||||
palette[paletteSize++] = blockID;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!overflow) {
|
||||
// Delegate to the compact palette path; the state reader is rescanned to keep temporary allocation bounded by palette size.
|
||||
final int size = paletteSize;
|
||||
char[] sourcePalette = Arrays.copyOf(palette, size);
|
||||
return copyOfPalette(sourcePalette, packed -> indexOf(sourcePalette, size, checkedBlockID(blockStateAtPacked.applyAsInt(packed))), blockInfoResolver);
|
||||
}
|
||||
|
||||
// More than 256 states require final direct storage, populated together with its occlusion mask.
|
||||
char[] blockData = new char[ChunkData.BLOCK_COUNT];
|
||||
long[] occlusionData = new long[ChunkData.WORD_COUNT];
|
||||
for (int packed = 0; packed < ChunkData.BLOCK_COUNT; packed++) {
|
||||
char blockID = checkedBlockID(blockStateAtPacked.applyAsInt(packed));
|
||||
blockData[packed] = blockID;
|
||||
if (blockInfoResolver.isOccluding(blockID)) {
|
||||
setPackedBit(occlusionData, packed);
|
||||
}
|
||||
}
|
||||
return new CharArrayBlockChunkData(blockData, occlusionData, true);
|
||||
}
|
||||
|
||||
private static int indexOf(char[] palette, int paletteSize, char blockID) {
|
||||
for (int index = 0; index < paletteSize; index++) {
|
||||
if (palette[index] == blockID) {
|
||||
return index;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private static int checkedPaletteIndex(int paletteIndex, int paletteSize) {
|
||||
if (paletteIndex < 0 || paletteIndex >= paletteSize) {
|
||||
throw new IllegalArgumentException("palette index must be in [0, " + (paletteSize - 1) + "], but was " + paletteIndex);
|
||||
}
|
||||
return paletteIndex;
|
||||
}
|
||||
|
||||
private static char checkedBlockID(int blockID) {
|
||||
if (blockID < 0 || blockID > Character.MAX_VALUE) {
|
||||
throw new IllegalArgumentException("blockID must fit in an unsigned 16-bit value, but was " + blockID);
|
||||
}
|
||||
return (char) blockID;
|
||||
}
|
||||
|
||||
private static void setPackedBit(long[] data, int packed) {
|
||||
// packed >>> 6 selects the 64-bit word; Java masks the long shift distance to packed & 63 for the bit.
|
||||
data[packed >>> 6] |= 1L << packed;
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.chunks.blocks;
|
||||
|
||||
import games.cubi.raycastedantiesp.core.chunks.BlockChunkData;
|
||||
import games.cubi.raycastedantiesp.core.chunks.BlockInfoResolver;
|
||||
import games.cubi.raycastedantiesp.core.chunks.ChunkData;
|
||||
import java.util.function.IntUnaryOperator;
|
||||
|
||||
import static games.cubi.utils.VarHandler.BYTE_ARRAY_HANDLE;
|
||||
|
||||
public class ByteArrayBlockChunkData extends AbstractPalettedBlockChunkData {
|
||||
private final byte[] blockData = new byte[ChunkData.BLOCK_COUNT];
|
||||
|
||||
public ByteArrayBlockChunkData(char blockID, BlockInfoResolver blockInfoResolver) {
|
||||
super(blockID, 256, blockInfoResolver);
|
||||
}
|
||||
|
||||
ByteArrayBlockChunkData(char[] palette, int paletteSize, IntUnaryOperator indexAtPacked, BlockInfoResolver blockInfoResolver) {
|
||||
super(palette, paletteSize, 256, new long[ChunkData.WORD_COUNT]);
|
||||
for (int packed = 0; packed < ChunkData.BLOCK_COUNT; packed++) {
|
||||
int paletteIndex = indexAtPacked.applyAsInt(packed);
|
||||
setPaletteIndex(packed, paletteIndex);
|
||||
setOccludingPacked(packed, blockInfoResolver.isOccluding(palette[paletteIndex]));
|
||||
}
|
||||
}
|
||||
|
||||
private ByteArrayBlockChunkData(SixteenBlockChunkData old) {
|
||||
super(old, 256);
|
||||
for (int packed = 0; packed < ChunkData.BLOCK_COUNT; packed++) {
|
||||
setPaletteIndex(packed, old.getPaletteIndex(packed));
|
||||
}
|
||||
}
|
||||
|
||||
static ByteArrayBlockChunkData upgradeFromSixteenBlock(SixteenBlockChunkData old) {
|
||||
return new ByteArrayBlockChunkData(old);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int getPaletteIndex(int packed) {
|
||||
// Each block gets one byte, so the packed block index directly selects the byte containing its palette index.
|
||||
// Byte.toUnsignedInt converts Java's signed byte back to the intended 0-255 palette index.
|
||||
return Byte.toUnsignedInt((byte) BYTE_ARRAY_HANDLE.getOpaque(blockData, packed));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void setPaletteIndex(int packed, int paletteIndex) {
|
||||
// Each block gets one byte, so the packed block index directly selects where to store the 0-255 palette index.
|
||||
BYTE_ARRAY_HANDLE.setOpaque(blockData, packed, (byte) paletteIndex);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected BlockChunkData upgrade() {
|
||||
return CharArrayBlockChunkData.upgradeFromByteArrayBlock(this);
|
||||
}
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.chunks.blocks;
|
||||
|
||||
import games.cubi.raycastedantiesp.core.chunks.BlockChunkData;
|
||||
import games.cubi.raycastedantiesp.core.chunks.BlockInfoResolver;
|
||||
import games.cubi.raycastedantiesp.core.chunks.ChunkData;
|
||||
import java.util.Arrays;
|
||||
|
||||
import static games.cubi.utils.VarHandler.CHAR_ARRAY_HANDLE;
|
||||
import static games.cubi.utils.VarHandler.LONG_ARRAY_HANDLE;
|
||||
|
||||
public class CharArrayBlockChunkData implements BlockChunkData {
|
||||
private final char[] blockData;
|
||||
private final long[] occlusionData;
|
||||
|
||||
public CharArrayBlockChunkData(char blockID, BlockInfoResolver blockInfoResolver) {
|
||||
this.blockData = new char[ChunkData.BLOCK_COUNT];
|
||||
Arrays.fill(this.blockData, blockID);
|
||||
this.occlusionData = new long[ChunkData.WORD_COUNT];
|
||||
if (blockInfoResolver.isOccluding(blockID)) {
|
||||
Arrays.fill(this.occlusionData, -1L);
|
||||
}
|
||||
}
|
||||
|
||||
CharArrayBlockChunkData(char[] blockData, long[] occlusionData) {
|
||||
this(blockData, occlusionData, false);
|
||||
}
|
||||
|
||||
CharArrayBlockChunkData(char[] blockData, long[] occlusionData, boolean takeOwnership) {
|
||||
if (blockData.length != ChunkData.BLOCK_COUNT) {
|
||||
throw new IllegalArgumentException("blockData must contain " + ChunkData.BLOCK_COUNT + " entries");
|
||||
}
|
||||
if (occlusionData.length != ChunkData.WORD_COUNT) {
|
||||
throw new IllegalArgumentException("occlusionData must contain " + ChunkData.WORD_COUNT + " longs");
|
||||
}
|
||||
this.blockData = takeOwnership ? blockData : Arrays.copyOf(blockData, blockData.length);
|
||||
this.occlusionData = takeOwnership ? occlusionData : Arrays.copyOf(occlusionData, occlusionData.length);
|
||||
}
|
||||
|
||||
static CharArrayBlockChunkData upgradeFromByteArrayBlock(ByteArrayBlockChunkData old) {
|
||||
char[] blockData = new char[ChunkData.BLOCK_COUNT];
|
||||
for (int packed = 0; packed < ChunkData.BLOCK_COUNT; packed++) {
|
||||
blockData[packed] = old.getBlockIDPacked(packed);
|
||||
}
|
||||
return new CharArrayBlockChunkData(blockData, old.occlusionData);
|
||||
}
|
||||
|
||||
@Override
|
||||
public char getBlockID(int x, int y, int z) {
|
||||
return (char) CHAR_ARRAY_HANDLE.getOpaque(blockData, ChunkData.packLocalChecked(x, y, z));
|
||||
}
|
||||
|
||||
@Override
|
||||
public BlockChunkData setBlockID(int x, int y, int z, char blockID, BlockInfoResolver blockInfoResolver) {
|
||||
int packed = ChunkData.packLocalChecked(x, y, z);
|
||||
CHAR_ARRAY_HANDLE.setOpaque(blockData, packed, blockID);
|
||||
setOccludingPacked(packed, blockInfoResolver.isOccluding(blockID));
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isOccludingLocal(int x, int y, int z) {
|
||||
int packed = ChunkData.packLocalChecked(x, y, z);
|
||||
// >>> 6 divides the packed block index by 64 to select the containing long.
|
||||
int wordIndex = packed >>> 6;
|
||||
// 1L << packed creates a mask with only the packed block's bit set.
|
||||
long mask = 1L << packed;
|
||||
long word = (long) LONG_ARRAY_HANDLE.getOpaque(occlusionData, wordIndex);
|
||||
// & keeps only the target bit; non-zero means that bit is set.
|
||||
return (word & mask) != 0;
|
||||
}
|
||||
|
||||
private void setOccludingPacked(int packed, boolean occluding) {
|
||||
// >>> 6 divides the packed block index by 64 to select the containing long.
|
||||
int wordIndex = packed >>> 6;
|
||||
// 1L << packed creates a mask for only the packed block's bit.
|
||||
long mask = 1L << packed;
|
||||
long word = (long) LONG_ARRAY_HANDLE.getOpaque(occlusionData, wordIndex);
|
||||
// If occluding is true, OR the mask in to set the bit; otherwise AND with ~mask to clear it.
|
||||
long updated = occluding ? word | mask : word & ~mask;
|
||||
LONG_ARRAY_HANDLE.setOpaque(occlusionData, wordIndex, updated);
|
||||
}
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.chunks.blocks;
|
||||
|
||||
import games.cubi.raycastedantiesp.core.chunks.BlockChunkData;
|
||||
import games.cubi.raycastedantiesp.core.chunks.BlockInfoResolver;
|
||||
import games.cubi.raycastedantiesp.core.chunks.ChunkData;
|
||||
import java.util.function.IntUnaryOperator;
|
||||
|
||||
import static games.cubi.utils.VarHandler.BYTE_ARRAY_HANDLE;
|
||||
|
||||
public class FourBlockChunkData extends AbstractPalettedBlockChunkData {
|
||||
private static final int ENTRIES_PER_BYTE = 4;
|
||||
private static final int BITS_PER_ENTRY = 2;
|
||||
private static final int PALETTE_MASK = 0b11;
|
||||
|
||||
private final byte[] blockData = new byte[ChunkData.BLOCK_COUNT / ENTRIES_PER_BYTE];
|
||||
|
||||
public FourBlockChunkData(char blockID, BlockInfoResolver blockInfoResolver) {
|
||||
super(blockID, 4, blockInfoResolver);
|
||||
}
|
||||
|
||||
FourBlockChunkData(char[] palette, int paletteSize, int[] indices, long[] occlusionData) {
|
||||
super(palette, paletteSize, 4, occlusionData);
|
||||
if (indices.length != ChunkData.BLOCK_COUNT) {
|
||||
throw new IllegalArgumentException("indices must contain " + ChunkData.BLOCK_COUNT + " entries");
|
||||
}
|
||||
for (int packed = 0; packed < ChunkData.BLOCK_COUNT; packed++) {
|
||||
setPaletteIndex(packed, indices[packed]);
|
||||
}
|
||||
}
|
||||
|
||||
FourBlockChunkData(char[] palette, int paletteSize, IntUnaryOperator indexAtPacked, BlockInfoResolver blockInfoResolver) {
|
||||
super(palette, paletteSize, 4, new long[ChunkData.WORD_COUNT]);
|
||||
for (int packed = 0; packed < ChunkData.BLOCK_COUNT; packed++) {
|
||||
int paletteIndex = indexAtPacked.applyAsInt(packed);
|
||||
setPaletteIndex(packed, paletteIndex);
|
||||
setOccludingPacked(packed, blockInfoResolver.isOccluding(palette[paletteIndex]));
|
||||
}
|
||||
}
|
||||
|
||||
static FourBlockChunkData upgradeFromTwoBlock(TwoBlockChunkData old) {
|
||||
int[] indices = new int[ChunkData.BLOCK_COUNT];
|
||||
for (int packed = 0; packed < ChunkData.BLOCK_COUNT; packed++) {
|
||||
indices[packed] = old.bitIsSet(packed) ? 1 : 0;
|
||||
}
|
||||
return new FourBlockChunkData(new char[]{old.falseBitBlock(), old.trueBitBlock()}, 2, indices, old.copyOcclusionData());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int getPaletteIndex(int packed) {
|
||||
// >>> 2 divides the packed block index by 4 to select the byte containing this block's 2-bit palette index.
|
||||
int byteIndex = packed >>> 2;
|
||||
// packed & 0b11 gets the block's position inside that byte, then * 2 converts it to a bit offset.
|
||||
int shift = (packed & 0b11) * BITS_PER_ENTRY;
|
||||
int packedByte = Byte.toUnsignedInt((byte) BYTE_ARRAY_HANDLE.getOpaque(blockData, byteIndex));
|
||||
// >>> moves the target 2-bit index to the bottom, and & keeps only those 2 bits.
|
||||
return (packedByte >>> shift) & PALETTE_MASK;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void setPaletteIndex(int packed, int paletteIndex) {
|
||||
// >>> 2 divides the packed block index by 4 to select the byte containing this block's 2-bit palette index.
|
||||
int byteIndex = packed >>> 2;
|
||||
// packed & 0b11 gets the block's position inside that byte, then * 2 converts it to a bit offset.
|
||||
int shift = (packed & 0b11) * BITS_PER_ENTRY;
|
||||
// PALETTE_MASK << shift creates 1s over the old 2-bit index; ~ flips that to 0s over only the target index.
|
||||
int clearMask = ~(PALETTE_MASK << shift);
|
||||
int packedByte = Byte.toUnsignedInt((byte) BYTE_ARRAY_HANDLE.getOpaque(blockData, byteIndex));
|
||||
// & clearMask clears the old index, then | writes the new 2-bit palette index into the cleared slot.
|
||||
int updated = (packedByte & clearMask) | ((paletteIndex & PALETTE_MASK) << shift);
|
||||
BYTE_ARRAY_HANDLE.setOpaque(blockData, byteIndex, (byte) updated);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected BlockChunkData upgrade() {
|
||||
return SixteenBlockChunkData.upgradeFromFourBlock(this);
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.chunks.blocks;
|
||||
|
||||
import games.cubi.raycastedantiesp.core.chunks.BlockChunkData;
|
||||
|
||||
import games.cubi.raycastedantiesp.core.chunks.BlockInfoResolver;
|
||||
import games.cubi.raycastedantiesp.core.chunks.ChunkData;
|
||||
|
||||
// If it is air, just use a null reference
|
||||
public class SingleBlockChunkData implements BlockChunkData {
|
||||
final char blockID;
|
||||
private final boolean occluding;
|
||||
|
||||
public SingleBlockChunkData(char blockID, boolean occluding) {
|
||||
this.blockID = blockID;
|
||||
this.occluding = occluding;
|
||||
}
|
||||
|
||||
@Override
|
||||
public char getBlockID(int x, int y, int z) {
|
||||
ChunkData.packLocalChecked(x, y, z);
|
||||
return blockID;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BlockChunkData setBlockID(int x, int y, int z, char newBlockID, BlockInfoResolver blockInfoResolver) {
|
||||
ChunkData.packLocalChecked(x, y, z);
|
||||
if (newBlockID == this.blockID) {
|
||||
return this; // Chunk data did not change, no need to resize
|
||||
}
|
||||
return TwoBlockChunkData.upgradeFromSingleBlock(this, newBlockID, x, y, z, blockInfoResolver);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isOccludingLocal(int x, int y, int z) {
|
||||
ChunkData.packLocalChecked(x, y, z);
|
||||
return occluding;
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.chunks.blocks;
|
||||
|
||||
import games.cubi.raycastedantiesp.core.chunks.BlockChunkData;
|
||||
import games.cubi.raycastedantiesp.core.chunks.BlockInfoResolver;
|
||||
import games.cubi.raycastedantiesp.core.chunks.ChunkData;
|
||||
import java.util.function.IntUnaryOperator;
|
||||
|
||||
import static games.cubi.utils.VarHandler.BYTE_ARRAY_HANDLE;
|
||||
|
||||
public class SixteenBlockChunkData extends AbstractPalettedBlockChunkData {
|
||||
private static final int ENTRIES_PER_BYTE = 2;
|
||||
private static final int BITS_PER_ENTRY = 4;
|
||||
private static final int PALETTE_MASK = 0b1111;
|
||||
|
||||
private final byte[] blockData = new byte[ChunkData.BLOCK_COUNT / ENTRIES_PER_BYTE];
|
||||
|
||||
public SixteenBlockChunkData(char blockID, BlockInfoResolver blockInfoResolver) {
|
||||
super(blockID, 16, blockInfoResolver);
|
||||
}
|
||||
|
||||
SixteenBlockChunkData(char[] palette, int paletteSize, IntUnaryOperator indexAtPacked, BlockInfoResolver blockInfoResolver) {
|
||||
super(palette, paletteSize, 16, new long[ChunkData.WORD_COUNT]);
|
||||
for (int packed = 0; packed < ChunkData.BLOCK_COUNT; packed++) {
|
||||
int paletteIndex = indexAtPacked.applyAsInt(packed);
|
||||
setPaletteIndex(packed, paletteIndex);
|
||||
setOccludingPacked(packed, blockInfoResolver.isOccluding(palette[paletteIndex]));
|
||||
}
|
||||
}
|
||||
|
||||
private SixteenBlockChunkData(FourBlockChunkData old) {
|
||||
super(old, 16);
|
||||
for (int packed = 0; packed < ChunkData.BLOCK_COUNT; packed++) {
|
||||
setPaletteIndex(packed, old.getPaletteIndex(packed));
|
||||
}
|
||||
}
|
||||
|
||||
static SixteenBlockChunkData upgradeFromFourBlock(FourBlockChunkData old) {
|
||||
return new SixteenBlockChunkData(old);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int getPaletteIndex(int packed) {
|
||||
// >>> 1 divides the packed block index by 2 to select the byte containing this block's 4-bit palette index.
|
||||
int byteIndex = packed >>> 1;
|
||||
// packed & 1 selects the low or high nibble, then * 4 converts it to a bit offset.
|
||||
int shift = (packed & 1) * BITS_PER_ENTRY;
|
||||
int packedByte = Byte.toUnsignedInt((byte) BYTE_ARRAY_HANDLE.getOpaque(blockData, byteIndex));
|
||||
// >>> moves the target nibble to the bottom, and & keeps only those 4 bits.
|
||||
return (packedByte >>> shift) & PALETTE_MASK;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void setPaletteIndex(int packed, int paletteIndex) {
|
||||
// >>> 1 divides the packed block index by 2 to select the byte containing this block's 4-bit palette index.
|
||||
int byteIndex = packed >>> 1;
|
||||
// packed & 1 selects the low or high nibble, then * 4 converts it to a bit offset.
|
||||
int shift = (packed & 1) * BITS_PER_ENTRY;
|
||||
// PALETTE_MASK << shift creates 1s over the old nibble; ~ flips that to 0s over only the target nibble.
|
||||
int clearMask = ~(PALETTE_MASK << shift);
|
||||
int packedByte = Byte.toUnsignedInt((byte) BYTE_ARRAY_HANDLE.getOpaque(blockData, byteIndex));
|
||||
// & clearMask clears the old nibble, then | writes the new 4-bit palette index into the cleared slot.
|
||||
int updated = (packedByte & clearMask) | ((paletteIndex & PALETTE_MASK) << shift);
|
||||
BYTE_ARRAY_HANDLE.setOpaque(blockData, byteIndex, (byte) updated);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected BlockChunkData upgrade() {
|
||||
return ByteArrayBlockChunkData.upgradeFromSixteenBlock(this);
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.chunks.blocks;
|
||||
|
||||
import games.cubi.raycastedantiesp.core.chunks.BlockChunkData;
|
||||
import games.cubi.raycastedantiesp.core.chunks.BlockInfoResolver;
|
||||
import games.cubi.raycastedantiesp.core.chunks.ChunkData;
|
||||
import java.util.Arrays;
|
||||
|
||||
import static games.cubi.raycastedantiesp.core.chunks.ChunkData.packLocalChecked;
|
||||
import static games.cubi.raycastedantiesp.core.chunks.ChunkData.packUncheckedGuarded;
|
||||
import static games.cubi.utils.VarHandler.LONG_ARRAY_HANDLE;
|
||||
|
||||
//functionally a bitset
|
||||
public class TwoBlockChunkData implements BlockChunkData {
|
||||
// Plain reads/writes would probably be fine as occluding state being stale for a few seconds causes no issues, and tearing is a non-issue as this is a bitset, so only a single bit value matters at a time.
|
||||
// However, plain reads can technically be cached indefinitely, so opaque reads are more correct.
|
||||
|
||||
private final char trueBitBlock;
|
||||
private final char falseBitBlock;
|
||||
private final boolean trueBitBlockIsOccluding;
|
||||
private final boolean falseBitBlockIsOccluding;
|
||||
private final long[] blockData;
|
||||
|
||||
TwoBlockChunkData(char trueBitBlock, char falseBitBlock, boolean trueBitBlockIsOccluding, boolean falseBitBlockIsOccluding, long[] blockData) {
|
||||
this.trueBitBlock = trueBitBlock;
|
||||
this.falseBitBlock = falseBitBlock;
|
||||
this.trueBitBlockIsOccluding = trueBitBlockIsOccluding;
|
||||
this.falseBitBlockIsOccluding = falseBitBlockIsOccluding;
|
||||
if (blockData.length != ChunkData.WORD_COUNT) {
|
||||
throw new IllegalArgumentException("blockData must have length " + ChunkData.WORD_COUNT + ", but has length " + blockData.length);
|
||||
}
|
||||
this.blockData = Arrays.copyOf(blockData, blockData.length);
|
||||
}
|
||||
|
||||
static TwoBlockChunkData upgradeFromSingleBlock(SingleBlockChunkData old, char newBlockID, int newX, int newY, int newZ, BlockInfoResolver blockInfoResolver) {
|
||||
long[] blockData = new long[ChunkData.WORD_COUNT];
|
||||
TwoBlockChunkData upgraded = new TwoBlockChunkData(newBlockID, old.blockID, blockInfoResolver.isOccluding(newBlockID), blockInfoResolver.isOccluding(old.blockID), blockData);
|
||||
upgraded.setBit(packLocalChecked(newX, newY, newZ), true);
|
||||
return upgraded;
|
||||
}
|
||||
|
||||
public static TwoBlockChunkData upgradeFromAir(char newBlockID, int newXGlobal, int newYGlobal, int newZGlobal, BlockInfoResolver blockInfoResolver) {
|
||||
long[] blockData = new long[ChunkData.WORD_COUNT];
|
||||
TwoBlockChunkData upgraded = new TwoBlockChunkData(newBlockID, (char) 0, blockInfoResolver.isOccluding(newBlockID), blockInfoResolver.isOccluding(0), blockData);
|
||||
upgraded.setBit(packUncheckedGuarded(newXGlobal, newYGlobal, newZGlobal), true);
|
||||
return upgraded;
|
||||
}
|
||||
|
||||
@Override
|
||||
public char getBlockID(int x, int y, int z) {
|
||||
return bitIsSet(packLocalChecked(x, y, z)) ? trueBitBlock : falseBitBlock;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isOccludingLocal(int x, int y, int z) {
|
||||
return bitIsSet(packLocalChecked(x, y, z)) ? trueBitBlockIsOccluding : falseBitBlockIsOccluding;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BlockChunkData setBlockID(int x, int y, int z, char blockID, BlockInfoResolver blockInfoResolver) {
|
||||
int packed = packLocalChecked(x, y, z);
|
||||
if (blockID == trueBitBlock) {
|
||||
setBit(packed, true);
|
||||
return this;
|
||||
}
|
||||
if (blockID == falseBitBlock) {
|
||||
setBit(packed, false);
|
||||
return this;
|
||||
}
|
||||
return FourBlockChunkData.upgradeFromTwoBlock(this).setBlockID(x, y, z, blockID, blockInfoResolver);
|
||||
}
|
||||
|
||||
char trueBitBlock() {
|
||||
return trueBitBlock;
|
||||
}
|
||||
|
||||
char falseBitBlock() {
|
||||
return falseBitBlock;
|
||||
}
|
||||
|
||||
long[] copyOcclusionData() {
|
||||
long[] copied = new long[ChunkData.WORD_COUNT];
|
||||
if (trueBitBlockIsOccluding == falseBitBlockIsOccluding) {
|
||||
if (trueBitBlockIsOccluding) {
|
||||
Arrays.fill(copied, -1L);
|
||||
}
|
||||
return copied;
|
||||
}
|
||||
|
||||
for (int wordIndex = 0; wordIndex < blockData.length; wordIndex++) {
|
||||
long word = (long) LONG_ARRAY_HANDLE.getOpaque(blockData, wordIndex);
|
||||
copied[wordIndex] = trueBitBlockIsOccluding ? word : ~word;
|
||||
}
|
||||
return copied;
|
||||
}
|
||||
|
||||
boolean bitIsSet(int packed) {
|
||||
// >>> 6 divides the packed block index by 64 to select the containing long.
|
||||
int wordIndex = packed >>> 6;
|
||||
// 1L << packed creates a mask with only the packed block's bit set.
|
||||
long mask = 1L << packed;
|
||||
long word = (long) LONG_ARRAY_HANDLE.getOpaque(blockData, wordIndex);
|
||||
// & keeps only the target bit; non-zero means that bit is set.
|
||||
return (word & mask) != 0;
|
||||
}
|
||||
|
||||
private void setBit(int packed, boolean value) {
|
||||
// >>> 6 divides the packed block index by 64 to select the containing long. Avoids signed division; probably an unnecessary optimisation but why not
|
||||
int wordIndex = packed >>> 6;
|
||||
// 1L << packed creates a mask for only the packed block's bit.
|
||||
long mask = 1L << packed;
|
||||
long word = (long) LONG_ARRAY_HANDLE.getOpaque(blockData, wordIndex);
|
||||
long updated = value ? word | mask : word & ~mask;
|
||||
LONG_ARRAY_HANDLE.setOpaque(blockData, wordIndex, updated);
|
||||
}
|
||||
}
|
||||
+18
-14
@@ -1,18 +1,22 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
|
||||
import org.spongepowered.configurate.objectmapping.meta.Comment;
|
||||
|
||||
public record BlockProcessorConfig(BlockProcessorMode mode, boolean trackAllBlocks) implements Config {
|
||||
public static BlockProcessorConfig load(ConfigurationNode root) {
|
||||
ConfigurationNode node = ConfigReader.node(root, "block-processor");
|
||||
String modeName = ConfigReader.string(ConfigReader.node(node, "mode"), "block-processor.mode");
|
||||
BlockProcessorMode mode = BlockProcessorMode.fromString(modeName);
|
||||
if (mode == null) {
|
||||
throw new ConfigLoadException("block-processor.mode has unsupported value '" + modeName + "'");
|
||||
}
|
||||
return new BlockProcessorConfig(
|
||||
mode,
|
||||
ConfigReader.bool(ConfigReader.node(node, "track-all-blocks"), "block-processor.track-all-blocks")
|
||||
);
|
||||
}
|
||||
@ConfigSerializable
|
||||
public record BlockProcessorConfig(
|
||||
@Comment("Block processor implementation used by the plugin.")
|
||||
BlockProcessorMode mode,
|
||||
@Comment("Track every block rather than only tile entities.")
|
||||
boolean trackAllBlocks
|
||||
) implements Config {
|
||||
public static final BlockProcessorConfig DEFAULT = new BlockProcessorConfig(BlockProcessorMode.PACKETEVENTS, false);
|
||||
}
|
||||
@@ -1,3 +1,11 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
@@ -1,3 +1,11 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import games.cubi.raycastedantiesp.core.config.raycast.ChunkSectionConfig;
|
||||
@@ -5,24 +13,28 @@ import games.cubi.raycastedantiesp.core.config.raycast.EntityConfig;
|
||||
import games.cubi.raycastedantiesp.core.config.raycast.PlayerConfig;
|
||||
import games.cubi.raycastedantiesp.core.config.raycast.SoundEffectsConfig;
|
||||
import games.cubi.raycastedantiesp.core.config.raycast.TileEntityConfig;
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
|
||||
import org.spongepowered.configurate.objectmapping.meta.Setting;
|
||||
|
||||
public record ChecksConfig(PlayerConfig playerConfig, EntityConfig entityConfig, TileEntityConfig tileEntityConfig, SoundEffectsConfig soundEffectsConfig, ChunkSectionConfig chunkSectionConfig) implements Config {
|
||||
public static ChecksConfig load(ConfigurationNode root) {
|
||||
ConfigurationNode checks = ConfigReader.node(root, "checks");
|
||||
return new ChecksConfig(
|
||||
PlayerConfig.load(ConfigReader.node(checks, "player"), "checks.player"),
|
||||
EntityConfig.load(ConfigReader.node(checks, "entity"), "checks.entity"),
|
||||
TileEntityConfig.load(ConfigReader.node(checks, "tile-entity"), "checks.tile-entity"),
|
||||
SoundEffectsConfig.load(ConfigReader.node(checks, "sound-effects"), "checks.sound-effects"),
|
||||
ChunkSectionConfig.load(ConfigReader.node(checks, "chunk-section"), "checks.chunk-section")
|
||||
);
|
||||
}
|
||||
@ConfigSerializable
|
||||
public record ChecksConfig(
|
||||
@Setting("player") PlayerConfig playerConfig,
|
||||
@Setting("entity") EntityConfig entityConfig,
|
||||
@Setting("tile-entity") TileEntityConfig tileEntityConfig,
|
||||
@Setting("sound-effects") SoundEffectsConfig soundEffectsConfig,
|
||||
@Setting("chunk-section") ChunkSectionConfig chunkSectionConfig
|
||||
) implements Config {
|
||||
public static final ChecksConfig DEFAULT = new ChecksConfig(
|
||||
PlayerConfig.DEFAULT,
|
||||
EntityConfig.DEFAULT,
|
||||
TileEntityConfig.DEFAULT,
|
||||
SoundEffectsConfig.DEFAULT,
|
||||
ChunkSectionConfig.DEFAULT
|
||||
);
|
||||
|
||||
public boolean hasRestartOnlyChanges(ChecksConfig startup) {
|
||||
public boolean hasEnabledStatusChanges(ChecksConfig startup) {
|
||||
return playerConfig.enabled() != startup.playerConfig.enabled()
|
||||
|| entityConfig.enabled() != startup.entityConfig.enabled()
|
||||
|| tileEntityConfig.enabled() != startup.tileEntityConfig.enabled()
|
||||
|| chunkSectionConfig.enabled() != startup.chunkSectionConfig.enabled();
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,11 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
public interface Config {
|
||||
|
||||
@@ -0,0 +1,327 @@
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import org.spongepowered.configurate.CommentedConfigurationNode;
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
import org.spongepowered.configurate.NodePath;
|
||||
import org.spongepowered.configurate.serialize.SerializationException;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* A mutable configuration under preparation, separate from the active runtime snapshot.
|
||||
* Used only during a load or edit; ConfigManager owns synchronization, persistence, and publication.
|
||||
*/
|
||||
final class ConfigCandidate {
|
||||
private final CommentedConfigurationNode node;
|
||||
private final CommentedConfigurationNode defaults;
|
||||
private final List<Repair> repairs = new ArrayList<>();
|
||||
private boolean dirty;
|
||||
|
||||
ConfigCandidate(CommentedConfigurationNode node, CommentedConfigurationNode defaults) {
|
||||
this.node = node;
|
||||
this.defaults = defaults;
|
||||
dirty |= ConfigMigration.migrate(node);
|
||||
dirty |= ConfigMapping.removeDuplicateHeader(node);
|
||||
mergeDefaults();
|
||||
}
|
||||
|
||||
CommentedConfigurationNode node() {
|
||||
return node;
|
||||
}
|
||||
|
||||
List<Repair> repairs() {
|
||||
return repairs;
|
||||
}
|
||||
|
||||
boolean isDirty() {
|
||||
return dirty;
|
||||
}
|
||||
|
||||
void markDirty() {
|
||||
dirty = true;
|
||||
}
|
||||
|
||||
boolean hasDefault(NodePath path) {
|
||||
return !defaults.node(path.array()).virtual();
|
||||
}
|
||||
|
||||
void mergeDefaults() {
|
||||
dirty |= mergeMissing(defaults, node);
|
||||
}
|
||||
|
||||
LoggingConfig parseLoggingConfig() {
|
||||
return deserializeWithRepairs(NodePath.path("logging"), LoggingConfig.class);
|
||||
}
|
||||
|
||||
RootConfig parseReadyConfig() {
|
||||
// Hiding sounds from hidden entities is currently unsupported; persist the false defaults.
|
||||
for (String section : List.of("player", "entity")) {
|
||||
repair(NodePath.path("checks", section, "hide-sounds-when-hidden"), "hiding sounds from hidden entities is currently unsupported");
|
||||
}
|
||||
int attemptsRemaining = Math.max(2, countLeaves(defaults) + 1);
|
||||
while (attemptsRemaining-- > 0) {
|
||||
RootConfig root = deserializeWithRepairs(NodePath.path(), RootConfig.class);
|
||||
if (!RootConfig.CURRENT_VERSION.equals(root.configVersion())) {
|
||||
throw ConfigMigration.unsupportedVersion(root.configVersion());
|
||||
}
|
||||
List<AbsoluteViolation> violations = validate(root);
|
||||
if (violations.isEmpty()) {
|
||||
canonicalizeEnums(root);
|
||||
return root;
|
||||
}
|
||||
|
||||
boolean repaired = false;
|
||||
for (AbsoluteViolation violation : violations) {
|
||||
repaired |= repair(violation.path, violation.message);
|
||||
}
|
||||
if (!repaired) {
|
||||
throw new ConfigLoadException("Configuration validation failed without a repairable default");
|
||||
}
|
||||
}
|
||||
throw new ConfigLoadException("Configuration could not be repaired after exhausting the available defaults");
|
||||
}
|
||||
|
||||
private void canonicalizeEnums(RootConfig root) {
|
||||
canonicalizeValue(NodePath.path("engine", "mode"), root.engineConfig().mode().getName());
|
||||
canonicalizeValue(NodePath.path("block-processor", "mode"), root.blockProcessorConfig().mode().getName());
|
||||
}
|
||||
|
||||
private void canonicalizeValue(NodePath path, String value) {
|
||||
ConfigurationNode target = node.node(path.array());
|
||||
if (!Objects.equals(target.raw(), value)) {
|
||||
target.raw(value);
|
||||
dirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
private <T> T deserializeWithRepairs(NodePath mappingPath, Class<T> type) {
|
||||
int attemptsRemaining = Math.max(1, countLeaves(defaults.node(mappingPath.array())) + 1);
|
||||
while (attemptsRemaining-- > 0) {
|
||||
try {
|
||||
T value = node.node(mappingPath.array()).get(type);
|
||||
if (value == null) {
|
||||
throw new ConfigLoadException("Configuration mapper returned null for " + pathToString(mappingPath));
|
||||
}
|
||||
return value;
|
||||
} catch (SerializationException exception) {
|
||||
boolean repaired = false;
|
||||
for (SerializationException failure : leafFailures(exception)) {
|
||||
NodePath failurePath = normalizePath(failure.path(), mappingPath);
|
||||
repaired |= repair(failurePath, failure.rawMessage());
|
||||
}
|
||||
if (!repaired) {
|
||||
throw new ConfigLoadException("Invalid configuration at " + pathToString(mappingPath), exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new ConfigLoadException("Configuration at " + pathToString(mappingPath) + " could not be repaired");
|
||||
}
|
||||
|
||||
private List<AbsoluteViolation> validate(RootConfig root) {
|
||||
List<AbsoluteViolation> violations = new ArrayList<>();
|
||||
if (!root.blockProcessorConfig().trackAllBlocks() && root.checksConfig().chunkSectionConfig().enabled()) {
|
||||
violations.add(new AbsoluteViolation(
|
||||
NodePath.path("checks", "chunk-section", "enabled"),
|
||||
"must be false when block-processor.track-all-blocks is false"
|
||||
));
|
||||
}
|
||||
return violations;
|
||||
}
|
||||
|
||||
boolean repair(NodePath failedPath, String reason) {
|
||||
NodePath repairPath = findRepairPath(failedPath);
|
||||
if (repairPath == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
ConfigurationNode target = node.node(repairPath.array());
|
||||
ConfigurationNode replacement = defaults.node(repairPath.array());
|
||||
if (Objects.equals(target.raw(), replacement.raw())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
String existingComment = target instanceof CommentedConfigurationNode commented ? commented.comment() : null;
|
||||
target.from(replacement);
|
||||
copyComments(replacement, target);
|
||||
if (existingComment != null && target instanceof CommentedConfigurationNode commented) {
|
||||
commented.comment(existingComment);
|
||||
}
|
||||
dirty = true;
|
||||
repairs.add(new Repair(repairPath, reason, replacement.raw()));
|
||||
return true;
|
||||
}
|
||||
|
||||
private NodePath findRepairPath(NodePath failedPath) {
|
||||
Object[] parts = failedPath.array();
|
||||
for (int index = 0; index < parts.length; index++) {
|
||||
if (parts[index] instanceof Number) {
|
||||
parts = Arrays.copyOf(parts, index);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
for (int length = parts.length; length >= 0; length--) {
|
||||
NodePath candidate = NodePath.path(Arrays.copyOf(parts, length));
|
||||
if (!defaults.node(candidate.array()).virtual()) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private List<SerializationException> leafFailures(SerializationException root) {
|
||||
List<SerializationException> failures = new ArrayList<>();
|
||||
ArrayDeque<SerializationException> pending = new ArrayDeque<>();
|
||||
pending.add(root);
|
||||
while (!pending.isEmpty()) {
|
||||
SerializationException current = pending.removeFirst();
|
||||
boolean hasNested = false;
|
||||
for (Throwable suppressed : current.getSuppressed()) {
|
||||
if (suppressed instanceof SerializationException nested) {
|
||||
pending.addLast(nested);
|
||||
hasNested = true;
|
||||
}
|
||||
}
|
||||
if (!hasNested) {
|
||||
failures.add(current);
|
||||
}
|
||||
}
|
||||
return failures;
|
||||
}
|
||||
|
||||
private NodePath normalizePath(NodePath failurePath, NodePath mappingPath) {
|
||||
if (failurePath == null || failurePath.size() == 0) {
|
||||
return mappingPath;
|
||||
}
|
||||
if (startsWith(failurePath, mappingPath)) {
|
||||
return failurePath;
|
||||
}
|
||||
return mappingPath.plus(failurePath);
|
||||
}
|
||||
|
||||
private boolean startsWith(NodePath path, NodePath prefix) {
|
||||
if (prefix.size() > path.size()) {
|
||||
return false;
|
||||
}
|
||||
for (int index = 0; index < prefix.size(); index++) {
|
||||
if (!Objects.equals(path.get(index), prefix.get(index))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean mergeMissing(ConfigurationNode defaults, ConfigurationNode target) {
|
||||
if (target.virtual() || target.raw() == null && target.childrenMap().isEmpty() && target.childrenList().isEmpty()) {
|
||||
target.from(defaults);
|
||||
copyComments(defaults, target);
|
||||
return true;
|
||||
}
|
||||
|
||||
boolean changed = mergeComment(defaults, target);
|
||||
if (!defaults.childrenMap().isEmpty()) {
|
||||
Object raw = target.raw();
|
||||
if (target.childrenMap().isEmpty() && !(raw instanceof Map<?, ?>)) {
|
||||
return repair(target.path(), "expected a mapping");
|
||||
}
|
||||
for (Map.Entry<Object, ? extends ConfigurationNode> entry : defaults.childrenMap().entrySet()) {
|
||||
changed |= mergeMissing(entry.getValue(), target.node(entry.getKey()));
|
||||
}
|
||||
} else if (!defaults.childrenList().isEmpty() && target.isList()) {
|
||||
// Entries can be reordered or removed, so default comments must follow values rather than indices.
|
||||
Map<String, ConfigurationNode> commentedDefaults = new LinkedHashMap<>();
|
||||
for (ConfigurationNode child : defaults.childrenList()) {
|
||||
if (child.rawScalar() instanceof String value && child instanceof CommentedConfigurationNode commented && commented.comment() != null) {
|
||||
commentedDefaults.put(value, child);
|
||||
}
|
||||
}
|
||||
for (ConfigurationNode child : target.childrenList()) {
|
||||
if (child.rawScalar() instanceof String value) {
|
||||
ConfigurationNode defaultChild = commentedDefaults.get(value);
|
||||
if (defaultChild != null) {
|
||||
changed |= mergeComment(defaultChild, child);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
private boolean mergeComment(ConfigurationNode defaults, ConfigurationNode target) {
|
||||
if (!(defaults instanceof CommentedConfigurationNode defaultCommented) || !(target instanceof CommentedConfigurationNode targetCommented)) {
|
||||
return false;
|
||||
}
|
||||
if (targetCommented.comment() == null && defaultCommented.comment() != null) {
|
||||
targetCommented.comment(defaultCommented.comment());
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void copyComments(ConfigurationNode source, ConfigurationNode target) {
|
||||
if (source instanceof CommentedConfigurationNode sourceCommented
|
||||
&& target instanceof CommentedConfigurationNode targetCommented
|
||||
&& sourceCommented.comment() != null) {
|
||||
targetCommented.commentIfAbsent(sourceCommented.comment());
|
||||
}
|
||||
for (Map.Entry<Object, ? extends ConfigurationNode> entry : source.childrenMap().entrySet()) {
|
||||
copyComments(entry.getValue(), target.node(entry.getKey()));
|
||||
}
|
||||
List<? extends ConfigurationNode> sourceChildren = source.childrenList();
|
||||
List<? extends ConfigurationNode> targetChildren = target.childrenList();
|
||||
for (int index = 0; index < Math.min(sourceChildren.size(), targetChildren.size()); index++) {
|
||||
copyComments(sourceChildren.get(index), targetChildren.get(index));
|
||||
}
|
||||
}
|
||||
|
||||
private int countLeaves(ConfigurationNode node) {
|
||||
if (node.childrenMap().isEmpty() && node.childrenList().isEmpty()) {
|
||||
return 1;
|
||||
}
|
||||
int count = 0;
|
||||
for (ConfigurationNode child : node.childrenMap().values()) {
|
||||
count += countLeaves(child);
|
||||
}
|
||||
for (ConfigurationNode child : node.childrenList()) {
|
||||
count += countLeaves(child);
|
||||
}
|
||||
return Math.max(1, count);
|
||||
}
|
||||
|
||||
private static String pathToString(NodePath path) {
|
||||
if (path.size() == 0) {
|
||||
return "<root>";
|
||||
}
|
||||
StringBuilder result = new StringBuilder();
|
||||
for (Object part : path) {
|
||||
if (part instanceof Number) {
|
||||
result.append('[').append(part).append(']');
|
||||
} else {
|
||||
if (!result.isEmpty()) {
|
||||
result.append('.');
|
||||
}
|
||||
result.append(part);
|
||||
}
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
record Repair(NodePath path, String reason, Object defaultValue) {
|
||||
Repair {
|
||||
path = path.copy();
|
||||
}
|
||||
|
||||
String pathString() {
|
||||
return pathToString(path);
|
||||
}
|
||||
}
|
||||
|
||||
private record AbsoluteViolation(NodePath path, String message) {
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,11 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
|
||||
public interface ConfigExtension<T extends Config> {
|
||||
Class<T> type();
|
||||
|
||||
T load(ConfigurationNode config, BlockProcessorConfig blockProcessorConfig);
|
||||
|
||||
default boolean requiresRestart(T startupConfig, T nextConfig) {
|
||||
return !startupConfig.equals(nextConfig);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import org.spongepowered.configurate.CommentedConfigurationNode;
|
||||
import org.spongepowered.configurate.loader.HeaderMode;
|
||||
import org.spongepowered.configurate.serialize.SerializationException;
|
||||
import org.spongepowered.configurate.yaml.NodeStyle;
|
||||
import org.spongepowered.configurate.yaml.YamlConfigurationLoader;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.AtomicMoveNotSupportedException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.Objects;
|
||||
|
||||
/** Owns YAML loading, default-node creation, and replacement of config.yml through a temporary file. */
|
||||
final class ConfigFile {
|
||||
private final Path dataFolder;
|
||||
private final Path configPath;
|
||||
private final YamlConfigurationLoader loader;
|
||||
|
||||
ConfigFile(Path dataFolder) {
|
||||
this.dataFolder = Objects.requireNonNull(dataFolder, "dataFolder");
|
||||
configPath = dataFolder.resolve("config.yml");
|
||||
loader = createLoader(configPath);
|
||||
}
|
||||
|
||||
private YamlConfigurationLoader createLoader(Path path) {
|
||||
return YamlConfigurationLoader.builder()
|
||||
.path(path)
|
||||
.nodeStyle(NodeStyle.BLOCK)
|
||||
.headerMode(HeaderMode.PRESERVE)
|
||||
.defaultOptions(ConfigMapping.options())
|
||||
.build();
|
||||
}
|
||||
|
||||
CommentedConfigurationNode createDefaultNode() {
|
||||
CommentedConfigurationNode defaults = loader.createNode();
|
||||
try {
|
||||
defaults.set(RootConfig.class, RootConfig.DEFAULT);
|
||||
} catch (SerializationException e) {
|
||||
throw new ConfigLoadException("Code-defined configuration defaults could not be serialized", e);
|
||||
}
|
||||
return defaults;
|
||||
}
|
||||
|
||||
CommentedConfigurationNode load() {
|
||||
try {
|
||||
Files.createDirectories(dataFolder);
|
||||
return Files.exists(configPath) ? loader.load() : loader.createNode();
|
||||
} catch (IOException e) {
|
||||
throw new ConfigLoadException("Failed to load config.yml", e);
|
||||
}
|
||||
}
|
||||
|
||||
void save(CommentedConfigurationNode node) {
|
||||
Path temporaryPath = null;
|
||||
try {
|
||||
temporaryPath = Files.createTempFile(dataFolder, "config-", ".yml.tmp");
|
||||
createLoader(temporaryPath).save(node);
|
||||
try {
|
||||
Files.move(temporaryPath, configPath, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
} catch (AtomicMoveNotSupportedException exception) {
|
||||
Files.move(temporaryPath, configPath, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
temporaryPath = null;
|
||||
} catch (IOException e) {
|
||||
throw new ConfigLoadException("Failed to save config.yml", e);
|
||||
} finally {
|
||||
if (temporaryPath != null) {
|
||||
try {
|
||||
Files.deleteIfExists(temporaryPath);
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,11 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
public class ConfigLoadException extends RuntimeException {
|
||||
|
||||
@@ -1,105 +1,150 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import games.cubi.logs.Logger;
|
||||
import games.cubi.raycastedantiesp.core.config.engine.EngineConfig;
|
||||
import games.cubi.raycastedantiesp.core.config.raycast.ChunkSectionConfig;
|
||||
import games.cubi.raycastedantiesp.core.config.raycast.EntityConfig;
|
||||
import games.cubi.raycastedantiesp.core.config.raycast.PlayerConfig;
|
||||
import games.cubi.raycastedantiesp.core.config.raycast.SoundEffectsConfig;
|
||||
import games.cubi.raycastedantiesp.core.config.raycast.TileEntityConfig;
|
||||
import games.cubi.utils.VarHandler;
|
||||
import org.spongepowered.configurate.CommentedConfigurationNode;
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
import org.spongepowered.configurate.yaml.NodeStyle;
|
||||
import org.spongepowered.configurate.ConfigurateException;
|
||||
import org.spongepowered.configurate.NodePath;
|
||||
import org.spongepowered.configurate.serialize.SerializationException;
|
||||
import org.spongepowered.configurate.yaml.YamlConfigurationLoader;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.file.Files;
|
||||
import java.lang.invoke.VarHandle;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Coordinates startup, runtime edits, and publication of configuration snapshots.
|
||||
* ConfigCandidate prepares values and repairs; ConfigFile handles persistence.
|
||||
*/
|
||||
public class ConfigManager {
|
||||
private static final String REQUIRED_CONFIG_VERSION = "2.0";
|
||||
private static ConfigManager instance;
|
||||
private static volatile ConfigManager instance;
|
||||
private static final VarHandle INSTANCE = VarHandler.$tatic(ConfigManager.class, "instance", ConfigManager.class);
|
||||
|
||||
private final Supplier<InputStream> resourceSupplier;
|
||||
private final Path dataFolder;
|
||||
private final Path configPath;
|
||||
private final YamlConfigurationLoader loader;
|
||||
private final List<ConfigExtension<? extends Config>> extensions;
|
||||
private final ConfigFile configFile;
|
||||
|
||||
private ConfigurationNode config;
|
||||
private volatile ActiveState activeState = new ActiveState(LoggingConfig.DEFAULT, null);
|
||||
private static final VarHandle ACTIVE_STATE = VarHandler.get(ConfigManager.class, "activeState", ActiveState.class);
|
||||
private RootConfig startupConfig;
|
||||
private volatile RootConfig activeConfig;
|
||||
private CommentedConfigurationNode configNode;
|
||||
|
||||
private ConfigManager(Supplier<InputStream> resourceSupplier, Path dataFolder, List<ConfigExtension<? extends Config>> extensions) {
|
||||
this.resourceSupplier = resourceSupplier;
|
||||
this.dataFolder = dataFolder;
|
||||
this.extensions = List.copyOf(extensions);
|
||||
this.configPath = dataFolder.resolve("config.yml");
|
||||
this.loader = YamlConfigurationLoader.builder()
|
||||
.path(configPath)
|
||||
.nodeStyle(NodeStyle.BLOCK)
|
||||
.build();
|
||||
load();
|
||||
ConfigManager(Path dataFolder) {
|
||||
configFile = new ConfigFile(dataFolder);
|
||||
}
|
||||
|
||||
public static ConfigManager initialiseConfigManager(Supplier<InputStream> resourceSupplier, Path dataFolder, List<ConfigExtension<? extends Config>> extensions) {
|
||||
if (instance == null) {
|
||||
instance = new ConfigManager(resourceSupplier, dataFolder, extensions);
|
||||
public static synchronized ConfigManager initialiseConfigManager(Path dataFolder) {
|
||||
ConfigManager current = (ConfigManager) INSTANCE.getAcquire();
|
||||
if (current == null) {
|
||||
ConfigManager manager = new ConfigManager(dataFolder);
|
||||
INSTANCE.setRelease(manager);
|
||||
try {
|
||||
manager.loadLoggingConfig();
|
||||
} catch (RuntimeException exception) {
|
||||
INSTANCE.setRelease(null);
|
||||
throw exception;
|
||||
}
|
||||
current = manager;
|
||||
}
|
||||
return instance;
|
||||
return current;
|
||||
}
|
||||
|
||||
public static ConfigManager get() {
|
||||
if (instance == null) {
|
||||
ConfigManager current = (ConfigManager) INSTANCE.getAcquire();
|
||||
if (current == null) {
|
||||
Logger.errorAndReturn(new RuntimeException("ConfigManager accessed before being initiated. Please report this."), 2, ConfigManager.class);
|
||||
}
|
||||
return instance;
|
||||
return current;
|
||||
}
|
||||
|
||||
public void load() {
|
||||
ensureConfigFileExists();
|
||||
ConfigurationNode loaded = loadConfigNode();
|
||||
ConfigurationNode defaults = loadBundledDefaults();
|
||||
if (defaults != null && mergeMissing(defaults, loaded)) {
|
||||
saveConfigNode(loaded);
|
||||
}
|
||||
RootConfig parsed = parse(loaded);
|
||||
validateReload(parsed);
|
||||
config = loaded;
|
||||
if (startupConfig == null) {
|
||||
startupConfig = parsed;
|
||||
}
|
||||
activeConfig = parsed;
|
||||
public static LoggingConfig getLoggingConfigOrDefault() {
|
||||
ConfigManager current = (ConfigManager) INSTANCE.getAcquire();
|
||||
return current == null ? LoggingConfig.DEFAULT : current.getLoggingConfig();
|
||||
}
|
||||
|
||||
public SetConfigResult setConfigValue(String path, String rawValue) {
|
||||
ConfigurationNode candidate = loadConfigNode();
|
||||
ConfigurationNode target = node(candidate, path);
|
||||
public synchronized void completeInitialLoad() {
|
||||
if (startupConfig != null) {
|
||||
throw new IllegalStateException("Configuration loading has already been completed");
|
||||
}
|
||||
|
||||
ConfigCandidate candidate = prepare();
|
||||
RootConfig ready = candidate.parseReadyConfig();
|
||||
saveIfChanged(candidate);
|
||||
|
||||
startupConfig = ready;
|
||||
configNode = candidate.node();
|
||||
ACTIVE_STATE.setRelease(this, new ActiveState(ready.loggingConfig(), ready));
|
||||
logRepairs(candidate.repairs());
|
||||
}
|
||||
|
||||
/**
|
||||
* Reloads the complete configuration. The active snapshot is replaced only after parsing and validation succeed.
|
||||
*/
|
||||
public synchronized void load() {
|
||||
requireReady();
|
||||
ConfigCandidate candidate = prepare();
|
||||
RootConfig ready = candidate.parseReadyConfig();
|
||||
saveIfChanged(candidate);
|
||||
configNode = candidate.node();
|
||||
logRepairs(candidate.repairs());
|
||||
validateReload(ready);
|
||||
ACTIVE_STATE.setRelease(this, new ActiveState(ready.loggingConfig(), ready));
|
||||
}
|
||||
|
||||
public synchronized SetConfigResult setConfigValue(String path, String rawValue) {
|
||||
requireReady();
|
||||
ConfigCandidate candidate = prepare();
|
||||
ConfigurationNode target = node(candidate.node(), path);
|
||||
if (target.virtual()) {
|
||||
return SetConfigResult.invalid("Unknown config path: " + path);
|
||||
}
|
||||
|
||||
ConfigReader.setRaw(target, ConfigReader.parseRawValue(rawValue));
|
||||
|
||||
try {
|
||||
Object parsedValue = parseRawValue(rawValue);
|
||||
target.set(parsedValue);
|
||||
candidate.markDirty();
|
||||
NodePath targetPath = NodePath.path((Object[]) path.split("\\."));
|
||||
if (parsedValue == null && candidate.hasDefault(targetPath)) {
|
||||
candidate.repair(targetPath, "value cannot be null");
|
||||
}
|
||||
} catch (ConfigurateException e) {
|
||||
return SetConfigResult.invalid("Invalid YAML value: " + rawValue);
|
||||
}
|
||||
return applyCandidate(candidate, false);
|
||||
}
|
||||
|
||||
public SetConfigResult addConfigListValue(String path, String rawValue) {
|
||||
public synchronized SetConfigResult addConfigListValue(String path, String rawValue) {
|
||||
requireReady();
|
||||
return mutateConfigListValue(path, rawValue, ListMutation.ADD);
|
||||
}
|
||||
|
||||
public SetConfigResult removeConfigListValue(String path, String rawValue) {
|
||||
public synchronized SetConfigResult removeConfigListValue(String path, String rawValue) {
|
||||
requireReady();
|
||||
return mutateConfigListValue(path, rawValue, ListMutation.REMOVE);
|
||||
}
|
||||
|
||||
private SetConfigResult mutateConfigListValue(String path, String rawValue, ListMutation mutation) {
|
||||
ConfigurationNode candidate = loadConfigNode();
|
||||
ConfigurationNode target = node(candidate, path);
|
||||
ConfigCandidate candidate = prepare();
|
||||
ConfigurationNode target = node(candidate.node(), path);
|
||||
if (target.virtual()) {
|
||||
return SetConfigResult.invalid("Unknown config path: " + path);
|
||||
}
|
||||
@@ -112,7 +157,13 @@ public class ConfigManager {
|
||||
return SetConfigResult.invalid(path + " is not a list path");
|
||||
}
|
||||
|
||||
Object parsedValue = ConfigReader.parseRawValue(rawValue);
|
||||
Object parsedValue;
|
||||
try {
|
||||
parsedValue = parseRawValue(rawValue);
|
||||
} catch (ConfigurateException e) {
|
||||
return SetConfigResult.invalid("Invalid YAML value: " + rawValue);
|
||||
}
|
||||
|
||||
boolean changed = switch (mutation) {
|
||||
case ADD -> {
|
||||
if (values.contains(parsedValue)) {
|
||||
@@ -123,96 +174,115 @@ public class ConfigManager {
|
||||
}
|
||||
case REMOVE -> values.remove(parsedValue);
|
||||
};
|
||||
|
||||
if (!changed) {
|
||||
return SetConfigResult.invalid("No change made for " + path);
|
||||
}
|
||||
|
||||
ConfigReader.setRaw(target, values);
|
||||
try {
|
||||
target.set(values);
|
||||
candidate.markDirty();
|
||||
} catch (SerializationException e) {
|
||||
return SetConfigResult.invalid("Failed to update " + path);
|
||||
}
|
||||
return applyCandidate(candidate, true);
|
||||
}
|
||||
|
||||
private SetConfigResult applyCandidate(ConfigurationNode candidate, boolean allowRestartRequired) {
|
||||
RootConfig parsed;
|
||||
private SetConfigResult applyCandidate(ConfigCandidate candidate, boolean allowRestartRequired) {
|
||||
candidate.mergeDefaults();
|
||||
RootConfig ready;
|
||||
try {
|
||||
parsed = parse(candidate);
|
||||
validateReload(parsed);
|
||||
ready = candidate.parseReadyConfig();
|
||||
validateReload(ready);
|
||||
} catch (RestartRequiredException e) {
|
||||
if (!allowRestartRequired) {
|
||||
return SetConfigResult.invalid(e.getMessage());
|
||||
}
|
||||
config = candidate;
|
||||
saveConfigNode(candidate);
|
||||
return SetConfigResult.restartRequired(e.getMessage());
|
||||
saveIfChanged(candidate);
|
||||
configNode = candidate.node();
|
||||
logRepairs(candidate.repairs());
|
||||
return SetConfigResult.restartRequired(e.getMessage(), candidate.repairs());
|
||||
} catch (ConfigLoadException e) {
|
||||
return SetConfigResult.invalid(e.getMessage());
|
||||
}
|
||||
|
||||
config = candidate;
|
||||
activeConfig = parsed;
|
||||
saveConfigNode(candidate);
|
||||
return SetConfigResult.ok();
|
||||
saveIfChanged(candidate);
|
||||
configNode = candidate.node();
|
||||
ACTIVE_STATE.setRelease(this, new ActiveState(ready.loggingConfig(), ready));
|
||||
logRepairs(candidate.repairs());
|
||||
return SetConfigResult.ok(candidate.repairs());
|
||||
}
|
||||
|
||||
public LoggingConfig getLoggingConfig() {
|
||||
return ((ActiveState) ACTIVE_STATE.getAcquire(this)).loggingConfig;
|
||||
}
|
||||
|
||||
public PlayerConfig getPlayerConfig() {
|
||||
return activeConfig.checksConfig().playerConfig();
|
||||
return requireReady().checksConfig().playerConfig();
|
||||
}
|
||||
|
||||
public EntityConfig getEntityConfig() {
|
||||
return activeConfig.checksConfig().entityConfig();
|
||||
return requireReady().checksConfig().entityConfig();
|
||||
}
|
||||
|
||||
public TileEntityConfig getTileEntityConfig() {
|
||||
return activeConfig.checksConfig().tileEntityConfig();
|
||||
return requireReady().checksConfig().tileEntityConfig();
|
||||
}
|
||||
|
||||
public SoundEffectsConfig getSoundEffectsConfig() {
|
||||
return requireReady().checksConfig().soundEffectsConfig();
|
||||
}
|
||||
|
||||
public ChunkSectionConfig getChunkSectionConfig() {
|
||||
return requireReady().checksConfig().chunkSectionConfig();
|
||||
}
|
||||
|
||||
public DebugConfig getDebugConfig() {
|
||||
RootConfig current = activeConfig;
|
||||
return current == null ? null : current.debugConfig();
|
||||
return requireReady().debugConfig();
|
||||
}
|
||||
|
||||
public UpdateConfig getUpdateConfig() {
|
||||
return requireReady().updateConfig();
|
||||
}
|
||||
|
||||
public EngineConfig getEngineConfig() {
|
||||
return activeConfig.engineConfig();
|
||||
return requireReady().engineConfig();
|
||||
}
|
||||
|
||||
public BlockProcessorConfig getBlockProcessorConfig() {
|
||||
return activeConfig.blockProcessorConfig();
|
||||
return requireReady().blockProcessorConfig();
|
||||
}
|
||||
|
||||
public <T extends Config> T getExtensionConfig(Class<T> type) {
|
||||
return activeConfig.extensionConfig(type);
|
||||
}
|
||||
|
||||
public ConfigurationNode getConfigFile() {
|
||||
return config;
|
||||
}
|
||||
|
||||
public Map<String, Object> getConfigValues() {
|
||||
public synchronized Map<String, Object> getConfigValues() {
|
||||
requireReady();
|
||||
Map<String, Object> values = new LinkedHashMap<>();
|
||||
collectConfigValues(config, "", values);
|
||||
return values;
|
||||
collectConfigValues(configNode, "", values);
|
||||
return Collections.unmodifiableMap(values);
|
||||
}
|
||||
|
||||
private RootConfig parse(ConfigurationNode loaded) {
|
||||
String version = ConfigReader.string(ConfigReader.node(loaded, "config-version"), "config-version");
|
||||
if (!REQUIRED_CONFIG_VERSION.equals(version)) {
|
||||
throw new ConfigLoadException("Unsupported config-version '" + version + "'. RaycastedAntiESP requires config-version '2.0'.");
|
||||
}
|
||||
void loadLoggingConfig() {
|
||||
ConfigCandidate candidate = prepare();
|
||||
LoggingConfig logging = candidate.parseLoggingConfig();
|
||||
saveIfChanged(candidate);
|
||||
configNode = candidate.node();
|
||||
ACTIVE_STATE.setRelease(this, new ActiveState(logging, null));
|
||||
logRepairs(candidate.repairs());
|
||||
}
|
||||
|
||||
ChecksConfig checksConfig = ChecksConfig.load(loaded);
|
||||
EngineConfig engineConfig = EngineConfig.load(loaded);
|
||||
BlockProcessorConfig blockProcessorConfig = BlockProcessorConfig.load(loaded);
|
||||
DebugConfig debugConfig = DebugConfig.load(loaded);
|
||||
Map<Class<? extends Config>, Config> extensionConfigs = new LinkedHashMap<>();
|
||||
for (ConfigExtension<? extends Config> extension : extensions) {
|
||||
extensionConfigs.put(extension.type(), extension.load(loaded, blockProcessorConfig));
|
||||
}
|
||||
private ConfigCandidate prepare() {
|
||||
return new ConfigCandidate(configFile.load(), configFile.createDefaultNode());
|
||||
}
|
||||
|
||||
if (!blockProcessorConfig.trackAllBlocks() && checksConfig.chunkSectionConfig().enabled()) {
|
||||
throw new ConfigLoadException("checks.chunk-section.enabled must be false when block-processor.track-all-blocks is false");
|
||||
private void saveIfChanged(ConfigCandidate candidate) {
|
||||
if (candidate.isDirty()) {
|
||||
configFile.save(candidate.node());
|
||||
}
|
||||
}
|
||||
|
||||
return new RootConfig(version, checksConfig, engineConfig, blockProcessorConfig, debugConfig, Map.copyOf(extensionConfigs));
|
||||
private Object parseRawValue(String rawValue) throws ConfigurateException {
|
||||
ConfigurationNode parsed = YamlConfigurationLoader.builder()
|
||||
.defaultOptions(ConfigMapping.options())
|
||||
.buildAndLoadString("value: " + rawValue);
|
||||
return parsed.node("value").raw();
|
||||
}
|
||||
|
||||
private void validateReload(RootConfig next) {
|
||||
@@ -220,25 +290,42 @@ public class ConfigManager {
|
||||
return;
|
||||
}
|
||||
if (next.engineConfig().mode() != startupConfig.engineConfig().mode()) {
|
||||
throw new RestartRequiredException("engine.mode cannot be changed without a restart");
|
||||
throw new RestartRequiredException("engine.mode cannot be changed without a restart.");
|
||||
}
|
||||
if (!next.blockProcessorConfig().equals(startupConfig.blockProcessorConfig())) {
|
||||
throw new RestartRequiredException("block-processor cannot be changed without a restart");
|
||||
throw new RestartRequiredException("block-processor cannot be changed without a restart.");
|
||||
}
|
||||
if (next.checksConfig().hasRestartOnlyChanges(startupConfig.checksConfig())) {
|
||||
throw new RestartRequiredException("checks cannot be enabled or disabled without a restart");
|
||||
if (!next.checksConfig().entityConfig().excludedTypes().equals(startupConfig.checksConfig().entityConfig().excludedTypes())) {
|
||||
throw new RestartRequiredException("excluded entity types cannot be changed without a restart.");
|
||||
}
|
||||
for (ConfigExtension<? extends Config> extension : extensions) {
|
||||
validateExtensionReload(extension, next);
|
||||
if (!next.checksConfig().tileEntityConfig().excludedBlocks().equals(startupConfig.checksConfig().tileEntityConfig().excludedBlocks())) {
|
||||
throw new RestartRequiredException("excluded tile-entity blocks cannot be changed without a restart.");
|
||||
}
|
||||
if (next.checksConfig().hasEnabledStatusChanges(startupConfig.checksConfig())) {
|
||||
throw new RestartRequiredException("player and entity checks cannot be enabled or disabled without a restart.");
|
||||
}
|
||||
}
|
||||
|
||||
private <T extends Config> void validateExtensionReload(ConfigExtension<T> extension, RootConfig next) {
|
||||
T startupExtensionConfig = startupConfig.extensionConfig(extension.type());
|
||||
T nextExtensionConfig = next.extensionConfig(extension.type());
|
||||
if (extension.requiresRestart(startupExtensionConfig, nextExtensionConfig)) {
|
||||
throw new RestartRequiredException("block-processor." + extension.type().getSimpleName() + " cannot be changed without a restart");
|
||||
private RootConfig requireReady() {
|
||||
RootConfig ready = ((ActiveState) ACTIVE_STATE.getAcquire(this)).readyConfig;
|
||||
if (ready == null) {
|
||||
throw new IllegalStateException("Configuration is not available until completeInitialLoad has finished");
|
||||
}
|
||||
return ready;
|
||||
}
|
||||
|
||||
private void logRepairs(List<ConfigCandidate.Repair> repairs) {
|
||||
for (ConfigCandidate.Repair repair : repairs) {
|
||||
String reason = repair.reason() == null || repair.reason().isBlank() ? "invalid value" : repair.reason();
|
||||
String message = "Invalid config value at " + repair.pathString() + ": " + reason
|
||||
+ ". Replaced it with the default " + displayValue(repair.defaultValue()) + ".";
|
||||
Logger.warning(message, 4, ConfigManager.class);
|
||||
}
|
||||
}
|
||||
|
||||
private String displayValue(Object value) {
|
||||
String displayed = String.valueOf(value);
|
||||
return displayed.length() <= 160 ? displayed : displayed.substring(0, 157) + "...";
|
||||
}
|
||||
|
||||
private void collectConfigValues(ConfigurationNode node, String path, Map<String, Object> values) {
|
||||
@@ -248,86 +335,18 @@ public class ConfigManager {
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!node.childrenList().isEmpty()) {
|
||||
values.put(path, node.childrenList().stream().map(ConfigurationNode::raw).toList());
|
||||
return;
|
||||
}
|
||||
|
||||
for (Map.Entry<Object, ? extends ConfigurationNode> entry : node.childrenMap().entrySet()) {
|
||||
String key = String.valueOf(entry.getKey());
|
||||
String nextPath = path.isEmpty() ? key : path + "." + key;
|
||||
collectConfigValues(entry.getValue(), nextPath, values);
|
||||
}
|
||||
}
|
||||
|
||||
private void ensureConfigFileExists() {
|
||||
try {
|
||||
Files.createDirectories(dataFolder);
|
||||
if (!Files.exists(configPath)) {
|
||||
InputStream resource = resourceSupplier.get();
|
||||
if (resource != null) {
|
||||
try (resource) {
|
||||
Files.copy(resource, configPath);
|
||||
}
|
||||
} else {
|
||||
Files.createFile(configPath);
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new ConfigLoadException("Failed to create config.yml", e);
|
||||
}
|
||||
}
|
||||
|
||||
private ConfigurationNode loadConfigNode() {
|
||||
try {
|
||||
return loader.load();
|
||||
} catch (IOException e) {
|
||||
throw new ConfigLoadException("Failed to load config.yml", e);
|
||||
}
|
||||
}
|
||||
|
||||
private ConfigurationNode loadBundledDefaults() {
|
||||
InputStream resource = resourceSupplier.get();
|
||||
if (resource == null) {
|
||||
return null;
|
||||
}
|
||||
try (resource) {
|
||||
return YamlConfigurationLoader.builder()
|
||||
.source(() -> new BufferedReader(new InputStreamReader(resource)))
|
||||
.build()
|
||||
.load();
|
||||
} catch (IOException e) {
|
||||
throw new ConfigLoadException("Failed to load bundled config defaults", e);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean mergeMissing(ConfigurationNode defaults, ConfigurationNode target) {
|
||||
if (target.virtual()) {
|
||||
target.from(defaults);
|
||||
return true;
|
||||
}
|
||||
|
||||
boolean changed = false;
|
||||
if (!defaults.childrenMap().isEmpty()) {
|
||||
for (Map.Entry<Object, ? extends ConfigurationNode> entry : defaults.childrenMap().entrySet()) {
|
||||
changed |= mergeMissing(entry.getValue(), target.node(entry.getKey()));
|
||||
}
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
private void saveConfigNode(ConfigurationNode node) {
|
||||
try {
|
||||
loader.save(node);
|
||||
} catch (IOException e) {
|
||||
throw new ConfigLoadException("Failed to save config.yml", e);
|
||||
collectConfigValues(entry.getValue(), path.isEmpty() ? key : path + "." + key, values);
|
||||
}
|
||||
}
|
||||
|
||||
private ConfigurationNode node(ConfigurationNode root, String path) {
|
||||
String[] parts = path.split("\\.");
|
||||
return ConfigReader.node(root, parts);
|
||||
return root.node((Object[]) path.split("\\."));
|
||||
}
|
||||
|
||||
private enum ListMutation {
|
||||
@@ -335,23 +354,38 @@ public class ConfigManager {
|
||||
REMOVE
|
||||
}
|
||||
|
||||
private record ActiveState(LoggingConfig loggingConfig, RootConfig readyConfig) {
|
||||
}
|
||||
|
||||
private static final class RestartRequiredException extends ConfigLoadException {
|
||||
private RestartRequiredException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
public record SetConfigResult(boolean success, boolean restartRequired, String message) {
|
||||
public static SetConfigResult ok() {
|
||||
return new SetConfigResult(true, false, "Config value updated.");
|
||||
public record SetConfigResult(boolean success, boolean restartRequired, boolean repaired, String message) {
|
||||
private static SetConfigResult ok(List<ConfigCandidate.Repair> repairs) {
|
||||
if (repairs.isEmpty()) {
|
||||
return new SetConfigResult(true, false, false, "Config value updated.");
|
||||
}
|
||||
return new SetConfigResult(true, false, true, repairMessage(repairs));
|
||||
}
|
||||
|
||||
public static SetConfigResult restartRequired(String message) {
|
||||
return new SetConfigResult(true, true, message);
|
||||
private static SetConfigResult restartRequired(String message, List<ConfigCandidate.Repair> repairs) {
|
||||
String result = repairs.isEmpty() ? message : message + " " + repairMessage(repairs);
|
||||
return new SetConfigResult(true, true, !repairs.isEmpty(), result);
|
||||
}
|
||||
|
||||
public static SetConfigResult invalid(String message) {
|
||||
return new SetConfigResult(false, false, message);
|
||||
return new SetConfigResult(false, false, false, message);
|
||||
}
|
||||
|
||||
private static String repairMessage(List<ConfigCandidate.Repair> repairs) {
|
||||
Set<String> paths = new LinkedHashSet<>();
|
||||
for (ConfigCandidate.Repair repair : repairs) {
|
||||
paths.add(repair.pathString());
|
||||
}
|
||||
return "Invalid values at " + String.join(", ", paths) + " were replaced with defaults.";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import games.cubi.raycastedantiesp.core.config.engine.EngineMode;
|
||||
import games.cubi.raycastedantiesp.core.config.raycast.BlockSelector;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.spongepowered.configurate.CommentedConfigurationNode;
|
||||
import org.spongepowered.configurate.ConfigurationOptions;
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
import org.spongepowered.configurate.objectmapping.ObjectMapper;
|
||||
import org.spongepowered.configurate.serialize.SerializationException;
|
||||
import org.spongepowered.configurate.serialize.TypeSerializer;
|
||||
import org.spongepowered.configurate.serialize.TypeSerializerCollection;
|
||||
import org.spongepowered.configurate.util.NamingSchemes;
|
||||
|
||||
import java.lang.reflect.Type;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.LongFunction;
|
||||
|
||||
final class ConfigMapping {
|
||||
private static final String HEADER = "An explanation of this configuration file and what all the options do can be found at https://raycastedantiesp.cubi.games/config/";
|
||||
private static final String LEGACY_HEADER = "An explanation of this configuration file and what the options do can be found at https://raycastedantiesp.cubi.games/config/";
|
||||
private static final ConfigurationOptions OPTIONS = createOptions();
|
||||
|
||||
private ConfigMapping() {
|
||||
}
|
||||
|
||||
static ConfigurationOptions options() {
|
||||
return OPTIONS;
|
||||
}
|
||||
|
||||
static boolean removeDuplicateHeader(CommentedConfigurationNode node) {
|
||||
// Without a blank line, the legacy YAML header is loaded as a comment on config-version.
|
||||
CommentedConfigurationNode version = node.node("config-version");
|
||||
String comment = version.comment();
|
||||
if (comment == null) {
|
||||
return false;
|
||||
}
|
||||
var lines = comment.lines().toList();
|
||||
var remaining = lines.stream().filter(line -> {
|
||||
String normalized = line.strip().replace("https\\://", "https://");
|
||||
return !LEGACY_HEADER.equals(normalized) && !HEADER.equals(normalized);
|
||||
}).toList();
|
||||
if (remaining.size() == lines.size()) {
|
||||
return false;
|
||||
}
|
||||
String retainedComment = String.join("\n", remaining);
|
||||
version.comment(retainedComment.isBlank() ? null : retainedComment);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static ConfigurationOptions createOptions() {
|
||||
ObjectMapper.Factory mapper = ObjectMapper.factoryBuilder()
|
||||
.defaultNamingScheme(NamingSchemes.LOWER_CASE_DASHED)
|
||||
.addProcessor(ListEntryComments.class, (annotation, type) -> {
|
||||
Map<String, String> comments = new HashMap<>();
|
||||
for (ListEntryComments.Entry entry : annotation.value()) {
|
||||
comments.put(entry.value(), entry.comment());
|
||||
}
|
||||
return (value, node) -> {
|
||||
for (ConfigurationNode child : node.childrenList()) {
|
||||
if (child.rawScalar() instanceof String entry && child instanceof CommentedConfigurationNode commented) {
|
||||
String comment = comments.get(entry);
|
||||
if (comment != null) {
|
||||
commented.commentIfAbsent(comment);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
})
|
||||
.addConstraint(ConfigRange.class, (annotation, type) -> value -> {
|
||||
if (!(value instanceof Number number)) {
|
||||
throw new SerializationException(type, "Expected a numeric value");
|
||||
}
|
||||
long numericValue = number.longValue();
|
||||
if (numericValue < annotation.min() || numericValue > annotation.max()) {
|
||||
throw new SerializationException(type, "Value must be between " + annotation.min() + " and " + annotation.max());
|
||||
}
|
||||
})
|
||||
.build();
|
||||
|
||||
TypeSerializer<String> stringSerializer = strictScalarSerializer(
|
||||
String.class,
|
||||
"a string",
|
||||
String.class::cast,
|
||||
value -> value
|
||||
);
|
||||
TypeSerializer<Boolean> booleanSerializer = strictScalarSerializer(
|
||||
Boolean.class,
|
||||
"a boolean",
|
||||
Boolean.class::cast,
|
||||
value -> value
|
||||
);
|
||||
TypeSerializer<Byte> byteSerializer = strictIntegerSerializer("a byte", Byte.MIN_VALUE, Byte.MAX_VALUE, value -> (byte) value);
|
||||
TypeSerializer<Short> shortSerializer = strictIntegerSerializer("a short", Short.MIN_VALUE, Short.MAX_VALUE, value -> (short) value);
|
||||
TypeSerializer<Integer> integerSerializer = strictIntegerSerializer("an integer", Integer.MIN_VALUE, Integer.MAX_VALUE, value -> (int) value);
|
||||
|
||||
TypeSerializerCollection serializers = TypeSerializerCollection.defaults().childBuilder()
|
||||
.registerExact(String.class, stringSerializer)
|
||||
.registerExact(boolean.class, booleanSerializer)
|
||||
.registerExact(Boolean.class, booleanSerializer)
|
||||
.registerExact(byte.class, byteSerializer)
|
||||
.registerExact(Byte.class, byteSerializer)
|
||||
.registerExact(short.class, shortSerializer)
|
||||
.registerExact(Short.class, shortSerializer)
|
||||
.registerExact(int.class, integerSerializer)
|
||||
.registerExact(Integer.class, integerSerializer)
|
||||
.registerExact(BlockSelector.class, blockSelectorSerializer())
|
||||
.registerExact(EngineMode.class, enumSerializer(EngineMode::fromString, EngineMode::getName))
|
||||
.registerExact(BlockProcessorMode.class, enumSerializer(BlockProcessorMode::fromString, BlockProcessorMode::getName))
|
||||
.registerAnnotatedObjects(mapper)
|
||||
.build();
|
||||
|
||||
return ConfigurationOptions.defaults()
|
||||
.header(HEADER)
|
||||
.serializers(serializers)
|
||||
.shouldCopyDefaults(true);
|
||||
}
|
||||
|
||||
private static <T> TypeSerializer<T> strictScalarSerializer(
|
||||
Class<T> type,
|
||||
String expected,
|
||||
Function<Object, T> reader,
|
||||
Function<T, Object> writer
|
||||
) {
|
||||
return new TypeSerializer<>() {
|
||||
@Override
|
||||
public T deserialize(@NotNull Type expectedType, @NotNull ConfigurationNode node) throws SerializationException {
|
||||
Object raw = node.rawScalar();
|
||||
if (!type.isInstance(raw)) {
|
||||
throw new SerializationException(expectedType, "Expected " + expected);
|
||||
}
|
||||
return reader.apply(raw);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void serialize(@NotNull Type expectedType, T value, @NotNull ConfigurationNode node) {
|
||||
node.raw(value == null ? null : writer.apply(value));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static <T extends Number> TypeSerializer<T> strictIntegerSerializer(String expected, long minimum, long maximum, LongFunction<T> converter) {
|
||||
return new TypeSerializer<>() {
|
||||
@Override
|
||||
public T deserialize(@NotNull Type expectedType, @NotNull ConfigurationNode node) throws SerializationException {
|
||||
Object raw = node.rawScalar();
|
||||
if (!(raw instanceof Number number)) {
|
||||
throw new SerializationException(expectedType, "Expected " + expected);
|
||||
}
|
||||
long value = exactLong(expectedType, number);
|
||||
if (value < minimum || value > maximum) {
|
||||
throw new SerializationException(expectedType, "Value is outside the supported range for " + expected);
|
||||
}
|
||||
return converter.apply(value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void serialize(@NotNull Type expectedType, T value, @NotNull ConfigurationNode node) {
|
||||
node.raw(value == null ? null : value.intValue());
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static long exactLong(Type expectedType, Number number) throws SerializationException {
|
||||
try {
|
||||
return switch (number) {
|
||||
case Byte ignored -> number.longValue();
|
||||
case Short ignored -> number.longValue();
|
||||
case Integer ignored -> number.longValue();
|
||||
case Long ignored -> number.longValue();
|
||||
case BigInteger value -> value.longValueExact();
|
||||
case BigDecimal value -> value.longValueExact();
|
||||
default -> exactLongFromFloatingPoint(expectedType, number.doubleValue());
|
||||
};
|
||||
} catch (ArithmeticException exception) {
|
||||
throw new SerializationException(expectedType, "Expected an integer", exception);
|
||||
}
|
||||
}
|
||||
|
||||
private static long exactLongFromFloatingPoint(Type expectedType, double value) throws SerializationException {
|
||||
if (!Double.isFinite(value) || Math.rint(value) != value || value < Long.MIN_VALUE || value > Long.MAX_VALUE) {
|
||||
throw new SerializationException(expectedType, "Expected an integer");
|
||||
}
|
||||
return (long) value;
|
||||
}
|
||||
|
||||
private static <T> TypeSerializer<T> enumSerializer(Function<String, T> parser, Function<T, String> writer) {
|
||||
return new TypeSerializer<>() {
|
||||
@Override
|
||||
public T deserialize(@NotNull Type expectedType, @NotNull ConfigurationNode node) throws SerializationException {
|
||||
Object raw = node.rawScalar();
|
||||
if (!(raw instanceof String string)) {
|
||||
throw new SerializationException(expectedType, "Expected a string");
|
||||
}
|
||||
T parsed = parser.apply(string);
|
||||
if (parsed == null) {
|
||||
throw new SerializationException(expectedType, "Unsupported value '" + string + "'");
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void serialize(@NotNull Type expectedType, T value, @NotNull ConfigurationNode node) {
|
||||
node.raw(value == null ? null : writer.apply(value));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static TypeSerializer<BlockSelector> blockSelectorSerializer() {
|
||||
return new TypeSerializer<>() {
|
||||
@Override
|
||||
public BlockSelector deserialize(@NotNull Type expectedType, @NotNull ConfigurationNode node) throws SerializationException {
|
||||
Object raw = node.rawScalar();
|
||||
if (!(raw instanceof String value)) {
|
||||
throw new SerializationException(expectedType, "Expected a namespaced block selector");
|
||||
}
|
||||
try {
|
||||
return BlockSelector.parse(value);
|
||||
} catch (IllegalArgumentException exception) {
|
||||
throw new SerializationException(expectedType, exception.getMessage(), exception);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void serialize(@NotNull Type expectedType, BlockSelector value, @NotNull ConfigurationNode node) {
|
||||
node.raw(value == null ? null : value.toString());
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import org.spongepowered.configurate.CommentedConfigurationNode;
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
import org.spongepowered.configurate.ConfigurateException;
|
||||
import org.spongepowered.configurate.NodePath;
|
||||
import org.spongepowered.configurate.transformation.ConfigurationTransformation;
|
||||
import org.spongepowered.configurate.transformation.MoveStrategy;
|
||||
|
||||
/** Upgrades supported on-disk schemas before defaults are merged or objects are mapped. */
|
||||
final class ConfigMigration {
|
||||
private static final String PREVIOUS_CONFIG_VERSION = "2.0";
|
||||
private static final ConfigurationTransformation VERSION_2_1_TRANSFORMATION = createVersion21Transformation();
|
||||
|
||||
private ConfigMigration() {
|
||||
}
|
||||
|
||||
static boolean migrate(CommentedConfigurationNode node) {
|
||||
ConfigurationNode versionNode = node.node("config-version");
|
||||
Object rawVersion = versionNode.raw();
|
||||
if (rawVersion == null) {
|
||||
versionNode.raw(RootConfig.CURRENT_VERSION);
|
||||
return true;
|
||||
}
|
||||
if (!(rawVersion instanceof String version)) {
|
||||
throw new ConfigLoadException("config-version must be a string");
|
||||
}
|
||||
if (RootConfig.CURRENT_VERSION.equals(version)) {
|
||||
return false;
|
||||
}
|
||||
if (!PREVIOUS_CONFIG_VERSION.equals(version)) {
|
||||
throw unsupportedVersion(version);
|
||||
}
|
||||
|
||||
try {
|
||||
VERSION_2_1_TRANSFORMATION.apply(node);
|
||||
} catch (ConfigurateException e) {
|
||||
throw new ConfigLoadException("Failed to migrate config-version '" + PREVIOUS_CONFIG_VERSION + "' to '" + RootConfig.CURRENT_VERSION + "'", e);
|
||||
}
|
||||
versionNode.raw(RootConfig.CURRENT_VERSION);
|
||||
return true;
|
||||
}
|
||||
|
||||
static ConfigLoadException unsupportedVersion(String version) {
|
||||
return new ConfigLoadException(
|
||||
"Unsupported config-version '" + version + "'. RaycastedAntiESP requires config-version '"
|
||||
+ RootConfig.CURRENT_VERSION + "'."
|
||||
);
|
||||
}
|
||||
|
||||
private static ConfigurationTransformation createVersion21Transformation() {
|
||||
ConfigurationTransformation.Builder builder = ConfigurationTransformation.builder().moveStrategy(MoveStrategy.MERGE);
|
||||
addMove(builder, "info-level", "info", "level");
|
||||
addMove(builder, "info-exempted-classes", "info", "exempted-classes");
|
||||
addMove(builder, "warn-level", "warn", "level");
|
||||
addMove(builder, "warn-exempted-classes", "warn", "exempted-classes");
|
||||
addMove(builder, "error-level", "error", "level");
|
||||
addMove(builder, "error-exempted-classes", "error", "exempted-classes");
|
||||
builder.addAction(NodePath.path("block-processor", "packetevents"), (path, value) -> {
|
||||
value.raw(null);
|
||||
return null;
|
||||
});
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
private static void addMove(ConfigurationTransformation.Builder builder, String oldKey, String severity, String newKey) {
|
||||
builder.addAction(NodePath.path("debug", oldKey), (path, value) -> new Object[] {"logging", severity, newKey});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Documented
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.RECORD_COMPONENT})
|
||||
public @interface ConfigRange {
|
||||
long min();
|
||||
|
||||
long max();
|
||||
}
|
||||
@@ -1,112 +0,0 @@
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
import org.spongepowered.configurate.serialize.SerializationException;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public final class ConfigReader {
|
||||
private ConfigReader() {}
|
||||
|
||||
public static ConfigurationNode node(ConfigurationNode parent, String... path) {
|
||||
return parent.node((Object[]) path);
|
||||
}
|
||||
|
||||
public static String string(ConfigurationNode node, String path) {
|
||||
Object raw = node.raw();
|
||||
if (raw instanceof String value) {
|
||||
return value;
|
||||
}
|
||||
throw invalid(path, "string", raw);
|
||||
}
|
||||
|
||||
public static int integer(ConfigurationNode node, String path) {
|
||||
Object raw = node.raw();
|
||||
if (raw instanceof Number value && value.doubleValue() % 1 == 0) {
|
||||
return value.intValue();
|
||||
}
|
||||
throw invalid(path, "integer", raw);
|
||||
}
|
||||
|
||||
public static boolean bool(ConfigurationNode node, String path) {
|
||||
Object raw = node.raw();
|
||||
if (raw instanceof Boolean value) {
|
||||
return value;
|
||||
}
|
||||
throw invalid(path, "boolean", raw);
|
||||
}
|
||||
|
||||
public static List<String> stringList(ConfigurationNode node, String path) {
|
||||
if (node.virtual() || node.raw() == null) {
|
||||
return List.of();
|
||||
}
|
||||
if (node.childrenList().isEmpty()) {
|
||||
Object raw = node.raw();
|
||||
if (raw instanceof List<?> list && list.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
throw invalid(path, "list of strings", raw);
|
||||
}
|
||||
List<String> values = new ArrayList<>();
|
||||
for (ConfigurationNode child : node.childrenList()) {
|
||||
Object raw = child.raw();
|
||||
if (!(raw instanceof String value)) {
|
||||
throw invalid(path, "list of strings", raw);
|
||||
}
|
||||
values.add(value);
|
||||
}
|
||||
return List.copyOf(values);
|
||||
}
|
||||
|
||||
public static List<Integer> integerList(ConfigurationNode node, String path) {
|
||||
if (node.virtual() || node.raw() == null) {
|
||||
return List.of();
|
||||
}
|
||||
if (node.childrenList().isEmpty()) {
|
||||
Object raw = node.raw();
|
||||
if (raw instanceof List<?> list && list.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
throw invalid(path, "list of integers", raw);
|
||||
}
|
||||
List<Integer> values = new ArrayList<>();
|
||||
for (ConfigurationNode child : node.childrenList()) {
|
||||
Object raw = child.raw();
|
||||
if (!(raw instanceof Number value) || value.doubleValue() % 1 != 0) {
|
||||
throw invalid(path, "list of integers", raw);
|
||||
}
|
||||
int id = value.intValue();
|
||||
if (id < 0) {
|
||||
throw new ConfigLoadException(path + " cannot contain negative block state IDs: " + id);
|
||||
}
|
||||
values.add(id);
|
||||
}
|
||||
return List.copyOf(values);
|
||||
}
|
||||
|
||||
public static Object parseRawValue(String rawValue) {
|
||||
try {
|
||||
ConfigurationNode parsed = org.spongepowered.configurate.yaml.YamlConfigurationLoader.builder()
|
||||
.source(() -> new java.io.BufferedReader(new java.io.StringReader("value: " + rawValue)))
|
||||
.build()
|
||||
.load();
|
||||
return parsed.node("value").raw();
|
||||
} catch (java.io.IOException e) {
|
||||
throw new ConfigLoadException("Invalid YAML value: " + rawValue, e);
|
||||
}
|
||||
}
|
||||
|
||||
public static void setRaw(ConfigurationNode node, Object value) {
|
||||
try {
|
||||
node.set(value);
|
||||
} catch (SerializationException e) {
|
||||
throw new ConfigLoadException("Failed to set config value", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static ConfigLoadException invalid(String path, String expected, Object raw) {
|
||||
String actual = raw == null ? "null" : raw.getClass().getSimpleName();
|
||||
return new ConfigLoadException(path + " must be a " + expected + " but was " + actual);
|
||||
}
|
||||
}
|
||||
@@ -1,77 +1,30 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
|
||||
import org.spongepowered.configurate.objectmapping.meta.Comment;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record DebugConfig(byte infoLevel, List<String> infoExemptedClasses, byte warnLevel, List<String> warnExemptedClasses,
|
||||
byte errorLevel, List<String> errorExemptedClasses, boolean debugParticles, boolean timings) implements Config {
|
||||
|
||||
public static DebugConfig load(ConfigurationNode root) {
|
||||
ConfigurationNode node = ConfigReader.node(root, "debug");
|
||||
return new DebugConfig(
|
||||
level(ConfigReader.node(node, "info-level"), "debug.info-level"),
|
||||
ConfigReader.stringList(ConfigReader.node(node, "info-exempted-classes"), "debug.info-exempted-classes"),
|
||||
level(ConfigReader.node(node, "warn-level"), "debug.warn-level"),
|
||||
ConfigReader.stringList(ConfigReader.node(node, "warn-exempted-classes"), "debug.warn-exempted-classes"),
|
||||
level(ConfigReader.node(node, "error-level"), "debug.error-level"),
|
||||
ConfigReader.stringList(ConfigReader.node(node, "error-exempted-classes"), "debug.error-exempted-classes"),
|
||||
ConfigReader.bool(ConfigReader.node(node, "particles"), "debug.particles"),
|
||||
ConfigReader.bool(ConfigReader.node(node, "timings"), "debug.timings")
|
||||
);
|
||||
}
|
||||
|
||||
public byte getInfoLevel() {
|
||||
return infoLevel;
|
||||
}
|
||||
|
||||
public byte getWarnLevel() {
|
||||
return warnLevel;
|
||||
}
|
||||
|
||||
public byte getErrorLevel() {
|
||||
return errorLevel;
|
||||
}
|
||||
@ConfigSerializable
|
||||
public record DebugConfig(
|
||||
@Comment("Show raycast debug particles.")
|
||||
boolean particles,
|
||||
@Comment("Record and report engine timing information.")
|
||||
boolean timings
|
||||
) implements Config {
|
||||
public static final DebugConfig DEFAULT = new DebugConfig(false, false);
|
||||
|
||||
public boolean showDebugParticles() {
|
||||
return debugParticles;
|
||||
return particles;
|
||||
}
|
||||
|
||||
public boolean recordTimings() {
|
||||
return timings;
|
||||
}
|
||||
|
||||
public boolean isExempted(Severity severity, Class<?>... sources) {
|
||||
List<String> exempted = switch (severity) {
|
||||
case INFO -> infoExemptedClasses;
|
||||
case WARN -> warnExemptedClasses;
|
||||
case ERROR -> errorExemptedClasses;
|
||||
};
|
||||
if (sources == null || exempted.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
for (Class<?> source : sources) {
|
||||
if (source == null) {
|
||||
continue;
|
||||
}
|
||||
if (exempted.contains(source.getSimpleName()) || exempted.contains(source.getName())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static byte level(ConfigurationNode node, String path) {
|
||||
int level = ConfigReader.integer(node, path);
|
||||
if (level < 0 || level > 10) {
|
||||
throw new ConfigLoadException(path + " must be between 0 and 10");
|
||||
}
|
||||
return (byte) level;
|
||||
}
|
||||
|
||||
public enum Severity {
|
||||
INFO,
|
||||
WARN,
|
||||
ERROR
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/** Adds comments to collection entries matched by their serialized string values, without replacing existing comments. */
|
||||
@Documented
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.RECORD_COMPONENT})
|
||||
public @interface ListEntryComments {
|
||||
Entry[] value();
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target({})
|
||||
@interface Entry {
|
||||
String value();
|
||||
|
||||
String comment();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
|
||||
import org.spongepowered.configurate.objectmapping.meta.Comment;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@ConfigSerializable
|
||||
public record LogLevelConfig(
|
||||
@Comment("Messages above this level are suppressed. Set to 0 to suppress this severity.")
|
||||
@ConfigRange(min = 0, max = 10)
|
||||
byte level,
|
||||
@Comment("Simple or fully qualified class names whose messages should be suppressed.")
|
||||
List<String> exemptedClasses
|
||||
) implements Config {
|
||||
public static final LogLevelConfig DEFAULT = new LogLevelConfig((byte) 5, List.of());
|
||||
|
||||
public LogLevelConfig {
|
||||
exemptedClasses = List.copyOf(exemptedClasses);
|
||||
}
|
||||
|
||||
public boolean isExempted(Class<?>... sources) {
|
||||
if (sources == null || exemptedClasses.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
for (Class<?> source : sources) {
|
||||
if (source != null && (exemptedClasses.contains(source.getSimpleName()) || exemptedClasses.contains(source.getName()))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
|
||||
|
||||
@ConfigSerializable
|
||||
public record LoggingConfig(LogLevelConfig info, LogLevelConfig warn, LogLevelConfig error) implements Config {
|
||||
public static final LoggingConfig DEFAULT = new LoggingConfig(LogLevelConfig.DEFAULT, LogLevelConfig.DEFAULT, LogLevelConfig.DEFAULT);
|
||||
|
||||
public LogLevelConfig forSeverity(Severity severity) {
|
||||
return switch (severity) {
|
||||
case INFO -> info;
|
||||
case WARN -> warn;
|
||||
case ERROR -> error;
|
||||
};
|
||||
}
|
||||
|
||||
public enum Severity {
|
||||
INFO,
|
||||
WARN,
|
||||
ERROR
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,35 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import games.cubi.raycastedantiesp.core.config.engine.EngineConfig;
|
||||
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
|
||||
import org.spongepowered.configurate.objectmapping.meta.Setting;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public record RootConfig(String configVersion, ChecksConfig checksConfig, EngineConfig engineConfig, BlockProcessorConfig blockProcessorConfig, DebugConfig debugConfig, Map<Class<? extends Config>, Config> extensionConfigs) implements Config {
|
||||
public <T extends Config> T extensionConfig(Class<T> type) {
|
||||
Config config = extensionConfigs.get(type);
|
||||
return type.cast(config);
|
||||
}
|
||||
@ConfigSerializable
|
||||
public record RootConfig(
|
||||
String configVersion,
|
||||
@Setting("logging") LoggingConfig loggingConfig,
|
||||
@Setting("checks") ChecksConfig checksConfig,
|
||||
@Setting("engine") EngineConfig engineConfig,
|
||||
@Setting("block-processor") BlockProcessorConfig blockProcessorConfig,
|
||||
@Setting("debug") DebugConfig debugConfig,
|
||||
@Setting("updates") UpdateConfig updateConfig
|
||||
) implements Config {
|
||||
public static final String CURRENT_VERSION = "2.1";
|
||||
public static final RootConfig DEFAULT = new RootConfig(
|
||||
CURRENT_VERSION,
|
||||
LoggingConfig.DEFAULT,
|
||||
ChecksConfig.DEFAULT,
|
||||
EngineConfig.DEFAULT,
|
||||
BlockProcessorConfig.DEFAULT,
|
||||
DebugConfig.DEFAULT,
|
||||
UpdateConfig.DEFAULT
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
|
||||
import org.spongepowered.configurate.objectmapping.meta.Comment;
|
||||
|
||||
@ConfigSerializable
|
||||
public record UpdateConfig(
|
||||
boolean checkRelease,
|
||||
boolean checkBeta,
|
||||
boolean checkAlpha,
|
||||
@Comment("When true, players with permission are notified; otherwise only the console is notified.")
|
||||
boolean notifyInGame
|
||||
) implements Config {
|
||||
public static final UpdateConfig DEFAULT = new UpdateConfig(true, true, true, true);
|
||||
|
||||
public boolean anyChannelEnabled() {
|
||||
return checkRelease || checkBeta || checkAlpha;
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.config.engine;
|
||||
|
||||
import games.cubi.raycastedantiesp.core.config.Config;
|
||||
import games.cubi.raycastedantiesp.core.config.ConfigRange;
|
||||
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
|
||||
import org.spongepowered.configurate.objectmapping.meta.Comment;
|
||||
import org.spongepowered.configurate.objectmapping.meta.Setting;
|
||||
|
||||
@ConfigSerializable
|
||||
public record AsyncEngineConfig(
|
||||
@Setting("processing-threads")
|
||||
@Comment("Number of async processing threads. One is sufficient for hundreds of players.")
|
||||
@ConfigRange(min = 1, max = 64)
|
||||
int asyncProcessingThreads
|
||||
) implements Config {
|
||||
public static final AsyncEngineConfig DEFAULT = new AsyncEngineConfig(1);
|
||||
}
|
||||
+16
-13
@@ -1,20 +1,23 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.config.engine;
|
||||
|
||||
import games.cubi.raycastedantiesp.core.config.Config;
|
||||
import games.cubi.raycastedantiesp.core.config.ConfigLoadException;
|
||||
import games.cubi.raycastedantiesp.core.config.ConfigReader;
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
|
||||
import org.spongepowered.configurate.objectmapping.meta.Setting;
|
||||
|
||||
public record EngineConfig(EngineMode mode, SimpleEngineConfig simpleConfig) implements Config {
|
||||
public static EngineConfig load(ConfigurationNode root) {
|
||||
ConfigurationNode node = ConfigReader.node(root, "engine");
|
||||
String modeName = ConfigReader.string(ConfigReader.node(node, "mode"), "engine.mode");
|
||||
EngineMode mode = EngineMode.fromString(modeName);
|
||||
if (mode == null) {
|
||||
throw new ConfigLoadException("engine.mode has unsupported value '" + modeName + "'");
|
||||
}
|
||||
return new EngineConfig(mode, SimpleEngineConfig.load(ConfigReader.node(node, "simple")));
|
||||
}
|
||||
@ConfigSerializable
|
||||
public record EngineConfig(
|
||||
EngineMode mode,
|
||||
@Setting("async") AsyncEngineConfig asyncConfig
|
||||
) implements Config {
|
||||
public static final EngineConfig DEFAULT = new EngineConfig(EngineMode.ASYNC, AsyncEngineConfig.DEFAULT);
|
||||
|
||||
public EngineMode getMode() {
|
||||
return mode;
|
||||
|
||||
@@ -1,16 +1,32 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.config.engine;
|
||||
|
||||
import games.cubi.raycastedantiesp.core.config.ConfigEnum;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public enum EngineMode implements ConfigEnum {
|
||||
SIMPLE("simple"),
|
||||
ASYNC("async", "simple"),
|
||||
NETTY("netty");
|
||||
|
||||
private final String configName;
|
||||
private final @Nullable String aliasName;
|
||||
|
||||
EngineMode(String configName) {
|
||||
this.configName = configName;
|
||||
aliasName = null;
|
||||
}
|
||||
|
||||
EngineMode(String configName, @NotNull String aliasName) {
|
||||
this.configName = configName;
|
||||
this.aliasName = aliasName;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
@@ -19,7 +35,7 @@ public enum EngineMode implements ConfigEnum {
|
||||
|
||||
public static @Nullable EngineMode fromString(String name) {
|
||||
for (EngineMode mode : values()) {
|
||||
if (mode.configName.equalsIgnoreCase(name)) {
|
||||
if (mode.configName.equalsIgnoreCase(name) || name.equalsIgnoreCase(mode.aliasName)) {
|
||||
return mode;
|
||||
}
|
||||
}
|
||||
@@ -28,6 +44,6 @@ public enum EngineMode implements ConfigEnum {
|
||||
|
||||
@Override
|
||||
public String[] getValues() {
|
||||
return new String[] {"simple", "netty"};
|
||||
return new String[] {NETTY.configName, ASYNC.configName};
|
||||
}
|
||||
}
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
package games.cubi.raycastedantiesp.core.config.engine;
|
||||
|
||||
import games.cubi.raycastedantiesp.core.config.Config;
|
||||
import games.cubi.raycastedantiesp.core.config.ConfigLoadException;
|
||||
import games.cubi.raycastedantiesp.core.config.ConfigReader;
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
|
||||
public record SimpleEngineConfig(int asyncProcessingThreads) implements Config {
|
||||
public static SimpleEngineConfig load(ConfigurationNode node) {
|
||||
int threads = ConfigReader.integer(ConfigReader.node(node, "async-processing-threads"), "engine.simple.async-processing-threads");
|
||||
if (threads < 1) {
|
||||
throw new ConfigLoadException("engine.simple.async-processing-threads must be at least 1");
|
||||
}
|
||||
return new SimpleEngineConfig(threads);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package games.cubi.raycastedantiesp.core.config.raycast;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* A namespaced block key, optionally restricted by property values. Omitted properties match any value.
|
||||
*/
|
||||
public record BlockSelector(String value) {
|
||||
private static final Pattern NAMESPACE = Pattern.compile("[a-z0-9_.-]+");
|
||||
private static final Pattern PATH = Pattern.compile("[a-z0-9/._-]+");
|
||||
private static final Pattern PROPERTY = Pattern.compile("[a-z0-9_]+");
|
||||
|
||||
public BlockSelector {
|
||||
validate(value);
|
||||
}
|
||||
|
||||
public static BlockSelector parse(String input) {
|
||||
return new BlockSelector(input);
|
||||
}
|
||||
|
||||
public String blockKey() {
|
||||
int openingBracket = value.indexOf('[');
|
||||
return openingBracket < 0 ? value : value.substring(0, openingBracket);
|
||||
}
|
||||
|
||||
public boolean matchesAllStates() {
|
||||
return value.indexOf('[') < 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull String toString() {
|
||||
return value;
|
||||
}
|
||||
|
||||
private static void validate(String input) {
|
||||
Objects.requireNonNull(input, "value");
|
||||
int openingBracket = input.indexOf('[');
|
||||
if (openingBracket < 0) {
|
||||
if (input.indexOf(']') >= 0) {
|
||||
throw new IllegalArgumentException("Unexpected closing bracket in block selector");
|
||||
}
|
||||
validateBlockKey(input);
|
||||
return;
|
||||
}
|
||||
if (!input.endsWith("]") || input.indexOf('[', openingBracket + 1) >= 0
|
||||
|| input.indexOf(']', openingBracket) != input.length() - 1) {
|
||||
throw new IllegalArgumentException("Malformed block-state properties");
|
||||
}
|
||||
|
||||
String propertyText = input.substring(openingBracket + 1, input.length() - 1);
|
||||
if (propertyText.isEmpty()) {
|
||||
throw new IllegalArgumentException("Block-state properties cannot be empty");
|
||||
}
|
||||
|
||||
validateBlockKey(input.substring(0, openingBracket));
|
||||
Set<String> properties = new HashSet<>();
|
||||
for (String assignment : propertyText.split(",", -1)) {
|
||||
int equals = assignment.indexOf('=');
|
||||
if (equals <= 0 || equals != assignment.lastIndexOf('=') || equals == assignment.length() - 1) {
|
||||
throw new IllegalArgumentException("Invalid block-state property '" + assignment + "'");
|
||||
}
|
||||
String name = validateProperty(assignment.substring(0, equals), "property name");
|
||||
validateProperty(assignment.substring(equals + 1), "property value");
|
||||
if (!properties.add(name)) {
|
||||
throw new IllegalArgumentException("Duplicate block property '" + name + "'");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String validateBlockKey(String blockKey) {
|
||||
Objects.requireNonNull(blockKey, "blockKey");
|
||||
int separator = blockKey.indexOf(':');
|
||||
if (separator <= 0 || separator != blockKey.lastIndexOf(':') || separator == blockKey.length() - 1
|
||||
|| !NAMESPACE.matcher(blockKey.substring(0, separator)).matches()
|
||||
|| !PATH.matcher(blockKey.substring(separator + 1)).matches()) {
|
||||
throw new IllegalArgumentException("Invalid namespaced block key '" + blockKey + "'");
|
||||
}
|
||||
return blockKey;
|
||||
}
|
||||
|
||||
private static String validateProperty(String value, String description) {
|
||||
Objects.requireNonNull(value, description);
|
||||
if (!PROPERTY.matcher(value).matches()) {
|
||||
throw new IllegalArgumentException("Invalid block-state " + description + " '" + value + "'");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
}
|
||||
+22
-11
@@ -1,16 +1,27 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.config.raycast;
|
||||
|
||||
import games.cubi.raycastedantiesp.core.config.Config;
|
||||
import games.cubi.raycastedantiesp.core.config.ConfigReader;
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
|
||||
import org.spongepowered.configurate.objectmapping.meta.Comment;
|
||||
|
||||
public record ChunkSectionConfig(boolean enabled, int maxOccludingCount, int alwaysShowRadiusChunks, int visibleRecheckIntervalTicks) implements Config {
|
||||
public static ChunkSectionConfig load(ConfigurationNode node, String path) {
|
||||
return new ChunkSectionConfig(
|
||||
ConfigReader.bool(ConfigReader.node(node, "enabled"), path + ".enabled"),
|
||||
ConfigReader.integer(ConfigReader.node(node, "max-occluding-count"), path + ".max-occluding-count"),
|
||||
ConfigReader.integer(ConfigReader.node(node, "always-show-radius-chunks"), path + ".always-show-radius-chunks"),
|
||||
ConfigReader.integer(ConfigReader.node(node, "visible-recheck-interval-ticks"), path + ".visible-recheck-interval-ticks")
|
||||
);
|
||||
}
|
||||
@ConfigSerializable
|
||||
public record ChunkSectionConfig(
|
||||
@Comment("Whether chunk sections are hidden when they cannot be seen. This feature is not implemented yet.")
|
||||
boolean enabled,
|
||||
@Comment("Maximum number of occluding blocks permitted by a successful raycast.")
|
||||
int maxOccludingCount,
|
||||
@Comment("Radius in chunks within which chunk sections are always visible.")
|
||||
int alwaysShowRadiusChunks,
|
||||
@Comment("Ticks between checks of visible chunk sections. -1 disables visible rechecks.")
|
||||
int visibleRecheckIntervalTicks
|
||||
) implements Config {
|
||||
public static final ChunkSectionConfig DEFAULT = new ChunkSectionConfig(false, 6, 2, -1);
|
||||
}
|
||||
+85
-8
@@ -1,14 +1,91 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.config.raycast;
|
||||
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
import games.cubi.raycastedantiesp.core.config.ListEntryComments;
|
||||
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
|
||||
import org.spongepowered.configurate.objectmapping.meta.Comment;
|
||||
import org.spongepowered.configurate.objectmapping.meta.Setting;
|
||||
|
||||
public class EntityConfig extends RaycastConfig {
|
||||
private EntityConfig(RaycastConfig config) {
|
||||
super(config.enabled(), config.hideSoundsWhenHidden(), config.getMaxOccludingCount(), config.getAlwaysShowRadius(),
|
||||
config.getRaycastRadius(), config.hideOnSpawnDistance(), config.getVisibleRecheckIntervalTicks());
|
||||
}
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
public static EntityConfig load(ConfigurationNode node, String path) {
|
||||
return new EntityConfig(RaycastConfig.load(node, path, true));
|
||||
@ConfigSerializable
|
||||
public record EntityConfig(
|
||||
@Setting(nodeFromParent = true)
|
||||
RaycastSettings raycastSettings,
|
||||
@Comment("Suppress sounds produced by hidden entities.")
|
||||
boolean hideSoundsWhenHidden,
|
||||
@Comment("Retain hidden entities client-side instead of destroying them. This will cause a non-moving \"ghost player\" to persist until the real player is visible again, but can reduce network load around large mob farms or bases.")
|
||||
boolean keepClientEntityWhenHidden,
|
||||
@Comment("""
|
||||
Entity types that must always remain visible.
|
||||
|
||||
Falling blocks are also often used in custom mechanics, especially by plugins predating display entities. However, they occur in regular gameplay and can reveal information about hidden players, so they are not excluded by default. To exclude them, add minecraft:falling_block.
|
||||
|
||||
Add further exclusions using the namespaced entity name accepted by the /summon command.
|
||||
""")
|
||||
@ListEntryComments({
|
||||
@ListEntryComments.Entry(value = "minecraft:arrow", comment =
|
||||
"Projectiles move very quickly, giving the raycast engine limited time to process them. "
|
||||
+ "This could leave players without enough time to dodge, so projectiles are always visible by default."),
|
||||
@ListEntryComments.Entry(value = "minecraft:area_effect_cloud", comment =
|
||||
"Potions and area-effect clouds can damage players even when not visible. "
|
||||
+ "A reasonable always-show-radius mitigates this, so exempting them is not always necessary. "
|
||||
+ "Servers where knowing the exact number of potions another player has used is an unfair advantage may want to remove these exclusions."),
|
||||
@ListEntryComments.Entry(value = "minecraft:potion", comment =
|
||||
"The minecraft:potion entity was removed in 1.21.5 and replaced by minecraft:splash_potion and minecraft:lingering_potion. "
|
||||
+ "On 1.21.4, remove the latter two entries; on 1.21.5 and newer, remove minecraft:potion instead."),
|
||||
@ListEntryComments.Entry(value = "minecraft:lightning_bolt", comment = "Lightning is short-lived and expected to be visible to players who cannot see the block being struck."),
|
||||
@ListEntryComments.Entry(value = "minecraft:ender_dragon", comment = "Boss entities are also always visible by default."),
|
||||
@ListEntryComments.Entry(value = "minecraft:block_display", comment =
|
||||
"Display, interaction, and mannequin entities are not normally seen in vanilla gameplay and are commonly used for custom mechanics. "
|
||||
+ "Removing these exclusions is likely to break plugins such as hologram or NPC plugins.")
|
||||
})
|
||||
Set<String> excludedTypes
|
||||
) implements RaycastConfig {
|
||||
public static final EntityConfig DEFAULT = new EntityConfig(
|
||||
new RaycastSettings(true, (byte) 3, (short) 8, (short) 92, (short) 24, (short) 5),
|
||||
false,
|
||||
false,
|
||||
new LinkedHashSet<>(List.of(
|
||||
"minecraft:arrow",
|
||||
"minecraft:spectral_arrow",
|
||||
"minecraft:fireball",
|
||||
"minecraft:dragon_fireball",
|
||||
"minecraft:small_fireball",
|
||||
"minecraft:firework_rocket",
|
||||
"minecraft:wither_skull",
|
||||
"minecraft:breeze_wind_charge",
|
||||
"minecraft:wind_charge",
|
||||
"minecraft:ender_pearl",
|
||||
"minecraft:evoker_fangs",
|
||||
"minecraft:shulker_bullet",
|
||||
"minecraft:area_effect_cloud",
|
||||
"minecraft:lingering_potion",
|
||||
"minecraft:splash_potion",
|
||||
"minecraft:potion",
|
||||
"minecraft:lightning_bolt",
|
||||
"minecraft:ender_dragon",
|
||||
"minecraft:wither",
|
||||
"minecraft:warden",
|
||||
"minecraft:block_display",
|
||||
"minecraft:text_display",
|
||||
"minecraft:item_display",
|
||||
"minecraft:interaction",
|
||||
"minecraft:mannequin"
|
||||
))
|
||||
);
|
||||
|
||||
public EntityConfig {
|
||||
excludedTypes = Collections.unmodifiableSet(new LinkedHashSet<>(excludedTypes));
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.config.raycast;
|
||||
|
||||
import games.cubi.logs.Logger;
|
||||
import it.unimi.dsi.fastutil.ints.IntSet;
|
||||
import it.unimi.dsi.fastutil.ints.IntSets;
|
||||
|
||||
/**
|
||||
* Immutable entity-type exclusion policy resolved during plugin startup.
|
||||
*/
|
||||
public final class EntityTypeExclusions {
|
||||
public static volatile IntSet volatileExclusionSet = null;
|
||||
|
||||
// Is this sort of an insane approach? Yes. But it works.
|
||||
static class FakeLazyConstant {
|
||||
private static final IntSet finalEntityTypeExclusions = init();
|
||||
|
||||
private static IntSet init() {
|
||||
IntSet set = volatileExclusionSet;
|
||||
if (set == null) {
|
||||
Logger.error(new RuntimeException("Exclusion set was not initialised before being read"), 4, EntityTypeExclusions.class);
|
||||
return IntSets.emptySet();
|
||||
}
|
||||
return set;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean excludes(int entityType) {
|
||||
return FakeLazyConstant.finalEntityTypeExclusions.contains(entityType);
|
||||
}
|
||||
|
||||
public static int size() {
|
||||
return FakeLazyConstant.finalEntityTypeExclusions.size();
|
||||
}
|
||||
}
|
||||
+28
-10
@@ -1,14 +1,32 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.config.raycast;
|
||||
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
|
||||
import org.spongepowered.configurate.objectmapping.meta.Comment;
|
||||
import org.spongepowered.configurate.objectmapping.meta.Setting;
|
||||
|
||||
public class PlayerConfig extends RaycastConfig {
|
||||
private PlayerConfig(RaycastConfig config) {
|
||||
super(config.enabled(), config.hideSoundsWhenHidden(), config.getMaxOccludingCount(), config.getAlwaysShowRadius(),
|
||||
config.getRaycastRadius(), config.hideOnSpawnDistance(), config.getVisibleRecheckIntervalTicks());
|
||||
}
|
||||
|
||||
public static PlayerConfig load(ConfigurationNode node, String path) {
|
||||
return new PlayerConfig(RaycastConfig.load(node, path, true));
|
||||
}
|
||||
@ConfigSerializable
|
||||
public record PlayerConfig(
|
||||
@Setting(nodeFromParent = true)
|
||||
RaycastSettings raycastSettings,
|
||||
@Comment("Suppress sounds produced by hidden players.")
|
||||
boolean hideSoundsWhenHidden,
|
||||
@Comment("Retain hidden players client-side instead of destroying their entities. This will cause a non-moving \"ghost player\" to persist until the real player is visible again.")
|
||||
boolean keepClientEntityWhenHidden,
|
||||
@Comment("Only raycast other players while the viewing player is sneaking.")
|
||||
boolean onlyCheckSneaking
|
||||
) implements RaycastConfig {
|
||||
public static final PlayerConfig DEFAULT = new PlayerConfig(
|
||||
new RaycastSettings(true, (byte) 3, (short) 8, (short) 128, (short) 24, (short) 5),
|
||||
false,
|
||||
false,
|
||||
true
|
||||
);
|
||||
}
|
||||
+39
-70
@@ -1,93 +1,62 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.config.raycast;
|
||||
|
||||
import games.cubi.logs.Logger;
|
||||
import games.cubi.raycastedantiesp.core.config.Config;
|
||||
import games.cubi.raycastedantiesp.core.config.ConfigLoadException;
|
||||
import games.cubi.raycastedantiesp.core.config.ConfigReader;
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
|
||||
public class RaycastConfig implements Config {
|
||||
private final boolean enabled;
|
||||
private final boolean hideSoundsWhenHidden;
|
||||
private final byte maxOccludingCount;
|
||||
private final short alwaysShowRadius;
|
||||
private final short raycastRadius;
|
||||
private final short hideOnSpawnDistance;
|
||||
private final short visibleRecheckIntervalTicks;
|
||||
public interface RaycastConfig extends Config {
|
||||
RaycastSettings raycastSettings();
|
||||
|
||||
public RaycastConfig(boolean enabled, boolean hideSoundsWhenHidden, int maxOccludingCount, int alwaysShowRadius,
|
||||
int raycastRadius, int hideOnSpawnDistance, int visibleRecheckIntervalTicks) {
|
||||
this.enabled = enabled;
|
||||
this.hideSoundsWhenHidden = hideSoundsWhenHidden;
|
||||
this.maxOccludingCount = (byte) maxOccludingCount;
|
||||
this.alwaysShowRadius = (short) alwaysShowRadius;
|
||||
this.raycastRadius = (short) raycastRadius;
|
||||
this.hideOnSpawnDistance = (short) hideOnSpawnDistance;
|
||||
this.visibleRecheckIntervalTicks = (short) visibleRecheckIntervalTicks;
|
||||
default boolean enabled() {
|
||||
return raycastSettings().enabled();
|
||||
}
|
||||
|
||||
protected static RaycastConfig load(ConfigurationNode node, String path, boolean hasHideSoundsWhenHidden) {
|
||||
int maxOccludingCount = ConfigReader.integer(ConfigReader.node(node, "max-occluding-count"), path + ".max-occluding-count");
|
||||
if (maxOccludingCount < -1 || maxOccludingCount > Byte.MAX_VALUE) {
|
||||
Logger.warning(path + ".max-occluding-count must be between -1 and " + Byte.MAX_VALUE + " but was " + maxOccludingCount +". Defaulting to 3.", 4, RaycastConfig.class);
|
||||
maxOccludingCount = 3;
|
||||
}
|
||||
int alwaysShowRadius = ConfigReader.integer(ConfigReader.node(node, "always-show-radius"), path + ".always-show-radius");
|
||||
if (alwaysShowRadius < -1 || alwaysShowRadius > Short.MAX_VALUE) {
|
||||
Logger.warning(path + ".always-show-radius must be between -1 and " + Short.MAX_VALUE + " but was " + alwaysShowRadius +". Defaulting to 8.", 4, RaycastConfig.class);
|
||||
alwaysShowRadius = 8;
|
||||
}
|
||||
int raycastRadius = ConfigReader.integer(ConfigReader.node(node, "raycast-radius"), path + ".raycast-radius");
|
||||
if (raycastRadius < -1 || raycastRadius > Short.MAX_VALUE) {
|
||||
Logger.warning(path + ".raycast-radius must be between -1 and " + Short.MAX_VALUE + " but was " + raycastRadius +". Defaulting to 48.", 4, RaycastConfig.class);
|
||||
raycastRadius = 48;
|
||||
}
|
||||
int hideOnSpawnDistance = ConfigReader.integer(ConfigReader.node(node, "hide-on-spawn-distance"), path + ".hide-on-spawn-distance");
|
||||
if (hideOnSpawnDistance < -1 || hideOnSpawnDistance > Short.MAX_VALUE) {
|
||||
Logger.warning(path + ".hide-on-spawn-distance must be between -1 and " + Short.MAX_VALUE + " but was " + hideOnSpawnDistance +". Defaulting to 32.", 4, RaycastConfig.class);
|
||||
hideOnSpawnDistance = 32;
|
||||
}
|
||||
int visibleRecheckIntervalTicks = ConfigReader.integer(ConfigReader.node(node, "visible-recheck-interval-ticks"), path + ".visible-recheck-interval-ticks");
|
||||
if (visibleRecheckIntervalTicks < -1 || visibleRecheckIntervalTicks > Short.MAX_VALUE) {
|
||||
Logger.warning(path + ".visible-recheck-interval-ticks must be between -1 and " + Short.MAX_VALUE + " but was " + visibleRecheckIntervalTicks +". Defaulting to 5.", 4, RaycastConfig.class);
|
||||
visibleRecheckIntervalTicks = 5;
|
||||
}
|
||||
return new RaycastConfig(
|
||||
ConfigReader.bool(ConfigReader.node(node, "enabled"), path + ".enabled"),
|
||||
hasHideSoundsWhenHidden && ConfigReader.bool(ConfigReader.node(node, "hide-sounds-when-hidden"), path + ".hide-sounds-when-hidden"),
|
||||
maxOccludingCount,
|
||||
alwaysShowRadius,
|
||||
raycastRadius,
|
||||
hideOnSpawnDistance,
|
||||
visibleRecheckIntervalTicks
|
||||
);
|
||||
default boolean hideSoundsWhenHidden() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean enabled() {
|
||||
return enabled;
|
||||
default byte getMaxOccludingCount() {
|
||||
return raycastSettings().maxOccludingCount();
|
||||
}
|
||||
|
||||
public boolean hideSoundsWhenHidden() {
|
||||
return hideSoundsWhenHidden;
|
||||
default short getAlwaysShowRadius() {
|
||||
return raycastSettings().alwaysShowRadius();
|
||||
}
|
||||
|
||||
public byte getMaxOccludingCount() {
|
||||
return maxOccludingCount;
|
||||
default short getRaycastRadius() {
|
||||
return raycastSettings().raycastRadius();
|
||||
}
|
||||
|
||||
public short getAlwaysShowRadius() {
|
||||
return alwaysShowRadius;
|
||||
default short hideOnSpawnDistance() {
|
||||
return raycastSettings().hideOnSpawnDistance();
|
||||
}
|
||||
|
||||
public short getRaycastRadius() {
|
||||
return raycastRadius;
|
||||
default short getVisibleRecheckIntervalTicks() {
|
||||
return raycastSettings().visibleRecheckIntervalTicks();
|
||||
}
|
||||
|
||||
public short hideOnSpawnDistance() {
|
||||
return hideOnSpawnDistance;
|
||||
default boolean keepClientEntityWhenHidden() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public short getVisibleRecheckIntervalTicks() {
|
||||
return visibleRecheckIntervalTicks;
|
||||
default int alwaysShowRadiusSquared() {
|
||||
int radius = getAlwaysShowRadius();
|
||||
return radius * radius;
|
||||
}
|
||||
|
||||
default int raycastRadiusSquared() {
|
||||
int radius = getRaycastRadius();
|
||||
return radius * radius;
|
||||
}
|
||||
|
||||
default int hideOnSpawnDistanceSquared() {
|
||||
int distance = hideOnSpawnDistance();
|
||||
return distance * distance;
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package games.cubi.raycastedantiesp.core.config.raycast;
|
||||
|
||||
import games.cubi.raycastedantiesp.core.config.ConfigRange;
|
||||
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
|
||||
import org.spongepowered.configurate.objectmapping.meta.Comment;
|
||||
|
||||
@ConfigSerializable
|
||||
public record RaycastSettings(
|
||||
@Comment("Whether this category is checked.")
|
||||
boolean enabled,
|
||||
@Comment("Maximum number of occluding blocks permitted by a successful raycast.")
|
||||
@ConfigRange(min = 0, max = Byte.MAX_VALUE)
|
||||
byte maxOccludingCount,
|
||||
@Comment("Distance in blocks within which targets are always visible.")
|
||||
@ConfigRange(min = 0, max = Short.MAX_VALUE)
|
||||
short alwaysShowRadius,
|
||||
@Comment("Maximum distance in blocks at which targets are raycasted.")
|
||||
@ConfigRange(min = 0, max = Short.MAX_VALUE)
|
||||
short raycastRadius,
|
||||
@Comment("Distance in blocks beyond which a newly spawned target starts hidden.")
|
||||
@ConfigRange(min = 0, max = Short.MAX_VALUE)
|
||||
short hideOnSpawnDistance,
|
||||
@Comment("Ticks between checks of visible targets. -1 keeps a shown target visible permanently.")
|
||||
@ConfigRange(min = -1, max = Short.MAX_VALUE)
|
||||
short visibleRecheckIntervalTicks
|
||||
) {
|
||||
}
|
||||
+16
-10
@@ -1,21 +1,27 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.config.raycast;
|
||||
|
||||
import games.cubi.raycastedantiesp.core.config.Config;
|
||||
import games.cubi.raycastedantiesp.core.config.ConfigReader;
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
|
||||
import org.spongepowered.configurate.objectmapping.meta.Comment;
|
||||
|
||||
@ConfigSerializable
|
||||
public record SoundEffectsConfig(
|
||||
@Comment("Whether sounds should be hidden when their source cannot be seen. This feature is not implemented yet.")
|
||||
boolean enabled,
|
||||
@Comment("Maximum number of occluding blocks permitted by a successful sound raycast.")
|
||||
int maxOccludingCount,
|
||||
@Comment("Distance in blocks within which sounds are always played.")
|
||||
int alwaysPlayRadius,
|
||||
@Comment("Maximum distance in blocks at which sounds are raycasted.")
|
||||
int raycastRadius
|
||||
) implements Config {
|
||||
public static SoundEffectsConfig load(ConfigurationNode node, String path) {
|
||||
return new SoundEffectsConfig(
|
||||
ConfigReader.bool(ConfigReader.node(node, "enabled"), path + ".enabled"),
|
||||
ConfigReader.integer(ConfigReader.node(node, "max-occluding-count"), path + ".max-occluding-count"),
|
||||
ConfigReader.integer(ConfigReader.node(node, "always-play-radius"), path + ".always-play-radius"),
|
||||
ConfigReader.integer(ConfigReader.node(node, "raycast-radius"), path + ".raycast-radius")
|
||||
);
|
||||
}
|
||||
public static final SoundEffectsConfig DEFAULT = new SoundEffectsConfig(false, 3, 8, 48);
|
||||
}
|
||||
+30
-8
@@ -1,14 +1,36 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.config.raycast;
|
||||
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
|
||||
import org.spongepowered.configurate.objectmapping.meta.Comment;
|
||||
import org.spongepowered.configurate.objectmapping.meta.Setting;
|
||||
|
||||
public class TileEntityConfig extends RaycastConfig {
|
||||
private TileEntityConfig(RaycastConfig config) {
|
||||
super(config.enabled(), false, config.getMaxOccludingCount(), config.getAlwaysShowRadius(),
|
||||
config.getRaycastRadius(), config.hideOnSpawnDistance(), config.getVisibleRecheckIntervalTicks());
|
||||
}
|
||||
import java.util.List;
|
||||
|
||||
public static TileEntityConfig load(ConfigurationNode node, String path) {
|
||||
return new TileEntityConfig(RaycastConfig.load(node, path, false));
|
||||
@ConfigSerializable
|
||||
public record TileEntityConfig(
|
||||
@Setting(nodeFromParent = true)
|
||||
RaycastSettings raycastSettings,
|
||||
@Comment("Blocks that should not be managed as tile entities. Use namespaced block keys.\n"
|
||||
+ "\"minecraft:chest\" matches every chest state.\n"
|
||||
+ "\"minecraft:chest[waterlogged=true]\" matches all waterlogged chests, regardless of facing or chest type.\n"
|
||||
+ "Omitted properties are wildcards. All specified properties must match. Specify every property to select one exact state.\n"
|
||||
+ "A block is excluded if any list entry matches. Changes require a server restart.")
|
||||
List<BlockSelector> excludedBlocks
|
||||
) implements RaycastConfig {
|
||||
public static final TileEntityConfig DEFAULT = new TileEntityConfig(
|
||||
new RaycastSettings(true, (byte) 3, (short) 8, (short) 64, (short) 24, (short) -1),
|
||||
List.of(BlockSelector.parse("minecraft:beacon"))
|
||||
);
|
||||
|
||||
public TileEntityConfig {
|
||||
excludedBlocks = List.copyOf(excludedBlocks);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,489 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.engine;
|
||||
|
||||
import games.cubi.locatables.api.Locatable;
|
||||
import games.cubi.logs.Logger;
|
||||
import games.cubi.raycastedantiesp.core.config.ConfigManager;
|
||||
import games.cubi.raycastedantiesp.core.config.DebugConfig;
|
||||
import games.cubi.raycastedantiesp.core.config.raycast.EntityConfig;
|
||||
import games.cubi.raycastedantiesp.core.config.raycast.PlayerConfig;
|
||||
import games.cubi.raycastedantiesp.core.config.raycast.TileEntityConfig;
|
||||
import games.cubi.raycastedantiesp.core.entity.EntityBypassRegistry;
|
||||
import games.cubi.raycastedantiesp.core.tracked.NettyEntity;
|
||||
import games.cubi.raycastedantiesp.core.players.PlayerData;
|
||||
import games.cubi.raycastedantiesp.core.players.PlayerRegistry;
|
||||
import games.cubi.raycastedantiesp.core.raycast.ParticleSpawner;
|
||||
import games.cubi.raycastedantiesp.core.raycast.RaycastUtil;
|
||||
import games.cubi.utils.lists.PrimitiveIntArrayList;
|
||||
import games.cubi.raycastedantiesp.core.view.BlockView;
|
||||
import games.cubi.raycastedantiesp.core.view.EntityView;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.function.IntSupplier;
|
||||
|
||||
public abstract class AsyncEngine implements Engine {
|
||||
private static final long SLOW_TICK_NANOS = 40 * 1_000_000L;
|
||||
//Literally just magic numbers I made by keyboard mashing
|
||||
private static final int TICK_IDLE = 1872;
|
||||
private static final int TICK_PENDING = -129;
|
||||
private static final int TICK_RUNNING = 34892;
|
||||
|
||||
private final ConfigManager config;
|
||||
private final ParticleSpawner particleSpawner;
|
||||
private final IntSupplier currentTickSupplier;
|
||||
private final AtomicInteger tickThreadsRunning = new AtomicInteger(0);
|
||||
private final AtomicInteger runningTick = new AtomicInteger(-1);
|
||||
private final AtomicInteger tickState = new AtomicInteger(TICK_IDLE);
|
||||
private final AtomicLong tickNanos = new AtomicLong(0);
|
||||
private final AsyncRunner asyncRunner;
|
||||
private final TimingStatsSelector timingStatsSelector = new TimingStatsSelector();
|
||||
|
||||
public AsyncEngine(ConfigManager config, ParticleSpawner particleSpawner, IntSupplier currentTickSupplier, AsyncRunner asyncRunner) {
|
||||
this.config = config;
|
||||
this.particleSpawner = particleSpawner;
|
||||
this.currentTickSupplier = currentTickSupplier;
|
||||
this.asyncRunner = asyncRunner;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reserves the next engine tick before it is handed to the async scheduler.
|
||||
*
|
||||
* @return true if the caller now owns the only pending tick slot; false if an existing pending
|
||||
* or running tick should cover this attempt.
|
||||
*/
|
||||
public boolean markTickRunning() {
|
||||
if (tickState.compareAndSet(TICK_IDLE, TICK_PENDING)) {
|
||||
return true;
|
||||
}
|
||||
recordSkippedTick(-1, System.nanoTime());
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases a pending tick reservation when async scheduling fails before {@link #tick(int, long)}
|
||||
* can claim it.
|
||||
*/
|
||||
public void cancelPendingTickReservation() {
|
||||
if (!tickState.compareAndSet(TICK_PENDING, TICK_IDLE)) {
|
||||
Logger.warning("Attempted to cancel a pending tick reservation, but the tick was no longer pending.", 5, AsyncEngine.class);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the tick which was reserved using {@link #markTickRunning} and, if the engine falls behind the server clock, keeps the
|
||||
* same worker on the latest tick instead of yielding back to the scheduler.
|
||||
*
|
||||
* @param scheduledTick the server tick captured before async handoff.
|
||||
* @param scheduledNanos the time captured before async handoff, used to separate queue delay from engine work.
|
||||
*/
|
||||
@Override
|
||||
public void tick(int scheduledTick, long scheduledNanos) {
|
||||
boolean runTick = true;
|
||||
boolean expectPending = true;
|
||||
int startTick = currentTickSupplier.getAsInt();
|
||||
while (runTick) {
|
||||
if (!startTickState(scheduledTick, expectPending)) {
|
||||
return;
|
||||
}
|
||||
if (!dispatchTick(scheduledTick, startTick, scheduledNanos)) {
|
||||
return;
|
||||
}
|
||||
|
||||
int latestTick = currentTickSupplier.getAsInt();
|
||||
if (latestTick > startTick) {
|
||||
// If running behind, don't yield the thread, just run the next tick immediately
|
||||
Logger.warning("Tick thread completed tick #" + startTick + " after tick #" + latestTick + " had already begun. Starting next tick immediately instead of yielding thread to scheduler. This is probably safe to ignore but may suggest that your server is overloaded.", 5, AsyncEngine.class);
|
||||
startTick = latestTick;
|
||||
scheduledNanos = System.nanoTime();
|
||||
scheduledTick = latestTick;
|
||||
|
||||
if (tickState.get() == TICK_RUNNING) {
|
||||
// This means that there is already a tick running, so we should exit
|
||||
Logger.info("Tick finished behind but another thread had already begun ticking the next tick.", 5, AsyncEngine.class);
|
||||
return;
|
||||
}
|
||||
expectPending = false; //Next call to startTickState should not expect to see status set to pending
|
||||
}
|
||||
else runTick = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Claims worker capacity and either runs work immediately or schedules worker batches.
|
||||
*
|
||||
* @return true if at least one sub-tick worker accepted responsibility for completing the tick
|
||||
* lifecycle; false if this attempt was skipped or cleaned up during setup.
|
||||
*/
|
||||
private boolean dispatchTick(int scheduledTick, int startTick, long scheduledNanos) {
|
||||
int threads = config.getEngineConfig().asyncConfig().asyncProcessingThreads();
|
||||
if (threads < 1) threads = 1;
|
||||
|
||||
DebugConfig debugConfig = config.getDebugConfig();
|
||||
TimingStats tickTimingStats = timingStats(debugConfig);
|
||||
boolean recordTimings = tickTimingStats != TimingStatsNoOp.INSTANCE;
|
||||
|
||||
long startNanos = System.nanoTime();
|
||||
|
||||
int tickAlreadyRunning = runningTick.get();
|
||||
// First guard for the current tick already being processed (can happen if the previous tick ran overtime and thus didn't yield the thread)
|
||||
if (scheduledTick == tickAlreadyRunning) {
|
||||
logAggregateReport(tickTimingStats.recordSkipped(threads, startNanos));
|
||||
Logger.info("RaycastedAntiESP is already processing this tick; skipping duplicate same-tick attempt."
|
||||
+ " scheduledTick=" + scheduledTick
|
||||
+ " currentServerTick=" + startTick
|
||||
+ " currentRunningTick=" + tickAlreadyRunning, 6, AsyncEngine.class);
|
||||
finishTickState();
|
||||
return false;
|
||||
}
|
||||
|
||||
int runningThreads = tickThreadsRunning.compareAndExchange(0, threads);
|
||||
// Now guard for previous tick still running
|
||||
if (runningThreads != 0) {
|
||||
long queueNanos = Math.max(0, startNanos - scheduledNanos);
|
||||
Logger.warning("RaycastedAntiESP is still ticking from the last tick! Skipping this tick to avoid concurrent modification issues."
|
||||
+ " scheduledTick=" + scheduledTick
|
||||
+ " currentServerTick=" + currentTickSupplier.getAsInt()
|
||||
+ " currentRunningTick=" + tickAlreadyRunning
|
||||
+ " runningThreads=" + runningThreads
|
||||
+ " timeSpentInQueue=" + TickTimingFormatter.formatMillis(queueNanos) + "ms", 5, AsyncEngine.class);
|
||||
logAggregateReport(tickTimingStats.recordSkipped(threads, startNanos));
|
||||
finishTickState();
|
||||
return false;
|
||||
}
|
||||
|
||||
TickTimings timings = null;
|
||||
boolean handedOffToSubTick = false;
|
||||
boolean claimedRunningTick = false;
|
||||
try {
|
||||
tickNanos.set(startNanos);
|
||||
|
||||
final int currentTick = startTick;
|
||||
runningTick.set(currentTick);
|
||||
claimedRunningTick = true;
|
||||
PlayerData[] allPlayers = PlayerRegistry.get().getPlayerDataArray();
|
||||
|
||||
EntityConfig entityConfig = config.getEntityConfig();
|
||||
PlayerConfig playerConfig = config.getPlayerConfig();
|
||||
TileEntityConfig tileEntityConfig = config.getTileEntityConfig();
|
||||
if (recordTimings) {
|
||||
timings = new TickTimings(scheduledTick, scheduledNanos, currentTick, startNanos, threads, allPlayers.length);
|
||||
}
|
||||
/*
|
||||
Logger.debug("Tick #" + currentTick);
|
||||
if (currentTick % 1200 == 0) {
|
||||
Logger.debug("Printing player data");
|
||||
for (PlayerData playerData : allPlayers) {
|
||||
Logger.debug("Player " + playerData.getPlayerUUID() + " location=" + playerData.ownLocation());
|
||||
Logger.debug("EntityView:" + playerData.entityView().getStringDataForDebugging());
|
||||
Logger.debug("PlayerView:" + playerData.playerView().getStringDataForDebugging());
|
||||
}
|
||||
}*/
|
||||
|
||||
// If only one thread is configured, just use the current async thread to avoid the overhead of scheduling tasks and context switching.
|
||||
if (threads == 1) {
|
||||
handedOffToSubTick = true;
|
||||
subTick(allPlayers, entityConfig, playerConfig, tileEntityConfig, debugConfig, currentTick, timings, tickTimingStats);
|
||||
return true;
|
||||
}
|
||||
|
||||
List<PlayerData[]> batches = new ArrayList<>(threads);
|
||||
int playerCount = allPlayers.length;
|
||||
for (int i = 0; i < threads; i++) {
|
||||
int batchSize = (playerCount + threads - 1 - i) / threads;
|
||||
batches.add(new PlayerData[batchSize]);
|
||||
}
|
||||
|
||||
int index = 0;
|
||||
for (PlayerData playerData : allPlayers) {
|
||||
int batchIndex = index % threads;
|
||||
int position = index / threads;
|
||||
|
||||
batches.get(batchIndex)[position] = playerData;
|
||||
index++;
|
||||
}
|
||||
|
||||
TickTimings tickTimings = timings; // needs to be effectively-final for lambda
|
||||
int scheduledBatches = 0;
|
||||
try {
|
||||
for (PlayerData[] batch : batches) {
|
||||
asyncRunner.runNow(() -> subTick(batch, entityConfig, playerConfig, tileEntityConfig, debugConfig, currentTick, tickTimings, tickTimingStats));
|
||||
scheduledBatches++;
|
||||
}
|
||||
handedOffToSubTick = true;
|
||||
}
|
||||
finally {
|
||||
if (scheduledBatches < threads) {
|
||||
tickThreadsRunning.addAndGet(-(threads - scheduledBatches));
|
||||
handedOffToSubTick = scheduledBatches > 0;
|
||||
}
|
||||
}
|
||||
return handedOffToSubTick;
|
||||
}
|
||||
finally {
|
||||
if (!handedOffToSubTick) {
|
||||
tickThreadsRunning.set(0);
|
||||
if (claimedRunningTick) {
|
||||
finaliseTick(startTick);
|
||||
} else {
|
||||
finishTickState();
|
||||
}
|
||||
Logger.error("An error occurred during tick scheduling before handing off to sub-tick processing. Resetting tickThreadsRunning to 0 to avoid deadlock. Current tick: " + currentTickSupplier.getAsInt(), 2, AsyncEngine.class);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes one worker batch and lets the final batch publish timing data and release the tick reservation.
|
||||
*
|
||||
* @param timingStats the timing sink selected when this tick started, so config changes during
|
||||
* worker execution do not split one tick across sinks.
|
||||
*/
|
||||
private void subTick(PlayerData[] batch, EntityConfig entityConfig, PlayerConfig playerConfig, TileEntityConfig tileEntityConfig, DebugConfig debugConfig, int currentTick, TickTimings timings, TimingStats timingStats) {
|
||||
TickTimingBatch batchTimings = timings == null ? TickTimingBatchNoOp.INSTANCE : new TickTimingBatch();
|
||||
long batchStartNanos = batchTimings.startBatch();
|
||||
try {
|
||||
processTickForPlayers(batch, entityConfig, playerConfig, tileEntityConfig, debugConfig.showDebugParticles(), currentTick, batchTimings);
|
||||
}
|
||||
finally {
|
||||
if (timings != null) {
|
||||
timings.recordBatch(batchTimings, batchTimings.elapsedSince(batchStartNanos));
|
||||
}
|
||||
int threadsRemaining = tickThreadsRunning.decrementAndGet();
|
||||
if (threadsRemaining < 0) {
|
||||
Logger.error("tickThreadsRunning went below 0! This should never happen. Resetting to 0 to avoid further issues.", 2, AsyncEngine.class);
|
||||
tickThreadsRunning.set(0);
|
||||
finaliseTick(currentTick);
|
||||
}
|
||||
if (threadsRemaining == 0) {
|
||||
try {
|
||||
long completionNanos = System.nanoTime();
|
||||
if (timings != null) {
|
||||
TickTimingSnapshot snapshot = timings.snapshot(currentTickSupplier.getAsInt(), completionNanos);
|
||||
String aggregateReport = timingStats.recordCompleted(snapshot, completionNanos);
|
||||
if (snapshot.wallNanos() > SLOW_TICK_NANOS) {
|
||||
Logger.warning(snapshot.toSlowTickMessage(), 5, AsyncEngine.class);
|
||||
}
|
||||
logAggregateReport(aggregateReport);
|
||||
} else {
|
||||
long elapsedNanos = completionNanos - tickNanos.get();
|
||||
if (elapsedNanos > SLOW_TICK_NANOS) {
|
||||
Logger.warning("Tick completed in " + (elapsedNanos / 1_000_000.0) + " ms. If you see this warning frequently, consider reducing the raycasting load by adjusting the configuration.", 5, AsyncEngine.class);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
finaliseTick(currentTick);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves the reserved tick into the running state. Catch-up iterations may start from idle
|
||||
* because they are created by the current worker instead of by the server tick event.
|
||||
*
|
||||
* @return true if this thread now owns the running state; false if another pending or running
|
||||
* tick should take precedence.
|
||||
*/
|
||||
private boolean startTickState(int scheduledTick, boolean expectPending) {
|
||||
if (expectPending) {
|
||||
if (tickState.compareAndSet(TICK_PENDING, TICK_RUNNING)) {
|
||||
return true;
|
||||
}
|
||||
if (tickState.compareAndSet(TICK_IDLE, TICK_RUNNING)) {
|
||||
// This means that this tick was dispatched but not marked as such, or was unmarked at some point.
|
||||
Logger.warning("Tick " + scheduledTick + " was dispatched but not marked as pending. This suggests a race condition. Please report this on our GitHub or Discord.", 5, AsyncEngine.class);
|
||||
return true;
|
||||
}
|
||||
} else if (tickState.compareAndSet(TICK_IDLE, TICK_RUNNING)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// This means there is already a tick pending or running, so we should exit.
|
||||
recordSkippedTick(-1, System.nanoTime());
|
||||
Logger.info("Tick " + scheduledTick + " is pending but another tick is already pending or running. Exiting now.", 6, AsyncEngine.class);
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases ownership for the tick that completed, without clearing a newer running tick that
|
||||
* may have already taken over.
|
||||
*/
|
||||
private void finaliseTick(int currentTick) {
|
||||
runningTick.compareAndSet(currentTick, -1);
|
||||
finishTickState();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the reservation state to idle after the active tick has stopped touching shared player visibility data.
|
||||
*/
|
||||
private void finishTickState() {
|
||||
if (!tickState.compareAndSet(TICK_RUNNING, TICK_IDLE)) {
|
||||
// This should never happen as it means the tick was marked as completed before processing was completed
|
||||
Logger.warning("tickState was not running when completing tick! This should never happen. Please report this on our GitHub or Discord.", 5, AsyncEngine.class);
|
||||
}
|
||||
}
|
||||
|
||||
private void processTickForPlayers(PlayerData[] playerDataList, EntityConfig entityConfig, PlayerConfig playerConfig, TileEntityConfig tileEntityConfig,
|
||||
boolean debugParticles, int currentTick, TickTimingBatch timings) {
|
||||
|
||||
for (PlayerData playerData : playerDataList) {
|
||||
if (!playerData.isConnected()) {
|
||||
continue;
|
||||
}
|
||||
playerData.nettyData().markPendingPostSpawnTasksForEviction();
|
||||
if (playerData.hasBypassPermission()) {
|
||||
timings.incrementBypassSkippedPlayers();
|
||||
continue;
|
||||
}
|
||||
|
||||
BlockView blockView = playerData.blockView();
|
||||
|
||||
Locatable playerLocation = playerData.ownLocation();
|
||||
if (playerLocation == null || playerLocation.world() == null) {
|
||||
timings.incrementNullLocationSkippedPlayers();
|
||||
continue;
|
||||
}
|
||||
int worldEpoch = playerData.tryAcquireWorldEpochFor(playerLocation.world());
|
||||
if (worldEpoch == PlayerData.INVALID_WORLD_EPOCH) {
|
||||
if (tileEntityConfig.enabled()) timings.incrementTileWorldSkipped();
|
||||
continue;
|
||||
}
|
||||
timings.incrementProcessedPlayers();
|
||||
|
||||
try {
|
||||
if (entityConfig.enabled()) {
|
||||
long sectionStartNanos = timings.startEntitySection();
|
||||
checkEntities(playerData, playerLocation, entityConfig, debugParticles, blockView, currentTick, worldEpoch, timings);
|
||||
timings.finishEntitySection(sectionStartNanos);
|
||||
}
|
||||
if (playerConfig.enabled()) {
|
||||
long sectionStartNanos = timings.startPlayerSection();
|
||||
checkPlayers(playerData, playerLocation, playerConfig, debugParticles, blockView, currentTick, worldEpoch, timings);
|
||||
timings.finishPlayerSection(sectionStartNanos);
|
||||
}
|
||||
if (tileEntityConfig.enabled()) {
|
||||
long sectionStartNanos = timings.startTileSection();
|
||||
checkTileEntities(playerData, playerLocation, tileEntityConfig, debugParticles, blockView, currentTick, worldEpoch, timings);
|
||||
timings.finishTileSection(sectionStartNanos);
|
||||
}
|
||||
} finally {
|
||||
playerData.entityView().flushPendingTransitions();
|
||||
playerData.playerView().flushPendingTransitions();
|
||||
blockView.flushPendingTransitions();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void checkEntities(PlayerData player, Locatable playerLocation, EntityConfig entityConfig, boolean debugParticles, BlockView blockView, int currentTick, int worldEpoch, TickTimingBatch timings) {
|
||||
EntityView<?> entityView = player.entityView();
|
||||
int alwaysShowRadiusSquared = entityConfig.alwaysShowRadiusSquared();
|
||||
int raycastRadiusSquared = entityConfig.raycastRadiusSquared();
|
||||
|
||||
int checked = entityView.forEachNeedingRecheckEntity(entityConfig.getVisibleRecheckIntervalTicks(), currentTick, !(timings instanceof TickTimingBatchNoOp), worldEpoch, entity -> {
|
||||
if (entity.glowing()) {
|
||||
entityView.setVisibility(entity, true, currentTick, worldEpoch);
|
||||
return;
|
||||
}
|
||||
if (attachedToAlwaysVisibleEntityOrSelf(player, entityView, entity, currentTick, worldEpoch)) {
|
||||
return;
|
||||
}
|
||||
|
||||
timings.incrementEntityRaycasts();
|
||||
boolean canSee = RaycastUtil.raycastUnrolledAccumulated(entityConfig.getMaxOccludingCount(), alwaysShowRadiusSquared, raycastRadiusSquared, debugParticles, entity.getYOffset(), blockView, playerLocation, entity, particleSpawner);
|
||||
entityView.setVisibility(entity, canSee, currentTick, worldEpoch);
|
||||
});
|
||||
timings.addEntityChecked(checked);
|
||||
}
|
||||
|
||||
private void checkPlayers(PlayerData player, Locatable playerLocation, PlayerConfig playerConfig, boolean debugParticles, BlockView blockView, int currentTick, int worldEpoch, TickTimingBatch timings) {
|
||||
EntityView<?> playerView = player.playerView();
|
||||
int alwaysShowRadiusSquared = playerConfig.alwaysShowRadiusSquared();
|
||||
int raycastRadiusSquared = playerConfig.raycastRadiusSquared();
|
||||
|
||||
int checked = playerView.forEachNeedingRecheckEntity(playerConfig.getVisibleRecheckIntervalTicks(), currentTick, !(timings instanceof TickTimingBatchNoOp), worldEpoch, otherPlayer -> {
|
||||
if (otherPlayer.glowing() || (playerConfig.onlyCheckSneaking() && !otherPlayer.sneaking())) {
|
||||
playerView.setVisibility(otherPlayer, true, currentTick, worldEpoch);
|
||||
return;
|
||||
}
|
||||
if (attachedToAlwaysVisibleEntityOrSelf(player, playerView, otherPlayer, currentTick, worldEpoch)) {
|
||||
return;
|
||||
}
|
||||
timings.incrementPlayerRaycasts();
|
||||
boolean canSee = RaycastUtil.raycastUnrolledAccumulated(playerConfig.getMaxOccludingCount(), alwaysShowRadiusSquared, raycastRadiusSquared, debugParticles, 1.5f, blockView, playerLocation, otherPlayer, particleSpawner);
|
||||
playerView.setVisibility(otherPlayer, canSee, currentTick, worldEpoch);
|
||||
});
|
||||
timings.addPlayerChecked(checked);
|
||||
}
|
||||
|
||||
private boolean attachedToAlwaysVisibleEntityOrSelf(PlayerData player, EntityView<?> view, NettyEntity<?> entity, int currentTick, int worldEpoch) {
|
||||
int selfEntityID = player.nettyData().getSelfEntityID();
|
||||
if (!player.nettyData().isSelfEntityID(entity.leashingEntity())
|
||||
&& !player.nettyData().isSelfEntityID(entity.vehicleID())
|
||||
&& !EntityBypassRegistry.isBypassed(entity.vehicleID())
|
||||
&& !PrimitiveIntArrayList.contains(entity.passengerIDsNoAlloc(), selfEntityID)) {
|
||||
return false;
|
||||
}
|
||||
view.setVisibility(entity, true, currentTick, worldEpoch);
|
||||
return true;
|
||||
}
|
||||
|
||||
private void checkTileEntities(PlayerData player, Locatable playerLocation, TileEntityConfig tileEntityConfig, boolean debugParticles, BlockView blockView, int currentTick, int worldEpoch, TickTimingBatch timings) {
|
||||
long modeToken = blockView.tileEntityCheckModeToken();
|
||||
int alwaysShowRadiusSquared = tileEntityConfig.alwaysShowRadiusSquared();
|
||||
int raycastRadiusSquared = tileEntityConfig.raycastRadiusSquared();
|
||||
int checked = blockView.updateVisibilityForEachNeedingRecheck(tileEntityConfig.getVisibleRecheckIntervalTicks(), currentTick, modeToken, worldEpoch, tileEntityLocation -> {
|
||||
|
||||
if (playerLocation.distanceSquared(tileEntityLocation) > raycastRadiusSquared) {
|
||||
timings.incrementTileRadiusSkipped();
|
||||
return BlockView.VisibilityResolver.HIDE;
|
||||
}
|
||||
timings.incrementTileRaycasts();
|
||||
boolean canSee = RaycastUtil.raycastUnrolledAccumulated(tileEntityConfig.getMaxOccludingCount(), alwaysShowRadiusSquared, raycastRadiusSquared, debugParticles, 0, blockView, playerLocation, tileEntityLocation, particleSpawner);
|
||||
return canSee ? BlockView.VisibilityResolver.SHOW : BlockView.VisibilityResolver.HIDE;
|
||||
});
|
||||
timings.addTileChecked(checked);
|
||||
}
|
||||
|
||||
private static void logAggregateReport(String aggregateReport) {
|
||||
if (aggregateReport != null) {
|
||||
Logger.info(aggregateReport, 4, AsyncEngine.class);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Counts a skipped tick against the currently configured timing sink.
|
||||
*/
|
||||
private void recordSkippedTick(int threads, long nowNanos) {
|
||||
logAggregateReport(timingStats().recordSkipped(threads, nowNanos));
|
||||
}
|
||||
|
||||
/**
|
||||
* Selects the timing sink from the current debug config.
|
||||
*
|
||||
* @return a collecting {@link TimingStats} while timing diagnostics are enabled, otherwise the
|
||||
* no-op singleton.
|
||||
*/
|
||||
private TimingStats timingStats() {
|
||||
return timingStats(config.getDebugConfig());
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps disabled timing diagnostics allocation-free and starts a fresh collection window when
|
||||
* diagnostics are re-enabled.
|
||||
*
|
||||
* @return the timing sink that should be used for a newly starting tick or skip record.
|
||||
*/
|
||||
private TimingStats timingStats(DebugConfig debugConfig) {
|
||||
return timingStatsSelector.select(debugConfig.recordTimings());
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,11 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.engine;
|
||||
|
||||
public interface AsyncRunner {
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.engine;
|
||||
|
||||
public interface Engine {
|
||||
void tick();
|
||||
void tick(int scheduledTick, long scheduledNanos);
|
||||
}
|
||||
@@ -1,202 +0,0 @@
|
||||
package games.cubi.raycastedantiesp.core.engine;
|
||||
|
||||
import games.cubi.locatables.BlockLocatable;
|
||||
import games.cubi.locatables.Locatable;
|
||||
import games.cubi.logs.Logger;
|
||||
import games.cubi.raycastedantiesp.core.config.ConfigManager;
|
||||
import games.cubi.raycastedantiesp.core.config.DebugConfig;
|
||||
import games.cubi.raycastedantiesp.core.config.raycast.EntityConfig;
|
||||
import games.cubi.raycastedantiesp.core.config.raycast.PlayerConfig;
|
||||
import games.cubi.raycastedantiesp.core.config.raycast.TileEntityConfig;
|
||||
import games.cubi.raycastedantiesp.core.players.PlayerData;
|
||||
import games.cubi.raycastedantiesp.core.players.PlayerRegistry;
|
||||
import games.cubi.raycastedantiesp.core.raycast.ParticleSpawner;
|
||||
import games.cubi.raycastedantiesp.core.raycast.RaycastUtil;
|
||||
import games.cubi.raycastedantiesp.core.view.BlockView;
|
||||
import games.cubi.raycastedantiesp.core.view.EntityView;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.function.IntSupplier;
|
||||
|
||||
public class SimpleEngine implements Engine {
|
||||
private final ConfigManager config;
|
||||
private final ParticleSpawner particleSpawner;
|
||||
private final IntSupplier currentTickSupplier;
|
||||
private final AtomicInteger tickThreadsRunning = new AtomicInteger(0);
|
||||
private final AtomicLong tickNanos = new AtomicLong(0);
|
||||
private final AsyncRunner asyncRunner;
|
||||
|
||||
public SimpleEngine(ConfigManager config, ParticleSpawner particleSpawner, IntSupplier currentTickSupplier, AsyncRunner asyncRunner) {
|
||||
this.config = config;
|
||||
this.particleSpawner = particleSpawner;
|
||||
this.currentTickSupplier = currentTickSupplier;
|
||||
this.asyncRunner = asyncRunner;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void tick() {
|
||||
int threads = config.getEngineConfig().simpleConfig().asyncProcessingThreads();
|
||||
if (threads < 1) threads = 1;
|
||||
|
||||
if (!tickThreadsRunning.compareAndSet(0, threads)) {
|
||||
Logger.warning("RaycastedAntiESP is still ticking from the last tick! Skipping this tick to avoid concurrent modification issues. Current tick: " + currentTickSupplier.getAsInt(), 2, SimpleEngine.class);
|
||||
return;
|
||||
}
|
||||
|
||||
boolean handedOffToSubTick = false;
|
||||
try {
|
||||
tickNanos.set(System.nanoTime());
|
||||
|
||||
final int currentTick = currentTickSupplier.getAsInt();
|
||||
Collection<PlayerData> allPlayers = PlayerRegistry.getInstance().getAllPlayerData();
|
||||
|
||||
EntityConfig entityConfig = config.getEntityConfig();
|
||||
PlayerConfig playerConfig = config.getPlayerConfig();
|
||||
TileEntityConfig tileEntityConfig = config.getTileEntityConfig();
|
||||
DebugConfig debugConfig = config.getDebugConfig();
|
||||
/*
|
||||
Logger.debug("Tick #" + currentTick);
|
||||
if (currentTick % 1200 == 0) {
|
||||
Logger.debug("Printing player data");
|
||||
for (PlayerData playerData : allPlayers) {
|
||||
Logger.debug("Player " + playerData.getPlayerUUID() + " location=" + playerData.ownLocation());
|
||||
Logger.debug("EntityView:" + playerData.entityView().getStringDataForDebugging());
|
||||
Logger.debug("PlayerView:" + playerData.playerView().getStringDataForDebugging());
|
||||
}
|
||||
}*/
|
||||
|
||||
// If only one thread is configured, just use the current async thread to avoid the overhead of scheduling tasks and context switching.
|
||||
if (threads == 1) {
|
||||
handedOffToSubTick = true;
|
||||
subTick(new ArrayList<>(allPlayers), entityConfig, playerConfig, tileEntityConfig, debugConfig, currentTick);
|
||||
return;
|
||||
}
|
||||
|
||||
List<List<PlayerData>> batches = new ArrayList<>(threads);
|
||||
for (int i = 0; i < threads; i++) {
|
||||
batches.add(new ArrayList<>());
|
||||
}
|
||||
|
||||
int index = 0;
|
||||
for (PlayerData playerData : allPlayers) {
|
||||
batches.get(index++ % threads).add(playerData);
|
||||
}
|
||||
|
||||
int scheduledBatches = 0;
|
||||
try {
|
||||
for (List<PlayerData> batch : batches) {
|
||||
asyncRunner.runNow(() -> subTick(batch, entityConfig, playerConfig, tileEntityConfig, debugConfig, currentTick));
|
||||
scheduledBatches++;
|
||||
}
|
||||
handedOffToSubTick = true;
|
||||
}
|
||||
finally {
|
||||
if (scheduledBatches < threads) {
|
||||
tickThreadsRunning.addAndGet(-(threads - scheduledBatches));
|
||||
handedOffToSubTick = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
finally {
|
||||
if (!handedOffToSubTick) {
|
||||
tickThreadsRunning.set(0);
|
||||
Logger.error("An error occurred during tick scheduling before handing off to sub-tick processing. Resetting tickThreadsRunning to 0 to avoid deadlock. Current tick: " + currentTickSupplier.getAsInt(), 2, SimpleEngine.class);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void subTick(List<PlayerData> batch, EntityConfig entityConfig, PlayerConfig playerConfig, TileEntityConfig tileEntityConfig, DebugConfig debugConfig, int currentTick) {
|
||||
try {
|
||||
processTickForPlayers(batch, entityConfig, playerConfig, tileEntityConfig, debugConfig.showDebugParticles(), currentTick);
|
||||
}
|
||||
finally {
|
||||
int threadsRemaining = tickThreadsRunning.decrementAndGet();
|
||||
if (threadsRemaining < 0) {
|
||||
Logger.warning("tickThreadsRunning went below 0! This should never happen. Resetting to 0 to avoid further issues.", 2, SimpleEngine.class);
|
||||
tickThreadsRunning.set(0);
|
||||
}
|
||||
if (threadsRemaining == 0) {
|
||||
long elapsedNanos = System.nanoTime() - tickNanos.get();
|
||||
if (elapsedNanos > 40 * 1000000) {//40 ms
|
||||
Logger.warning("Tick completed in " + (elapsedNanos / 1_000_000.0) + " ms. If you see this warning frequently, consider reducing the raycasting load by adjusting the configuration.", 5, SimpleEngine.class);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void processTickForPlayers(List<PlayerData> playerDataList, EntityConfig entityConfig, PlayerConfig playerConfig, TileEntityConfig tileEntityConfig,
|
||||
boolean debugParticles, int currentTick) {
|
||||
|
||||
for (PlayerData playerData : playerDataList) {
|
||||
playerData.nettyData().markPendingPostSpawnTasksForEviction();
|
||||
if (playerData.hasBypassPermission()) continue;
|
||||
|
||||
BlockView blockView = playerData.blockView();
|
||||
|
||||
Locatable playerLocation = playerData.ownLocation();
|
||||
if (playerLocation == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (entityConfig.enabled()) checkEntities(playerData, playerLocation, entityConfig, debugParticles, blockView, currentTick);
|
||||
if (playerConfig.enabled()) checkPlayers(playerData, playerLocation, playerConfig, debugParticles, blockView, currentTick);
|
||||
if (tileEntityConfig.enabled()) checkTileEntities(playerData, playerLocation, tileEntityConfig, debugParticles, blockView, currentTick);
|
||||
}
|
||||
}
|
||||
|
||||
private void checkEntities(PlayerData player, Locatable playerLocation, EntityConfig entityConfig, boolean debugParticles, BlockView blockView, int currentTick) {
|
||||
EntityView<?> entityView = player.entityView();
|
||||
|
||||
for (UUID entityUUID : entityView.getNeedingRecheck(entityConfig.getVisibleRecheckIntervalTicks(), currentTick)) {
|
||||
boolean wasVisible = entityView.isVisible(entityUUID, currentTick);
|
||||
Locatable entityLocation = entityView.getLocation(entityUUID);
|
||||
if (entityLocation == null) {
|
||||
Logger.debug("SimpleEngine.checkEntities skipped-null-location viewer=" + player.getPlayerUUID()
|
||||
+ " target=" + entityUUID
|
||||
+ " wasVisible=" + wasVisible
|
||||
+ " tick=" + currentTick);
|
||||
continue;
|
||||
}
|
||||
boolean canSee = RaycastUtil.raycast(player, playerLocation, entityLocation, entityConfig.getMaxOccludingCount(), entityConfig.getAlwaysShowRadius(), entityConfig.getRaycastRadius(), debugParticles, blockView, 1, particleSpawner);
|
||||
entityView.setVisibility(entityUUID, canSee, currentTick);
|
||||
}
|
||||
}
|
||||
|
||||
private void checkPlayers(PlayerData player, Locatable playerLocation, PlayerConfig playerConfig, boolean debugParticles, BlockView blockView, int currentTick) {
|
||||
EntityView<?> playerView = player.playerView();
|
||||
|
||||
for (UUID otherPlayerUUID : playerView.getNeedingRecheck(playerConfig.getVisibleRecheckIntervalTicks(), currentTick)) {
|
||||
boolean wasVisible = playerView.isVisible(otherPlayerUUID, currentTick);
|
||||
Locatable otherPlayerLocation = playerView.getLocation(otherPlayerUUID);
|
||||
if (otherPlayerLocation == null) {
|
||||
Logger.debug("SimpleEngine.checkPlayers skipped-null-location viewer=" + player.getPlayerUUID()
|
||||
+ " target=" + otherPlayerUUID
|
||||
+ " wasVisible=" + wasVisible
|
||||
+ " tick=" + currentTick);
|
||||
continue;
|
||||
}
|
||||
boolean canSee = RaycastUtil.raycast(player, playerLocation, otherPlayerLocation, playerConfig.getMaxOccludingCount(), playerConfig.getAlwaysShowRadius(), playerConfig.getRaycastRadius(), debugParticles, blockView, 1, particleSpawner);
|
||||
playerView.setVisibility(otherPlayerUUID, canSee, currentTick);
|
||||
}
|
||||
}
|
||||
|
||||
private void checkTileEntities(PlayerData player, Locatable playerLocation, TileEntityConfig tileEntityConfig, boolean debugParticles, BlockView blockView, int currentTick) {
|
||||
for (BlockLocatable tileEntityLocation : blockView.getNeedingRecheck(tileEntityConfig.getVisibleRecheckIntervalTicks(), currentTick)) {
|
||||
if (tileEntityLocation.world() == null || !tileEntityLocation.world().equals(playerLocation.world())) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (playerLocation.distanceSquared(tileEntityLocation) > (double) tileEntityConfig.getRaycastRadius() * tileEntityConfig.getRaycastRadius()) {
|
||||
blockView.setVisibility(tileEntityLocation, false, currentTick);
|
||||
continue;
|
||||
}
|
||||
boolean canSee = RaycastUtil.raycast(player, playerLocation, tileEntityLocation, tileEntityConfig.getMaxOccludingCount() + 1, tileEntityConfig.getAlwaysShowRadius(), tileEntityConfig.getRaycastRadius(), debugParticles, blockView, 1, particleSpawner);
|
||||
blockView.setVisibility(tileEntityLocation, canSee, currentTick);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.engine;
|
||||
|
||||
public class TickTimingBatch {
|
||||
long entityNanos;
|
||||
long playerNanos;
|
||||
long tileNanos;
|
||||
|
||||
int processedPlayers;
|
||||
int bypassSkippedPlayers;
|
||||
int nullLocationSkippedPlayers;
|
||||
|
||||
int entityChecked;
|
||||
int entityRaycasts;
|
||||
int entityNullTargets;
|
||||
|
||||
int playerChecked;
|
||||
int playerRaycasts;
|
||||
int playerNullTargets;
|
||||
|
||||
int tileChecked;
|
||||
int tileRaycasts;
|
||||
int tileWorldSkipped;
|
||||
int tileRadiusSkipped;
|
||||
|
||||
TickTimingBatch() {}
|
||||
|
||||
public long startBatch() {
|
||||
return System.nanoTime();
|
||||
}
|
||||
|
||||
public long elapsedSince(long startNanos) {
|
||||
return System.nanoTime() - startNanos;
|
||||
}
|
||||
|
||||
public long startEntitySection() {
|
||||
return System.nanoTime();
|
||||
}
|
||||
|
||||
public void finishEntitySection(long startNanos) {
|
||||
entityNanos += Math.max(0, System.nanoTime() - startNanos);
|
||||
}
|
||||
|
||||
public long startPlayerSection() {
|
||||
return System.nanoTime();
|
||||
}
|
||||
|
||||
public void finishPlayerSection(long startNanos) {
|
||||
playerNanos += Math.max(0, System.nanoTime() - startNanos);
|
||||
}
|
||||
|
||||
public long startTileSection() {
|
||||
return System.nanoTime();
|
||||
}
|
||||
|
||||
public void finishTileSection(long startNanos) {
|
||||
tileNanos += Math.max(0, System.nanoTime() - startNanos);
|
||||
}
|
||||
|
||||
public void incrementProcessedPlayers() {
|
||||
processedPlayers++;
|
||||
}
|
||||
|
||||
public void incrementBypassSkippedPlayers() {
|
||||
bypassSkippedPlayers++;
|
||||
}
|
||||
|
||||
public void incrementNullLocationSkippedPlayers() {
|
||||
nullLocationSkippedPlayers++;
|
||||
}
|
||||
|
||||
public void addEntityChecked(int count) {
|
||||
entityChecked += count;
|
||||
}
|
||||
|
||||
public void incrementEntityRaycasts() {
|
||||
entityRaycasts++;
|
||||
}
|
||||
|
||||
public void addPlayerChecked(int count) {
|
||||
playerChecked += count;
|
||||
}
|
||||
|
||||
public void incrementPlayerRaycasts() {
|
||||
playerRaycasts++;
|
||||
}
|
||||
|
||||
public void addTileChecked(int count) {
|
||||
tileChecked += count;
|
||||
}
|
||||
|
||||
public void incrementTileWorldSkipped() {
|
||||
tileWorldSkipped++;
|
||||
}
|
||||
|
||||
public void incrementTileRadiusSkipped() {
|
||||
tileRadiusSkipped++;
|
||||
}
|
||||
|
||||
public void incrementTileRaycasts() {
|
||||
tileRaycasts++;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.engine;
|
||||
|
||||
public class TickTimingBatchNoOp extends TickTimingBatch {
|
||||
public static final TickTimingBatchNoOp INSTANCE = new TickTimingBatchNoOp();
|
||||
public long startBatch() {return 0;}
|
||||
public long elapsedSince(long startNanos) {return 0;}
|
||||
public long startEntitySection() {return 0;}
|
||||
public void finishEntitySection(long startNanos) {}
|
||||
public long startPlayerSection() {return 0;}
|
||||
public void finishPlayerSection(long startNanos) {}
|
||||
public long startTileSection() {return 0;}
|
||||
public void finishTileSection(long startNanos) {}
|
||||
public void incrementProcessedPlayers() {}
|
||||
public void incrementBypassSkippedPlayers() {}
|
||||
public void incrementNullLocationSkippedPlayers() {}
|
||||
public void addEntityChecked(int count) {}
|
||||
public void incrementEntityNullTargets() {}
|
||||
public void incrementEntityRaycasts() {}
|
||||
public void addPlayerChecked(int count) {}
|
||||
public void incrementPlayerNullTargets() {}
|
||||
public void incrementPlayerRaycasts() {}
|
||||
public void addTileChecked(int count) {}
|
||||
public void incrementTileWorldSkipped() {}
|
||||
public void incrementTileRadiusSkipped() {}
|
||||
public void incrementTileRaycasts() {}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.engine;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
final class TickTimingFormatter {
|
||||
private TickTimingFormatter() {}
|
||||
|
||||
static String formatMillis(long nanos) {
|
||||
return String.format(Locale.ROOT, "%.3f", nanos / 1_000_000.0);
|
||||
}
|
||||
|
||||
static String formatSeconds(long nanos) {
|
||||
return String.format(Locale.ROOT, "%.3f", nanos / 1_000_000_000.0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.engine;
|
||||
|
||||
record TickTimingSnapshot(
|
||||
int scheduledTick,
|
||||
int startTick,
|
||||
int completionTick,
|
||||
int threads,
|
||||
int registeredPlayers,
|
||||
long queueNanos,
|
||||
long wallNanos,
|
||||
long maxBatchNanos,
|
||||
long entityNanos,
|
||||
long playerNanos,
|
||||
long tileNanos,
|
||||
int processedPlayers,
|
||||
int bypassSkippedPlayers,
|
||||
int nullLocationSkippedPlayers,
|
||||
int entityChecked,
|
||||
int entityRaycasts,
|
||||
int playerChecked,
|
||||
int playerRaycasts,
|
||||
int tileChecked,
|
||||
int tileRaycasts,
|
||||
int tileWorldSkipped,
|
||||
int tileRadiusSkipped
|
||||
) {
|
||||
String toSlowTickMessage() {
|
||||
return "Tick completed slowly."
|
||||
+ " scheduledTick=" + scheduledTick
|
||||
+ " startTick=" + startTick
|
||||
+ " completionTick=" + completionTick
|
||||
+ " threads=" + threads
|
||||
+ " wallTimeTaken=" + TickTimingFormatter.formatMillis(wallNanos) + "ms"
|
||||
+ " schedulerWait=" + TickTimingFormatter.formatMillis(queueNanos) + "ms"
|
||||
+ " slowestWorkerBatch=" + TickTimingFormatter.formatMillis(maxBatchNanos) + "ms"
|
||||
+ " entityProcessingTime=" + TickTimingFormatter.formatMillis(entityNanos) + "ms"
|
||||
+ " playerProcessingTime=" + TickTimingFormatter.formatMillis(playerNanos) + "ms"
|
||||
+ " tileProcessingTime=" + TickTimingFormatter.formatMillis(tileNanos) + "ms"
|
||||
+ " playerCount=" + registeredPlayers
|
||||
+ " processedPlayers=" + processedPlayers
|
||||
+ " bypassSkippedPlayers=" + bypassSkippedPlayers
|
||||
+ " nullLocationSkippedPlayers=" + nullLocationSkippedPlayers
|
||||
+ " entityRecheckCandidates=" + entityChecked
|
||||
+ " entityRaycasts=" + entityRaycasts
|
||||
+ " playerRecheckCandidates=" + playerChecked
|
||||
+ " playerRaycasts=" + playerRaycasts
|
||||
+ " tileRecheckCandidates=" + tileChecked
|
||||
+ " tileRaycasts=" + tileRaycasts
|
||||
+ " tileWorldSkipped=" + tileWorldSkipped
|
||||
+ " tileRadiusSkipped=" + tileRadiusSkipped;
|
||||
}
|
||||
|
||||
String toSlowestSummary() {
|
||||
return "scheduledTick=" + scheduledTick
|
||||
+ ", startedAtTick=" + startTick
|
||||
+ ", totalWallTime=" + TickTimingFormatter.formatMillis(wallNanos) + " ms"
|
||||
+ ", schedulerWait=" + TickTimingFormatter.formatMillis(queueNanos) + " ms"
|
||||
+ ", slowestWorkerBatch=" + TickTimingFormatter.formatMillis(maxBatchNanos) + " ms"
|
||||
+ ", processingTime(entity/player/tile)=" + TickTimingFormatter.formatMillis(entityNanos) + "/" + TickTimingFormatter.formatMillis(playerNanos) + "/" + TickTimingFormatter.formatMillis(tileNanos) + " ms"
|
||||
+ ", raycasts(entity/player/tile)=" + entityRaycasts + "/" + playerRaycasts + "/" + tileRaycasts;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.engine;
|
||||
|
||||
final class TickTimings {
|
||||
private final int scheduledTick;
|
||||
private final long scheduledNanos;
|
||||
private final int startTick;
|
||||
private final long startNanos;
|
||||
private final int threads;
|
||||
private final int registeredPlayers;
|
||||
|
||||
private long maxBatchNanos;
|
||||
private long entityNanos;
|
||||
private long playerNanos;
|
||||
private long tileNanos;
|
||||
|
||||
private int processedPlayers;
|
||||
private int bypassSkippedPlayers;
|
||||
private int nullLocationSkippedPlayers;
|
||||
|
||||
private int entityChecked;
|
||||
private int entityRaycasts;
|
||||
|
||||
private int playerChecked;
|
||||
private int playerRaycasts;
|
||||
|
||||
private int tileChecked;
|
||||
private int tileRaycasts;
|
||||
private int tileWorldSkipped;
|
||||
private int tileRadiusSkipped;
|
||||
|
||||
TickTimings(int scheduledTick, long scheduledNanos, int startTick, long startNanos, int threads, int registeredPlayers) {
|
||||
this.scheduledTick = scheduledTick;
|
||||
this.scheduledNanos = scheduledNanos;
|
||||
this.startTick = startTick;
|
||||
this.startNanos = startNanos;
|
||||
this.threads = threads;
|
||||
this.registeredPlayers = registeredPlayers;
|
||||
}
|
||||
|
||||
synchronized void recordBatch(TickTimingBatch batch, long batchNanos) {
|
||||
// Batch-local primitive counters avoid atomic writes in the raycast loop, where the work being measured is sub-microsecond.
|
||||
maxBatchNanos = Math.max(maxBatchNanos, Math.max(0, batchNanos));
|
||||
entityNanos += batch.entityNanos;
|
||||
playerNanos += batch.playerNanos;
|
||||
tileNanos += batch.tileNanos;
|
||||
|
||||
processedPlayers += batch.processedPlayers;
|
||||
bypassSkippedPlayers += batch.bypassSkippedPlayers;
|
||||
nullLocationSkippedPlayers += batch.nullLocationSkippedPlayers;
|
||||
|
||||
entityChecked += batch.entityChecked;
|
||||
entityRaycasts += batch.entityRaycasts;
|
||||
|
||||
playerChecked += batch.playerChecked;
|
||||
playerRaycasts += batch.playerRaycasts;
|
||||
|
||||
tileChecked += batch.tileChecked;
|
||||
tileRaycasts += batch.tileRaycasts;
|
||||
tileWorldSkipped += batch.tileWorldSkipped;
|
||||
tileRadiusSkipped += batch.tileRadiusSkipped;
|
||||
}
|
||||
|
||||
synchronized TickTimingSnapshot snapshot(int completionTick, long completionNanos) {
|
||||
return new TickTimingSnapshot(
|
||||
scheduledTick,
|
||||
startTick,
|
||||
completionTick,
|
||||
threads,
|
||||
registeredPlayers,
|
||||
Math.max(0, startNanos - scheduledNanos),
|
||||
Math.max(0, completionNanos - scheduledNanos),
|
||||
maxBatchNanos,
|
||||
entityNanos,
|
||||
playerNanos,
|
||||
tileNanos,
|
||||
processedPlayers,
|
||||
bypassSkippedPlayers,
|
||||
nullLocationSkippedPlayers,
|
||||
entityChecked,
|
||||
entityRaycasts,
|
||||
playerChecked,
|
||||
playerRaycasts,
|
||||
tileChecked,
|
||||
tileRaycasts,
|
||||
tileWorldSkipped,
|
||||
tileRadiusSkipped
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.engine;
|
||||
|
||||
import it.unimi.dsi.fastutil.longs.LongArrayList;
|
||||
import it.unimi.dsi.fastutil.longs.LongComparators;
|
||||
import it.unimi.dsi.fastutil.longs.LongIterator;
|
||||
import it.unimi.dsi.fastutil.longs.LongList;
|
||||
|
||||
public class TimingStats {
|
||||
private static final long REPORT_INTERVAL_NANOS = 30_000_000_000L;
|
||||
|
||||
private final LongArrayList wallSamples = new LongArrayList();
|
||||
private final LongArrayList schedulerWaitSamples = new LongArrayList();
|
||||
private final LongArrayList slowestWorkerBatchSamples = new LongArrayList();
|
||||
private final LongArrayList entityWorkerSamples = new LongArrayList();
|
||||
private final LongArrayList playerWorkerSamples = new LongArrayList();
|
||||
private final LongArrayList tileWorkerSamples = new LongArrayList();
|
||||
|
||||
private long intervalStartNanos = 0;
|
||||
private long nextReportNanos = 0;
|
||||
private int completedTicks = 0;
|
||||
private int skippedTicks = 0;
|
||||
private int lastThreads = 0;
|
||||
|
||||
private long entityRaycastsTotal = 0;
|
||||
private long playerRaycastsTotal = 0;
|
||||
private long tileRaycastsTotal = 0;
|
||||
|
||||
private TickTimingSnapshot slowestTick = null;
|
||||
|
||||
/**
|
||||
* Drops the current reporting window so later samples do not mix with data collected under a previous timing configuration.
|
||||
*/
|
||||
synchronized void reset() {
|
||||
wallSamples.clear();
|
||||
schedulerWaitSamples.clear();
|
||||
slowestWorkerBatchSamples.clear();
|
||||
entityWorkerSamples.clear();
|
||||
playerWorkerSamples.clear();
|
||||
tileWorkerSamples.clear();
|
||||
intervalStartNanos = 0;
|
||||
nextReportNanos = 0;
|
||||
completedTicks = 0;
|
||||
skippedTicks = 0;
|
||||
lastThreads = 0;
|
||||
entityRaycastsTotal = 0;
|
||||
playerRaycastsTotal = 0;
|
||||
tileRaycastsTotal = 0;
|
||||
slowestTick = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a completed tick to the active reporting window.
|
||||
*
|
||||
* @return a formatted aggregate report when the reporting interval has elapsed; otherwise null.
|
||||
*/
|
||||
synchronized String recordCompleted(TickTimingSnapshot snapshot, long nowNanos) {
|
||||
ensureInterval(nowNanos);
|
||||
completedTicks++;
|
||||
lastThreads = snapshot.threads();
|
||||
wallSamples.add(snapshot.wallNanos());
|
||||
schedulerWaitSamples.add(snapshot.queueNanos());
|
||||
slowestWorkerBatchSamples.add(snapshot.maxBatchNanos());
|
||||
entityWorkerSamples.add(snapshot.entityNanos());
|
||||
playerWorkerSamples.add(snapshot.playerNanos());
|
||||
tileWorkerSamples.add(snapshot.tileNanos());
|
||||
|
||||
entityRaycastsTotal += snapshot.entityRaycasts();
|
||||
playerRaycastsTotal += snapshot.playerRaycasts();
|
||||
tileRaycastsTotal += snapshot.tileRaycasts();
|
||||
|
||||
if (slowestTick == null || snapshot.wallNanos() > slowestTick.wallNanos()) {
|
||||
slowestTick = snapshot;
|
||||
}
|
||||
return reportIfDue(nowNanos);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a skipped tick attempt to the active reporting window without creating worker timing samples.
|
||||
*
|
||||
* @return a formatted aggregate report when the reporting interval has elapsed; otherwise null.
|
||||
*/
|
||||
synchronized String recordSkipped(int threads, long nowNanos) {
|
||||
ensureInterval(nowNanos);
|
||||
skippedTicks++;
|
||||
if (threads != -1) lastThreads = threads;
|
||||
return reportIfDue(nowNanos);
|
||||
}
|
||||
|
||||
private void ensureInterval(long nowNanos) {
|
||||
if (nextReportNanos == 0) {
|
||||
intervalStartNanos = nowNanos;
|
||||
nextReportNanos = nowNanos + REPORT_INTERVAL_NANOS;
|
||||
}
|
||||
}
|
||||
|
||||
private String reportIfDue(long nowNanos) {
|
||||
if (nextReportNanos == 0 || nowNanos < nextReportNanos) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String report = buildReport(nowNanos);
|
||||
reset();
|
||||
intervalStartNanos = nowNanos;
|
||||
nextReportNanos = nowNanos + REPORT_INTERVAL_NANOS;
|
||||
return report;
|
||||
}
|
||||
|
||||
private String buildReport(long nowNanos) {
|
||||
long intervalNanos = Math.max(1, nowNanos - intervalStartNanos);
|
||||
String slowestSummary = slowestTick == null ? "n/a" : slowestTick.toSlowestSummary();
|
||||
return "Raycasted Anti-ESP tick timing summary for the last " + TickTimingFormatter.formatSeconds(intervalNanos) + "s:\n"
|
||||
+ "Completed Anti-ESP ticks: " + completedTicks + "\n"
|
||||
+ "Skipped tick attempts: " + skippedTicks + "\n"
|
||||
+ "Configured worker threads: " + lastThreads + "\n\n"
|
||||
+ "Total time from server tick event to Anti-ESP completion (avg / p50 / p95 / max): " + formatStats(wallSamples) + "\n"
|
||||
+ "Time spent waiting in the async scheduler before Anti-ESP work started (avg / p50 / p95 / max): " + formatStats(schedulerWaitSamples) + "\n"
|
||||
+ "Slowest worker batch processing time after work started (avg / p50 / p95 / max): " + formatStats(slowestWorkerBatchSamples) + "\n\n"
|
||||
+ "Worker section times are summed across worker batches for multi-threaded ticks, not wall-clock critical-path time.\n"
|
||||
+ "Worker time spent checking entities per completed tick (avg / p50 / p95 / max): " + formatStats(entityWorkerSamples) + "\n"
|
||||
+ "Worker time spent checking players per completed tick (avg / p50 / p95 / max): " + formatStats(playerWorkerSamples) + "\n"
|
||||
+ "Worker time spent checking tile entities per completed tick (avg / p50 / p95 / max): " + formatStats(tileWorkerSamples) + "\n\n"
|
||||
+ "Total raycasts performed, entity / player / tile: " + entityRaycastsTotal + " / " + playerRaycastsTotal + " / " + tileRaycastsTotal + "\n"
|
||||
+ "Slowest tick in this interval: " + slowestSummary;
|
||||
}
|
||||
|
||||
private String formatStats(LongList samples) {
|
||||
if (samples.isEmpty()) {
|
||||
return "n/a";
|
||||
}
|
||||
LongArrayList sorted = new LongArrayList(samples);
|
||||
sorted.sort(LongComparators.NATURAL_COMPARATOR);
|
||||
long total = 0;
|
||||
LongIterator iterator = sorted.longIterator();
|
||||
while (iterator.hasNext()) {
|
||||
total += iterator.nextLong();
|
||||
}
|
||||
int sampleCount = sorted.size();
|
||||
return TickTimingFormatter.formatMillis(total / sorted.size())
|
||||
+ " / " + TickTimingFormatter.formatMillis(percentile(sorted, 0.50))
|
||||
+ " / " + TickTimingFormatter.formatMillis(percentile(sorted, 0.95))
|
||||
+ " / " + TickTimingFormatter.formatMillis(sorted.getLong(sampleCount - 1))
|
||||
+ " ms";
|
||||
}
|
||||
|
||||
private long percentile(LongList sorted, double percentile) {
|
||||
int index = Math.min(sorted.size() - 1, Math.max(0, (int) Math.ceil(sorted.size() * percentile) - 1));
|
||||
return sorted.getLong(index);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.engine;
|
||||
|
||||
public class TimingStatsNoOp extends TimingStats {
|
||||
static final TimingStatsNoOp INSTANCE = new TimingStatsNoOp();
|
||||
|
||||
private TimingStatsNoOp() {}
|
||||
|
||||
@Override
|
||||
void reset() {}
|
||||
|
||||
@Override
|
||||
String recordCompleted(TickTimingSnapshot snapshot, long nowNanos) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
String recordSkipped(int threads, long nowNanos) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.engine;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
/** Lock-free selection of the timing sink used by a newly starting tick or skip record. */
|
||||
final class TimingStatsSelector {
|
||||
private final AtomicReference<TimingStats> current = new AtomicReference<>(TimingStatsNoOp.INSTANCE);
|
||||
|
||||
TimingStats select(boolean enabled) {
|
||||
if (!enabled) {
|
||||
current.set(TimingStatsNoOp.INSTANCE);
|
||||
return TimingStatsNoOp.INSTANCE;
|
||||
}
|
||||
|
||||
TimingStats existing = current.get();
|
||||
if (existing != TimingStatsNoOp.INSTANCE) {
|
||||
return existing;
|
||||
}
|
||||
|
||||
TimingStats created = new TimingStats();
|
||||
TimingStats witness = current.compareAndExchange(TimingStatsNoOp.INSTANCE, created);
|
||||
return witness == TimingStatsNoOp.INSTANCE ? created : witness;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.entity;
|
||||
|
||||
import games.cubi.utils.sets.CopyOnWriteMTIntSet;
|
||||
|
||||
/**
|
||||
* Global registry of entity IDs which RaycastedAntiESP must ignore.
|
||||
*/
|
||||
public final class EntityBypassRegistry {
|
||||
private static final CopyOnWriteMTIntSet BYPASSED_ENTITY_IDS = CopyOnWriteMTIntSet.get();
|
||||
// Technically, (26.2+) Minecraft only guarantees that an entity ID corresponds to one-and-only-one entity within a single world, and entities in different worlds can have the same ID.
|
||||
// (26.1.2-) Minecraft does not guarantee that an entity ID is unique.
|
||||
// However, this requires the int id counter to overflow from Integer.MAX_VALUE all the way back to 0. This is unlikely to occur, and even if it does occur, it is unlikely that the original entities are still alive.
|
||||
private EntityBypassRegistry() {
|
||||
}
|
||||
|
||||
public static void addEntity(int entityID) {
|
||||
BYPASSED_ENTITY_IDS.add(entityID);
|
||||
}
|
||||
|
||||
/**
|
||||
* For use when an entity is despawned/killed, or in other words completely gone from the server.
|
||||
*/
|
||||
public static boolean markEntityDespawned(int entityID) {
|
||||
return BYPASSED_ENTITY_IDS.remove(entityID);
|
||||
}
|
||||
|
||||
public static boolean isBypassed(int entityID) {
|
||||
return BYPASSED_ENTITY_IDS.contains(entityID);
|
||||
}
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
package games.cubi.raycastedantiesp.core.locatables;
|
||||
|
||||
import games.cubi.locatables.MutableLocatable;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Per-player platform-independent representation of an entity
|
||||
*/
|
||||
public interface EntityLocatable<EntityType, PacketReplayData> extends MutableLocatable {
|
||||
|
||||
int entityID();
|
||||
|
||||
UUID entityUUID();
|
||||
|
||||
boolean visible();
|
||||
EntityLocatable<?, ?> setVisible(boolean visible);
|
||||
|
||||
int lastChecked();
|
||||
EntityLocatable<?, ?> setLastChecked(int lastChecked);
|
||||
|
||||
boolean clientVisible();
|
||||
EntityLocatable<?, ?> setClientVisible(boolean clientVisible);
|
||||
|
||||
boolean isSelfEntity();
|
||||
|
||||
float yaw();
|
||||
EntityLocatable<?, ?> setYaw(float yaw);
|
||||
|
||||
float pitch();
|
||||
EntityLocatable<?, ?> setPitch(float pitch);
|
||||
|
||||
float headYaw();
|
||||
EntityLocatable<?, ?> setHeadYaw(float headYaw);
|
||||
|
||||
double velocityX();
|
||||
double velocityY();
|
||||
double velocityZ();
|
||||
EntityLocatable<?, ?> setVelocity(double velocityX, double velocityY, double velocityZ);
|
||||
|
||||
boolean onGround();
|
||||
EntityLocatable<?, ?> setOnGround(boolean onGround);
|
||||
|
||||
EntityType entityType();
|
||||
|
||||
int entityData();
|
||||
EntityLocatable<?, ?> setEntityData(int entityData);
|
||||
|
||||
int[] passengerIDs();
|
||||
EntityLocatable<?, ?> setPassengerIDs(int[] passengerIDs);
|
||||
|
||||
void setVehicleID(int vehicleID);
|
||||
int vehicleID();
|
||||
|
||||
void addLeashedEntity(int leashedEntityID);
|
||||
void removeLeashedEntity(int leashedEntityID);
|
||||
int@Nullable[] leashedEntityIDsOrNull();
|
||||
int leashingEntity();
|
||||
void setLeashingEntity(int leashingEntityID);
|
||||
|
||||
PacketReplayData packetReplayData();
|
||||
EntityLocatable<?, ?> setPacketReplayData(PacketReplayData packetReplayData);
|
||||
|
||||
/**
|
||||
* For use when the player disconnects, clears all data.
|
||||
*/
|
||||
void clear();
|
||||
|
||||
default <T> T cast() {
|
||||
return (T) this;
|
||||
}
|
||||
}
|
||||
-420
@@ -1,420 +0,0 @@
|
||||
package games.cubi.raycastedantiesp.core.locatables;
|
||||
|
||||
import games.cubi.locatables.Locatable;
|
||||
import games.cubi.locatables.MutableLocatable;
|
||||
import games.cubi.locatables.implementations.MutableLocatableImpl;
|
||||
import games.cubi.raycastedantiesp.core.players.PlayerData;
|
||||
import games.cubi.raycastedantiesp.core.utils.Clearable;
|
||||
import games.cubi.raycastedantiesp.core.utils.IntArrayList;
|
||||
import games.cubi.raycastedantiesp.core.utils.IntArrayListMarker;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Designed for use with netty-based systems, where entity data updates only ever come from one thread, but reads may come from multiple threads. This is however not enforced, and must be kept in mind when using this class.
|
||||
* A representation of an entity for a specific player.
|
||||
*/
|
||||
public abstract class NettyEntityLocatable<EntityType, PacketReplayData extends Clearable> implements EntityLocatable<EntityType, PacketReplayData> {
|
||||
// immutable fields
|
||||
private final int entityID;
|
||||
private final UUID entityUUID;
|
||||
private final boolean isSelfEntity;
|
||||
private final EntityType entityType;
|
||||
private final PlayerData owningPlayer;
|
||||
|
||||
// Netty mutatable fields. Should NEVER be mutated from the engine thread, but reads are fine.
|
||||
private volatile UUID world;
|
||||
private volatile double x, y, z;
|
||||
private volatile float yaw;
|
||||
private volatile float pitch;
|
||||
private volatile float headYaw;
|
||||
private volatile double velocityX;
|
||||
private volatile double velocityY;
|
||||
private volatile double velocityZ;
|
||||
private volatile boolean onGround = true;
|
||||
private int@IntArrayListMarker[] leashedIDs;
|
||||
private int leasherID = NO_LEASHER;
|
||||
private int[] passengerIDs;
|
||||
private int vehicleID = NO_VEHICLE;
|
||||
|
||||
|
||||
private volatile int entityData;
|
||||
private volatile PacketReplayData packetReplayData; // For use storing the packets we can't be bothered to directly store, with all cached packets being sent back out to the client when entity is visible again.
|
||||
|
||||
// mutatable by several threads (engine and netty), may need to investigate atomic updates for thread safety
|
||||
private volatile int lastChecked;
|
||||
private volatile boolean clientVisible = true;
|
||||
|
||||
// engine thread mutable, reads from netty and engine.
|
||||
private volatile boolean visible;
|
||||
|
||||
public NettyEntityLocatable(PlayerData owningPlayer, UUID world, double x, double y, double z, int entityID, UUID entityUUID, boolean isSelfEntity, EntityType entityType, boolean visible) {
|
||||
this.world = world;
|
||||
this.x = x; this.y = y; this.z = z;
|
||||
|
||||
this.entityID = entityID;
|
||||
this.entityUUID = entityUUID;
|
||||
this.isSelfEntity = isSelfEntity;
|
||||
this.entityType = entityType;
|
||||
|
||||
this.visible = visible;
|
||||
|
||||
this.owningPlayer = owningPlayer;
|
||||
}
|
||||
|
||||
// For creating the self entity, where we don't have access to the world or position. Always visible.
|
||||
protected NettyEntityLocatable(PlayerData selfData, int selfPlayerID, UUID ownUUID) {
|
||||
entityID = selfPlayerID;
|
||||
entityUUID = ownUUID;
|
||||
owningPlayer = selfData;
|
||||
isSelfEntity = true;
|
||||
entityType = null;
|
||||
clientVisible = true;
|
||||
visible = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public LocatableType getType() {
|
||||
return LocatableType.NettyEntity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int entityID() {
|
||||
return entityID;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID entityUUID() {
|
||||
return entityUUID;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean visible() {
|
||||
return visible;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wherever possible, effort should be made to only call this from the engine thread, for thread safety reasons.
|
||||
*/
|
||||
@Override
|
||||
public EntityLocatable<?, ?> setVisible(boolean visible) {
|
||||
this.visible = visible;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int lastChecked() {
|
||||
return lastChecked;
|
||||
}
|
||||
// todo it may be that this is only ever set by the engine thread? If so, just volatile annotation may be safe enough, as no two engine threads should update a single player at the same time (add guard lock for this)
|
||||
@Override
|
||||
public EntityLocatable<?, ?> setLastChecked(int lastChecked) {
|
||||
this.lastChecked = lastChecked;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean clientVisible() {
|
||||
return clientVisible;
|
||||
}
|
||||
|
||||
@Override
|
||||
public EntityLocatable<?, ?> setClientVisible(boolean clientVisible) {
|
||||
this.clientVisible = clientVisible;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSelfEntity() {
|
||||
return isSelfEntity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float yaw() {
|
||||
return yaw;
|
||||
}
|
||||
|
||||
/**
|
||||
* THIS METHOD IS ONLY SAFE TO CALL FROM THE PLAYER's NETTY THREAD
|
||||
*/
|
||||
@Override
|
||||
public EntityLocatable<?, ?> setYaw(float yaw) {
|
||||
this.yaw = yaw;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float pitch() {
|
||||
return pitch;
|
||||
}
|
||||
|
||||
/**
|
||||
* THIS METHOD IS ONLY SAFE TO CALL FROM THE PLAYER's NETTY THREAD
|
||||
*/
|
||||
@Override
|
||||
public EntityLocatable<?, ?> setPitch(float pitch) {
|
||||
this.pitch = pitch;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float headYaw() {
|
||||
return headYaw;
|
||||
}
|
||||
|
||||
/**
|
||||
* THIS METHOD IS ONLY SAFE TO CALL FROM THE PLAYER's NETTY THREAD
|
||||
*/
|
||||
@Override
|
||||
public EntityLocatable<?, ?> setHeadYaw(float headYaw) {
|
||||
this.headYaw = headYaw;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double velocityX() {
|
||||
return velocityX;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double velocityY() {
|
||||
return velocityY;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double velocityZ() {
|
||||
return velocityZ;
|
||||
}
|
||||
|
||||
/**
|
||||
* THIS METHOD IS ONLY SAFE TO CALL FROM THE PLAYER's NETTY THREAD
|
||||
*/
|
||||
@Override
|
||||
public EntityLocatable<?, ?> setVelocity(double velocityX, double velocityY, double velocityZ) {
|
||||
this.velocityX = velocityX;
|
||||
this.velocityY = velocityY;
|
||||
this.velocityZ = velocityZ;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onGround() {
|
||||
return onGround;
|
||||
}
|
||||
|
||||
/**
|
||||
* THIS METHOD IS ONLY SAFE TO CALL FROM THE PLAYER's NETTY THREAD
|
||||
*/
|
||||
@Override
|
||||
public EntityLocatable<?, ?> setOnGround(boolean onGround) {
|
||||
this.onGround = onGround;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public EntityType entityType() {
|
||||
return entityType;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int entityData() {
|
||||
return entityData;
|
||||
}
|
||||
|
||||
@Override
|
||||
public EntityLocatable<?, ?> setEntityData(int entityData) {
|
||||
this.entityData = entityData;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int[] passengerIDs() {
|
||||
return passengerIDs == null ? null : passengerIDs.clone();
|
||||
}
|
||||
|
||||
@Override
|
||||
public EntityLocatable<?, ?> setPassengerIDs(int[] passengerIDs) {
|
||||
this.passengerIDs = passengerIDs == null ? new int[0] : passengerIDs.clone();
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setVehicleID(int vehicleID) {
|
||||
this.vehicleID = vehicleID;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int vehicleID() {
|
||||
return vehicleID;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addLeashedEntity(int leashedEntityID) {
|
||||
leashedIDs = IntArrayList.add(leashedIDs, leashedEntityID);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeLeashedEntity(int leashedEntityID) {
|
||||
leashedIDs = IntArrayList.remove(leashedIDs, leashedEntityID);
|
||||
}
|
||||
|
||||
public int@Nullable[] leashedEntityIDsOrNull() {
|
||||
return IntArrayList.getCopyOrNull(leashedIDs);
|
||||
}
|
||||
|
||||
public static final int NO_VEHICLE = -1;
|
||||
public static final int NO_LEASHER = -2;
|
||||
|
||||
@Override
|
||||
public int leashingEntity() {
|
||||
return leasherID;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setLeashingEntity(int leashingEntityID) {
|
||||
this.leasherID = leashingEntityID;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PacketReplayData packetReplayData() {
|
||||
return packetReplayData;
|
||||
}
|
||||
|
||||
@Override
|
||||
public EntityLocatable<?, ?> setPacketReplayData(PacketReplayData packetReplayData) {
|
||||
this.packetReplayData = packetReplayData;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double x() {
|
||||
return x;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double y() {
|
||||
return y;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double z() {
|
||||
return z;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID world() {
|
||||
return world;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MutableLocatable clonePlainAndCentreIfBlockLocation() {
|
||||
return new MutableLocatableImpl(world, x, y, z);
|
||||
}
|
||||
|
||||
@Override
|
||||
public MutableLocatable setX(double x) {
|
||||
this.x = x;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MutableLocatable setY(double y) {
|
||||
this.y = y;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MutableLocatable setZ(double z) {
|
||||
this.z = z;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MutableLocatable setWorld(UUID world) {
|
||||
this.world = world;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MutableLocatable set(double x, double y, double z) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
this.z = z;
|
||||
updatePassengerPositions();
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MutableLocatable add(double x, double y, double z) {
|
||||
this.x += x;
|
||||
this.y += y;
|
||||
this.z += z;
|
||||
updatePassengerPositions();
|
||||
return this;
|
||||
}
|
||||
|
||||
// This does not correctly set the passenger position, as the passenger is above the vehicle. It is however close enough to minimise annoying interpolation on show.
|
||||
private void updatePassengerPositions() {
|
||||
if (passengerIDs == null || passengerIDs.length == 0) return;
|
||||
for (int passengerID : passengerIDs) {
|
||||
NettyEntityLocatable<?, ?> passenger = owningPlayer.entityFromID(passengerID);
|
||||
if (passenger != null) {
|
||||
passenger.setVehicleID(entityID);
|
||||
passenger.setWorld(world);
|
||||
passenger.setX(x);
|
||||
passenger.setY(y);
|
||||
passenger.setZ(z);
|
||||
passenger.updatePassengerPositions();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
world = null;
|
||||
packetReplayData.clear();
|
||||
packetReplayData = null;
|
||||
|
||||
vehicleID = NO_VEHICLE;
|
||||
passengerIDs = null;
|
||||
leashedIDs = null;
|
||||
leasherID = NO_LEASHER;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
return isEqualTo(other);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return makeHash();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "NettyEntityLocatable{" +
|
||||
"entityID=" + entityID +
|
||||
", entityUUID=" + entityUUID +
|
||||
", isSelfEntity=" + isSelfEntity +
|
||||
", entityType=" + entityType +
|
||||
", world=" + world +
|
||||
", x=" + x +
|
||||
", y=" + y +
|
||||
", z=" + z +
|
||||
", yaw=" + yaw +
|
||||
", pitch=" + pitch +
|
||||
", headYaw=" + headYaw +
|
||||
", velocityX=" + velocityX +
|
||||
", velocityY=" + velocityY +
|
||||
", velocityZ=" + velocityZ +
|
||||
", onGround=" + onGround +
|
||||
", leashedIDs=" + (leashedIDs == null ? null : IntArrayList.toString(leashedIDs)) +
|
||||
", leasherID=" + leasherID +
|
||||
", passengerIDs=" + (passengerIDs == null ? null : IntArrayList.toString(passengerIDs)) +
|
||||
", vehicleID=" + vehicleID +
|
||||
", entityData=" + entityData +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
@@ -1,129 +0,0 @@
|
||||
package games.cubi.raycastedantiesp.core.locatables;
|
||||
|
||||
import games.cubi.locatables.Locatable;
|
||||
import games.cubi.raycastedantiesp.core.utils.Clearable;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public abstract class NettyTileEntity<PacketReplayData extends Clearable> implements TileEntityLocatable<PacketReplayData> {
|
||||
private volatile boolean visible;
|
||||
private volatile int lastChecked;
|
||||
private volatile int blockID;
|
||||
private volatile PacketReplayData extraData;
|
||||
|
||||
private final int x, y, z;
|
||||
private final UUID world;
|
||||
|
||||
public NettyTileEntity(Locatable location, boolean visible, int lastChecked, int blockID) {
|
||||
x = location.blockX();
|
||||
y = location.blockY();
|
||||
z = location.blockZ();
|
||||
world = location.world();
|
||||
|
||||
this.blockID = blockID;
|
||||
|
||||
this.visible = visible;
|
||||
this.lastChecked = lastChecked;
|
||||
}
|
||||
|
||||
public NettyTileEntity(UUID world, int x, int y, int z, boolean visible, int blockID) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
this.z = z;
|
||||
this.visible = visible;
|
||||
this.blockID = blockID;
|
||||
this.world = world;
|
||||
lastChecked = 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean visible() {
|
||||
return visible;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TileEntityLocatable<PacketReplayData> setVisible(boolean visible) {
|
||||
this.visible = visible;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int lastChecked() {
|
||||
return lastChecked;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TileEntityLocatable<PacketReplayData> setLastChecked(int lastChecked) {
|
||||
this.lastChecked = lastChecked;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int blockID() {
|
||||
return blockID;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TileEntityLocatable<PacketReplayData> setBlockID(int blockID) {
|
||||
this.blockID = blockID;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PacketReplayData extraData() {
|
||||
return extraData;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TileEntityLocatable<PacketReplayData> setExtraData(PacketReplayData extraData) {
|
||||
this.extraData = extraData;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int blockX() {
|
||||
return x;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int blockY() {
|
||||
return y;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int blockZ() {
|
||||
return z;
|
||||
}
|
||||
|
||||
@Override
|
||||
public LocatableType getType() {
|
||||
return LocatableType.NettyTileEntity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID world() {
|
||||
return world;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
if (extraData != null) {
|
||||
extraData.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
return isEqualTo(other);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return blockHash();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return toStringForm();
|
||||
}
|
||||
}
|
||||
-30
@@ -1,30 +0,0 @@
|
||||
package games.cubi.raycastedantiesp.core.locatables;
|
||||
|
||||
import games.cubi.locatables.BlockLocatable;
|
||||
import games.cubi.locatables.ImmutableLocatable;
|
||||
import games.cubi.locatables.MutableLocatable;
|
||||
import games.cubi.raycastedantiesp.core.utils.Clearable;
|
||||
|
||||
public interface TileEntityLocatable<T> extends BlockLocatable, ImmutableLocatable, Clearable {
|
||||
boolean visible();
|
||||
TileEntityLocatable<T> setVisible(boolean visible);
|
||||
|
||||
int lastChecked();
|
||||
TileEntityLocatable<T> setLastChecked(int lastChecked);
|
||||
|
||||
int blockID();
|
||||
TileEntityLocatable<T> setBlockID(int blockID);
|
||||
|
||||
T extraData();
|
||||
TileEntityLocatable<T> setExtraData(T extraData);
|
||||
|
||||
@Override
|
||||
default boolean isMutable() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
default MutableLocatable castToMutableOrNull() {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,87 +1,228 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.players;
|
||||
|
||||
import games.cubi.logs.Logger;
|
||||
import games.cubi.raycastedantiesp.core.utils.*;
|
||||
import games.cubi.raycastedantiesp.core.tracked.EntitySpawnTask;
|
||||
import games.cubi.raycastedantiesp.core.tracked.NettyEntity;
|
||||
import games.cubi.raycastedantiesp.core.utils.Packet.Packets;
|
||||
import games.cubi.utils.Clearable;
|
||||
import games.cubi.utils.VarHandler;
|
||||
import games.cubi.utils.lists.IntArrayListMarker;
|
||||
import games.cubi.utils.lists.PrimitiveIntArrayList;
|
||||
import it.unimi.dsi.fastutil.ints.Int2IntArrayMap;
|
||||
import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap;
|
||||
import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap;
|
||||
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
|
||||
import it.unimi.dsi.fastutil.objects.ObjectIterator;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.lang.invoke.VarHandle;
|
||||
|
||||
import static games.cubi.raycastedantiesp.core.tracked.NettyEntity.NO_LEASHER;
|
||||
import static games.cubi.raycastedantiesp.core.tracked.NettyEntity.NO_VEHICLE;
|
||||
|
||||
/**
|
||||
* Per-player mutable state intended for Netty-side packet tracking and deferred reconciliation.
|
||||
*/
|
||||
public class NettyData implements Clearable {
|
||||
//
|
||||
public boolean packetsAreWithinBundle = false;
|
||||
//
|
||||
private static final int DEFAULT_MAP_SIZE = 16;
|
||||
//
|
||||
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||
// START Leash tracking:
|
||||
//
|
||||
private final Int2ObjectArrayMap<int[]> unresolvedLeashedEntityIDsByHolderID = new Int2ObjectArrayMap<>(16); // shot in the dark guess at capacity here. Can't be the more generic Int2ObjectMap because that doesn't expose a fast iterator.
|
||||
private final Int2ObjectArrayMap<int[]> unresolvedLeashedEntityIDsByHolderID = new Int2ObjectArrayMap<>(DEFAULT_MAP_SIZE);
|
||||
private final Int2IntArrayMap unresolvedHolderIDsByLeashedEntityID = new Int2IntArrayMap(DEFAULT_MAP_SIZE);
|
||||
|
||||
public void addUnresolvedLeash(int holderEntityID, int leashedEntityID) {
|
||||
int previousHolderEntityID = unresolvedHolderIDsByLeashedEntityID.put(leashedEntityID, holderEntityID);
|
||||
if (previousHolderEntityID != NO_LEASHER && previousHolderEntityID != holderEntityID) {
|
||||
removeLeashedEntityFromUnresolvedHolder(previousHolderEntityID, leashedEntityID);
|
||||
}
|
||||
unresolvedLeashedEntityIDsByHolderID.compute(holderEntityID, (ignored, existing) -> {
|
||||
if (IntArrayList.contains(existing, leashedEntityID)) {
|
||||
if (PrimitiveIntArrayList.contains(existing, leashedEntityID)) {
|
||||
return existing;
|
||||
}
|
||||
return IntArrayList.add(existing, leashedEntityID);
|
||||
return PrimitiveIntArrayList.add(existing, leashedEntityID);
|
||||
});
|
||||
}
|
||||
|
||||
public boolean removeUnresolvedLeash(int holderEntityID, int leashedEntityID) {
|
||||
final boolean[] removed = new boolean[1];
|
||||
unresolvedLeashedEntityIDsByHolderID.computeIfPresent(holderEntityID, (ignored, existing) -> {
|
||||
if (!IntArrayList.contains(existing, leashedEntityID)) {
|
||||
return existing;
|
||||
}
|
||||
removed[0] = true;
|
||||
int[] updated = IntArrayList.remove(existing, leashedEntityID);
|
||||
return IntArrayList.isEmpty(updated) ? null : updated;
|
||||
});
|
||||
return removed[0];
|
||||
if (unresolvedHolderIDsByLeashedEntityID.get(leashedEntityID) != holderEntityID) {
|
||||
return false;
|
||||
}
|
||||
unresolvedHolderIDsByLeashedEntityID.remove(leashedEntityID);
|
||||
removeLeashedEntityFromUnresolvedHolder(holderEntityID, leashedEntityID);
|
||||
return true;
|
||||
}
|
||||
|
||||
public int getUnresolvedHolderForLeashedEntity(int leashedEntityID) {
|
||||
return unresolvedHolderIDsByLeashedEntityID.get(leashedEntityID);
|
||||
}
|
||||
|
||||
public int[] getUnresolvedLeashes(int holderEntityID) {
|
||||
return PrimitiveIntArrayList.getCopyOrNull(unresolvedLeashedEntityIDsByHolderID.get(holderEntityID));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns internal Netty-thread reconciliation state without copying it.
|
||||
* Callers must not mutate the returned array.
|
||||
*/
|
||||
public int[] getUnresolvedLeashesNoAlloc(int holderEntityID) {
|
||||
return unresolvedLeashedEntityIDsByHolderID.get(holderEntityID);
|
||||
}
|
||||
|
||||
public int[] consumeUnresolvedLeashes(int holderEntityID) {
|
||||
return unresolvedLeashedEntityIDsByHolderID.remove(holderEntityID);
|
||||
int[] existing = unresolvedLeashedEntityIDsByHolderID.remove(holderEntityID);
|
||||
if (PrimitiveIntArrayList.isEmpty(existing)) {
|
||||
return existing;
|
||||
}
|
||||
for (int leashedEntityID : existing) {
|
||||
if (unresolvedHolderIDsByLeashedEntityID.get(leashedEntityID) == holderEntityID) {
|
||||
unresolvedHolderIDsByLeashedEntityID.remove(leashedEntityID);
|
||||
}
|
||||
}
|
||||
return existing;
|
||||
}
|
||||
|
||||
public void removeUnresolvedLeashedEntityFromAll(int leashedEntityID) {
|
||||
ObjectIterator<Int2ObjectMap.Entry<int @IntArrayListMarker []>> iterator = unresolvedLeashedEntityIDsByHolderID.int2ObjectEntrySet().fastIterator();
|
||||
while (iterator.hasNext()) {
|
||||
Int2ObjectMap.Entry<int @IntArrayListMarker []> entry = iterator.next();
|
||||
int[] existing = entry.getValue();
|
||||
if (!IntArrayList.contains(existing, leashedEntityID)) {
|
||||
continue;
|
||||
}
|
||||
int[] updated = IntArrayList.remove(existing, leashedEntityID);
|
||||
if (IntArrayList.isEmpty(updated)) {
|
||||
iterator.remove();
|
||||
continue;
|
||||
}
|
||||
entry.setValue(updated);
|
||||
public int consumeUnresolvedHolderForLeashedEntity(int leashedEntityID) {
|
||||
int holderEntityID = unresolvedHolderIDsByLeashedEntityID.remove(leashedEntityID);
|
||||
if (holderEntityID == NO_LEASHER) {
|
||||
return NO_LEASHER;
|
||||
}
|
||||
removeLeashedEntityFromUnresolvedHolder(holderEntityID, leashedEntityID);
|
||||
return holderEntityID;
|
||||
}
|
||||
|
||||
private void removeLeashedEntityFromUnresolvedHolder(int holderEntityID, int leashedEntityID) {
|
||||
unresolvedLeashedEntityIDsByHolderID.computeIfPresent(holderEntityID, (ignored, existing) -> {
|
||||
int[] updated = PrimitiveIntArrayList.remove(existing, leashedEntityID);
|
||||
return PrimitiveIntArrayList.isEmpty(updated) ? null : updated;
|
||||
});
|
||||
}
|
||||
//
|
||||
// END Leash tracking.
|
||||
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||
//
|
||||
|
||||
//
|
||||
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||
// START Passenger tracking:
|
||||
//
|
||||
/**
|
||||
* Latest full passenger list for a vehicle that is not represented by a tracked entity.
|
||||
* Normally this is temporary reconciliation state while a vehicle or passenger is waiting to spawn.
|
||||
* Bypassed vehicles remain untracked, so their authoritative passenger list stays here until it is
|
||||
* replaced by another passenger packet or cleared by the vehicle's destroy packet.
|
||||
*/
|
||||
private final Int2ObjectArrayMap<int[]> unresolvedPassengerIDsByVehicleID = new Int2ObjectArrayMap<>(DEFAULT_MAP_SIZE);
|
||||
/**
|
||||
* Reverse lookup for passenger relationships stored above.
|
||||
* Lets a later passenger spawn discover which untracked vehicle most recently claimed it as a passenger.
|
||||
* This may grow larger than {@link #unresolvedPassengerIDsByVehicleID} if vehicles have several passengers, so it's an open hash map.
|
||||
*/
|
||||
private final Int2IntOpenHashMap unresolvedVehicleIDsByPassengerID = new Int2IntOpenHashMap(DEFAULT_MAP_SIZE);
|
||||
|
||||
{
|
||||
unresolvedHolderIDsByLeashedEntityID.defaultReturnValue(NO_LEASHER);
|
||||
unresolvedVehicleIDsByPassengerID.defaultReturnValue(NO_VEHICLE);
|
||||
}
|
||||
|
||||
public int[] getUnresolvedPassengers(int vehicleEntityID) {
|
||||
return PrimitiveIntArrayList.getCopyOrNull(unresolvedPassengerIDsByVehicleID.get(vehicleEntityID));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns internal Netty-thread reconciliation state without copying it.
|
||||
* Callers must not mutate the returned array.
|
||||
*/
|
||||
public int[] getUnresolvedPassengersNoAlloc(int vehicleEntityID) {
|
||||
return unresolvedPassengerIDsByVehicleID.get(vehicleEntityID);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces any previous unresolved passenger state for this vehicle.
|
||||
* The passenger packet is authoritative, so the latest packet wins.
|
||||
*/
|
||||
public void setUnresolvedPassengers(int vehicleEntityID, int[] passengerIDs) {
|
||||
consumeUnresolvedPassengers(vehicleEntityID);
|
||||
if (PrimitiveIntArrayList.isEmpty(passengerIDs)) {
|
||||
return;
|
||||
}
|
||||
int[] copiedPassengerIDs = passengerIDs.clone();
|
||||
unresolvedPassengerIDsByVehicleID.put(vehicleEntityID, copiedPassengerIDs);
|
||||
for (int passengerID : copiedPassengerIDs) {
|
||||
int previousVehicleID = unresolvedVehicleIDsByPassengerID.put(passengerID, vehicleEntityID);
|
||||
if (previousVehicleID != NO_VEHICLE && previousVehicleID != vehicleEntityID) {
|
||||
removePassengerFromUnresolvedVehicle(previousVehicleID, passengerID);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public int[] consumeUnresolvedPassengers(int vehicleEntityID) {
|
||||
int[] existing = unresolvedPassengerIDsByVehicleID.remove(vehicleEntityID);
|
||||
if (PrimitiveIntArrayList.isEmpty(existing)) {
|
||||
return existing;
|
||||
}
|
||||
for (int passengerID : existing) {
|
||||
if (unresolvedVehicleIDsByPassengerID.get(passengerID) == vehicleEntityID) {
|
||||
unresolvedVehicleIDsByPassengerID.remove(passengerID);
|
||||
}
|
||||
}
|
||||
return existing;
|
||||
}
|
||||
|
||||
public int getUnresolvedVehicleForPassenger(int passengerEntityID) {
|
||||
return unresolvedVehicleIDsByPassengerID.get(passengerEntityID);
|
||||
}
|
||||
|
||||
public boolean removeUnresolvedPassengerLink(int passengerEntityID, int vehicleEntityID) {
|
||||
if (unresolvedVehicleIDsByPassengerID.get(passengerEntityID) != vehicleEntityID) {
|
||||
return false;
|
||||
}
|
||||
unresolvedVehicleIDsByPassengerID.remove(passengerEntityID);
|
||||
removePassengerFromUnresolvedVehicle(vehicleEntityID, passengerEntityID);
|
||||
return true;
|
||||
}
|
||||
|
||||
public int consumeUnresolvedVehicleForPassenger(int passengerEntityID) {
|
||||
int vehicleEntityID = unresolvedVehicleIDsByPassengerID.remove(passengerEntityID);
|
||||
if (vehicleEntityID == NO_VEHICLE) {
|
||||
return NO_VEHICLE;
|
||||
}
|
||||
removePassengerFromUnresolvedVehicle(vehicleEntityID, passengerEntityID);
|
||||
return vehicleEntityID;
|
||||
}
|
||||
|
||||
private void removePassengerFromUnresolvedVehicle(int vehicleEntityID, int passengerEntityID) {
|
||||
unresolvedPassengerIDsByVehicleID.computeIfPresent(vehicleEntityID, (ignored, existing) -> {
|
||||
if (!PrimitiveIntArrayList.contains(existing, passengerEntityID)) {
|
||||
return existing;
|
||||
}
|
||||
int[] updated = PrimitiveIntArrayList.remove(existing, passengerEntityID);
|
||||
return PrimitiveIntArrayList.isEmpty(updated) ? null : updated;
|
||||
});
|
||||
}
|
||||
//
|
||||
// END Passenger tracking.
|
||||
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||
//
|
||||
|
||||
//
|
||||
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||
// START Netty entity spawn task queue:
|
||||
//
|
||||
private final Int2ObjectArrayMap<EntitySpawnTask> pendingPostEntitySpawnTasksByEntityID = new Int2ObjectArrayMap<>(16); // shot in the dark guess at capacity here. Can't be the more generic Int2ObjectMap because that doesn't expose a fast iterator.
|
||||
private volatile boolean evictPendingPostSpawnTasksOnNextPacket = false;
|
||||
private static final VarHandle EVICT_PENDING_POST_SPAWN_TASKS_ON_NEXT_PACKET_HANDLE; //TBH there is minimal advantage to using a VarHandle over an AtomicBoolean here, just felt like it.
|
||||
static {
|
||||
try {
|
||||
EVICT_PENDING_POST_SPAWN_TASKS_ON_NEXT_PACKET_HANDLE = MethodHandles.lookup().findVarHandle( NettyData.class, "evictPendingPostSpawnTasksOnNextPacket", boolean.class);
|
||||
} catch (ReflectiveOperationException e) {
|
||||
throw new ExceptionInInitializerError(e);
|
||||
}
|
||||
}
|
||||
private volatile boolean evictPendingPostSpawnTasksOnNextPacket; private static final VarHandle EVICT_PENDING_POST_SPAWN_TASKS_ON_NEXT_PACKET_HANDLE = VarHandler.get(NettyData.class, "evictPendingPostSpawnTasksOnNextPacket", boolean.class);
|
||||
/**
|
||||
* This is intended for reconciliation tasks due to Minecraft sending packets out of order. For example, {@link Packets#ENTITY_EQUIPMENT} is sent before the corresponding {@link Packets#SPAWN_ENTITY} packet, so caching of the equipment packet must await the spawn packet.
|
||||
* @param entityID The entity ID to associate the task with. Immediately after a {@link Packets#SPAWN_ENTITY} packet is processed for this entity ID, the task will be consumed and run.
|
||||
@@ -107,11 +248,12 @@ public class NettyData implements Clearable {
|
||||
}
|
||||
|
||||
public void evictPendingPostSpawnTasksIfRequired(int currentTick) {
|
||||
if (EVICT_PENDING_POST_SPAWN_TASKS_ON_NEXT_PACKET_HANDLE.compareAndSet(this, true, false)) evictOldPendingPostSpawnTasks(currentTick);
|
||||
if ((boolean) EVICT_PENDING_POST_SPAWN_TASKS_ON_NEXT_PACKET_HANDLE.getOpaque(this)
|
||||
&& (boolean) EVICT_PENDING_POST_SPAWN_TASKS_ON_NEXT_PACKET_HANDLE.compareAndExchangeAcquire(this, true, false)) evictOldPendingPostSpawnTasks(currentTick);
|
||||
}
|
||||
|
||||
public void markPendingPostSpawnTasksForEviction() {
|
||||
evictPendingPostSpawnTasksOnNextPacket = true;
|
||||
EVICT_PENDING_POST_SPAWN_TASKS_ON_NEXT_PACKET_HANDLE.setOpaque(this, true);
|
||||
}
|
||||
|
||||
public EntitySpawnTask consumePendingPostSpawnTasksForEntity(int entityID) {
|
||||
@@ -140,9 +282,118 @@ public class NettyData implements Clearable {
|
||||
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||
//
|
||||
|
||||
//
|
||||
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||
// START Self entity tracking:
|
||||
//
|
||||
private final NettyEntity<?> selfEntity;
|
||||
private final int selfEntityID;
|
||||
|
||||
public NettyData(NettyEntity<?> selfEntity) {
|
||||
this.selfEntity = selfEntity;
|
||||
this.selfEntityID = selfEntity.entityID();
|
||||
}
|
||||
|
||||
public NettyEntity<?> getSelfEntity() {
|
||||
return selfEntity;
|
||||
}
|
||||
|
||||
public int getSelfEntityID() {
|
||||
return selfEntityID;
|
||||
}
|
||||
|
||||
public boolean isSelfEntityID(int entityID) {
|
||||
return entityID == selfEntityID;
|
||||
}
|
||||
//
|
||||
// END Self entity tracking.
|
||||
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||
//
|
||||
|
||||
//
|
||||
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||
// START World-transition destroy tracking:
|
||||
//
|
||||
private int @IntArrayListMarker [] expectedWorldTransitionDestroyEntityIDs;
|
||||
|
||||
/**
|
||||
* When changing worlds, the server sends destroy packets for all the entities in the old world, but we want to clear the view. Tracking them here allows those destroy packets to be handled correctly.
|
||||
*/
|
||||
public void setExpectedWorldTransitionDestroyEntityIDs(int[] expectedEntityIDs) {
|
||||
expectedWorldTransitionDestroyEntityIDs = PrimitiveIntArrayList.isEmpty(expectedEntityIDs) ? null : expectedEntityIDs.clone();
|
||||
}
|
||||
|
||||
public boolean consumeExpectedWorldTransitionDestroyEntityID(int entityID) {
|
||||
if (!PrimitiveIntArrayList.contains(expectedWorldTransitionDestroyEntityIDs, entityID)) {
|
||||
return false;
|
||||
}
|
||||
expectedWorldTransitionDestroyEntityIDs = PrimitiveIntArrayList.remove(expectedWorldTransitionDestroyEntityIDs, entityID);
|
||||
if (PrimitiveIntArrayList.isEmpty(expectedWorldTransitionDestroyEntityIDs)) {
|
||||
expectedWorldTransitionDestroyEntityIDs = null;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
//
|
||||
// END World-transition destroy tracking.
|
||||
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||
//
|
||||
|
||||
//
|
||||
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||
// START World tracking:
|
||||
//
|
||||
|
||||
private int currentWorldMinHeight = Integer.MIN_VALUE; // Netty thread access only
|
||||
private String currentWorldName = null; // Netty thread access only
|
||||
|
||||
public int getCurrentWorldMinHeight() {
|
||||
if (currentWorldMinHeight == Integer.MIN_VALUE) {
|
||||
Logger.error(new IllegalStateException("Current world min height was requested before it was set"), 3, NettyData.class);
|
||||
return -64;
|
||||
}
|
||||
return currentWorldMinHeight;
|
||||
}
|
||||
|
||||
public NettyData setCurrentWorldMinHeight(int currentWorldMinHeight) {
|
||||
this.currentWorldMinHeight = currentWorldMinHeight;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return The current world name, or null if the player is still in the process of joining the server.
|
||||
*/
|
||||
public @Nullable String getCurrentWorldName() {
|
||||
return currentWorldName;
|
||||
}
|
||||
|
||||
public NettyData setCurrentWorldName(String currentWorldName) {
|
||||
this.currentWorldName = currentWorldName;
|
||||
return this;
|
||||
}
|
||||
|
||||
//
|
||||
// END World tracking.
|
||||
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||
//
|
||||
|
||||
public void clearPendingReconciliationState() {
|
||||
unresolvedLeashedEntityIDsByHolderID.clear();
|
||||
unresolvedHolderIDsByLeashedEntityID.clear();
|
||||
unresolvedPassengerIDsByVehicleID.clear();
|
||||
unresolvedVehicleIDsByPassengerID.clear();
|
||||
pendingPostEntitySpawnTasksByEntityID.clear();
|
||||
evictPendingPostSpawnTasksOnNextPacket = false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
unresolvedLeashedEntityIDsByHolderID.clear();
|
||||
pendingPostEntitySpawnTasksByEntityID.clear();
|
||||
clearPendingReconciliationState();
|
||||
expectedWorldTransitionDestroyEntityIDs = null;
|
||||
if (selfEntity != null) {
|
||||
selfEntity.clear();
|
||||
}
|
||||
currentWorldMinHeight = Integer.MIN_VALUE;
|
||||
currentWorldName = null;
|
||||
}
|
||||
}
|
||||
@@ -1,41 +1,64 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.players;
|
||||
|
||||
import games.cubi.locatables.Locatable;
|
||||
import games.cubi.locatables.api.Locatable;
|
||||
import games.cubi.locatables.implementations.ThreadSafeLocatable;
|
||||
import games.cubi.logs.Logger;
|
||||
import games.cubi.raycastedantiesp.core.locatables.NettyEntityLocatable;
|
||||
import games.cubi.raycastedantiesp.core.tracked.NettyEntity;
|
||||
import games.cubi.utils.VarHandler;
|
||||
import games.cubi.raycastedantiesp.core.view.BlockView;
|
||||
import games.cubi.raycastedantiesp.core.view.EntityView;
|
||||
import games.cubi.raycastedantiesp.core.view.ViewRegistry;
|
||||
import games.cubi.raycastedantiesp.core.view.controller.PacketEntityViewController;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.lang.invoke.VarHandle;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import java.util.function.IntSupplier;
|
||||
|
||||
public class PlayerData {
|
||||
public static final int INVALID_WORLD_EPOCH = -1;
|
||||
|
||||
private final UUID playerUUID;
|
||||
private final int joinTick;
|
||||
private volatile boolean hasBypassPermission;
|
||||
private volatile boolean connected;
|
||||
private final ThreadSafeLocatable ownLocation;
|
||||
|
||||
private final BlockView blockView;
|
||||
private final EntityView<?> entityView;
|
||||
private final EntityView<?> playerView;
|
||||
private final NettyData nettyData;
|
||||
// Even positive values are stable world sessions; odd values mean the views are being replaced.
|
||||
private volatile int worldEpoch; private static final VarHandle WORLD_EPOCH = VarHandler.get(PlayerData.class, "worldEpoch", int.class);
|
||||
private UUID viewWorld;
|
||||
|
||||
public PlayerData(UUID player, boolean hasBypassPermission, int joinTick) {
|
||||
this(player, joinTick);
|
||||
this.hasBypassPermission = hasBypassPermission;
|
||||
}
|
||||
|
||||
public PlayerData(UUID player, int joinTick) {
|
||||
PlayerData(UUID player, boolean hasBypassPermission, int joinTick, int selfEntityID, PlayerRegistry.SelfEntityCreator selfEntityCreator) {
|
||||
this.joinTick = joinTick;
|
||||
this.playerUUID = player;
|
||||
this.hasBypassPermission = hasBypassPermission;
|
||||
connected = true;
|
||||
|
||||
blockView = ViewRegistry.createBlockView();
|
||||
entityView = ViewRegistry.createEntityView();
|
||||
playerView = ViewRegistry.createPlayerEntityView();
|
||||
nettyData = new NettyData();
|
||||
IntSupplier worldEpochSupplier = this::acquireWorldEpoch;
|
||||
blockView = ViewRegistry.createBlockView(worldEpochSupplier);
|
||||
entityView = ViewRegistry.createEntityView(worldEpochSupplier);
|
||||
playerView = ViewRegistry.createPlayerEntityView(worldEpochSupplier);
|
||||
ownLocation = new ThreadSafeLocatable(null, 0, 0, 0);
|
||||
NettyEntity<?> selfEntity = Logger.requireNonNull(
|
||||
selfEntityCreator.createSelfEntity(this, selfEntityID, player),
|
||||
"Self entity creator returned null",
|
||||
3,
|
||||
PlayerData.class
|
||||
);
|
||||
nettyData = new NettyData(selfEntity);
|
||||
}
|
||||
|
||||
public EntityView<?> entityView() {
|
||||
@@ -54,13 +77,63 @@ public class PlayerData {
|
||||
return blockView;
|
||||
}
|
||||
|
||||
/** Acquire-reads the current player-wide view epoch. */
|
||||
public int acquireWorldEpoch() {
|
||||
return (int) WORLD_EPOCH.getAcquire(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a stable epoch for {@code expectedWorld}, or {@link #INVALID_WORLD_EPOCH} when the world session is not usable.
|
||||
*/
|
||||
public int tryAcquireWorldEpochFor(UUID expectedWorld) {
|
||||
int before = acquireWorldEpoch();
|
||||
if (!isStableWorldEpoch(before)) {
|
||||
return INVALID_WORLD_EPOCH;
|
||||
}
|
||||
UUID currentWorld = viewWorld;
|
||||
int after = acquireWorldEpoch();
|
||||
if (before != after || !Objects.equals(currentWorld, expectedWorld)) {
|
||||
return INVALID_WORLD_EPOCH;
|
||||
}
|
||||
return before;
|
||||
}
|
||||
|
||||
public static boolean isStableWorldEpoch(int epoch) {
|
||||
return epoch != 0 && (epoch & 1) == 0;
|
||||
}
|
||||
|
||||
/** Structural-writer operation performed before clearing all world-scoped views. */
|
||||
public void beginWorldTransition() {
|
||||
int current = acquireWorldEpoch();
|
||||
if ((current & 1) != 0) { //current is odd
|
||||
throw new IllegalStateException("World transition already in progress");
|
||||
}
|
||||
WORLD_EPOCH.setRelease(this, current + 1);
|
||||
// Keep subsequent view-clearing writes behind the invalidating odd epoch.
|
||||
VarHandle.releaseFence();
|
||||
viewWorld = null;
|
||||
}
|
||||
|
||||
/** Structural-writer operation performed after all world-scoped views have been cleared. */
|
||||
public void completeWorldTransition(UUID world) {
|
||||
int current = acquireWorldEpoch();
|
||||
if ((current & 1) == 0) { //current is even
|
||||
throw new IllegalStateException("No world transition in progress");
|
||||
}
|
||||
viewWorld = world;
|
||||
WORLD_EPOCH.setRelease(this, current + 1);
|
||||
}
|
||||
|
||||
public void updateOwnLocation(UUID world, double x, double y, double z) {
|
||||
ownLocation.set(x, y, z, world);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a live, thread-safe view of the player's current location.
|
||||
* Casting the result to a mutable type and modifying it is unsupported.
|
||||
*/
|
||||
public Locatable ownLocation() {
|
||||
ThreadSafeLocatable existing = ownLocation;
|
||||
return existing == null ? null : existing.clonePlainAndCentreIfBlockLocation();
|
||||
return ownLocation;
|
||||
}
|
||||
|
||||
public UUID getPlayerUUID() {
|
||||
@@ -75,6 +148,18 @@ public class PlayerData {
|
||||
return joinTick;
|
||||
}
|
||||
|
||||
public boolean isConnected() {
|
||||
return connected;
|
||||
}
|
||||
|
||||
public void markDisconnected() {
|
||||
connected = false;
|
||||
int current = acquireWorldEpoch();
|
||||
if ((current & 1) == 0) {
|
||||
WORLD_EPOCH.setRelease(this, current + 1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Either the entity or player view for this player, depending on the entity ID
|
||||
*/
|
||||
@@ -89,12 +174,15 @@ public class PlayerData {
|
||||
return null;
|
||||
}
|
||||
|
||||
public NettyEntityLocatable<?,?> entityFromID(int entityID) {
|
||||
public @Nullable NettyEntity<?> entityFromID(int entityID) {
|
||||
if (nettyData.isSelfEntityID(entityID)) {
|
||||
return nettyData.getSelfEntity();
|
||||
}
|
||||
EntityView<?> entityView = viewFromEntityID(entityID);
|
||||
if (entityView == null) {
|
||||
return null;
|
||||
}
|
||||
return (NettyEntityLocatable<?, ?>) entityView.getEntity(entityID);
|
||||
return (NettyEntity<?>) entityView.getEntity(entityID);
|
||||
}
|
||||
|
||||
public void setBypassPermission(boolean hasBypassPermission) {
|
||||
@@ -106,7 +194,7 @@ public class PlayerData {
|
||||
return "PlayerData{" +
|
||||
"playerUUID=" + playerUUID +
|
||||
", joinTick=" + joinTick +
|
||||
", hasBypassPermission=" + hasBypassPermission +
|
||||
", hasBypassPermission=" + hasBypassPermission() +
|
||||
", ownLocation=" + ownLocation +
|
||||
", blockView=" + blockView +
|
||||
", entityView=" + entityView +
|
||||
|
||||
@@ -0,0 +1,355 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.players;
|
||||
|
||||
import games.cubi.locatables.api.FloatingLocatableEquality;
|
||||
import games.cubi.locatables.api.Locatable;
|
||||
import games.cubi.locatables.api.MutableFloatingLocatable;
|
||||
import games.cubi.locatables.api.Spatial;
|
||||
import games.cubi.utils.VarHandler;
|
||||
|
||||
import java.lang.invoke.VarHandle;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* A mutable, thread-safe location and view state for a player.
|
||||
*
|
||||
* <p>Mutations are serialized because platform and packet lifecycle callbacks
|
||||
* may write from different threads. World and scalar reads use relaxed
|
||||
* per-field access: a read may combine values from adjacent updates.</p>
|
||||
* <p></p>
|
||||
* Reads of several fields are not coherently published. This is acceptable
|
||||
* since players typically move in small increments, so an old x and new z
|
||||
* still closely approximate the player's actual position. In less-frequent
|
||||
* cases such as teleports or dimension switches, raycasts may use the incorrect
|
||||
* position briefly. This does not matter, as incorrect state will be fixed by next tick's raycast.
|
||||
*/
|
||||
public final class PlayerLocatable implements MutableFloatingLocatable, FloatingLocatableEquality {
|
||||
private final Object writerMonitor = new Object();
|
||||
|
||||
private volatile UUID world; private static final VarHandle WORLD = VarHandler.get(PlayerLocatable.class, "world", UUID.class);
|
||||
private volatile double x; private static final VarHandle X = VarHandler.get(PlayerLocatable.class, "x", double.class);
|
||||
private volatile double y; private static final VarHandle Y = VarHandler.get(PlayerLocatable.class, "y", double.class);
|
||||
private volatile double z; private static final VarHandle Z = VarHandler.get(PlayerLocatable.class, "z", double.class);
|
||||
private volatile float yaw; private static final VarHandle YAW = VarHandler.get(PlayerLocatable.class, "yaw", float.class);
|
||||
private volatile float pitch; private static final VarHandle PITCH = VarHandler.get(PlayerLocatable.class, "pitch", float.class);
|
||||
private volatile PlayerPose pose; private static final VarHandle POSE = VarHandler.get(PlayerLocatable.class, "pose", PlayerPose.class);
|
||||
|
||||
public PlayerLocatable() {
|
||||
}
|
||||
|
||||
/** Initialises or replaces the complete valid player state. */
|
||||
public void initialise(UUID world, double footX, double footY, double footZ, float yaw, float pitch, PlayerPose pose) {
|
||||
validateFullState(world, footX, footY, footZ, yaw, pitch, pose);
|
||||
synchronized (writerMonitor) {
|
||||
writeFullState(world, footX, footY, footZ, yaw, pitch, pose);
|
||||
}
|
||||
}
|
||||
|
||||
/** Updates the complete state for a world change. */
|
||||
public void worldChange(UUID world, double footX, double footY, double footZ, float yaw, float pitch, PlayerPose pose) {
|
||||
validateFullState(world, footX, footY, footZ, yaw, pitch, pose);
|
||||
synchronized (writerMonitor) {
|
||||
writeFullState(world, footX, footY, footZ, yaw, pitch, pose);
|
||||
}
|
||||
}
|
||||
|
||||
/** Updates the player's foot position while retaining rotation and pose. */
|
||||
public void updateFoot(double footX, double footY, double footZ) {
|
||||
validateFinite(footX, footY, footZ);
|
||||
synchronized (writerMonitor) {
|
||||
X.setOpaque(this, footX);
|
||||
Y.setOpaque(this, footY);
|
||||
Z.setOpaque(this, footZ);
|
||||
}
|
||||
}
|
||||
|
||||
/** Updates the player's rotation while retaining position and pose. */
|
||||
public void updateRotation(float yaw, float pitch) {
|
||||
validateRotation(yaw, pitch);
|
||||
synchronized (writerMonitor) {
|
||||
YAW.setOpaque(this, yaw);
|
||||
PITCH.setOpaque(this, pitch);
|
||||
}
|
||||
}
|
||||
|
||||
/** Updates the player's pose while retaining position and rotation. */
|
||||
public void updatePose(PlayerPose pose) {
|
||||
Objects.requireNonNull(pose, "pose");
|
||||
synchronized (writerMonitor) {
|
||||
POSE.setOpaque(this, pose);
|
||||
}
|
||||
}
|
||||
|
||||
/** Updates position and rotation in one logical operation. */
|
||||
public void updateFootAndRotation(double footX, double footY, double footZ, float yaw, float pitch) {
|
||||
validateFinite(footX, footY, footZ);
|
||||
validateRotation(yaw, pitch);
|
||||
synchronized (writerMonitor) {
|
||||
X.setOpaque(this, footX);
|
||||
Y.setOpaque(this, footY);
|
||||
Z.setOpaque(this, footZ);
|
||||
YAW.setOpaque(this, yaw);
|
||||
PITCH.setOpaque(this, pitch);
|
||||
}
|
||||
}
|
||||
|
||||
/** Invalidates and clears the complete player state. */
|
||||
public void invalidate() {
|
||||
synchronized (writerMonitor) {
|
||||
WORLD.setOpaque(this, null);
|
||||
X.setOpaque(this, 0.0);
|
||||
Y.setOpaque(this, 0.0);
|
||||
Z.setOpaque(this, 0.0);
|
||||
YAW.setOpaque(this, 0.0f);
|
||||
PITCH.setOpaque(this, 0.0f);
|
||||
POSE.setOpaque(this, null);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID world() {
|
||||
return (UUID) WORLD.getOpaque(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public double x() {
|
||||
return (double) X.getOpaque(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public double y() {
|
||||
return (double) Y.getOpaque(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public double z() {
|
||||
return (double) Z.getOpaque(this);
|
||||
}
|
||||
|
||||
public float yaw() {
|
||||
return (float) YAW.getOpaque(this);
|
||||
}
|
||||
|
||||
public float pitch() {
|
||||
return (float) PITCH.getOpaque(this);
|
||||
}
|
||||
|
||||
public PlayerPose pose() {
|
||||
return (PlayerPose) POSE.getOpaque(this);
|
||||
}
|
||||
|
||||
public float cameraYOffset() {
|
||||
PlayerPose currentPose = (PlayerPose) POSE.getOpaque(this);
|
||||
return currentPose == null ? 0.0f : currentPose.cameraYOffset();
|
||||
}
|
||||
|
||||
public double cameraX() {
|
||||
return (double) X.getOpaque(this);
|
||||
}
|
||||
|
||||
public double cameraY() {
|
||||
double currentY = (double) Y.getOpaque(this);
|
||||
PlayerPose currentPose = (PlayerPose) POSE.getOpaque(this);
|
||||
return currentY + (currentPose == null ? 0.0 : (double) currentPose.cameraYOffset());
|
||||
}
|
||||
|
||||
public double cameraZ() {
|
||||
return (double) Z.getOpaque(this);
|
||||
}
|
||||
|
||||
public double cameraDistanceSquared(Spatial spatial) {
|
||||
Objects.requireNonNull(spatial, "spatial");
|
||||
double targetX = spatial.x();
|
||||
double targetY = spatial.y();
|
||||
double targetZ = spatial.z();
|
||||
double currentX = (double) X.getOpaque(this);
|
||||
double currentY = (double) Y.getOpaque(this);
|
||||
double currentZ = (double) Z.getOpaque(this);
|
||||
PlayerPose currentPose = (PlayerPose) POSE.getOpaque(this);
|
||||
double dx = currentX - targetX;
|
||||
double dy = currentY + (currentPose == null ? 0.0 : (double) currentPose.cameraYOffset()) - targetY;
|
||||
double dz = currentZ - targetZ;
|
||||
return dx * dx + dy * dy + dz * dz;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlayerLocatable setX(double x) {
|
||||
validateFinite(x);
|
||||
synchronized (writerMonitor) {
|
||||
X.setOpaque(this, x);
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlayerLocatable setY(double y) {
|
||||
validateFinite(y);
|
||||
synchronized (writerMonitor) {
|
||||
Y.setOpaque(this, y);
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlayerLocatable setZ(double z) {
|
||||
validateFinite(z);
|
||||
synchronized (writerMonitor) {
|
||||
Z.setOpaque(this, z);
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlayerLocatable setPosition(double x, double y, double z) {
|
||||
validateFinite(x, y, z);
|
||||
synchronized (writerMonitor) {
|
||||
X.setOpaque(this, x);
|
||||
Y.setOpaque(this, y);
|
||||
Z.setOpaque(this, z);
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlayerLocatable setPosition(Spatial spatial) {
|
||||
Objects.requireNonNull(spatial, "spatial");
|
||||
return setPosition(spatial.x(), spatial.y(), spatial.z());
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlayerLocatable setWorld(UUID world) {
|
||||
if (world == null) {
|
||||
invalidate();
|
||||
return this;
|
||||
}
|
||||
synchronized (writerMonitor) {
|
||||
WORLD.setOpaque(this, world);
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlayerLocatable setLocation(Locatable locatable) {
|
||||
Objects.requireNonNull(locatable, "locatable");
|
||||
return setLocation(locatable.world(), locatable.x(), locatable.y(), locatable.z());
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlayerLocatable setLocation(UUID world, double x, double y, double z) {
|
||||
validateFinite(x, y, z);
|
||||
if (world == null) {
|
||||
invalidate();
|
||||
return this;
|
||||
}
|
||||
synchronized (writerMonitor) {
|
||||
X.setOpaque(this, x);
|
||||
Y.setOpaque(this, y);
|
||||
Z.setOpaque(this, z);
|
||||
WORLD.setOpaque(this, world);
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlayerLocatable set(Locatable locatable) {
|
||||
return setLocation(locatable);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlayerLocatable set(double x, double y, double z) {
|
||||
return setPosition(x, y, z);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlayerLocatable set(int x, int y, int z) {
|
||||
return setPosition(x, y, z);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlayerLocatable set(double x, double y, double z, UUID world) {
|
||||
return setLocation(world, x, y, z);
|
||||
}
|
||||
|
||||
@Override
|
||||
public LocatableType getType() {
|
||||
return LocatableType.ThreadSafe;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
return isEqualTo(other);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return makeHash();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean strictlyEquals(Object other) {
|
||||
if (this == other) {
|
||||
return true;
|
||||
}
|
||||
if (!(other instanceof PlayerLocatable that)) {
|
||||
return false;
|
||||
}
|
||||
UUID thisWorld = world();
|
||||
double thisX = x();
|
||||
double thisY = y();
|
||||
double thisZ = z();
|
||||
return Objects.equals(thisWorld, that.world())
|
||||
&& Double.doubleToLongBits(thisX) == Double.doubleToLongBits(that.x())
|
||||
&& Double.doubleToLongBits(thisY) == Double.doubleToLongBits(that.y())
|
||||
&& Double.doubleToLongBits(thisZ) == Double.doubleToLongBits(that.z());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return toStringForm();
|
||||
}
|
||||
|
||||
/** This method must only be called while holding {@link #writerMonitor}. */
|
||||
private void writeFullState(UUID world, double footX, double footY, double footZ, float yaw, float pitch, PlayerPose pose) {
|
||||
WORLD.setOpaque(this, null);
|
||||
X.setOpaque(this, footX);
|
||||
Y.setOpaque(this, footY);
|
||||
Z.setOpaque(this, footZ);
|
||||
YAW.setOpaque(this, yaw);
|
||||
PITCH.setOpaque(this, pitch);
|
||||
POSE.setOpaque(this, pose);
|
||||
WORLD.setOpaque(this, world);
|
||||
}
|
||||
|
||||
private static void validateFullState(UUID world, double footX, double footY, double footZ, float yaw, float pitch, PlayerPose pose) {
|
||||
Objects.requireNonNull(world, "world");
|
||||
Objects.requireNonNull(pose, "pose");
|
||||
validateFinite(footX, footY, footZ);
|
||||
validateRotation(yaw, pitch);
|
||||
}
|
||||
|
||||
private static void validateFinite(double x, double y, double z) {
|
||||
if (!Double.isFinite(x) || !Double.isFinite(y) || !Double.isFinite(z)) {
|
||||
throw new IllegalArgumentException("Coordinates must be finite");
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateFinite(double value) {
|
||||
if (!Double.isFinite(value)) {
|
||||
throw new IllegalArgumentException("Coordinate must be finite");
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateRotation(float yaw, float pitch) {
|
||||
if (!Float.isFinite(yaw) || !Float.isFinite(pitch) || pitch < -90.0f || pitch > 90.0f) {
|
||||
throw new IllegalArgumentException("Rotation must be finite and pitch must be between -90 and 90 degrees");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.players;
|
||||
|
||||
/** Player body poses and the corresponding camera height above the feet. */
|
||||
public enum PlayerPose {
|
||||
UNKNOWN(1.62f),
|
||||
STANDING(1.62f),
|
||||
SNEAKING(1.27f),
|
||||
SWIMMING(0.40f),
|
||||
FALL_FLYING(0.40f),
|
||||
SPIN_ATTACK(0.40f),
|
||||
SLEEPING(0.20f),
|
||||
DYING(0.20f);
|
||||
|
||||
private final float cameraYOffset;
|
||||
|
||||
PlayerPose(float cameraYOffset) {
|
||||
this.cameraYOffset = cameraYOffset;
|
||||
}
|
||||
|
||||
public float cameraYOffset() {
|
||||
return cameraYOffset;
|
||||
}
|
||||
}
|
||||
@@ -1,50 +1,58 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.players;
|
||||
|
||||
import games.cubi.raycastedantiesp.core.tracked.NettyEntity;
|
||||
import games.cubi.utils.VarHandler;
|
||||
|
||||
import java.lang.invoke.VarHandle;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class PlayerRegistry {
|
||||
public final class PlayerRegistry {
|
||||
|
||||
private static PlayerRegistry instance;
|
||||
@FunctionalInterface
|
||||
public interface SelfEntityCreator {
|
||||
NettyEntity<?> createSelfEntity(PlayerData playerData, int selfEntityID, UUID playerUUID);
|
||||
}
|
||||
|
||||
private static final PlayerRegistry instance = new PlayerRegistry();
|
||||
|
||||
private PlayerRegistry() {}
|
||||
|
||||
public static PlayerRegistry getInstance() {
|
||||
if (instance == null) {
|
||||
instance = new PlayerRegistry();
|
||||
}
|
||||
public static PlayerRegistry get() {
|
||||
return instance;
|
||||
}
|
||||
|
||||
private final ConcurrentHashMap<UUID, PlayerData> playerDataMap = new ConcurrentHashMap<>();
|
||||
|
||||
public void registerPlayerIfAbsent(UUID playerUUID, boolean hasBypassPermission, int joinTick) {
|
||||
playerDataMap.putIfAbsent(playerUUID, new PlayerData(playerUUID, hasBypassPermission, joinTick));
|
||||
}
|
||||
private final Collection<PlayerData> unmodifiablePlayerData = Collections.unmodifiableCollection(playerDataMap.values());
|
||||
private volatile PlayerData[] playerDataArray = new PlayerData[0]; private static final VarHandle PLAYER_DATA_ARRAY = VarHandler.get(PlayerRegistry.class, "playerDataArray", PlayerData[].class);
|
||||
|
||||
/** Forcefully registers a player and returns the new PlayerData, even if they were already registered.**/
|
||||
public PlayerData registerAndGetPlayer(UUID playerUUID, int joinTick) {
|
||||
PlayerData newData = new PlayerData(playerUUID, joinTick);
|
||||
playerDataMap.put(playerUUID, newData);
|
||||
public synchronized PlayerData registerAndGetPlayer(UUID playerUUID, int joinTick, int selfEntityID, SelfEntityCreator selfEntityCreator) {
|
||||
PlayerData newData = new PlayerData(playerUUID, false, joinTick, selfEntityID, selfEntityCreator);
|
||||
PlayerData old = playerDataMap.put(playerUUID, newData);
|
||||
if (old != null) old.markDisconnected();
|
||||
updatePlayerDataArray();
|
||||
return newData;
|
||||
}
|
||||
|
||||
public PlayerData registerAndGetPlayerIfAbsent(UUID playerUUID, boolean hasBypassPermission, int joinTick) {
|
||||
PlayerData newData = new PlayerData(playerUUID, hasBypassPermission, joinTick);
|
||||
PlayerData existingData = playerDataMap.putIfAbsent(playerUUID, newData);
|
||||
return existingData != null ? existingData : newData;
|
||||
}
|
||||
|
||||
public void unregisterPlayer(UUID playerUUID) {
|
||||
public synchronized void unregisterPlayer(UUID playerUUID) {
|
||||
PlayerData unregisteredPlayer = playerDataMap.remove(playerUUID);
|
||||
if (unregisteredPlayer == null) {
|
||||
return;
|
||||
}
|
||||
unregisteredPlayer.blockView().clear();
|
||||
unregisteredPlayer.entityView().clear();
|
||||
unregisteredPlayer.playerView().clear();
|
||||
unregisteredPlayer.nettyData().clear();
|
||||
unregisteredPlayer.markDisconnected();
|
||||
updatePlayerDataArray();
|
||||
}
|
||||
|
||||
public PlayerData getPlayerData(UUID playerUUID) {
|
||||
@@ -56,9 +64,34 @@ public class PlayerRegistry {
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Live, mutable collection of all PlayerData instances.
|
||||
* @return Live, unmodifiable view of all PlayerData instances.
|
||||
* **/
|
||||
public Collection<PlayerData> getAllPlayerData() {
|
||||
return playerDataMap.values();
|
||||
return unmodifiablePlayerData;
|
||||
}
|
||||
|
||||
private void updatePlayerDataArray() {
|
||||
PLAYER_DATA_ARRAY.setRelease(this, playerDataMap.values().toArray(PlayerData[]::new));
|
||||
}
|
||||
|
||||
/**
|
||||
* Do not mutate this array, all changes must go through {@link #registerAndGetPlayer(UUID, int, int, SelfEntityCreator)} /
|
||||
* {@link #unregisterPlayer(UUID)}.
|
||||
* <p></p>
|
||||
* Changes to this array will be lost on next player join/leave, and will not apply everywhere.
|
||||
*/
|
||||
public PlayerData[] getPlayerDataArray() {
|
||||
return (PlayerData[]) PLAYER_DATA_ARRAY.getAcquire(this);
|
||||
}
|
||||
|
||||
public void forEachPlayer(Consumer<PlayerData> consumer) {
|
||||
PlayerData[] data = getPlayerDataArray();
|
||||
for (PlayerData player : data) {
|
||||
consumer.accept(player);
|
||||
}
|
||||
}
|
||||
|
||||
public int getPlayerCount() {
|
||||
return playerDataMap.size();
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,17 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.raycast;
|
||||
|
||||
import games.cubi.locatables.Locatable;
|
||||
import games.cubi.locatables.api.Locatable;
|
||||
import games.cubi.locatables.api.Spatial;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public interface ParticleSpawner {
|
||||
|
||||
@@ -8,5 +19,9 @@ public interface ParticleSpawner {
|
||||
RED, GREEN, BLUE,
|
||||
}
|
||||
|
||||
void spawnParticleAt(Locatable locatable, Colour color);
|
||||
void spawnParticleAt(Locatable locatable, Colour colour);
|
||||
|
||||
void spawnParticleAt(UUID world, Spatial spatial, Colour colour);
|
||||
|
||||
void spawnParticleAt(UUID world, double x, double y, double z, Colour colour);
|
||||
}
|
||||
@@ -1,42 +1,175 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.raycast;
|
||||
|
||||
import games.cubi.locatables.Locatable;
|
||||
import games.cubi.locatables.MutableLocatable;
|
||||
import games.cubi.locatables.implementations.MutableBlockVector;
|
||||
import games.cubi.logs.Logger;
|
||||
import games.cubi.raycastedantiesp.core.players.PlayerData;
|
||||
import games.cubi.locatables.api.Locatable;
|
||||
import games.cubi.locatables.api.Spatial;
|
||||
import games.cubi.locatables.api.BlockSpatial;
|
||||
import games.cubi.raycastedantiesp.core.chunks.ChunkOcclusionView;
|
||||
import games.cubi.raycastedantiesp.core.view.BlockView;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public class RaycastUtil {
|
||||
|
||||
//True: Has line-of-sight
|
||||
public static boolean raycast(PlayerData player, Locatable start, Locatable end, int maxOccluding, int alwaysShowRadius, int maxRaycastRadius, boolean debug, BlockView snap, int stepSize, ParticleSpawner particleSpawner) {
|
||||
if (!start.world().equals(end.world())) return false;
|
||||
//True: Has line-of-sight
|
||||
//This is deliberately a ray-stepping algorithm rather than DDA as it is much faster (2x in benchmarking)
|
||||
//Missing blocks is acceptable, as it will be assumed the player can see past those corners.
|
||||
//While this uses objects, JHM and in-game profiling have both shown that all objects used here are consistently scalarised by the JVM.
|
||||
/**
|
||||
* Mutable position and chunk-section state is flattened into the advancer so C2 only
|
||||
* needs to scalarise one state holder while retaining a readable ray-stepping method.
|
||||
*/
|
||||
public static boolean raycastUnrolledAccumulated(int maxOccluding, final int alwaysShowRadiusSquared, final int maxRaycastRadiusSquared, boolean debug,
|
||||
float yOffsetEnd, final BlockView snap, final Locatable start, final Spatial end, ParticleSpawner spawner) {
|
||||
double startX = start.x();
|
||||
double startY = start.y();
|
||||
double startZ = start.z();
|
||||
double endOffset = end instanceof BlockSpatial ? 0.5 : 0.0;
|
||||
RayDirection direction = RayDirection.from(end.x() + endOffset, end.y() + endOffset + yOffsetEnd, end.z() + endOffset, startX, startY, startZ);
|
||||
double lengthSquared = direction.getLengthSquared();
|
||||
if (lengthSquared <= alwaysShowRadiusSquared) return true;
|
||||
if (lengthSquared > maxRaycastRadiusSquared) return false;
|
||||
double total = direction.normaliseAndGetLength(lengthSquared);
|
||||
float finalDist = (float) (total - 1);
|
||||
|
||||
MutableLocatable clonedEnd = end.clonePlainAndCentreIfBlockLocation();
|
||||
double total = start.distance(clonedEnd) - stepSize; //benchmarking shows that calling distance() is faster than distanceSquared() then checking distanceSquared < stepSize*stepSize every time despite the latter replacing a square root with multiplication
|
||||
if (total <= alwaysShowRadius) return true;
|
||||
if (total > maxRaycastRadius) return false;
|
||||
if (debug && particleSpawner == null) {
|
||||
Logger.errorAndReturn(new RuntimeException("raycast called with debug enabled but no ParticleSpawner supplied"), 2, RaycastUtil.class);
|
||||
final RayAdvancer rayAdvancer = debug ? new DebugRayAdvancer(startX, startY, startZ, direction, snap, start.world(), spawner) : new RayAdvancer(startX, startY, startZ, direction, snap);
|
||||
|
||||
int remainingSteps = (int) Math.floor(finalDist);
|
||||
while (remainingSteps >= 4) {
|
||||
rayAdvancer.advance();
|
||||
rayAdvancer.advance();
|
||||
rayAdvancer.advance();
|
||||
rayAdvancer.advance();
|
||||
if (rayAdvancer.occluded > maxOccluding) return false;
|
||||
remainingSteps -= 4;
|
||||
}
|
||||
while (remainingSteps-- > 0) rayAdvancer.advance();
|
||||
return rayAdvancer.occluded <= maxOccluding;
|
||||
}
|
||||
|
||||
private static sealed class RayAdvancer extends RayPosition permits DebugRayAdvancer {
|
||||
private final RayDirection direction;
|
||||
private final BlockView blockView;
|
||||
|
||||
private int chunkX, chunkY, chunkZ;
|
||||
private ChunkOcclusionView currentOcclusionView;
|
||||
private int occluded = 0;
|
||||
|
||||
private RayAdvancer(double startX, double startY, double startZ, RayDirection direction, BlockView blockView) {
|
||||
super(startX, startY, startZ);
|
||||
this.direction = direction;
|
||||
chunkX = blockX() >> 4;
|
||||
chunkY = blockY() >> 4;
|
||||
chunkZ = blockZ() >> 4;
|
||||
currentOcclusionView = blockView.getChunkOcclusionView(chunkX, chunkY, chunkZ);
|
||||
this.blockView = blockView;
|
||||
}
|
||||
|
||||
Locatable dir = clonedEnd.subtract(start).normalize().scalarMultiply(stepSize);
|
||||
|
||||
MutableBlockVector current = new MutableBlockVector(start.world(), start.x(),start.y(),start.z());
|
||||
|
||||
for (double traveled = 0; traveled < total; traveled += stepSize) { //benchmarking shows that for loop is marginally faster than while loop initially (after running for a while they are equal
|
||||
current.add(dir);
|
||||
|
||||
if (snap.isBlockOccluding(current)) {//This works as MutableBlockVector resolves to a block location in #equals and #hashCode, and thus works fine as a key in the snapshot manager
|
||||
maxOccluding--;
|
||||
if (debug) particleSpawner.spawnParticleAt(current, ParticleSpawner.Colour.RED);
|
||||
if (maxOccluding < 1) return false;
|
||||
continue;
|
||||
private void advance() {
|
||||
add(direction);
|
||||
int blockX = blockX();
|
||||
int blockY = blockY();
|
||||
int blockZ = blockZ();
|
||||
if (!isCurrentChunk(blockX, blockY, blockZ)) {
|
||||
moveToChunk(blockX, blockY, blockZ);
|
||||
currentOcclusionView = blockView.getChunkOcclusionView(chunkX, chunkY, chunkZ);
|
||||
}
|
||||
|
||||
if (debug) particleSpawner.spawnParticleAt(current, ParticleSpawner.Colour.GREEN);
|
||||
if (currentOcclusionView != null && currentOcclusionView.isOccludingGlobal(blockX, blockY, blockZ)) {
|
||||
occluded++;
|
||||
particleRed();
|
||||
} else particleGreen();
|
||||
}
|
||||
|
||||
private boolean isCurrentChunk(int blockX, int blockY, int blockZ) {
|
||||
return blockX >> 4 == chunkX && blockY >> 4 == chunkY && blockZ >> 4 == chunkZ;
|
||||
// ((nextChunkX ^ chunkX) | (nextChunkY ^ chunkY) | (nextChunkZ ^ chunkZ)) != 0 is slower than this
|
||||
}
|
||||
|
||||
private void moveToChunk(int blockX, int blockY, int blockZ) {
|
||||
chunkX = blockX >> 4;
|
||||
chunkY = blockY >> 4;
|
||||
chunkZ = blockZ >> 4;
|
||||
}
|
||||
|
||||
void particleGreen() {}
|
||||
void particleRed() {}
|
||||
}
|
||||
|
||||
private static final class DebugRayAdvancer extends RayAdvancer {
|
||||
private final UUID world;
|
||||
private final ParticleSpawner particleSpawner;
|
||||
private DebugRayAdvancer(double startX, double startY, double startZ, RayDirection direction, BlockView blockView, UUID world, ParticleSpawner particleSpawner) {
|
||||
super(startX, startY, startZ, direction, blockView);
|
||||
this.world = world;
|
||||
this.particleSpawner = particleSpawner;
|
||||
}
|
||||
void particleGreen() {
|
||||
particleSpawner.spawnParticleAt(world, x, y, z, ParticleSpawner.Colour.GREEN);
|
||||
}
|
||||
void particleRed() {
|
||||
particleSpawner.spawnParticleAt(world, x, y, z, ParticleSpawner.Colour.RED);
|
||||
}
|
||||
}
|
||||
|
||||
private static sealed class RayPosition permits RayAdvancer {
|
||||
double x, y, z;
|
||||
|
||||
private RayPosition(double x, double y, double z) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
this.z = z;
|
||||
}
|
||||
|
||||
final void add(RayDirection direction) {
|
||||
x += direction.x;
|
||||
y += direction.y;
|
||||
z += direction.z;
|
||||
}
|
||||
|
||||
final int blockX() {
|
||||
return (int) Math.floor(x);
|
||||
}
|
||||
|
||||
final int blockY() {
|
||||
return (int) Math.floor(y);
|
||||
}
|
||||
|
||||
final int blockZ() {
|
||||
return (int) Math.floor(z);
|
||||
}
|
||||
}
|
||||
|
||||
private static final class RayDirection {
|
||||
private double x, y, z;
|
||||
|
||||
private RayDirection(double x, double y, double z) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
this.z = z;
|
||||
}
|
||||
|
||||
private static RayDirection from(double endX, double endY, double endZ, double startX, double startY, double startZ) {
|
||||
return new RayDirection(endX - startX, endY - startY, endZ - startZ);
|
||||
}
|
||||
|
||||
private double getLengthSquared() {
|
||||
return x * x + y * y + z * z;
|
||||
}
|
||||
|
||||
private double normaliseAndGetLength(double lengthSquared) {
|
||||
double len = Math.sqrt(lengthSquared);
|
||||
double scale = 1 / len;
|
||||
x *= scale;
|
||||
y *= scale;
|
||||
z *= scale;
|
||||
return len;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
+9
-1
@@ -1,4 +1,12 @@
|
||||
package games.cubi.raycastedantiesp.core.utils;
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.tracked;
|
||||
|
||||
import games.cubi.logs.Logger;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
+15
-3
@@ -1,4 +1,12 @@
|
||||
package games.cubi.raycastedantiesp.core.utils;
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.tracked;
|
||||
|
||||
import games.cubi.logs.Logger;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
@@ -7,7 +15,7 @@ import org.jetbrains.annotations.Nullable;
|
||||
* For runnable tasks which should be run immediately after an entity is spawned.
|
||||
*/
|
||||
public interface EntitySpawnTask extends Runnable {
|
||||
int TICKS_BEFORE_EVICTION = 3;
|
||||
int TICKS_BEFORE_EVICTION = 16;
|
||||
|
||||
int getSubmittedTick();
|
||||
|
||||
@@ -36,7 +44,11 @@ public interface EntitySpawnTask extends Runnable {
|
||||
Logger.warning("A task was evicted from the Netty task queue due to being too old! This should not happen under normal circumstances and may indicate a problem with the system being overloaded or tasks taking too long to execute. Current tick=" + currentTick + " Task=" + current, 3, EntitySpawnTask.class);
|
||||
EntitySpawnTask next = current.getNext();
|
||||
current.setNext(null);
|
||||
current.run(); // perhaps the task is salvageable even if we missed the correct caller
|
||||
try {
|
||||
current.run(); // perhaps the task is salvageable even if we missed the correct caller
|
||||
} catch (Exception e) {
|
||||
Logger.error("Error while running evicted future netty task " + current, e, 3, EntitySpawnTask.class);
|
||||
}
|
||||
current = next;
|
||||
}
|
||||
return current;
|
||||
@@ -0,0 +1,480 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.tracked;
|
||||
|
||||
import games.cubi.locatables.api.MutableFloatingSpatial;
|
||||
import games.cubi.raycastedantiesp.core.players.PlayerData;
|
||||
import games.cubi.utils.Clearable;
|
||||
import games.cubi.utils.lists.PrimitiveIntArrayList;
|
||||
import games.cubi.utils.lists.IntArrayListMarker;
|
||||
import games.cubi.utils.VarHandler;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.lang.invoke.VarHandle;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Designed for use with netty-based systems, where entity data updates only ever come from one thread, but reads may come from multiple threads. This is however not enforced, and must be kept in mind when using this class.
|
||||
* A representation of an entity for a specific player.
|
||||
*/
|
||||
public abstract class NettyEntity<PacketReplayData extends Clearable> implements TrackedEntity<PacketReplayData> {
|
||||
// immutable fields
|
||||
private final int entityID; // Note that, while rare, entity ids will be negative once the entity id counter overflows.
|
||||
private final UUID entityUUID;
|
||||
private final boolean isSelfEntity;
|
||||
private final int entityType;
|
||||
private final PlayerData owningPlayer;
|
||||
|
||||
// Netty mutatable fields. Should NEVER be mutated from the engine thread, but reads are fine.
|
||||
private volatile double x; private static final VarHandle X = VarHandler.get(NettyEntity.class, "x", double.class);
|
||||
private volatile double y; private static final VarHandle Y = VarHandler.get(NettyEntity.class, "y", double.class);
|
||||
private volatile double z; private static final VarHandle Z = VarHandler.get(NettyEntity.class, "z", double.class);
|
||||
|
||||
// Packet-derived state shared with the engine.
|
||||
private static final byte FLAG_SNEAKING = 1;
|
||||
private static final byte FLAG_GLOWING = 1 << 1;
|
||||
private volatile byte trackedFlags; private static final VarHandle TRACKED_FLAGS = VarHandler.get(NettyEntity.class, "trackedFlags", byte.class);
|
||||
|
||||
// Packet-thread-only replay and client state.
|
||||
private float yaw;
|
||||
private float pitch;
|
||||
private float headYaw;
|
||||
private double velocityX;
|
||||
private double velocityY;
|
||||
private double velocityZ;
|
||||
private boolean onGround = true;
|
||||
private int@IntArrayListMarker[] leashedIDs;
|
||||
|
||||
// Netty-written attachment state shared with the engine thread.
|
||||
private volatile int leasherID = NO_LEASHER; private static final VarHandle LEASHER_ID = VarHandler.get(NettyEntity.class, "leasherID", int.class);
|
||||
private volatile int[] passengerIDs; private static final VarHandle PASSENGER_IDS = VarHandler.get(NettyEntity.class, "passengerIDs", int[].class);
|
||||
private volatile int vehicleID = NO_VEHICLE; private static final VarHandle VEHICLE_ID = VarHandler.get(NettyEntity.class, "vehicleID", int.class);
|
||||
|
||||
|
||||
private int entityData;
|
||||
private PacketReplayData packetReplayData; // For use storing the packets we can't be bothered to directly store, with all cached packets being sent back out to the client when entity is visible again.
|
||||
|
||||
// Mutable by the engine and packet threads.
|
||||
private volatile int lastChecked; private static final VarHandle LAST_CHECKED = VarHandler.get(NettyEntity.class, "lastChecked", int.class);
|
||||
private boolean clientVisible = true;
|
||||
|
||||
// engine thread mutable, reads from netty and engine.
|
||||
private volatile boolean visible;
|
||||
|
||||
// Constants
|
||||
public static final int NEVER_CHECKED = Integer.MIN_VALUE;
|
||||
public static final int NO_VEHICLE = -1;
|
||||
public static final int NO_LEASHER = -2;
|
||||
public static final int SELF_ENTITY_TYPE = -29;
|
||||
|
||||
public NettyEntity(PlayerData owningPlayer, double x, double y, double z, int entityID, UUID entityUUID, boolean isSelfEntity, int entityType, boolean visible) {
|
||||
X.set(this, x); Y.set(this, y); Z.set(this, z);
|
||||
|
||||
this.entityID = entityID;
|
||||
this.entityUUID = entityUUID;
|
||||
this.isSelfEntity = isSelfEntity;
|
||||
this.entityType = entityType;
|
||||
|
||||
this.visible = visible;
|
||||
|
||||
this.owningPlayer = owningPlayer;
|
||||
}
|
||||
|
||||
// For creating the self entity, where we don't have access to its position. Always visible.
|
||||
protected NettyEntity(PlayerData selfData, int selfPlayerID, UUID ownUUID) {
|
||||
entityID = selfPlayerID;
|
||||
entityUUID = ownUUID;
|
||||
owningPlayer = selfData;
|
||||
isSelfEntity = true;
|
||||
entityType = SELF_ENTITY_TYPE;
|
||||
visible = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int entityID() {
|
||||
return entityID;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID entityUUID() {
|
||||
return entityUUID;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean visible() {
|
||||
return visible;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wherever possible, effort should be made to only call this from the engine thread, for thread safety reasons.
|
||||
*/
|
||||
@Override
|
||||
public TrackedEntity<?> setVisible(boolean visible) {
|
||||
this.visible = visible;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean glowing() {
|
||||
return (((byte) TRACKED_FLAGS.getOpaque(this)) & FLAG_GLOWING) != 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean sneaking() {
|
||||
return (((byte) TRACKED_FLAGS.getOpaque(this)) & FLAG_SNEAKING) != 0;
|
||||
}
|
||||
|
||||
public boolean setGlowing(boolean glowing) {
|
||||
return setTrackedFlag(FLAG_GLOWING, glowing);
|
||||
}
|
||||
|
||||
public boolean setSneaking(boolean sneaking) {
|
||||
return setTrackedFlag(FLAG_SNEAKING, sneaking);
|
||||
}
|
||||
|
||||
private boolean setTrackedFlag(byte mask, boolean enabled) {
|
||||
byte previous = enabled
|
||||
? (byte) TRACKED_FLAGS.getAndBitwiseOrRelease(this, mask)
|
||||
: (byte) TRACKED_FLAGS.getAndBitwiseAndRelease(this, (byte) ~mask);
|
||||
boolean changed = (previous & mask) != (enabled ? mask : 0);
|
||||
if (changed) {
|
||||
// A concurrent engine check may overwrite this marker. Hidden entities retry next tick; visible entities
|
||||
// may wait for their configured recheck or remain visible if rechecks are disabled.
|
||||
// This is acceptable and not considered an issue.
|
||||
LAST_CHECKED.setOpaque(this, NEVER_CHECKED);
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int lastChecked() {
|
||||
return (int) LAST_CHECKED.getOpaque(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public TrackedEntity<?> setLastChecked(int lastChecked) {
|
||||
LAST_CHECKED.setOpaque(this, lastChecked);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean clientVisible() {
|
||||
return clientVisible;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TrackedEntity<?> setClientVisible(boolean clientVisible) {
|
||||
this.clientVisible = clientVisible;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSelfEntity() {
|
||||
return isSelfEntity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float yaw() {
|
||||
return yaw;
|
||||
}
|
||||
|
||||
/**
|
||||
* THIS METHOD IS ONLY SAFE TO CALL FROM THE PLAYER's NETTY THREAD
|
||||
*/
|
||||
@Override
|
||||
public TrackedEntity<?> setYaw(float yaw) {
|
||||
this.yaw = yaw;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float pitch() {
|
||||
return pitch;
|
||||
}
|
||||
|
||||
/**
|
||||
* THIS METHOD IS ONLY SAFE TO CALL FROM THE PLAYER's NETTY THREAD
|
||||
*/
|
||||
@Override
|
||||
public TrackedEntity<?> setPitch(float pitch) {
|
||||
this.pitch = pitch;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float headYaw() {
|
||||
return headYaw;
|
||||
}
|
||||
|
||||
/**
|
||||
* THIS METHOD IS ONLY SAFE TO CALL FROM THE PLAYER's NETTY THREAD
|
||||
*/
|
||||
@Override
|
||||
public TrackedEntity<?> setHeadYaw(float headYaw) {
|
||||
this.headYaw = headYaw;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double velocityX() {
|
||||
return velocityX;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double velocityY() {
|
||||
return velocityY;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double velocityZ() {
|
||||
return velocityZ;
|
||||
}
|
||||
|
||||
/**
|
||||
* THIS METHOD IS ONLY SAFE TO CALL FROM THE PLAYER's NETTY THREAD
|
||||
*/
|
||||
@Override
|
||||
public TrackedEntity<?> setVelocity(double velocityX, double velocityY, double velocityZ) {
|
||||
this.velocityX = velocityX;
|
||||
this.velocityY = velocityY;
|
||||
this.velocityZ = velocityZ;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onGround() {
|
||||
return onGround;
|
||||
}
|
||||
|
||||
/**
|
||||
* THIS METHOD IS ONLY SAFE TO CALL FROM THE PLAYER's NETTY THREAD
|
||||
*/
|
||||
@Override
|
||||
public TrackedEntity<?> setOnGround(boolean onGround) {
|
||||
this.onGround = onGround;
|
||||
return this;
|
||||
}
|
||||
|
||||
public int entityType() {
|
||||
return entityType;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int entityData() {
|
||||
return entityData;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TrackedEntity<?> setEntityData(int entityData) {
|
||||
this.entityData = entityData;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return a clone of the passenger ID array, which may be null
|
||||
*/
|
||||
@Override
|
||||
public int[] passengerIDs() {
|
||||
int[] current = passengerIDsAcquire();
|
||||
return current == null ? null : current.clone();
|
||||
}
|
||||
|
||||
/**
|
||||
* Do not mutate this.
|
||||
* <p></p>
|
||||
* This method is not considered public api.
|
||||
* <p>
|
||||
* Returned array may be null
|
||||
* </p>
|
||||
*/
|
||||
public int[] passengerIDsNoAlloc() {
|
||||
return passengerIDsAcquire();
|
||||
}
|
||||
|
||||
@Override
|
||||
public TrackedEntity<?> setPassengerIDs(int[] passengerIDs) {
|
||||
PASSENGER_IDS.setRelease(this, passengerIDs == null ? new int[0] : passengerIDs.clone());
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setVehicleID(int vehicleID) {
|
||||
VEHICLE_ID.setOpaque(this, vehicleID);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int vehicleID() {
|
||||
return (int) VEHICLE_ID.getOpaque(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addLeashedEntity(int leashedEntityID) {
|
||||
if (PrimitiveIntArrayList.contains(leashedIDs, leashedEntityID)) {
|
||||
return;
|
||||
}
|
||||
leashedIDs = PrimitiveIntArrayList.add(leashedIDs, leashedEntityID);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeLeashedEntity(int leashedEntityID) {
|
||||
leashedIDs = PrimitiveIntArrayList.remove(leashedIDs, leashedEntityID);
|
||||
}
|
||||
|
||||
public int@Nullable[] leashedEntityIDsOrNull() {
|
||||
return PrimitiveIntArrayList.getCopyOrNull(leashedIDs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns internal Netty-thread leash state without copying it.
|
||||
* Callers must not mutate the returned array.
|
||||
* <p>
|
||||
* This is not considered public API.
|
||||
* </p>
|
||||
*/
|
||||
public int@Nullable[] leashedEntityIDsOrNullNoAlloc() {
|
||||
return leashedIDs;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int leashingEntity() {
|
||||
return (int) LEASHER_ID.getOpaque(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setLeashingEntity(int leashingEntityID) {
|
||||
LEASHER_ID.setOpaque(this, leashingEntityID);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PacketReplayData packetReplayData() {
|
||||
return packetReplayData;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TrackedEntity<?> setPacketReplayData(PacketReplayData packetReplayData) {
|
||||
this.packetReplayData = packetReplayData;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getYOffset() {
|
||||
return 0.5f; //todo: move away from hardcoded offset
|
||||
}
|
||||
|
||||
@Override
|
||||
public double x() {
|
||||
return (double) X.getOpaque(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public double y() {
|
||||
return (double) Y.getOpaque(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public double z() {
|
||||
return (double) Z.getOpaque(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public MutableFloatingSpatial setX(double x) {
|
||||
X.setOpaque(this, x);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MutableFloatingSpatial setY(double y) {
|
||||
Y.setOpaque(this, y);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MutableFloatingSpatial setZ(double z) {
|
||||
Z.setOpaque(this, z);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MutableFloatingSpatial setPosition(double x, double y, double z) {
|
||||
X.setOpaque(this, x);
|
||||
Y.setOpaque(this, y);
|
||||
Z.setOpaque(this, z);
|
||||
updatePassengerPositions();
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MutableFloatingSpatial add(double x, double y, double z) {
|
||||
X.setOpaque(this, x() + x);
|
||||
Y.setOpaque(this, y() + y);
|
||||
Z.setOpaque(this, z() + z);
|
||||
updatePassengerPositions();
|
||||
return this;
|
||||
}
|
||||
|
||||
// This does not correctly set the passenger position, as the passenger is above the vehicle. It is however close enough to minimise annoying interpolation on show.
|
||||
private void updatePassengerPositions() {
|
||||
int[] currentPassengerIDs = passengerIDsAcquire();
|
||||
if (currentPassengerIDs == null || currentPassengerIDs.length == 0) return;
|
||||
double currentX = x();
|
||||
double currentY = y();
|
||||
double currentZ = z();
|
||||
for (int passengerID : currentPassengerIDs) {
|
||||
NettyEntity<?> passenger = owningPlayer.entityFromID(passengerID);
|
||||
if (passenger != null) {
|
||||
passenger.setVehicleID(entityID);
|
||||
passenger.setX(currentX);
|
||||
passenger.setY(currentY);
|
||||
passenger.setZ(currentZ);
|
||||
passenger.updatePassengerPositions();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
if (packetReplayData != null) packetReplayData.clear();
|
||||
packetReplayData = null;
|
||||
|
||||
TRACKED_FLAGS.setOpaque(this, (byte) 0);
|
||||
VEHICLE_ID.setOpaque(this, NO_VEHICLE);
|
||||
PASSENGER_IDS.setRelease(this, null);
|
||||
leashedIDs = null;
|
||||
LEASHER_ID.setOpaque(this, NO_LEASHER);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "NettyEntity{" +
|
||||
"entityID=" + entityID +
|
||||
", entityUUID=" + entityUUID +
|
||||
", isSelfEntity=" + isSelfEntity +
|
||||
", entityType=" + entityType +
|
||||
", x=" + x() +
|
||||
", y=" + y() +
|
||||
", z=" + z() +
|
||||
", yaw=" + yaw() +
|
||||
", pitch=" + pitch() +
|
||||
", headYaw=" + headYaw() +
|
||||
", velocityX=" + velocityX() +
|
||||
", velocityY=" + velocityY() +
|
||||
", velocityZ=" + velocityZ() +
|
||||
", onGround=" + onGround() +
|
||||
", leashedIDs=" + PrimitiveIntArrayList.toString(leashedIDs) +
|
||||
", leasherID=" + leashingEntity() +
|
||||
", passengerIDs=" + PrimitiveIntArrayList.toString(passengerIDsAcquire()) +
|
||||
", vehicleID=" + vehicleID() +
|
||||
", entityData=" + entityData() +
|
||||
'}';
|
||||
}
|
||||
|
||||
private int[] passengerIDsAcquire() {
|
||||
return (int[]) PASSENGER_IDS.getAcquire(this);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.tracked;
|
||||
|
||||
import games.cubi.locatables.api.BlockSpatial;
|
||||
import games.cubi.utils.Clearable;
|
||||
import games.cubi.utils.lists.InvasivelyLinkedSWMRList;
|
||||
import games.cubi.utils.VarHandler;
|
||||
|
||||
import java.lang.invoke.VarHandle;
|
||||
|
||||
/** Tile desired visibility and lifecycle are shared with the engine; client, block, and replay data are packet-thread-only. */
|
||||
public abstract class NettyTileEntity<PacketReplayData extends Clearable> extends InvasivelyLinkedSWMRList<NettyTileEntity<PacketReplayData>> implements TrackedTileEntity<PacketReplayData> {
|
||||
private volatile boolean visible;
|
||||
private boolean clientVisible;
|
||||
private volatile int lastChecked; private static final VarHandle LAST_CHECKED = VarHandler.get(NettyTileEntity.class, "lastChecked", int.class);
|
||||
private char blockID;
|
||||
private PacketReplayData extraData;
|
||||
|
||||
private static final int REMOVED = Integer.MIN_VALUE + 11;
|
||||
|
||||
private final int x, y, z;
|
||||
public NettyTileEntity(BlockSpatial position, boolean visible, int lastChecked, char blockID) {
|
||||
x = position.blockX();
|
||||
y = position.blockY();
|
||||
z = position.blockZ();
|
||||
|
||||
this.blockID = blockID;
|
||||
this.visible = visible;
|
||||
this.clientVisible = visible;
|
||||
LAST_CHECKED.set(this, lastChecked);
|
||||
}
|
||||
|
||||
public NettyTileEntity(int x, int y, int z, boolean visible, char blockID) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
this.z = z;
|
||||
this.visible = visible;
|
||||
this.clientVisible = visible;
|
||||
this.blockID = blockID;
|
||||
LAST_CHECKED.set(this, NEVER_CHECKED);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean visible() {
|
||||
return visible;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TrackedTileEntity<PacketReplayData> setVisible(boolean visible) {
|
||||
this.visible = visible;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean clientVisible() {
|
||||
return clientVisible;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TrackedTileEntity<PacketReplayData> setClientVisible(boolean clientVisible) {
|
||||
this.clientVisible = clientVisible;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int lastChecked() {
|
||||
return (int) LAST_CHECKED.getAcquire(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public TrackedTileEntity<PacketReplayData> setLastChecked(int checkedTick) {
|
||||
int current = (int) LAST_CHECKED.getAcquire(this);
|
||||
while (current != REMOVED) {
|
||||
if (LAST_CHECKED.weakCompareAndSetRelease(this, current, checkedTick)) {
|
||||
break;
|
||||
}
|
||||
current = (int) LAST_CHECKED.getAcquire(this);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Marks this allocation as detached. This state is absorbing because removed nodes are never reused. */
|
||||
public final void markRemoved() {
|
||||
LAST_CHECKED.setRelease(this, REMOVED);
|
||||
}
|
||||
|
||||
/** Consumer-side lifecycle check performed immediately before emitting a queued transition. */
|
||||
public final boolean isRemoved() {
|
||||
return (int) LAST_CHECKED.getAcquire(this) == REMOVED;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int blockID() {
|
||||
return blockID;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TrackedTileEntity<PacketReplayData> setBlockID(char blockID) {
|
||||
this.blockID = blockID;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PacketReplayData extraData() {
|
||||
return extraData;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TrackedTileEntity<PacketReplayData> setExtraData(PacketReplayData extraData) {
|
||||
this.extraData = extraData;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearExtraData() {
|
||||
if (extraData != null) {
|
||||
//extraData.clear(); probs not needed
|
||||
extraData = null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int blockX() {
|
||||
return x;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int blockY() {
|
||||
return y;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int blockZ() {
|
||||
return z;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
if (extraData != null) {
|
||||
extraData.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return toStringForm();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.tracked;
|
||||
|
||||
import games.cubi.locatables.api.MutableFloatingSpatial;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Per-player platform-independent representation of an entity
|
||||
*/
|
||||
public interface TrackedEntity<PacketReplayData> extends MutableFloatingSpatial {
|
||||
|
||||
int entityID();
|
||||
|
||||
UUID entityUUID();
|
||||
|
||||
boolean visible();
|
||||
TrackedEntity<?> setVisible(boolean visible);
|
||||
|
||||
boolean glowing();
|
||||
|
||||
boolean sneaking();
|
||||
|
||||
int lastChecked();
|
||||
TrackedEntity<?> setLastChecked(int lastChecked);
|
||||
|
||||
/** Packet-thread-only client state. */
|
||||
boolean clientVisible();
|
||||
TrackedEntity<?> setClientVisible(boolean clientVisible);
|
||||
|
||||
boolean isSelfEntity();
|
||||
|
||||
/** Packet-thread-only replay state. */
|
||||
float yaw();
|
||||
TrackedEntity<?> setYaw(float yaw);
|
||||
|
||||
/** Packet-thread-only replay state. */
|
||||
float pitch();
|
||||
TrackedEntity<?> setPitch(float pitch);
|
||||
|
||||
/** Packet-thread-only replay state. */
|
||||
float headYaw();
|
||||
TrackedEntity<?> setHeadYaw(float headYaw);
|
||||
|
||||
/** Packet-thread-only replay state. */
|
||||
double velocityX();
|
||||
double velocityY();
|
||||
double velocityZ();
|
||||
TrackedEntity<?> setVelocity(double velocityX, double velocityY, double velocityZ);
|
||||
|
||||
/** Packet-thread-only replay state. */
|
||||
boolean onGround();
|
||||
TrackedEntity<?> setOnGround(boolean onGround);
|
||||
|
||||
/** Packet-thread-only replay state. */
|
||||
int entityData();
|
||||
TrackedEntity<?> setEntityData(int entityData);
|
||||
|
||||
int[] passengerIDs();
|
||||
TrackedEntity<?> setPassengerIDs(int[] passengerIDs);
|
||||
|
||||
void setVehicleID(int vehicleID);
|
||||
int vehicleID();
|
||||
|
||||
/** Packet-thread-only holder-side relationship state. */
|
||||
void addLeashedEntity(int leashedEntityID);
|
||||
void removeLeashedEntity(int leashedEntityID);
|
||||
int@Nullable[] leashedEntityIDsOrNull();
|
||||
int leashingEntity();
|
||||
void setLeashingEntity(int leashingEntityID);
|
||||
|
||||
/** Packet-thread-only cached packet state. */
|
||||
PacketReplayData packetReplayData();
|
||||
TrackedEntity<?> setPacketReplayData(PacketReplayData packetReplayData);
|
||||
|
||||
float getYOffset();
|
||||
|
||||
/**
|
||||
* For use when the player disconnects, clears all data.
|
||||
*/
|
||||
void clear();
|
||||
|
||||
default <T> T cast() {
|
||||
return (T) this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.tracked;
|
||||
|
||||
import games.cubi.locatables.api.ImmutableBlockSpatial;
|
||||
import games.cubi.utils.Clearable;
|
||||
|
||||
public interface TrackedTileEntity<T> extends ImmutableBlockSpatial, Clearable {
|
||||
int NEVER_CHECKED = Integer.MIN_VALUE;
|
||||
|
||||
boolean visible();
|
||||
TrackedTileEntity<T> setVisible(boolean visible);
|
||||
|
||||
/** Packet-thread-only client state. */
|
||||
boolean clientVisible();
|
||||
TrackedTileEntity<T> setClientVisible(boolean clientVisible);
|
||||
|
||||
int lastChecked();
|
||||
TrackedTileEntity<T> setLastChecked(int lastChecked);
|
||||
|
||||
/** Packet-thread-only structural state. */
|
||||
int blockID();
|
||||
TrackedTileEntity<T> setBlockID(char blockID);
|
||||
|
||||
/** Packet-thread-only replay state. */
|
||||
T extraData();
|
||||
TrackedTileEntity<T> setExtraData(T extraData);
|
||||
void clearExtraData();
|
||||
}
|
||||
@@ -1,3 +1,11 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.utils;
|
||||
|
||||
import games.cubi.logs.Logger;
|
||||
@@ -68,15 +76,15 @@ public record BuildProperties(String gitHashLong, String gitHashShort, String bu
|
||||
return new BuildProperties("unknown", "unknown", "unknown", new Version(-1, -1, -1, true));
|
||||
}
|
||||
|
||||
record Version(short major, short minor, short patch, boolean snapshot) {
|
||||
Version(int major, int minor, int patch, boolean snapshot) {
|
||||
public record Version(short major, short minor, short patch, boolean snapshot) implements Comparable<Version> {
|
||||
public Version(int major, int minor, int patch, boolean snapshot) {
|
||||
this((short) major, (short) minor, (short) patch, snapshot);
|
||||
}
|
||||
|
||||
public static Version parse(String versionString) {
|
||||
String[] parts = versionString.split("[.-]");
|
||||
if (parts.length < 3) {
|
||||
Logger.errorAndReturn(new IllegalArgumentException("Version string must be in the format 'major.minor.patch'"), 2, BuildProperties.class, Version.class);
|
||||
String[] parts = versionString.replaceFirst("[+-].*$", "").split("\\.");
|
||||
if (parts.length != 3) {
|
||||
throw new IllegalArgumentException("Version string must be in the format 'major.minor.patch'. Attempted: " + versionString);
|
||||
}
|
||||
try {
|
||||
short major = Short.parseShort(parts[0]);
|
||||
@@ -85,9 +93,19 @@ public record BuildProperties(String gitHashLong, String gitHashShort, String bu
|
||||
boolean snapshot = versionString.contains("SNAPSHOT");
|
||||
return new Version(major, minor, patch, snapshot);
|
||||
} catch (NumberFormatException e) {
|
||||
Logger.errorAndReturn(new IllegalArgumentException("Version parts must be valid short integers. Attempted: " + versionString, e), 2, BuildProperties.class, Version.class);
|
||||
return new Version(-1, -1, -1, true);
|
||||
throw new IllegalArgumentException("Version parts must be valid short integers. Attempted: " + versionString, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compareTo(Version other) {
|
||||
int majorDifference = Short.compare(major, other.major);
|
||||
if (majorDifference != 0) return majorDifference;
|
||||
|
||||
int minorDifference = Short.compare(minor, other.minor);
|
||||
if (minorDifference != 0) return minorDifference;
|
||||
|
||||
return Short.compare(patch, other.patch);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
package games.cubi.raycastedantiesp.core.utils;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* A Set-like data structure that stores canonical instances of key values.
|
||||
* Any compatible key type may be used for lookup, but only canonical values
|
||||
* of type {@code V} may be stored.
|
||||
*
|
||||
* @param <K> key type used for lookup
|
||||
* @param <V> stored canonical value type
|
||||
*/
|
||||
public interface CanonicalSet<K, V extends K> {
|
||||
int size();
|
||||
|
||||
boolean isEmpty();
|
||||
|
||||
boolean contains(K keyValue);
|
||||
|
||||
@Nullable V get(K keyValue);
|
||||
|
||||
@Nullable V add(V keyValue);
|
||||
|
||||
void addAll(Set<? extends V> keyValues);
|
||||
|
||||
@Nullable V computeIfAbsent(K keyValue, @NotNull Function<? super K, ? extends V> mappingFunction);
|
||||
|
||||
@Nullable V remove(K keyValue);
|
||||
|
||||
void clear();
|
||||
|
||||
@NotNull Set<V> keySet();
|
||||
|
||||
@NotNull Collection<V> values();
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
package games.cubi.raycastedantiesp.core.utils;
|
||||
|
||||
public interface Clearable {
|
||||
/**
|
||||
* Dereferences all internal references to other objects, allowing them to be garbage collected. In theory this isn't needed but idk what's causing the memory leak so we're covering all bases.
|
||||
*/
|
||||
void clear();
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
package games.cubi.raycastedantiesp.core.utils;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Function;
|
||||
|
||||
public class ConcurrentSelfMap<K, V extends K> implements CanonicalSet<K, V> {
|
||||
private final ConcurrentHashMap<V, V> backingMap = new ConcurrentHashMap<>();
|
||||
|
||||
public ConcurrentSelfMap() {}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return backingMap.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
return backingMap.isEmpty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean contains(K keyValue) {
|
||||
return backingMap.containsKey(keyValue);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable V get(K keyValue) {
|
||||
return backingMap.get(keyValue);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable V add(V keyValue) {
|
||||
return backingMap.put(keyValue, keyValue);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addAll(Set<? extends V> keyValues) {
|
||||
for (V keyValue : keyValues) {
|
||||
backingMap.put(keyValue, keyValue);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable V computeIfAbsent(
|
||||
K keyValue,
|
||||
@NotNull Function<? super K, ? extends V> mappingFunction
|
||||
) {
|
||||
V existing = backingMap.get(keyValue);
|
||||
if (existing != null) {
|
||||
return existing;
|
||||
}
|
||||
|
||||
V canonicalValue = mappingFunction.apply(keyValue);
|
||||
if (canonicalValue == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!canonicalValue.equals(keyValue)) {
|
||||
throw new IllegalArgumentException(
|
||||
"Computed canonical value must be equal to the key value."
|
||||
);
|
||||
}
|
||||
|
||||
V racedValue = backingMap.putIfAbsent(canonicalValue, canonicalValue);
|
||||
return racedValue != null ? racedValue : canonicalValue;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable V remove(K keyValue) {
|
||||
return backingMap.remove(keyValue);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
backingMap.clear();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull Set<V> keySet() {
|
||||
return backingMap.keySet();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull Collection<V> values() {
|
||||
return backingMap.values();
|
||||
}
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
package games.cubi.raycastedantiesp.core.utils;
|
||||
|
||||
import games.cubi.logs.Logger;
|
||||
|
||||
/**
|
||||
* Static utility class for operations on int arrays annotated with {@link IntArrayListMarker}, which are intended to be used as lists of integers without the overhead of autoboxing.
|
||||
* <p>
|
||||
* {@link IntArrayListMarker} fields may be null or non-initialised to save memory, {@code IntArrayList} methods will treat null or non-initialised arrays as empty lists.
|
||||
* <p>
|
||||
* Arrays expand and contract as needed such that the length of the backing array is always equal to the number of elements in the list, so there is no extra capacity. This means that adding or removing elements from the list will involve creating a new array and copying the existing elements, which can be inefficient for large lists. However, this design choice was made to save memory and avoid the overhead of maintaining a separate size field and capacity management logic.
|
||||
*/
|
||||
public class IntArrayList {
|
||||
private IntArrayList() {}
|
||||
|
||||
public static int size(int@IntArrayListMarker[] array) {
|
||||
return array == null ? 0 : array.length;
|
||||
}
|
||||
|
||||
public static boolean isEmpty(int@IntArrayListMarker[] array) {
|
||||
return array == null || array.length == 0;
|
||||
}
|
||||
|
||||
public static boolean contains(int@IntArrayListMarker[] array, int value) {
|
||||
if (array == null) return false;
|
||||
for (int i : array) {
|
||||
if (i == value) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Caller of this method <b>must</b> reassign the returned array to the original array reference, as the original array will not be modified and a new array with the added element will be returned.
|
||||
*/
|
||||
public static int@IntArrayListMarker[] add(int@IntArrayListMarker[] array, int value) {
|
||||
if (array == null) {
|
||||
return new int[]{value};
|
||||
} else {
|
||||
int[] newArray = new int[array.length + 1];
|
||||
System.arraycopy(array, 0, newArray, 0, array.length);
|
||||
newArray[array.length] = value;
|
||||
return newArray;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Caller of this method <b>must</b> reassign the returned array to the original array reference, as the original array will not be modified and a new array with the added element will be returned.
|
||||
*/
|
||||
public static int@IntArrayListMarker[] remove(int@IntArrayListMarker[] array, int value) {
|
||||
if (array == null) return null;
|
||||
int index = -1;
|
||||
for (int i = 0; i < array.length; i++) {
|
||||
if (array[i] == value) {
|
||||
index = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (index == -1) return array; // value not found, return original array
|
||||
int[] newArray = new int[array.length - 1];
|
||||
System.arraycopy(array, 0, newArray, 0, index);
|
||||
System.arraycopy(array, index + 1, newArray, index, array.length - index - 1);
|
||||
return newArray;
|
||||
}
|
||||
|
||||
/**
|
||||
* Caller of this method <b>must</b> reassign the returned array to the original array reference, as the original array will not be modified and a new array with the added element will be returned.
|
||||
*/
|
||||
public static int@IntArrayListMarker[] clear(int@IntArrayListMarker[] array) {
|
||||
return null;
|
||||
}
|
||||
|
||||
public static int get(int@IntArrayListMarker[] array, int index) {
|
||||
if (array == null) Logger.errorAndReturn(new IndexOutOfBoundsException("Attempted to find value at index: " + index + ", for IntArrayList with size: 0"), 3, IntArrayList.class);
|
||||
if (index < 0 || index >= array.length) Logger.errorAndReturn(new IndexOutOfBoundsException("Attempted to find value at index: " + index + ", for IntArrayList with size: " + size(array)), 3, IntArrayList.class);
|
||||
return array[index];
|
||||
}
|
||||
|
||||
public static int@IntArrayListMarker[] set(int@IntArrayListMarker[] array, int index, int value) {
|
||||
array[index] = value;
|
||||
return array;
|
||||
}
|
||||
|
||||
public static int[] getCopyOrNull(int@IntArrayListMarker[] array) {
|
||||
if (size(array) == 0) return null;
|
||||
int[] copy = new int[array.length];
|
||||
System.arraycopy(array, 0, copy, 0, array.length);
|
||||
return copy;
|
||||
}
|
||||
|
||||
public static String toString(int@IntArrayListMarker[] array) {
|
||||
if (array == null) return "[]";
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("[");
|
||||
for (int i = 0; i < array.length; i++) {
|
||||
sb.append(array[i]);
|
||||
if (i < array.length - 1) {
|
||||
sb.append(", ");
|
||||
}
|
||||
}
|
||||
sb.append("]");
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
package games.cubi.raycastedantiesp.core.utils;
|
||||
|
||||
import java.lang.annotation.*; /**
|
||||
* {@code int[]} fields annotated with this are backing arrays for {@code IntArrayLists}. {@code IntArrayLists} are not objects directly, instead just an {@code int[]} array, with static operations provided by {@link IntArrayList}.
|
||||
* <p>
|
||||
* This is used to avoid the overhead of an actual object for each {@link IntArrayList}. To further reduce overhead, the field may not be initialised, {@link IntArrayList} is null safe.
|
||||
*
|
||||
* <p> Do not use this array directly, all calls should go through {@link IntArrayList}.
|
||||
*/
|
||||
@Documented @Retention(RetentionPolicy.SOURCE) @Target({ElementType.TYPE_USE, ElementType.FIELD, ElementType.PARAMETER})
|
||||
public @interface IntArrayListMarker {}
|
||||
@@ -0,0 +1,326 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.utils;
|
||||
|
||||
import it.unimi.dsi.fastutil.Hash;
|
||||
import it.unimi.dsi.fastutil.longs.Long2ObjectMap;
|
||||
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
|
||||
import it.unimi.dsi.fastutil.longs.LongObjectBiConsumer;
|
||||
import it.unimi.dsi.fastutil.objects.ObjectIterator;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.locks.StampedLock;
|
||||
import java.util.function.LongFunction;
|
||||
import java.util.function.LongPredicate;
|
||||
|
||||
/**
|
||||
* A small thread-safe utility map for primitive {@code long} keys backed by a {@link StampedLock} and a {@link Long2ObjectOpenHashMap}.
|
||||
*
|
||||
* <p>Reads use optimistic locking where possible. Mutations use the write lock. Tests indicate that
|
||||
* even under heavy read-write contention, optimistic reading works almost all the time.
|
||||
*
|
||||
* <p>Callback-based methods such as {@link #computeIfAbsent(long, LongFunction)}, {@link #forEach(LongObjectBiConsumer)},
|
||||
* and {@link #removeIfKey(LongPredicate)} run their callbacks while holding the write lock, so those
|
||||
* callbacks must not call back into this same map instance or deadlock may occur as StampedLock is not reentrant.
|
||||
*
|
||||
* <p>This class only synchronizes access to the map structure itself. Stored values are returned by
|
||||
* reference and are not made thread-safe by this map.
|
||||
*
|
||||
* @param <V> the type of mapped values
|
||||
*/
|
||||
public class Long2ObjectMTHashMap<V> {
|
||||
private final Long2ObjectOpenHashMap<V> backingMap;
|
||||
private final StampedLock lock = new StampedLock();
|
||||
private final ThreadLocal<Integer> writeLockedCallbackDepth = ThreadLocal.withInitial(() -> 0);
|
||||
|
||||
public Long2ObjectMTHashMap(final int expected, final float loadFactor) {
|
||||
this.backingMap = new Long2ObjectOpenHashMap<>(expected, loadFactor);
|
||||
}
|
||||
|
||||
public Long2ObjectMTHashMap(final int expected) {
|
||||
this(expected, Hash.DEFAULT_LOAD_FACTOR);
|
||||
}
|
||||
|
||||
public Long2ObjectMTHashMap() {
|
||||
this(Hash.DEFAULT_INITIAL_SIZE, Hash.DEFAULT_LOAD_FACTOR);
|
||||
}
|
||||
|
||||
public V get(final long key) {
|
||||
long stamp = lock.tryOptimisticRead();
|
||||
V value = backingMap.get(key);
|
||||
if (failsValidation(stamp)) {
|
||||
assertNoWriteLockedCallbackReentry();
|
||||
stamp = lock.readLock();
|
||||
try {
|
||||
value = backingMap.get(key);
|
||||
} finally {
|
||||
lock.unlockRead(stamp);
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
public V getOrDefault(final long key, final V defaultValue) {
|
||||
long stamp = lock.tryOptimisticRead();
|
||||
V value = getOrDefaultInternal(key, defaultValue);
|
||||
if (failsValidation(stamp)) {
|
||||
assertNoWriteLockedCallbackReentry();
|
||||
stamp = lock.readLock();
|
||||
try {
|
||||
value = getOrDefaultInternal(key, defaultValue);
|
||||
} finally {
|
||||
lock.unlockRead(stamp);
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
public boolean containsKey(final long key) {
|
||||
long stamp = lock.tryOptimisticRead();
|
||||
boolean contains = backingMap.containsKey(key);
|
||||
if (failsValidation(stamp)) {
|
||||
assertNoWriteLockedCallbackReentry();
|
||||
stamp = lock.readLock();
|
||||
try {
|
||||
contains = backingMap.containsKey(key);
|
||||
} finally {
|
||||
lock.unlockRead(stamp);
|
||||
}
|
||||
}
|
||||
return contains;
|
||||
}
|
||||
|
||||
public int size() {
|
||||
long stamp = lock.tryOptimisticRead();
|
||||
int size = backingMap.size();
|
||||
if (failsValidation(stamp)) {
|
||||
assertNoWriteLockedCallbackReentry();
|
||||
stamp = lock.readLock();
|
||||
try {
|
||||
size = backingMap.size();
|
||||
} finally {
|
||||
lock.unlockRead(stamp);
|
||||
}
|
||||
}
|
||||
return size;
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
long stamp = lock.tryOptimisticRead();
|
||||
boolean empty = backingMap.isEmpty();
|
||||
if (failsValidation(stamp)) {
|
||||
assertNoWriteLockedCallbackReentry();
|
||||
stamp = lock.readLock();
|
||||
try {
|
||||
empty = backingMap.isEmpty();
|
||||
} finally {
|
||||
lock.unlockRead(stamp);
|
||||
}
|
||||
}
|
||||
return empty;
|
||||
}
|
||||
|
||||
public V put(final long key, final V value) {
|
||||
assertNoWriteLockedCallbackReentry();
|
||||
|
||||
long stamp = lock.writeLock();
|
||||
try {
|
||||
return backingMap.put(key, value);
|
||||
} finally {
|
||||
lock.unlockWrite(stamp);
|
||||
}
|
||||
}
|
||||
|
||||
public V putIfAbsent(final long key, final V value) {
|
||||
assertNoWriteLockedCallbackReentry();
|
||||
|
||||
long stamp = lock.writeLock();
|
||||
try {
|
||||
if (backingMap.containsKey(key)) {
|
||||
return backingMap.get(key);
|
||||
}
|
||||
backingMap.put(key, value);
|
||||
return null;
|
||||
} finally {
|
||||
lock.unlockWrite(stamp);
|
||||
}
|
||||
}
|
||||
|
||||
public V replace(final long key, final V value) {
|
||||
assertNoWriteLockedCallbackReentry();
|
||||
|
||||
long stamp = lock.writeLock();
|
||||
try {
|
||||
if (!backingMap.containsKey(key)) {
|
||||
return null;
|
||||
}
|
||||
return backingMap.put(key, value);
|
||||
} finally {
|
||||
lock.unlockWrite(stamp);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean replace(final long key, final V oldValue, final V value) {
|
||||
assertNoWriteLockedCallbackReentry();
|
||||
|
||||
long stamp = lock.writeLock();
|
||||
try {
|
||||
if (!backingMap.containsKey(key) || !Objects.equals(backingMap.get(key), oldValue)) {
|
||||
return false;
|
||||
}
|
||||
backingMap.put(key, value);
|
||||
return true;
|
||||
} finally {
|
||||
lock.unlockWrite(stamp);
|
||||
}
|
||||
}
|
||||
|
||||
public V remove(final long key) {
|
||||
assertNoWriteLockedCallbackReentry();
|
||||
|
||||
long stamp = lock.writeLock();
|
||||
try {
|
||||
return backingMap.remove(key);
|
||||
} finally {
|
||||
lock.unlockWrite(stamp);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean remove(final long key, final Object value) {
|
||||
assertNoWriteLockedCallbackReentry();
|
||||
|
||||
long stamp = lock.writeLock();
|
||||
try {
|
||||
if (!backingMap.containsKey(key) || !Objects.equals(backingMap.get(key), value)) {
|
||||
return false;
|
||||
}
|
||||
backingMap.remove(key);
|
||||
return true;
|
||||
} finally {
|
||||
lock.unlockWrite(stamp);
|
||||
}
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
assertNoWriteLockedCallbackReentry();
|
||||
|
||||
long stamp = lock.writeLock();
|
||||
try {
|
||||
backingMap.clear();
|
||||
} finally {
|
||||
lock.unlockWrite(stamp);
|
||||
}
|
||||
}
|
||||
|
||||
public V computeIfAbsent(final long key, final LongFunction<? extends V> mappingFunction) {
|
||||
assertNoWriteLockedCallbackReentry();
|
||||
Objects.requireNonNull(mappingFunction, "mappingFunction");
|
||||
|
||||
long stamp = lock.writeLock();
|
||||
try {
|
||||
if (backingMap.containsKey(key)) {
|
||||
return backingMap.get(key);
|
||||
}
|
||||
|
||||
V value = invokeWriteLockedCallback(() -> mappingFunction.apply(key));
|
||||
backingMap.put(key, value);
|
||||
return value;
|
||||
} finally {
|
||||
lock.unlockWrite(stamp);
|
||||
}
|
||||
}
|
||||
|
||||
public void forEach(final LongObjectBiConsumer<? super V> consumer) {
|
||||
assertNoWriteLockedCallbackReentry();
|
||||
Objects.requireNonNull(consumer, "consumer");
|
||||
|
||||
long stamp = lock.writeLock();
|
||||
try {
|
||||
ObjectIterator<Long2ObjectMap.Entry<V>> iterator = backingMap.long2ObjectEntrySet().fastIterator();
|
||||
while (iterator.hasNext()) {
|
||||
Long2ObjectMap.Entry<V> entry = iterator.next();
|
||||
invokeWriteLockedCallback(() -> {
|
||||
consumer.accept(entry.getLongKey(), entry.getValue());
|
||||
return null;
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
lock.unlockWrite(stamp);
|
||||
}
|
||||
}
|
||||
|
||||
public int removeIfKey(final LongPredicate predicate) {
|
||||
assertNoWriteLockedCallbackReentry();
|
||||
Objects.requireNonNull(predicate, "predicate");
|
||||
|
||||
long stamp = lock.writeLock();
|
||||
try {
|
||||
int removed = 0;
|
||||
ObjectIterator<Long2ObjectMap.Entry<V>> iterator = backingMap.long2ObjectEntrySet().fastIterator();
|
||||
while (iterator.hasNext()) {
|
||||
Long2ObjectMap.Entry<V> entry = iterator.next();
|
||||
if (invokeWriteLockedCallback(() -> predicate.test(entry.getLongKey()))) {
|
||||
iterator.remove();
|
||||
removed++;
|
||||
}
|
||||
}
|
||||
return removed;
|
||||
} finally {
|
||||
lock.unlockWrite(stamp);
|
||||
}
|
||||
}
|
||||
|
||||
private V getOrDefaultInternal(final long key, final V defaultValue) {
|
||||
V value = backingMap.get(key);
|
||||
return value != null || backingMap.containsKey(key) ? value : defaultValue;
|
||||
}
|
||||
|
||||
private void assertNoWriteLockedCallbackReentry() {
|
||||
if (writeLockedCallbackDepth.get() > 0) {
|
||||
throw new IllegalStateException(
|
||||
"Callbacks executed under the write lock must not reenter this Long2ObjectMTHashMap instance."
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private <T> T invokeWriteLockedCallback(final Long2ObjectMTHashMapCallback<T> callback) {
|
||||
writeLockedCallbackDepth.set(writeLockedCallbackDepth.get() + 1);
|
||||
try {
|
||||
return callback.invoke();
|
||||
} finally {
|
||||
int depth = writeLockedCallbackDepth.get() - 1;
|
||||
if (depth == 0) {
|
||||
writeLockedCallbackDepth.remove();
|
||||
} else {
|
||||
writeLockedCallbackDepth.set(depth);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final AtomicInteger successfulOptimisticReads = new AtomicInteger();
|
||||
final AtomicInteger failedOptimisticReads = new AtomicInteger();
|
||||
|
||||
private boolean failsValidation(long stamp) {
|
||||
boolean valid = lock.validate(stamp);
|
||||
if (!valid) {
|
||||
failedOptimisticReads.incrementAndGet();
|
||||
} else {
|
||||
successfulOptimisticReads.incrementAndGet();
|
||||
}
|
||||
return !valid;
|
||||
|
||||
//return !lock.validate(stamp);
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface Long2ObjectMTHashMapCallback<T> {
|
||||
T invoke();
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,11 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.utils;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.utils;
|
||||
|
||||
/**
|
||||
* Classes where specific methods must be called from a single thread can extend this class and call {@link #guardThread()}
|
||||
* at the start of those methods to ensure that they are only called from the permitted thread.
|
||||
*/
|
||||
public abstract class SingleThreadedGuard {
|
||||
private final Thread permittedThread;
|
||||
|
||||
protected SingleThreadedGuard(Thread thread) {
|
||||
permittedThread = thread;
|
||||
}
|
||||
|
||||
protected void guardThread() {
|
||||
if (Thread.currentThread() != permittedThread) {
|
||||
throw new IllegalStateException("Method called from wrong thread. Expected: " + permittedThread + ", actual: " + Thread.currentThread());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,11 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.utils;
|
||||
|
||||
public class ThreadGuard {
|
||||
|
||||
@@ -1,196 +1,467 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.view;
|
||||
|
||||
import games.cubi.locatables.BlockLocatable;
|
||||
import games.cubi.locatables.ChunkSectionLocatable;
|
||||
import games.cubi.locatables.Locatable;
|
||||
import games.cubi.locatables.implementations.ImmutableBlockLocatable;
|
||||
import ca.spottedleaf.concurrentutil.map.SWMRInt2ObjectHashTable;
|
||||
import games.cubi.locatables.api.BlockLocatable;
|
||||
import games.cubi.locatables.api.BlockSpatial;
|
||||
import games.cubi.logs.Logger;
|
||||
import games.cubi.raycastedantiesp.core.locatables.TileEntityLocatable;
|
||||
import games.cubi.raycastedantiesp.core.utils.CanonicalSet;
|
||||
import games.cubi.raycastedantiesp.core.utils.ConcurrentSelfMap;
|
||||
import games.cubi.raycastedantiesp.core.chunks.BlockInfoResolver;
|
||||
import games.cubi.raycastedantiesp.core.chunks.BlockChunkData;
|
||||
import games.cubi.raycastedantiesp.core.chunks.ChunkOcclusionView;
|
||||
import games.cubi.raycastedantiesp.core.chunks.OccludingChunkData;
|
||||
import games.cubi.raycastedantiesp.core.tracked.TrackedTileEntity;
|
||||
import games.cubi.raycastedantiesp.core.tracked.NettyTileEntity;
|
||||
import games.cubi.raycastedantiesp.core.players.PlayerData;
|
||||
import games.cubi.utils.Clearable;
|
||||
import games.cubi.utils.lists.InvasivelyLinkedSWMRList;
|
||||
import games.cubi.utils.VarHandler;
|
||||
import games.cubi.raycastedantiesp.core.view.chunks.BlockChunkSectionStore;
|
||||
import games.cubi.raycastedantiesp.core.view.chunks.ChunkSectionStore;
|
||||
import games.cubi.raycastedantiesp.core.view.chunks.OccludingChunkSectionStore;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
import java.lang.invoke.VarHandle;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.IntSupplier;
|
||||
|
||||
public abstract class AbstractBlockView<T extends TileEntityLocatable<?>> implements BlockView {
|
||||
public static final int CHUNK_SIZE = 16;
|
||||
public static final int LOCAL_MASK = CHUNK_SIZE - 1;
|
||||
import static games.cubi.raycastedantiesp.core.chunks.ChunkData.packUncheckedGuarded;
|
||||
|
||||
private final Map<ChunkSectionLocatable, BitSet /*true if that position is occluding. Positions are 0-15 for x,y,z*/> chunks = new ConcurrentHashMap<>();
|
||||
private final CanonicalSet<Locatable, T> knownTileEntities = new ConcurrentSelfMap<>();
|
||||
private final ConcurrentLinkedQueue<BlockViewTransition> transitions = new ConcurrentLinkedQueue<>();
|
||||
public abstract class AbstractBlockView<R extends Clearable, T extends NettyTileEntity<R>> implements BlockView {
|
||||
private final ChunkSectionStore chunks;
|
||||
private final boolean trackAllBlocks;
|
||||
/**
|
||||
* The int key represents a packed chunk column bucket, with (signed) 16 bits allocated for x and z respectively. While chunk columns over 60k chunks apart may overlap, this is unlikely to ever actually occur.
|
||||
* <p> {@code NettyTileEntity<R>} is an {@link InvasivelyLinkedSWMRList}, so all tile entities in the column chain from the head entry.
|
||||
* <p> Since direct access to this object outside {@link AbstractBlockView} is impossible, a marker head object is skipped, and head removal is handled separately.
|
||||
* **/
|
||||
private final SWMRInt2ObjectHashTable<NettyTileEntity<R>> knownTileEntitiesByColumnBucket = new SWMRInt2ObjectHashTable<>();
|
||||
private final PackedBlockTransitionQueue transitions = new PackedBlockTransitionQueue();
|
||||
private final IntSupplier worldEpochSupplier;
|
||||
private volatile UUID trackedWorld;
|
||||
// Bit 0 is enabled; higher bits are a generation. The generation prevents enabled -> disabled -> enabled ABA from
|
||||
// accepting an old raycast and also tags transitions that may be drained after their originating mode was replaced.
|
||||
private volatile long tileEntityCheckModeToken; private static final VarHandle TILE_ENTITY_CHECK_MODE_TOKEN = VarHandler.get(AbstractBlockView.class, "tileEntityCheckModeToken", long.class);
|
||||
|
||||
@Deprecated
|
||||
protected abstract T createTrackedTileEntity(BlockLocatable location, int blockID, boolean visible);
|
||||
protected AbstractBlockView(BlockInfoResolver blockInfoResolver, boolean trackAllBlocks, IntSupplier worldEpochSupplier) {
|
||||
Logger.requireNonNull(blockInfoResolver, "blockInfoResolver was null", 1, AbstractBlockView.class);
|
||||
Logger.requireNonNull(worldEpochSupplier, "worldEpochSupplier was null", 1, AbstractBlockView.class);
|
||||
this.trackAllBlocks = trackAllBlocks;
|
||||
this.worldEpochSupplier = worldEpochSupplier;
|
||||
this.chunks = trackAllBlocks
|
||||
? new BlockChunkSectionStore(blockInfoResolver)
|
||||
: new OccludingChunkSectionStore(blockInfoResolver);
|
||||
}
|
||||
|
||||
protected abstract T createTrackedTileEntity(UUID world, int x, int y, int z, int blockID);
|
||||
protected abstract T createTrackedTileEntity(BlockSpatial position, char blockID, boolean visible);
|
||||
|
||||
@Override
|
||||
public ChunkOcclusionView getChunkOcclusionView(int chunkX, int chunkY, int chunkZ) {
|
||||
return chunks.getSection(chunkX, chunkY, chunkZ);
|
||||
}
|
||||
|
||||
public boolean isBlockOccluding(UUID world, int x, int y, int z) {
|
||||
final BitSet chunk = getChunk(world, x >> 4, y >> 4, z >> 4);
|
||||
if (chunk == null) {
|
||||
// chunks may be empty if there are no occluding blocks in that chunk
|
||||
return false;
|
||||
}
|
||||
|
||||
return chunk.get(maskAndPack(x, y, z));
|
||||
@Override
|
||||
public boolean isBlockOccluding(int x, int y, int z) {
|
||||
return chunks.isOccluding(x, y, z);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isBlockOccluding(BlockLocatable location) {
|
||||
return location != null
|
||||
&& location.world() != null
|
||||
&& isBlockOccluding(location.world(), location.blockX(), location.blockY(), location.blockZ());
|
||||
if (location == null || !isTrackedWorld(location.world())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return isBlockOccluding(location.blockX(), location.blockY(), location.blockZ());
|
||||
}
|
||||
|
||||
public int loadedChunkCount() {
|
||||
return chunks.size();
|
||||
return chunks.loadedSectionCount();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateOrInsertTileEntity(BlockLocatable location, int blockID, boolean visibleIfNew) {
|
||||
T tileEntity = knownTileEntities.computeIfAbsent(location, ignored -> createTrackedTileEntity(location, blockID, visibleIfNew));
|
||||
public T updateOrInsertTileEntity(UUID world, BlockSpatial position, char blockID, boolean visibleIfNew) {
|
||||
if (position == null || !ensureTrackedWorld(world)) {
|
||||
return null;
|
||||
}
|
||||
SWMRInt2ObjectHashTable<NettyTileEntity<R>> map = knownTileEntitiesByColumnBucket;
|
||||
int bucketKey = packColumnBucket(position.chunkX(), position.chunkZ());
|
||||
NettyTileEntity<R> head = map.get(bucketKey);
|
||||
T tileEntity = findTileEntityInBucket(head, position);
|
||||
if (tileEntity == null) {
|
||||
Logger.error("Tile entity null when attempting to update or insert", 3, AbstractBlockView.class);
|
||||
tileEntity = createTrackedTileEntity(position, blockID, visibleIfNew);
|
||||
if (tileEntity == null) {
|
||||
Logger.error("createTrackedTileEntity returned null", 3, AbstractBlockView.class);
|
||||
return null;
|
||||
}
|
||||
if (head == null) {
|
||||
map.put(bucketKey, tileEntity);
|
||||
} else {
|
||||
head.linkAfter(tileEntity);
|
||||
}
|
||||
}
|
||||
tileEntity.clearExtraData();
|
||||
tileEntity.setBlockID(blockID);
|
||||
return tileEntity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeTileEntity(UUID world, BlockSpatial position) {
|
||||
if (position == null || !isTrackedWorld(world)) {
|
||||
return;
|
||||
}
|
||||
tileEntity.setBlockID(blockID);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeTileEntity(BlockLocatable location) {
|
||||
T tileEntity = knownTileEntities.remove(location);
|
||||
SWMRInt2ObjectHashTable<NettyTileEntity<R>> map = knownTileEntitiesByColumnBucket;
|
||||
int bucketKey = packColumnBucket(position.chunkX(), position.chunkZ());
|
||||
NettyTileEntity<R> head = map.get(bucketKey);
|
||||
T tileEntity = findTileEntityInBucket(head, position);
|
||||
if (tileEntity != null) {
|
||||
tileEntity.clear();
|
||||
removeNode(map, bucketKey, head, tileEntity);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public T getTrackedTileEntity(BlockLocatable location) {
|
||||
return knownTileEntities.get(location);
|
||||
public T getTrackedTileEntity(UUID world, BlockSpatial position) {
|
||||
if (position == null || !isTrackedWorld(world)) {
|
||||
return null;
|
||||
}
|
||||
return findTileEntityInBucket(knownTileEntitiesByColumnBucket.get(packColumnBucket(position.chunkX(), position.chunkZ())), position);
|
||||
}
|
||||
|
||||
@Override
|
||||
public T getTrackedTileEntity(ImmutableBlockLocatable location) {
|
||||
return knownTileEntities.get(location);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isVisible(BlockLocatable location, int currentTick) {
|
||||
T state = knownTileEntities.get(location);
|
||||
public boolean isVisible(UUID world, BlockSpatial position, int currentTick) {
|
||||
if (position == null || !isTrackedWorld(world)) {
|
||||
return true;
|
||||
}
|
||||
T state = getTrackedTileEntity(world, position);
|
||||
return state == null || state.visible();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setVisibility(BlockLocatable location, boolean visible, int currentTick) {
|
||||
T existing = knownTileEntities.get(location);
|
||||
if (existing == null) {
|
||||
private void commitTileEntityVisibilityDecision(T tileEntity, boolean currentVisibility, boolean shouldBeVisible, int currentTick, long modeToken, int expectedWorldEpoch) {
|
||||
if (!isCurrentWorldEpoch(expectedWorldEpoch) || tileEntityCheckModeTokenAcquire() != modeToken) {
|
||||
return;
|
||||
}
|
||||
if (existing.visible() != visible) {
|
||||
transitions.add(new BlockViewTransition(
|
||||
visible ? BlockViewTransition.Type.SHOW : BlockViewTransition.Type.HIDE,
|
||||
location
|
||||
));
|
||||
if (!modeEnabled(modeToken)) {
|
||||
shouldBeVisible = true;
|
||||
}
|
||||
boolean visibilityChanged = currentVisibility != shouldBeVisible;
|
||||
tileEntity.setVisible(shouldBeVisible);
|
||||
tileEntity.setLastChecked(currentTick);
|
||||
if (visibilityChanged) {
|
||||
TransitionType.Tile type = shouldBeVisible ? TransitionType.Tile.SHOW : TransitionType.Tile.HIDE;
|
||||
transitions.add(type, tileEntity, modeToken, expectedWorldEpoch);
|
||||
}
|
||||
existing.setVisible(visible);
|
||||
existing.setLastChecked(currentTick);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<BlockLocatable> getKnownTileEntities() {
|
||||
return List.copyOf(knownTileEntities.keySet());
|
||||
// Only used on non-mutation paths
|
||||
public void recordOutboundTileEntityVisibility(TrackedTileEntity<?> tileEntity, boolean visible) {
|
||||
if (tileEntity != null) {
|
||||
tileEntity.setVisible(visible);
|
||||
tileEntity.setClientVisible(visible);
|
||||
tileEntity.setLastChecked(TrackedTileEntity.NEVER_CHECKED);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<BlockLocatable> getNeedingRecheck(int recheckTicks, int currentTick) {
|
||||
List<BlockLocatable> needingRecheck = new ArrayList<>();
|
||||
for (T tileEntity : knownTileEntities.values()) {
|
||||
if (tileEntity.visible() && currentTick - tileEntity.lastChecked() < recheckTicks) {
|
||||
continue;
|
||||
public void applyTileEntityCheckMode(boolean enabled, int currentTick, Consumer<TrackedTileEntity<?>> visibilityRepairConsumer) {
|
||||
long current = tileEntityCheckModeTokenAcquire();
|
||||
if (modeEnabled(current) == enabled) {
|
||||
return;
|
||||
}
|
||||
// Drop the enabled bit, increment the generation, then restore bit 0 below only for enabled mode.
|
||||
long next = ((current >>> 1) + 1L) << 1;
|
||||
if (enabled) {
|
||||
forEachTileEntity(tileEntity -> tileEntity.setLastChecked(TrackedTileEntity.NEVER_CHECKED));
|
||||
TILE_ENTITY_CHECK_MODE_TOKEN.setRelease(this, next | 1L);
|
||||
return;
|
||||
}
|
||||
|
||||
TILE_ENTITY_CHECK_MODE_TOKEN.setRelease(this, next);
|
||||
forEachTileEntity(tileEntity -> {
|
||||
if (!tileEntity.visible()) {
|
||||
tileEntity.setVisible(true);
|
||||
tileEntity.setLastChecked(currentTick);
|
||||
}
|
||||
needingRecheck.add(tileEntity);
|
||||
if (!tileEntity.clientVisible()) {
|
||||
visibilityRepairConsumer.accept(tileEntity);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public long tileEntityCheckModeToken() {
|
||||
return tileEntityCheckModeTokenAcquire();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCurrentEnabledTileEntityMode(long modeToken) {
|
||||
return modeEnabled(modeToken) && tileEntityCheckModeTokenAcquire() == modeToken;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<TrackedTileEntity<?>> getKnownTileEntities() {
|
||||
ArrayList<TrackedTileEntity<?>> snapshot = new ArrayList<>();
|
||||
forEachTileEntity(snapshot::add);
|
||||
return List.copyOf(snapshot);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int forEachNeedingRecheck(int recheckTicks, int currentTick, Consumer<TrackedTileEntity<?>> action) {
|
||||
return knownTileEntitiesByColumnBucket.forEachValueSummed(head -> {
|
||||
int processed = 0;
|
||||
for (NettyTileEntity<R> tileEntity = head; tileEntity != null; tileEntity = tileEntity.nextAcquire()) {
|
||||
int lastChecked = tileEntity.lastChecked();
|
||||
if (tileEntity.visible() && lastChecked != TrackedTileEntity.NEVER_CHECKED && (recheckTicks < 0 || currentTick - lastChecked < recheckTicks)) {
|
||||
continue;
|
||||
}
|
||||
action.accept(tileEntity);
|
||||
processed++;
|
||||
}
|
||||
return processed;
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public int updateVisibilityForEachNeedingRecheck(int recheckTicks, int currentTick, long modeToken, int expectedWorldEpoch, VisibilityResolver action) {
|
||||
if (!isCurrentEnabledTileEntityMode(modeToken) || !isCurrentWorldEpoch(expectedWorldEpoch)) {
|
||||
return 0;
|
||||
}
|
||||
return needingRecheck;
|
||||
return knownTileEntitiesByColumnBucket.forEachValueSummed(head -> {
|
||||
int processed = 0;
|
||||
for (NettyTileEntity<R> tileEntity = head; tileEntity != null; tileEntity = tileEntity.nextAcquire()) {
|
||||
boolean currentVisibility = tileEntity.visible();
|
||||
int lastChecked = tileEntity.lastChecked();
|
||||
if (currentVisibility && lastChecked != TrackedTileEntity.NEVER_CHECKED && (recheckTicks < 0 || currentTick - lastChecked < recheckTicks)) {
|
||||
continue;
|
||||
}
|
||||
byte shouldBeVisible = action.setVisible(tileEntity);
|
||||
if (shouldBeVisible != VisibilityResolver.SKIPPED) {
|
||||
@SuppressWarnings("unchecked") T typed = (T) tileEntity;
|
||||
commitTileEntityVisibilityDecision(typed, currentVisibility, shouldBeVisible == VisibilityResolver.SHOW, currentTick, modeToken, expectedWorldEpoch);
|
||||
}
|
||||
processed++;
|
||||
}
|
||||
return processed;
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasPendingTransitions() {
|
||||
return !transitions.isEmpty();
|
||||
return transitions.hasPendingTransitions();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<BlockViewTransition> drainTransitions() {
|
||||
List<BlockViewTransition> drained = new ArrayList<>();
|
||||
BlockViewTransition transition;
|
||||
while ((transition = transitions.poll()) != null) {
|
||||
drained.add(transition);
|
||||
public void flushPendingTransitions() {
|
||||
transitions.flushPendingTransitions();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void drainTransitions(BlockView.TransitionConsumer consumer) {
|
||||
transitions.drainTransitions(consumer);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void upsertBlock(UUID world, int x, int y, int z, int blockID) {
|
||||
if (!ensureTrackedWorld(world)) {
|
||||
return;
|
||||
}
|
||||
return drained;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void upsertBlock(UUID world, int x, int y, int z, boolean occluding) {
|
||||
final BitSet chunk = getOrCreateChunk(world, x >> 4, y >> 4, z >> 4);
|
||||
chunk.set(maskAndPack(x, y, z), occluding);
|
||||
chunks.setBlockID(x, y, z, blockID);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeChunk(UUID world, int chunkX, int chunkZ) {
|
||||
chunks.entrySet().removeIf(entry ->
|
||||
entry.getKey().world().equals(world)
|
||||
&& entry.getKey().chunkX() == chunkX
|
||||
&& entry.getKey().chunkZ() == chunkZ
|
||||
);
|
||||
if (!isTrackedWorld(world)) {
|
||||
return;
|
||||
}
|
||||
chunks.removeColumn(chunkX, chunkZ);
|
||||
removeTileEntitiesInChunk(chunkX, chunkZ);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeChunkSection(UUID world, int chunkX, int chunkY, int chunkZ) {
|
||||
chunks.remove(new ChunkSectionLocatable.ImmutableChunkSectionLocatable(world, chunkX, chunkY, chunkZ));
|
||||
if (!isTrackedWorld(world)) {
|
||||
return;
|
||||
}
|
||||
chunks.removeSection(chunkX, chunkY, chunkZ);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void replaceChunkSection(UUID world, int chunkX, int chunkY, int chunkZ, BitSet occludingBlocks) {
|
||||
chunks.put(new ChunkSectionLocatable.ImmutableChunkSectionLocatable(world, chunkX, chunkY, chunkZ), occludingBlocks
|
||||
);
|
||||
public void pruneTileEntitiesAbsentFromChunkSections(UUID world, int chunkX, int chunkZ, int minimumSectionY, int sectionCount, long[][] presentBySection) {
|
||||
if (!isTrackedWorld(world) || sectionCount < 0 || (presentBySection != null && presentBySection.length != sectionCount)) {
|
||||
return;
|
||||
}
|
||||
SWMRInt2ObjectHashTable<NettyTileEntity<R>> map = knownTileEntitiesByColumnBucket;
|
||||
int bucketKey = packColumnBucket(chunkX, chunkZ);
|
||||
// The wrapped key selects a collision bucket; full chunk coordinates below establish ownership.
|
||||
NettyTileEntity<R> head = map.get(bucketKey);
|
||||
NettyTileEntity<R> currentHead = head;
|
||||
for (NettyTileEntity<R> current = head; current != null; ) {
|
||||
NettyTileEntity<R> next = current.nextAcquire();
|
||||
if (current.chunkX() == chunkX && current.chunkZ() == chunkZ) {
|
||||
int sectionIndex = current.chunkY() - minimumSectionY;
|
||||
long[] present = sectionIndex >= 0 && sectionIndex < sectionCount && presentBySection != null
|
||||
? presentBySection[sectionIndex]
|
||||
: null;
|
||||
if (sectionIndex < 0 || sectionIndex >= sectionCount || present == null) {
|
||||
currentHead = removeNode(map, bucketKey, currentHead, current);
|
||||
} else {
|
||||
int packed = packUncheckedGuarded(current.blockX(), current.blockY(), current.blockZ());
|
||||
// Guarded packing masks the full coordinates to local x/y/z. The high bits choose the 64-bit word;
|
||||
// Java masks the long shift distance to the low six bits, selecting the bit within that word.
|
||||
if ((present[packed >>> 6] & 1L << packed) == 0L) {
|
||||
currentHead = removeNode(map, bucketKey, currentHead, current);
|
||||
}
|
||||
}
|
||||
}
|
||||
current = next;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void replaceChunkSection(UUID world, int chunkX, int chunkY, int chunkZ, BlockChunkData data) {
|
||||
if (!ensureTrackedWorld(world)) {
|
||||
return;
|
||||
}
|
||||
chunks.replaceSection(chunkX, chunkY, chunkZ, data);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void replaceChunkSectionOcclusion(UUID world, int chunkX, int chunkY, int chunkZ, OccludingChunkData data) {
|
||||
if (trackAllBlocks) {
|
||||
throw new UnsupportedOperationException("Block chunk storage requires full block IDs for section replacement");
|
||||
}
|
||||
if (!ensureTrackedWorld(world)) {
|
||||
return;
|
||||
}
|
||||
chunks.replaceSectionOcclusion(chunkX, chunkY, chunkZ, data);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
trackedWorld = null;
|
||||
clearTrackedState();
|
||||
}
|
||||
|
||||
private boolean isTrackedWorld(UUID world) {
|
||||
UUID current = trackedWorld;
|
||||
return world != null && current != null && current.equals(world);
|
||||
}
|
||||
|
||||
private boolean ensureTrackedWorld(UUID world) {
|
||||
if (world == null) {
|
||||
return false;
|
||||
}
|
||||
if (world.equals(trackedWorld)) {
|
||||
return true;
|
||||
}
|
||||
trackedWorld = null;
|
||||
clearTrackedState();
|
||||
trackedWorld = world;
|
||||
return true;
|
||||
}
|
||||
|
||||
private void clearTrackedState() {
|
||||
chunks.clear();
|
||||
knownTileEntities.clear();
|
||||
transitions.clear();
|
||||
forEachTileEntity(NettyTileEntity::markRemoved);
|
||||
knownTileEntitiesByColumnBucket.clear();
|
||||
transitions.clearPublishedTransitions();
|
||||
}
|
||||
|
||||
public static int maskAndPack(int x, int y, int z) {
|
||||
return pack(x & LOCAL_MASK, y & LOCAL_MASK, z & LOCAL_MASK);
|
||||
private void removeTileEntitiesInChunk(int chunkX, int chunkZ) {
|
||||
SWMRInt2ObjectHashTable<NettyTileEntity<R>> map = knownTileEntitiesByColumnBucket;
|
||||
int bucketKey = packColumnBucket(chunkX, chunkZ);
|
||||
NettyTileEntity<R> head = map.get(bucketKey);
|
||||
if (head == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
boolean collision = false;
|
||||
for (NettyTileEntity<R> current = head; current != null; current = current.nextAcquire()) {
|
||||
if (current.chunkX() != chunkX || current.chunkZ() != chunkZ) {
|
||||
collision = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!collision) {
|
||||
// Removing the map entry publishes removal of the whole bucket. Keep the old chain intact so readers that
|
||||
// already acquired its head can finish their weakly-consistent traversal; detached nodes are never reused.
|
||||
map.remove(bucketKey, head);
|
||||
for (NettyTileEntity<R> current = head; current != null; current = current.nextAcquire()) {
|
||||
current.markRemoved();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
Logger.info("Chunk collision occured, failing back to linear scan for tile entity removal in chunk " + chunkX + ", " + chunkZ, 5, AbstractBlockView.class); // I want to see if this occurs frequently
|
||||
|
||||
// Wrapped-key collisions are rare. Remove matching nodes individually while preserving other columns.
|
||||
NettyTileEntity<R> currentHead = head;
|
||||
for (NettyTileEntity<R> current = head; current != null; ) {
|
||||
NettyTileEntity<R> next = current.nextAcquire();
|
||||
if (current.chunkX() == chunkX && current.chunkZ() == chunkZ) {
|
||||
currentHead = removeNode(map, bucketKey, currentHead, current);
|
||||
}
|
||||
current = next;
|
||||
}
|
||||
}
|
||||
|
||||
public static int pack(int x, int y, int z) {
|
||||
return (x & LOCAL_MASK) | ((y & LOCAL_MASK) << 4) | ((z & LOCAL_MASK) << 8);
|
||||
private NettyTileEntity<R> removeNode(SWMRInt2ObjectHashTable<NettyTileEntity<R>> map, int bucketKey, NettyTileEntity<R> head, NettyTileEntity<R> node) {
|
||||
node.markRemoved();
|
||||
if (node != head) {
|
||||
node.unlink();
|
||||
return head;
|
||||
}
|
||||
NettyTileEntity<R> successor = node.nextAcquire();
|
||||
if (successor == null) {
|
||||
map.remove(bucketKey, node);
|
||||
} else {
|
||||
map.put(bucketKey, successor);
|
||||
}
|
||||
node.detachHeadWriterOnly();
|
||||
return successor;
|
||||
}
|
||||
|
||||
public static int unpackX(int packed) {
|
||||
return packed & LOCAL_MASK;
|
||||
@SuppressWarnings("unchecked")
|
||||
private T findTileEntityInBucket(NettyTileEntity<R> bucketHead, BlockSpatial position) {
|
||||
for (NettyTileEntity<R> current = bucketHead; current != null; current = current.nextAcquire()) {
|
||||
if (current.blockX() == position.blockX() && current.blockY() == position.blockY() && current.blockZ() == position.blockZ()) {
|
||||
return (T) current;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static int unpackY(int packed) {
|
||||
return (packed >> 4) & LOCAL_MASK;
|
||||
private boolean isCurrentWorldEpoch(int expectedWorldEpoch) {
|
||||
return PlayerData.isStableWorldEpoch(expectedWorldEpoch) && worldEpochSupplier.getAsInt() == expectedWorldEpoch;
|
||||
}
|
||||
|
||||
public static int unpackZ(int packed) {
|
||||
return (packed >> 8) & LOCAL_MASK;
|
||||
private long tileEntityCheckModeTokenAcquire() {
|
||||
return (long) TILE_ENTITY_CHECK_MODE_TOKEN.getAcquire(this);
|
||||
}
|
||||
|
||||
private BitSet getChunk(UUID world, int chunkX, int chunkY, int chunkZ) {
|
||||
return chunks.get(new ChunkSectionLocatable.ImmutableChunkSectionLocatable(world, chunkX, chunkY, chunkZ));
|
||||
private void forEachTileEntity(Consumer<NettyTileEntity<R>> action) {
|
||||
knownTileEntitiesByColumnBucket.forEachValue(head -> {
|
||||
for (NettyTileEntity<R> current = head; current != null; current = current.nextAcquire()) {
|
||||
action.accept(current);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private BitSet getOrCreateChunk(UUID world, int chunkX, int chunkY, int chunkZ) {
|
||||
return chunks.computeIfAbsent(
|
||||
new ChunkSectionLocatable.ImmutableChunkSectionLocatable(world, chunkX, chunkY, chunkZ),
|
||||
ignored -> new BitSet(CHUNK_SIZE*CHUNK_SIZE*CHUNK_SIZE)
|
||||
);
|
||||
private static int packColumnBucket(int chunkX, int chunkZ) {
|
||||
// Keep the low 16 bits of X, then put the low 16 bits of Z in the upper half of the int.
|
||||
// Full coordinates on every tile disambiguate columns whose wrapped keys collide.
|
||||
return (chunkX & 0xFFFF) | (chunkZ & 0xFFFF) << 16;
|
||||
}
|
||||
|
||||
private static boolean modeEnabled(long modeToken) {
|
||||
return (modeToken & 1L) != 0L;
|
||||
}
|
||||
}
|
||||
@@ -1,54 +1,150 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.view;
|
||||
|
||||
import games.cubi.locatables.BlockLocatable;
|
||||
import games.cubi.locatables.implementations.ImmutableBlockLocatable;
|
||||
import games.cubi.raycastedantiesp.core.locatables.TileEntityLocatable;
|
||||
import games.cubi.raycastedantiesp.core.utils.Clearable;
|
||||
|
||||
import java.util.BitSet;
|
||||
import games.cubi.locatables.api.BlockLocatable;
|
||||
import games.cubi.locatables.api.BlockSpatial;
|
||||
import games.cubi.locatables.api.SpatialChunkSection;
|
||||
import games.cubi.raycastedantiesp.core.chunks.ChunkOcclusionView;
|
||||
import games.cubi.raycastedantiesp.core.tracked.TrackedTileEntity;
|
||||
import games.cubi.raycastedantiesp.core.chunks.BlockChunkData;
|
||||
import games.cubi.raycastedantiesp.core.chunks.OccludingChunkData;
|
||||
import games.cubi.utils.Clearable;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.IntSupplier;
|
||||
|
||||
/**
|
||||
* A per-player block view with one structural writer and concurrent weakly-consistent readers.
|
||||
*
|
||||
* <p>Packet-driven structural mutations, including chunk and tile membership changes, must all be performed by the
|
||||
* same outbound Netty thread. At most one engine worker concurrently traverses a player's view and commits visibility
|
||||
* decisions; visibility fields and the transition queue are safe for that Netty/engine overlap.</p>
|
||||
*/
|
||||
public interface BlockView extends Clearable {
|
||||
/**
|
||||
* Parameters are chunk coordinates
|
||||
*/
|
||||
ChunkOcclusionView getChunkOcclusionView(int chunkX, int chunkY, int chunkZ);
|
||||
|
||||
default ChunkOcclusionView getChunkOcclusionView(SpatialChunkSection chunkSection) {
|
||||
return getChunkOcclusionView(chunkSection.chunkX(), chunkSection.chunkY(), chunkSection.chunkZ());
|
||||
}
|
||||
|
||||
boolean isBlockOccluding(BlockLocatable location);
|
||||
|
||||
boolean isBlockOccluding(int x, int y, int z);
|
||||
|
||||
/**
|
||||
* Constructs a new tile entity with the provided id and visibility, or updates the block id for existing tile entities.
|
||||
* Constructs a new tile entity with the provided id and visibility, or updates the block id for an existing tile
|
||||
* entity. This is a structural-writer operation.
|
||||
*
|
||||
* @return the current tracked tile entity, or null when the location cannot be tracked.
|
||||
*/
|
||||
void updateOrInsertTileEntity(BlockLocatable location, int blockID, boolean visibleIfNew);
|
||||
TrackedTileEntity<?> updateOrInsertTileEntity(UUID world, BlockSpatial position, char blockID, boolean visibleIfNew);
|
||||
|
||||
void removeTileEntity(BlockLocatable location);
|
||||
/** Structural-writer operation. */
|
||||
void removeTileEntity(UUID world, BlockSpatial position);
|
||||
|
||||
TileEntityLocatable<?> getTrackedTileEntity(BlockLocatable location);
|
||||
TrackedTileEntity<?> getTrackedTileEntity(UUID world, BlockSpatial position);
|
||||
|
||||
TileEntityLocatable<?> getTrackedTileEntity(ImmutableBlockLocatable location);
|
||||
/** Returns the engine's desired visibility, not the state currently applied to the client. */
|
||||
boolean isVisible(UUID world, BlockSpatial position, int currentTick);
|
||||
|
||||
boolean isVisible(BlockLocatable location, int currentTick);
|
||||
/**
|
||||
* Records visibility established by the current outbound packet without queuing another packet. This synchronizes
|
||||
* both desired and client visibility and resets the check timestamp because the transmitted state supersedes the
|
||||
* result of any previous visibility check. The tile entity must be the current state returned by this view's
|
||||
* structural-writer operations.
|
||||
*/
|
||||
void recordOutboundTileEntityVisibility(TrackedTileEntity<?> tileEntity, boolean visible);
|
||||
|
||||
void setVisibility(BlockLocatable location, boolean visible, int currentTick);
|
||||
/**
|
||||
* Applies a mode change from the structural writer.
|
||||
*
|
||||
* Sets every desired state visible when checks are disabled and invokes {@code visibilityRepairConsumer} for each
|
||||
* tile entity still hidden from the client. The structural writer must send their current state directly rather
|
||||
* than publishing them to the engine transition queue.
|
||||
*/
|
||||
void applyTileEntityCheckMode(boolean enabled, int currentTick, Consumer<TrackedTileEntity<?>> visibilityRepairConsumer);
|
||||
|
||||
Collection<BlockLocatable> getKnownTileEntities();
|
||||
/** Returns an opaque enabled-state/generation snapshot for rejecting results that cross a mode change. */
|
||||
long tileEntityCheckModeToken();
|
||||
|
||||
Collection<BlockLocatable> getNeedingRecheck(int recheckTicks, int currentTick);
|
||||
/** Returns whether {@code modeToken} is still the current enabled generation. */
|
||||
boolean isCurrentEnabledTileEntityMode(long modeToken);
|
||||
|
||||
Collection<TrackedTileEntity<?>> getKnownTileEntities();
|
||||
|
||||
/**
|
||||
* Iterates currently tracked tile entities that should be visibility-checked.
|
||||
*
|
||||
* @return number of tile entities passed to {@code action}.
|
||||
*/
|
||||
int forEachNeedingRecheck(int recheckTicks, int currentTick, Consumer<TrackedTileEntity<?>> action);
|
||||
|
||||
@FunctionalInterface
|
||||
interface VisibilityResolver {
|
||||
byte SKIPPED = 78;
|
||||
byte HIDE = -23;
|
||||
byte SHOW = 42;
|
||||
|
||||
byte setVisible(TrackedTileEntity<?> tileEntity);
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterates currently tracked tile entities that should be visibility-checked.
|
||||
*
|
||||
* @return number of tile entities passed to {@code action}.
|
||||
*/
|
||||
int updateVisibilityForEachNeedingRecheck(int recheckTicks, int currentTick, long modeToken, int expectedWorldEpoch, VisibilityResolver action);
|
||||
|
||||
boolean hasPendingTransitions();
|
||||
|
||||
List<BlockViewTransition> drainTransitions();
|
||||
/** Publishes the partial transition batch owned by the current engine producer. */
|
||||
void flushPendingTransitions();
|
||||
|
||||
void upsertBlock(UUID world, int x, int y, int z, boolean occluding);
|
||||
@FunctionalInterface
|
||||
interface TransitionConsumer {
|
||||
void accept(TransitionType.Tile type, TrackedTileEntity<?> tileEntity, long modeToken, int worldEpoch);
|
||||
}
|
||||
|
||||
void drainTransitions(TransitionConsumer consumer);
|
||||
|
||||
/** Structural-writer operation. */
|
||||
void upsertBlock(UUID world, int x, int y, int z, int blockID);
|
||||
|
||||
/** Structural-writer operation. */
|
||||
void removeChunk(UUID world, int chunkX, int chunkZ);
|
||||
|
||||
/** Structural-writer operation. */
|
||||
void removeChunkSection(UUID world, int chunkX, int chunkY, int chunkZ);
|
||||
|
||||
void replaceChunkSection(UUID world, int chunkX, int chunkY, int chunkZ, BitSet occludingBlocks);
|
||||
/**
|
||||
* Removes tracked tile entities absent from an authoritative chunk column. A null {@code presentBySection} means
|
||||
* the entire column has no managed tiles; a null entry means that section has none. This is a structural-writer
|
||||
* operation.
|
||||
*/
|
||||
void pruneTileEntitiesAbsentFromChunkSections(UUID world, int chunkX, int chunkZ, int minimumSectionY, int sectionCount, long[][] presentBySection);
|
||||
|
||||
/** Structural-writer operation. */
|
||||
void replaceChunkSection(UUID world, int chunkX, int chunkY, int chunkZ, BlockChunkData data);
|
||||
|
||||
/** Structural-writer operation. */
|
||||
void replaceChunkSectionOcclusion(UUID world, int chunkX, int chunkY, int chunkZ, OccludingChunkData data);
|
||||
|
||||
default <T> T cast() {
|
||||
return (T) this;
|
||||
}
|
||||
|
||||
interface Factory {
|
||||
BlockView createBlockView();
|
||||
BlockView createBlockView(IntSupplier worldEpochSupplier);
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
package games.cubi.raycastedantiesp.core.view;
|
||||
|
||||
import games.cubi.locatables.BlockLocatable;
|
||||
|
||||
// Used to cache visibility changes until the player's netty thread next processes them.
|
||||
public record BlockViewTransition(Type type, BlockLocatable location) {
|
||||
public enum Type {
|
||||
SHOW,
|
||||
HIDE,
|
||||
}
|
||||
}
|
||||
@@ -1,25 +1,37 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.view;
|
||||
|
||||
import games.cubi.raycastedantiesp.core.locatables.EntityLocatable;
|
||||
import games.cubi.locatables.Locatable;
|
||||
import games.cubi.raycastedantiesp.core.utils.Clearable;
|
||||
import games.cubi.raycastedantiesp.core.tracked.TrackedEntity;
|
||||
import games.cubi.locatables.api.Spatial;
|
||||
import games.cubi.raycastedantiesp.core.tracked.NettyEntity;
|
||||
import games.cubi.utils.Clearable;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.IntSupplier;
|
||||
|
||||
public interface EntityView<T extends EntityLocatable<?, ?>> extends Clearable {
|
||||
void insertEntity(T entity);
|
||||
public interface EntityView<T extends TrackedEntity<?>> extends Clearable {
|
||||
void insertEntity(UUID world, T entity);
|
||||
|
||||
void removeEntity(int entityID, int currentTick);
|
||||
|
||||
void removeEntity(int entityID);
|
||||
|
||||
void removeEntity(UUID entityUUID, int currentTick);
|
||||
|
||||
T getEntity(UUID entityUUID);
|
||||
|
||||
T getEntity(int entityID);
|
||||
|
||||
Locatable getLocation(UUID entityUUID);
|
||||
Spatial getPosition(UUID entityUUID);
|
||||
|
||||
int getEntityID(UUID entityUUID);
|
||||
|
||||
@@ -27,22 +39,54 @@ public interface EntityView<T extends EntityLocatable<?, ?>> extends Clearable
|
||||
|
||||
boolean exists(int entityID);
|
||||
|
||||
@Deprecated
|
||||
boolean isVisible(UUID entityUUID, int currentTick);
|
||||
/**
|
||||
* Returns a weakly consistent count of the entities currently tracked by this view.
|
||||
* This operation is safe to call from threads other than the structural writer.
|
||||
*/
|
||||
int size();
|
||||
|
||||
boolean isVisible(UUID entityUUID);
|
||||
|
||||
boolean isVisible(int entityID);
|
||||
|
||||
void setVisibility(UUID entityUUID, boolean visible, int currentTick);
|
||||
void setVisibility(NettyEntity<?> entity, boolean visible, int currentTick, int expectedWorldEpoch);
|
||||
|
||||
/**
|
||||
* Applies visibility from the Netty structural writer without publishing an engine transition.
|
||||
*
|
||||
* @return whether the entity and epoch were current and the visibility was applied
|
||||
*/
|
||||
boolean recordDirectVisibility(NettyEntity<?> entity, boolean visible, int currentTick, int expectedWorldEpoch);
|
||||
|
||||
Collection<UUID> getKnownEntities();
|
||||
|
||||
Collection<UUID> getNeedingRecheck(int recheckTicks, int currentTick);
|
||||
int[] getKnownEntityIDs();
|
||||
|
||||
/**
|
||||
* Iterates currently tracked entities that should be visibility-checked.
|
||||
*
|
||||
* @return number of entities passed to {@code action}.
|
||||
*/
|
||||
int forEachNeedingRecheck(int visibleRecheckTicks, int currentTick, Consumer<UUID> action);
|
||||
|
||||
/**
|
||||
* Iterates currently tracked entities that should be visibility-checked.
|
||||
*
|
||||
* @return number of entities passed to {@code action}, or 0 if {@code countingActuallyNeeded} is false.
|
||||
*/
|
||||
int forEachNeedingRecheckEntity(int visibleRecheckTicks, int currentTick, boolean countingActuallyNeeded, int expectedWorldEpoch, Consumer<NettyEntity<?>> action);
|
||||
|
||||
boolean hasPendingTransitions();
|
||||
|
||||
List<EntityViewTransition> drainTransitions();
|
||||
/** Publishes the partial transition batch owned by the current engine producer. */
|
||||
void flushPendingTransitions();
|
||||
|
||||
@FunctionalInterface
|
||||
interface TransitionConsumer {
|
||||
void accept(TransitionType.Entity type, TrackedEntity<?> entity, int worldEpoch);
|
||||
}
|
||||
|
||||
void drainTransitions(TransitionConsumer consumer);
|
||||
|
||||
boolean isPlayerView();
|
||||
|
||||
@@ -53,6 +97,6 @@ public interface EntityView<T extends EntityLocatable<?, ?>> extends Clearable
|
||||
String getStringDataForDebugging();
|
||||
|
||||
interface Factory {
|
||||
EntityView<?> createEntityView();
|
||||
EntityView<?> createEntityView(IntSupplier worldEpochSupplier);
|
||||
}
|
||||
}
|
||||
Loaded 100 of 212 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user