mirror of
https://github.com/Cubicake/RaycastedAntiESP.git
synced 2026-11-17 06:26:04 -05:00
Compare commits
652
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4b9a5083ac | ||
|
|
f2e9919026 | ||
|
|
c47535cdb1 | ||
|
|
5ba314045e | ||
|
|
1e45335bad | ||
|
|
d6356faf6a | ||
|
|
81d05427e5 | ||
|
|
311b69433f | ||
|
|
7861298502 | ||
|
|
e6ba88d981 | ||
|
|
081ccb9408 | ||
|
|
63fab1d5ee | ||
|
|
bb628a7b41 | ||
|
|
43980c1364 | ||
|
|
321f8d4c3a | ||
|
|
d19987d337 | ||
|
|
65a4b7c94e | ||
|
|
8e0420b31f | ||
|
|
f686e81430 | ||
|
|
0ba40c8dbb | ||
|
|
6bce78a254 | ||
|
|
7ea2602282 | ||
|
|
bc37329ff7 | ||
|
|
8b57d5ce34 | ||
|
|
33cd4b0455 | ||
|
|
bf733b4c5b | ||
|
|
d3a088a30c | ||
|
|
0166031975 | ||
|
|
3b712d6918 | ||
|
|
d44f3d0fdf | ||
|
|
0e4dfc08b7 | ||
|
|
dbe72d3c5e | ||
|
|
4e1c77fe7b | ||
|
|
9c7bfdfa57 | ||
|
|
1e73d78724 | ||
|
|
a284eb98f5 | ||
|
|
2dafdb53af | ||
|
|
acb71072ac | ||
|
|
fdde9d957f | ||
|
|
3abc73e9f7 | ||
|
|
130166d787 | ||
|
|
c2e9d81942 | ||
|
|
b80a9c0f3c | ||
|
|
b493b1af2e | ||
|
|
807bfa02f3 | ||
|
|
d134343bc9 | ||
|
|
8c5aaea5f5 | ||
|
|
93fd8b4d3e | ||
|
|
417ebae0ec | ||
|
|
4cf4453996 | ||
|
|
785729c443 | ||
|
|
eb2ec969a9 | ||
|
|
fed0379899 | ||
|
|
934825daef | ||
|
|
627c3c3f10 | ||
|
|
36c349d7e9 | ||
|
|
593211fad2 | ||
|
|
e0037b5da9 | ||
|
|
4a71852fd4 | ||
|
|
0eb47f5a93 | ||
|
|
275fc53f9a | ||
|
|
e157f50f86 | ||
|
|
27ca927d55 | ||
|
|
a3e2f3d052 | ||
|
|
0c16268142 | ||
|
|
41bafad04c | ||
|
|
9f7a06cc89 | ||
|
|
94ee2ef6fd | ||
|
|
a2c09831cf | ||
|
|
8c61813bbf | ||
|
|
49acaaf4fa | ||
|
|
e6cca8d1b4 | ||
|
|
778ed7bb0e | ||
|
|
5e6e249fd4 | ||
|
|
6685d60fc4 | ||
|
|
7f9f6606bc | ||
|
|
e31349db26 | ||
|
|
58bab35223 | ||
|
|
4afe454de9 | ||
|
|
e75c3731b1 | ||
|
|
2556f5b369 | ||
|
|
0243cef884 | ||
|
|
f8fbbd8a74 | ||
|
|
f22133efe8 | ||
|
|
08db0d384f | ||
|
|
0ac8dc372f | ||
|
|
c5a5009fe9 | ||
|
|
aae0060cd4 | ||
|
|
56ff445cb6 | ||
|
|
be880e80c7 | ||
|
|
d80555c016 | ||
|
|
2e33bf9415 | ||
|
|
0f87b90787 | ||
|
|
0a9f115e92 | ||
|
|
ebfa47efbc | ||
|
|
5be167fdb3 | ||
|
|
0799b911a9 | ||
|
|
97d2bc7bdd | ||
|
|
0bd6b4203f | ||
|
|
f4a61f43ff | ||
|
|
9372928ae9 | ||
|
|
68ed857f25 | ||
|
|
30569c711f | ||
|
|
5005b3eb7b | ||
|
|
dd00bdd1fa | ||
|
|
0e1c2815ae | ||
|
|
489db71b2b | ||
|
|
2a821c0ebf | ||
|
|
7115fe6e34 | ||
|
|
323c83c93e | ||
|
|
aa0dc3297a | ||
|
|
cb4c55fdbd | ||
|
|
a6c79d4bbe | ||
|
|
3f8ac5cc5d | ||
|
|
3bd4c5339c | ||
|
|
9f3bb3793a | ||
|
|
baf560546f | ||
|
|
9f27907a83 | ||
|
|
f4eba53f7f | ||
|
|
f60934a023 | ||
|
|
e524d072b2 | ||
|
|
4e1ca5401c | ||
|
|
4381459a69 | ||
|
|
1e7be8637c | ||
|
|
5ee2a18173 | ||
|
|
c98c1c474f | ||
|
|
d3ddb28ec3 | ||
|
|
1a2469cbc4 | ||
|
|
1fc5000782 | ||
|
|
9121c0f4f6 | ||
|
|
5833213c20 | ||
|
|
1d3d3f5b55 | ||
|
|
dcb5af8721 | ||
|
|
ac3745d1e4 | ||
|
|
76d11242f6 | ||
|
|
108ba8a5b4 | ||
|
|
5228e06033 | ||
|
|
7884b02d8a | ||
|
|
fb861860bb | ||
|
|
d7036dd9d6 | ||
|
|
777e31cf59 | ||
|
|
7645335bb6 | ||
|
|
297278b998 | ||
|
|
b3455dfb92 | ||
|
|
2eecde1ee3 | ||
|
|
688f39463b | ||
|
|
fc23764bce | ||
|
|
5a57e44869 | ||
|
|
4318f8b23e | ||
|
|
8b370d0fe2 | ||
|
|
4a8527909a | ||
|
|
eca024118f | ||
|
|
3f814cd6d6 | ||
|
|
2cbe04c6cc | ||
|
|
2151f88f95 | ||
|
|
af387145fa | ||
|
|
8f760b7769 | ||
|
|
b4d35ab9f5 | ||
|
|
1c510322a9 | ||
|
|
dd1dd32391 | ||
|
|
f1342514e0 | ||
|
|
331bd2a4c0 | ||
|
|
a9de49a9a9 | ||
|
|
e2c61cb926 | ||
|
|
036ff55317 | ||
|
|
19c58d5a71 | ||
|
|
6c3d75643a | ||
|
|
587f45f86b | ||
|
|
5eb815010d | ||
|
|
70a0c1d1de | ||
|
|
c59d650a94 | ||
|
|
bcdbdf3c94 | ||
|
|
99eb62a72e | ||
|
|
e17d0b616a | ||
|
|
7c44cc1614 | ||
|
|
d75c5604e0 | ||
|
|
902d0dcf20 | ||
|
|
dbe04d1861 | ||
|
|
a0ffab833e | ||
|
|
e95fb3a97b | ||
|
|
d033cba970 | ||
|
|
c810152fa8 | ||
|
|
28929c0e20 | ||
|
|
8046bbad91 | ||
|
|
59fef9cd5d | ||
|
|
98b31ee4cf | ||
|
|
be5b1b59f6 | ||
|
|
49d8c7cbf7 | ||
|
|
a51ff8beaa | ||
|
|
c3183ef3d4 | ||
|
|
b5e78cc0ff | ||
|
|
3c7fabb52e | ||
|
|
004fc8bec9 | ||
|
|
45c6306482 | ||
|
|
b37624b38f | ||
|
|
5aaa9bd6c9 | ||
|
|
89a2629b77 | ||
|
|
83759a1c61 | ||
|
|
79cf23d04f | ||
|
|
513dfc2b96 | ||
|
|
1632258ae8 | ||
|
|
98b910fd2e | ||
|
|
4c97544ac7 | ||
|
|
d01b080207 | ||
|
|
f167004657 | ||
|
|
260278c380 | ||
|
|
fe864dfb42 | ||
|
|
ee84361f7f | ||
|
|
054b092b10 | ||
|
|
3dfcb5e8a4 | ||
|
|
53ffc67492 | ||
|
|
38d9f794e8 | ||
|
|
19c1db1fec | ||
|
|
38eeba1875 | ||
|
|
d3561e28ca | ||
|
|
702ef77248 | ||
|
|
e347904aa1 | ||
|
|
03d0844907 | ||
|
|
ca41d935aa | ||
|
|
a7764ada31 | ||
|
|
53c3c5cb4c | ||
|
|
a065180096 | ||
|
|
2389ac0f8a | ||
|
|
b12037bbe9 | ||
|
|
6b8abe25cf | ||
|
|
a791eabacb | ||
|
|
ceb0d48554 | ||
|
|
9e7c62dc02 | ||
|
|
4c21c16e3b | ||
|
|
2db473077f | ||
|
|
078cfa8266 | ||
|
|
e7ee8991b9 | ||
|
|
77a7394d22 | ||
|
|
c34bfdb61f | ||
|
|
43e11210cf | ||
|
|
cb39e82485 | ||
|
|
d3756978dc | ||
|
|
fcaffbabcc | ||
|
|
c6e4af9cdb | ||
|
|
335958939b | ||
|
|
12c3894d04 | ||
|
|
50fdebf44b | ||
|
|
f941b6cc7b | ||
|
|
c30aced6be | ||
|
|
7eb515d8c2 | ||
|
|
36ddc2ab4b | ||
|
|
5e13f99fbf | ||
|
|
af1e35cf80 | ||
|
|
1ac28cca35 | ||
|
|
562f203d09 | ||
|
|
a1c0a6d860 | ||
|
|
2e816d92b8 | ||
|
|
3fedbc2a17 | ||
|
|
abd2dab77c | ||
|
|
a7eacf704d | ||
|
|
a55022d4fd | ||
|
|
8b6b0332eb | ||
|
|
79f018cd13 | ||
|
|
5815d327cf | ||
|
|
b76b0c900b | ||
|
|
9c6ab79f1c | ||
|
|
01f37f6e1d | ||
|
|
958c6468b4 | ||
|
|
3977e21568 | ||
|
|
92dfbe9599 | ||
|
|
74f823b1a7 | ||
|
|
7d07e67d5b | ||
|
|
7ddf475e90 | ||
|
|
20bd20b60a | ||
|
|
e858c4e6eb | ||
|
|
5127ebd260 | ||
|
|
f88b482a65 | ||
|
|
a325dcc05f | ||
|
|
186dd11aeb | ||
|
|
4131f0c61b | ||
|
|
5d94735581 | ||
|
|
7d6a4860f6 | ||
|
|
31b6ec3426 | ||
|
|
97703c90d0 | ||
|
|
d9109fcbcd | ||
|
|
ba93e28d09 | ||
|
|
55de301117 | ||
|
|
2da16f39a5 | ||
|
|
ff81ae5d1a | ||
|
|
18472570f4 | ||
|
|
07d563c343 | ||
|
|
6b89ab91e1 | ||
|
|
8b6c2a895f | ||
|
|
eb49446618 | ||
|
|
6d3e768689 | ||
|
|
d828461ce5 | ||
|
|
bf51d0cfb6 | ||
|
|
73cec9faf5 | ||
|
|
af7c1253e2 | ||
|
|
d84b4c4bd8 | ||
|
|
b8998ca936 | ||
|
|
2363190bbf | ||
|
|
7068eec49e | ||
|
|
516f4425a7 | ||
|
|
5c541178a4 | ||
|
|
acab9879e1 | ||
|
|
d1c7efa586 | ||
|
|
21dceabb2f | ||
|
|
ea8e11710c | ||
|
|
72b838921f | ||
|
|
55d770496a | ||
|
|
bfbe635032 | ||
|
|
d560cbbd56 | ||
|
|
a0a3834c13 | ||
|
|
566cd93e8d | ||
|
|
78fcec3f11 | ||
|
|
fbdbcd39e3 | ||
|
|
2f0555c030 | ||
|
|
758263345f | ||
|
|
56ec5ffcb7 | ||
|
|
7e58806271 | ||
|
|
9791348634 | ||
|
|
09a95cc735 | ||
|
|
529b7977d4 | ||
|
|
6f4a6d4b2e | ||
|
|
f57829e7fc | ||
|
|
cf69030c56 | ||
|
|
828f302d5c | ||
|
|
927066adb9 | ||
|
|
7c2fc00a87 | ||
|
|
29890541af | ||
|
|
0ebd1903b1 | ||
|
|
f0cb5d0281 | ||
|
|
300ae927d7 | ||
|
|
54dc47c89f | ||
|
|
60f8ea55b0 | ||
|
|
47e7a08547 | ||
|
|
e2089aace3 | ||
|
|
cef2a0e7ee | ||
|
|
609fa9f9f4 | ||
|
|
383bfe0abe | ||
|
|
bd2c0f0c62 | ||
|
|
08dff2867f | ||
|
|
84114b3325 | ||
|
|
30f78ab351 | ||
|
|
0d8eec08ae | ||
|
|
79d67832ac | ||
|
|
8429c33791 | ||
|
|
ddc5052741 | ||
|
|
9aff6869d1 | ||
|
|
09f92498fc | ||
|
|
47182ad24a | ||
|
|
e1a7a9b278 | ||
|
|
5390965693 | ||
|
|
75e7a3ddff | ||
|
|
17c0db3980 | ||
|
|
13e6ece4ae | ||
|
|
dfe1ff6f9c | ||
|
|
c84993571a | ||
|
|
a2efea0060 | ||
|
|
15d30ce397 | ||
|
|
5baeb75619 | ||
|
|
11ef7e6388 | ||
|
|
6c1b3fdc7c | ||
|
|
1a25c49271 | ||
|
|
001e8b3688 | ||
|
|
22c1321873 | ||
|
|
167b4be8b8 | ||
|
|
0a5c130cd1 | ||
|
|
eb64d03d05 | ||
|
|
95d14e97b3 | ||
|
|
c1e71c52aa | ||
|
|
18e1857d83 | ||
|
|
6a1214e126 | ||
|
|
6b1f9cf24f | ||
|
|
96dec1d654 | ||
|
|
b6507cb052 | ||
|
|
5f27b1da1f | ||
|
|
433a09b7c6 | ||
|
|
a57dba3ff4 | ||
|
|
5f34f0cc6f | ||
|
|
c09a69381f | ||
|
|
44f9bf4196 | ||
|
|
973e500c9f | ||
|
|
f436f31dea | ||
|
|
a6b9d34bab | ||
|
|
b5ef1d7ac4 | ||
|
|
516197aa36 | ||
|
|
08212cdb78 | ||
|
|
4658e99bd9 | ||
|
|
f74d6c90e8 | ||
|
|
26e830bdd0 | ||
|
|
0fb6d31cde | ||
|
|
07b2c50edc | ||
|
|
be9796c712 | ||
|
|
433f873f82 | ||
|
|
914909039e | ||
|
|
92c5a9f4d1 | ||
|
|
bfaa8605f0 | ||
|
|
55f68eed8c | ||
|
|
2634b1a59e | ||
|
|
dd4d0476dd | ||
|
|
b6bb3abd28 | ||
|
|
a70ecf0b9d | ||
|
|
40b7d9e58d | ||
|
|
05e2caaf43 | ||
|
|
4030db77c7 | ||
|
|
d2913e2c64 | ||
|
|
9f5fa5cd3a | ||
|
|
2f92860f76 | ||
|
|
4d06bac9a3 | ||
|
|
7b63d6b352 | ||
|
|
1fe44a8e45 | ||
|
|
bb3f06a070 | ||
|
|
c9ee55f864 | ||
|
|
5654216ac3 | ||
|
|
351397852c | ||
|
|
6532fb619c | ||
|
|
ae63a4c56f | ||
|
|
ae4ff7c593 | ||
|
|
e016d4339f | ||
|
|
d1071427d1 | ||
|
|
c4d56582d8 | ||
|
|
266e04aa0c | ||
|
|
cf0240b940 | ||
|
|
1eee0946a3 | ||
|
|
f49f58749b | ||
|
|
8e06c4a3d8 | ||
|
|
1f5e428023 | ||
|
|
96a92e95e9 | ||
|
|
5e80239c14 | ||
|
|
8943800c59 | ||
|
|
858b08d558 | ||
|
|
625218513f | ||
|
|
e9cd8a031e | ||
|
|
4d161ca0a2 | ||
|
|
6a92d4de18 | ||
|
|
b8ecbf3636 | ||
|
|
e53fad05e3 | ||
|
|
8138e326b6 | ||
|
|
a31ba406c6 | ||
|
|
2237edc1fd | ||
|
|
f8ec2b7000 | ||
|
|
00ee95a537 | ||
|
|
0e31708380 | ||
|
|
5a3b083928 | ||
|
|
a9cc1ab604 | ||
|
|
4d20087dfa | ||
|
|
b8236c2e6d | ||
|
|
d3d67de973 | ||
|
|
96ee9c6931 | ||
|
|
b184eda584 | ||
|
|
d15420d46a | ||
|
|
b62a008063 | ||
|
|
3e00bbf61b | ||
|
|
359feffdcf | ||
|
|
06978953b1 | ||
|
|
e1fc76df77 | ||
|
|
4153cf4aac | ||
|
|
2d7303eb33 | ||
|
|
b0d8e32202 | ||
|
|
5649f4ad7c | ||
|
|
9e5ad8c0a3 | ||
|
|
57848b81f8 | ||
|
|
2dc2dbb5f7 | ||
|
|
34690d2408 | ||
|
|
90f5ddbe8a | ||
|
|
98edc8968b | ||
|
|
e632a5b98d | ||
|
|
5d8c786ba4 | ||
|
|
bd1edf8332 | ||
|
|
7a003368ff | ||
|
|
542d681bb4 | ||
|
|
500aa72106 | ||
|
|
e9a22ff518 | ||
|
|
fca7cc9d2d | ||
|
|
4486e60ff2 | ||
|
|
f322ab668a | ||
|
|
59059248df | ||
|
|
b499b62745 | ||
|
|
2d7dc391ae | ||
|
|
d81a7bde44 | ||
|
|
149bae4ac2 | ||
|
|
d61be5ba8d | ||
|
|
c06fe81df3 | ||
|
|
9c7dd360a5 | ||
|
|
c58417f15b | ||
|
|
7b6c663510 | ||
|
|
1a97a70d9b | ||
|
|
ee473162bf | ||
|
|
41b41cace6 | ||
|
|
01cd0d04da | ||
|
|
7b6aa88e0f | ||
|
|
dbef12eb7b | ||
|
|
15f5d77bae | ||
|
|
f45c85a838 | ||
|
|
8cdad10f14 | ||
|
|
ae98d76ded | ||
|
|
3f1e3a170d | ||
|
|
3c053dbacc | ||
|
|
1e0f08083e | ||
|
|
ae66f039f7 | ||
|
|
5224317545 | ||
|
|
6a3a8b5768 | ||
|
|
4eeb2b5d06 | ||
|
|
0995d546da | ||
|
|
a01ff503f4 | ||
|
|
066c6a32ea | ||
|
|
5d2b6c9f4a | ||
|
|
7a8a7364df | ||
|
|
0072c9ff8e | ||
|
|
d78f562762 | ||
|
|
c6e845527e | ||
|
|
68cb54c0ed | ||
|
|
7c45f6ec4e | ||
|
|
53f0615805 | ||
|
|
dd9d807d92 | ||
|
|
902ed25a5b | ||
|
|
7a90d92c0a | ||
|
|
7ca097b35c | ||
|
|
d0a6c8475e | ||
|
|
b1fa7e7c96 | ||
|
|
70bbb06ee9 | ||
|
|
8193baf9df | ||
|
|
d6e62f11ee | ||
|
|
992dad2775 | ||
|
|
814cf86541 | ||
|
|
f3e4c1cb47 | ||
|
|
0bf28b6951 | ||
|
|
e71e9006fd | ||
|
|
06b3395d03 | ||
|
|
222987baae | ||
|
|
a495d3946d | ||
|
|
7a514d6236 | ||
|
|
26a4d4c10c | ||
|
|
cbb48372ac | ||
|
|
ff31d9085a | ||
|
|
1d93653422 | ||
|
|
db13824a0f | ||
|
|
dba313847c | ||
|
|
c319a6ffd4 | ||
|
|
486e5dcb36 | ||
|
|
20842449af | ||
|
|
027f62727a | ||
|
|
3ae7ca0d2e | ||
|
|
3fa02c2561 | ||
|
|
32a0b94f61 | ||
|
|
e28b7b6f23 | ||
|
|
2fc7e50145 | ||
|
|
c56ee078c9 | ||
|
|
4400151878 | ||
|
|
50d0e54687 | ||
|
|
2f15ca9d5b | ||
|
|
f6535848c0 | ||
|
|
4b96935f34 | ||
|
|
40b99d5c43 | ||
|
|
e448e18472 | ||
|
|
d806ae3c0b | ||
|
|
34fe60a7ae | ||
|
|
0ff67e11a7 | ||
|
|
98eaf72cae | ||
|
|
e5c7f6ef90 | ||
|
|
da73bb26ec | ||
|
|
bd57a9b72c | ||
|
|
116f5e8e03 | ||
|
|
bcfdd731e2 | ||
|
|
e83ec5e6a2 | ||
|
|
2b48e7e8d2 | ||
|
|
38c39aecc5 | ||
|
|
70ec4c212f | ||
|
|
d5026d28d4 | ||
|
|
df5e9f6ca8 | ||
|
|
7f1a284eae | ||
|
|
87aba0e2b5 | ||
|
|
d46d63668b | ||
|
|
83a278b00a | ||
|
|
c1e0db5613 | ||
|
|
34db141f08 | ||
|
|
61831a813a | ||
|
|
a68bcfdbf5 | ||
|
|
9ca8b4ee3a | ||
|
|
77825067de | ||
|
|
635f407c3a | ||
|
|
c18b30da36 | ||
|
|
b524cfdf10 | ||
|
|
968c803106 | ||
|
|
77c5a18433 | ||
|
|
085fa59e42 | ||
|
|
2db88a4498 | ||
|
|
081e762c5c | ||
|
|
1733fd1884 | ||
|
|
773378e6cb | ||
|
|
ac67aa8786 | ||
|
|
40bbaeb5ff | ||
|
|
76f5816162 | ||
|
|
1201ff1370 | ||
|
|
e9935f0350 | ||
|
|
11f1c6ecb7 | ||
|
|
0a6302674d | ||
|
|
4283dfd87b | ||
|
|
9d01af18f3 | ||
|
|
77dd9bb31a | ||
|
|
47f862323b | ||
|
|
c356ed0172 | ||
|
|
8d39fa5427 | ||
|
|
7e0725c538 | ||
|
|
b958d0dc46 | ||
|
|
e9adb65690 | ||
|
|
6a289c81a9 | ||
|
|
34b04ff059 | ||
|
|
1a73c2509a | ||
|
|
e3731f76f0 | ||
|
|
bd1f6ad482 | ||
|
|
951e4f4ad9 | ||
|
|
114746aeaf | ||
|
|
9dc9652917 | ||
|
|
b97f675159 | ||
|
|
f5e16fc75d | ||
|
|
6dc3f2f84e | ||
|
|
8e76557a88 | ||
|
|
f76e2bbcf7 | ||
|
|
c228cef24a | ||
|
|
098aab5e31 | ||
|
|
31b500bc7b | ||
|
|
d5e3281cf2 | ||
|
|
98dbefd576 | ||
|
|
4dce9b3278 | ||
|
|
d5bf02b4ea | ||
|
|
ed98e2abeb | ||
|
|
9a07bd0119 | ||
|
|
87cd59b346 | ||
|
|
74aca26910 | ||
|
|
25f5652a12 | ||
|
|
7679f08d06 | ||
|
|
7ad99917d1 | ||
|
|
ce56eb316e | ||
|
|
74426d80af | ||
|
|
fdb1f567ac | ||
|
|
e823f7a2f7 | ||
|
|
7c1f7fd2a6 | ||
|
|
c26e6a1623 | ||
|
|
8155903342 | ||
|
|
f2ade6b0b8 | ||
|
|
f486d1fc2e | ||
|
|
50eeab8cfe | ||
|
|
4009fe6d02 | ||
|
|
b7e6fa9c5f | ||
|
|
dcc986c232 | ||
|
|
95cea9f875 | ||
|
|
a151bdbeca | ||
|
|
6d288de95b | ||
|
|
aa0ebdbc93 | ||
|
|
af50b9c69c | ||
|
|
963fbbe9be | ||
|
|
02ef0c3343 | ||
|
|
1ac6e6b50b | ||
|
|
f1dfe64d67 |
No files matched your search
@@ -0,0 +1,15 @@
|
||||
# These are supported funding model platforms
|
||||
|
||||
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
|
||||
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
|
||||
issuehunt: # Replace with a single IssueHunt username
|
||||
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
|
||||
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']
|
||||
@@ -0,0 +1,26 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve
|
||||
title: "[Bug]: xyz"
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Describe the bug**
|
||||
A clear and concise description of what the bug is.
|
||||
|
||||
**To Reproduce**
|
||||
Steps to reproduce the behaviour. A video or images may be helpful here.
|
||||
|
||||
**Expected behavior**
|
||||
A clear and concise description of what you expected to happen.
|
||||
|
||||
**General debugging information**
|
||||
- Any relevant crash or console logs
|
||||
- The output of `/raycastedentityocclusions`
|
||||
- The output of `/raycastedentityocclusions config-values`
|
||||
- The link returned by `/spark profiler start --timeout 11`
|
||||
|
||||
**Additional context**
|
||||
Add any other context about the problem here.
|
||||
@@ -0,0 +1,20 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea for this project
|
||||
title: "[Feature Request]"
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Is your feature request related to a problem? Please describe.**
|
||||
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
||||
|
||||
**Describe the solution you'd like**
|
||||
A clear and concise description of what you want to happen.
|
||||
|
||||
**Describe alternatives you've considered**
|
||||
A clear and concise description of any alternative solutions or features you've considered.
|
||||
|
||||
**Additional context**
|
||||
Add any other context or screenshots about the feature request here.
|
||||
+4
-1
@@ -1,11 +1,13 @@
|
||||
# User-specific stuff
|
||||
.idea/
|
||||
|
||||
README.md
|
||||
*.md
|
||||
|
||||
*.iml
|
||||
*.ipr
|
||||
*.iws
|
||||
|
||||
README.md
|
||||
|
||||
# IntelliJ
|
||||
out/
|
||||
@@ -116,6 +118,7 @@ gradle-app.setting
|
||||
# Common working directory
|
||||
run/
|
||||
runs/
|
||||
run-1-21-11/
|
||||
|
||||
# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
|
||||
!gradle-wrapper.jar
|
||||
@@ -0,0 +1,3 @@
|
||||
[submodule "logging"]
|
||||
path = logging
|
||||
url = https://github.com/Cubicake/CubiLogging.git
|
||||
@@ -0,0 +1,6 @@
|
||||
## 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`.
|
||||
|
||||
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).
|
||||
@@ -1,12 +1,12 @@
|
||||
Latest version: v1.5.1
|
||||
### Latest stable version: v1.6.5
|
||||
|
||||
The latest version can currently only be found on Modrinth https://modrinth.com/plugin/raycasted-entity-occlusions/
|
||||
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`.
|
||||
|
||||
This is an async plugin for PaperMC and its forks that hides/culls entities (and tile entities) from players if they do not have line-of-sight.
|
||||
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.
|
||||
The supported versions are 1.21.x PaperMC and Pufferfish. Other server versions and software may work too. v2 alpha builds support 26.x.
|
||||
|
||||
Use cases:
|
||||
## Use cases:
|
||||
|
||||
- Prevent cheating (anti-esp hacks)
|
||||
- Block usage of pie-ray to locate underground bases
|
||||
@@ -15,7 +15,22 @@ Use cases:
|
||||
- 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.
|
||||
- Hide nametags behind walls
|
||||
- Yes, this plugin is a bit overkill for doing that, yes you can do it anyways.
|
||||
|
||||
## Dependencies:
|
||||
- Packetevents (soft depend)
|
||||
- Only needed if you are using the cull-players option and wish for the players to remain in the tablist
|
||||
|
||||
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
|
||||
- If cull-player is set to true any culled players will be removed from tablist. Potential solutions are being investigated, suggestions are welcome.
|
||||
## 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.
|
||||
|
||||
## Versioning:
|
||||
Note that the following versioning information only applies to v2 and beyond.
|
||||
|
||||
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.
|
||||
|
||||
Each of these has its own versioning system. Locatable-lib and the logging api both declare public apis, and follow [Semantic Versioning](https://semver.org/#semantic-versioning-specification-semver). The platform adapter and core do not declare public apis, and thus [cannot follow semantic versioning](https://semver.org/#spec-item-1). They still follow a major.minor.patch versioning system, but which version number increments is less deterministic. Generally, major version bumps will be for when significant refactoring or rewriting has occurred, or a very significant distinct feature has been added or removed. Minor version bumps will be for the addition/removal of smaller distinct features, while patch version bumps are for bug fixes and tweaks or minor addition/removals which are related to the features added/removed in the minor version bumps.
|
||||
|
||||
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.
|
||||
|
||||
## Contributions:
|
||||
Contributions via pull requests are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md) for details.
|
||||
@@ -1,53 +0,0 @@
|
||||
plugins {
|
||||
id 'java'
|
||||
}
|
||||
|
||||
group = 'games.cubi'
|
||||
version = '1.6.0-dev-1'
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
maven {
|
||||
name = "papermc-repo"
|
||||
url = "https://repo.papermc.io/repository/maven-public/"
|
||||
}
|
||||
maven {
|
||||
name = "sonatype"
|
||||
url = "https://oss.sonatype.org/content/groups/public/"
|
||||
}
|
||||
maven { url = uri("https://repo.codemc.io/repository/maven-releases/") }
|
||||
|
||||
maven { url = uri("https://repo.codemc.io/repository/maven-snapshots/") }
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compileOnly("io.papermc.paper:paper-api:1.21.4-R0.1-SNAPSHOT")
|
||||
compileOnly("com.github.retrooper:packetevents-spigot:2.8.0")
|
||||
}
|
||||
|
||||
def targetJavaVersion = 21
|
||||
java {
|
||||
def javaVersion = JavaVersion.toVersion(targetJavaVersion)
|
||||
sourceCompatibility = javaVersion
|
||||
targetCompatibility = javaVersion
|
||||
if (JavaVersion.current() < javaVersion) {
|
||||
toolchain.languageVersion = JavaLanguageVersion.of(targetJavaVersion)
|
||||
}
|
||||
}
|
||||
|
||||
tasks.withType(JavaCompile).configureEach {
|
||||
options.encoding = 'UTF-8'
|
||||
|
||||
if (targetJavaVersion >= 10 || JavaVersion.current().isJava10Compatible()) {
|
||||
options.release.set(targetJavaVersion)
|
||||
}
|
||||
}
|
||||
|
||||
processResources {
|
||||
def props = [version: version]
|
||||
inputs.properties props
|
||||
filteringCharset 'UTF-8'
|
||||
filesMatching('plugin.yml') {
|
||||
expand props
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import java.time.Instant
|
||||
|
||||
plugins {
|
||||
id("java-library")
|
||||
}
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
maven { url = uri("https://repo.codemc.io/repository/maven-releases/") }
|
||||
maven { url = uri("https://repo.codemc.io/repository/maven-snapshots/") }
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compileOnly("org.spongepowered:configurate-core:4.2.0")
|
||||
compileOnly("org.spongepowered:configurate-yaml:4.2.0")
|
||||
compileOnly("it.unimi.dsi:fastutil:8.5.18")
|
||||
implementation(project(":locatable-lib"))
|
||||
compileOnly(project(":logging"))
|
||||
}
|
||||
|
||||
val coreVersion = "0.4.1-SNAPSHOT"
|
||||
|
||||
val isRelease = gradle.startParameter.taskNames.any {
|
||||
it.contains("buildRelease")
|
||||
}
|
||||
|
||||
fun getVersionString(): String {
|
||||
if (isRelease) {
|
||||
return coreVersion.substringBefore("-") // Remove any suffixes like "-SNAPSHOT"
|
||||
} else {
|
||||
return coreVersion
|
||||
}
|
||||
}
|
||||
|
||||
fun getBasicVersionString(): String {
|
||||
return if (isRelease) {
|
||||
coreVersion.substringBefore("-") // Remove any suffixes like "-SNAPSHOT"
|
||||
} else {
|
||||
coreVersion
|
||||
}
|
||||
}
|
||||
|
||||
version = getVersionString()
|
||||
|
||||
val commitShort = providers.exec {
|
||||
commandLine("git", "rev-parse", "--short=8", "HEAD")
|
||||
}.standardOutput.asText.map { it.trim() }
|
||||
|
||||
val commitFull = providers.exec {
|
||||
commandLine("git", "rev-parse", "HEAD")
|
||||
}.standardOutput.asText.map { it.trim() }
|
||||
|
||||
val buildTime = providers.provider {
|
||||
Instant.now().toString()
|
||||
}
|
||||
|
||||
tasks {
|
||||
processResources {
|
||||
val gitProps = mapOf(
|
||||
"short_git" to commitShort.get(),
|
||||
"long_git" to commitFull.get(),
|
||||
"build_time" to buildTime.get(),
|
||||
"version" to getBasicVersionString()
|
||||
)
|
||||
inputs.properties(gitProps)
|
||||
filesMatching("build-properties/core.yml") {
|
||||
expand(gitProps)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
java {
|
||||
toolchain.languageVersion = JavaLanguageVersion.of(21)
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package games.cubi.raycastedantiesp.core;
|
||||
|
||||
import games.cubi.logs.PlatformLogger;
|
||||
import games.cubi.logs.Logger;
|
||||
|
||||
public class Core {
|
||||
|
||||
public static Core instance;
|
||||
|
||||
private Core(PlatformLogger logger) {
|
||||
Logger.init(logger);
|
||||
}
|
||||
|
||||
public static Core initialize(PlatformLogger logger) {
|
||||
if (instance != null) {
|
||||
return instance;
|
||||
}
|
||||
instance = new Core(logger);
|
||||
return instance;
|
||||
}
|
||||
|
||||
public static Core getInstance() {
|
||||
if (instance == null) {
|
||||
Logger.error(new IllegalStateException("Core has not been initialized yet but Core#getInstance called!"),1, Core.class);
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
public void intelliJStopThinkingThisIsAUtilClass() {}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
|
||||
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")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public enum BlockProcessorMode implements ConfigEnum {
|
||||
PACKETEVENTS("packetevents");
|
||||
|
||||
private final String configName;
|
||||
|
||||
BlockProcessorMode(String configName) {
|
||||
this.configName = configName;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return configName;
|
||||
}
|
||||
|
||||
public static @Nullable BlockProcessorMode fromString(String name) {
|
||||
for (BlockProcessorMode mode : values()) {
|
||||
if (mode.configName.equalsIgnoreCase(name)) {
|
||||
return mode;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getValues() {
|
||||
return new String[] {configName};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
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 org.spongepowered.configurate.ConfigurationNode;
|
||||
|
||||
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")
|
||||
);
|
||||
}
|
||||
|
||||
public boolean hasRestartOnlyChanges(ChecksConfig startup) {
|
||||
return playerConfig.enabled() != startup.playerConfig.enabled()
|
||||
|| entityConfig.enabled() != startup.entityConfig.enabled()
|
||||
|| tileEntityConfig.enabled() != startup.tileEntityConfig.enabled()
|
||||
|| chunkSectionConfig.enabled() != startup.chunkSectionConfig.enabled();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
public interface Config {
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
public interface ConfigEnum {
|
||||
String[] getValues();
|
||||
|
||||
Registry REGISTRY = new Registry();
|
||||
|
||||
default void register() {
|
||||
REGISTRY.add(this.getClass());
|
||||
}
|
||||
|
||||
static String[] getAllValues() {
|
||||
return REGISTRY.getAllValues();
|
||||
}
|
||||
|
||||
final class Registry {
|
||||
private final Set<Class<? extends ConfigEnum>> enums = new HashSet<>();
|
||||
|
||||
void add(Class<? extends ConfigEnum> e) {
|
||||
enums.add(e);
|
||||
}
|
||||
|
||||
String[] getAllValues() {
|
||||
return enums.stream()
|
||||
.flatMap(e -> Arrays.stream(e.getEnumConstants()[0].getValues()))
|
||||
.toArray(String[]::new);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
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,11 @@
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
public class ConfigLoadException extends RuntimeException {
|
||||
public ConfigLoadException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public ConfigLoadException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
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.EntityConfig;
|
||||
import games.cubi.raycastedantiesp.core.config.raycast.PlayerConfig;
|
||||
import games.cubi.raycastedantiesp.core.config.raycast.TileEntityConfig;
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
import org.spongepowered.configurate.yaml.NodeStyle;
|
||||
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.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class ConfigManager {
|
||||
private static final String REQUIRED_CONFIG_VERSION = "2.0";
|
||||
private static ConfigManager instance;
|
||||
|
||||
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 ConfigurationNode config;
|
||||
private RootConfig startupConfig;
|
||||
private volatile RootConfig activeConfig;
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
public static ConfigManager initialiseConfigManager(Supplier<InputStream> resourceSupplier, Path dataFolder, List<ConfigExtension<? extends Config>> extensions) {
|
||||
if (instance == null) {
|
||||
instance = new ConfigManager(resourceSupplier, dataFolder, extensions);
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
public static ConfigManager get() {
|
||||
if (instance == null) {
|
||||
Logger.errorAndReturn(new RuntimeException("ConfigManager accessed before being initiated. Please report this."), 2, ConfigManager.class);
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
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 SetConfigResult setConfigValue(String path, String rawValue) {
|
||||
ConfigurationNode candidate = loadConfigNode();
|
||||
ConfigurationNode target = node(candidate, path);
|
||||
if (target.virtual()) {
|
||||
return SetConfigResult.invalid("Unknown config path: " + path);
|
||||
}
|
||||
|
||||
ConfigReader.setRaw(target, ConfigReader.parseRawValue(rawValue));
|
||||
|
||||
return applyCandidate(candidate, false);
|
||||
}
|
||||
|
||||
public SetConfigResult addConfigListValue(String path, String rawValue) {
|
||||
return mutateConfigListValue(path, rawValue, ListMutation.ADD);
|
||||
}
|
||||
|
||||
public SetConfigResult removeConfigListValue(String path, String rawValue) {
|
||||
return mutateConfigListValue(path, rawValue, ListMutation.REMOVE);
|
||||
}
|
||||
|
||||
private SetConfigResult mutateConfigListValue(String path, String rawValue, ListMutation mutation) {
|
||||
ConfigurationNode candidate = loadConfigNode();
|
||||
ConfigurationNode target = node(candidate, path);
|
||||
if (target.virtual()) {
|
||||
return SetConfigResult.invalid("Unknown config path: " + path);
|
||||
}
|
||||
if (!target.childrenMap().isEmpty()) {
|
||||
return SetConfigResult.invalid(path + " is not a list path");
|
||||
}
|
||||
|
||||
List<Object> values = new ArrayList<>(target.childrenList().stream().map(ConfigurationNode::raw).toList());
|
||||
if (values.isEmpty() && target.raw() != null && !(target.raw() instanceof List<?>)) {
|
||||
return SetConfigResult.invalid(path + " is not a list path");
|
||||
}
|
||||
|
||||
Object parsedValue = ConfigReader.parseRawValue(rawValue);
|
||||
boolean changed = switch (mutation) {
|
||||
case ADD -> {
|
||||
if (values.contains(parsedValue)) {
|
||||
yield false;
|
||||
}
|
||||
values.add(parsedValue);
|
||||
yield true;
|
||||
}
|
||||
case REMOVE -> values.remove(parsedValue);
|
||||
};
|
||||
|
||||
if (!changed) {
|
||||
return SetConfigResult.invalid("No change made for " + path);
|
||||
}
|
||||
|
||||
ConfigReader.setRaw(target, values);
|
||||
return applyCandidate(candidate, true);
|
||||
}
|
||||
|
||||
private SetConfigResult applyCandidate(ConfigurationNode candidate, boolean allowRestartRequired) {
|
||||
RootConfig parsed;
|
||||
try {
|
||||
parsed = parse(candidate);
|
||||
validateReload(parsed);
|
||||
} catch (RestartRequiredException e) {
|
||||
if (!allowRestartRequired) {
|
||||
return SetConfigResult.invalid(e.getMessage());
|
||||
}
|
||||
config = candidate;
|
||||
saveConfigNode(candidate);
|
||||
return SetConfigResult.restartRequired(e.getMessage());
|
||||
} catch (ConfigLoadException e) {
|
||||
return SetConfigResult.invalid(e.getMessage());
|
||||
}
|
||||
|
||||
config = candidate;
|
||||
activeConfig = parsed;
|
||||
saveConfigNode(candidate);
|
||||
return SetConfigResult.ok();
|
||||
}
|
||||
|
||||
public PlayerConfig getPlayerConfig() {
|
||||
return activeConfig.checksConfig().playerConfig();
|
||||
}
|
||||
|
||||
public EntityConfig getEntityConfig() {
|
||||
return activeConfig.checksConfig().entityConfig();
|
||||
}
|
||||
|
||||
public TileEntityConfig getTileEntityConfig() {
|
||||
return activeConfig.checksConfig().tileEntityConfig();
|
||||
}
|
||||
|
||||
public DebugConfig getDebugConfig() {
|
||||
RootConfig current = activeConfig;
|
||||
return current == null ? null : current.debugConfig();
|
||||
}
|
||||
|
||||
public EngineConfig getEngineConfig() {
|
||||
return activeConfig.engineConfig();
|
||||
}
|
||||
|
||||
public BlockProcessorConfig getBlockProcessorConfig() {
|
||||
return activeConfig.blockProcessorConfig();
|
||||
}
|
||||
|
||||
public <T extends Config> T getExtensionConfig(Class<T> type) {
|
||||
return activeConfig.extensionConfig(type);
|
||||
}
|
||||
|
||||
public ConfigurationNode getConfigFile() {
|
||||
return config;
|
||||
}
|
||||
|
||||
public Map<String, Object> getConfigValues() {
|
||||
Map<String, Object> values = new LinkedHashMap<>();
|
||||
collectConfigValues(config, "", values);
|
||||
return 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'.");
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
if (!blockProcessorConfig.trackAllBlocks() && checksConfig.chunkSectionConfig().enabled()) {
|
||||
throw new ConfigLoadException("checks.chunk-section.enabled must be false when block-processor.track-all-blocks is false");
|
||||
}
|
||||
|
||||
return new RootConfig(version, checksConfig, engineConfig, blockProcessorConfig, debugConfig, Map.copyOf(extensionConfigs));
|
||||
}
|
||||
|
||||
private void validateReload(RootConfig next) {
|
||||
if (startupConfig == null) {
|
||||
return;
|
||||
}
|
||||
if (next.engineConfig().mode() != startupConfig.engineConfig().mode()) {
|
||||
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");
|
||||
}
|
||||
if (next.checksConfig().hasRestartOnlyChanges(startupConfig.checksConfig())) {
|
||||
throw new RestartRequiredException("checks cannot be enabled or disabled without a restart");
|
||||
}
|
||||
for (ConfigExtension<? extends Config> extension : extensions) {
|
||||
validateExtensionReload(extension, next);
|
||||
}
|
||||
}
|
||||
|
||||
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 void collectConfigValues(ConfigurationNode node, String path, Map<String, Object> values) {
|
||||
if (node.childrenMap().isEmpty() && node.childrenList().isEmpty()) {
|
||||
if (!path.isEmpty() && !node.virtual()) {
|
||||
values.put(path, node.raw());
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
private ConfigurationNode node(ConfigurationNode root, String path) {
|
||||
String[] parts = path.split("\\.");
|
||||
return ConfigReader.node(root, parts);
|
||||
}
|
||||
|
||||
private enum ListMutation {
|
||||
ADD,
|
||||
REMOVE
|
||||
}
|
||||
|
||||
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 static SetConfigResult restartRequired(String message) {
|
||||
return new SetConfigResult(true, true, message);
|
||||
}
|
||||
|
||||
public static SetConfigResult invalid(String message) {
|
||||
return new SetConfigResult(false, false, message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
public boolean showDebugParticles() {
|
||||
return debugParticles;
|
||||
}
|
||||
|
||||
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,12 @@
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import games.cubi.raycastedantiesp.core.config.engine.EngineConfig;
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
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 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")));
|
||||
}
|
||||
|
||||
public EngineMode getMode() {
|
||||
return mode;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package games.cubi.raycastedantiesp.core.config.engine;
|
||||
|
||||
import games.cubi.raycastedantiesp.core.config.ConfigEnum;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public enum EngineMode implements ConfigEnum {
|
||||
SIMPLE("simple"),
|
||||
NETTY("netty");
|
||||
|
||||
private final String configName;
|
||||
|
||||
EngineMode(String configName) {
|
||||
this.configName = configName;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return configName;
|
||||
}
|
||||
|
||||
public static @Nullable EngineMode fromString(String name) {
|
||||
for (EngineMode mode : values()) {
|
||||
if (mode.configName.equalsIgnoreCase(name)) {
|
||||
return mode;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getValues() {
|
||||
return new String[] {"simple", "netty"};
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
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;
|
||||
|
||||
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")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package games.cubi.raycastedantiesp.core.config.raycast;
|
||||
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
|
||||
public class EntityConfig extends RaycastConfig {
|
||||
private EntityConfig(RaycastConfig config) {
|
||||
super(config.enabled(), config.hideSoundsWhenHidden(), config.getMaxOccludingCount(), config.getAlwaysShowRadius(),
|
||||
config.getRaycastRadius(), config.hideOnSpawnDistance(), config.getVisibleRecheckIntervalTicks());
|
||||
}
|
||||
|
||||
public static EntityConfig load(ConfigurationNode node, String path) {
|
||||
return new EntityConfig(RaycastConfig.load(node, path, true));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package games.cubi.raycastedantiesp.core.config.raycast;
|
||||
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
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 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;
|
||||
}
|
||||
|
||||
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
|
||||
);
|
||||
}
|
||||
|
||||
public boolean enabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
public boolean hideSoundsWhenHidden() {
|
||||
return hideSoundsWhenHidden;
|
||||
}
|
||||
|
||||
public byte getMaxOccludingCount() {
|
||||
return maxOccludingCount;
|
||||
}
|
||||
|
||||
public short getAlwaysShowRadius() {
|
||||
return alwaysShowRadius;
|
||||
}
|
||||
|
||||
public short getRaycastRadius() {
|
||||
return raycastRadius;
|
||||
}
|
||||
|
||||
public short hideOnSpawnDistance() {
|
||||
return hideOnSpawnDistance;
|
||||
}
|
||||
|
||||
public short getVisibleRecheckIntervalTicks() {
|
||||
return visibleRecheckIntervalTicks;
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
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;
|
||||
|
||||
public record SoundEffectsConfig(
|
||||
boolean enabled,
|
||||
int maxOccludingCount,
|
||||
int alwaysPlayRadius,
|
||||
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")
|
||||
);
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package games.cubi.raycastedantiesp.core.config.raycast;
|
||||
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
|
||||
public class TileEntityConfig extends RaycastConfig {
|
||||
private TileEntityConfig(RaycastConfig config) {
|
||||
super(config.enabled(), false, config.getMaxOccludingCount(), config.getAlwaysShowRadius(),
|
||||
config.getRaycastRadius(), config.hideOnSpawnDistance(), config.getVisibleRecheckIntervalTicks());
|
||||
}
|
||||
|
||||
public static TileEntityConfig load(ConfigurationNode node, String path) {
|
||||
return new TileEntityConfig(RaycastConfig.load(node, path, false));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package games.cubi.raycastedantiesp.core.engine;
|
||||
|
||||
public interface AsyncRunner {
|
||||
void runNow(Runnable task);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package games.cubi.raycastedantiesp.core.engine;
|
||||
|
||||
public interface Engine {
|
||||
void tick();
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
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,73 @@
|
||||
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
@@ -0,0 +1,420 @@
|
||||
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 +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
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
@@ -0,0 +1,30 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package games.cubi.raycastedantiesp.core.players;
|
||||
|
||||
import games.cubi.logs.Logger;
|
||||
import games.cubi.raycastedantiesp.core.utils.*;
|
||||
import games.cubi.raycastedantiesp.core.utils.Packet.Packets;
|
||||
import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap;
|
||||
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
|
||||
import it.unimi.dsi.fastutil.objects.ObjectIterator;
|
||||
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.lang.invoke.VarHandle;
|
||||
|
||||
|
||||
/**
|
||||
* Per-player mutable state intended for Netty-side packet tracking and deferred reconciliation.
|
||||
*/
|
||||
public class NettyData implements Clearable {
|
||||
//
|
||||
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||
// 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.
|
||||
|
||||
public void addUnresolvedLeash(int holderEntityID, int leashedEntityID) {
|
||||
unresolvedLeashedEntityIDsByHolderID.compute(holderEntityID, (ignored, existing) -> {
|
||||
if (IntArrayList.contains(existing, leashedEntityID)) {
|
||||
return existing;
|
||||
}
|
||||
return IntArrayList.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];
|
||||
}
|
||||
|
||||
public int[] consumeUnresolvedLeashes(int holderEntityID) {
|
||||
return unresolvedLeashedEntityIDsByHolderID.remove(holderEntityID);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
//
|
||||
// END Leash 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);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 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.
|
||||
* @param task The task to run.
|
||||
*/
|
||||
public void addPostEntitySpawnTask(int entityID, EntitySpawnTask task) {
|
||||
if (task.getNext() != null) {
|
||||
Logger.errorAndReturn(new IllegalArgumentException("Pending netty task was chained before queueing. Task=" + task), 4, NettyData.class);
|
||||
}
|
||||
EntitySpawnTask existing = pendingPostEntitySpawnTasksByEntityID.get(entityID);
|
||||
if (existing == null) {
|
||||
pendingPostEntitySpawnTasksByEntityID.put(entityID, task);
|
||||
return;
|
||||
}
|
||||
existing.appendLinkedTask(task);
|
||||
}
|
||||
|
||||
public void runPendingPostSpawnTaskForEntity(int entityID) {
|
||||
EntitySpawnTask pendingTasks = consumePendingPostSpawnTasksForEntity(entityID);
|
||||
if (pendingTasks != null) {
|
||||
pendingTasks.runLinkedTasks();
|
||||
}
|
||||
}
|
||||
|
||||
public void evictPendingPostSpawnTasksIfRequired(int currentTick) {
|
||||
if (EVICT_PENDING_POST_SPAWN_TASKS_ON_NEXT_PACKET_HANDLE.compareAndSet(this, true, false)) evictOldPendingPostSpawnTasks(currentTick);
|
||||
}
|
||||
|
||||
public void markPendingPostSpawnTasksForEviction() {
|
||||
evictPendingPostSpawnTasksOnNextPacket = true;
|
||||
}
|
||||
|
||||
public EntitySpawnTask consumePendingPostSpawnTasksForEntity(int entityID) {
|
||||
return pendingPostEntitySpawnTasksByEntityID.remove(entityID);
|
||||
}
|
||||
|
||||
public void clearPendingPostSpawnTasksForEntity(int entityID) {
|
||||
pendingPostEntitySpawnTasksByEntityID.remove(entityID);
|
||||
}
|
||||
|
||||
public void evictOldPendingPostSpawnTasks(int currentTick) {
|
||||
ObjectIterator<Int2ObjectMap.Entry<EntitySpawnTask>> iterator = pendingPostEntitySpawnTasksByEntityID.int2ObjectEntrySet().fastIterator();
|
||||
while (iterator.hasNext()) {
|
||||
Int2ObjectMap.Entry<EntitySpawnTask> entry = iterator.next();
|
||||
EntitySpawnTask survivingHead = entry.getValue().trimExpiredTasks(currentTick);
|
||||
if (survivingHead == null) {
|
||||
iterator.remove();
|
||||
} else {
|
||||
entry.setValue(survivingHead);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// END Netty entity spawn task queue.
|
||||
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||
//
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
unresolvedLeashedEntityIDsByHolderID.clear();
|
||||
pendingPostEntitySpawnTasksByEntityID.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package games.cubi.raycastedantiesp.core.players;
|
||||
|
||||
import games.cubi.locatables.Locatable;
|
||||
import games.cubi.locatables.implementations.ThreadSafeLocatable;
|
||||
import games.cubi.logs.Logger;
|
||||
import games.cubi.raycastedantiesp.core.locatables.NettyEntityLocatable;
|
||||
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 java.util.UUID;
|
||||
|
||||
public class PlayerData {
|
||||
private final UUID playerUUID;
|
||||
private final int joinTick;
|
||||
private volatile boolean hasBypassPermission;
|
||||
private final ThreadSafeLocatable ownLocation;
|
||||
|
||||
private final BlockView blockView;
|
||||
private final EntityView<?> entityView;
|
||||
private final EntityView<?> playerView;
|
||||
private final NettyData nettyData;
|
||||
|
||||
public PlayerData(UUID player, boolean hasBypassPermission, int joinTick) {
|
||||
this(player, joinTick);
|
||||
this.hasBypassPermission = hasBypassPermission;
|
||||
}
|
||||
|
||||
public PlayerData(UUID player, int joinTick) {
|
||||
this.joinTick = joinTick;
|
||||
this.playerUUID = player;
|
||||
|
||||
blockView = ViewRegistry.createBlockView();
|
||||
entityView = ViewRegistry.createEntityView();
|
||||
playerView = ViewRegistry.createPlayerEntityView();
|
||||
nettyData = new NettyData();
|
||||
ownLocation = new ThreadSafeLocatable(null, 0, 0, 0);
|
||||
}
|
||||
|
||||
public EntityView<?> entityView() {
|
||||
return entityView;
|
||||
}
|
||||
|
||||
public EntityView<?> playerView() {
|
||||
return playerView;
|
||||
}
|
||||
|
||||
public NettyData nettyData() {
|
||||
return nettyData;
|
||||
}
|
||||
|
||||
public BlockView blockView() {
|
||||
return blockView;
|
||||
}
|
||||
|
||||
public void updateOwnLocation(UUID world, double x, double y, double z) {
|
||||
ownLocation.set(x, y, z, world);
|
||||
}
|
||||
|
||||
public Locatable ownLocation() {
|
||||
ThreadSafeLocatable existing = ownLocation;
|
||||
return existing == null ? null : existing.clonePlainAndCentreIfBlockLocation();
|
||||
}
|
||||
|
||||
public UUID getPlayerUUID() {
|
||||
return playerUUID;
|
||||
}
|
||||
|
||||
public boolean hasBypassPermission() {
|
||||
return hasBypassPermission;
|
||||
}
|
||||
|
||||
public int getJoinTick() {
|
||||
return joinTick;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Either the entity or player view for this player, depending on the entity ID
|
||||
*/
|
||||
public EntityView<?> viewFromEntityID(int entityID) {
|
||||
if (entityView.exists(entityID)) {
|
||||
return entityView;
|
||||
}
|
||||
if (playerView.exists(entityID)) {
|
||||
return playerView;
|
||||
}
|
||||
Logger.warning("Could not find view for entityID=" + entityID + " uuid=" + playerUUID, 6, PacketEntityViewController.class);
|
||||
return null;
|
||||
}
|
||||
|
||||
public NettyEntityLocatable<?,?> entityFromID(int entityID) {
|
||||
EntityView<?> entityView = viewFromEntityID(entityID);
|
||||
if (entityView == null) {
|
||||
return null;
|
||||
}
|
||||
return (NettyEntityLocatable<?, ?>) entityView.getEntity(entityID);
|
||||
}
|
||||
|
||||
public void setBypassPermission(boolean hasBypassPermission) {
|
||||
this.hasBypassPermission = hasBypassPermission;
|
||||
} //todo: need to link up
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "PlayerData{" +
|
||||
"playerUUID=" + playerUUID +
|
||||
", joinTick=" + joinTick +
|
||||
", hasBypassPermission=" + hasBypassPermission +
|
||||
", ownLocation=" + ownLocation +
|
||||
", blockView=" + blockView +
|
||||
", entityView=" + entityView +
|
||||
", playerView=" + playerView +
|
||||
", nettyData=" + nettyData +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package games.cubi.raycastedantiesp.core.players;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public class PlayerRegistry {
|
||||
|
||||
private static PlayerRegistry instance;
|
||||
|
||||
private PlayerRegistry() {}
|
||||
|
||||
public static PlayerRegistry getInstance() {
|
||||
if (instance == null) {
|
||||
instance = new PlayerRegistry();
|
||||
}
|
||||
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));
|
||||
}
|
||||
|
||||
/** 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);
|
||||
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) {
|
||||
PlayerData unregisteredPlayer = playerDataMap.remove(playerUUID);
|
||||
if (unregisteredPlayer == null) {
|
||||
return;
|
||||
}
|
||||
unregisteredPlayer.blockView().clear();
|
||||
unregisteredPlayer.entityView().clear();
|
||||
unregisteredPlayer.playerView().clear();
|
||||
unregisteredPlayer.nettyData().clear();
|
||||
}
|
||||
|
||||
public PlayerData getPlayerData(UUID playerUUID) {
|
||||
return playerDataMap.get(playerUUID);
|
||||
}
|
||||
|
||||
public boolean isPlayerRegistered(UUID playerUUID) {
|
||||
return playerDataMap.containsKey(playerUUID);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Live, mutable collection of all PlayerData instances.
|
||||
* **/
|
||||
public Collection<PlayerData> getAllPlayerData() {
|
||||
return playerDataMap.values();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package games.cubi.raycastedantiesp.core.raycast;
|
||||
|
||||
import games.cubi.locatables.Locatable;
|
||||
|
||||
public interface ParticleSpawner {
|
||||
|
||||
enum Colour {
|
||||
RED, GREEN, BLUE,
|
||||
}
|
||||
|
||||
void spawnParticleAt(Locatable locatable, Colour color);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
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.raycastedantiesp.core.view.BlockView;
|
||||
|
||||
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;
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
if (debug) particleSpawner.spawnParticleAt(current, ParticleSpawner.Colour.GREEN);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package games.cubi.raycastedantiesp.core.utils;
|
||||
|
||||
import games.cubi.logs.Logger;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public abstract class BaseEntitySpawnTask implements EntitySpawnTask {
|
||||
protected final int submittedTick;
|
||||
private @Nullable EntitySpawnTask next;
|
||||
|
||||
protected BaseEntitySpawnTask(int submittedTick) {
|
||||
this.submittedTick = submittedTick;
|
||||
}
|
||||
|
||||
@Override
|
||||
public final int getSubmittedTick() {
|
||||
return submittedTick;
|
||||
}
|
||||
|
||||
@Override
|
||||
public final @Nullable EntitySpawnTask getNext() {
|
||||
return next;
|
||||
}
|
||||
|
||||
@Override
|
||||
public final void setNext(@Nullable EntitySpawnTask next) {
|
||||
if (next == this) {
|
||||
Logger.errorAndReturn(new IllegalArgumentException("A FutureNettyTask cannot link to itself: " + this), 1, BaseEntitySpawnTask.class);
|
||||
}
|
||||
if (this.next != null && next != null) {
|
||||
Logger.errorAndReturn(new IllegalStateException("FutureNettyTask already has a next task. Existing next=" + this.next + ", attempted next=" + next + ", task=" + this), 1, BaseEntitySpawnTask.class);
|
||||
}
|
||||
this.next = next;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package games.cubi.raycastedantiesp.core.utils;
|
||||
|
||||
import games.cubi.logs.Logger;
|
||||
import org.jspecify.annotations.NullMarked;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
// Not specific to RaycastedAntiESP, could be moved to a more general utils package if needed
|
||||
@NullMarked
|
||||
public record BuildProperties(String gitHashLong, String gitHashShort, String buildTime, Version version) {
|
||||
public static final BuildProperties CORE = fromResource("build-properties/core.yml");
|
||||
public static final BuildProperties PLATFORM = fromResource("build-properties/platform.yml");
|
||||
public static final BuildProperties LOGGER = fromResource("build-properties/logging.yml");
|
||||
public static final BuildProperties LOCATABLES = fromResource("build-properties/locatable-lib.yml");
|
||||
|
||||
public static BuildProperties fromResource(String resourcePath) {
|
||||
try (InputStream inputStream = BuildProperties.class.getClassLoader().getResourceAsStream(resourcePath)) {
|
||||
if (inputStream == null) {
|
||||
Logger.error(new IllegalArgumentException("BuildProperties resource not found: " + resourcePath), 2, BuildProperties.class);
|
||||
return error();
|
||||
}
|
||||
|
||||
String shortGit = null;
|
||||
String longGit = null;
|
||||
String buildTime = null;
|
||||
Version version = null;
|
||||
|
||||
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
String trimmedLine = line.trim();
|
||||
if (trimmedLine.isEmpty() || trimmedLine.startsWith("#")) continue;
|
||||
|
||||
String[] parts = trimmedLine.split(":", 2);
|
||||
if (parts.length != 2) continue;
|
||||
|
||||
String key = parts[0].trim();
|
||||
String value = parts[1].trim();
|
||||
|
||||
if ((value.startsWith("\"") && value.endsWith("\"")) || (value.startsWith("'") && value.endsWith("'"))) {
|
||||
value = value.substring(1, value.length() - 1);
|
||||
}
|
||||
|
||||
switch (key) {
|
||||
case "short-git" -> shortGit = value;
|
||||
case "long-git" -> longGit = value;
|
||||
case "build-time" -> buildTime = value;
|
||||
case "version" -> version = Version.parse(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (shortGit == null || longGit == null || buildTime == null || version == null) {
|
||||
Logger.error(new IllegalArgumentException("Missing required build properties in resource: " + resourcePath + ". Found shortGit=" + shortGit + ", longGit=" + longGit + ", buildTime=" + buildTime + ", version=" + version), 2, BuildProperties.class);
|
||||
return error();
|
||||
}
|
||||
return new BuildProperties(longGit, shortGit, buildTime, version);
|
||||
} catch (Exception e) {
|
||||
Logger.error(new IllegalArgumentException("Failed to parse BuildProperties resource: " + resourcePath, e), 2, BuildProperties.class);
|
||||
return error();
|
||||
}
|
||||
}
|
||||
|
||||
private static BuildProperties error() {
|
||||
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) {
|
||||
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);
|
||||
}
|
||||
try {
|
||||
short major = Short.parseShort(parts[0]);
|
||||
short minor = Short.parseShort(parts[1]);
|
||||
short patch = Short.parseShort(parts[2]);
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
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();
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
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();
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package games.cubi.raycastedantiesp.core.utils;
|
||||
|
||||
import games.cubi.logs.Logger;
|
||||
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 getSubmittedTick();
|
||||
|
||||
default boolean thisShouldBeEvicted(int currentTick) {
|
||||
return ( currentTick - getSubmittedTick() ) >= TICKS_BEFORE_EVICTION;
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends the provided task to the end of this linked task chain.
|
||||
*/
|
||||
default void appendLinkedTask(EntitySpawnTask task) {
|
||||
EntitySpawnTask current = this;
|
||||
while (current.getNext() != null) {
|
||||
current = current.getNext();
|
||||
}
|
||||
current.setNext(task);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the first task in this chain that should not be evicted yet, or null if all tasks should be evicted.
|
||||
*/
|
||||
@Nullable
|
||||
default EntitySpawnTask trimExpiredTasks(int currentTick) {
|
||||
EntitySpawnTask current = this;
|
||||
while (current != null && current.thisShouldBeEvicted(currentTick)) {
|
||||
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
|
||||
current = next;
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
default void runLinkedTasks() {
|
||||
EntitySpawnTask current = this;
|
||||
while (current != null) {
|
||||
EntitySpawnTask next = current.getNext();
|
||||
current.setNext(null);
|
||||
try {
|
||||
current.run();
|
||||
} catch (Exception e) {
|
||||
Logger.error("Error while running future netty task " + current, e, 3, EntitySpawnTask.class);
|
||||
}
|
||||
current = next;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Allows linking of tasks into lists for each entity, so that when an entity is processed, all pending tasks for that entity can be processed at once.
|
||||
* @return the next task in the list, or null if this is the end of the list. Order of tasks is guaranteed to be in ascending order of submitted tick.
|
||||
*/
|
||||
@Nullable EntitySpawnTask getNext();
|
||||
|
||||
/**
|
||||
* Sets the next task in the linked task chain.
|
||||
* Passing null is allowed and is used when detaching already-linked tasks before eviction or execution.
|
||||
* <p>
|
||||
* This should generally not be called directly, use {@link #appendLinkedTask} to link tasks together and let the system handle detaching when necessary.
|
||||
*/
|
||||
void setNext(@Nullable EntitySpawnTask next);
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
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,40 @@
|
||||
package games.cubi.raycastedantiesp.core.utils;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
|
||||
@Documented
|
||||
@Retention(RetentionPolicy.SOURCE)
|
||||
public @interface Packet {
|
||||
//todo note: spawn living entity and painting are really old and no longer used, delete them from code maybe
|
||||
enum Packets {
|
||||
@Until("1.9")
|
||||
SPAWN_LIVING_ENTITY("N/A", "WrapperPlayServerSpawnEntityLiving"),
|
||||
SPAWN_ENTITY("https://minecraft.wiki/w/Java_Edition_protocol/Packets#Spawn_Entity", "WrapperPlayServerSpawnEntity"), //Note does not fire for self player
|
||||
ENTITY_ANIMATION("https://minecraft.wiki/w/Java_Edition_protocol/Packets#Entity_Animation", "WrapperPlayServerEntityAnimation"),
|
||||
ENTITY_EVENT("https://minecraft.wiki/w/Java_Edition_protocol/Packets#Entity_Event", "WrapperPlayServerEntityStatus"),
|
||||
HURT_ANIMATION("https://minecraft.wiki/w/Java_Edition_protocol/Packets#Hurt_Animation", "WrapperPlayServerHurtAnimation"),
|
||||
UPDATE_ATTRIBUTES("https://minecraft.wiki/w/Java_Edition_protocol/Packets#Update_Attributes", "WrapperPlayServerUpdateAttributes"),
|
||||
LEASH_ENTITY("https://minecraft.wiki/w/Java_Edition_protocol/Packets#Link_Entities", "WrapperPlayServerAttachEntity"), //Note in 1.8 and below this was also used for setting passengers
|
||||
ENTITY_EQUIPMENT("https://minecraft.wiki/w/Java_Edition_protocol/Packets#Set_Equipment", "WrapperPlayServerEntityEquipment"),
|
||||
;
|
||||
|
||||
Packets(String wikiURL, String PEName) {
|
||||
}
|
||||
}
|
||||
|
||||
Packets value();
|
||||
|
||||
@Documented
|
||||
@Retention(RetentionPolicy.SOURCE)
|
||||
@interface Since {
|
||||
String value();
|
||||
}
|
||||
|
||||
@Documented
|
||||
@Retention(RetentionPolicy.SOURCE)
|
||||
@interface Until {
|
||||
String value();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package games.cubi.raycastedantiesp.core.utils;
|
||||
|
||||
public class ThreadGuard {
|
||||
public static final boolean ASSERTIONS_ENABLED = areAssertionsEnabled();
|
||||
|
||||
@SuppressWarnings("PointlessBooleanExpression")
|
||||
/**
|
||||
* @return true if assertions are enabled, false otherwise
|
||||
*/
|
||||
private static boolean areAssertionsEnabled() {
|
||||
try {
|
||||
assert true == false; // can be simplified to assert false but this reads more clearly to me as a statement which will fail.
|
||||
return false;
|
||||
} catch (AssertionError e) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
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 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 java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
|
||||
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;
|
||||
|
||||
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<>();
|
||||
|
||||
@Deprecated
|
||||
protected abstract T createTrackedTileEntity(BlockLocatable location, int blockID, boolean visible);
|
||||
|
||||
protected abstract T createTrackedTileEntity(UUID world, int x, int y, int z, int blockID);
|
||||
|
||||
|
||||
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(BlockLocatable location) {
|
||||
return location != null
|
||||
&& location.world() != null
|
||||
&& isBlockOccluding(location.world(), location.blockX(), location.blockY(), location.blockZ());
|
||||
}
|
||||
|
||||
public int loadedChunkCount() {
|
||||
return chunks.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateOrInsertTileEntity(BlockLocatable location, int blockID, boolean visibleIfNew) {
|
||||
T tileEntity = knownTileEntities.computeIfAbsent(location, ignored -> createTrackedTileEntity(location, blockID, visibleIfNew));
|
||||
if (tileEntity == null) {
|
||||
Logger.error("Tile entity null when attempting to update or insert", 3, AbstractBlockView.class);
|
||||
return;
|
||||
}
|
||||
tileEntity.setBlockID(blockID);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeTileEntity(BlockLocatable location) {
|
||||
T tileEntity = knownTileEntities.remove(location);
|
||||
if (tileEntity != null) {
|
||||
tileEntity.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public T getTrackedTileEntity(BlockLocatable location) {
|
||||
return knownTileEntities.get(location);
|
||||
}
|
||||
|
||||
@Override
|
||||
public T getTrackedTileEntity(ImmutableBlockLocatable location) {
|
||||
return knownTileEntities.get(location);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isVisible(BlockLocatable location, int currentTick) {
|
||||
T state = knownTileEntities.get(location);
|
||||
return state == null || state.visible();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setVisibility(BlockLocatable location, boolean visible, int currentTick) {
|
||||
T existing = knownTileEntities.get(location);
|
||||
if (existing == null) {
|
||||
return;
|
||||
}
|
||||
if (existing.visible() != visible) {
|
||||
transitions.add(new BlockViewTransition(
|
||||
visible ? BlockViewTransition.Type.SHOW : BlockViewTransition.Type.HIDE,
|
||||
location
|
||||
));
|
||||
}
|
||||
existing.setVisible(visible);
|
||||
existing.setLastChecked(currentTick);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<BlockLocatable> getKnownTileEntities() {
|
||||
return List.copyOf(knownTileEntities.keySet());
|
||||
}
|
||||
|
||||
@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;
|
||||
}
|
||||
needingRecheck.add(tileEntity);
|
||||
}
|
||||
return needingRecheck;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasPendingTransitions() {
|
||||
return !transitions.isEmpty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<BlockViewTransition> drainTransitions() {
|
||||
List<BlockViewTransition> drained = new ArrayList<>();
|
||||
BlockViewTransition transition;
|
||||
while ((transition = transitions.poll()) != null) {
|
||||
drained.add(transition);
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
@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
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeChunkSection(UUID world, int chunkX, int chunkY, int chunkZ) {
|
||||
chunks.remove(new ChunkSectionLocatable.ImmutableChunkSectionLocatable(world, 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
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
chunks.clear();
|
||||
knownTileEntities.clear();
|
||||
transitions.clear();
|
||||
}
|
||||
|
||||
public static int maskAndPack(int x, int y, int z) {
|
||||
return pack(x & LOCAL_MASK, y & LOCAL_MASK, z & LOCAL_MASK);
|
||||
}
|
||||
|
||||
public static int pack(int x, int y, int z) {
|
||||
return (x & LOCAL_MASK) | ((y & LOCAL_MASK) << 4) | ((z & LOCAL_MASK) << 8);
|
||||
}
|
||||
|
||||
public static int unpackX(int packed) {
|
||||
return packed & LOCAL_MASK;
|
||||
}
|
||||
|
||||
public static int unpackY(int packed) {
|
||||
return (packed >> 4) & LOCAL_MASK;
|
||||
}
|
||||
|
||||
public static int unpackZ(int packed) {
|
||||
return (packed >> 8) & LOCAL_MASK;
|
||||
}
|
||||
|
||||
private BitSet getChunk(UUID world, int chunkX, int chunkY, int chunkZ) {
|
||||
return chunks.get(new ChunkSectionLocatable.ImmutableChunkSectionLocatable(world, chunkX, chunkY, chunkZ));
|
||||
}
|
||||
|
||||
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)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
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 java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface BlockView extends Clearable {
|
||||
boolean isBlockOccluding(BlockLocatable location);
|
||||
|
||||
/**
|
||||
* Constructs a new tile entity with the provided id and visibility, or updates the block id for existing tile entities.
|
||||
*/
|
||||
void updateOrInsertTileEntity(BlockLocatable location, int blockID, boolean visibleIfNew);
|
||||
|
||||
void removeTileEntity(BlockLocatable location);
|
||||
|
||||
TileEntityLocatable<?> getTrackedTileEntity(BlockLocatable location);
|
||||
|
||||
TileEntityLocatable<?> getTrackedTileEntity(ImmutableBlockLocatable location);
|
||||
|
||||
boolean isVisible(BlockLocatable location, int currentTick);
|
||||
|
||||
void setVisibility(BlockLocatable location, boolean visible, int currentTick);
|
||||
|
||||
Collection<BlockLocatable> getKnownTileEntities();
|
||||
|
||||
Collection<BlockLocatable> getNeedingRecheck(int recheckTicks, int currentTick);
|
||||
|
||||
boolean hasPendingTransitions();
|
||||
|
||||
List<BlockViewTransition> drainTransitions();
|
||||
|
||||
void upsertBlock(UUID world, int x, int y, int z, boolean occluding);
|
||||
|
||||
void removeChunk(UUID world, int chunkX, int chunkZ);
|
||||
|
||||
void removeChunkSection(UUID world, int chunkX, int chunkY, int chunkZ);
|
||||
|
||||
void replaceChunkSection(UUID world, int chunkX, int chunkY, int chunkZ, BitSet occludingBlocks);
|
||||
|
||||
default <T> T cast() {
|
||||
return (T) this;
|
||||
}
|
||||
|
||||
interface Factory {
|
||||
BlockView createBlockView();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
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,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
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 java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface EntityView<T extends EntityLocatable<?, ?>> extends Clearable {
|
||||
void insertEntity(T entity);
|
||||
|
||||
void removeEntity(int entityID, int currentTick);
|
||||
|
||||
void removeEntity(UUID entityUUID, int currentTick);
|
||||
|
||||
T getEntity(UUID entityUUID);
|
||||
|
||||
T getEntity(int entityID);
|
||||
|
||||
Locatable getLocation(UUID entityUUID);
|
||||
|
||||
int getEntityID(UUID entityUUID);
|
||||
|
||||
boolean exists(UUID entityUUID);
|
||||
|
||||
boolean exists(int entityID);
|
||||
|
||||
@Deprecated
|
||||
boolean isVisible(UUID entityUUID, int currentTick);
|
||||
|
||||
boolean isVisible(UUID entityUUID);
|
||||
|
||||
boolean isVisible(int entityID);
|
||||
|
||||
void setVisibility(UUID entityUUID, boolean visible, int currentTick);
|
||||
|
||||
Collection<UUID> getKnownEntities();
|
||||
|
||||
Collection<UUID> getNeedingRecheck(int recheckTicks, int currentTick);
|
||||
|
||||
boolean hasPendingTransitions();
|
||||
|
||||
List<EntityViewTransition> drainTransitions();
|
||||
|
||||
boolean isPlayerView();
|
||||
|
||||
default <T> T cast() {
|
||||
return (T) this;
|
||||
}
|
||||
|
||||
String getStringDataForDebugging();
|
||||
|
||||
interface Factory {
|
||||
EntityView<?> createEntityView();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package games.cubi.raycastedantiesp.core.view;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
// Used to cache visibility changes until the player's netty thread next processes
|
||||
public record EntityViewTransition(Type type, UUID targetUUID, int entityID) {
|
||||
public enum Type {
|
||||
SHOW,
|
||||
HIDE,
|
||||
FORGET,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package games.cubi.raycastedantiesp.core.view;
|
||||
|
||||
import games.cubi.logs.Logger;
|
||||
|
||||
public final class ViewRegistry {
|
||||
private static EntityView.Factory entityViewFactory;
|
||||
private static EntityView.Factory playerEntityViewFactory;
|
||||
private static BlockView.Factory blockViewFactory;
|
||||
|
||||
private ViewRegistry() {}
|
||||
|
||||
public static void initialise(BlockView.Factory blockViewFactory1, EntityView.Factory entityViewFactory1, EntityView.Factory playerEntityViewFactory1) {
|
||||
blockViewFactory = blockViewFactory1;
|
||||
entityViewFactory = entityViewFactory1;
|
||||
playerEntityViewFactory = playerEntityViewFactory1;
|
||||
}
|
||||
|
||||
public static BlockView createBlockView() {
|
||||
if (blockViewFactory == null) {
|
||||
Logger.error(new IllegalStateException("Block view factory is null. Did you forget to initialise ViewRegistry?"), 1, ViewRegistry.class);
|
||||
}
|
||||
return blockViewFactory.createBlockView();
|
||||
}
|
||||
|
||||
public static EntityView<?> createEntityView() {
|
||||
if (entityViewFactory == null) {
|
||||
Logger.error(new IllegalStateException("Entity view factory is null. Did you forget to initialise ViewRegistry?"), 1, ViewRegistry.class);
|
||||
}
|
||||
return entityViewFactory.createEntityView();
|
||||
}
|
||||
|
||||
public static EntityView<?> createPlayerEntityView() {
|
||||
if (playerEntityViewFactory == null) {
|
||||
Logger.error(new IllegalStateException("Player entity view factory is null. Did you forget to initialise ViewRegistry?"), 1, ViewRegistry.class);
|
||||
}
|
||||
return playerEntityViewFactory.createEntityView();
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package games.cubi.raycastedantiesp.core.view.controller;
|
||||
|
||||
import games.cubi.logs.Logger;
|
||||
import games.cubi.raycastedantiesp.core.locatables.NettyEntityLocatable;
|
||||
import games.cubi.raycastedantiesp.core.players.PlayerData;
|
||||
import games.cubi.raycastedantiesp.core.utils.BaseEntitySpawnTask;
|
||||
|
||||
final class LeashReconciliationTask extends BaseEntitySpawnTask {
|
||||
private final PlayerData playerData;
|
||||
private final int leashedEntityID;
|
||||
private final int leashingEntityID;
|
||||
|
||||
LeashReconciliationTask(PlayerData playerData, int leashedEntityID, int leashingEntityID, int submittedTick) {
|
||||
super(submittedTick);
|
||||
this.playerData = playerData;
|
||||
this.leashedEntityID = leashedEntityID;
|
||||
this.leashingEntityID = leashingEntityID;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
NettyEntityLocatable<?,?> leashed = playerData.entityFromID(leashedEntityID);
|
||||
if (leashed == null) {
|
||||
Logger.error("Reconciliation fail: Attempted to reconcile leash for unknown leashed entity, leashedEntityId=" + leashedEntityID, 3, this.getClass());
|
||||
return;
|
||||
}
|
||||
PacketEntityViewController.get().handleLeashEntityNow(leashed, leashingEntityID, playerData);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "LeashReconciliationTask{" +
|
||||
"submittedTick=" + submittedTick +
|
||||
", leashedEntityId=" + leashedEntityID +
|
||||
", leashingEntityId=" + leashingEntityID +
|
||||
", playerUUID=" + playerData.getPlayerUUID() +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
+428
@@ -0,0 +1,428 @@
|
||||
package games.cubi.raycastedantiesp.core.view.controller;
|
||||
|
||||
import games.cubi.logs.Logger;
|
||||
import games.cubi.raycastedantiesp.core.config.raycast.EntityConfig;
|
||||
import games.cubi.raycastedantiesp.core.config.raycast.PlayerConfig;
|
||||
import games.cubi.raycastedantiesp.core.config.raycast.RaycastConfig;
|
||||
import games.cubi.raycastedantiesp.core.locatables.NettyEntityLocatable;
|
||||
import games.cubi.raycastedantiesp.core.players.PlayerData;
|
||||
import games.cubi.raycastedantiesp.core.players.PlayerRegistry;
|
||||
import games.cubi.raycastedantiesp.core.utils.IntArrayList;
|
||||
import games.cubi.raycastedantiesp.core.utils.Packet;
|
||||
import games.cubi.raycastedantiesp.core.view.EntityView;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.UUID;
|
||||
|
||||
import static games.cubi.raycastedantiesp.core.locatables.NettyEntityLocatable.NO_LEASHER;
|
||||
import static games.cubi.raycastedantiesp.core.locatables.NettyEntityLocatable.NO_VEHICLE;
|
||||
|
||||
/**
|
||||
* @param <P> The platform's packet wrapper (PacketWrapper<?>)
|
||||
*/
|
||||
public abstract class PacketEntityViewController<P> {
|
||||
private static PacketEntityViewController<?> SELF; //TODO Switch to LazyConstant once out of preview (see https://openjdk.org/jeps/526)
|
||||
|
||||
{
|
||||
synchronized (PacketEntityViewController.class) {
|
||||
if (SELF != null) {
|
||||
throw new IllegalStateException("Multiple instances of PacketEventsEntityViewController created.");
|
||||
}
|
||||
SELF = this;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
protected static PacketEntityViewController<?> get() {
|
||||
return SELF;
|
||||
}
|
||||
|
||||
protected EntityConfig entityConfig = null;
|
||||
protected PlayerConfig playerConfig = null;
|
||||
protected double hideOnSpawnEntityDistanceSquared = 0;
|
||||
protected double hideOnSpawnPlayerDistanceSquared = 0;
|
||||
|
||||
protected void handlePlayPhaseLoginPacket(int entityID, UUID playerUUID, int currentTick) {
|
||||
PlayerData playerData = PlayerRegistry.getInstance().getPlayerData(playerUUID);
|
||||
playerData.playerView().insertEntity(createSelfEntity(playerData, entityID, playerUUID).cast());
|
||||
}
|
||||
|
||||
protected PlayerData handleLoginPhaseLoginPacket(UUID playerUUID, int currentTick) {
|
||||
return PlayerRegistry.getInstance().registerAndGetPlayer(playerUUID, currentTick);
|
||||
}
|
||||
|
||||
protected abstract NettyEntityLocatable<?,?> createSelfEntity(PlayerData ownData, int entityID, UUID playerUUID);
|
||||
|
||||
/**
|
||||
* @return Whether or not to cancel the packet event. <code>true</code> to cancel, <code>false</code> to do nothing.
|
||||
*/
|
||||
@Packet(Packet.Packets.SPAWN_ENTITY)
|
||||
protected boolean handleEntitySpawn(P packet, int entityID, boolean isPlayer, PlayerData playerData, UUID world, int currentTick) {
|
||||
boolean returnValue = handleEntitySpawn0(packet, isPlayer, playerData, world, currentTick);
|
||||
playerData.nettyData().runPendingPostSpawnTaskForEntity(entityID);
|
||||
return returnValue;
|
||||
}
|
||||
|
||||
protected boolean handleEntitySpawn0(P packet, boolean isPlayer, PlayerData playerData, UUID world, int currentTick) {
|
||||
if (world == null) {
|
||||
Logger.error(new RuntimeException("World null when handling spawn entity packet, uuid=" + playerData.getPlayerUUID() + " tick=" + currentTick), 2, PacketEntityViewController.class);
|
||||
return false;
|
||||
}
|
||||
|
||||
NettyEntityLocatable<?,?> entity = processEntitySpawn(playerData, packet, world, currentTick);
|
||||
|
||||
if ((!isPlayer && entityConfig.enabled()) || isPlayer && playerConfig.enabled()) {
|
||||
double distanceSquared = playerData.ownLocation().distanceSquared(entity);
|
||||
if (distanceSquared > (isPlayer ? hideOnSpawnPlayerDistanceSquared : hideOnSpawnEntityDistanceSquared)) {
|
||||
entity.setVisible(false);
|
||||
entity.setClientVisible(false);
|
||||
if (isPlayer) {
|
||||
insertEntityToPlayerView(entity, playerData);
|
||||
return true;
|
||||
}
|
||||
insertEntityToEntityView(entity, playerData);
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
entity.setClientVisible(true);
|
||||
}
|
||||
if (isPlayer) {
|
||||
insertEntityToPlayerView(entity, playerData);
|
||||
return false;
|
||||
}
|
||||
insertEntityToEntityView(entity, playerData);
|
||||
return false;
|
||||
}
|
||||
|
||||
@Packet(Packet.Packets.ENTITY_ANIMATION)
|
||||
protected boolean handleEntityAnimation(int entityID, PlayerData playerData) {
|
||||
return cancelIfEnabledAndHidden(entityID, playerData);
|
||||
}
|
||||
|
||||
@Packet(Packet.Packets.ENTITY_EVENT)
|
||||
protected boolean handleEntityEvent(int entityID, PlayerData playerData) {
|
||||
return cancelIfEnabledAndHidden(entityID, playerData);
|
||||
}
|
||||
|
||||
@Packet(Packet.Packets.HURT_ANIMATION)
|
||||
protected boolean handleHurtAnimation(int entityID, PlayerData playerData) {
|
||||
return cancelIfEnabledAndHidden(entityID, playerData);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Whether or not to cancel the packet event. <code>true</code> to cancel, <code>false</code> to do nothing.
|
||||
*/
|
||||
protected boolean handleRelativeMove(P packet, PlayerData playerData, int currentTick) {
|
||||
int entityID = processRelativeMovePacket(packet, playerData, currentTick);
|
||||
return cancelIfEnabledAndHidden(entityID, playerData);
|
||||
}
|
||||
/**
|
||||
* @return Whether or not to cancel the packet event. <code>true</code> to cancel, <code>false</code> to do nothing.
|
||||
*/
|
||||
protected boolean handleRelativeMoveAndRotation(P packet, PlayerData playerData, int currentTick) {
|
||||
int entityID = processRelativeMoveAndRotationPacket(packet, playerData, currentTick);
|
||||
return cancelIfEnabledAndHidden(entityID, playerData);
|
||||
}
|
||||
/**
|
||||
* @return Whether or not to cancel the packet event. <code>true</code> to cancel, <code>false</code> to do nothing.
|
||||
*/
|
||||
protected boolean handleTeleport(P packet, PlayerData playerData, int currentTick) {
|
||||
int entityID = processTeleportPacket(packet, playerData, currentTick);
|
||||
return cancelIfEnabledAndHidden(entityID, playerData);
|
||||
}
|
||||
/**
|
||||
* @return Whether or not to cancel the packet event. <code>true</code> to cancel, <code>false</code> to do nothing.
|
||||
*/
|
||||
protected boolean handlePositionSync(P packet, PlayerData playerData, int currentTick) {
|
||||
int entityID = processPositionSyncPacket(packet, playerData, currentTick);
|
||||
return cancelIfEnabledAndHidden(entityID, playerData);
|
||||
}
|
||||
/**
|
||||
* @return Whether or not to cancel the packet event. <code>true</code> to cancel, <code>false</code> to do nothing.
|
||||
*/
|
||||
protected boolean handleEntityRotation(P packet, PlayerData playerData, int currentTick) {
|
||||
int entityID = processRotationPacket(packet, playerData, currentTick);
|
||||
return cancelIfEnabledAndHidden(entityID, playerData);
|
||||
}
|
||||
/**
|
||||
* @return Whether or not to cancel the packet event. <code>true</code> to cancel, <code>false</code> to do nothing.
|
||||
*/
|
||||
protected boolean handleEntityHeadLook(P packet, PlayerData playerData, int currentTick) {
|
||||
int entityID = processHeadLookPacket(packet, playerData, currentTick);
|
||||
return cancelIfEnabledAndHidden(entityID, playerData);
|
||||
}
|
||||
/**
|
||||
* @return Whether or not to cancel the packet event. <code>true</code> to cancel, <code>false</code> to do nothing.
|
||||
*/
|
||||
protected boolean handleEntityMetadata(P packet, int entityID, PlayerData playerData, int currentTick) {
|
||||
cachePacket(packet, entityID, playerData, currentTick);
|
||||
return cancelIfEnabledAndHidden(entityID, playerData);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Whether or not to cancel the packet event. <code>true</code> to cancel, <code>false</code> to do nothing.
|
||||
*/
|
||||
protected boolean handleRemoveEntityEffect(P packet, int entityID, PlayerData playerData, int currentTick) {
|
||||
cachePacket(packet, entityID, playerData, currentTick);
|
||||
return cancelIfEnabledAndHidden(entityID, playerData);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Whether or not to cancel the packet event. <code>true</code> to cancel, <code>false</code> to do nothing.
|
||||
*/
|
||||
@Packet(Packet.Packets.ENTITY_EQUIPMENT)
|
||||
protected boolean handleEntityEquipment(P packet, int entityID, PlayerData playerData, int currentTick) {
|
||||
cachePacket(packet, entityID, playerData, currentTick);
|
||||
return cancelIfEnabledAndHidden(entityID, playerData);
|
||||
}
|
||||
/**
|
||||
* @return Whether or not to cancel the packet event. <code>true</code> to cancel, <code>false</code> to do nothing.
|
||||
*/
|
||||
protected boolean handleEntityVelocity(P packet, int entityID, PlayerData playerData, int currentTick) {
|
||||
processEntityVelocityPacket(packet, playerData, currentTick);
|
||||
cachePacket(packet, entityID, playerData, currentTick); //todo: may be wrong?
|
||||
return cancelIfEnabledAndHidden(entityID, playerData);
|
||||
}
|
||||
/**
|
||||
* @return Whether or not to cancel the packet event. <code>true</code> to cancel, <code>false</code> to do nothing.
|
||||
*/
|
||||
protected boolean handleEntityEffect(P packet, int entityID, PlayerData playerData, int currentTick) {
|
||||
cachePacket(packet, entityID, playerData, currentTick);
|
||||
return cancelIfEnabledAndHidden(entityID, playerData);
|
||||
}
|
||||
/**
|
||||
* @return Whether or not to cancel the packet event. <code>true</code> to cancel, <code>false</code> to do nothing.
|
||||
*/
|
||||
protected boolean handleEntityPassengers(int entityID, int[] passengers, PlayerData playerData, int currentTick) {
|
||||
NettyEntityLocatable<?,?> entity = playerData.entityFromID(entityID);
|
||||
if (entity == null) {
|
||||
queuePassengerRetry(playerData, entityID, entityID, passengers, currentTick);
|
||||
return false;
|
||||
}
|
||||
return handleEntityPassengersNow(entity, passengers, playerData, currentTick);
|
||||
}
|
||||
|
||||
//This (and leash handling) leaks some info to the client, as it will receive the passenger packet even if the passengers are auto-hidden once parsed, but as the packet doesn't include any location or type info, this shouldn't be too incriminating.
|
||||
boolean handleEntityPassengersNow(NettyEntityLocatable<?,?> entity, int[] passengers, PlayerData playerData, int currentTick) {
|
||||
int entityID = entity.entityID();
|
||||
entity.setPassengerIDs(passengers);
|
||||
int blockingEntityID = NO_VEHICLE;
|
||||
for (int passengerID : passengers) {
|
||||
NettyEntityLocatable<?,?> passenger = playerData.entityFromID(passengerID);
|
||||
if (passenger == null) {
|
||||
if (blockingEntityID == NO_VEHICLE) {
|
||||
blockingEntityID = passengerID;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
passenger.setVehicleID(entityID);
|
||||
}
|
||||
if (blockingEntityID != NO_VEHICLE) {
|
||||
queuePassengerRetry(playerData, blockingEntityID, entityID, passengers, currentTick);
|
||||
}
|
||||
checkVehicle(entity, playerData);
|
||||
if (cancelIfEnabledAndHidden(entityID, playerData)) return true;
|
||||
boolean passengersNotVisible = false;
|
||||
ArrayList<Integer> visiblePassengers = new ArrayList<>(passengers.length);
|
||||
for (int passengerID : passengers) {
|
||||
if (cancelIfEnabledAndHidden(passengerID, playerData)) {
|
||||
passengersNotVisible = true;
|
||||
}
|
||||
else {
|
||||
visiblePassengers.add(passengerID);
|
||||
}
|
||||
}
|
||||
if (passengersNotVisible) {
|
||||
//some passengers are hidden but others aren't. Cancel this packet and send another silently with just the visible passengers.
|
||||
sendEntityPassengerPacket(entityID, visiblePassengers, playerData);
|
||||
}
|
||||
return passengersNotVisible;
|
||||
}
|
||||
|
||||
private void queuePassengerRetry(PlayerData playerData, int queueEntityID, int vehicleEntityID, int[] passengers, int submittedTick) {
|
||||
playerData.nettyData().addPostEntitySpawnTask(queueEntityID, new PassengerReconciliationTask(playerData, queueEntityID, vehicleEntityID, passengers, submittedTick));
|
||||
}
|
||||
|
||||
private void checkVehicle(NettyEntityLocatable<?,?> entity, PlayerData playerData) {
|
||||
int vehicleID = entity.vehicleID();
|
||||
if (vehicleID >= 0) {
|
||||
NettyEntityLocatable<?,?> vehicle = playerData.entityFromID(vehicleID);
|
||||
if (vehicle == null) {
|
||||
Logger.error(new RuntimeException("Found null vehicle when handling entity passengers packet, vehicleID=" + vehicleID + " for player: " + playerData.getPlayerUUID()), 2, PacketEntityViewController.class);
|
||||
return;
|
||||
}
|
||||
if (cancelIfEnabledAndHidden(vehicleID, playerData)) {
|
||||
//Vehicle is hidden, so this entity should be hidden as well. No need to check passengers.
|
||||
return;
|
||||
}
|
||||
//Vehicle is visible, but this entity may not be.
|
||||
if (cancelIfEnabledAndHidden(entity.entityID(), playerData)) {
|
||||
return;
|
||||
}
|
||||
ArrayList<Integer> passengers = new ArrayList<>();
|
||||
passengers.add(entity.entityID());
|
||||
sendEntityPassengerPacket(vehicleID, passengers, playerData);
|
||||
}
|
||||
}
|
||||
|
||||
protected void handleDestroyEntities(int[] entityIDs, PlayerData playerData, int currentTick) {
|
||||
for (int entityID : entityIDs) {
|
||||
clearPendingHolderReference(entityID, playerData);
|
||||
playerData.nettyData().removeUnresolvedLeashedEntityFromAll(entityID);
|
||||
playerData.nettyData().clearPendingPostSpawnTasksForEntity(entityID);
|
||||
EntityView<?> entityView = playerData.viewFromEntityID(entityID);
|
||||
if (entityView == null) {
|
||||
Logger.error("Could not find view for entity when processing destroy packet, id=" + entityID, 2, PacketEntityViewController.class);
|
||||
continue;
|
||||
}
|
||||
Logger.debug("Removing entity from view due to destroy packet, entityID=" + entityID + " player=" + playerData.getPlayerUUID() + " tick=" + currentTick);
|
||||
entityView.removeEntity(entityID, currentTick);
|
||||
}
|
||||
}
|
||||
|
||||
private void clearPendingHolderReference(int holderEntityID, PlayerData playerData) {
|
||||
int[] pendingLeashedEntityIDs = playerData.nettyData().consumeUnresolvedLeashes(holderEntityID);
|
||||
if (IntArrayList.isEmpty(pendingLeashedEntityIDs)) {
|
||||
return;
|
||||
}
|
||||
for (int leashedEntityID : pendingLeashedEntityIDs) {
|
||||
NettyEntityLocatable<?,?> leashedEntity = playerData.entityFromID(leashedEntityID);
|
||||
if (leashedEntity != null && leashedEntity.leashingEntity() == holderEntityID) {
|
||||
leashedEntity.setLeashingEntity(NO_LEASHER);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Whether or not to cancel the packet event. <code>true</code> to cancel, <code>false</code> to do nothing.
|
||||
*/
|
||||
protected boolean handleAttributeUpdate(P packet, int entityID, PlayerData playerData, int currentTick) {
|
||||
cachePacket(packet, entityID, playerData, currentTick);
|
||||
return cancelIfEnabledAndHidden(entityID, playerData);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Whether or not to cancel the packet event. <code>true</code> to cancel, <code>false</code> to do nothing.
|
||||
*/
|
||||
@Packet(Packet.Packets.LEASH_ENTITY)
|
||||
protected boolean handleLeashEntity(int leashedEntity, int leashingEntity, PlayerData playerData, int currentTick) {
|
||||
NettyEntityLocatable<?,?> leashed = playerData.entityFromID(leashedEntity);
|
||||
if (leashed == null) {
|
||||
playerData.nettyData().addPostEntitySpawnTask(leashedEntity, new LeashReconciliationTask(playerData, leashedEntity, leashingEntity, currentTick));
|
||||
return false;
|
||||
}
|
||||
return handleLeashEntityNow(leashed, leashingEntity, playerData);
|
||||
}
|
||||
|
||||
boolean handleLeashEntityNow(NettyEntityLocatable<?,?> leashedEntity, int leashingEntity, PlayerData playerData) {
|
||||
//Note, leashing entity ID will be -1 to unleash. From testing it sometimes seems to be 0?
|
||||
removeExistingLeashReference(leashedEntity.entityID(), leashedEntity, playerData);
|
||||
if (leashingEntity == -1 || leashingEntity == 0) {
|
||||
if (leashedEntity.leashingEntity() == NO_LEASHER) {
|
||||
Logger.warning("Entity was already unleashing when handling leash entity packet, leashedEntityID=" + leashedEntity + " for player: " + playerData.getPlayerUUID(), 4, PacketEntityViewController.class);
|
||||
return false;
|
||||
}
|
||||
leashedEntity.setLeashingEntity(NO_LEASHER);
|
||||
return cancelIfEnabledAndHidden(leashedEntity, playerData);
|
||||
}
|
||||
else {
|
||||
leashedEntity.setLeashingEntity(leashingEntity);
|
||||
NettyEntityLocatable<?,?> leashing = playerData.entityFromID(leashingEntity);
|
||||
if (leashing == null) {
|
||||
playerData.nettyData().addUnresolvedLeash(leashingEntity, leashedEntity.entityID());
|
||||
return cancelIfEnabledAndHidden(leashedEntity, playerData);
|
||||
}
|
||||
else {
|
||||
leashing.addLeashedEntity(leashedEntity.entityID());
|
||||
return cancelIfEnabledAndHidden(leashedEntity, playerData) || cancelIfEnabledAndHidden(leashingEntity, playerData);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void removeExistingLeashReference(int leashedEntityID, NettyEntityLocatable<?,?> leashed, PlayerData playerData) {
|
||||
int previousLeashingEntityID = leashed.leashingEntity();
|
||||
if (previousLeashingEntityID == NO_LEASHER) {
|
||||
return;
|
||||
}
|
||||
if (playerData.nettyData().removeUnresolvedLeash(previousLeashingEntityID, leashedEntityID)) {
|
||||
return;
|
||||
}
|
||||
NettyEntityLocatable<?,?> previouslyLeashing = playerData.entityFromID(previousLeashingEntityID);
|
||||
if (previouslyLeashing == null) {
|
||||
Logger.warning("Found null previously leashing entity when handling leash entity packet, previouslyLeashingEntityID=" + previousLeashingEntityID + " for player: " + playerData.getPlayerUUID(), 5, PacketEntityViewController.class);
|
||||
return;
|
||||
}
|
||||
previouslyLeashing.removeLeashedEntity(leashedEntityID);
|
||||
}
|
||||
|
||||
protected RaycastConfig getCorrectConfig(EntityView<?> entityView) {
|
||||
if (entityView.isPlayerView()) {
|
||||
return playerConfig;
|
||||
} else {
|
||||
return entityConfig;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return True if the packet should be suppressed
|
||||
*/
|
||||
protected boolean cancelIfEnabledAndHidden(int entityID, PlayerData playerData) {
|
||||
EntityView<?> entityView = playerData.viewFromEntityID(entityID);
|
||||
|
||||
if (entityView == null) {
|
||||
Logger.warning("Checked if packet for entity should be cancelled, but entity did not exist. ID: " + entityID + " for player: " + playerData.getPlayerUUID(), 6, PacketEntityViewController.class);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (entityView.isVisible(entityID)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return getCorrectConfig(entityView).enabled(); // If this statement is reached, the entity should be hidden, so if the config is enabled it is hidden.
|
||||
}
|
||||
|
||||
/**
|
||||
* @return True if the packet should be suppressed
|
||||
*/
|
||||
protected boolean cancelIfEnabledAndHidden(NettyEntityLocatable<?,?> entity, PlayerData playerData) {
|
||||
if (entity.visible()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return getCorrectConfig(playerData.viewFromEntityID(entity.entityID())).enabled(); // If this statement is reached, the entity should be hidden, so if the config is enabled it is hidden.
|
||||
}
|
||||
|
||||
/**
|
||||
* @return The created entity, with a default visibility of <code>true</code>. Does not insert the entity into any views, that is the responsibility of the caller.
|
||||
*/
|
||||
protected abstract NettyEntityLocatable<?,?> processEntitySpawn(PlayerData playerData, P packet, UUID world, int currentTick);
|
||||
|
||||
/** @return The entity ID of the entity */
|
||||
protected abstract int processRelativeMovePacket(P packet, PlayerData playerData, int currentTick);
|
||||
|
||||
/** @return The entity ID of the entity */
|
||||
protected abstract int processRelativeMoveAndRotationPacket(P packet, PlayerData playerData, int currentTick);
|
||||
|
||||
/** @return The entity ID of the entity */
|
||||
protected abstract int processTeleportPacket(P packet, PlayerData playerData, int currentTick);
|
||||
|
||||
/** @return The entity ID of the entity */
|
||||
protected abstract int processPositionSyncPacket(P packet, PlayerData playerData, int currentTick);
|
||||
|
||||
protected abstract void cachePacket(P packet, int entityID, PlayerData playerData, int currentTick);
|
||||
/** @return The entity ID of the entity */
|
||||
protected abstract int processRotationPacket(P packet, PlayerData playerData, int currentTick);
|
||||
|
||||
/** @return The entity ID of the entity */
|
||||
protected abstract int processHeadLookPacket(P packet, PlayerData playerData, int currentTick);
|
||||
|
||||
/** @return The entity ID of the entity */
|
||||
protected abstract int processEntityVelocityPacket(P packet, PlayerData playerData, int currentTick);
|
||||
|
||||
/**Silently sends the provided array of entities as passengers for the required vehicle.*/
|
||||
protected abstract void sendEntityPassengerPacket(int vehicle, ArrayList<Integer> passengers, PlayerData playerData);
|
||||
|
||||
protected abstract void insertEntityToPlayerView(NettyEntityLocatable<?,?> entity, PlayerData playerData);
|
||||
|
||||
protected abstract void insertEntityToEntityView(NettyEntityLocatable<?,?> entity, PlayerData playerData);
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package games.cubi.raycastedantiesp.core.view.controller;
|
||||
|
||||
import games.cubi.logs.Logger;
|
||||
import games.cubi.raycastedantiesp.core.locatables.NettyEntityLocatable;
|
||||
import games.cubi.raycastedantiesp.core.players.PlayerData;
|
||||
import games.cubi.raycastedantiesp.core.utils.BaseEntitySpawnTask;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
final class PassengerReconciliationTask extends BaseEntitySpawnTask {
|
||||
private final PlayerData playerData;
|
||||
private final int queuedEntityId;
|
||||
private final int vehicleEntityId;
|
||||
private final int[] passengerIds;
|
||||
|
||||
PassengerReconciliationTask(PlayerData playerData, int queuedEntityId, int vehicleEntityId, int[] passengerIds, int submittedTick) {
|
||||
super(submittedTick);
|
||||
this.playerData = playerData;
|
||||
this.queuedEntityId = queuedEntityId;
|
||||
this.vehicleEntityId = vehicleEntityId;
|
||||
this.passengerIds = passengerIds.clone();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
NettyEntityLocatable<?,?> vehicle = playerData.entityFromID(vehicleEntityId);
|
||||
if (vehicle == null) {
|
||||
Logger.error("Reconciliation fail: Attempted to reconcile passengers for unknown vehicle, queuedEntityId=" + queuedEntityId + " vehicleEntityId=" + vehicleEntityId, 3, this.getClass());
|
||||
return;
|
||||
}
|
||||
PacketEntityViewController.get().handleEntityPassengersNow(vehicle, passengerIds, playerData, submittedTick);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "PassengerReconciliationTask{" +
|
||||
"submittedTick=" + submittedTick +
|
||||
", queuedEntityId=" + queuedEntityId +
|
||||
", vehicleEntityId=" + vehicleEntityId +
|
||||
", passengerIds=" + Arrays.toString(passengerIds) +
|
||||
", playerUUID=" + playerData.getPlayerUUID() +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
short-git: ${short_git}
|
||||
long-git: ${long_git}
|
||||
build-time: ${build_time}
|
||||
version: ${version}
|
||||
@@ -0,0 +1,4 @@
|
||||
group=games.cubi
|
||||
org.gradle.configuration-cache=true
|
||||
org.gradle.parallel=true
|
||||
org.gradle.caching=true
|
||||
Vendored
BIN
Binary file not shown.
+1
-1
@@ -1,6 +1,6 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.0-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
# Copyright © 2015 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
@@ -15,6 +15,8 @@
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
@@ -84,7 +86,7 @@ done
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
|
||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
@@ -112,7 +114,6 @@ case "$( uname )" in #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
@@ -170,7 +171,6 @@ fi
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
@@ -203,15 +203,14 @@ fi
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
|
||||
Vendored
+3
-2
@@ -13,6 +13,8 @@
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
@rem SPDX-License-Identifier: Apache-2.0
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@@ -68,11 +70,10 @@ goto fail
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import java.time.Instant
|
||||
|
||||
plugins {
|
||||
id("java")
|
||||
}
|
||||
|
||||
group = "games.cubi.locatables"
|
||||
version = "0.1.0"
|
||||
|
||||
val commitShort = providers.exec {
|
||||
commandLine("git", "rev-parse", "--short=8", "HEAD")
|
||||
}.standardOutput.asText.map { it.trim() }
|
||||
|
||||
val commitFull = providers.exec {
|
||||
commandLine("git", "rev-parse", "HEAD")
|
||||
}.standardOutput.asText.map { it.trim() }
|
||||
|
||||
val buildTime = providers.provider {
|
||||
Instant.now().toString()
|
||||
}
|
||||
|
||||
tasks {
|
||||
processResources {
|
||||
val gitProps = mapOf(
|
||||
"short_git" to commitShort.get(),
|
||||
"long_git" to commitFull.get(),
|
||||
"build_time" to buildTime.get(),
|
||||
"version" to version.toString()
|
||||
)
|
||||
// build-properties is not used by the locatables library itself, but is included in the jar so that platforms can access it.
|
||||
filesMatching("build-properties/locatable-lib.yml") {
|
||||
expand(gitProps)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compileOnly(project(":logging"))
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package games.cubi.locatables;
|
||||
|
||||
import games.cubi.locatables.implementations.MutableLocatableImpl;
|
||||
|
||||
public non-sealed interface BlockLocatable extends Locatable {
|
||||
|
||||
default MutableLocatable clonePlainAndCentreIfBlockLocation() {
|
||||
return new MutableLocatableImpl(world(), blockX() + 0.5, blockY() + 0.5, blockZ() + 0.5);
|
||||
}
|
||||
|
||||
default boolean isEqual(Object o) {
|
||||
if (this == o) return true;
|
||||
if (!(o instanceof BlockLocatable other)) return false;
|
||||
return this.blockX() == other.blockX() && this.blockY() == other.blockY() && this.blockZ() == other.blockZ() && world().equals(other.world());
|
||||
}
|
||||
|
||||
default int blockHash() {
|
||||
int result = 17;
|
||||
result = 31 * result + (this.world() != null ? this.world().hashCode() : 0);
|
||||
result = 31 * result + this.blockX();
|
||||
result = 31 * result + this.blockY();
|
||||
result = 31 * result + this.blockZ();
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
default double x() {
|
||||
return blockX();
|
||||
}
|
||||
|
||||
@Override
|
||||
default double y() {
|
||||
return blockY();
|
||||
}
|
||||
|
||||
@Override
|
||||
default double z() {
|
||||
return blockZ();
|
||||
}
|
||||
|
||||
@Override
|
||||
int blockX();
|
||||
|
||||
@Override
|
||||
int blockY();
|
||||
|
||||
@Override
|
||||
int blockZ();
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package games.cubi.locatables;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public sealed interface ChunkLocatable permits ChunkLocatable.ImmutableChunkLocatable, ChunkSectionLocatable {
|
||||
UUID world();
|
||||
int chunkX();
|
||||
int chunkZ();
|
||||
|
||||
record ImmutableChunkLocatable(UUID world, int chunkX, int chunkZ) implements ChunkLocatable {
|
||||
public ImmutableChunkLocatable(Locatable locatable) {
|
||||
this(locatable.world(), locatable.chunkX(), locatable.chunkZ());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package games.cubi.locatables;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public sealed interface ChunkSectionLocatable extends ChunkLocatable permits ChunkSectionLocatable.ImmutableChunkSectionLocatable, Locatable {
|
||||
int chunkY();
|
||||
|
||||
record ImmutableChunkSectionLocatable(UUID world, int chunkX, int chunkY, int chunkZ) implements ChunkSectionLocatable {
|
||||
public ImmutableChunkSectionLocatable(Locatable locatable) {
|
||||
this(locatable.world(), locatable.chunkX(), locatable.chunkY(), locatable.chunkZ());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package games.cubi.locatables;
|
||||
|
||||
public non-sealed interface ImmutableLocatable extends Locatable {
|
||||
default boolean isMutable() {
|
||||
return false;
|
||||
}
|
||||
|
||||
default MutableLocatable castToMutableOrNull() {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
package games.cubi.locatables;
|
||||
|
||||
import games.cubi.locatables.implementations.*;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
// A vector-like interface representing a location in a 3D space within a specific world.
|
||||
public sealed interface Locatable extends ChunkSectionLocatable, StrictEquality permits MutableLocatable, ImmutableLocatable, BlockLocatable {
|
||||
|
||||
double x();
|
||||
double y();
|
||||
double z();
|
||||
UUID world();
|
||||
|
||||
default int blockX() {
|
||||
return (int) Math.floor(x());
|
||||
}
|
||||
default int blockY() {
|
||||
return (int) Math.floor(y());
|
||||
}
|
||||
default int blockZ() {
|
||||
return (int) Math.floor(z());
|
||||
}
|
||||
|
||||
@Override
|
||||
default int chunkX() {
|
||||
return blockX() >> 4;
|
||||
}
|
||||
@Override
|
||||
default int chunkZ() {
|
||||
return blockZ() >> 4;
|
||||
}
|
||||
@Override
|
||||
default int chunkY() {
|
||||
return blockY() >> 4;
|
||||
}
|
||||
|
||||
default double length() {
|
||||
return Math.sqrt(lengthSquared());
|
||||
}
|
||||
|
||||
default double lengthSquared() {
|
||||
return x() * x() + y() * y() + z() * z();
|
||||
}
|
||||
|
||||
default double distance(Locatable locatable) {
|
||||
return Math.sqrt(distanceSquared(locatable));
|
||||
}
|
||||
|
||||
default double distanceSquared(Locatable locatable) {
|
||||
double dx = x() - locatable.x();
|
||||
double dy = y() - locatable.y();
|
||||
double dz = z() - locatable.z();
|
||||
return dx * dx + dy * dy + dz * dz;
|
||||
}
|
||||
|
||||
default double distanceSquared(double x, double y, double z) {
|
||||
double dx = this.x() - x;
|
||||
double dy = this.y() - y;
|
||||
double dz = this.z() - z;
|
||||
return dx * dx + dy * dy + dz * dz;
|
||||
}
|
||||
|
||||
default MutableLocatable clonePlainAndCentreIfBlockLocation() {
|
||||
return new MutableLocatableImpl(world(), x(), y(), z());
|
||||
}
|
||||
|
||||
/**@return An array of the 3 coordinates, in the order [x,y,z]. This is used for atomic updates of all 3 coordinates.*/
|
||||
default double[] getAtomicPositionArray() {
|
||||
synchronized (this) {
|
||||
return new double[]{x(), y(), z()};
|
||||
}
|
||||
}
|
||||
|
||||
LocatableType getType();
|
||||
|
||||
boolean isMutable();
|
||||
|
||||
MutableLocatable castToMutableOrNull(); // There shouldn't be a need for an equivalent of this method for immutable locatables as all of their methods are common to all Locatables
|
||||
|
||||
default boolean isEqualTo(Object thatOne) {
|
||||
if (this == thatOne) return true;
|
||||
if (!(thatOne instanceof Locatable that)) return false;
|
||||
if (!(this.world().equals(that.world()))) return false;
|
||||
|
||||
if (Double.doubleToLongBits(this.x()) != Double.doubleToLongBits(that.x())) {
|
||||
return false;
|
||||
}
|
||||
if (Double.doubleToLongBits(this.y()) != Double.doubleToLongBits(that.y())) {
|
||||
return false;
|
||||
}
|
||||
if (Double.doubleToLongBits(this.z()) != Double.doubleToLongBits(that.z())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
default int makeHash() {
|
||||
int hash = 3;
|
||||
|
||||
hash = 19 * hash + this.world().hashCode();
|
||||
hash = 19 * hash + Long.hashCode(Double.doubleToLongBits(x()));
|
||||
hash = 19 * hash + Long.hashCode(Double.doubleToLongBits(y()));
|
||||
hash = 19 * hash + Long.hashCode(Double.doubleToLongBits(z()));
|
||||
return hash;
|
||||
}
|
||||
|
||||
default String toStringForm() {
|
||||
return getType()+
|
||||
"{" +
|
||||
"world=" + world() +
|
||||
", x=" + x() +
|
||||
", y=" + y() +
|
||||
", z=" + z() +
|
||||
'}';
|
||||
}
|
||||
|
||||
enum LocatableType {
|
||||
ThreadSafe,
|
||||
NettyEntity,
|
||||
NettyTileEntity,
|
||||
MutableBlockVector,
|
||||
ImmutableBlockLocation,
|
||||
Immutable,
|
||||
Mutable,
|
||||
// implementations from other modules/projects should use the following
|
||||
ExternalMutable,
|
||||
ExternalImmutable,
|
||||
ExternalMutableBlock,
|
||||
ExternalImmutableBlock,
|
||||
}
|
||||
|
||||
static Locatable convertLocatable(Locatable from, LocatableType to, boolean clone) {
|
||||
switch (to) {
|
||||
case ThreadSafe -> {
|
||||
if ((from instanceof ThreadSafeLocatable) && !clone) return from;
|
||||
return new ThreadSafeLocatable(from.world(), from.x(), from.y(), from.z());
|
||||
}
|
||||
case MutableBlockVector -> {
|
||||
if ((from instanceof MutableBlockVector) && !clone) return from;
|
||||
return new MutableBlockVector(from.world(), from.x(), from.y(), from.z());
|
||||
}
|
||||
case ImmutableBlockLocation -> {
|
||||
if ((from instanceof ImmutableBlockLocatable) && !clone) return from;
|
||||
return new ImmutableBlockLocatable(from.world(), from.x(), from.y(), from.z());
|
||||
}
|
||||
case Mutable -> {
|
||||
if ((from instanceof MutableLocatableImpl) && !clone) return from;
|
||||
return new MutableLocatableImpl(from.world(), from.x(), from.y(), from.z());
|
||||
}
|
||||
default -> {
|
||||
return new MutableLocatableImpl(from.world(), from.x(), from.y(), from.z());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static Locatable copyOf(Locatable locatable) {
|
||||
return convertLocatable(locatable, locatable.getType(), true);
|
||||
}
|
||||
|
||||
static Locatable create(UUID world, double x, double y, double z, LocatableType type) {
|
||||
switch (type) {
|
||||
case ThreadSafe -> {
|
||||
return new ThreadSafeLocatable(world, x, y, z);
|
||||
}
|
||||
case MutableBlockVector, ExternalMutableBlock -> {
|
||||
return new MutableBlockVector(world, x, y, z);
|
||||
}
|
||||
case Mutable, ExternalMutable -> {
|
||||
return new MutableLocatableImpl(world, x, y, z);
|
||||
}
|
||||
case ImmutableBlockLocation, ExternalImmutableBlock -> {
|
||||
return new ImmutableBlockLocatable(world, x, y, z);
|
||||
}
|
||||
case Immutable, ExternalImmutable -> {
|
||||
return new ImmutableLocatableImpl(world, x, y, z);
|
||||
}
|
||||
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
static <T extends Locatable> T create(UUID world, double x, double y, double z, Class<T> type) {
|
||||
if (type == ThreadSafeLocatable.class) {
|
||||
return (T) new ThreadSafeLocatable(world, x, y, z);
|
||||
} else if (type == MutableBlockVector.class) {
|
||||
return (T) new MutableBlockVector(world, x, y, z);
|
||||
} else if (type == ImmutableBlockLocatable.class) {
|
||||
return (T) new ImmutableBlockLocatable(world, x, y, z);
|
||||
} else if (type == MutableLocatableImpl.class) {
|
||||
return (T) new MutableLocatableImpl(world, x, y, z);
|
||||
} else if (type == ImmutableLocatableImpl.class) {
|
||||
return (T) new ImmutableLocatableImpl(world, x, y, z);
|
||||
} else {
|
||||
throw new IllegalArgumentException("Unsupported Locatable type: " + type.getName());
|
||||
}
|
||||
}
|
||||
|
||||
static Locatable create(UUID world, double x, double y, double z) {
|
||||
return create(world, x, y, z, LocatableType.Mutable);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package games.cubi.locatables;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public non-sealed interface MutableLocatable extends Locatable {
|
||||
MutableLocatable setX(double x);
|
||||
MutableLocatable setY(double y);
|
||||
MutableLocatable setZ(double z);
|
||||
MutableLocatable setWorld(UUID world);
|
||||
|
||||
/**@return The same Locatable, with the same direction but a length of 1.*/
|
||||
default MutableLocatable normalize() {
|
||||
double length = length();
|
||||
return scalarMultiply(1.0 / length);
|
||||
}
|
||||
|
||||
/**@return The same Locatable, now mutated.*/
|
||||
default MutableLocatable add(Locatable locatable) {
|
||||
setX(x() + locatable.x());
|
||||
setY(y() + locatable.y());
|
||||
setZ(z() + locatable.z());
|
||||
return this;
|
||||
}
|
||||
|
||||
default MutableLocatable add(double x, double y, double z) {
|
||||
setX(x() + x);
|
||||
setY(y() + y);
|
||||
setZ(z() + z);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**@return The same Locatable, now mutated.*/
|
||||
default MutableLocatable subtract(Locatable locatable) {
|
||||
setX(x() - locatable.x());
|
||||
setY(y() - locatable.y());
|
||||
setZ(z() - locatable.z());
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param locatable The locatable to copy the position and world from.
|
||||
* @return The same Locatable, now mutated to have the same position and world as the given locatable.
|
||||
*/
|
||||
default MutableLocatable set(Locatable locatable) {
|
||||
setX(locatable.x());
|
||||
setY(locatable.y());
|
||||
setZ(locatable.z());
|
||||
setWorld(locatable.world());
|
||||
return this;
|
||||
}
|
||||
|
||||
default MutableLocatable set(double x, double y, double z) {
|
||||
setX(x);
|
||||
setY(y);
|
||||
setZ(z);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return The same Locatable, now mutated to have the same position and world as the given values.
|
||||
*/
|
||||
default MutableLocatable set(double x, double y, double z, UUID world) {
|
||||
setWorld(world);
|
||||
setX(x);
|
||||
setY(y);
|
||||
setZ(z);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**@return The same Locatable, now mutated.*/
|
||||
default MutableLocatable scalarMultiply(double factor) {
|
||||
setX(x() * factor);
|
||||
setY(y() * factor);
|
||||
setZ(z() * factor);
|
||||
return this;
|
||||
}
|
||||
|
||||
default boolean isMutable() {
|
||||
return true;
|
||||
}
|
||||
|
||||
default MutableLocatable castToMutableOrNull() {
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package games.cubi.locatables;
|
||||
|
||||
public interface StrictEquality {
|
||||
/**
|
||||
* For use with classes of interfaces such as {@link games.cubi.locatables.Locatable}, where the interface contract specifies that all implementations must use interface-defined <code>equals</code> and <code>hashcode</code> methods for interchangeability in data structures. In this case, the default {@link Object#equals(Object)} method is no longer able to confirm genuine equality, as it only checks for interface field equality.
|
||||
* <p>
|
||||
* This method should check for more typical equality, meaning that all fields of the object are equal, and the classes of the two objects are the same. This is useful for debugging and testing, as it allows us to confirm that two objects are genuinely equal, rather than just being interchangeable in data structures.
|
||||
* @param other The other object to compare to.
|
||||
* @return <code>True</code> if the two objects are
|
||||
* <p>- references to the same object, or
|
||||
* <p>- different objects of the same class with equal fields.
|
||||
* <p><code>False</code> otherwise.
|
||||
*/
|
||||
boolean strictlyEquals(Object other);
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package games.cubi.locatables.implementations;
|
||||
|
||||
import games.cubi.locatables.ImmutableLocatable;
|
||||
import games.cubi.locatables.BlockLocatable;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public record ImmutableBlockLocatable(UUID world, int blockX, int blockY, int blockZ) implements BlockLocatable, ImmutableLocatable {
|
||||
|
||||
public ImmutableBlockLocatable(UUID world, double x, double y, double z) {
|
||||
this(world, (int) Math.floor(x), (int) Math.floor(y), (int) Math.floor(z));
|
||||
}
|
||||
|
||||
@Override
|
||||
public LocatableType getType() {
|
||||
return LocatableType.ImmutableBlockLocation;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
return isEqual(o);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return blockHash();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return toStringForm();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean strictlyEquals(Object other) {
|
||||
if (this == other) return true;
|
||||
if (!(other instanceof ImmutableBlockLocatable(UUID world1, int x, int y, int z))) return false;
|
||||
return blockX == x && blockY == y && blockZ == z && world.equals(world1);
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package games.cubi.locatables.implementations;
|
||||
|
||||
import games.cubi.locatables.ImmutableLocatable;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public record ImmutableLocatableImpl(UUID world, double x, double y, double z) implements ImmutableLocatable {
|
||||
|
||||
@Override
|
||||
public LocatableType getType() {
|
||||
return LocatableType.Immutable;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
return isEqualTo(o);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return makeHash();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return toStringForm();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean strictlyEquals(Object other) {
|
||||
if (this == other) return true;
|
||||
if (!(other instanceof ImmutableLocatableImpl(UUID world1, double x1, double y1, double z1))) return false;
|
||||
return this.world.equals(world1) &&
|
||||
Double.doubleToLongBits(this.x) == Double.doubleToLongBits(x1) &&
|
||||
Double.doubleToLongBits(this.y) == Double.doubleToLongBits(y1) &&
|
||||
Double.doubleToLongBits(this.z) == Double.doubleToLongBits(z1);
|
||||
}
|
||||
}
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
package games.cubi.locatables.implementations;
|
||||
|
||||
import games.cubi.locatables.Locatable;
|
||||
import games.cubi.locatables.MutableLocatable;
|
||||
import games.cubi.locatables.BlockLocatable;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* A mutable locatable representing a floating-point vector in a given world, akin to a MutableLocatableImpl. However, Object#equals and Object#hashCode are implemented as per BlockLocatable, meaning that they are equal if their blockX, blockY, blockZ and world are equal.
|
||||
* <p>
|
||||
* This allows them to be used as keys in hashmaps where they will be considered equal to AbstractBlockLocations with the same block coordinates and world, but they can also be mutated and have vector-like operations performed on them.
|
||||
* <p>
|
||||
* The object is named "Vector" to reflect the fact that it supports floating-point coordinates under the hood.
|
||||
*/
|
||||
public class MutableBlockVector implements BlockLocatable, MutableLocatable {
|
||||
private UUID world;
|
||||
private double mutableX;
|
||||
private double mutableY;
|
||||
private double mutableZ;
|
||||
|
||||
public MutableBlockVector(UUID world, double x, double y, double z) {
|
||||
this.world = world;
|
||||
this.mutableX = x;
|
||||
this.mutableY = y;
|
||||
this.mutableZ = z;
|
||||
}
|
||||
|
||||
public MutableBlockVector(UUID world, int x, int y, int z) {
|
||||
this.world = world;
|
||||
this.mutableX = x;
|
||||
this.mutableY = y;
|
||||
this.mutableZ = z;
|
||||
}
|
||||
|
||||
@Override
|
||||
public LocatableType getType() {
|
||||
return LocatableType.MutableBlockVector;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double length() {
|
||||
return Math.sqrt(lengthSquared());
|
||||
}
|
||||
|
||||
@Override
|
||||
public double lengthSquared() {
|
||||
return mutableX*mutableX + mutableY*mutableY + mutableZ*mutableZ;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MutableLocatable add(Locatable locatable) {
|
||||
this.mutableX += locatable.x();
|
||||
this.mutableY += locatable.y();
|
||||
this.mutableZ += locatable.z();
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MutableLocatable subtract(Locatable locatable) {
|
||||
this.mutableX -= locatable.x();
|
||||
this.mutableY -= locatable.y();
|
||||
this.mutableZ -= locatable.z();
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MutableLocatable scalarMultiply(double factor) {
|
||||
this.mutableX *= factor;
|
||||
this.mutableY *= factor;
|
||||
this.mutableZ *= factor;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID world() {
|
||||
return world;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int blockX() {
|
||||
return (int) Math.floor(mutableX);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int blockY() {
|
||||
return (int) Math.floor(mutableY);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int blockZ() {
|
||||
return (int) Math.floor(mutableZ);
|
||||
}
|
||||
|
||||
@Override
|
||||
public double x() {
|
||||
return mutableX;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double y() {
|
||||
return mutableY;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double z() {
|
||||
return mutableZ;
|
||||
}
|
||||
|
||||
public void add(int dx, int dy, int dz) {
|
||||
this.mutableX += dx;
|
||||
this.mutableY += dy;
|
||||
this.mutableZ += dz;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MutableLocatable setX(double x) {
|
||||
this.mutableX = x;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MutableLocatable setY(double y) {
|
||||
this.mutableY = y;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MutableLocatable setZ(double z) {
|
||||
this.mutableZ = z;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MutableLocatable setWorld(UUID world) {
|
||||
this.world = world;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* This checks equality with AbstractBlockLocations, not Locatables. Use Locatable#isEqualTo for that. Thus, hashmap lookups are compatible with only AbstractBlockLocations, not Locatables.
|
||||
*/
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
return isEqual(o);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return blockHash();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return toStringForm();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean strictlyEquals(Object other) {
|
||||
if (this == other) return true;
|
||||
if (!(other instanceof MutableBlockVector that)) return false;
|
||||
if (!(this.world().equals(that.world()))) return false;
|
||||
|
||||
if (Double.doubleToLongBits(this.x()) != Double.doubleToLongBits(that.x())) {
|
||||
return false;
|
||||
}
|
||||
if (Double.doubleToLongBits(this.y()) != Double.doubleToLongBits(that.y())) {
|
||||
return false;
|
||||
}
|
||||
return Double.doubleToLongBits(this.z()) == Double.doubleToLongBits(that.z());
|
||||
}
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
package games.cubi.locatables.implementations;
|
||||
|
||||
import games.cubi.locatables.MutableLocatable;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public class MutableLocatableImpl implements MutableLocatable {
|
||||
private double x;
|
||||
private double y;
|
||||
private double z;
|
||||
private UUID world;
|
||||
|
||||
public MutableLocatableImpl(UUID world, double x, double y, double z) {
|
||||
this.world = world;
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
this.z = z;
|
||||
}
|
||||
|
||||
@Override
|
||||
public LocatableType getType() {
|
||||
return LocatableType.Mutable;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID world() {
|
||||
return world;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double x() {
|
||||
return x;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double y() {
|
||||
return y;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double z() {
|
||||
return 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;
|
||||
}
|
||||
|
||||
public MutableLocatable setWorld(UUID world) {
|
||||
this.world = world;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
return isEqualTo(o);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return makeHash();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return toStringForm();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean strictlyEquals(Object other) {
|
||||
if (this == other) return true;
|
||||
if (!(other instanceof MutableLocatableImpl that)) return false;
|
||||
if (!(this.world().equals(that.world()))) return false;
|
||||
|
||||
if (Double.doubleToLongBits(this.x()) != Double.doubleToLongBits(that.x())) {
|
||||
return false;
|
||||
}
|
||||
if (Double.doubleToLongBits(this.y()) != Double.doubleToLongBits(that.y())) {
|
||||
return false;
|
||||
}
|
||||
return Double.doubleToLongBits(this.z()) == Double.doubleToLongBits(that.z());
|
||||
}
|
||||
}
|
||||
+328
@@ -0,0 +1,328 @@
|
||||
package games.cubi.locatables.implementations;
|
||||
|
||||
import games.cubi.locatables.Locatable;
|
||||
import games.cubi.locatables.MutableLocatable;
|
||||
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.locks.StampedLock;
|
||||
|
||||
public class ThreadSafeLocatable implements MutableLocatable {
|
||||
private volatile UUID world;
|
||||
|
||||
private double x, y, z;
|
||||
|
||||
private final StampedLock lock = new StampedLock();
|
||||
|
||||
public ThreadSafeLocatable(UUID world, double x, double y, double z) {
|
||||
this.world = world;
|
||||
this.x = x; this.y = y; this.z = z;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a write operation on x, y, z fields under a write lock.
|
||||
*/
|
||||
private void withWriteLock(Runnable body) {
|
||||
long stamp = lock.writeLock();
|
||||
try {
|
||||
body.run();
|
||||
} finally {
|
||||
lock.unlockWrite(stamp);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (!(o instanceof Locatable that)) return false;
|
||||
|
||||
long stamp = lock.tryOptimisticRead();
|
||||
|
||||
UUID thatWorld = that.world();
|
||||
double[] thatPos = that.getAtomicPositionArray();
|
||||
|
||||
boolean equal = this.world.equals(thatWorld) &&
|
||||
Double.doubleToLongBits(this.x) == Double.doubleToLongBits(thatPos[0]) &&
|
||||
Double.doubleToLongBits(this.y) == Double.doubleToLongBits(thatPos[1]) &&
|
||||
Double.doubleToLongBits(this.z) == Double.doubleToLongBits(thatPos[2]);
|
||||
if (!lock.validate(stamp)) {
|
||||
// If the lock was invalid, we can't trust the result, so we have to retry with locks again
|
||||
stamp = lock.readLock();
|
||||
thatWorld = that.world();
|
||||
thatPos = that.getAtomicPositionArray();
|
||||
try {
|
||||
equal = this.world.equals(thatWorld) &&
|
||||
Double.doubleToLongBits(this.x) == Double.doubleToLongBits(thatPos[0]) &&
|
||||
Double.doubleToLongBits(this.y) == Double.doubleToLongBits(thatPos[1]) &&
|
||||
Double.doubleToLongBits(this.z) == Double.doubleToLongBits(thatPos[2]);
|
||||
} finally {
|
||||
lock.unlockRead(stamp);
|
||||
}
|
||||
}
|
||||
return equal;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
long stamp = lock.tryOptimisticRead();
|
||||
int hash = 3;
|
||||
// while we could just grab the values, release the lock, and then calculate the hash, that would marginally increase ram use for a marginal performance gain and this looks neater
|
||||
hash = 19 * hash + this.world.hashCode();
|
||||
hash = 19 * hash + Long.hashCode(Double.doubleToLongBits(this.x));
|
||||
hash = 19 * hash + Long.hashCode(Double.doubleToLongBits(this.y));
|
||||
hash = 19 * hash + Long.hashCode(Double.doubleToLongBits(this.z));
|
||||
if (!lock.validate(stamp)) {
|
||||
stamp = lock.readLock();
|
||||
try {
|
||||
hash = 3;
|
||||
hash = 19 * hash + this.world.hashCode();
|
||||
hash = 19 * hash + Long.hashCode(Double.doubleToLongBits(this.x));
|
||||
hash = 19 * hash + Long.hashCode(Double.doubleToLongBits(this.y));
|
||||
hash = 19 * hash + Long.hashCode(Double.doubleToLongBits(this.z));
|
||||
} finally {
|
||||
lock.unlockRead(stamp);
|
||||
}
|
||||
}
|
||||
return hash;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
// It's a string, who cares if it's not thread safe?
|
||||
return toStringForm();
|
||||
}
|
||||
|
||||
@Override
|
||||
public LocatableType getType() {
|
||||
return LocatableType.ThreadSafe;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double length() {
|
||||
return Math.sqrt(lengthSquared());
|
||||
}
|
||||
|
||||
@Override
|
||||
public double lengthSquared() {
|
||||
long stamp = lock.tryOptimisticRead();
|
||||
double result = x*x + y*y + z*z;
|
||||
if (!lock.validate(stamp)) {
|
||||
stamp = lock.readLock();
|
||||
try {
|
||||
result = x*x + y*y + z*z;
|
||||
} finally {
|
||||
lock.unlockRead(stamp);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Normalised internal vectors, may busy-wait if write access is locked
|
||||
*/
|
||||
@Override
|
||||
public MutableLocatable normalize() {
|
||||
withWriteLock(() -> {
|
||||
double len = Math.sqrt(x*x + y*y + z*z);
|
||||
x /= len; y /= len; z /= len;
|
||||
});
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MutableLocatable add(Locatable locatable) {
|
||||
double[] otherPosition = locatable.getAtomicPositionArray();
|
||||
withWriteLock(() -> {
|
||||
x += otherPosition[0];
|
||||
y += otherPosition[1];
|
||||
z += otherPosition[2];
|
||||
});
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MutableLocatable add(double x, double y, double z) {
|
||||
withWriteLock(() -> { this.x += x; this.y += y; this.z += z; });
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MutableLocatable subtract(Locatable locatable) {
|
||||
double[] otherPosition = locatable.getAtomicPositionArray();
|
||||
withWriteLock(() -> {
|
||||
x -= otherPosition[0];
|
||||
y -= otherPosition[1];
|
||||
z -= otherPosition[2];
|
||||
});
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MutableLocatable scalarMultiply(double factor) {
|
||||
withWriteLock(() -> { x *= factor; y *= factor; z *= factor; });
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID world() {
|
||||
long stamp = lock.tryOptimisticRead();
|
||||
UUID result = world;
|
||||
if (!lock.validate(stamp)) {
|
||||
stamp = lock.readLock();
|
||||
try {
|
||||
result = world;
|
||||
} finally {
|
||||
lock.unlockRead(stamp);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int blockX() {
|
||||
return (int) Math.floor(x());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int blockY() {
|
||||
return (int) Math.floor(y());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int blockZ() {
|
||||
return (int) Math.floor(z());
|
||||
}
|
||||
|
||||
@Override
|
||||
public double x() {
|
||||
long stamp = lock.tryOptimisticRead();
|
||||
double result = x;
|
||||
if (!lock.validate(stamp)) {
|
||||
stamp = lock.readLock();
|
||||
try {
|
||||
result = x;
|
||||
} finally {
|
||||
lock.unlockRead(stamp);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double y() {
|
||||
long stamp = lock.tryOptimisticRead();
|
||||
double result = y;
|
||||
if (!lock.validate(stamp)) {
|
||||
stamp = lock.readLock();
|
||||
try {
|
||||
result = y;
|
||||
} finally {
|
||||
lock.unlockRead(stamp);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double z() {
|
||||
long stamp = lock.tryOptimisticRead();
|
||||
double result = z;
|
||||
if (!lock.validate(stamp)) {
|
||||
stamp = lock.readLock();
|
||||
try {
|
||||
result = z;
|
||||
} finally {
|
||||
lock.unlockRead(stamp);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double[] getAtomicPositionArray() {
|
||||
long stamp = lock.tryOptimisticRead();
|
||||
double[] result = new double[]{x, y, z};
|
||||
if (!lock.validate(stamp)) {
|
||||
stamp = lock.readLock();
|
||||
try {
|
||||
result = new double[]{x, y, z};
|
||||
} finally {
|
||||
lock.unlockRead(stamp);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MutableLocatable setX(double x) {
|
||||
withWriteLock(() -> this.x = x);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MutableLocatable setY(double y) {
|
||||
withWriteLock(() -> this.y = y);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MutableLocatable setZ(double z) {
|
||||
withWriteLock(() -> this.z = z);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MutableLocatable setWorld(UUID world) {
|
||||
this.world = world;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MutableLocatable set(Locatable locatable) {
|
||||
double[] otherPosition = locatable.getAtomicPositionArray();
|
||||
withWriteLock(() -> {
|
||||
this.world = locatable.world(); // technically this could be racy, but the world shouldn't be changing often
|
||||
this.x = otherPosition[0];
|
||||
this.y = otherPosition[1];
|
||||
this.z = otherPosition[2];
|
||||
});
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MutableLocatable set(double x, double y, double z, UUID world) {
|
||||
withWriteLock(() -> {
|
||||
this.world = world;
|
||||
this.x = x; this.y = y; this.z = z;
|
||||
});
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean strictlyEquals(Object other) {
|
||||
if (this == other) return true;
|
||||
if (!(other instanceof ThreadSafeLocatable that)) return false;
|
||||
|
||||
long thisStamp = lock.tryOptimisticRead();
|
||||
long thatStamp = that.lock.tryOptimisticRead();
|
||||
boolean equal = this.world.equals(that.world) &&
|
||||
Double.doubleToLongBits(this.x) == Double.doubleToLongBits(that.x) &&
|
||||
Double.doubleToLongBits(this.y) == Double.doubleToLongBits(that.y) &&
|
||||
Double.doubleToLongBits(this.z) == Double.doubleToLongBits(that.z);
|
||||
if (!lock.validate(thisStamp) || !that.lock.validate(thatStamp)) {
|
||||
// If either lock was invalid, we can't trust the result, so we have to retry with locks again
|
||||
thisStamp = lock.readLock();
|
||||
thatStamp = that.lock.readLock();
|
||||
try {
|
||||
equal = this.world.equals(that.world) &&
|
||||
Double.doubleToLongBits(this.x) == Double.doubleToLongBits(that.x) &&
|
||||
Double.doubleToLongBits(this.y) == Double.doubleToLongBits(that.y) &&
|
||||
Double.doubleToLongBits(this.z) == Double.doubleToLongBits(that.z);
|
||||
} finally {
|
||||
lock.unlockRead(thisStamp);
|
||||
that.lock.unlockRead(thatStamp);
|
||||
}
|
||||
}
|
||||
return equal;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
short-git: ${short_git}
|
||||
long-git: ${long_git}
|
||||
build-time: ${build_time}
|
||||
version: ${version}
|
||||
Submodule
+1
Submodule logging added at 02939225ba.
@@ -0,0 +1,25 @@
|
||||
plugins {
|
||||
id("java")
|
||||
}
|
||||
|
||||
group = "games.cubi.raycastedantiesp.packetevents"
|
||||
version = "unspecified"
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
maven { url = uri("https://repo.codemc.io/repository/maven-releases/") }
|
||||
maven { url = uri("https://repo.codemc.io/repository/maven-snapshots/") }
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(project(":locatable-lib"))
|
||||
implementation(project(":logging"))
|
||||
implementation(project(":core"))
|
||||
|
||||
compileOnly("com.github.retrooper:packetevents-api:2.12.0")
|
||||
compileOnly("org.spongepowered:configurate-core:4.2.0")
|
||||
}
|
||||
|
||||
java {
|
||||
toolchain.languageVersion = JavaLanguageVersion.of(21)
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package games.cubi.raycastedantiesp.packetevents;
|
||||
|
||||
import org.jetbrains.annotations.Contract;
|
||||
|
||||
public interface BlockInfoResolver {
|
||||
@Contract(pure = true)
|
||||
boolean isOccluding(int blockStateID);
|
||||
@Contract(pure = true)
|
||||
boolean isTileEntity(int blockStateID);
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package games.cubi.raycastedantiesp.packetevents.config;
|
||||
|
||||
import games.cubi.raycastedantiesp.core.config.BlockProcessorConfig;
|
||||
import games.cubi.raycastedantiesp.core.config.Config;
|
||||
import games.cubi.raycastedantiesp.core.config.ConfigExtension;
|
||||
import games.cubi.raycastedantiesp.core.config.ConfigLoadException;
|
||||
import games.cubi.raycastedantiesp.core.config.ConfigReader;
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record PacketEventsBlockProcessorConfig(List<Integer> tileEntityExemptedIds, List<Integer> tileEntityForceIncludedIds) implements Config {
|
||||
public static final ConfigExtension<PacketEventsBlockProcessorConfig> EXTENSION = new ConfigExtension<>() {
|
||||
@Override
|
||||
public Class<PacketEventsBlockProcessorConfig> type() {
|
||||
return PacketEventsBlockProcessorConfig.class;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PacketEventsBlockProcessorConfig load(ConfigurationNode config, BlockProcessorConfig blockProcessorConfig) {
|
||||
ConfigurationNode node = ConfigReader.node(config, "block-processor", "packetevents");
|
||||
PacketEventsBlockProcessorConfig packetEventsConfig = new PacketEventsBlockProcessorConfig(
|
||||
ConfigReader.integerList(ConfigReader.node(node, "tile-entity-exempted-ids"), "block-processor.packetevents.tile-entity-exempted-ids"),
|
||||
ConfigReader.integerList(ConfigReader.node(node, "tile-entity-force-included-ids"), "block-processor.packetevents.tile-entity-force-included-ids")
|
||||
);
|
||||
if (!blockProcessorConfig.trackAllBlocks() && !packetEventsConfig.tileEntityForceIncludedIds().isEmpty()) {
|
||||
throw new ConfigLoadException("block-processor.packetevents.tile-entity-force-included-ids must be empty when block-processor.track-all-blocks is false");
|
||||
}
|
||||
return packetEventsConfig;
|
||||
}
|
||||
};
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package games.cubi.raycastedantiesp.packetevents.locatables;
|
||||
|
||||
import com.github.retrooper.packetevents.protocol.entity.type.EntityType;
|
||||
import games.cubi.raycastedantiesp.core.locatables.NettyEntityLocatable;
|
||||
import games.cubi.raycastedantiesp.core.players.PlayerData;
|
||||
import games.cubi.raycastedantiesp.packetevents.replaydata.PacketEventsEntityReplayData;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public class PacketEventsEntity extends NettyEntityLocatable<EntityType, PacketEventsEntityReplayData> {
|
||||
public PacketEventsEntity(PlayerData owningPlayer, UUID world, double x, double y, double z, int entityID, UUID entityUUID, boolean isSelfEntity, EntityType entityType, boolean visible) {
|
||||
super(owningPlayer,world, x, y, z, entityID, entityUUID, isSelfEntity, entityType, visible);
|
||||
}
|
||||
|
||||
private PacketEventsEntity(PlayerData selfData, int selfEntityID, UUID selfEntityUUID) {
|
||||
super(selfData, selfEntityID, selfEntityUUID);
|
||||
}
|
||||
|
||||
public static PacketEventsEntity createSelfEntity(PlayerData selfData, int selfEntityID, UUID selfEntityUUID) {
|
||||
return new PacketEventsEntity(selfData, selfEntityID, selfEntityUUID);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean strictlyEquals(Object other) {
|
||||
if (this == other) return true;
|
||||
if (!(other instanceof PacketEventsEntity that)) return false;
|
||||
if (!this.equals(other)) return false;
|
||||
|
||||
if (entityID() != that.entityID()) return false;
|
||||
if (!entityUUID().equals(that.entityUUID())) return false;
|
||||
if (isSelfEntity() != that.isSelfEntity()) return false;
|
||||
if (entityType() != that.entityType()) return false;
|
||||
if (visible() != that.visible()) return false;
|
||||
if (yaw() != that.yaw()) return false;
|
||||
if (pitch() != that.pitch()) return false;
|
||||
if (headYaw() != that.headYaw()) return false;
|
||||
if (velocityX() != that.velocityX()) return false;
|
||||
if (velocityY() != that.velocityY()) return false;
|
||||
if (velocityZ() != that.velocityZ()) return false;
|
||||
if (onGround() != that.onGround()) return false;
|
||||
return entityData() == that.entityData();
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package games.cubi.raycastedantiesp.packetevents.locatables;
|
||||
|
||||
import games.cubi.locatables.Locatable;
|
||||
import games.cubi.raycastedantiesp.core.locatables.NettyTileEntity;
|
||||
import games.cubi.raycastedantiesp.packetevents.replaydata.PacketEventsTileEntityReplayData;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public class PacketEventsTileEntity extends NettyTileEntity<PacketEventsTileEntityReplayData> {
|
||||
public PacketEventsTileEntity(Locatable location, boolean visible, int lastChecked, int blockID) {
|
||||
super(location, visible, lastChecked, blockID);
|
||||
}
|
||||
|
||||
public PacketEventsTileEntity(UUID world, int x, int y, int z, boolean visible, int blockID) {
|
||||
super(world, x, y, z, visible, blockID);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean strictlyEquals(Object other) {
|
||||
if (this == other) return true;
|
||||
if (!(other instanceof PacketEventsTileEntity that)) return false;
|
||||
if (!this.equals(that)) return false;
|
||||
return this.visible() == that.visible() &&
|
||||
this.lastChecked() == that.lastChecked() &&
|
||||
this.blockID() == that.blockID() &&
|
||||
((this.extraData() == null && that.extraData() == null) || (this.extraData() != null && this.extraData().equals(that.extraData())));
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package games.cubi.raycastedantiesp.packetevents.replaydata;
|
||||
|
||||
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
|
||||
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPlayerInfoUpdate;
|
||||
|
||||
import games.cubi.raycastedantiesp.core.utils.Clearable;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.List;
|
||||
import java.util.Queue;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
|
||||
public sealed interface PacketEventsEntityReplayData extends Clearable permits PacketEventsEntityReplayData.Impl {
|
||||
|
||||
void addPacket(PacketWrapper<?> packet);
|
||||
|
||||
/**
|
||||
* @return The actual queue, do not modify.
|
||||
*/
|
||||
Queue<PacketWrapper<?>> getPackets();
|
||||
|
||||
static PacketEventsEntityReplayData create() {
|
||||
return new Impl();
|
||||
}
|
||||
|
||||
final class Impl implements PacketEventsEntityReplayData {
|
||||
private final Queue<PacketWrapper<?>> packets = new ArrayDeque<>();
|
||||
|
||||
public Impl() {
|
||||
}
|
||||
|
||||
public void addPacket(PacketWrapper<?> packet) {
|
||||
packets.add(packet);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Queue<PacketWrapper<?>> getPackets() {
|
||||
return packets;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
packets.clear();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package games.cubi.raycastedantiesp.packetevents.replaydata;
|
||||
|
||||
import com.github.retrooper.packetevents.protocol.nbt.NBTCompound;
|
||||
import com.github.retrooper.packetevents.protocol.world.blockentity.BlockEntityType;
|
||||
import games.cubi.raycastedantiesp.core.utils.Clearable;
|
||||
|
||||
public final class PacketEventsTileEntityReplayData implements Clearable {
|
||||
private volatile BlockEntityType blockEntityType;
|
||||
private volatile NBTCompound nbt;
|
||||
|
||||
public BlockEntityType blockEntityType() {
|
||||
return blockEntityType;
|
||||
}
|
||||
|
||||
public NBTCompound nbt() {
|
||||
return nbt == null ? null : nbt.copy();
|
||||
}
|
||||
|
||||
public void setBlockEntityData(BlockEntityType blockEntityType, NBTCompound nbt) {
|
||||
this.blockEntityType = blockEntityType;
|
||||
this.nbt = nbt == null ? null : nbt.copy();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
blockEntityType = null;
|
||||
nbt = null;
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package games.cubi.raycastedantiesp.packetevents.view;
|
||||
|
||||
import games.cubi.locatables.BlockLocatable;
|
||||
import games.cubi.locatables.implementations.ImmutableBlockLocatable;
|
||||
import games.cubi.raycastedantiesp.core.view.AbstractBlockView;
|
||||
import games.cubi.raycastedantiesp.packetevents.locatables.PacketEventsTileEntity;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public class PacketEventsBlockView extends AbstractBlockView<PacketEventsTileEntity> {
|
||||
@Override
|
||||
protected PacketEventsTileEntity createTrackedTileEntity(BlockLocatable location, int blockID, boolean visible) {
|
||||
return new PacketEventsTileEntity(location, visible, 0, blockID);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected PacketEventsTileEntity createTrackedTileEntity(UUID world, int x, int y, int z, int blockID) {
|
||||
return new PacketEventsTileEntity(world, x, y, z, false, blockID);
|
||||
}
|
||||
}
|
||||
+197
@@ -0,0 +1,197 @@
|
||||
package games.cubi.raycastedantiesp.packetevents.view;
|
||||
|
||||
import games.cubi.locatables.Locatable;
|
||||
import games.cubi.logs.Logger;
|
||||
import games.cubi.raycastedantiesp.core.view.EntityView;
|
||||
import games.cubi.raycastedantiesp.core.view.EntityViewTransition;
|
||||
import games.cubi.raycastedantiesp.packetevents.locatables.PacketEventsEntity;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
|
||||
public class PacketEventsEntityView implements EntityView<PacketEventsEntity> {
|
||||
private final Map<UUID, PacketEventsEntity> entitiesByUUID = new ConcurrentHashMap<>();
|
||||
private final Map<Integer, UUID> entityUUIDsByID = new ConcurrentHashMap<>();
|
||||
private final ConcurrentLinkedQueue<EntityViewTransition> transitions = new ConcurrentLinkedQueue<>();
|
||||
private final boolean isPlayerView;
|
||||
|
||||
public PacketEventsEntityView(boolean isPlayerView) {
|
||||
this.isPlayerView = isPlayerView;
|
||||
}
|
||||
|
||||
public static PacketEventsEntityView createPlayerView() {
|
||||
return new PacketEventsEntityView(true);
|
||||
}
|
||||
|
||||
public static PacketEventsEntityView createEntityView() {
|
||||
return new PacketEventsEntityView(false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void insertEntity(PacketEventsEntity entity) {
|
||||
if (entity == null || entity.entityUUID() == null) {
|
||||
Logger.error(new RuntimeException("Attempted to insert null entity or entity with null UUID into EntityView"), 2, PacketEventsEntityView.class);
|
||||
return;
|
||||
}
|
||||
entitiesByUUID.put(entity.entityUUID(), entity);
|
||||
entityUUIDsByID.put(entity.entityID(), entity.entityUUID());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeEntity(int entityID, int currentTick) {
|
||||
UUID entityUUID = entityUUIDsByID.remove(entityID);
|
||||
if (entityUUID == null) {
|
||||
return;
|
||||
}
|
||||
PacketEventsEntity removed = entitiesByUUID.remove(entityUUID);
|
||||
if (removed == null) {
|
||||
return;
|
||||
}
|
||||
removed.clear();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeEntity(UUID entityUUID, int currentTick) {
|
||||
int entityID = getEntityID(entityUUID);
|
||||
|
||||
removeEntity(entityID, currentTick);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PacketEventsEntity getEntity(UUID entityUUID) {
|
||||
return entitiesByUUID.get(entityUUID);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PacketEventsEntity getEntity(int entityID) {
|
||||
return getTrackedEntity(entityID);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean exists(UUID entityUUID) {
|
||||
return entitiesByUUID.containsKey(entityUUID);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean exists(int entityID) {
|
||||
return entityUUIDsByID.containsKey(entityID);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isVisible(int entityID) {
|
||||
PacketEventsEntity entity = getTrackedEntity(entityID);
|
||||
assert entity != null;
|
||||
return entity.visible();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Locatable getLocation(UUID entityUUID) {
|
||||
PacketEventsEntity entity = entitiesByUUID.get(entityUUID);
|
||||
if (entity == null) {
|
||||
return null;
|
||||
}
|
||||
return entity.clonePlainAndCentreIfBlockLocation().set(entity.x(), entity.y() + 0.5, entity.z(), entity.world());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getEntityID(UUID entityUUID) {
|
||||
PacketEventsEntity entity = entitiesByUUID.get(entityUUID);
|
||||
return entity == null ? -1 : entity.entityID();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isVisible(UUID entityUUID, int currentTick) {
|
||||
return isVisible(entityUUID);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isVisible(UUID entityUUID) {
|
||||
PacketEventsEntity entity = entitiesByUUID.get(entityUUID);
|
||||
return entity == null || entity.visible();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setVisibility(UUID entityUUID, boolean visible, int currentTick) {
|
||||
PacketEventsEntity existing = entitiesByUUID.get(entityUUID);
|
||||
if (existing == null) {
|
||||
Logger.debug("EntityView.setVisibility missing uuid=" + entityUUID
|
||||
+ " requestedVisible=" + visible
|
||||
+ " tick=" + currentTick);
|
||||
return;
|
||||
}
|
||||
if (existing.isSelfEntity()) return;
|
||||
if (existing.visible() != visible) {
|
||||
transitions.add(new EntityViewTransition(
|
||||
visible ? EntityViewTransition.Type.SHOW : EntityViewTransition.Type.HIDE,
|
||||
existing.entityUUID(),
|
||||
existing.entityID()
|
||||
));
|
||||
}
|
||||
existing.setVisible(visible);
|
||||
existing.setLastChecked(currentTick);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<UUID> getKnownEntities() {
|
||||
return List.copyOf(entitiesByUUID.keySet());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<UUID> getNeedingRecheck(int recheckTicks, int currentTick) {
|
||||
List<UUID> needingRecheck = new ArrayList<>();
|
||||
for (PacketEventsEntity state : entitiesByUUID.values()) {
|
||||
if (state.visible() && (currentTick - state.lastChecked()) < recheckTicks) {
|
||||
continue;
|
||||
}
|
||||
needingRecheck.add(state.entityUUID());
|
||||
}
|
||||
return needingRecheck;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasPendingTransitions() {
|
||||
return !transitions.isEmpty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<EntityViewTransition> drainTransitions() {
|
||||
List<EntityViewTransition> drained = new ArrayList<>();
|
||||
EntityViewTransition transition;
|
||||
while ((transition = transitions.poll()) != null) {
|
||||
drained.add(transition);
|
||||
}
|
||||
return drained;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isPlayerView() {
|
||||
return isPlayerView;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
entitiesByUUID.clear();
|
||||
entityUUIDsByID.clear();
|
||||
transitions.clear();
|
||||
}
|
||||
|
||||
private PacketEventsEntity getTrackedEntity(int entityID) {
|
||||
UUID entityUUID = entityUUIDsByID.get(entityID);
|
||||
return entityUUID == null ? null : entitiesByUUID.get(entityUUID);
|
||||
}
|
||||
|
||||
public String getStringDataForDebugging() {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
builder.append("EntityView isPlayerView=").append(isPlayerView).append("\n");
|
||||
Set<Map.Entry<Integer, UUID>> entries = new HashSet<>(entityUUIDsByID.entrySet());
|
||||
for (Map.Entry<Integer, UUID> entry : entries) {
|
||||
PacketEventsEntity entity = entitiesByUUID.get(entry.getValue());
|
||||
builder.append("EntityID=").append(entry.getKey())
|
||||
.append(" UUID=").append(entry.getValue())
|
||||
.append(" Entity=").append(entity)
|
||||
.append("\n");
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package games.cubi.raycastedantiesp.packetevents.viewcontrollers;
|
||||
|
||||
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
|
||||
import games.cubi.logs.Logger;
|
||||
import games.cubi.raycastedantiesp.core.locatables.NettyEntityLocatable;
|
||||
import games.cubi.raycastedantiesp.core.players.PlayerData;
|
||||
import games.cubi.raycastedantiesp.core.utils.BaseEntitySpawnTask;
|
||||
import games.cubi.raycastedantiesp.packetevents.locatables.PacketEventsEntity;
|
||||
|
||||
final class PECacheablePacketReconciliationTask extends BaseEntitySpawnTask {
|
||||
private final PlayerData playerData;
|
||||
private final int entityID;
|
||||
private final PacketWrapper<?> packet;
|
||||
|
||||
PECacheablePacketReconciliationTask(PacketEventsEntityViewController controller, PlayerData playerData, int entityID, PacketWrapper<?> packet, int submittedTick) {
|
||||
super(submittedTick);
|
||||
this.playerData = playerData;
|
||||
this.entityID = entityID;
|
||||
this.packet = packet;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
NettyEntityLocatable<?,?> entity = playerData.entityFromID(entityID);
|
||||
if (entity == null) {
|
||||
Logger.error("Reconciliation fail: Attempted to cache packet for unknown entity, id=" + entityID + " packet=" + packet.getClass().getSimpleName() + ".", 3, this.getClass());
|
||||
return;
|
||||
}
|
||||
PacketEventsEntityViewController.get().ensureReplayData((PacketEventsEntity) entity).addPacket(packet);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "PECacheablePacketReconciliationTask{" +
|
||||
"submittedTick=" + submittedTick +
|
||||
", entityID=" + entityID +
|
||||
", packetType=" + packet.getClass().getSimpleName() +
|
||||
", playerUUID=" + playerData.getPlayerUUID() +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
+417
@@ -0,0 +1,417 @@
|
||||
package games.cubi.raycastedantiesp.packetevents.viewcontrollers;
|
||||
|
||||
import com.github.retrooper.packetevents.PacketEvents;
|
||||
import com.github.retrooper.packetevents.event.PacketListener;
|
||||
import com.github.retrooper.packetevents.event.PacketSendEvent;
|
||||
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
|
||||
import com.github.retrooper.packetevents.protocol.player.User;
|
||||
import com.github.retrooper.packetevents.protocol.world.blockentity.BlockEntityType;
|
||||
import com.github.retrooper.packetevents.protocol.world.blockentity.BlockEntityTypes;
|
||||
import com.github.retrooper.packetevents.protocol.world.chunk.BaseChunk;
|
||||
import com.github.retrooper.packetevents.protocol.world.chunk.Column;
|
||||
import com.github.retrooper.packetevents.protocol.world.chunk.TileEntity;
|
||||
import com.github.retrooper.packetevents.util.Vector3i;
|
||||
import com.github.retrooper.packetevents.wrapper.play.server.*;
|
||||
import games.cubi.locatables.BlockLocatable;
|
||||
import games.cubi.locatables.Locatable;
|
||||
import games.cubi.locatables.implementations.ImmutableBlockLocatable;
|
||||
import games.cubi.logs.Logger;
|
||||
import games.cubi.raycastedantiesp.core.config.ConfigManager;
|
||||
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.view.BlockView;
|
||||
import games.cubi.raycastedantiesp.core.view.BlockViewTransition;
|
||||
import games.cubi.raycastedantiesp.core.locatables.TileEntityLocatable;
|
||||
import games.cubi.raycastedantiesp.packetevents.BlockInfoResolver;
|
||||
import games.cubi.raycastedantiesp.packetevents.replaydata.PacketEventsTileEntityReplayData;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.function.IntSupplier;
|
||||
|
||||
import static games.cubi.raycastedantiesp.core.view.AbstractBlockView.CHUNK_SIZE;
|
||||
import static games.cubi.raycastedantiesp.core.view.AbstractBlockView.pack;
|
||||
|
||||
public abstract class PacketEventsBlockViewController implements PacketListener {
|
||||
private final BlockInfoResolver blockInfoResolver;
|
||||
private final IntSupplier currentTickSupplier;
|
||||
private final PacketEventsCommonViewController common;
|
||||
private TileEntityConfig tileEntityConfig = null;
|
||||
private int hideOnSpawnDistanceSquared = 0;
|
||||
|
||||
protected PacketEventsBlockViewController(BlockInfoResolver blockInfoResolver, IntSupplier currentTickSupplier) {
|
||||
this.blockInfoResolver = blockInfoResolver;
|
||||
this.currentTickSupplier = currentTickSupplier;
|
||||
common = PacketEventsCommonViewController.get(currentTickSupplier);
|
||||
}
|
||||
|
||||
protected abstract UUID resolveWorldUUID(User user);
|
||||
|
||||
protected abstract int getHiddenBlockId(int blockY);
|
||||
|
||||
public void removeViewer(UUID viewerUUID) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPacketSend(PacketSendEvent event) {
|
||||
UUID viewerUUID = event.getUser().getUUID();
|
||||
if (viewerUUID == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!(ConfigManager.get().getTileEntityConfig() == tileEntityConfig)) {
|
||||
tileEntityConfig = ConfigManager.get().getTileEntityConfig();
|
||||
hideOnSpawnDistanceSquared = tileEntityConfig.hideOnSpawnDistance() * tileEntityConfig.hideOnSpawnDistance();
|
||||
}
|
||||
|
||||
PlayerData playerData = PlayerRegistry.getInstance().getPlayerData(viewerUUID);
|
||||
if (playerData == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
Locatable ownLocation = playerData.ownLocation();
|
||||
UUID world = ownLocation != null ? ownLocation.world() : resolveWorldUUID(event.getUser());
|
||||
int currentTick = currentTickSupplier.getAsInt();
|
||||
|
||||
handleBlockPackets(event, event.getUser(), playerData, world, currentTick);
|
||||
|
||||
if (playerData.blockView().hasPendingTransitions()) {
|
||||
processTileEntityTransitions(event.getUser(), playerData.blockView());
|
||||
}
|
||||
//event.getUser().flushPackets();
|
||||
}
|
||||
|
||||
private void handleBlockPackets(PacketSendEvent event, User viewer, PlayerData playerData, UUID world, int currentTick) {
|
||||
if (world == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
BlockView blockView = playerData.blockView();
|
||||
|
||||
if (event.getPacketType() == PacketType.Play.Server.UNLOAD_CHUNK) {
|
||||
WrapperPlayServerUnloadChunk packet = new WrapperPlayServerUnloadChunk(event);
|
||||
removeChunk(packet, blockView, world);
|
||||
} else if (event.getPacketType() == PacketType.Play.Server.BLOCK_CHANGE) {
|
||||
WrapperPlayServerBlockChange packet = new WrapperPlayServerBlockChange(event);
|
||||
handleSingleBlockChange(event, viewer, playerData, world, packet, currentTick);
|
||||
} else if (event.getPacketType() == PacketType.Play.Server.MULTI_BLOCK_CHANGE) {
|
||||
WrapperPlayServerMultiBlockChange packet = new WrapperPlayServerMultiBlockChange(event);
|
||||
handleMultiBlockChange(event, blockView, world, packet, playerData.ownLocation(), currentTick);
|
||||
} else if (event.getPacketType() == PacketType.Play.Server.BLOCK_ENTITY_DATA) {
|
||||
WrapperPlayServerBlockEntityData packet = new WrapperPlayServerBlockEntityData(event);
|
||||
ImmutableBlockLocatable location = new ImmutableBlockLocatable(world, packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ());
|
||||
TileEntityLocatable<PacketEventsTileEntityReplayData> tileEntity = getTrackedTileEntity(blockView, location);
|
||||
if (tileEntity == null) {
|
||||
Logger.warning("Received standalone block entity data for an uncached tile entity. Location: " + location.world() + " " + location.blockX() + "," + location.blockY() + "," + location.blockZ(), 3, PacketEventsBlockViewController.class);
|
||||
return;
|
||||
}
|
||||
ensureTileReplayData(tileEntity).setBlockEntityData(packet.getBlockEntityType(), packet.getNBT());
|
||||
if (!blockView.isVisible(location, currentTick)) {
|
||||
event.setCancelled(true);
|
||||
sendHiddenBlock(viewer, location);
|
||||
}
|
||||
} else if (event.getPacketType() == PacketType.Play.Server.CHUNK_DATA) {
|
||||
WrapperPlayServerChunkData packet = new WrapperPlayServerChunkData(event);
|
||||
Column column = ingestChunkAndSetTileEntitiesToHiddenBlocks(
|
||||
playerData,
|
||||
world,
|
||||
packet.getColumn().getX(),
|
||||
packet.getColumn().getZ(),
|
||||
packet.getColumn(),
|
||||
event.getUser().getMinWorldHeight() >> 4,
|
||||
event
|
||||
);
|
||||
Column tileEntitiesRemoved;
|
||||
if (column.hasBiomeData()) {
|
||||
int[] biomeInts = column.getBiomeDataInts();
|
||||
byte[] biomeBytes = column.getBiomeDataBytes();
|
||||
if (biomeInts.length >= biomeBytes.length) {
|
||||
tileEntitiesRemoved = new Column(column.getX(), column.getZ(), column.isFullChunk(), column.getChunks(), new TileEntity[0], column.getHeightMaps(), biomeInts);
|
||||
}
|
||||
else {
|
||||
tileEntitiesRemoved = new Column(column.getX(), column.getZ(), column.isFullChunk(), column.getChunks(), new TileEntity[0], column.getHeightMaps(), biomeBytes);
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (common.v_1_21_5_orAbove) tileEntitiesRemoved = new Column(column.getX(), column.getZ(), column.isFullChunk(), column.getChunks(), new TileEntity[0], column.getHeightmaps());
|
||||
else tileEntitiesRemoved = new Column(column.getX(), column.getZ(), column.isFullChunk(), column.getChunks(), new TileEntity[0], column.getHeightMaps());
|
||||
}
|
||||
packet.setColumn(tileEntitiesRemoved);
|
||||
event.markForReEncode(true);
|
||||
|
||||
} else if (event.getPacketType() == PacketType.Play.Server.MAP_CHUNK_BULK) {
|
||||
WrapperPlayServerChunkDataBulk packet = new WrapperPlayServerChunkDataBulk(event);
|
||||
throw new RuntimeException("I didn't think this packet existed. Please report this to the developer with details on how to reproduce it so it can be implemented");
|
||||
}
|
||||
}
|
||||
|
||||
private void removeChunk(WrapperPlayServerUnloadChunk packet, BlockView blockView, UUID world) {
|
||||
blockView.removeChunk(world, packet.getChunkX(), packet.getChunkZ());
|
||||
removeChunkTileEntities(blockView, world, packet.getChunkX(), packet.getChunkZ());
|
||||
}
|
||||
|
||||
private void handleMultiBlockChange(PacketSendEvent event, BlockView blockView, UUID world, WrapperPlayServerMultiBlockChange packet, Locatable playerLocation, int currentTick) {
|
||||
for (WrapperPlayServerMultiBlockChange.EncodedBlock change : packet.getBlocks()) {
|
||||
int blockID = change.getBlockId();
|
||||
boolean occluding = blockID != 0 && blockInfoResolver.isOccluding(blockID);
|
||||
boolean tileEntity = blockInfoResolver.isTileEntity(blockID);
|
||||
blockView.upsertBlock(world, change.getX(), change.getY(), change.getZ(), occluding);
|
||||
ImmutableBlockLocatable location = new ImmutableBlockLocatable(world, change.getX(), change.getY(), change.getZ());
|
||||
if (tileEntity) {
|
||||
TileEntityLocatable<?> existing = blockView.getTrackedTileEntity(location);
|
||||
boolean visibleIfNew = false;
|
||||
if (existing == null) {
|
||||
double distanceSquared = location.distanceSquared(playerLocation);
|
||||
visibleIfNew = (distanceSquared <= hideOnSpawnDistanceSquared) && tileEntityConfig.enabled();
|
||||
}
|
||||
blockView.updateOrInsertTileEntity(location, blockID, visibleIfNew);
|
||||
if (!blockView.isVisible(location, currentTick)) {
|
||||
change.setBlockId(getHiddenBlockId(location.blockY()));
|
||||
event.markForReEncode(true);
|
||||
}
|
||||
} else {
|
||||
blockView.removeTileEntity(location);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void processTileEntityTransitions(User viewer, BlockView blockView) {
|
||||
for (BlockViewTransition transition : blockView.drainTransitions()) {
|
||||
BlockLocatable location = transition.location();
|
||||
TileEntityLocatable<PacketEventsTileEntityReplayData> state = getTrackedTileEntity(blockView, location);
|
||||
|
||||
switch (transition.type()) {
|
||||
case HIDE -> viewer.writePacketSilently(new WrapperPlayServerBlockChange(
|
||||
new Vector3i(location.blockX(), location.blockY(), location.blockZ()),
|
||||
getHiddenBlockId(location.blockY())
|
||||
));
|
||||
case SHOW -> {
|
||||
if (state == null || state.blockID() == 0) {
|
||||
continue;
|
||||
}
|
||||
viewer.writePacketSilently(new WrapperPlayServerBlockChange(
|
||||
new Vector3i(location.blockX(), location.blockY(), location.blockZ()),
|
||||
state.blockID()
|
||||
));
|
||||
PacketEventsTileEntityReplayData replayData = ensureTileReplayData(state);
|
||||
if (replayData.blockEntityType() != null && replayData.nbt() != null) {
|
||||
viewer.writePacketSilently(buildBlockEntityDataPacket(location, replayData));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void handleSingleBlockChange(PacketSendEvent event, User viewer, PlayerData playerData, UUID world, WrapperPlayServerBlockChange packet, int currentTick) {
|
||||
int blockID = packet.getBlockId();
|
||||
boolean occluding = blockID != 0 && blockInfoResolver.isOccluding(blockID);
|
||||
boolean tileEntity = blockInfoResolver.isTileEntity(blockID);
|
||||
Vector3i position = packet.getBlockPosition();
|
||||
ImmutableBlockLocatable location = new ImmutableBlockLocatable(world, position.getX(), position.getY(), position.getZ());
|
||||
|
||||
playerData.blockView().upsertBlock(world, position.getX(), position.getY(), position.getZ(), occluding);
|
||||
if (tileEntity) {
|
||||
TileEntityLocatable<?> existing = playerData.blockView().getTrackedTileEntity(location);
|
||||
boolean visibleIfNew = false;
|
||||
if (existing == null) {
|
||||
double distanceSquared = location.distanceSquared(playerData.ownLocation());
|
||||
visibleIfNew = (distanceSquared <= hideOnSpawnDistanceSquared) && tileEntityConfig.enabled();
|
||||
}
|
||||
playerData.blockView().updateOrInsertTileEntity(location, blockID, visibleIfNew);
|
||||
if (!playerData.blockView().isVisible(location, currentTick)) {
|
||||
event.setCancelled(true);
|
||||
sendHiddenBlock(viewer, location);
|
||||
}
|
||||
} else {
|
||||
playerData.blockView().removeTileEntity(location);
|
||||
}
|
||||
}
|
||||
|
||||
private Column ingestChunkAndSetTileEntitiesToHiddenBlocks(
|
||||
PlayerData playerData,
|
||||
UUID worldID,
|
||||
int chunkX,
|
||||
int chunkZ,
|
||||
Column column,
|
||||
int minimumChunkSectionY,
|
||||
PacketSendEvent event
|
||||
) {
|
||||
Map<Integer, BitSet> occludingBySectionY = new HashMap<>();
|
||||
Map<Integer, Set<ImmutableBlockLocatable>> tileEntitiesBySectionY = new HashMap<>();
|
||||
BlockView blockView = playerData.blockView();
|
||||
|
||||
BaseChunk[] sections = column.getChunks();
|
||||
TileEntity[] chunkTileEntitiesData = column.getTileEntities();
|
||||
|
||||
for (int sectionIndex = 0; sectionIndex < sections.length; sectionIndex++) {
|
||||
BaseChunk section = sections[sectionIndex];
|
||||
if (section == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
int sectionY = minimumChunkSectionY + sectionIndex;
|
||||
BitSet occluding = null;
|
||||
Set<ImmutableBlockLocatable> tileEntities = tileEntitiesBySectionY.computeIfAbsent(sectionY, ignored -> new HashSet<>());
|
||||
|
||||
boolean chunkSectionHasOccluding = false;
|
||||
|
||||
for (int localX = 0; localX < 16; localX++) {
|
||||
for (int localY = 0; localY < 16; localY++) {
|
||||
for (int localZ = 0; localZ < 16; localZ++) {
|
||||
int blockID = section.getBlockId(localX, localY, localZ);
|
||||
if (blockID == 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
int blockX = (chunkX << 4) + localX;
|
||||
int blockY = (sectionY << 4) + localY;
|
||||
int blockZ = (chunkZ << 4) + localZ;
|
||||
|
||||
if (blockInfoResolver.isOccluding(blockID)) {
|
||||
if (occluding == null) {
|
||||
occluding = new BitSet(CHUNK_SIZE * CHUNK_SIZE * CHUNK_SIZE);
|
||||
}
|
||||
occluding.set(pack(localX, localY, localZ));
|
||||
chunkSectionHasOccluding = true;
|
||||
}
|
||||
if (blockInfoResolver.isTileEntity(blockID)) {
|
||||
ImmutableBlockLocatable location = new ImmutableBlockLocatable(worldID, blockX, blockY, blockZ);
|
||||
tileEntities.add(location);
|
||||
blockView.updateOrInsertTileEntity(location, blockID, false);
|
||||
section.set(localX, localY, localZ, getHiddenBlockId(blockY));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (chunkSectionHasOccluding) {
|
||||
// skip empty sections to save memory
|
||||
occludingBySectionY.put(sectionY, occluding);
|
||||
}
|
||||
}
|
||||
|
||||
if (chunkTileEntitiesData != null) {
|
||||
for (TileEntity tileEntity : chunkTileEntitiesData) {
|
||||
int blockX = (chunkX << 4) + tileEntity.getX();
|
||||
int blockY = tileEntity.getY();
|
||||
int blockZ = (chunkZ << 4) + tileEntity.getZ();
|
||||
int sectionY = blockY >> 4;
|
||||
ImmutableBlockLocatable location = new ImmutableBlockLocatable(worldID, blockX, blockY, blockZ);
|
||||
tileEntitiesBySectionY.computeIfAbsent(sectionY, ignored -> new HashSet<>()).add(location);
|
||||
|
||||
TileEntityLocatable<PacketEventsTileEntityReplayData> state = getTrackedTileEntity(blockView, location);
|
||||
|
||||
if (state == null) {
|
||||
Logger.warning("Received block entity data for a tile entity that wasn't in the chunk's tile entity list. Location: " + location.world() + " " + location.blockX() + "," + location.blockY() + "," + location.blockZ(), 3, PacketEventsBlockViewController.class);
|
||||
int sectionIndex = sectionY - minimumChunkSectionY;
|
||||
if (sectionIndex < 0 || sectionIndex >= sections.length) {
|
||||
Logger.warning("Skipping uncached chunk block entity with out-of-bounds section index. Location: " + location.world() + " " + location.blockX() + "," + location.blockY() + "," + location.blockZ(), 3, PacketEventsBlockViewController.class);
|
||||
continue;
|
||||
}
|
||||
|
||||
BaseChunk sourceSection = sections[sectionIndex];
|
||||
if (sourceSection == null) {
|
||||
Logger.warning("Skipping uncached chunk block entity because its section data is missing. Location: " + location.world() + " " + location.blockX() + "," + location.blockY() + "," + location.blockZ(), 3, PacketEventsBlockViewController.class);
|
||||
continue;
|
||||
}
|
||||
|
||||
int blockID = sourceSection.getBlockId(tileEntity.getX(), blockY & 15, tileEntity.getZ());
|
||||
if (blockID <= 0) {
|
||||
Logger.warning("Skipping uncached chunk block entity because the recovered block state was air or invalid (" + blockID + "). Location: " + location.world() + " " + location.blockX() + "," + location.blockY() + "," + location.blockZ(), 3, PacketEventsBlockViewController.class);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!blockInfoResolver.isTileEntity(blockID)) {
|
||||
Logger.warning("Recovered uncached chunk block entity from chunk sections with a non-tile-entity block state ID (" + blockID + "). Location: " + location.world() + " " + location.blockX() + "," + location.blockY() + "," + location.blockZ(), 3, PacketEventsBlockViewController.class);
|
||||
}
|
||||
|
||||
blockView.updateOrInsertTileEntity(location, blockID, false);
|
||||
state = getTrackedTileEntity(blockView, location);
|
||||
if (state == null) {
|
||||
Logger.warning("Skipping uncached chunk block entity because caching recovery failed. Location: " + location.world() + " " + location.blockX() + "," + location.blockY() + "," + location.blockZ(), 3, PacketEventsBlockViewController.class);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
ensureTileReplayData(state).setBlockEntityData(packetTileEntityType(tileEntity), tileEntity.getNBT());
|
||||
}
|
||||
}
|
||||
|
||||
Set<Integer> sectionYs = new HashSet<>(tileEntitiesBySectionY.keySet());
|
||||
sectionYs.addAll(occludingBySectionY.keySet());
|
||||
for (int sectionY : sectionYs) {
|
||||
BitSet occluding = occludingBySectionY.get(sectionY);
|
||||
if (occluding != null) {
|
||||
blockView.replaceChunkSection(worldID, chunkX, sectionY, chunkZ, occluding);
|
||||
}
|
||||
else {
|
||||
blockView.removeChunkSection(worldID, chunkX, sectionY, chunkZ);
|
||||
}
|
||||
}
|
||||
|
||||
return column;
|
||||
}
|
||||
|
||||
private void removeChunkTileEntities(BlockView blockView, UUID worldID, int chunkX, int chunkZ) {
|
||||
for (BlockLocatable known : blockView.getKnownTileEntities()) {
|
||||
if (!sameChunk(known, worldID, chunkX, chunkZ)) {
|
||||
continue;
|
||||
}
|
||||
blockView.removeTileEntity(known);
|
||||
}
|
||||
}
|
||||
|
||||
private void sendHiddenBlock(User viewer, BlockLocatable location) {
|
||||
viewer.writePacketSilently(new WrapperPlayServerBlockChange(
|
||||
new Vector3i(location.blockX(), location.blockY(), location.blockZ()),
|
||||
getHiddenBlockId(location.blockY())
|
||||
));
|
||||
}
|
||||
|
||||
private boolean sameChunk(BlockLocatable location, UUID worldID, int chunkX, int chunkZ) {
|
||||
return location.world().equals(worldID) && location.chunkX() == chunkX && location.chunkZ() == chunkZ;
|
||||
}
|
||||
|
||||
private boolean sameChunkSection(BlockLocatable location, UUID worldID, int chunkX, int chunkY, int chunkZ) {
|
||||
return sameChunk(location, worldID, chunkX, chunkZ) && location.chunkY() == chunkY;
|
||||
}
|
||||
|
||||
private WrapperPlayServerBlockEntityData copyBlockEntityDataPacket(WrapperPlayServerBlockEntityData packet) {
|
||||
return new WrapperPlayServerBlockEntityData(
|
||||
copyBlockVector(packet.getPosition()),
|
||||
packet.getBlockEntityType(),
|
||||
packet.getNBT()
|
||||
);
|
||||
}
|
||||
|
||||
private WrapperPlayServerBlockEntityData buildBlockEntityDataPacket(BlockLocatable location, PacketEventsTileEntityReplayData replayData) {
|
||||
return new WrapperPlayServerBlockEntityData(
|
||||
new Vector3i(location.blockX(), location.blockY(), location.blockZ()),
|
||||
replayData.blockEntityType(),
|
||||
replayData.nbt()
|
||||
);
|
||||
}
|
||||
|
||||
private BlockEntityType packetTileEntityType(TileEntity tileEntity) {
|
||||
return BlockEntityTypes.getById(
|
||||
PacketEvents.getAPI().getServerManager().getVersion().toClientVersion(),
|
||||
tileEntity.getType()
|
||||
);
|
||||
}
|
||||
|
||||
private Vector3i copyBlockVector(Vector3i vector) {
|
||||
return new Vector3i(vector.getX(), vector.getY(), vector.getZ());
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private TileEntityLocatable<PacketEventsTileEntityReplayData> getTrackedTileEntity(BlockView blockView, BlockLocatable location) {
|
||||
return (TileEntityLocatable<PacketEventsTileEntityReplayData>) blockView.getTrackedTileEntity(location);
|
||||
}
|
||||
|
||||
private PacketEventsTileEntityReplayData ensureTileReplayData(TileEntityLocatable<PacketEventsTileEntityReplayData> tileEntity) {
|
||||
PacketEventsTileEntityReplayData replayData = tileEntity.extraData();
|
||||
if (replayData == null) {
|
||||
replayData = new PacketEventsTileEntityReplayData();
|
||||
tileEntity.setExtraData(replayData);
|
||||
}
|
||||
return replayData;
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package games.cubi.raycastedantiesp.packetevents.viewcontrollers;
|
||||
|
||||
import com.github.retrooper.packetevents.PacketEvents;
|
||||
import com.github.retrooper.packetevents.manager.server.ServerVersion;
|
||||
import com.github.retrooper.packetevents.protocol.player.User;
|
||||
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
|
||||
|
||||
import java.util.function.IntSupplier;
|
||||
|
||||
public class PacketEventsCommonViewController {
|
||||
private static PacketEventsCommonViewController INSTANCE;
|
||||
private final IntSupplier currentTickSupplier;
|
||||
public final boolean v_1_21_5_orAbove = PacketEvents.getAPI().getServerManager().getVersion().isNewerThanOrEquals(ServerVersion.V_1_21_5);
|
||||
|
||||
private PacketEventsCommonViewController(IntSupplier currentTick) {
|
||||
this.currentTickSupplier = currentTick;
|
||||
}
|
||||
|
||||
public static PacketEventsCommonViewController get(IntSupplier currentTick) {
|
||||
if (INSTANCE == null) {
|
||||
INSTANCE = new PacketEventsCommonViewController(currentTick);
|
||||
}
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
public void writeIfPresent(User viewer, PacketWrapper<?> packet) {
|
||||
if (viewer == null || packet == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
viewer.writePacketSilently(packet);
|
||||
}
|
||||
}
|
||||
+662
@@ -0,0 +1,662 @@
|
||||
package games.cubi.raycastedantiesp.packetevents.viewcontrollers;
|
||||
|
||||
import com.github.retrooper.packetevents.PacketEvents;
|
||||
import com.github.retrooper.packetevents.event.PacketListener;
|
||||
import com.github.retrooper.packetevents.event.PacketSendEvent;
|
||||
import com.github.retrooper.packetevents.protocol.entity.data.EntityData;
|
||||
import com.github.retrooper.packetevents.protocol.entity.type.EntityType;
|
||||
import com.github.retrooper.packetevents.protocol.entity.type.EntityTypes;
|
||||
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
|
||||
import com.github.retrooper.packetevents.protocol.player.Equipment;
|
||||
import com.github.retrooper.packetevents.protocol.player.User;
|
||||
import com.github.retrooper.packetevents.protocol.teleport.RelativeFlag;
|
||||
import com.github.retrooper.packetevents.util.Vector3d;
|
||||
import com.github.retrooper.packetevents.wrapper.PacketWrapper;
|
||||
import com.github.retrooper.packetevents.wrapper.play.server.*;
|
||||
import games.cubi.raycastedantiesp.core.config.ConfigManager;
|
||||
import games.cubi.locatables.Locatable;
|
||||
import games.cubi.logs.Logger;
|
||||
import games.cubi.raycastedantiesp.core.locatables.NettyEntityLocatable;
|
||||
import games.cubi.raycastedantiesp.core.players.PlayerData;
|
||||
import games.cubi.raycastedantiesp.core.players.PlayerRegistry;
|
||||
import games.cubi.raycastedantiesp.core.utils.IntArrayList;
|
||||
import games.cubi.raycastedantiesp.core.view.EntityView;
|
||||
import games.cubi.raycastedantiesp.core.view.EntityViewTransition;
|
||||
import games.cubi.raycastedantiesp.core.view.controller.PacketEntityViewController;
|
||||
import games.cubi.raycastedantiesp.packetevents.locatables.PacketEventsEntity;
|
||||
import games.cubi.raycastedantiesp.packetevents.replaydata.PacketEventsEntityReplayData;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.function.IntSupplier;
|
||||
|
||||
import static games.cubi.raycastedantiesp.core.locatables.NettyEntityLocatable.NO_LEASHER;
|
||||
import static games.cubi.raycastedantiesp.core.locatables.NettyEntityLocatable.NO_VEHICLE;
|
||||
|
||||
public abstract class PacketEventsEntityViewController extends PacketEntityViewController<PacketWrapper<?>> implements PacketListener {
|
||||
private final IntSupplier CURRENT_TICK_SUPPLIER;
|
||||
private final PacketEventsCommonViewController COMMON;
|
||||
private static PacketEventsEntityViewController SELF; //TODO Switch to LazyConstant once out of preview (see https://openjdk.org/jeps/526)
|
||||
|
||||
public static PacketEventsEntityViewController get() {
|
||||
if (SELF == null) {
|
||||
SELF = (PacketEventsEntityViewController) PacketEntityViewController.get();
|
||||
}
|
||||
return SELF;
|
||||
}
|
||||
|
||||
protected PacketEventsEntityViewController(IntSupplier currentTickSupplier) {
|
||||
this.CURRENT_TICK_SUPPLIER = currentTickSupplier;
|
||||
COMMON = PacketEventsCommonViewController.get(currentTickSupplier);
|
||||
}
|
||||
|
||||
protected abstract UUID resolveWorldUUID(User user);
|
||||
|
||||
public void removeViewer(UUID viewerUUID) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPacketSend(PacketSendEvent event) {
|
||||
UUID viewerUUID = event.getUser().getUUID();
|
||||
if (viewerUUID == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
PlayerData playerData = PlayerRegistry.getInstance().getPlayerData(viewerUUID);
|
||||
|
||||
if (event.getPacketType() == PacketType.Login.Server.LOGIN_SUCCESS) {
|
||||
handleLoginPhaseLoginPacket(viewerUUID, CURRENT_TICK_SUPPLIER.getAsInt());
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.getPacketType() == PacketType.Play.Server.JOIN_GAME) {
|
||||
WrapperPlayServerJoinGame packet = new WrapperPlayServerJoinGame(event);
|
||||
handlePlayPhaseLoginPacket(packet.getEntityId(), viewerUUID, CURRENT_TICK_SUPPLIER.getAsInt());
|
||||
}
|
||||
|
||||
if (playerData == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (ConfigManager.get().getEntityConfig() != entityConfig) {
|
||||
entityConfig = ConfigManager.get().getEntityConfig();
|
||||
hideOnSpawnEntityDistanceSquared = entityConfig.hideOnSpawnDistance() * entityConfig.hideOnSpawnDistance();
|
||||
}
|
||||
|
||||
if (ConfigManager.get().getPlayerConfig() != playerConfig) {
|
||||
playerConfig = ConfigManager.get().getPlayerConfig();
|
||||
hideOnSpawnPlayerDistanceSquared = playerConfig.hideOnSpawnDistance() * playerConfig.hideOnSpawnDistance();
|
||||
}
|
||||
|
||||
Locatable ownLocation = playerData.ownLocation();
|
||||
UUID world = ownLocation != null ? ownLocation.world() : resolveWorldUUID(event.getUser());
|
||||
int currentTick = CURRENT_TICK_SUPPLIER.getAsInt();
|
||||
|
||||
handleEntityPackets(event, event.getUser(), playerData, world, currentTick);
|
||||
|
||||
if (playerData.entityView().hasPendingTransitions()) {
|
||||
processEntityTransitions(viewerUUID, event.getUser(), cast(playerData.entityView()));
|
||||
}
|
||||
|
||||
if (playerData.playerView().hasPendingTransitions()) {
|
||||
processEntityTransitions(viewerUUID, event.getUser(), cast(playerData.playerView()));
|
||||
}
|
||||
|
||||
//event.getUser().flushPackets();
|
||||
playerData.nettyData().evictPendingPostSpawnTasksIfRequired(currentTick);
|
||||
}
|
||||
|
||||
private void handleEntityPackets(PacketSendEvent event, User viewer, PlayerData playerData, UUID world, int currentTick) {
|
||||
//code readability helper constant
|
||||
final boolean REQUIRE_EVENT_CANCELLATION = true;
|
||||
switch (event.getPacketType()) {
|
||||
case PacketType.Play.Server.SPAWN_LIVING_ENTITY -> {
|
||||
Logger.error("Received spawn living entity packet. This packet type should not be used in modern Minecraft versions, and its presence likely indicates a protocol mapping issue. Viewer=" + viewer.getUUID() + " tick=" + currentTick, 2, PacketEventsEntityViewController.class);
|
||||
throw new RuntimeException("Spawn Living Entity packet appeared. This shouldn't exist");
|
||||
//if (handleLivingEntitySpawn(new WrapperPlayServerSpawnLivingEntity(event), playerData, world, currentTick) == REQUIRE_EVENT_CANCELLATION)
|
||||
// event.setCancelled(true);
|
||||
}
|
||||
case PacketType.Play.Server.SPAWN_ENTITY -> {
|
||||
WrapperPlayServerSpawnEntity packet = new WrapperPlayServerSpawnEntity(event);
|
||||
Logger.debug("Spawning entity for player " + viewer.getUUID() + " entity #" + packet.getEntityId() + " tick=" + currentTick + " type=" + packet.getEntityType().getName());
|
||||
if (handleEntitySpawn(packet, packet.getEntityId(), packet.getEntityType().isInstanceOf(EntityTypes.PLAYER), playerData, world, currentTick) == REQUIRE_EVENT_CANCELLATION)
|
||||
event.setCancelled(true);
|
||||
}
|
||||
case PacketType.Play.Server.ENTITY_ANIMATION -> {
|
||||
if (handleEntityAnimation(new WrapperPlayServerEntityAnimation(event).getEntityId(), playerData) == REQUIRE_EVENT_CANCELLATION)
|
||||
event.setCancelled(true);
|
||||
}
|
||||
case PacketType.Play.Server.ENTITY_STATUS -> {
|
||||
if (handleEntityEvent(new WrapperPlayServerEntityStatus(event).getEntityId(), playerData) == REQUIRE_EVENT_CANCELLATION)
|
||||
event.setCancelled(true);
|
||||
}
|
||||
case PacketType.Play.Server.HURT_ANIMATION -> {
|
||||
if (handleHurtAnimation(new WrapperPlayServerHurtAnimation(event).getEntityId(), playerData) == REQUIRE_EVENT_CANCELLATION)
|
||||
event.setCancelled(true);
|
||||
}
|
||||
case PacketType.Play.Server.SPAWN_PAINTING -> {
|
||||
throw new RuntimeException("Spawn Painting packet appeared. This shouldn't exist");
|
||||
//if (handlePaintingSpawn(new WrapperPlayServerSpawnPainting(event), playerData, world, currentTick) == REQUIRE_EVENT_CANCELLATION)
|
||||
// event.setCancelled(true);
|
||||
}
|
||||
case PacketType.Play.Server.SPAWN_PLAYER -> {
|
||||
Logger.error("Received spawn player entity packet. This packet type should not be used in modern Minecraft versions, and its presence likely indicates a protocol mapping issue. Viewer=" + viewer.getUUID() + " tick=" + currentTick, 2, PacketEventsEntityViewController.class);
|
||||
throw new RuntimeException("Spawn Player packet appeared. This shouldn't exist");
|
||||
//if (handlePlayerSpawn(new WrapperPlayServerSpawnPlayer(event), playerData, world, currentTick) == REQUIRE_EVENT_CANCELLATION)
|
||||
// event.setCancelled(true);
|
||||
}
|
||||
case PacketType.Play.Server.ENTITY_RELATIVE_MOVE -> {
|
||||
if (handleRelativeMove(new WrapperPlayServerEntityRelativeMove(event), playerData, currentTick) == REQUIRE_EVENT_CANCELLATION)
|
||||
event.setCancelled(true);
|
||||
}
|
||||
case PacketType.Play.Server.ENTITY_RELATIVE_MOVE_AND_ROTATION -> {
|
||||
if (handleRelativeMoveAndRotation(new WrapperPlayServerEntityRelativeMoveAndRotation(event), playerData, currentTick) == REQUIRE_EVENT_CANCELLATION)
|
||||
event.setCancelled(true);
|
||||
}
|
||||
case PacketType.Play.Server.ENTITY_TELEPORT -> {
|
||||
if (handleTeleport(new WrapperPlayServerEntityTeleport(event), playerData, currentTick) == REQUIRE_EVENT_CANCELLATION)
|
||||
event.setCancelled(true);
|
||||
}
|
||||
case PacketType.Play.Server.ENTITY_POSITION_SYNC -> {
|
||||
if (handlePositionSync(new WrapperPlayServerEntityPositionSync(event), playerData, currentTick) == REQUIRE_EVENT_CANCELLATION)
|
||||
event.setCancelled(true);
|
||||
}
|
||||
case PacketType.Play.Server.ENTITY_ROTATION -> {
|
||||
if (handleEntityRotation(new WrapperPlayServerEntityRotation(event), playerData, currentTick) == REQUIRE_EVENT_CANCELLATION)
|
||||
event.setCancelled(true);
|
||||
}
|
||||
case PacketType.Play.Server.ENTITY_HEAD_LOOK -> {
|
||||
if (handleEntityHeadLook(new WrapperPlayServerEntityHeadLook(event), playerData, currentTick) == REQUIRE_EVENT_CANCELLATION)
|
||||
event.setCancelled(true);
|
||||
}
|
||||
case PacketType.Play.Server.ENTITY_METADATA -> {
|
||||
WrapperPlayServerEntityMetadata packet = new WrapperPlayServerEntityMetadata(event);
|
||||
if (handleEntityMetadata(packet, packet.getEntityId(), playerData, currentTick) == REQUIRE_EVENT_CANCELLATION)
|
||||
event.setCancelled(true);
|
||||
}
|
||||
case PacketType.Play.Server.REMOVE_ENTITY_EFFECT -> {
|
||||
WrapperPlayServerRemoveEntityEffect packet = new WrapperPlayServerRemoveEntityEffect(event);
|
||||
if (handleRemoveEntityEffect(packet, packet.getEntityId(), playerData, currentTick) == REQUIRE_EVENT_CANCELLATION)
|
||||
event.setCancelled(true);
|
||||
}
|
||||
case PacketType.Play.Server.ENTITY_EQUIPMENT -> {
|
||||
WrapperPlayServerEntityEquipment packet = new WrapperPlayServerEntityEquipment(event);
|
||||
if (handleEntityEquipment(packet, packet.getEntityId(), playerData, currentTick) == REQUIRE_EVENT_CANCELLATION)
|
||||
event.setCancelled(true);
|
||||
}
|
||||
case PacketType.Play.Server.ENTITY_VELOCITY -> {
|
||||
WrapperPlayServerEntityVelocity packet = new WrapperPlayServerEntityVelocity(event);
|
||||
if (handleEntityVelocity(packet, packet.getEntityId(), playerData, currentTick) == REQUIRE_EVENT_CANCELLATION)
|
||||
event.setCancelled(true);
|
||||
}
|
||||
case PacketType.Play.Server.ENTITY_EFFECT -> {
|
||||
WrapperPlayServerEntityEffect packet = new WrapperPlayServerEntityEffect(event);
|
||||
if (handleEntityEffect(packet, packet.getEntityId(), playerData, currentTick) == REQUIRE_EVENT_CANCELLATION)
|
||||
event.setCancelled(true);
|
||||
}
|
||||
case PacketType.Play.Server.SET_PASSENGERS -> {
|
||||
WrapperPlayServerSetPassengers packet = new WrapperPlayServerSetPassengers(event);
|
||||
if (handleEntityPassengers(packet.getEntityId(), packet.getPassengers(), playerData, currentTick) == REQUIRE_EVENT_CANCELLATION)
|
||||
event.setCancelled(true);
|
||||
}
|
||||
case PacketType.Play.Server.DESTROY_ENTITIES -> {
|
||||
handleDestroyEntities(new WrapperPlayServerDestroyEntities(event).getEntityIds(), playerData, currentTick);
|
||||
}
|
||||
case PacketType.Play.Server.UPDATE_ATTRIBUTES -> {
|
||||
WrapperPlayServerUpdateAttributes wrapper = new WrapperPlayServerUpdateAttributes(event);
|
||||
if (handleAttributeUpdate(wrapper, wrapper.getEntityId(), playerData, currentTick) == REQUIRE_EVENT_CANCELLATION)
|
||||
event.setCancelled(true);
|
||||
}
|
||||
case PacketType.Play.Server.ATTACH_ENTITY -> {
|
||||
WrapperPlayServerAttachEntity wrapper = new WrapperPlayServerAttachEntity(event);
|
||||
if (handleLeashEntity(wrapper.getAttachedId(), wrapper.getHoldingId(), playerData, currentTick) == REQUIRE_EVENT_CANCELLATION)
|
||||
event.setCancelled(true);
|
||||
}
|
||||
default -> {}
|
||||
}
|
||||
}
|
||||
|
||||
protected NettyEntityLocatable<?,?> createSelfEntity(PlayerData ownData, int entityID, UUID playerUUID) {
|
||||
return PacketEventsEntity.createSelfEntity(ownData, entityID, playerUUID);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected @NotNull NettyEntityLocatable<?,?> processEntitySpawn(PlayerData playerData, PacketWrapper<?> packetWrapper, UUID world, int currentTick) {
|
||||
WrapperPlayServerSpawnEntity packet = (WrapperPlayServerSpawnEntity) packetWrapper;
|
||||
if (packet.getUUID().isEmpty()) {
|
||||
Logger.errorAndReturn(new RuntimeException("Entity UUID null when handling spawn entity packet, id=" + packet.getEntityId() + " tick=" + currentTick), 2, PacketEventsEntityViewController.class);
|
||||
return null;
|
||||
}
|
||||
UUID entityUUID = packet.getUUID().get();
|
||||
|
||||
PacketEventsEntity entity = trackEntitySpawn(playerData, entityUUID, packet.getEntityId(), world,
|
||||
packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ(), packet.getEntityType());
|
||||
Vector3d velocity = packet.getVelocity().orElseGet(Vector3d::zero);
|
||||
entity.setEntityData(packet.getData())
|
||||
.setYaw(packet.getYaw())
|
||||
.setPitch(packet.getPitch())
|
||||
.setHeadYaw(packet.getHeadYaw())
|
||||
.setVelocity(velocity.getX(), velocity.getY(), velocity.getZ());
|
||||
return entity;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int processRelativeMovePacket(PacketWrapper<?> packetWrapper, PlayerData playerData, int currentTick) {
|
||||
WrapperPlayServerEntityRelativeMove packet = (WrapperPlayServerEntityRelativeMove) packetWrapper;
|
||||
int entityID = packet.getEntityId();
|
||||
|
||||
NettyEntityLocatable<?,?> entity = playerData.entityFromID(entityID);
|
||||
if (entity == null) {
|
||||
Logger.error("Received relative move packet for unknown entity, id=" + entityID, 2, PacketEventsEntityViewController.class);
|
||||
return entityID;
|
||||
}
|
||||
entity.add(packet.getDeltaX(), packet.getDeltaY(), packet.getDeltaZ());
|
||||
entity.setOnGround(packet.isOnGround());
|
||||
|
||||
return entityID;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int processRelativeMoveAndRotationPacket(PacketWrapper<?> packet, PlayerData playerData, int currentTick) {
|
||||
WrapperPlayServerEntityRelativeMoveAndRotation packetWrapper = (WrapperPlayServerEntityRelativeMoveAndRotation) packet;
|
||||
int entityID = packetWrapper.getEntityId();
|
||||
|
||||
NettyEntityLocatable<?,?> entity = playerData.entityFromID(entityID);
|
||||
if (entity == null) {
|
||||
Logger.error("Received relative move and rotation packet for unknown entity, id=" + entityID, 2, PacketEventsEntityViewController.class);
|
||||
return entityID;
|
||||
}
|
||||
entity.add(packetWrapper.getDeltaX(), packetWrapper.getDeltaY(), packetWrapper.getDeltaZ());
|
||||
entity.setYaw(packetWrapper.getYaw()).setPitch(packetWrapper.getPitch()).setOnGround(packetWrapper.isOnGround());
|
||||
|
||||
return entityID;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int processTeleportPacket(PacketWrapper<?> packet, PlayerData playerData, int currentTick) {
|
||||
WrapperPlayServerEntityTeleport packetWrapper = (WrapperPlayServerEntityTeleport) packet;
|
||||
int entityID = packetWrapper.getEntityId();
|
||||
|
||||
NettyEntityLocatable<?,?> entity = playerData.entityFromID(entityID);
|
||||
if (entity == null) {
|
||||
Logger.error("Received teleport packet for unknown entity, id=" + entityID, 2, PacketEventsEntityViewController.class);
|
||||
return entityID;
|
||||
}
|
||||
Vector3d position = packetWrapper.getPosition();
|
||||
Vector3d velocity = packetWrapper.getDeltaMovement();
|
||||
entity.set(position.getX(), position.getY(), position.getZ());
|
||||
entity.setYaw(packetWrapper.getYaw()).setPitch(packetWrapper.getPitch()).setVelocity(velocity.x, velocity.y, velocity.z).setOnGround(packetWrapper.isOnGround());
|
||||
|
||||
return entityID;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int processPositionSyncPacket(PacketWrapper<?> packet, PlayerData playerData, int currentTick) {
|
||||
WrapperPlayServerEntityPositionSync packetWrapper = (WrapperPlayServerEntityPositionSync) packet;
|
||||
int entityID = packetWrapper.getId();
|
||||
|
||||
NettyEntityLocatable<?,?> entity = playerData.entityFromID(entityID);
|
||||
if (entity == null) {
|
||||
Logger.error("Received position sync packet for unknown entity, id=" + entityID, 2, PacketEventsEntityViewController.class);
|
||||
return entityID;
|
||||
}
|
||||
Vector3d position = packetWrapper.getValues().getPosition();
|
||||
Vector3d velocity = packetWrapper.getValues().getDeltaMovement();
|
||||
entity.set(position.getX(), position.getY(), position.getZ());
|
||||
entity.setYaw(packetWrapper.getValues().getYaw()).setPitch(packetWrapper.getValues().getPitch()).setVelocity(velocity.x, velocity.y, velocity.z).setOnGround(packetWrapper.isOnGround());
|
||||
|
||||
return entityID;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
protected void cachePacket(PacketWrapper<?> packet, int entityID, PlayerData playerData, int currentTick) {
|
||||
NettyEntityLocatable<?,?> entity = playerData.entityFromID(entityID);
|
||||
if (entity == null) {
|
||||
Logger.warning("Attempted to cache packet for unknown entity, id=" + entityID + " packet=" + packet.getClass().getSimpleName() + ". Queuing retry.", 6, PacketEventsEntityViewController.class);
|
||||
playerData.nettyData().addPostEntitySpawnTask(entityID, new PECacheablePacketReconciliationTask(this, playerData, entityID, packet, currentTick));
|
||||
return;
|
||||
}
|
||||
ensureReplayData((PacketEventsEntity) entity).addPacket(packet);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int processRotationPacket(PacketWrapper<?> packet, PlayerData playerData, int currentTick) {
|
||||
WrapperPlayServerEntityRotation packetWrapper = (WrapperPlayServerEntityRotation) packet;
|
||||
int entityID = packetWrapper.getEntityId();
|
||||
|
||||
NettyEntityLocatable<?,?> entity = playerData.entityFromID(entityID);
|
||||
if (entity == null) {
|
||||
Logger.error("Received rotation packet for unknown entity, id=" + entityID, 2, PacketEventsEntityViewController.class);
|
||||
return entityID;
|
||||
}
|
||||
entity.setYaw(packetWrapper.getYaw()).setPitch(packetWrapper.getPitch()).setOnGround(packetWrapper.isOnGround());
|
||||
|
||||
return entityID;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int processHeadLookPacket(PacketWrapper<?> packet, PlayerData playerData, int currentTick) {
|
||||
WrapperPlayServerEntityHeadLook packetWrapper = (WrapperPlayServerEntityHeadLook) packet;
|
||||
int entityID = packetWrapper.getEntityId();
|
||||
|
||||
NettyEntityLocatable<?,?> entity = playerData.entityFromID(entityID);
|
||||
if (entity == null) {
|
||||
Logger.error("Received head look packet for unknown entity, id=" + entityID, 2, PacketEventsEntityViewController.class);
|
||||
return entityID;
|
||||
}
|
||||
entity.setHeadYaw(packetWrapper.getHeadYaw());
|
||||
|
||||
return entityID;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int processEntityVelocityPacket(PacketWrapper<?> packet, PlayerData playerData, int currentTick) {
|
||||
WrapperPlayServerEntityVelocity packetWrapper = (WrapperPlayServerEntityVelocity) packet;
|
||||
int entityID = packetWrapper.getEntityId();
|
||||
|
||||
NettyEntityLocatable<?,?> entity = playerData.entityFromID(entityID);
|
||||
if (entity == null) {
|
||||
Logger.error("Received velocity packet for unknown entity, id=" + entityID, 2, PacketEventsEntityViewController.class);
|
||||
return entityID;
|
||||
}
|
||||
entity.setVelocity(packetWrapper.getVelocity().getX(), packetWrapper.getVelocity().getY(), packetWrapper.getVelocity().getZ());
|
||||
|
||||
return entityID;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void sendEntityPassengerPacket(int vehicle, ArrayList<Integer> passengers, PlayerData playerData) {
|
||||
NettyEntityLocatable<?,?> entity = playerData.entityFromID(vehicle);
|
||||
if (entity == null) {
|
||||
Logger.error("Attempted to send passenger packet for unknown entity, id=" + vehicle, 2, PacketEventsEntityViewController.class);
|
||||
return;
|
||||
}
|
||||
WrapperPlayServerSetPassengers packet = new WrapperPlayServerSetPassengers(vehicle, passengers.stream().mapToInt(Integer::intValue).toArray());
|
||||
Object channel = PacketEvents.getAPI().getProtocolManager().getChannel(playerData.getPlayerUUID());
|
||||
PacketEvents.getAPI().getProtocolManager().getUser(channel).writePacketSilently(packet);
|
||||
}
|
||||
|
||||
private PacketEventsEntity trackEntitySpawn(PlayerData playerData, UUID entityUUID, int entityID, UUID world, double x, double y, double z, EntityType entityType) {
|
||||
|
||||
PacketEventsEntity entity = new PacketEventsEntity(playerData, world, x, y, z, entityID, entityUUID, false, entityType, true /*default value as this is handled in PacketEntityViewController*/);
|
||||
ensureReplayData(entity);
|
||||
return entity;
|
||||
}
|
||||
|
||||
private void processEntityTransitions(UUID viewerUUID, User viewer, EntityView<PacketEventsEntity> entityView) {
|
||||
for (EntityViewTransition transition : entityView.drainTransitions()) {
|
||||
PacketEventsEntity entity = getTrackedEntity(entityView, transition.targetUUID());
|
||||
|
||||
switch (transition.type()) {
|
||||
case HIDE -> {
|
||||
if (entity != null && entity.clientVisible() && entity.entityID() >= 0) {
|
||||
viewer.writePacketSilently(new WrapperPlayServerDestroyEntities(entity.entityID()));
|
||||
entity.setClientVisible(false);
|
||||
}
|
||||
}
|
||||
case SHOW -> {
|
||||
if (entity == null || entity.isSelfEntity()) {
|
||||
Logger.warning("PacketEvents.processEntityTransitions show-skipped viewer=" + viewerUUID
|
||||
+ " target=" + transition.targetUUID()
|
||||
+ " reason="
|
||||
+ (entity == null ? "missing-entity" : "self-entity"), 2, PacketEventsEntityViewController.class);
|
||||
continue;
|
||||
}
|
||||
PacketEventsEntityReplayData replayData = ensureReplayData(entity);
|
||||
sendEntityShow(viewer, PlayerRegistry.getInstance().getPlayerData(viewerUUID), entity, replayData);
|
||||
entity.setClientVisible(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private PacketWrapper<?> buildSpawnPacket(PacketEventsEntity entity) {
|
||||
if (entity.isSelfEntity()) {
|
||||
Logger.errorAndReturn(new RuntimeException("Should not build spawn packet for self entity"), 1, PacketEventsEntityViewController.class);
|
||||
return null;
|
||||
}
|
||||
return new WrapperPlayServerSpawnEntity(
|
||||
entity.entityID(),
|
||||
Optional.of(entity.entityUUID()),
|
||||
entity.entityType(),
|
||||
new Vector3d(entity.x(), entity.y(), entity.z()),
|
||||
entity.pitch(),
|
||||
entity.yaw(),
|
||||
entity.headYaw(),
|
||||
entity.entityData(),
|
||||
Optional.of(new Vector3d(entity.velocityX(), entity.velocityY(), entity.velocityZ()))
|
||||
);
|
||||
}
|
||||
|
||||
private WrapperPlayServerSetPassengers buildPassengersPacket(@Nullable NettyEntityLocatable<?,?> entity, PlayerData playerData) {
|
||||
if (entity == null) {
|
||||
return null;
|
||||
}
|
||||
int[] passengerIDs = entity.passengerIDs();
|
||||
if (passengerIDs == null || passengerIDs.length == 0) {
|
||||
return null;
|
||||
}
|
||||
ArrayList<Integer> visiblePassengerIDs = new ArrayList<>();
|
||||
for (int passengerID : passengerIDs) {
|
||||
NettyEntityLocatable<?,?> passenger = playerData.entityFromID(passengerID);
|
||||
if (passenger != null && passenger.visible()) {
|
||||
visiblePassengerIDs.add(passengerID);
|
||||
}
|
||||
}
|
||||
return new WrapperPlayServerSetPassengers(entity.entityID(), visiblePassengerIDs.stream().mapToInt(Integer::intValue).toArray());
|
||||
}
|
||||
|
||||
private @Nullable WrapperPlayServerAttachEntity[] buildLeashPackets(PacketEventsEntity entity, PlayerData playerData) {
|
||||
int[] leashedIDs = entity.leashedEntityIDsOrNull();
|
||||
int leashingID = entity.leashingEntity();
|
||||
WrapperPlayServerAttachEntity leashingShow = null;
|
||||
if (leashingID != NO_LEASHER) {
|
||||
NettyEntityLocatable<?,?> leashHolder = playerData.entityFromID(leashingID);
|
||||
if (leashHolder != null && leashHolder.visible()) {
|
||||
leashingShow = new WrapperPlayServerAttachEntity(entity.entityID(), leashingID, true);
|
||||
}
|
||||
}
|
||||
if (leashedIDs == null || leashedIDs.length == 0) {
|
||||
return leashingShow == null ? null : new WrapperPlayServerAttachEntity[]{leashingShow};
|
||||
}
|
||||
WrapperPlayServerAttachEntity[] packets = new WrapperPlayServerAttachEntity[leashedIDs.length + (leashingShow == null ? 0 : 1)];
|
||||
int index = 0;
|
||||
if (leashingShow != null) {
|
||||
packets[0] = leashingShow;
|
||||
index = 1;
|
||||
}
|
||||
for (int leashedID : leashedIDs) {
|
||||
NettyEntityLocatable<?,?> leashHolder = playerData.entityFromID(leashedID);
|
||||
if (leashHolder != null && leashHolder.visible()) {
|
||||
packets[index] = new WrapperPlayServerAttachEntity(leashedID, entity.entityID(), true);
|
||||
index++;
|
||||
}
|
||||
}
|
||||
return packets;
|
||||
}
|
||||
|
||||
private WrapperPlayServerEntityEffect copyEffectPacket(WrapperPlayServerEntityEffect effect) {
|
||||
WrapperPlayServerEntityEffect copy = new WrapperPlayServerEntityEffect(
|
||||
effect.getEntityId(),
|
||||
effect.getPotionType(),
|
||||
effect.getEffectAmplifier(),
|
||||
effect.getEffectDurationTicks(),
|
||||
buildEffectFlags(effect.isAmbient(), effect.isVisible(), effect.isShowIcon())
|
||||
);
|
||||
copy.setFactorData(effect.getFactorData());
|
||||
return copy;
|
||||
}
|
||||
|
||||
private WrapperPlayServerEntityMetadata copyEntityMetadataPacket(WrapperPlayServerEntityMetadata packet) {
|
||||
return new WrapperPlayServerEntityMetadata(
|
||||
packet.getEntityId(),
|
||||
copyEntityMetadata(packet.getEntityMetadata())
|
||||
);
|
||||
}
|
||||
|
||||
private WrapperPlayServerEntityEquipment copyEntityEquipmentPacket(WrapperPlayServerEntityEquipment packet) {
|
||||
return new WrapperPlayServerEntityEquipment(
|
||||
packet.getEntityId(),
|
||||
copyEquipment(packet.getEquipment())
|
||||
);
|
||||
}
|
||||
|
||||
private WrapperPlayServerEntityVelocity copyEntityVelocityPacket(WrapperPlayServerEntityVelocity packet) {
|
||||
return new WrapperPlayServerEntityVelocity(
|
||||
packet.getEntityId(),
|
||||
new Vector3d(packet.getVelocity().getX(), packet.getVelocity().getY(), packet.getVelocity().getZ())
|
||||
);
|
||||
}
|
||||
|
||||
private WrapperPlayServerRemoveEntityEffect copyRemoveEntityEffectPacket(WrapperPlayServerRemoveEntityEffect packet) {
|
||||
return new WrapperPlayServerRemoveEntityEffect(
|
||||
packet.getEntityId(),
|
||||
packet.getPotionType()
|
||||
);
|
||||
}
|
||||
|
||||
private List<EntityData<?>> copyEntityMetadata(List<EntityData<?>> metadata) {
|
||||
return metadata == null ? List.of() : List.copyOf(metadata);
|
||||
}
|
||||
|
||||
private List<Equipment> copyEquipment(List<Equipment> equipment) {
|
||||
return equipment == null ? List.of() : List.copyOf(equipment);
|
||||
}
|
||||
|
||||
private byte buildEffectFlags(boolean ambient, boolean visible, boolean showIcon) {
|
||||
byte flags = 0;
|
||||
if (ambient) {
|
||||
flags |= 1;
|
||||
}
|
||||
if (visible) {
|
||||
flags |= 2;
|
||||
}
|
||||
if (showIcon) {
|
||||
flags |= 4;
|
||||
}
|
||||
return flags;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> T cast(Object value) {
|
||||
return (T) value;
|
||||
}
|
||||
|
||||
private PacketEventsEntity getTrackedEntity(EntityView<PacketEventsEntity> entityView, UUID entityUUID) {
|
||||
return entityView.getEntity(entityUUID);
|
||||
}
|
||||
|
||||
private PacketEventsEntity getTrackedEntity(EntityView<PacketEventsEntity> entityView, int entityID) {
|
||||
return entityView.getEntity(entityID);
|
||||
}
|
||||
|
||||
PacketEventsEntityReplayData ensureReplayData(PacketEventsEntity entity) {
|
||||
PacketEventsEntityReplayData replayData = entity.packetReplayData();
|
||||
if (replayData == null) {
|
||||
replayData = PacketEventsEntityReplayData.create();
|
||||
entity.setPacketReplayData(replayData);
|
||||
}
|
||||
return replayData;
|
||||
}
|
||||
|
||||
private void sendEntityShow(User viewer, PlayerData data, PacketEventsEntity entity, PacketEventsEntityReplayData replayData) {
|
||||
viewer.writePacketSilently(buildSpawnPacket(entity));
|
||||
sendEntityAbsoluteCorrection(viewer, entity);
|
||||
|
||||
for (PacketWrapper<?> cachedPacket : replayData.getPackets()) {
|
||||
|
||||
if (cachedPacket.getClass() == WrapperPlayServerEntityMetadata.class) {
|
||||
WrapperPlayServerEntityMetadata metadataPacket = copyEntityMetadataPacket((WrapperPlayServerEntityMetadata) cachedPacket);
|
||||
viewer.writePacketSilently(metadataPacket);
|
||||
} else if (cachedPacket.getClass() == WrapperPlayServerEntityEquipment.class) {
|
||||
WrapperPlayServerEntityEquipment equipmentPacket = copyEntityEquipmentPacket((WrapperPlayServerEntityEquipment) cachedPacket);
|
||||
viewer.writePacketSilently(equipmentPacket);
|
||||
} else if (cachedPacket.getClass() == WrapperPlayServerEntityVelocity.class) {
|
||||
WrapperPlayServerEntityVelocity velocityPacket = copyEntityVelocityPacket((WrapperPlayServerEntityVelocity) cachedPacket);
|
||||
viewer.writePacketSilently(velocityPacket);
|
||||
} else if (cachedPacket.getClass() == WrapperPlayServerEntityEffect.class) {
|
||||
viewer.writePacketSilently(copyEffectPacket((WrapperPlayServerEntityEffect) cachedPacket));
|
||||
} else if (cachedPacket.getClass() == WrapperPlayServerRemoveEntityEffect.class) {
|
||||
viewer.writePacketSilently(copyRemoveEntityEffectPacket((WrapperPlayServerRemoveEntityEffect) cachedPacket));
|
||||
} else if (cachedPacket.getClass() == WrapperPlayServerUpdateAttributes.class) {
|
||||
WrapperPlayServerUpdateAttributes existing = (WrapperPlayServerUpdateAttributes) cachedPacket;
|
||||
WrapperPlayServerUpdateAttributes copy = new WrapperPlayServerUpdateAttributes(existing.getEntityId(), existing.getProperties());
|
||||
viewer.writePacketSilently(copy);
|
||||
}
|
||||
else {
|
||||
Logger.warning("Unsupported cached packet type for replay: " + cachedPacket.getClass().getName(), 2, PacketEventsEntityViewController.class);
|
||||
}
|
||||
}
|
||||
COMMON.writeIfPresent(viewer, buildPassengersPacket(entity, data));
|
||||
if (entity.vehicleID() != NO_VEHICLE) {
|
||||
COMMON.writeIfPresent(viewer, buildPassengersPacket(data.entityFromID(entity.vehicleID()), data));
|
||||
}
|
||||
WrapperPlayServerAttachEntity[] leashPackets = buildLeashPackets(entity, data);
|
||||
if (leashPackets == null) return;
|
||||
for (WrapperPlayServerAttachEntity leashPacket : leashPackets) {
|
||||
if (leashPacket != null) {
|
||||
viewer.writePacketSilently(leashPacket);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void sendEntityAbsoluteCorrection(User viewer, PacketEventsEntity entity) {
|
||||
if (entity.entityID() < 0) {
|
||||
return;
|
||||
}
|
||||
viewer.writePacketSilently(new WrapperPlayServerEntityTeleport(
|
||||
entity.entityID(),
|
||||
new Vector3d(entity.x(), entity.y(), entity.z()),
|
||||
new Vector3d(entity.velocityX(), entity.velocityY(), entity.velocityZ()),
|
||||
entity.yaw(),
|
||||
entity.pitch(),
|
||||
RelativeFlag.NONE,
|
||||
entity.onGround()
|
||||
));
|
||||
viewer.writePacketSilently(new WrapperPlayServerEntityHeadLook(entity.entityID(), entity.headYaw()));
|
||||
}
|
||||
|
||||
protected void insertEntityToPlayerView(NettyEntityLocatable<?,?> entity, PlayerData playerData) {
|
||||
playerData.playerView().insertEntity(entity.cast());
|
||||
reconcileUnresolvedLeashes(entity, playerData);
|
||||
}
|
||||
|
||||
protected void insertEntityToEntityView(NettyEntityLocatable<?,?> entity, PlayerData playerData) {
|
||||
playerData.entityView().insertEntity(entity.cast()); //todo: no need to put here, move to abstract packet view controller
|
||||
reconcileUnresolvedLeashes(entity, playerData);
|
||||
}
|
||||
|
||||
private void reconcileUnresolvedLeashes(NettyEntityLocatable<?,?> insertedEntity, PlayerData playerData) {
|
||||
int[] pendingLeashedEntityIDs = playerData.nettyData().consumeUnresolvedLeashes(insertedEntity.entityID());
|
||||
if (IntArrayList.isEmpty(pendingLeashedEntityIDs)) {
|
||||
return;
|
||||
}
|
||||
for (int leashedEntityID : pendingLeashedEntityIDs) {
|
||||
NettyEntityLocatable<?,?> leashedEntity = playerData.entityFromID(leashedEntityID);
|
||||
if (leashedEntity == null || leashedEntity.leashingEntity() != insertedEntity.entityID()) {
|
||||
continue;
|
||||
}
|
||||
insertedEntity.addLeashedEntity(leashedEntityID);
|
||||
}
|
||||
if (!insertedEntity.clientVisible()) {
|
||||
return;
|
||||
}
|
||||
WrapperPlayServerAttachEntity[] leashPackets = buildLeashPackets((PacketEventsEntity) insertedEntity, playerData);
|
||||
if (leashPackets == null) {
|
||||
return;
|
||||
}
|
||||
Object channel = PacketEvents.getAPI().getProtocolManager().getChannel(playerData.getPlayerUUID());
|
||||
User viewer = PacketEvents.getAPI().getProtocolManager().getUser(channel);
|
||||
for (WrapperPlayServerAttachEntity leashPacket : leashPackets) {
|
||||
if (leashPacket != null) {
|
||||
viewer.writePacketSilently(leashPacket);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
import java.time.Instant
|
||||
import org.gradle.jvm.toolchain.JavaToolchainService
|
||||
|
||||
plugins {
|
||||
id("java-library")
|
||||
id("io.papermc.paperweight.userdev") version "2.0.0-beta.21"
|
||||
id("xyz.jpenilla.run-paper") version "3.0.2"
|
||||
id("com.gradleup.shadow") version "9.4.0"
|
||||
}
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
maven { url = uri("https://repo.codemc.io/repository/maven-releases/") }
|
||||
maven { url = uri("https://repo.codemc.io/repository/maven-snapshots/") }
|
||||
maven { url = uri("https://eldonexus.de/repository/maven-public/") }
|
||||
}
|
||||
|
||||
dependencies {
|
||||
paperweight.paperDevBundle("1.21.11-R0.1-SNAPSHOT")
|
||||
//paperweight.paperDevBundle("26.1.2.build.+")
|
||||
compileOnly("com.github.retrooper:packetevents-spigot:2.12.0")
|
||||
compileOnly("org.spongepowered:configurate-core:4.2.0")
|
||||
compileOnly("org.spongepowered:configurate-yaml:4.2.0")
|
||||
|
||||
compileOnly("net.strokkur.commands:annotations-paper:2.1.2")
|
||||
annotationProcessor("net.strokkur.commands:processor-paper:2.1.2")
|
||||
|
||||
implementation("org.jetbrains:annotations:24.0.1")
|
||||
|
||||
implementation(project(":locatable-lib"))
|
||||
implementation(project(":logging"))
|
||||
implementation(project(":core"))
|
||||
implementation(project(":packetevents"))
|
||||
}
|
||||
|
||||
java {
|
||||
toolchain.languageVersion = JavaLanguageVersion.of(21)
|
||||
}
|
||||
|
||||
val javaToolchainService = project.extensions.getByType(JavaToolchainService::class.java)
|
||||
|
||||
group = "games.cubi.raycastedantiesp.paper"
|
||||
|
||||
val platformPaperVersion: String = "0.4.7-SNAPSHOT"
|
||||
val coreVersion = project(":core").version.toString()
|
||||
|
||||
val commitShort = providers.exec {
|
||||
commandLine("git", "rev-parse", "--short=8", "HEAD")
|
||||
}.standardOutput.asText.map { it.trim() }
|
||||
|
||||
val commitFull = providers.exec {
|
||||
commandLine("git", "rev-parse", "HEAD")
|
||||
}.standardOutput.asText.map { it.trim() }
|
||||
|
||||
val buildTime = providers.provider {
|
||||
Instant.now().toString().replace(":", "-") // Replace colons to avoid issues in file names on some platforms
|
||||
}
|
||||
|
||||
val isRelease = gradle.startParameter.taskNames.any {
|
||||
it.contains("buildRelease")
|
||||
}
|
||||
|
||||
fun getVersionString(): String {
|
||||
if (isRelease) {
|
||||
val paperVersion = platformPaperVersion.substringBefore("-") // Remove any suffixes like "-SNAPSHOT"
|
||||
return "${coreVersion}-Paper-${paperVersion}-RELEASE"
|
||||
} else {
|
||||
return "${coreVersion}-Paper-${platformPaperVersion}+build-${buildTime.get()}+git-${commitShort.get()}"
|
||||
}
|
||||
}
|
||||
|
||||
fun getBasicVersionString(): String {
|
||||
return if (isRelease) {
|
||||
platformPaperVersion.substringBefore("-") // Remove any suffixes like "-SNAPSHOT"
|
||||
} else {
|
||||
platformPaperVersion
|
||||
}
|
||||
}
|
||||
|
||||
version = getVersionString()
|
||||
|
||||
tasks {
|
||||
runServer {
|
||||
// Configure the Minecraft version for our task.
|
||||
// This is the only required configuration besides applying the plugin.
|
||||
// Your plugin's jar (or shadowJar if present) will be used automatically.
|
||||
javaLauncher = javaToolchainService.launcherFor {
|
||||
//languageVersion.set(paperRunJavaVersion.map(JavaLanguageVersion::of))
|
||||
languageVersion.set(JavaLanguageVersion.of(25))
|
||||
}
|
||||
minecraftVersion("26.1.2")
|
||||
//minecraftVersion("1.21.11")
|
||||
jvmArgs("-Xms4G", "-Xmx4G", "-Dcom.mojang.eula.agree=true")
|
||||
}
|
||||
|
||||
processResources {
|
||||
val props = mapOf("version" to version.toString())
|
||||
inputs.properties(props)
|
||||
filesMatching("plugin.yml") {
|
||||
expand(props)
|
||||
}
|
||||
val gitProps = mapOf(
|
||||
"short_git" to commitShort.get(),
|
||||
"long_git" to commitFull.get(),
|
||||
"build_time" to buildTime.get(),
|
||||
"version" to getBasicVersionString()
|
||||
)
|
||||
inputs.properties(gitProps)
|
||||
filesMatching("build-properties/platform.yml") {
|
||||
expand(gitProps)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tasks.shadowJar {
|
||||
dependencies {
|
||||
include(project(":logging"))
|
||||
include(project(":locatable-lib"))
|
||||
include(project(":core"))
|
||||
include(project(":packetevents"))
|
||||
}
|
||||
archiveBaseName.set("RaycastedAntiESP")
|
||||
archiveClassifier.set("")
|
||||
}
|
||||
|
||||
tasks.jar {
|
||||
archiveBaseName.set("Incorrectly-Compiled-Without-ShadowJar")
|
||||
}
|
||||
|
||||
// This is the task to run to test if changes to the plugin are working
|
||||
tasks.register("buildSnapshot") {
|
||||
group = "raycasted anti-esp" //Not caps sensitive so using spacing and hyphen
|
||||
description = "Builds a snapshot version of the plugin with git and build-time metadata included in the file name."
|
||||
dependsOn("shadowJar")
|
||||
}
|
||||
|
||||
tasks.register("buildRelease") {
|
||||
group = "raycasted anti-esp"
|
||||
description = "Builds a release version of the plugin with a clean version number (no git or build-time metadata) included in the file name."
|
||||
dependsOn("shadowJar")
|
||||
}
|
||||
|
||||
tasks.register("runPaper") {
|
||||
// alias for runServer to put it in the same group as the build tasks
|
||||
group = "raycasted anti-esp"
|
||||
description = "Runs a Paper server with the plugin loaded for testing purposes."
|
||||
dependsOn("runServer")
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package games.cubi.raycastedantiesp.paper;
|
||||
|
||||
import com.destroystokyo.paper.event.server.ServerTickEndEvent;
|
||||
import com.destroystokyo.paper.event.server.ServerTickStartEvent;
|
||||
import games.cubi.logs.Logger;
|
||||
import games.cubi.raycastedantiesp.core.players.PlayerRegistry;
|
||||
import games.cubi.raycastedantiesp.paper.engine.PaperSimpleEngine;
|
||||
import games.cubi.raycastedantiesp.core.players.PlayerData;
|
||||
import games.cubi.raycastedantiesp.paper.utils.PaperListener;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.player.PlayerChangedWorldEvent;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
import org.bukkit.event.player.PlayerMoveEvent;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import org.bukkit.event.player.PlayerRespawnEvent;
|
||||
import org.bukkit.event.player.PlayerTeleportEvent;
|
||||
|
||||
import java.util.function.IntSupplier;
|
||||
|
||||
import static games.cubi.raycastedantiesp.paper.UpdateChecker.checkForUpdates;
|
||||
|
||||
public class EventListener extends PaperListener {
|
||||
private final RaycastedAntiESP plugin;
|
||||
private final PaperSimpleEngine engine;
|
||||
private final IntSupplier currentTickSupplier;
|
||||
|
||||
private static EventListener instance = null;
|
||||
|
||||
private EventListener(RaycastedAntiESP plugin, PaperSimpleEngine engine, IntSupplier currentTickSupplier) {
|
||||
this.plugin = plugin;
|
||||
this.engine = engine;
|
||||
this.currentTickSupplier = currentTickSupplier;
|
||||
}
|
||||
|
||||
public static EventListener initialise(RaycastedAntiESP plugin, PaperSimpleEngine engine, IntSupplier currentTickSupplier) {
|
||||
if (instance == null) {
|
||||
instance = new EventListener(plugin, engine, currentTickSupplier);
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onPlayerDisconnect(PlayerQuitEvent e) {
|
||||
PlayerRegistry.getInstance().unregisterPlayer(e.getPlayer().getUniqueId());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOWEST) //Runs first
|
||||
public void onPlayerJoin(PlayerJoinEvent e) {
|
||||
Player player = e.getPlayer();
|
||||
|
||||
if (player.hasPermission("raycastedantiesp.updatecheck")) { //todo: centralise permission strings to prevent issues when perm names are changed
|
||||
checkForUpdates(plugin, player);
|
||||
}
|
||||
|
||||
boolean hasBypassPermission = player.hasPermission("raycastedantiesp.bypass");
|
||||
PlayerData playerData = PlayerRegistry.getInstance().getPlayerData(player.getUniqueId());
|
||||
|
||||
if (playerData == null) {
|
||||
Logger.warning("Failed to load player data for " + player.getName() + " (" + player.getUniqueId() + "). Attempting to reconstruct.", 3, EventListener.class);
|
||||
playerData = PlayerRegistry.getInstance().registerAndGetPlayerIfAbsent(player.getUniqueId(), hasBypassPermission, currentTickSupplier.getAsInt());
|
||||
}
|
||||
playerData.setBypassPermission(hasBypassPermission);
|
||||
updateOwnLocation(playerData, player.getEyeLocation());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onPlayerMove(PlayerMoveEvent event) {
|
||||
PlayerData playerData = PlayerRegistry.getInstance().getPlayerData(event.getPlayer().getUniqueId());
|
||||
if (playerData == null) return;
|
||||
updateOwnLocation(playerData, event.getPlayer().getEyeLocation());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onPlayerTeleport(PlayerTeleportEvent event) {
|
||||
updateOwnLocation(event.getPlayer(), event.getTo());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onPlayerChangedWorld(PlayerChangedWorldEvent event) {
|
||||
updateOwnLocation(event.getPlayer(), event.getPlayer().getLocation());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onPlayerRespawn(PlayerRespawnEvent event) {
|
||||
updateOwnLocation(event.getPlayer(), event.getRespawnLocation());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOWEST) //Runs first
|
||||
public void serverTickStartEvent(ServerTickStartEvent event) {
|
||||
Bukkit.getAsyncScheduler().runNow(plugin, task -> engine.tick());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR) //Runs last
|
||||
public void serverTickStopEvent(ServerTickEndEvent event) {
|
||||
}
|
||||
|
||||
private void updateOwnLocation(PlayerData playerData, Location location) {
|
||||
if (playerData == null || location == null || location.getWorld() == null) {
|
||||
return;
|
||||
}
|
||||
playerData.updateOwnLocation(location.getWorld().getUID(), location.getX(), location.getY(), location.getZ());
|
||||
}
|
||||
|
||||
private void updateOwnLocation(Player player, Location location) {
|
||||
PlayerData playerData = PlayerRegistry.getInstance().getPlayerData(player.getUniqueId());
|
||||
if (playerData == null || location == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
Location eyeLocation = location.clone().add(0, player.getEyeHeight(), 0);
|
||||
updateOwnLocation(playerData, eyeLocation);
|
||||
}
|
||||
|
||||
}
|
||||
+239
@@ -0,0 +1,239 @@
|
||||
package games.cubi.raycastedantiesp.paper;
|
||||
|
||||
import games.cubi.logs.CheckPreviousLogForError;
|
||||
import games.cubi.logs.PlatformLogger;
|
||||
import games.cubi.raycastedantiesp.core.config.ConfigManager;
|
||||
import games.cubi.raycastedantiesp.core.config.DebugConfig;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Range;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ConcurrentLinkedDeque;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
public class PaperLoggerAdapter implements PlatformLogger {
|
||||
|
||||
/**
|
||||
* Set this to true to send logs to the file regardless of the log level.
|
||||
*/
|
||||
private static final boolean LOG_TO_FILE = false;
|
||||
|
||||
/*
|
||||
* If too many logs queue up before clear() is called, flush them anyway.
|
||||
* This avoids unbounded memory growth.
|
||||
*/
|
||||
private static final int MAX_QUEUED_MESSAGES_BEFORE_FLUSH = 128;
|
||||
|
||||
private final java.util.logging.Logger logger;
|
||||
private final Path logFilePath;
|
||||
|
||||
private final ConcurrentLinkedDeque<String> queuedFileMessages = new ConcurrentLinkedDeque<>();
|
||||
private final AtomicInteger queuedFileMessageCount = new AtomicInteger(0);
|
||||
|
||||
/*
|
||||
* Prevents two threads from flushing the queue to the file at the same time.
|
||||
*/
|
||||
private final AtomicBoolean writingToFile = new AtomicBoolean(false);
|
||||
|
||||
protected PaperLoggerAdapter(java.util.logging.Logger logger, Path logFilePath) {
|
||||
this.logger = Objects.requireNonNull(logger, "logger");
|
||||
this.logFilePath = Objects.requireNonNull(logFilePath, "logFilePath");
|
||||
|
||||
if (LOG_TO_FILE) {
|
||||
try {
|
||||
Path parent = logFilePath.getParent();
|
||||
if (parent != null) {
|
||||
Files.createDirectories(parent);
|
||||
}
|
||||
|
||||
if (!Files.exists(logFilePath)) {
|
||||
Files.createFile(logFilePath);
|
||||
}
|
||||
} catch (IOException exception) {
|
||||
throw new IllegalStateException("Could not initialise log file at " + logFilePath, exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Logging severity is from 0-10. If the configured severity is 0, no logs will be sent. If 1, only most important logs.
|
||||
*
|
||||
* Therefore, logs with level of 1 are most important and 10 least.
|
||||
*
|
||||
* Note that by default the log levels are at 5, so any logs which should appear normally should be at 1-5. Additionally, loggers which fire several times a tick should be at 10, once a tick at 9, and loggers firing frequently at 6-8
|
||||
* */
|
||||
|
||||
private int getLevel(Level severity, DebugConfig debug) {
|
||||
return switch (severity) {
|
||||
case INFO -> debug.getInfoLevel();
|
||||
case WARN -> debug.getWarnLevel();
|
||||
case ERROR -> debug.getErrorLevel();
|
||||
default -> 1;
|
||||
};
|
||||
}
|
||||
|
||||
private DebugConfig.Severity getDebugSeverity(Level severity) {
|
||||
return switch (severity) {
|
||||
case INFO -> DebugConfig.Severity.INFO;
|
||||
case WARN -> DebugConfig.Severity.WARN;
|
||||
case ERROR -> DebugConfig.Severity.ERROR;
|
||||
default -> DebugConfig.Severity.ERROR;
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Logs a warning message and serves as an early return. Nothing called after this method will be executed.
|
||||
* @param throwable The throwable to log, used for the included stack trace. The message of the throwable will be used as the warning message
|
||||
* @throws CheckPreviousLogForError Always throws this to allow for early return from functions after logging an error
|
||||
* **/
|
||||
@Override
|
||||
public void warningAndReturn(Throwable throwable, @Range(from = 1, to = 10) int level, Class<?>... source) {
|
||||
warning(PlatformLogger.processThrowable(throwable), level, source);
|
||||
throw earlyReturn;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void warning(Throwable throwable, @Range(from = 1, to = 10) int level, Class<?>... source) {
|
||||
warning(PlatformLogger.processThrowable(throwable), level, source);
|
||||
}
|
||||
|
||||
@Deprecated @Override
|
||||
public void debug(String message) {
|
||||
forwardLog(message, Level.INFO, 10);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void error(Throwable throwable, @Range(from = 1, to = 10) int level, Class<?>... source) {
|
||||
error(PlatformLogger.processThrowable(throwable), level, source);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void error(String message, Throwable throwable, @Range(from = 1, to = 10) int level, Class<?>... source) {
|
||||
error(PlatformLogger.processThrowable(throwable, message), level, source);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void info(String message, @Range(from = 1, to = 10) int level, @NotNull Class<?>... source) {
|
||||
forwardLog(message, Level.INFO, level, source);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void warning(String message, @Range(from = 1, to = 10) int level, Class<?>... source) {
|
||||
forwardLog(message, Level.WARN, level, source);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void error(String message, @Range(from = 1, to = 10) int level, Class<?>... source) {
|
||||
forwardLog(message, Level.ERROR, level, source);
|
||||
}
|
||||
|
||||
private void forwardLog(String message, Level severity, int level, Class<?>... source) {
|
||||
ConfigManager configManager = RaycastedAntiESP.getConfigManager();
|
||||
if (LOG_TO_FILE) {
|
||||
queueFileLog(PlatformLogger.constructFileLogMessage(message, severity, level, source), severity);
|
||||
}
|
||||
if (configManager != null && configManager.getDebugConfig() != null) {
|
||||
DebugConfig debug = configManager.getDebugConfig();
|
||||
|
||||
if (debug.isExempted(getDebugSeverity(severity), source)) {
|
||||
return;
|
||||
}
|
||||
if (getLevel(severity, debug) < level) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
message = source != null ? PlatformLogger.constructMessage(message, source) : message;
|
||||
|
||||
switch (severity) {
|
||||
case INFO:
|
||||
logger.info(message);
|
||||
break;
|
||||
case WARN:
|
||||
logger.warning(message);
|
||||
break;
|
||||
case ERROR:
|
||||
logger.severe(message);
|
||||
break;
|
||||
default:
|
||||
logger.severe(message + "| Additionally, severity " + severity + " is not supported by the logger.");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void queueFileLog(String message, Level severity) {
|
||||
queuedFileMessages.addLast(message);
|
||||
|
||||
int queuedMessages = queuedFileMessageCount.incrementAndGet();
|
||||
if (queuedMessages >= MAX_QUEUED_MESSAGES_BEFORE_FLUSH) {
|
||||
flushToFile();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Flushes queued log messages to the log file asynchronously.
|
||||
*/
|
||||
public void flushToFile() {
|
||||
if (!LOG_TO_FILE) {
|
||||
return;
|
||||
}
|
||||
Bukkit.getAsyncScheduler().runNow(RaycastedAntiESP.get(), (ignored) -> {
|
||||
if (!writingToFile.compareAndSet(false, true)) return;
|
||||
|
||||
try {
|
||||
forceFlushToFileNow();
|
||||
} finally {
|
||||
writingToFile.set(false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Flushes queued log messages to the log file immediately, on the calling thread. Should only be used directly before shutdown to ensure all logs are flushed, or via <code>flushToFile()</code>.
|
||||
*/
|
||||
public void forceFlushToFileNow() {
|
||||
List<String> drainedMessages = new ArrayList<>();
|
||||
|
||||
String message;
|
||||
while ((message = queuedFileMessages.pollFirst()) != null) {
|
||||
queuedFileMessageCount.decrementAndGet();
|
||||
drainedMessages.add(message);
|
||||
}
|
||||
|
||||
if (drainedMessages.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
Files.write(
|
||||
logFilePath,
|
||||
drainedMessages,
|
||||
StandardCharsets.UTF_8,
|
||||
StandardOpenOption.CREATE,
|
||||
StandardOpenOption.APPEND
|
||||
);
|
||||
} catch (IOException exception) {
|
||||
/*
|
||||
* Put the messages back at the front of the queue so they are not lost.
|
||||
* Reverse order is needed because addFirst() is used.
|
||||
*/
|
||||
for (int index = drainedMessages.size() - 1; index >= 0; index--) {
|
||||
queuedFileMessages.addFirst(drainedMessages.get(index));
|
||||
queuedFileMessageCount.incrementAndGet();
|
||||
}
|
||||
|
||||
/*
|
||||
* Last-resort console error. Without this, file logging failures are silent.
|
||||
*/
|
||||
logger.severe("Failed to write queued log messages to " + logFilePath + ": " + exception.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package games.cubi.raycastedantiesp.paper;
|
||||
|
||||
import games.cubi.locatables.Locatable;
|
||||
import games.cubi.raycastedantiesp.core.raycast.ParticleSpawner;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Color;
|
||||
import org.bukkit.Particle;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public class PaperParticleSpawner implements ParticleSpawner {
|
||||
public void spawnParticleAt(Locatable locatable, Colour colour) {
|
||||
Objects.requireNonNull(Bukkit.getWorld(locatable.world())).spawnParticle(Particle.DUST, locatable.x(), locatable.y(), locatable.z(), 0, toBukkitDust(colour));
|
||||
}
|
||||
|
||||
private static final Particle.DustOptions RED_DUST = new Particle.DustOptions(Color.RED, 1);
|
||||
private static final Particle.DustOptions GREEN_DUST = new Particle.DustOptions(Color.GREEN, 1);
|
||||
private static final Particle.DustOptions BLUE_DUST = new Particle.DustOptions(Color.BLUE, 1);
|
||||
|
||||
private static Particle.DustOptions toBukkitDust(Colour colour) {
|
||||
return switch (colour) {
|
||||
case RED -> RED_DUST;
|
||||
case GREEN -> GREEN_DUST;
|
||||
case BLUE -> BLUE_DUST;
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package games.cubi.raycastedantiesp.paper;
|
||||
|
||||
import games.cubi.raycastedantiesp.core.Core;
|
||||
import games.cubi.raycastedantiesp.paper.commands.RaycastedAntiESPCommandBrigadier;
|
||||
import games.cubi.raycastedantiesp.paper.engine.PaperSimpleEngine;
|
||||
import games.cubi.raycastedantiesp.packetevents.config.PacketEventsBlockProcessorConfig;
|
||||
import games.cubi.raycastedantiesp.packetevents.view.PacketEventsBlockView;
|
||||
import games.cubi.raycastedantiesp.packetevents.view.PacketEventsEntityView;
|
||||
import games.cubi.raycastedantiesp.core.view.ViewRegistry;
|
||||
import games.cubi.raycastedantiesp.paper.packets.PaperPacketEventsBlockViewController;
|
||||
import games.cubi.raycastedantiesp.paper.packets.PaperPacketEventsEntityViewController;
|
||||
import games.cubi.raycastedantiesp.core.config.ConfigManager;
|
||||
import games.cubi.raycastedantiesp.paper.bStats.MetricsCollector;
|
||||
import games.cubi.logs.Logger;
|
||||
|
||||
import games.cubi.raycastedantiesp.paper.utils.FoliaTicker;
|
||||
import games.cubi.raycastedantiesp.paper.utils.PaperTicker;
|
||||
import io.papermc.paper.command.brigadier.CommandSourceStack;
|
||||
import io.papermc.paper.command.brigadier.Commands;
|
||||
import io.papermc.paper.plugin.lifecycle.event.types.LifecycleEvents;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.command.CommandExecutor;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.function.IntSupplier;
|
||||
import java.util.List;
|
||||
|
||||
public final class RaycastedAntiESP extends JavaPlugin implements CommandExecutor {
|
||||
private static ConfigManager config;
|
||||
private static PaperPacketEventsEntityViewController packetEventsController;
|
||||
private static PaperSimpleEngine engine;
|
||||
private static MetricsCollector metricsCollector;
|
||||
private static RaycastedAntiESP instance;
|
||||
private static PaperLoggerAdapter loggerAdapter;
|
||||
|
||||
public static final boolean isFolia = getClass("io.papermc.paper.threadedregions.RegionizedServer") != null;
|
||||
//todo: should probably rethink this entire class structure at some point. Too many static fields/methods. Also, a lot of the classes no longer need a reference to the main plugin class since Logger has been abstracted out and config could be given its own getter if needed
|
||||
{
|
||||
instance = this;
|
||||
loggerAdapter = new PaperLoggerAdapter(getLogger(), getDataPath().resolve("logs/" +System.currentTimeMillis()+ ".log"));
|
||||
Core.initialize(loggerAdapter);
|
||||
}
|
||||
|
||||
public static @Nullable Class<?> getClass(String className) {
|
||||
try {
|
||||
return Class.forName(className);
|
||||
} catch (ClassNotFoundException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onLoad() {
|
||||
config = ConfigManager.initialiseConfigManager(
|
||||
() -> getResource("config.yml"),
|
||||
getDataFolder().toPath(),
|
||||
List.of(PacketEventsBlockProcessorConfig.EXTENSION)
|
||||
);
|
||||
Plugin packetEvents = Bukkit.getPluginManager().getPlugin("packetevents");
|
||||
if (packetEvents == null) {
|
||||
throw new IllegalStateException("PacketEvents is required but was not found.");
|
||||
}
|
||||
Logger.info("PacketEvents detected.", 5);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
IntSupplier currentTickSupplier;
|
||||
if (isFolia) {
|
||||
Logger.info("Folia detected. Some features may not work as expected.", 5);
|
||||
currentTickSupplier = new FoliaTicker();
|
||||
}
|
||||
else {
|
||||
currentTickSupplier = new PaperTicker();
|
||||
}
|
||||
ViewRegistry.initialise(PacketEventsBlockView::new, PacketEventsEntityView::createEntityView, PacketEventsEntityView::createPlayerView);
|
||||
packetEventsController = new PaperPacketEventsEntityViewController(currentTickSupplier);
|
||||
new PaperPacketEventsBlockViewController(currentTickSupplier);
|
||||
|
||||
engine = new PaperSimpleEngine(this, config, currentTickSupplier);
|
||||
UpdateChecker.checkForUpdates(this, Bukkit.getConsoleSender());
|
||||
EventListener.initialise(this, engine, currentTickSupplier);
|
||||
|
||||
this.getLifecycleManager().registerEventHandler(LifecycleEvents.COMMANDS.newHandler(event -> {
|
||||
RaycastedAntiESPCommandBrigadier.register(event.registrar());
|
||||
}));
|
||||
//bStats
|
||||
metricsCollector = new MetricsCollector(this, config);
|
||||
/*
|
||||
Bukkit.getScheduler().scheduleSyncRepeatingTask(this, () -> {
|
||||
for (World world : Bukkit.getWorlds()) {
|
||||
Logger.debug("Printing bukkit info for world " + world.getName() + ": " + world.getLoadedChunks().length + " loaded chunks, " + world.getEntities().size() + " entities");
|
||||
for (Entity entity : world.getEntities()) {
|
||||
Logger.debug("Entity " + entity.getType() + " at " + entity.getLocation() + " with id " + entity.getEntityId() + " and uuid " + entity.getUniqueId() + " is tracked by " + parseTrackers(entity.getTrackedPlayers()));
|
||||
}
|
||||
}
|
||||
}, 1200, 1200);*/
|
||||
}
|
||||
|
||||
private String parseTrackers(Set<Player> trackers) {
|
||||
if (trackers.isEmpty()) return "no one";
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (Player tracker : trackers) {
|
||||
sb.append(tracker.getName()).append(", ");
|
||||
}
|
||||
if (sb.length() > 0) {
|
||||
sb.setLength(sb.length() - 2); // Remove trailing comma and space
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
metricsCollector.shutdown();
|
||||
loggerAdapter.forceFlushToFileNow();
|
||||
}
|
||||
|
||||
|
||||
public static ConfigManager getConfigManager() {
|
||||
return config;
|
||||
}
|
||||
public static PaperPacketEventsEntityViewController getPacketEventsController() {
|
||||
return packetEventsController;
|
||||
}
|
||||
public static PaperSimpleEngine getEngine() {
|
||||
return engine;
|
||||
}
|
||||
public static RaycastedAntiESP get() {
|
||||
return instance;
|
||||
}
|
||||
}
|
||||
Loaded 100 of 135 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user