Compare commits

...
1040 Commits
Author SHA1 Message Date
Cubicake 5b207a9ecd Update FUNDING.yml 2026-10-22 14:12:11 +10:30
Cubicake d90ac06a63 Merge remote-tracking branch 'origin/main' 2026-10-05 21:35:26 +10:30
Cubicake 77237fde49 Fix #94 2026-10-05 21:35:17 +10:30
Cubicake 40ae58b7ee Fix test 2026-10-05 21:32:14 +10:30
Cubicake 02c24527ef Don't hide sounds by default (not like this does anything rn) 2026-10-05 18:15:27 +10:30
Cubicake c9f374e074 Don't hide sounds by default (not like this does anything rn) 2026-10-05 18:05:14 +10:30
Cubicake 2cb0a46917 Merge pull request #95 from Cubicake/v2/more-config-reworking
Rework config
2026-10-05 18:01:26 +10:30
Cubicake d6818e579d fix submodules 2026-10-05 17:57:04 +10:30
Cubicake 807477712d Update pointers 2026-10-05 17:26:59 +10:30
Cubicake 6073e634c4 Finish config migration 2026-10-05 17:26:52 +10:30
Cubicake ad707b7158 Rebase 2026-10-05 17:26:42 +10:30
Cubicake 3ebb4a9138 Doc update 2026-10-05 17:25:33 +10:30
Cubicake ca8bb02010 Remove unused 2026-10-05 17:25:33 +10:30
Cubicake c393d502bd Match config entries to block data 2026-10-05 17:25:33 +10:30
Cubicake f032a12a66 Match config entries to block data 2026-10-05 17:25:33 +10:30
Cubicake fd343fc9b3 More transferring to idiomatic Configurate 2026-10-05 17:25:33 +10:30
Cubicake 21653da4f9 More transferring to idiomatic Configurate 2026-10-05 17:25:32 +10:30
Cubicake c42f008fa0 Begin transferring to idiomatic Configurate 2026-10-05 17:25:32 +10:30
Cubicake 1fcec23a57 Allow searching bukkit from console 2026-09-16 16:30:22 +09:30
Cubicake 37c905eb8c Remove unnecessary allocs 2026-09-07 18:05:45 +09:30
Cubicake 516b5df1d3 PrimitiveIntArrayList.remove does not mutate the provided array 2026-09-07 17:51:31 +09:30
Cubicake 914779f3e0 Remove utterly pointless overload 2026-09-07 17:49:22 +09:30
Cubicake 7c16afccb3 Remove unused EntityViewTransition and BlockViewTransition 2026-09-07 15:21:53 +09:30
Cubicake a49213e054 Remove unused constants 2026-09-07 15:04:29 +09:30
Cubicake 6877911210 Make it more compact 2026-09-07 14:59:53 +09:30
Cubicake 006ac0ba7a Update imports and move entity spawn tasks 2026-09-07 14:54:04 +09:30
Cubicake f92de7631b Move more util classes to games.cubi.util 2026-09-07 14:53:24 +09:30
Cubicake a6903ebffd Move more util classes to games.cubi.util 2026-09-07 11:52:14 +09:30
Cubicake d01e202401 Move util classes to games.cubi.util 2026-09-07 11:43:20 +09:30
Cubicake 71406b5803 Avoid allocating pointless arrays 2026-09-07 11:37:04 +09:30
Cubicake 30a9a73e25 PrimitiveIntArrayList.toString() is already null-guarded 2026-09-07 11:20:01 +09:30
Cubicake e982cb4550 probably pointless but why not make this private 2026-09-06 19:53:55 +09:30
Cubicake 37514fa879 Remove unused and misleading method 2026-09-06 17:48:54 +09:30
Cubicake 6eee4351ab ImplementationRegistry 2026-09-06 17:02:23 +09:30
Cubicake 1f0cb15714 Disable block chunk parsers since they currently use more memory and cpu for no gain. 2026-09-06 16:53:44 +09:30
Cubicake 367976e51f StrokkCommands 2.3.0: Nicer benchmark command syntax 2026-09-02 21:52:38 +09:30
Cubicake c4c3c498c2 Bump StrokkCommands 2026-09-01 22:54:54 +09:30
Cubicake c29667aae0 Make copyright headers more readable 2026-08-31 19:19:46 +09:30
Cubicake 558e773085 Make copyright headers more readable 2026-08-31 19:11:50 +09:30
Cubicake 30b123ba3c Cache a player data array 2026-08-30 16:31:25 +09:30
Cubicake 87fd94baf4 Rename getInstance to get 2026-08-30 13:44:18 +09:30
Cubicake 1e5a4eb95b Merge remote-tracking branch 'origin/main' 2026-08-28 21:43:36 +09:30
Cubicake 981b375d6d This way even if you leave a trailing "." it resolves correctly (resolves #90) 2026-08-28 21:43:11 +09:30
Cubicake 6de11030b0 Bump version 2026-08-26 21:04:42 +09:30
Cubicake d445aa58ba Resolve #88 for blocks too 2026-08-25 20:08:32 +09:30
Cubicake 49311be791 Properly precompute hideOnSpawnDistanceSquared 2026-08-25 19:53:19 +09:30
Cubicake 0b4df5124b Do not send unrelated packets in a bundle (#88) 2026-08-25 19:52:45 +09:30
Cubicake 4435058373 Do not send unrelated packets in a bundle (#88) 2026-08-25 19:46:20 +09:30
Cubicake 4dfed55d48 Add clientVisible tracking 2026-08-23 14:56:47 +09:30
Cubicake c2b6941922 Add clientVisible tracking 2026-08-23 14:51:49 +09:30
Cubicake feb80bf678 Update submodules 2026-08-23 11:41:25 +09:30
Cubicake c4fd919a08 Update submodules 2026-08-22 12:18:26 +09:30
Cubicake 40f91482d4 Don't step into the final block 2026-08-22 12:13:49 +09:30
Cubicake 3f82330433 Match the other change 2026-08-21 19:24:16 +09:30
Cubicake 8cfe2b0a2e Mark barrier as non-occluding 2026-08-21 19:05:04 +09:30
Cubicake f2c1d01051 Don't count the block it first hits as solid 2026-08-21 17:59:50 +09:30
Cubicake e1d0db9d5f oops 2026-08-21 17:51:46 +09:30
Cubicake a86a9bc4c0 Merge remote-tracking branch 'origin/main' 2026-08-21 17:46:06 +09:30
Cubicake 377c12a00a Final cleanup 2026-08-21 17:45:45 +09:30
Cubicake 9bc14b2097 Slightly faster; less arithmetic 2026-08-21 17:37:41 +09:30
Cubicake 02f9df6643 Simplify and seal code 2026-08-21 17:29:00 +09:30
Cubicake e2af9f65c1 Remove unused param 2026-08-21 17:21:58 +09:30
Cubicake 0eb1766a4a Switch to faster method for everything 2026-08-21 17:21:29 +09:30
Cubicake 4a3f25045f Add AsyncEngine class to log
#86
2026-08-21 14:27:48 +09:30
Cubicake 0c80348416 Do not log every npc/hologram spawn
#86
2026-08-21 14:21:10 +09:30
Cubicake 4295d2fe8a Better benchmarking 2026-08-20 22:20:39 +09:30
Cubicake 3f8ccff505 It gets even faster somehow 2026-08-20 22:20:21 +09:30
Cubicake bc440490f9 Reduce division ops 2026-08-20 17:11:02 +09:30
Cubicake 5527e38ea4 Actually no-alloc now (faster too) 2026-08-17 23:00:27 +09:30
Cubicake 244fde97c0 Merge remote-tracking branch 'origin/main' 2026-08-16 20:49:37 +09:30
Cubicake 8b3a62f1f5 So so much easier to read, same perf (well 2ns slower in testing but probably run-to-run variance) 2026-08-16 20:48:09 +09:30
Cubicake 45d0e0581c Update README.md 2026-08-15 17:37:06 +09:30
Cubicake aa7934f258 Rewrite existing configs to set it to false 2026-08-13 17:26:56 +09:30
Cubicake cfdb255b56 Set sound-effect check to false by default 2026-08-13 16:54:42 +09:30
Cubicake 14e6aaaae6 Might as well keep this debugging code in case future issues occur (Added to diagnose RoseStacker issue) 2026-08-13 16:54:11 +09:30
Cubicake d7cc7abd8c Cover all run types 2026-08-13 16:51:28 +09:30
Cubicake 73e58e191e oops 2026-08-13 16:48:38 +09:30
Cubicake e5a591af1a Add worldless particle spawn 2026-08-11 17:27:31 +09:30
Cubicake 9951b5d7a1 Add licence header to every class 2026-08-10 16:57:09 +09:30
Cubicake e99c3b9de2 Change default only-check-sneaking to minimise noticeability of running this plugin 2026-08-09 21:18:27 +09:30
Cubicake 0500f4bd5f So it turns out that using the connection with initialised timeouts is the smart thing to do 2026-08-09 20:17:45 +09:30
Cubicake 9a841308ff Bump ver 2026-08-09 16:21:08 +09:30
Cubicake c4bf1cbf0b Citizens compat 2026-08-09 13:24:24 +09:30
Cubicake db22c675db Restore usual raycasting for now 2026-08-09 13:23:09 +09:30
Cubicake 5a42fd74ad optimise 2026-08-08 22:05:02 +09:30
Cubicake 85b788742c Update CONTRIBUTING.md 2026-08-07 19:03:29 +09:30
Cubicake 20f660b8a3 Splitting was inefficient 2026-08-06 10:20:51 +09:30
Cubicake 4d17483a5a Use floats 2026-08-06 09:32:12 +09:30
Cubicake 274b081c78 Add solid check 2026-08-05 22:34:10 +09:30
Cubicake 45e14637e0 Separate debug path 2026-08-05 22:17:22 +09:30
Cubicake b007735636 About 18% faster raycasting 2026-08-05 22:04:16 +09:30
Cubicake bb7275a618 Add chunk section stuff 2026-08-05 22:04:04 +09:30
Cubicake 853fa1531a Tests 2026-08-05 17:09:12 +09:30
Cubicake 396382bcc2 Add pose enum 2026-08-05 17:09:06 +09:30
Cubicake aae6bdb53c Add playerlocatable 2026-08-05 17:07:36 +09:30
Cubicake 2f8f698069 Merge remote-tracking branch 'origin/main' 2026-08-04 17:44:08 +09:30
Cubicake fc3badb90a Make PlayerRegistry final 2026-08-04 17:43:30 +09:30
Cubicake 7aab3b60e8 Consider not overwriting configs 2026-08-04 16:31:33 +09:30
Cubicake 2ab157bd4a Merge remote-tracking branch 'origin/main' 2026-08-02 22:19:06 +09:30
Cubicake 3227c63e2e Remove unused imports 2026-08-02 22:18:46 +09:30
Cubicake 1dc77b3e6f Prepend comment to top of file 2026-08-02 21:25:23 +09:30
Cubicake cb044f789d Add link to config doc 2026-08-02 19:28:13 +09:30
Cubicake c110aab634 Update usecases 2026-08-02 17:37:34 +09:30
Cubicake 5d407afbdf Add retrying 2026-08-02 15:40:20 +09:30
Cubicake a8f12c9a24 Change defaults 2026-08-02 15:01:57 +09:30
Cubicake 0e4c251c6c Fix typo 2026-08-02 14:55:05 +09:30
Cubicake e2b598a361 Don't flush 2026-08-02 14:50:19 +09:30
Cubicake 8c140cf8b6 Update leafpile 2026-08-02 14:40:30 +09:30
Cubicake 4fe9ab02ef Reduce allocations when sending block changes 2026-08-02 14:40:06 +09:30
Cubicake a21102d04f Use striped sets and place in utils 2026-08-02 14:18:39 +09:30
Cubicake 22488e9e71 Fix fancycompat logs 2026-08-02 14:18:17 +09:30
Cubicake bc40438cb3 Remove unused set 2026-08-02 13:50:23 +09:30
Cubicake 3f633710e7 Merge pull request #77 from Cubicake/v2/glowing-sneaking
Exempt all glowing entities and add a config to only check sneaking players
2026-08-01 23:02:58 +09:30
Cubicake 8de5d53198 idk 2026-08-01 23:02:40 +09:30
Cubicake 53650f9b63 Remove stupid test 2026-08-01 22:59:52 +09:30
Cubicake ba812bce3a Default to true to minimise intrusion on vanilla 2026-08-01 22:49:17 +09:30
Cubicake 42932abaa5 Prioritise skipping visible recheck -1, and tidy up 2026-08-01 22:22:02 +09:30
Cubicake 290749dde8 Exempt glowing entities and non-sneaking players when configured to exempt non-sneaking players 2026-08-01 22:22:01 +09:30
Cubicake e19808fb4b Remove stupid test 2026-08-01 22:22:01 +09:30
Cubicake 691d429652 Document visible-recheck-interval-ticks 2026-08-01 22:22:01 +09:30
Cubicake 1575091d12 Implement metadata packet scanning 2026-08-01 22:22:01 +09:30
Cubicake 4919383c73 Tests 2026-08-01 22:22:01 +09:30
Cubicake 5293db6c86 Add only-check-sneaking player config option 2026-08-01 22:22:01 +09:30
Cubicake c5f17a7b12 Add glowing and sneaking state storage 2026-08-01 22:22:01 +09:30
Cubicake ddafbd0c25 Old todo: no longer relevant 2026-08-01 22:22:01 +09:30
Cubicake 8d9a354154 Merge pull request #76 from Cubicake/v2/optimise
More optimisations
2026-08-01 22:21:14 +09:30
Cubicake 64bfcccde5 Use consumers 2026-08-01 22:20:05 +09:30
Cubicake e91dc4647d Everything else 2026-08-01 21:58:59 +09:30
Cubicake 96601efed5 showing entities from the netty thread without enqueueing 2026-08-01 21:53:35 +09:30
Cubicake c63a194ea9 Clear specific things 2026-08-01 21:48:23 +09:30
Cubicake 71cde26cb9 Directly dispatch mode change fixes 2026-08-01 21:45:03 +09:30
Cubicake 33ab1cd234 Add timeouts 2026-08-01 21:24:48 +09:30
Cubicake e1c96d87ff Update leafpile 2026-08-01 20:37:02 +09:30
Cubicake 3d8686e1ae Add transition queues 2026-08-01 20:22:23 +09:30
Cubicake 971a648ad8 Merge branch 'main' into v2/optimise 2026-08-01 15:52:43 +09:30
Cubicake b0f05eaf4f Update locatables 2026-08-01 15:52:24 +09:30
Cubicake bc9fcd6d7a Exclude toml files 2026-08-01 15:50:24 +09:30
Cubicake a631c57465 No object allocation pre-raycasting 2026-08-01 15:50:24 +09:30
Cubicake 9f9fb7f021 Do not allocate a string concat each time: this is a hot method 2026-08-01 15:50:23 +09:30
Cubicake 903e7c84bc No object allocation raycasting 2026-08-01 15:50:23 +09:30
Cubicake ae75c37d90 Move tick dispatch responsibility to the tickers 2026-07-31 15:36:55 +09:30
Cubicake 17f5040c49 Switch to weaker folia visibility 2026-07-31 15:08:39 +09:30
Cubicake c04cf7558e Refactor HackyEntityIDGuard and edit jd 2026-07-31 15:01:06 +09:30
Cubicake 11358badac Fix priority 2026-07-31 14:35:33 +09:30
Cubicake 008e62eee2 Refactor 2026-07-31 14:33:20 +09:30
Cubicake 409261000e Merge pull request #73 from UsainSrht/v2/update-checker-config
update checker toggles
2026-07-30 21:52:48 +09:30
Cubicake 4854b1f88b Merge remote-tracking branch 'UsainSrht/v2/update-checker-config' into fork/UsainSrht/v2/update-checker-config
# Conflicts:
#	platform-paper/src/main/java/games/cubi/raycastedantiesp/paper/EventListener.java
2026-07-30 21:51:34 +09:30
Cubicake e384ea0775 Spelling 2026-07-30 21:50:00 +09:30
Hüseyin Serhat Han 61df3f4f2d remove brackets 2026-07-30 21:50:00 +09:30
UsainSrht 9f3eec6f09 update checker toggles 2026-07-30 21:49:52 +09:30
Cubicake 4361276070 Spelling 2026-07-30 21:48:17 +09:30
Cubicake 5d852cd6d3 Merge pull request #74 from Cubicake/v2/entity-type
V2/entity type
2026-07-30 21:44:45 +09:30
Cubicake 2b2c7b9108 huh I didn't know this 2026-07-30 21:43:13 +09:30
Cubicake 93949b7906 Bump version 2026-07-30 21:18:54 +09:30
Cubicake cee4d4b6f9 Remaining changes 2026-07-30 21:18:33 +09:30
Cubicake 9fed35527d Make self entity sentinel closer to 0 2026-07-30 19:19:59 +09:30
Cubicake d101ba9b99 Add bypass hooks 2026-07-30 18:32:04 +09:30
Cubicake 4527a9dd02 Remove debugging messages 2026-07-30 18:29:54 +09:30
Cubicake 8aefd39d65 Implement fancy compat 2026-07-30 18:28:50 +09:30
Cubicake ccbed56a99 For viewing modern sources 2026-07-29 16:45:19 +09:30
Cubicake 5e4692c753 Nullability JD 2026-07-29 14:10:05 +09:30
Cubicake 5d05ac00b7 Add info comment 2026-07-28 21:55:05 +09:30
Cubicake 7d611ffdcb Mark entities as despawned once they are despawned 2026-07-28 21:54:20 +09:30
Cubicake f3ff087874 Add justifying comment 2026-07-28 21:54:02 +09:30
Cubicake a11711e06f Update README.md 2026-07-28 17:52:06 +09:30
Hüseyin Serhat Han 30286928b2 remove brackets 2026-07-28 08:56:29 +03:00
Cubicake 5fdf26f624 Unhinged method but it'll work 2026-07-27 19:39:48 +09:30
Cubicake f72da61436 Falling block 2026-07-27 17:03:15 +09:30
Cubicake 980cc33e7b Merge remote-tracking branch 'origin/v2/entity-type' into v2/entity-type
# Conflicts:
#	core/src/main/java/games/cubi/raycastedantiesp/core/engine/AsyncEngine.java
2026-07-26 19:26:36 +09:30
Cubicake d873c7b1ff Skip when attached to always visible entity 2026-07-26 19:24:24 +09:30
Cubicake f67b0b2ae7 Guard against adding leashed entities into the array repeatedly 2026-07-26 19:20:13 +09:30
Cubicake c047ed08e1 Keep a registry of all entity IDs which correspond to an entity which should not be tracked. 2026-07-26 19:17:27 +09:30
Cubicake e886efa823 Resolve excluded entity types to ints 2026-07-26 19:10:42 +09:30
Cubicake 740974f17c Formatting 2026-07-26 19:08:03 +09:30
Cubicake f38bda6993 Add excluded entities config 2026-07-26 19:05:49 +09:30
Cubicake 61e7cac35f CopyOnWriteMTIntSet tests 2026-07-26 17:45:28 +09:30
Cubicake 8f61e203f8 Rename int sets 2026-07-26 14:06:02 +09:30
Cubicake 751398eaaa Add removal methods 2026-07-26 14:02:27 +09:30
UsainSrht 736ccab3e0 update checker toggles 2026-07-25 22:44:35 +03:00
Cubicake 32a8d92df4 Add some comments 2026-07-25 12:03:44 +09:30
Cubicake af0d887e14 Store entity type as primitive 2026-07-23 18:54:21 +09:30
Cubicake f32c8ec9fa Add int sets 2026-07-23 18:25:04 +09:30
Cubicake 858c4d4340 Add UUID path without going through bukkit for packet-based entities. 2026-07-23 10:24:37 +09:30
Cubicake 274d437525 Store entity type as primitive 2026-07-22 21:18:33 +09:30
Cubicake c610bc42a6 Merge pull request #70 from Cubicake/v2/rename-engine
Rename SimpleEngine to AsyncEngine
2026-07-22 20:47:39 +09:30
Cubicake ae8905ed46 Rename debug messages 2026-07-22 20:42:12 +09:30
Cubicake dcaed38f4d Rename field 2026-07-22 20:41:30 +09:30
Cubicake 512a4db255 Make it an explicit alias 2026-07-22 20:39:18 +09:30
Cubicake 4fd8954fea Merge remote-tracking branch 'origin/main' 2026-07-22 20:23:53 +09:30
Cubicake 1b5db5edca Rename config
Not going to bother with config transfer
2026-07-22 20:22:18 +09:30
Cubicake a08a477176 SimpleEngine should be called AsyncEngine 2026-07-22 20:17:04 +09:30
Cubicake f4f3ca4d63 Merge pull request #69 from Cubicake/v2/restore-bstats
Restore custom bstats
2026-07-22 20:14:31 +09:30
Cubicake ab537e777b Don't use same chart id 2026-07-22 20:14:11 +09:30
Cubicake 02938e3b57 Mutating is good 2026-07-22 20:01:48 +09:30
Cubicake e4b488eb69 idk what these even are 2026-07-21 22:01:28 +09:30
Cubicake e55b685ce2 Restore server size and entity count metrics. Add basic wiring for metrics for other configs. 2026-07-21 22:01:20 +09:30
Cubicake 6fd6d9bc04 Expose these configs for later 2026-07-21 21:46:49 +09:30
Cubicake d1244be5d1 I know how to use shadowJar now actually 2026-07-21 21:46:30 +09:30
Cubicake dd9db4211d Add size api 2026-07-21 21:42:21 +09:30
Cubicake 162bd3cf20 Bump version 2026-07-20 21:23:53 +09:30
Cubicake f78c3d1243 Remove obsolete Locatables gitlink 2026-07-20 21:20:36 +09:30
Cubicake 3feff5eb8a Merge branch 'refs/heads/v2/keep-client-entity-when-hidden' 2026-07-20 21:17:05 +09:30
Cubicake a47dcb94a8 Add new keep-client-entity-when-hidden option 2026-07-20 21:15:56 +09:30
Cubicake 65b6dbc44a Fix debug command 2026-07-20 19:48:13 +09:30
Cubicake a87a403e2d Whatever these are 2026-07-20 19:14:06 +09:30
Cubicake ddfb1748f7 Timings 2026-07-20 19:13:57 +09:30
Cubicake c4669494b4 Downgrade memory strictness 2026-07-20 19:12:22 +09:30
Cubicake d340702530 Prevent ABA visibility issues 2026-07-20 19:11:47 +09:30
Cubicake fd8aa8a82a Acquire/Release 2026-07-20 19:05:58 +09:30
Cubicake 39f17f92a5 Add thread JD notes 2026-07-20 18:57:02 +09:30
Cubicake f47ef79707 Use VarHandler 2026-07-20 18:56:23 +09:30
Cubicake f8a3f09c07 Opaque tick reads and writes 2026-07-20 18:55:34 +09:30
Cubicake 18c8dd11f5 Single threaded 2026-07-20 18:54:34 +09:30
Cubicake 7fccdb6e53 VarHandler 2026-07-20 18:54:16 +09:30
Cubicake 769c13db81 VarHandler and opaque/acquire 2026-07-20 18:45:41 +09:30
Cubicake 65bdc8fa7d Opaque 2026-07-20 18:36:21 +09:30
Cubicake f94c2053eb Use acquire/release instead of volatile mode token checks 2026-07-20 18:28:44 +09:30
Cubicake 7cb16521a2 Palette size is only read from inside this class, and on the netty thread 2026-07-20 18:10:28 +09:30
Cubicake 4dff4245f0 Use VarHandler 2026-07-20 18:04:56 +09:30
Cubicake 5472af1191 Add VarHandler 2026-07-20 17:35:38 +09:30
Cubicake a7d2c953bc PlayerClientLoadedWorldEvent fires on every world change 2026-07-20 16:31:41 +09:30
Cubicake f565ea0fe1 Refactor: not locatables anymore 2026-07-20 15:40:10 +09:30
Cubicake b4430b70df Add a removed tile entity sentinel value 2026-07-20 15:37:30 +09:30
Cubicake 28b3cff770 Switch to char to represent blocks 2026-07-20 15:15:49 +09:30
Cubicake 1d4f452098 Merge remote-tracking branch 'origin/main' 2026-07-20 15:07:46 +09:30
Cubicake 2e7d35bc1a I don't even read the tests ngl 2026-07-20 15:07:35 +09:30
Cubicake 1be44580c0 Use epochs and update to spatials 2026-07-20 15:07:18 +09:30
Cubicake a0aba0d37b Use epochs 2026-07-20 15:06:32 +09:30
Cubicake 1cc87b5b9e Use epochs 2026-07-20 15:06:05 +09:30
Cubicake dfcfe3576f Use epochs 2026-07-20 14:52:34 +09:30
Cubicake 1d15c21200 Remove unnecessary comments 2026-07-20 14:50:15 +09:30
Cubicake c56aab576b Pass epoch everywhere and use spatials 2026-07-20 14:45:50 +09:30
Cubicake c73b9abb6e Validate entity transition epochs before sending, and include a reference to the actual entity instead of doing a lookup 2026-07-20 14:38:42 +09:30
Cubicake 9e9d880691 New method signature 2026-07-20 14:34:31 +09:30
Cubicake 2773b98ef1 Wire the world epoch 2026-07-20 14:32:19 +09:30
Cubicake 5f7a247224 Create incrementing world epoch counter to ensure changes do not apply across worlds 2026-07-20 14:25:47 +09:30
Cubicake ae852ae4c7 Clear self entity data 2026-07-19 20:09:15 +09:30
Cubicake 0325ee118e Null guard 2026-07-19 19:58:25 +09:30
Cubicake 55ba8e5b9e Update README 2026-07-19 19:54:41 +09:30
Cubicake c7705d8217 Merge remote-tracking branch 'origin/main' 2026-07-19 19:46:35 +09:30
Cubicake 94ea345614 Revert "huh?"
This reverts commit 5ebfb36f4b.
2026-07-19 19:46:01 +09:30
Cubicake 5ebfb36f4b huh? 2026-07-19 19:45:25 +09:30
Cubicake 4770f22770 Rename stuff 2026-07-19 19:05:25 +09:30
Cubicake 6451771f1d Rename NettyEntityLocatable to NettyEntity, make it extend TrackedEntity 2026-07-19 18:57:44 +09:30
Cubicake 038768adda Make NettyTileEntity extend Spatial and TrackedTileEntity 2026-07-19 18:57:01 +09:30
Cubicake e5338bbc34 Rename EntityLocatable and make it spatial 2026-07-19 15:35:01 +09:30
Cubicake cfbb6a54aa Rename TileEntityLocatable and make it spatial 2026-07-19 15:34:08 +09:30
Cubicake 89a2a1cf32 Bump version for refactor 2026-07-19 15:31:58 +09:30
Cubicake 955e24da66 (Bad) tests 2026-07-19 15:31:48 +09:30
Cubicake 152dcbc4db More default implementations 2026-07-19 15:29:29 +09:30
Cubicake 04d85e843a Bump to see if this fixes issues 2026-07-18 22:53:24 +09:30
Cubicake fb28453f4f Finish update to new locatables system 2026-07-18 22:48:25 +09:30
Cubicake 53a60be932 Once again update locatables 2026-07-18 20:58:27 +09:30
Cubicake 284233e1b2 Switch to spatials for RaycastUtil 2026-07-18 20:58:16 +09:30
Cubicake 6e2a110380 No such method anymore 2026-07-18 20:29:20 +09:30
Cubicake dddbaee001 It will work fine, but it's cleaner this way 2026-07-18 20:28:44 +09:30
Cubicake 958756df2d Begin moving to new locatables system by fixing imports and updating reference to locatables 2026-07-18 20:14:15 +09:30
Cubicake 371c9c8155 Merge pull request #68 from Cubicake/v2/optimise
V2/optimise
2026-07-18 20:04:05 +09:30
Cubicake 3f212e8766 These tests are a real vibe 2026-07-14 19:02:46 +09:30
Cubicake 4f086b4d6a New params 2026-07-14 19:02:10 +09:30
Cubicake b97d938425 Use the new chunk parsers 2026-07-14 19:01:51 +09:30
Cubicake f93723a0a4 oops this should've been committed already 2026-07-14 18:37:40 +09:30
Cubicake 93e0b54ff4 Columns are always full 2026-07-14 18:37:14 +09:30
Cubicake e77d450053 Pass the tile entity object to remove pointless lookups 2026-07-14 18:35:27 +09:30
Cubicake 50acc8e66c Return the tile entity 2026-07-14 18:34:37 +09:30
Cubicake fea6800269 Parser impls 2026-07-14 18:33:07 +09:30
Cubicake 9e742e62b5 Somewhat optimised 2026-07-14 18:32:53 +09:30
Cubicake 0ab820fcd9 Create an abstract chunk parser 2026-07-14 18:15:03 +09:30
Cubicake b07de426a4 Add methods now in AbstractBlockView 2026-07-14 17:02:04 +09:30
Cubicake 316c2ec10f Mark changing tile entity enabled status during runtime as supported 2026-07-14 17:01:29 +09:30
Cubicake a7465f9d59 AbstractChunkData has two generics now 2026-07-14 17:00:49 +09:30
Cubicake 332f0becb4 Polymorphic chunk data 2026-07-14 16:57:55 +09:30
Cubicake 3cc6b43999 Pass mode token into tile check 2026-07-14 16:39:40 +09:30
Cubicake d8daf0dd7a Track the exact tile entity being changed, and invalidate changes from a previous enabled cycle 2026-07-14 16:36:43 +09:30
Cubicake b189e576c0 Add NEVER_CHECKED sentinel 2026-07-14 16:36:03 +09:30
Cubicake 165f30e339 Make NettyTileEntity an InvasivelyLinkedSWMRList 2026-07-14 16:35:44 +09:30
Cubicake 5d00ae3a02 Add forEachValueSummed method to SWMRInt2ObjectHashTable 2026-07-14 16:34:52 +09:30
Cubicake d04a0903bd Rework AbstractBlockView 2026-07-14 16:34:29 +09:30
Cubicake 50d1d359c4 Create InvasivelyLinkedSWMRList 2026-07-14 14:23:37 +09:30
Cubicake 3e33722426 Pass objects, not primitive arrays 2026-07-11 22:20:39 +09:30
Cubicake 84eb5fc888 Move BlockInfoResolver interface to core 2026-07-11 22:12:24 +09:30
Cubicake 2923125933 Chunk section storage using SWMR 2026-07-09 15:39:06 +09:30
Cubicake 812ef94284 Bump version 2026-07-08 21:32:23 +09:30
Cubicake e47f788086 I take no responsibility for these tests 2026-07-08 21:31:55 +09:30
Cubicake 254c86919b Completely redo update checker for new system 2026-07-08 21:28:15 +09:30
Cubicake d42ab704d6 Upgrade class visibility, implement Comparator, and throw instead of logging 2026-07-08 19:39:42 +09:30
Cubicake f226b53bb0 Support Folia/Canvas 2026-07-08 16:54:35 +09:30
Cubicake 400a5b96eb Not sure why but my laptop got very confused 2026-07-08 16:47:32 +09:30
Cubicake e1d737c67b WIP polymorphic 2026-07-08 15:11:30 +09:30
Cubicake 6c5fcc35e8 Add lightweight Solid impl 2026-07-08 14:22:13 +09:30
Cubicake a2094ebac5 Switch to using ChunkData 2026-07-07 22:43:16 +09:30
Cubicake 3250ea4b33 Add interfaces 2026-07-07 22:39:25 +09:30
Cubicake df6537b12d Bitmath hurts my head 2026-07-07 22:35:57 +09:30
Cubicake 7a5794efee No clue why Locatables reference has changed 2026-07-07 22:35:21 +09:30
Cubicake 89c07d5b53 WIP 2026-07-07 22:34:34 +09:30
Cubicake 15132e4825 Check against client visibility 2026-07-06 22:31:17 +09:30
Cubicake db48f8fe08 Clear tile entity nbt on update
I think this is correct, maybe it'll turn out to be wrong
2026-07-05 22:18:28 +09:30
Cubicake 6dfb7c3715 Temp better int parsing before I rewrite this all 2026-07-05 22:17:47 +09:30
Cubicake 9fc793b761 These values do nothing at -1 2026-07-05 22:13:19 +09:30
Cubicake 160597a5a0 Mark git properties as inputs 2026-07-05 21:45:09 +09:30
Cubicake 75957b9081 Guard tasks throwing 2026-07-05 18:54:48 +09:30
Cubicake da344c7962 Specify java version 2026-07-05 17:27:18 +09:30
Cubicake ba08b02975 Refactor: Move locatables to separate git project. No changes to compiled binary except for build-properties. 2026-07-05 16:25:06 +09:30
Cubicake 328de7f129 Merge pull request #63 from Cubicake/v2/optimise
Use LeafPile and correct threading
2026-07-04 22:05:16 +09:30
Cubicake c814e1e0b6 Bump version 2026-07-03 17:29:49 +09:30
Cubicake 50b259ed5b Make sure test can't be JIT optimised away 2026-07-01 21:57:59 +09:30
Cubicake f7d21a716d Use SWMRHashTable for lock-free work 2026-06-29 19:56:16 +09:30
Cubicake ce8ce72151 Bump version 2026-06-28 17:22:21 +09:30
Cubicake 02253fd487 Turns out ConcurrentHashMap is better; Also entityUUIDsByID is accessed from netty thread only so it can be a fastutil map 2026-06-28 17:21:33 +09:30
Cubicake b5540006e3 Move null state guard here 2026-06-28 16:08:58 +09:30
Cubicake 344f259f95 Remove unused import 2026-06-28 16:05:13 +09:30
Cubicake 331310ddd1 Don't do unnecessary lookups 2026-06-28 16:02:55 +09:30
Cubicake d35adc6f5f Don't do unnecessary lookups 2026-06-28 15:22:46 +09:30
Cubicake 8afb1d10e9 Bump minimum supported version and use PlayerClientLoadedWorldEvent as it is after the play-phase join packet. This also requires guarding for null world in engine 2026-06-28 14:05:50 +09:30
Cubicake e963a69f64 Create NettyData inside PlayerData, and just mark PlayerData as disconnected so that engine threads ticking the object don't break 2026-06-28 13:32:36 +09:30
Cubicake d66bf182b9 Skip already visible entities to prevent duplicate packets 2026-06-28 13:27:14 +09:30
Cubicake ea36d636e9 Move player registration to play phase only and handle disconnect from netty 2026-06-28 13:26:50 +09:30
Cubicake d3a2b43ba3 Make self entity fields final 2026-06-28 13:23:09 +09:30
Cubicake 26ce1ff826 Don't handle PlayerData lifecycle from main thread 2026-06-28 13:21:56 +09:30
Cubicake 563f19e4a3 Remove unused import 2026-06-28 13:17:46 +09:30
Cubicake bdf22111ad Mark fields volatile 2026-06-28 13:17:32 +09:30
Cubicake b4e65f9653 Add thread guards for netty thread 2026-06-28 13:13:31 +09:30
Cubicake de3ddd88da Use SWMR and MTQueue 2026-06-28 12:50:41 +09:30
Cubicake d5a55ef393 Update leafpile and include it in PE module 2026-06-28 12:22:09 +09:30
Cubicake 7dd2d204ce Include ParallelepipedLeafPile 2026-06-28 12:03:46 +09:30
Cubicake b3a418482b Update default configs 2026-06-27 18:39:53 +09:30
Cubicake 77c391996e Update README for raised minimum version 2026-06-27 18:31:18 +09:30
Cubicake 5d3fbb92a0 Bump minimum supported version to 1.21 2026-06-27 18:05:41 +09:30
Cubicake 30e26de415 Build against the lowest supported version and bump version 2026-06-27 18:00:05 +09:30
Cubicake ff7e71087b Don't use assertion 2026-06-27 17:57:23 +09:30
Cubicake 9221ea87fa Prevent NPE due to unregistering on a different thread 2026-06-27 17:56:20 +09:30
Cubicake e72440051c Update CubiLogging
- Fix gitignore
2026-06-27 17:42:35 +09:30
Cubicake 7edf021f33 Make self-attached entities always visible 2026-06-27 17:41:23 +09:30
Cubicake e785d2c7d3 Clean up world change stuff 2026-06-27 17:40:46 +09:30
Cubicake 6b3177175f Update CubiLogging 2026-06-27 17:38:45 +09:30
Cubicake d90f3e4389 Don't let entities attached to the player become hidden 2026-06-26 17:12:15 +09:30
Cubicake f733ee6ff6 Allow setting visibility using the NettyEntityLocatable object rather than just a UUID 2026-06-26 17:10:38 +09:30
Cubicake 868b41ea02 Remove stale UUID references 2026-06-24 22:39:01 +09:30
Cubicake 3076fccbea Implement the Consumer method 2026-06-24 22:38:48 +09:30
Cubicake f637ac5607 Switch to the Consumer methods 2026-06-24 22:37:27 +09:30
Cubicake da8db38d51 Make IDE happy 2026-06-24 22:36:16 +09:30
Cubicake cf92d3817b Don't cache packets for the player 2026-06-24 22:35:56 +09:30
Cubicake dac5d8597d Schedule messages to the right audience. I doubt this matters in practice, but might as well. 2026-06-24 22:33:53 +09:30
Cubicake e0029df844 Add tracking of self entity to netty data, previous world entity id tracking 2026-06-24 22:27:48 +09:30
Cubicake 07865ea73b Switch views to a consumer method 2026-06-24 22:06:05 +09:30
Cubicake 0622ad6f83 Handle null packet replay data 2026-06-24 21:58:35 +09:30
Cubicake 33863642de JD clarity 2026-06-24 21:06:45 +09:30
Cubicake 0c22c40d3e This should've been moved out of staging ages ago 2026-06-24 20:42:01 +09:30
Cubicake 4e9d88dc08 Fix disabling recheck not being a thing 2026-06-24 20:37:20 +09:30
Cubicake a2a96a3353 Merge pull request #60 from Cubicake/v2/optimise
Optimise a bunch of stuff
2026-06-24 16:44:36 +09:30
Cubicake e4c8ac11dc Bump version 2026-06-21 17:51:12 +09:30
Cubicake fda6d08e9a Use packet world data and migrate duplicated view controller code to common 2026-06-21 17:45:22 +09:30
Cubicake db7032b5b2 Rework common view controller to handle worlds 2026-06-21 17:38:17 +09:30
Cubicake a46746d5cf Misc import cleaning 2026-06-21 17:37:52 +09:30
Cubicake 35a42a49a9 Significantly reduce netty thread load 2026-06-21 14:55:16 +09:30
Cubicake cf953eb3c8 Merge branch 'main' into v2/optimise 2026-06-21 14:52:01 +09:30
Cubicake 92f4b9ac45 Merge pull request #59 from Cubicake/v2/tick-timing
Implement timing of ticks
2026-06-21 14:31:34 +09:30
Cubicake b0f0e1a8f5 Fail safe 2026-06-21 13:09:49 +09:30
Cubicake ca9da23ceb Use int status states for atomic updating 2026-06-21 12:58:47 +09:30
Cubicake 25295627cc Prevent pointless scheduling 2026-06-20 22:49:12 +09:30
Cubicake 090b96ac81 Implement tick timing 2026-06-20 19:35:24 +09:30
Cubicake 63efc23203 Reshape tick method signature to capture info 2026-06-20 12:36:41 +09:30
Cubicake e57238897a Capture player world and min height on respawn packet, when player changes world drop all existing data. 2026-06-18 15:28:53 +09:30
Cubicake a870d24c31 Merge remote-tracking branch 'origin/v2/optimise' into v2/optimise
# Conflicts:
#	core/build.gradle.kts
2026-06-18 11:57:20 +09:30
Cubicake c895787ce2 Make benchmark longer 2026-06-18 11:55:21 +09:30
Cubicake 91ab493a77 oops 2026-06-18 11:55:21 +09:30
Cubicake b6ac0d54be Count optimistic reads 2026-06-18 11:55:21 +09:30
Cubicake 63c7b398c1 Improve JD note 2026-06-18 11:55:21 +09:30
Cubicake acf9c27c86 Increase write contention by writing more 2026-06-18 11:55:21 +09:30
Cubicake 422a189069 Add tests to verify MT capability of Long2ObjectMTHashMap 2026-06-18 11:55:21 +09:30
Cubicake 80ac9d287f Implement Long2ObjectMTHashMap as a composition-based StampedLock wrapper around a Long2ObjectOpenHashMap. 2026-06-18 11:55:21 +09:30
Cubicake d2dff3de3c Begin making Long2ObjectOpenHashMap thread safe 2026-06-18 11:55:07 +09:30
Cubicake 30dc0f420e Unmodified copy of Long2ObjectMap 2026-06-18 11:54:36 +09:30
Cubicake bae7feea94 Unmodified copy of Long2ObjectOpenHashMap 2026-06-18 11:54:36 +09:30
Cubicake c5c5d12002 Bump version 2026-06-13 22:11:06 +09:30
Cubicake 75d50eecbc Merge pull request #58 from Cubicake/fix-flagging-exempted-tile-entities
Fix flagging exempted tile entities
2026-06-13 20:16:43 +09:30
Cubicake c9e8b9b1c0 Wrong hashCode and equals impl 2026-06-13 20:04:32 +09:30
Cubicake 59e42d75f6 Actually implement methods everywhere its needed 2026-06-13 19:59:59 +09:30
Cubicake aa0d909505 Actually implement methods everywhere its needed 2026-06-13 19:56:10 +09:30
Cubicake 7339d64322 Properly handle exempted tile entities and reduce object allocations 2026-06-13 19:44:03 +09:30
Cubicake 6a4c344143 Add support for mutable block locatables 2026-06-13 19:19:35 +09:30
Cubicake eba11b6717 Add implementation for hasBlockEntityData 2026-06-13 17:08:18 +09:30
Cubicake 05e7a4295a Beacon ID changes between versions, don't hardcode 2026-06-13 17:07:52 +09:30
Cubicake 1d2c7d2afb Add block entity data check to BlockInfoResolver 2026-06-13 17:07:31 +09:30
Cubicake 60913b3c13 Debug messages are not always visible 2026-06-13 17:07:14 +09:30
Cubicake d3da22dfa9 Merge pull request #57 from Cubicake/fix-vehicles-again
Fix vehicles properly this time hopefully
2026-06-07 19:28:23 +09:30
Cubicake 7f836b85bf Bump version 2026-06-07 19:24:05 +09:30
Cubicake d8fc2bfc93 Use toIntArray 2026-06-07 19:23:42 +09:30
Cubicake ccb4672da6 No logspam plz 2026-06-07 17:38:17 +09:30
Cubicake 0bdd1fe61c Include fastutils 2026-06-07 17:38:11 +09:30
Cubicake da07fa063b Bump version 2026-06-07 17:38:05 +09:30
Cubicake 1f3ac0e2a5 Avoid (un)boxing 2026-06-07 17:37:53 +09:30
Cubicake c498cfa634 Switch to an unresolvedLeashedEntityIDsByHolderID-style system for vehicle-passenger relationships 2026-06-07 17:37:33 +09:30
Cubicake 3c28104ba4 Switch to an unresolvedLeashedEntityIDsByHolderID-style system for vehicle-passenger relationships 2026-06-07 17:25:47 +09:30
Cubicake cdca05ca32 Fix gitignore 2026-06-07 17:22:41 +09:30
Cubicake fb83bbbf4a Remove old PassengerReconciliationTask 2026-06-07 17:22:12 +09:30
Cubicake 9f860c1a40 Rename IntArrayList to PrimitiveIntArrayList to avoid collision with fastutil's IntArrayList 2026-06-07 14:22:25 +09:30
Cubicake dcca2d4733 Fix warning caused by virtual signs 2026-06-06 18:00:59 +09:30
Cubicake e53c51002b Merge pull request #55 from Cubicake/improve-readme-contributing-texts
Improve readme contributing texts
2026-05-31 17:59:42 +09:30
CubicakeandCopilot Autofix powered by AI c58b19d411 Fix reference to license
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-05-31 17:59:33 +09:30
Cubicake f243c305b1 I doubt any of this will matter since I'm the only contributor lol 2026-05-31 17:56:02 +09:30
Cubicake a9d6679c45 Fix formatting and wording 2026-05-31 17:43:05 +09:30
Cubicake ede8662f79 Merge pull request #53 from Cubicake/AGPL
Add AGPL compliance
2026-05-31 17:26:44 +09:30
Cubicake 7f9d543339 Merge branch 'main' into AGPL 2026-05-31 17:24:09 +09:30
Cubicake 868776bd04 Merge pull request #54 from Cubicake/v2/abstract-packets
v2/abstract packets - Make tile entity ID mutable again, use a better task queue system
2026-05-30 13:29:18 +09:30
Cubicake c47535cdb1 Bump version 2026-05-30 13:23:18 +09:30
Cubicake 5ba314045e Make stale eviction thread safe 2026-05-30 13:22:35 +09:30
Cubicake 1e45335bad Actually log the ID it says it is logging 2026-05-30 13:02:57 +09:30
Cubicake d6356faf6a Bump version and disable file logger 2026-05-30 12:52:14 +09:30
Cubicake 81d05427e5 Use direct reference to submittedTick where possible 2026-05-30 12:45:00 +09:30
Cubicake 311b69433f Leash reconcilliation using new system 2026-05-30 12:43:36 +09:30
Cubicake fc819abb2c Documentation comment and grammar 2026-05-28 22:16:13 +09:30
Cubicake e35f32705b Documentation comment 2026-05-28 22:15:15 +09:30
Cubicake f15a571c1d Duplicate word 2026-05-28 22:13:48 +09:30
Cubicake b5179739dc oops that file doesn't exist 2026-05-28 22:13:22 +09:30
Cubicake 1e7a7cf02a Add information about raycastedantiespCredits and legal obligations for servers running this plugin 2026-05-28 22:06:09 +09:30
Cubicake 4a63e0420d Add forking and legal notices to README 2026-05-28 21:51:37 +09:30
Cubicake fea9794a01 Link Attribution.java to actually-needed code so that it cannot be deleted by accident. 2026-05-28 21:51:15 +09:30
Cubicake 3b53334f1a Register attribution command and print license info to console on startup 2026-05-28 21:50:33 +09:30
Cubicake 4e9b43d2d3 Add an AGPL attribution command, runnable by all players and the console. 2026-05-28 21:49:20 +09:30
Cubicake 2ba7a24f19 General README improvements, adding credits and fixing up other info. 2026-05-28 21:06:50 +09:30
Cubicake 7861298502 This missed the rename somehow 2026-05-27 22:32:23 +09:30
Cubicake e6ba88d981 Use new system for leash and cache packets 2026-05-27 21:46:05 +09:30
Cubicake 081ccb9408 Make both PacketEntityViewController and PacketEventsEntityViewController have static singleton get methods (returning the same object) 2026-05-27 21:44:50 +09:30
Cubicake 63fab1d5ee Fix leash reconciliation 2026-05-27 21:44:00 +09:30
Cubicake bb628a7b41 Delete unused code 2026-05-27 21:15:41 +09:30
Cubicake 43980c1364 Pass in entity ID to entity spawn handler 2026-05-27 21:14:46 +09:30
Cubicake 321f8d4c3a Rename final fields to indicate that they are constants 2026-05-27 21:07:17 +09:30
Cubicake d19987d337 Fixup PECacheablePacketReconciliationTask 2026-05-27 21:05:41 +09:30
Cubicake 65a4b7c94e Delete unused code 2026-05-27 20:47:41 +09:30
Cubicake 8e0420b31f Remove now-pointless nettyTask queue 2026-05-27 20:34:40 +09:30
Cubicake f686e81430 Implement reconciliation entity-spawn tasks 2026-05-27 20:33:42 +09:30
Cubicake 0ba40c8dbb Document entity equipment packet 2026-05-27 20:31:58 +09:30
Cubicake 6bce78a254 Rename to EntitySpawnTask to better reflect use case rather than imply generic netty-thread running, and properly implement NettyData methods 2026-05-27 20:31:37 +09:30
Cubicake 7ea2602282 Run netty task during eviction 2026-05-27 20:09:52 +09:30
Cubicake bc37329ff7 Make FutureNettyTask use loops rather than recursion, add setNext and appendLinkedTask methods 2026-05-25 22:45:08 +09:30
Cubicake 8b57d5ce34 Create abstract implementation of FutureNettyTask 2026-05-25 22:40:11 +09:30
Cubicake 33cd4b0455 Evict old netty tasks each tick 2026-05-25 20:17:12 +09:30
Cubicake bf733b4c5b Add netty tasks to NettyData 2026-05-25 20:16:06 +09:30
Cubicake d3a088a30c Switch to updateOrInsertTileEntity 2026-05-24 21:45:23 +09:30
Cubicake 0166031975 Implement BlockView#insertTileEntityIfAbsent 2026-05-24 21:44:12 +09:30
Cubicake 3b712d6918 Update BlockView for mutable block IDs 2026-05-24 21:38:00 +09:30
Cubicake d44f3d0fdf Begin to make tile entities mutable again 2026-05-24 21:35:13 +09:30
Cubicake 0e4dfc08b7 Update readme 2026-05-24 21:10:54 +09:30
Cubicake dbe72d3c5e Merge pull request #52 from Cubicake/v2/fix-leashes 2026-05-24 21:07:52 +09:30
Cubicake 4e1c77fe7b Clean up code slightly 2026-05-24 21:07:17 +09:30
Cubicake 9c7bfdfa57 Make sure file logging isn't sent to console 2026-05-24 21:04:40 +09:30
Cubicake 1e73d78724 That doesn't exist 2026-05-24 20:56:02 +09:30
Cubicake a284eb98f5 Merge remote-tracking branch 'origin/v2/fix-leashes' into v2/fix-leashes 2026-05-24 20:54:37 +09:30
copilot-swe-agent[bot]andCubicake 2dafdb53af Avoid map mutation during unresolved leash iteration
Agent-Logs-Url: https://github.com/Cubicake/RaycastedAntiESP/sessions/b1bdce15-4fbb-47c3-b86a-cd4873214359

Co-authored-by: Cubicake <70577278+Cubicake@users.noreply.github.com>
2026-05-24 11:22:41 +00:00
Cubicake acb71072ac If leashing entity doesn't exist, handle properly 2026-05-24 20:49:17 +09:30
Cubicake fdde9d957f Change discord link 2026-05-24 14:57:23 +09:30
Cubicake 3abc73e9f7 Add JD note 2026-05-23 21:17:17 +09:30
Cubicake 130166d787 Bump version 2026-05-23 21:07:54 +09:30
Cubicake c2e9d81942 Log to file 2026-05-23 21:07:47 +09:30
Cubicake b80a9c0f3c clear pending leash holder references 2026-05-23 21:07:32 +09:30
Cubicake b493b1af2e Reconcile leashes 2026-05-23 13:36:34 +09:30
Cubicake 807bfa02f3 Add NettyData to PlayerData 2026-05-23 13:07:04 +09:30
Cubicake d134343bc9 Create NettyData 2026-05-23 13:06:50 +09:30
Cubicake 8c5aaea5f5 Add the ability to log arbitrary strings 2026-05-21 17:23:08 +09:30
Cubicake 93fd8b4d3e Check if vehicle exists before sending show 2026-05-20 21:31:17 +09:30
Cubicake 61e550894f Merge branch 'main' into v2/optimise 2026-05-20 21:15:30 +09:30
Cubicake 417ebae0ec Bump value because idk why else this would be broken 2026-05-20 21:15:10 +09:30
Cubicake 4cf4453996 Make run task use java 25 2026-05-20 21:14:06 +09:30
Cubicake 545a0eae2a Make benchmark longer 2026-05-20 21:13:36 +09:30
Cubicake c56edb67ac Make run task use java 25 2026-05-20 21:09:59 +09:30
Cubicake cbe6bf2635 Merge branch 'main' into v2/optimise 2026-05-20 20:55:32 +09:30
Cubicake 8b84d6e43a oops 2026-05-20 20:46:56 +09:30
Cubicake ad3d06f1aa Count optimistic reads 2026-05-20 20:33:50 +09:30
Cubicake 4a8fb2ca53 Improve JD note 2026-05-20 17:26:27 +09:30
Cubicake 912523aba9 Increase write contention by writing more 2026-05-20 17:19:10 +09:30
Cubicake 71cf2f4657 Add tests to verify MT capability of Long2ObjectMTHashMap 2026-05-20 17:11:37 +09:30
Cubicake bbdd4982a0 Implement Long2ObjectMTHashMap as a composition-based StampedLock wrapper around a Long2ObjectOpenHashMap. 2026-05-20 17:11:17 +09:30
Cubicake 785729c443 Bump version 2026-05-20 09:41:22 +09:30
Cubicake eb2ec969a9 If a throwable is thrown before the tick threads are dispatched, clean up the tick threads running var 2026-05-20 09:41:08 +09:30
Cubicake fed0379899 Make sure NPEs don't throw 2026-05-20 09:40:31 +09:30
Cubicake 1ea51136ce Begin making Long2ObjectOpenHashMap thread safe 2026-05-19 19:47:57 +09:30
Cubicake 2fb8b0e92a Unmodified copy of Long2ObjectMap 2026-05-19 18:38:46 +09:30
Cubicake c3ebfbbcd0 Unmodified copy of Long2ObjectOpenHashMap 2026-05-19 17:51:37 +09:30
Cubicake 934825daef Merge pull request #51 from Cubicake/v2/abstract-packets
[v2] Abstract entity packet logic from actual packet manipulation
2026-05-19 17:29:40 +09:30
Cubicake 627c3c3f10 Properly always update player own location 2026-05-19 17:29:17 +09:30
Cubicake 36c349d7e9 Merge remote-tracking branch 'origin/v2/abstract-packets' into v2/abstract-packets 2026-05-19 17:21:00 +09:30
Cubicake 593211fad2 Add null guards 2026-05-19 17:20:29 +09:30
Cubicake e0037b5da9 Update logging 2026-05-19 17:15:19 +09:30
Cubicake 4a71852fd4 Bump version and downgrade java 2026-05-19 17:07:40 +09:30
Cubicake 0eb47f5a93 Preliminary work on assertion-based thread guarding, to be completed in a different branch 2026-05-19 17:07:16 +09:30
Cubicake 275fc53f9a Comment out debug logger 2026-05-19 17:06:53 +09:30
Cubicake e157f50f86 Check if config is enabled before setting block entities to hidden 2026-05-19 17:06:41 +09:30
Cubicake 27ca927d55 Null check before removing leashed entity 2026-05-19 17:06:03 +09:30
Cubicake a3e2f3d052 Update CubiLogs 2026-05-19 17:05:42 +09:30
Cubicake 0c16268142 Update logging 2026-05-18 19:50:15 +09:30
Cubicake 41bafad04c Track logging as submodule 2026-05-18 19:40:14 +09:30
Cubicake 9f7a06cc89 Make file writes async except on disable 2026-05-18 19:11:50 +09:30
Cubicake 94ee2ef6fd Fix test server version 2026-05-18 19:11:29 +09:30
Cubicake a2c09831cf Add file message log construction 2026-05-18 19:09:54 +09:30
Cubicake 8c61813bbf It would be helpful to put the loggers *before* the early return 2026-05-16 17:02:21 +09:30
Cubicake 49acaaf4fa Add file logging 2026-05-16 15:16:41 +09:30
Cubicake e6cca8d1b4 Fix priority 2026-05-16 14:10:35 +09:30
Cubicake 778ed7bb0e Bump version 2026-05-13 21:53:45 +09:30
Cubicake 5e6e249fd4 Bump version 2026-05-10 20:30:43 +09:30
Cubicake 6685d60fc4 Remove unneeded player info packet handling 2026-05-10 20:28:34 +09:30
Cubicake 7f9f6606bc Remove unneeded remnant of when there was only one view controller. 2026-05-10 20:27:46 +09:30
Cubicake e31349db26 Change magic numbers based on testing 2026-05-10 20:17:40 +09:30
Cubicake 58bab35223 Add a bit more info to the warning. 2026-05-10 20:12:25 +09:30
Cubicake 4afe454de9 Recursively update passenger positions whenever the vehicle moves. Move entityFromID to PlayerData. 2026-05-10 20:12:13 +09:30
Cubicake e75c3731b1 Note 2026-05-10 15:59:55 +09:30
Cubicake 2556f5b369 Comment 2026-05-10 15:56:18 +09:30
Cubicake 0243cef884 Add individualised delay factors 2026-05-10 15:55:31 +09:30
Cubicake f8fbbd8a74 Clean up unneeded code 2026-05-10 15:15:39 +09:30
Cubicake f22133efe8 Add delaying to leash and passenger packets 2026-05-10 15:15:10 +09:30
Cubicake 08db0d384f Simplify check 2026-05-09 21:34:29 +09:30
Cubicake 0ac8dc372f Send passenger packets on passenger show too 2026-05-09 21:34:09 +09:30
Cubicake c5a5009fe9 Remove unneeded code 2026-05-09 21:28:36 +09:30
Cubicake aae0060cd4 Add contract annotations 2026-05-09 21:26:26 +09:30
Cubicake 56ff445cb6 Remove unneeded abstract method 2026-05-09 21:26:17 +09:30
Cubicake be880e80c7 Untrack these files 2026-05-09 21:25:52 +09:30
Cubicake d80555c016 Merge branch 'main' into v2/abstract-packets 2026-05-09 20:37:04 +09:30
Cubicake 2e33bf9415 Make sure self players never change visibility 2026-05-09 20:36:12 +09:30
Cubicake 0f87b90787 Remove unused deprecated methods 2026-05-09 20:35:59 +09:30
Cubicake 0a9f115e92 Move entity destroy handling to PacketEntityViewController 2026-05-09 17:59:28 +09:30
Cubicake ebfa47efbc Properly dereference this 2026-05-09 17:59:03 +09:30
Cubicake 5be167fdb3 Self player should always be visible 2026-05-09 17:55:45 +09:30
Cubicake 0799b911a9 Leash and passenger packets are not related to packet cache 2026-05-09 17:55:33 +09:30
Cubicake 97d2bc7bdd Set vehicle IDs 2026-05-09 16:47:57 +09:30
Cubicake 0bd6b4203f Obey IntArrayList contract 2026-05-09 16:46:02 +09:30
Cubicake f4a61f43ff Use correct distance 2026-05-09 16:44:55 +09:30
Cubicake 9372928ae9 Oh right that's how logic works 2026-05-09 16:44:06 +09:30
Cubicake 68ed857f25 Handle leashing and riding entities, only the spawn entity packet is used in modern MC so remove everything else. 2026-05-09 16:37:05 +09:30
Cubicake 30569c711f Doc note 2026-05-09 16:35:52 +09:30
Cubicake 5005b3eb7b Move logging to a separate git module 2026-05-08 16:40:43 +09:30
Cubicake dd00bdd1fa Document leash/attach packet 2026-05-07 22:42:08 +09:30
Cubicake 0e1c2815ae Create primitive int arraylist handling util class and annotation 2026-05-07 22:40:24 +09:30
Cubicake 489db71b2b Replace spawn type with isSelfEntity boolean 2026-05-06 20:23:08 +09:30
Cubicake 2a821c0ebf Begin to remove unneeded generics and detach equipment, metadata, etc from entity locatables 2026-05-06 20:16:11 +09:30
Cubicake 7115fe6e34 Bump version 2026-05-04 23:15:08 +09:30
Cubicake 323c83c93e Handle entity attributes 2026-05-04 23:12:24 +09:30
Cubicake aa0dc3297a Mojang, simply why 2026-05-04 22:57:12 +09:30
Cubicake cb4c55fdbd Track a couple more packets and begin annotating 2026-05-04 22:48:02 +09:30
Cubicake a6c79d4bbe Start documenting packets and what PE class they map to 2026-05-04 22:47:23 +09:30
Cubicake 3f8ac5cc5d Fix stupid packet order issue 2026-05-04 22:09:13 +09:30
Cubicake 3bd4c5339c Netty action cache 2026-05-04 22:08:51 +09:30
Cubicake 9f3bb3793a Yet another debug command 2026-05-04 22:08:40 +09:30
Cubicake baf560546f Properly use packets to register player data. 2026-05-03 21:39:44 +09:30
Cubicake 9f27907a83 Add self entity tracking 2026-05-03 20:58:53 +09:30
Cubicake f4eba53f7f Oops 2026-05-03 16:17:55 +09:30
Cubicake f60934a023 Make ReplayData an append-only queue. 2026-05-03 16:10:45 +09:30
Cubicake e524d072b2 Make inserting tile entity to view the responsibility of PacketEntityViewController, as well as default visibility. Handle REMOVE_ENTITY_EFFECT packet. Implement concrete packet manipulation based off old monoclass. 2026-05-03 16:10:21 +09:30
Cubicake 4e1ca5401c Increase visibility 2026-05-03 16:08:19 +09:30
Cubicake 4381459a69 Shouldn't use the view like this 2026-05-03 16:04:03 +09:30
Cubicake 1e7be8637c Add set(x,y,z) method to MutableLocatable 2026-05-03 15:49:20 +09:30
Cubicake 5ee2a18173 Remove player-specific replay data 2026-05-03 15:48:35 +09:30
Cubicake c98c1c474f Add some needed methods to entity view 2026-05-02 20:13:21 +09:30
Cubicake d3ddb28ec3 Core shouldn't have access to packetevents 2026-05-02 20:12:49 +09:30
Cubicake 1a2469cbc4 Begin extracting logic from the packetevents specific classes 2026-05-02 20:12:06 +09:30
Cubicake 1fc5000782 Add visibility check without useless currentTick parameter 2026-05-02 16:16:52 +09:30
Cubicake 9121c0f4f6 Update StrokkCommands 2026-05-02 16:15:40 +09:30
Cubicake 5833213c20 Require entity visibility to be explicitly set 2026-04-26 18:21:26 +09:30
Cubicake 1d3d3f5b55 No need for two seperate methods 2026-04-26 18:21:16 +09:30
Cubicake dcb5af8721 Check distance to decide whether to auto hide an entity 2026-04-26 18:21:03 +09:30
Cubicake ac3745d1e4 Require tile visibility to be explicitly set 2026-04-26 18:20:41 +09:30
Cubicake 76d11242f6 Require entity visibility to be explicitly set 2026-04-26 18:20:32 +09:30
Cubicake 108ba8a5b4 Add a primitive distance method 2026-04-26 18:20:11 +09:30
Cubicake 5228e06033 Require tile visibility to be explicitly set 2026-04-26 18:20:00 +09:30
Cubicake 7884b02d8a Copilot is a tad dumb 2026-04-26 16:15:04 +09:30
Cubicake fb861860bb Update for 26.1 testing 2026-04-26 16:03:09 +09:30
Cubicake d7036dd9d6 Update gitignore 2026-04-26 16:00:04 +09:30
Cubicake 777e31cf59 Revert back to PE, keeping internals code for when it may be needed 2026-04-26 15:59:05 +09:30
Cubicake 7645335bb6 Merge pull request #44 from Cubicake/v2/new-new-config
Rework config
2026-04-26 14:20:40 +09:30
copilot-swe-agent[bot]andCubicake 297278b998 Add bounds validation in RaycastConfig before byte/short casts
Agent-Logs-Url: https://github.com/Cubicake/RaycastedAntiESP/sessions/4cfd15a0-1329-4512-813f-b4f19f613388

Co-authored-by: Cubicake <70577278+Cubicake@users.noreply.github.com>
2026-04-26 04:47:45 +00:00
Cubicake b3455dfb92 Add missing defaults 2026-04-26 14:04:39 +09:30
Cubicake 2eecde1ee3 Use StrokkCommands 2026-04-26 14:04:18 +09:30
Cubicake 688f39463b Remove unused permission 2026-04-26 14:03:23 +09:30
Cubicake fc23764bce Delete MovementTracker.java 2026-04-26 14:03:10 +09:30
Cubicake 5a57e44869 Fix log messages 2026-04-26 13:16:40 +09:30
Cubicake 4318f8b23e Rework config system 2026-04-26 13:15:28 +09:30
Cubicake 8b370d0fe2 Add a command to dump the block ids for adding to the checks 2026-04-23 21:21:18 +09:30
Cubicake 4a8527909a Bump size slightly 2026-04-23 20:48:39 +09:30
Cubicake eca024118f Directly get from player registry 2026-04-23 12:17:34 +09:30
Cubicake 3f814cd6d6 Merge branch 'v2/track-vehicles' 2026-04-22 23:00:55 +09:30
Cubicake 2cbe04c6cc Bump version 2026-04-22 23:00:25 +09:30
Cubicake 2151f88f95 Apparently it was that simple lmao 2026-04-22 22:45:35 +09:30
Cubicake af387145fa Merge remote-tracking branch 'origin/main' 2026-04-21 20:09:01 +09:30
Cubicake 8f760b7769 Merge pull request #39 from Cubicake/v2/attempt-3-per-player-snapshots
Per-player snapshots
2026-04-20 21:43:46 +09:30
Cubicake b4d35ab9f5 clearer JD note 2026-04-20 20:51:19 +09:30
Cubicake 1c510322a9 Bump version 2026-04-20 17:25:35 +09:30
Cubicake dd1dd32391 Correct value 2026-04-20 14:42:24 +09:30
Cubicake f1342514e0 Use bitsets to save memory 2026-04-20 14:34:24 +09:30
Cubicake 331bd2a4c0 Merge pull request #41 from Cubicake/v2/try-and-fix-mem-leak
Fix some bugs and hopefully a memory leak
2026-04-20 12:30:44 +09:30
Cubicake a9de49a9a9 Don't allocate the boolean array for empty chunks 2026-04-20 12:20:46 +09:30
Cubicake e2c61cb926 Add tick time debugging 2026-04-20 12:18:20 +09:30
Cubicake 036ff55317 Merge remote-tracking branch 'origin/v2/try-and-fix-mem-leak' into v2/try-and-fix-mem-leak 2026-04-20 12:05:08 +09:30
Cubicake 19c58d5a71 Insert new tile entity if id changes 2026-04-20 12:03:41 +09:30
Cubicake 6c3d75643a Rename replaceChunk to replaceChunkSection and properly remove chunk sections if empty. 2026-04-20 12:03:08 +09:30
Cubicake 587f45f86b Expand to all block locatables 2026-04-20 11:56:54 +09:30
Cubicake 5eb815010d Create insertTileEntity 2026-04-20 11:56:41 +09:30
Cubicake 70a0c1d1de Properly utilise the features of CanonicalSet, implement insertTileEntity 2026-04-20 11:56:29 +09:30
Cubicake c59d650a94 Don't save empty chunks 2026-04-20 11:51:14 +09:30
Cubicake bcdbdf3c94 Remove unused import 2026-04-20 11:50:24 +09:30
Cubicake 99eb62a72e Null safety 2026-04-20 11:48:57 +09:30
Cubicake e17d0b616a Null safety 2026-04-20 11:48:29 +09:30
Cubicake 7c44cc1614 Clean up imports 2026-04-20 11:46:57 +09:30
Cubicake d75c5604e0 Properly dispatch across several threads when configured to use more than one. 2026-04-20 10:56:38 +09:30
Cubicake 902d0dcf20 Get correct block id 2026-04-19 22:58:39 +09:30
Cubicake dbe04d1861 Null check 2026-04-19 22:58:18 +09:30
Cubicake a0ffab833e Debug command 2026-04-19 22:58:04 +09:30
Cubicake e95fb3a97b Bump version 2026-04-19 22:57:51 +09:30
Cubicake d033cba970 Tile entities can't move 2026-04-19 22:08:33 +09:30
Cubicake c810152fa8 Correctly use block hashing (and label as such) 2026-04-19 21:11:12 +09:30
Cubicake 28929c0e20 Only one thread ever touches this 2026-04-19 20:30:47 +09:30
Cubicake 8046bbad91 Implement strictEquality 2026-04-19 20:30:33 +09:30
Cubicake 59fef9cd5d Remove transition type "FORGET", implement clearable where possible 2026-04-19 20:30:20 +09:30
Cubicake 98b31ee4cf Refactor 2026-04-19 20:28:13 +09:30
Cubicake be5b1b59f6 Make blockID final, refactor package, implement strictEquality 2026-04-19 20:27:45 +09:30
Cubicake 49d8c7cbf7 Specify the stored canonical type. 2026-04-19 20:19:47 +09:30
Cubicake a51ff8beaa Make ThreadSafeLocatable equality and hashcode checks properly thread safe 2026-04-19 20:03:19 +09:30
Cubicake c3183ef3d4 Implement StrictEquality 2026-04-19 20:02:58 +09:30
Cubicake b5e78cc0ff Functionally identical 2026-04-19 19:59:34 +09:30
Cubicake 3c7fabb52e Create CanonicalSet 2026-04-19 19:43:58 +09:30
Cubicake 004fc8bec9 Fix wording 2026-04-19 16:04:10 +09:30
Cubicake 45c6306482 Use new block view 2026-04-19 16:04:00 +09:30
Cubicake b37624b38f Explicitly do some clean up on player leave 2026-04-19 16:03:46 +09:30
Cubicake 5aaa9bd6c9 Use new block view 2026-04-19 16:03:07 +09:30
Cubicake 89a2629b77 Use new block view 2026-04-19 16:02:42 +09:30
Cubicake 83759a1c61 Create ChunkSectionLocatable and make Locatable inherit it 2026-04-19 16:02:23 +09:30
Cubicake 79cf23d04f Replace old with new unified block view 2026-04-19 16:01:45 +09:30
Cubicake 513dfc2b96 Use new block view 2026-04-19 16:01:39 +09:30
Cubicake 1632258ae8 Replace old with new unified block view 2026-04-19 16:00:30 +09:30
Cubicake 98b910fd2e Update registry for new merged factory 2026-04-19 15:59:59 +09:30
Cubicake 4c97544ac7 Merge tile entity view and block snapshot manager 2026-04-19 15:59:44 +09:30
Cubicake d01b080207 Remove an unnecessary allocation 2026-04-19 15:52:55 +09:30
Cubicake f167004657 Test commands 2026-04-18 22:11:26 +09:30
Cubicake 260278c380 Oops forgot to delete imports 2026-04-18 21:57:25 +09:30
Cubicake fe864dfb42 Finally remove DataHolder 2026-04-18 21:53:34 +09:30
Cubicake ee84361f7f If it's been marked as visible, keep it visible 2026-04-18 21:07:07 +09:30
Cubicake 054b092b10 Make sure people can't break everything by joining too quickly 2026-04-18 21:03:24 +09:30
Cubicake 3dfcb5e8a4 Switch to PaperListener pattern, begin replacement of DataHolder 2026-04-18 20:54:55 +09:30
Cubicake 53ffc67492 Don't drop data from column other than tile entities 2026-04-18 20:26:45 +09:30
Cubicake 38d9f794e8 Unnecessary casts 2026-04-17 22:35:46 +09:30
Cubicake 19c1db1fec Fix up 2026-04-17 22:25:57 +09:30
Cubicake 38eeba1875 Bump version 2026-04-17 22:15:46 +09:30
Cubicake d3561e28ca Use generics 2026-04-17 22:15:33 +09:30
Cubicake 702ef77248 Move EntityLocatable, TileEntityLocatable, and implementations, and make generic 2026-04-17 22:00:34 +09:30
Cubicake e347904aa1 Organise packetevents module 2026-04-17 21:53:49 +09:30
Cubicake 03d0844907 Add debugging commands 2026-04-17 21:48:51 +09:30
Cubicake ca41d935aa Packet reading and writing 2026-04-17 21:48:33 +09:30
Cubicake a7764ada31 Just bodge config a bit until it temporarily works 2026-04-17 21:48:00 +09:30
Cubicake 53c3c5cb4c Remove unneeded 2026-04-17 21:47:46 +09:30
Cubicake a065180096 Chunk-based was only needed for global bukkit, which is gone now 2026-04-17 21:47:25 +09:30
Cubicake 2389ac0f8a Store and expose the new views 2026-04-17 21:47:01 +09:30
Cubicake b12037bbe9 Just bodge config a bit until it temporarily works 2026-04-17 21:45:30 +09:30
Cubicake 6b8abe25cf Adapt to new systems 2026-04-17 21:44:42 +09:30
Cubicake a791eabacb Create ViewRegistry (supersedes SnapshotManager) 2026-04-17 21:44:17 +09:30
Cubicake ceb0d48554 Renamed TrackedTileEntity to TileEntityLocatable 2026-04-17 21:43:36 +09:30
Cubicake 9e7c62dc02 Create and implement a TileEntityLocatable 2026-04-17 21:43:13 +09:30
Cubicake 4c21c16e3b Cache changes until on player's netty thread 2026-04-17 21:35:02 +09:30
Cubicake 2db473077f No need to take current tick 2026-04-17 21:33:47 +09:30
Cubicake 078cfa8266 Use views 2026-04-17 21:33:36 +09:30
Cubicake e7ee8991b9 Don't step past the entity 2026-04-17 21:32:40 +09:30
Cubicake 77a7394d22 View interfaces 2026-04-17 21:32:20 +09:30
Cubicake c34bfdb61f View interfaces 2026-04-17 21:29:12 +09:30
Cubicake 43e11210cf getType does not exist anymore 2026-04-17 21:28:54 +09:30
Cubicake cb39e82485 Update PacketBlockSnapshotManager to work with the new interface formats 2026-04-17 21:28:11 +09:30
Cubicake d3756978dc Add LocatableType.NettyEntity 2026-04-17 21:27:27 +09:30
Cubicake fcaffbabcc Implementation of EntityLocatable with thread safety as needed for netty-based systems 2026-04-17 21:26:14 +09:30
Cubicake c6e4af9cdb A locatable that represents a per-player entity 2026-04-17 21:25:16 +09:30
Cubicake 335958939b Begin working on folia support 2026-04-17 17:33:46 +09:30
Cubicake 12c3894d04 Support all versions possible 2026-04-17 17:32:36 +09:30
Cubicake 50fdebf44b Make it so that version numbers properly update 2026-04-17 17:32:20 +09:30
Cubicake f941b6cc7b Most of this stuff has migrated away from bukkit events 2026-04-17 15:00:44 +09:30
Cubicake c30aced6be Hard depend PE for now 2026-04-17 14:59:46 +09:30
Cubicake 7eb515d8c2 Turns out there are a lot more block IDs than I thought 2026-04-17 14:59:35 +09:30
Cubicake 36ddc2ab4b Superseded by the new tile/entity view interfaces and their packet implementations 2026-04-16 20:05:55 +09:30
Cubicake 5e13f99fbf All superceded by the new tile/entity view interfaces 2026-04-16 20:05:28 +09:30
Cubicake af1e35cf80 Replaced by new impl of packets 2026-04-16 20:04:24 +09:30
Cubicake 1ac28cca35 All superceded by the new tile/entity view interfaces 2026-04-16 20:03:27 +09:30
Cubicake 562f203d09 Thread safety 2026-04-15 20:13:50 +09:30
Cubicake a1c0a6d860 Add debug method 2026-04-14 20:53:18 +09:30
Cubicake 2e816d92b8 Merge remote-tracking branch 'origin/v2/attempt-3-per-player-snapshots' into v2/attempt-3-per-player-snapshots 2026-04-14 14:20:05 +09:30
Cubicake 3fedbc2a17 World getting via key 2026-04-14 14:19:39 +09:30
Cubicake abd2dab77c Shut the logger up 2026-04-14 13:09:05 +09:30
Cubicake a7eacf704d Add delay 2026-04-14 12:59:49 +09:30
Cubicake a55022d4fd Fix some issues 2026-04-14 12:48:14 +09:30
Cubicake 8b6b0332eb WIP per-player-isation 2026-04-14 12:11:26 +09:30
Cubicake 79f018cd13 Massive changes, still very borked 2026-04-14 12:11:11 +09:30
Cubicake 5815d327cf Clarify versioning details in README
Removed note about version number differences between platforms.
2026-04-09 16:20:21 +09:30
Cubicake b76b0c900b Merge pull request #36 from Cubicake/modularise
Modularise code for platform-independence
2026-04-09 16:16:20 +09:30
Cubicake 9c6ab79f1c Might as well use the cache 2026-04-09 16:15:47 +09:30
Cubicake 01f37f6e1d Unless specified, providing a throwable shouldn't result in it actually being thrown 2026-04-09 16:14:13 +09:30
Cubicake 958c6468b4 Use inherited method rather than config-specific 2026-04-09 16:02:11 +09:30
Cubicake 3977e21568 Fix versioning docs 2026-04-09 16:00:04 +09:30
Cubicake 92dfbe9599 Logger should never fail; Add FallbackLogger 2026-04-09 15:56:36 +09:30
Cubicake 74f823b1a7 Replace colons to avoid issues in file names on some platforms 2026-04-09 15:56:11 +09:30
Cubicake 7d07e67d5b Issue identified by copilot code review 2026-04-09 15:41:31 +09:30
Cubicake 7ddf475e90 Error identified by copilot review 2026-04-09 15:38:16 +09:30
Cubicake 20bd20b60a Put time first so sorting by file name sorts by build time 2026-04-09 15:32:36 +09:30
Cubicake e858c4e6eb I forgot that this was in every build script 2026-04-09 15:27:38 +09:30
Cubicake 5127ebd260 Turns out this isn't a thing on windows 2026-04-09 14:07:14 +09:30
Cubicake f88b482a65 No need to put each snapshot manager in its own package 2026-04-07 14:46:50 +09:30
Cubicake a325dcc05f No need to put each visibility changer in its own package 2026-04-07 14:46:18 +09:30
Cubicake 186dd11aeb Add build properties 2026-04-07 14:45:04 +09:30
Cubicake 4131f0c61b Does not need to specify a class 2026-04-07 14:44:51 +09:30
Cubicake 5d94735581 JD notes 2026-04-07 14:44:33 +09:30
Cubicake 7d6a4860f6 Init messages do not need to specify class 2026-04-07 14:44:09 +09:30
Cubicake 31b6ec3426 Renamed gradle project 2026-04-07 14:43:30 +09:30
Cubicake 97703c90d0 No need for this anymore 2026-04-07 14:43:23 +09:30
Cubicake d9109fcbcd Renamed gradle project 2026-04-07 14:43:07 +09:30
Cubicake ba93e28d09 WIP plan 2026-04-02 19:36:18 +10:30
Cubicake 55de301117 Update JD note: class names have changed 2026-04-02 17:19:33 +10:30
Cubicake 2da16f39a5 oops 2026-04-02 12:19:58 +10:30
Cubicake ff81ae5d1a Use platform-independent logging with class info 2026-04-02 12:19:45 +10:30
Cubicake 18472570f4 Use platform-independent logging with class info 2026-04-02 12:03:12 +10:30
Cubicake 07d563c343 Finish core migration 2026-04-02 11:36:01 +10:30
Cubicake 6b89ab91e1 Update logging 2026-04-02 11:35:49 +10:30
Cubicake 8b6c2a895f Update to match PlatformLogger 2026-04-02 11:29:22 +10:30
Cubicake eb49446618 Fixup 2026-04-02 11:26:06 +10:30
Cubicake 6d3e768689 Update logger and imports 2026-03-31 17:47:39 +10:30
Cubicake d828461ce5 Update logger and imports 2026-03-31 17:46:45 +10:30
Cubicake bf51d0cfb6 Update logger and imports 2026-03-31 17:46:32 +10:30
Cubicake 73cec9faf5 WIP add commit hash awareness to project 2026-03-31 17:45:15 +10:30
Cubicake af7c1253e2 Update logger and imports 2026-03-31 17:44:40 +10:30
Cubicake d84b4c4bd8 Update logger and imports 2026-03-31 17:44:22 +10:30
Cubicake b8998ca936 Abstracted particle spawning 2026-03-31 17:43:57 +10:30
Cubicake 2363190bbf Add faster getWorld lookup 2026-03-31 17:43:33 +10:30
Cubicake 7068eec49e Remove unneeded attribute 2026-03-31 17:43:06 +10:30
Cubicake 516f4425a7 Move EntityVisibilityChanger to core 2026-03-31 17:42:47 +10:30
Cubicake 5c541178a4 Update logger and imports 2026-03-31 15:14:34 +10:30
Cubicake acab9879e1 Update logger and imports 2026-03-31 15:13:37 +10:30
Cubicake d1c7efa586 Add deprecation tag to make it more clear where it needs to be removed from 2026-03-31 15:12:40 +10:30
Cubicake 21dceabb2f Slightly changed passing of parameters 2026-03-31 15:12:12 +10:30
Cubicake ea8e11710c Update imports 2026-03-31 15:11:19 +10:30
Cubicake 72b838921f Move PlayerRegistry and PlayerData to core 2026-03-31 15:09:18 +10:30
Cubicake 55d770496a Move PlayerVisibilityChanger to core 2026-03-31 15:08:50 +10:30
Cubicake bfbe635032 Update logger and imports 2026-03-31 15:07:33 +10:30
Cubicake d560cbbd56 Move VisibilityTracker to core 2026-03-31 15:06:42 +10:30
Cubicake a0a3834c13 Move VisibilityChangeHandlers to core 2026-03-31 15:06:17 +10:30
Cubicake 566cd93e8d Update logger and imports 2026-03-31 15:05:26 +10:30
Cubicake 78fcec3f11 Move TileEntityVisibilityChanger to core 2026-03-31 15:04:46 +10:30
Cubicake fbdbcd39e3 Update logger and imports 2026-03-31 15:04:23 +10:30
Cubicake 2f0555c030 Move RaycastUtil to core 2026-03-31 15:03:31 +10:30
Cubicake 758263345f Add central static logger instance, require class for all logs 2026-03-31 15:01:11 +10:30
Cubicake 56ec5ffcb7 Move SnapshotManager 2026-03-30 20:06:17 +10:30
Cubicake 7e58806271 Update impls for changed interface location and format; Move away from DataHolder 2026-03-30 20:03:56 +10:30
Cubicake 9791348634 Move Engine
todo: move more methods to this interface
2026-03-30 19:49:35 +10:30
Cubicake 09a95cc735 Move BlockSnapshotManager 2026-03-30 19:49:09 +10:30
Cubicake 529b7977d4 Move EntitySnapshotManager 2026-03-30 19:45:35 +10:30
Cubicake 6f4a6d4b2e Rename RaycastedAntiESPCore.java to Core.java 2026-03-26 18:14:36 +10:30
Cubicake f57829e7fc update comment 2026-03-26 15:17:49 +10:30
Cubicake cf69030c56 Migrate config to core 2026-03-22 20:20:53 +10:30
Cubicake 828f302d5c Turns out module-info doesn't work with the bukkit ecosystem 2026-03-21 21:03:27 +10:30
Cubicake 927066adb9 Fix errors until it compiles 2026-03-21 20:20:54 +10:30
Cubicake 7c2fc00a87 Fix errors until it compiles 2026-03-21 16:58:36 +10:30
Cubicake 29890541af This should all be in paper until the non-paper stuff can be extricated 2026-03-21 16:37:17 +10:30
Cubicake 0ebd1903b1 Rename package to raycastedantiesp while we're at it 2026-03-21 14:55:39 +10:30
Cubicake f0cb5d0281 Massive refactoring in progress 2026-03-21 14:49:29 +10:30
Cubicake 300ae927d7 Massive refactoring in progress 2026-03-21 12:34:06 +10:30
Cubicake 54dc47c89f Separate Locatables into new module 2026-03-21 12:13:02 +10:30
Cubicake 60f8ea55b0 WIP Locatable refactoring 2026-03-21 12:04:55 +10:30
Cubicake 47e7a08547 Merge branch 'main' into fix-locatable 2026-03-20 14:56:20 +10:30
Cubicake e2089aace3 Make ThreadSafeLocatable properly atomic 2026-03-20 14:52:10 +10:30
Cubicake cef2a0e7ee Fix whatever this is 2026-03-20 14:51:50 +10:30
Cubicake 609fa9f9f4 Update issue templates
Add spark config view command
2026-03-14 13:50:16 +10:30
Ayushman Gaur 383bfe0abe changes made 2026-03-09 17:00:02 +05:30
Ayushman Gaur bd2c0f0c62 fix-locatable and implement stampedLock 2026-03-09 16:04:24 +05:30
Cubicake 08dff2867f Clarify stable version access in README
Updated information on stable version availability.
2026-03-09 15:16:24 +10:30
Cubicake 84114b3325 Update README formatting and content
Contributing info moved to CONTRIBUTING.md
2026-03-09 15:15:37 +10:30
Cubicake 30f78ab351 Add CONTRIBUTING.md 2026-03-09 15:11:53 +10:30
Cubicake 0d8eec08ae Oops 2026-03-09 14:55:31 +10:30
Cubicake 79d67832ac Update version information in README.md 2026-03-09 14:54:24 +10:30
Cubicake 8429c33791 Update beta version to alpha version in README 2026-03-09 14:53:54 +10:30
Cubicake ddc5052741 Merge remote-tracking branch 'origin/main'
# Conflicts:
#	src/main/java/games/cubi/raycastedAntiESP/utils/ConcurrentSetMap.java
2026-02-27 19:50:09 +10:30
Cubicake 9aff6869d1 Add warning to JD note on ConcurrentSetMap#asActualConcurrentMap 2026-02-27 19:49:34 +10:30
Cubicake 09f92498fc Add warning to JD note on ConcurrentSetMap#asActualConcurrentMap 2026-02-27 19:46:40 +10:30
Cubicake 47182ad24a Create ConcurrentSetMap<K, V> and replace instances of ConcurrentHashMap<K, Set<V>> with it 2026-02-27 19:36:35 +10:30
Cubicake e1a7a9b278 Implement ImmutableLocatable 2026-02-27 18:03:17 +10:30
Cubicake 5390965693 Add JD notes 2026-02-27 18:02:33 +10:30
Cubicake 75e7a3ddff Move away from Paper Position
WIP: Platform Independence
2026-02-25 22:05:45 +10:30
Cubicake 17c0db3980 Move interface methods above static 2026-02-25 21:57:43 +10:30
Cubicake 13e6ece4ae Merge branch 'config' 2026-02-22 18:07:17 +10:30
Cubicake dfe1ff6f9c Merge remote-tracking branch 'origin/main' 2026-02-22 18:06:54 +10:30
Cubicake c84993571a AbstractBlockLocation 2026-02-22 17:59:46 +10:30
Cubicake a2efea0060 Add PacketEvents support for BlockSnapshotManager (WIP)
todo: actually populate PacketEventsBSM with data from packetevents, link to config so that the object can be created.
2026-02-21 22:36:02 +10:30
Cubicake 15d30ce397 Modrinth link changed 2026-02-20 18:56:14 +10:30
Cubicake 5baeb75619 Fix copilot 2026-02-19 22:03:31 +10:30
Cubicake 11ef7e6388 Merge pull request #31 from Cubicake/copilot/migrate-to-sponge-configurate
Migrate Bukkit config handling to Configurate YAML
2026-02-19 21:21:23 +10:30
copilot-swe-agent[bot]andCubicake 6c1b3fdc7c Finalize Configurate migration implementation
Co-authored-by: Cubicake <70577278+Cubicake@users.noreply.github.com>
2026-02-19 10:38:05 +00:00
copilot-swe-agent[bot]andCubicake 1a25c49271 Migrate config system to Configurate YAML
Co-authored-by: Cubicake <70577278+Cubicake@users.noreply.github.com>
2026-02-19 10:34:54 +00:00
copilot-swe-agent[bot]andCubicake 001e8b3688 Document Configurate migration plan
Co-authored-by: Cubicake <70577278+Cubicake@users.noreply.github.com>
2026-02-19 10:15:58 +00:00
copilot-swe-agent[bot] 22c1321873 Initial plan 2026-02-19 10:12:43 +00:00
Cubicake 167b4be8b8 Fixup merge 2026-02-19 20:25:42 +10:30
Cubicake 0a5c130cd1 Merge branch 'main' into config
# Conflicts:
#	src/main/java/games/cubi/raycastedAntiESP/Logger.java
#	src/main/java/games/cubi/raycastedAntiESP/config/RaycastConfig.java
#	src/main/java/games/cubi/raycastedAntiESP/config/TileEntityConfig.java
#	src/main/java/games/cubi/raycastedAntiESP/engine/Engine.java
#	src/main/java/games/cubi/raycastedAntiESP/engine/SimpleEngine.java
2026-02-19 20:21:48 +10:30
Cubicake eb64d03d05 Preparations to merge changes from main 2026-02-19 20:13:40 +10:30
Cubicake 95d14e97b3 Debugging statements 2026-02-19 20:12:20 +10:30
Cubicake c1e71c52aa Debugging statements 2026-02-16 21:50:29 +10:30
Cubicake 18e1857d83 Add methods to track if player can see chunk 2026-02-16 21:47:58 +10:30
Cubicake 6a1214e126 Check that player has loaded chunk 2026-02-16 21:47:40 +10:30
Cubicake 6b1f9cf24f Clean up 2026-02-16 21:47:25 +10:30
Cubicake 96dec1d654 Add method to check if player is registered 2026-02-16 21:46:33 +10:30
Cubicake b6507cb052 Move TileEntityVisibilityTracker to its own class as it is quite a bit more complex than the trackers for players and entities 2026-02-16 21:44:08 +10:30
Cubicake 5f27b1da1f Add chunk coord getters to Locatable 2026-02-16 21:43:31 +10:30
Cubicake 433a09b7c6 Bump version 2026-02-16 21:43:16 +10:30
Cubicake a57dba3ff4 Permission checks cannot occur within core systems as this will not work when made platform independent 2026-02-16 18:38:18 +10:30
Cubicake 5f34f0cc6f Switch to kotlin gradle, bump gradle version, add paperweight (for now just for easier source reading, may actually be used later) 2026-02-16 18:21:45 +10:30
Cubicake c09a69381f Clean up 2026-02-14 22:46:15 +10:30
Cubicake 44f9bf4196 Migrate Tile visibility tracking to a system similar to player and entity 2026-02-14 22:19:30 +10:30
Cubicake 973e500c9f Begin making Engine an interface 2026-02-11 20:56:16 +10:30
Cubicake f436f31dea Properly flush cache 2026-02-08 16:09:26 +10:30
Cubicake a6b9d34bab Properly calculate tile entity chunk radius 2026-02-08 15:46:30 +10:30
Cubicake b5ef1d7ac4 continue 2026-02-01 18:56:44 +10:30
Cubicake 516197aa36 Merge remote-tracking branch 'origin/main' 2026-01-30 21:57:46 +10:30
Cubicake 08212cdb78 Bump version 2026-01-30 21:57:35 +10:30
Cubicake 4658e99bd9 Fix entities not being untracked correctly 2026-01-30 21:57:24 +10:30
Cubicake f74d6c90e8 Fix tile entities not being hidden correctly until being seen once 2026-01-30 21:57:11 +10:30
Cubicake 26e830bdd0 fixup copilot 2026-01-29 23:31:07 +10:30
Cubicake 0fb6d31cde Revise version information in README.md
Updated version information and added beta version details.
2026-01-28 17:12:59 +10:30
Cubicake 07b2c50edc Merge pull request #27
Overhaul config for new format
2026-01-28 17:09:06 +10:30
copilot-swe-agent[bot]andCubicake be9796c712 Cache debug config factory
Co-authored-by: Cubicake <70577278+Cubicake@users.noreply.github.com>
2026-01-27 12:52:04 +00:00
copilot-swe-agent[bot]andCubicake 433f873f82 Fill snapshot defaults and packet placeholders
Co-authored-by: Cubicake <70577278+Cubicake@users.noreply.github.com>
2026-01-27 12:47:48 +00:00
copilot-swe-agent[bot]andCubicake 914909039e Refactor debug config factory
Co-authored-by: Cubicake <70577278+Cubicake@users.noreply.github.com>
2026-01-27 12:38:43 +00:00
copilot-swe-agent[bot]andCubicake 92c5a9f4d1 Refactor visibility handler configs
Co-authored-by: Cubicake <70577278+Cubicake@users.noreply.github.com>
2026-01-27 09:09:46 +00:00
copilot-swe-agent[bot]andCubicake bfaa8605f0 Clarify engine factory init and tile entity parsing
Co-authored-by: Cubicake <70577278+Cubicake@users.noreply.github.com>
2026-01-27 05:44:07 +00:00
copilot-swe-agent[bot]andCubicake 55f68eed8c Lazily init engine config factories
Co-authored-by: Cubicake <70577278+Cubicake@users.noreply.github.com>
2026-01-27 05:42:57 +00:00
copilot-swe-agent[bot]andCubicake 2634b1a59e Reuse engine factories and cleanup defaults
Co-authored-by: Cubicake <70577278+Cubicake@users.noreply.github.com>
2026-01-27 05:41:26 +00:00
copilot-swe-agent[bot]andCubicake dd4d0476dd Refine tile entity defaults
Co-authored-by: Cubicake <70577278+Cubicake@users.noreply.github.com>
2026-01-27 05:39:42 +00:00
copilot-swe-agent[bot]andCubicake b6bb3abd28 Tidy enum registration and defaults
Co-authored-by: Cubicake <70577278+Cubicake@users.noreply.github.com>
2026-01-27 05:38:16 +00:00
copilot-swe-agent[bot]andCubicake a70ecf0b9d Refactor config factories and defaults
Co-authored-by: Cubicake <70577278+Cubicake@users.noreply.github.com>
2026-01-27 05:35:52 +00:00
copilot-swe-agent[bot]andCubicake 40b7d9e58d Co-authored-by: Cubicake <70577278+Cubicake@users.noreply.github.com> 2026-01-27 05:06:52 +00:00
Cubicake 05e2caaf43 Delete deletion candidates 2026-01-27 15:28:35 +10:30
copilot-swe-agent[bot]andCubicake 4030db77c7 Plan config overhaul updates
Co-authored-by: Cubicake <70577278+Cubicake@users.noreply.github.com>
2026-01-27 02:31:44 +00:00
copilot-swe-agent[bot] d2913e2c64 Initial plan 2026-01-27 02:27:01 +00:00
Cubicake 9f5fa5cd3a Merge remote-tracking branch 'origin/config' into config 2026-01-27 12:55:04 +10:30
Cubicake 2f92860f76 Delete deletion candidates 2026-01-27 12:54:50 +10:30
Cubicake 4d06bac9a3 Merge pull request #26 from Cubicake/main
Update name
2026-01-27 12:44:01 +10:30
Cubicake 7b63d6b352 Begin implementing Entity 2026-01-27 12:41:28 +10:30
Cubicake 1fe44a8e45 Have config classes define their own factories as internal static classes, begin moving default configs to config classes 2026-01-27 11:44:57 +10:30
Cubicake bb3f06a070 Move Mode to its own class 2026-01-27 11:42:54 +10:30
Cubicake c9ee55f864 Add more support for setting configs using commands 2026-01-27 11:42:33 +10:30
Cubicake 5654216ac3 Update name 2026-01-26 17:31:13 +10:30
Cubicake 351397852c WIP, begin defining factory methods 2026-01-26 17:01:15 +10:30
Cubicake 6532fb619c wtf how???????? 2026-01-24 19:39:17 +10:30
Cubicake ae63a4c56f Bump version 2026-01-24 12:30:18 +10:30
Cubicake ae4ff7c593 Rename project 2026-01-24 12:30:04 +10:30
Cubicake e016d4339f superclass method requires entity visibility not to have been set yet 2026-01-24 12:17:47 +10:30
Cubicake d1071427d1 Remove unneeded comment 2026-01-24 12:16:41 +10:30
Cubicake c4d56582d8 Move PacketEvents initialisation fully to onLoad() 2026-01-23 22:51:32 +10:30
Cubicake 266e04aa0c Add new Frequency enum 2026-01-23 22:50:59 +10:30
Cubicake cf0240b940 Suppress unnecessary warning, fix interface conflicts 2026-01-23 22:50:43 +10:30
Cubicake 1eee0946a3 Suppress unnecessary warning 2026-01-23 22:50:26 +10:30
Cubicake f49f58749b Fail loudly 2026-01-23 22:49:57 +10:30
Cubicake 8e06c4a3d8 Mark deprecated things 2026-01-23 22:49:17 +10:30
Cubicake 1f5e428023 Since packet processor init was moved earlier, all this logic is redundant now 2026-01-23 22:06:49 +10:30
Cubicake 96a92e95e9 Make PacketEventsStatus#get() not null 2026-01-23 22:02:44 +10:30
Cubicake 5e80239c14 oops forgot to revert 2026-01-23 21:41:41 +10:30
Cubicake 8943800c59 Move init of important variables to as soon as possible 2026-01-23 21:40:39 +10:30
Cubicake 858b08d558 Increase stacktrace length 2026-01-23 21:26:30 +10:30
Cubicake 625218513f Update version check string 2026-01-19 21:30:12 +10:30
Cubicake e9cd8a031e Update version check string 2026-01-19 21:24:41 +10:30
Cubicake 4d161ca0a2 Fix a bug with the version check system so it properly checks when very out of date. 2026-01-19 21:20:59 +10:30
Cubicake 6a92d4de18 Refactor main class to be easier to read and thus maintain. 2026-01-17 20:47:34 +10:30
Cubicake b8ecbf3636 Refactor CommandsManager to be a util class, inline return variable, and rename cfg to config.
There was no stateful behaviour in this class previously, so having a useless CommandsManager object was weird.
2026-01-17 20:46:51 +10:30
Cubicake e53fad05e3 Move EntityVisibilityChangeCache to deletioncandidates 2026-01-17 20:43:16 +10:30
Cubicake 8138e326b6 Add unstable api usage warning suppression 2026-01-17 20:42:54 +10:30
Cubicake a31ba406c6 Remove unused imports 2026-01-17 20:41:29 +10:30
Cubicake 2237edc1fd Bump version 2026-01-17 20:41:17 +10:30
Cubicake f8ec2b7000 Add Locatable#toBukkitLocation as a default method 2026-01-17 20:36:26 +10:30
Cubicake 00ee95a537 Move methods 2026-01-17 20:34:20 +10:30
Cubicake 0e31708380 Label worker threads 2026-01-10 23:33:24 +01:00
Cubicake 5a3b083928 Make BukkitTVC properly handle hiding tile entities 2026-01-08 17:25:30 +01:00
Cubicake a9cc1ab604 Remove now-unneeded cast 2026-01-08 17:25:09 +01:00
Cubicake 4d20087dfa Formatting 2026-01-08 17:24:45 +01:00
Cubicake b8236c2e6d Make more of BukkitESM methods overrides of interface, add EntitySnapshotManager#removeEntityLocation 2026-01-08 17:24:33 +01:00
Cubicake d3d67de973 Add more entity tracking events to keep Bukkit EntitySnapshotManager updated 2026-01-08 17:23:49 +01:00
Cubicake 96ee9c6931 Add Locatable#clonePlainAndCentreIfBlockLocation and use it to make RaycastUtil#raycast correctly cast to the centre of the block 2026-01-08 17:23:12 +01:00
Cubicake b184eda584 Update contribution licensing terms in README
Clarified contribution rights and licensing terms in README.
2026-01-07 23:45:23 +01:00
Cubicake d15420d46a Update README.md
Add contribution notes
2026-01-07 23:37:54 +01:00
Cubicake b62a008063 Update issue templates 2026-01-07 23:35:08 +01:00
Cubicake 3e00bbf61b Update issue templates
Add bug report template
2026-01-07 23:33:36 +01:00
Cubicake 359feffdcf Insert value if it did not exist 2026-01-06 21:56:56 +01:00
Cubicake 06978953b1 TODO note 2026-01-06 21:56:37 +01:00
Cubicake e1fc76df77 Update PlayerData info when changing visibility 2026-01-06 21:56:27 +01:00
Cubicake 4153cf4aac Update permission name 2026-01-06 21:55:55 +01:00
Cubicake 2d7303eb33 Add null checks 2026-01-06 21:55:39 +01:00
Cubicake b0d8e32202 Fix bypass permission check 2026-01-06 21:04:55 +01:00
Cubicake 5649f4ad7c Comment 2026-01-05 17:53:46 +01:00
Cubicake 9e5ad8c0a3 Bump version 2026-01-05 17:53:37 +01:00
Cubicake 57848b81f8 Remove redundant comment 2026-01-02 21:28:03 +01:00
Cubicake 2dc2dbb5f7 Fix bypass permission check, populate players into entity snapshot manager on join 2026-01-02 21:27:43 +01:00
Cubicake 34690d2408 Properly call Metrics#shutdown to avoid edge-cases 2026-01-02 21:26:50 +01:00
Cubicake 90f5ddbe8a Debugging 2025-12-25 21:27:05 +10:30
Cubicake 98edc8968b Fix typo 2025-12-25 21:26:59 +10:30
Cubicake e632a5b98d Plugin name has changed 2025-12-24 18:38:23 +10:30
Cubicake 5d8c786ba4 Update error logging to include a log level so it can be excluded 2025-12-24 18:37:11 +10:30
Cubicake bd1edf8332 Remove now-incorrect JD notes 2025-12-23 22:30:14 +10:30
Cubicake 7a003368ff Hook new systems into EventListener 2025-12-23 22:29:59 +10:30
Cubicake 542d681bb4 Update main class to use new systems 2025-12-23 22:29:42 +10:30
Cubicake 500aa72106 Add processCache method 2025-12-23 22:29:22 +10:30
Cubicake e9a22ff518 Add methods to TileEntitySnapshotManager 2025-12-23 22:29:11 +10:30
Cubicake fca7cc9d2d Add processCache method 2025-12-23 22:28:48 +10:30
Cubicake 4486e60ff2 Moved stateful handling of entity caching from interface to abstract class 2025-12-23 22:28:18 +10:30
Cubicake f322ab668a Remove imports 2025-12-23 22:27:00 +10:30
Cubicake 59059248df Implement TileEntityVisibilityChanger for Bukkit 2025-12-23 22:26:48 +10:30
Cubicake b499b62745 Abstract TileEntity caching which will be used by all impls of TVC 2025-12-23 22:26:18 +10:30
Cubicake 2d7dc391ae Add enums to check which snapshot managers are present 2025-12-23 22:25:46 +10:30
Cubicake d81a7bde44 Rename methods, add compareAndSet method 2025-12-23 22:25:23 +10:30
Cubicake 149bae4ac2 Implement TileEntitySnapshotManager for Bukkit, leeching off of BukkitBSM/old ChunkSnapshotManager for now 2025-12-23 22:24:44 +10:30
Cubicake d61be5ba8d Conform EntityLocationService to the EntitySnapshotManager interface, rename to match 2025-12-23 22:23:32 +10:30
Cubicake c06fe81df3 Conform ChunkSnapshotManager to the BlockSnapshotManager interface, rename to match 2025-12-23 22:23:09 +10:30
Cubicake 9c7dd360a5 Fix bug when logging messages 2025-12-23 22:22:31 +10:30
Cubicake c58417f15b Abstract caching into its own class, share logic between Bukkit impls of entity and player visibility handling. 2025-12-22 17:03:45 +10:30
Cubicake 7b6c663510 Change visibility, add flush methods to interface 2025-12-21 22:32:01 +10:30
Cubicake 1a97a70d9b Remove methods pointing to nowhere 2025-12-21 22:31:31 +10:30
Cubicake ee473162bf Migrate away from DataHolder by separating packetevents tracking into its own class in the packets package 2025-12-19 22:32:01 +10:30
Cubicake 41b41cace6 Move interfaces into their own package with implementations 2025-12-19 22:29:40 +10:30
Cubicake 01cd0d04da Add deprecation markers 2025-12-19 22:28:33 +10:30
Cubicake 7b6aa88e0f Add getType method 2025-12-19 22:28:07 +10:30
Cubicake dbef12eb7b Refactor EventListener to use new systems 2025-12-19 22:27:34 +10:30
Cubicake 15f5d77bae Add change caching to EntityVisibilityChanger, move away from EntityVisibilityChangeCache 2025-12-19 21:43:33 +10:30
Cubicake f45c85a838 Add visibility changer types and update changeHandlers method 2025-12-19 21:42:04 +10:30
Cubicake 8cdad10f14 Change debug log defaults, rename initiateConfigManager to initialiseConfigManager 2025-12-17 17:56:54 +10:30
Cubicake ae98d76ded Remove unnecessary imports 2025-12-17 17:56:16 +10:30
Cubicake 3f1e3a170d Add toString() method for each Locatable object 2025-12-17 17:53:17 +10:30
Cubicake 3c053dbacc change interface to supply boolean instead of Material 2025-12-16 14:17:32 +10:30
Cubicake 1e0f08083e Migrate away from WrappedBukkitLocation 2025-12-16 14:17:15 +10:30
Cubicake ae66f039f7 oops forgot this method 2025-12-16 14:16:46 +10:30
Cubicake 5224317545 Can directly pass UUID 2025-12-16 14:16:32 +10:30
Cubicake 6a3a8b5768 add javadocs comment to communicate how the method works 2025-12-16 14:16:17 +10:30
Cubicake 4eeb2b5d06 Move normalize() to default locatable 2025-12-16 14:15:24 +10:30
Cubicake 0995d546da Add set method which takes boolean 2025-12-16 14:15:07 +10:30
Cubicake a01ff503f4 Add set method which takes boolean 2025-12-16 14:15:01 +10:30
Cubicake 066c6a32ea Move LocatableImpl#normalize() to default Locatable method 2025-12-16 14:14:48 +10:30
Cubicake 5d2b6c9f4a Make AbstractBlockLocation extend Locatable 2025-12-16 14:14:14 +10:30
Cubicake 7a8a7364df Add more methods 2025-12-14 22:48:53 +10:30
Cubicake 0072c9ff8e Add setEntityVisibilityForPlayer method 2025-12-14 22:48:21 +10:30
Cubicake d78f562762 Work on implementing engine 2025-12-14 22:47:05 +10:30
Cubicake c6e845527e import package changed 2025-12-14 22:46:42 +10:30
Cubicake 68cb54c0ed Add more static conversion methods 2025-12-13 19:23:05 +10:30
Cubicake 7c45f6ec4e Add default implementation of Locatable 2025-12-13 19:22:34 +10:30
Cubicake 53f0615805 Improve equals and hashcode 2025-12-13 19:22:18 +10:30
Cubicake dd9d807d92 Add min and max distance checks to RaycastUtil#raycast, optimise raycasting 2025-12-12 23:06:05 +10:30
Cubicake 902ed25a5b SnapshotManager is a static util class now 2025-12-12 15:35:06 +10:30
Cubicake 7a90d92c0a Match styling 2025-12-12 15:34:36 +10:30
Cubicake 7ca097b35c Update RaycastUtil to work with new objects, make MutableBlockVector behave like a floating-point vector except it equals and hashcodes like a BlockLocation 2025-12-11 17:03:36 +10:30
Cubicake d0a6c8475e Update RaycastUtil to work with new objects, make MutableBlockVector behave like a floating-point vector except it equals and hashcodes like a BlockLocation 2025-12-11 17:01:38 +10:30
Cubicake b1fa7e7c96 Update interface for new AbstractBlockLocation 2025-12-09 14:17:05 +10:30
Cubicake 70bbb06ee9 Create Interface Methods 2025-12-09 14:16:38 +10:30
Cubicake 8193baf9df Implement vector methods from Locatable 2025-12-09 14:16:13 +10:30
Cubicake d6e62f11ee Rename to ThreadSafeLocation, implement vector methods from Locatable 2025-12-09 14:16:00 +10:30
Cubicake 992dad2775 deletion candidate 2025-12-09 14:15:34 +10:30
Cubicake 814cf86541 deletion candidate 2025-12-09 14:15:21 +10:30
Cubicake f3e4c1cb47 Add vector methods to Locatable 2025-12-09 14:15:02 +10:30
Cubicake 0bf28b6951 Add mutable version of block location for raycast iteration, make common interface 2025-12-09 14:14:27 +10:30
Cubicake e71e9006fd Locatable package moved 2025-12-05 18:08:49 +10:30
Cubicake 06b3395d03 Change Locatable to only cover ThreadSafeLoc and WrappedBukkitLocation 2025-12-05 18:07:44 +10:30
Cubicake 222987baae Update README.md with new version 2025-11-26 17:11:29 +10:30
Cubicake a495d3946d Create util class for handling visibility change 2025-11-25 22:04:54 +10:30
Cubicake 7a514d6236 Split entity and player visibility tracking, have data modified by generic methods but invoked by entity or player specific methods 2025-11-25 22:04:13 +10:30
Cubicake 26a4d4c10c Modify TileEntitySnapshotManager interface to add methods needed for engine 2025-11-25 22:03:19 +10:30
Cubicake cbb48372ac Update RaycastUtil to use new objects 2025-11-25 22:02:43 +10:30
Cubicake ff31d9085a TODO note 2025-11-25 22:02:00 +10:30
Cubicake 1d93653422 TODO note 2025-11-25 22:01:53 +10:30
Cubicake db13824a0f Add process distribution over multiple threads, begin impl of actual checks 2025-11-25 22:01:38 +10:30
Cubicake dba313847c Change config paths to include "checks" 2025-11-25 22:00:45 +10:30
Cubicake c319a6ffd4 Clean up unnecessary files 2025-11-25 21:58:48 +10:30
Cubicake 486e5dcb36 Move logic to tile entity snapshotting manager 2025-11-18 21:00:15 +10:30
Cubicake 20842449af Formatting fix 2025-11-18 20:59:35 +10:30
Cubicake 027f62727a Make ThreadSafeLoc implement locatable 2025-11-18 20:59:06 +10:30
Cubicake 3ae7ca0d2e Create abstracted interfaces for snapshotting so that different methods of snapshotting can be implemented 2025-11-18 20:58:47 +10:30
Cubicake 3fa02c2561 Create abstracted interfaces for visibility change handling so that different methods of handling can be implemented 2025-11-18 20:58:10 +10:30
Cubicake 32a0b94f61 WIP 2025-11-13 22:16:54 +10:30
Cubicake e28b7b6f23 WIP: Abstract snapshotting so that multiple different snapshotting means can exist 2025-11-13 22:10:10 +10:30
Cubicake 2fc7e50145 WIP: Make all locations implement Locatable 2025-11-13 22:09:32 +10:30
Cubicake c56ee078c9 Merge branch 'v1.7.x' 2025-11-10 18:17:41 +10:30
Cubicake 4400151878 Merge branch 'v1.7.x' 2025-11-10 18:13:01 +10:30
Cubicake 50d0e54687 prepare for merge with v1.7.x branch 2025-11-08 17:46:10 +10:30
Cubicake 2f15ca9d5b prepare for merge with v1.7.x branch 2025-11-08 17:45:17 +10:30
Cubicake f6535848c0 prepare for merge with v1.7.x branch 2025-11-08 16:43:45 +10:30
Cubicake 4b96935f34 Change package in preparation of merge with v1.7.x branch 2025-11-08 16:43:09 +10:30
Cubicake 40b99d5c43 Clean up 2025-11-08 16:36:33 +10:30
Cubicake e448e18472 Support lower versions 2025-11-08 16:36:24 +10:30
Cubicake d806ae3c0b Support lower versions 2025-10-21 19:49:51 +10:30
Cubicake 34fe60a7ae Merge remote-tracking branch 'origin/main'
# Conflicts:
#	src/main/java/games/cubi/raycastedEntityOcclusion/Snapshot/ChunkSnapshotManager.java
2025-10-21 19:42:12 +10:30
Cubicake 0ff67e11a7 Improve Regex to handle suffixes ie v1.6.3-beta 2025-10-21 19:38:34 +10:30
Cubicake 98eaf72cae Part of the snapshot changes 2025-10-21 19:37:55 +10:30
Cubicake e5c7f6ef90 Comment 2025-10-21 19:37:27 +10:30
Cubicake da73bb26ec Temporary BlockLocation changes (v1.7.x already has a better system) 2025-10-21 19:37:04 +10:30
Cubicake bd57a9b72c Version bump 2025-10-21 19:36:26 +10:30
Cubicake 116f5e8e03 IntelliJ is having a fit 2025-10-18 16:04:25 +10:30
Cubicake bcfdd731e2 IntelliJ is having a fit 2025-10-18 15:59:17 +10:30
Cubicake e83ec5e6a2 Investigating a bug where tile entities being removed is not properly handled 2025-10-18 15:55:49 +10:30
Cubicake 2b48e7e8d2 Investigating a bug where tile entities being removed is not properly handled 2025-10-18 15:50:37 +10:30
Cubicake 7f1a284eae Remove unused import 2025-10-17 09:56:48 +10:30
Cubicake 87aba0e2b5 Fix minor bug with better version checking 2025-10-16 12:38:43 +10:30
Cubicake d46d63668b Implement better version checking 2025-10-16 12:08:49 +10:30
Cubicake 83a278b00a Add run-paper plugin, bump version number 2025-10-16 12:08:12 +10:30
Cubicake c1e0db5613 Merge remote-tracking branch 'origin/main' 2025-10-16 11:08:23 +10:30
Cubicake 34db141f08 Re-enable logging, clean up Logger.java 2025-10-16 11:08:07 +10:30
Cubicake a68bcfdbf5 Update README with dependencies and known issues 2025-10-02 21:43:39 -04:00
Cubicake 77825067de Create FUNDING.yml 2025-09-18 21:22:52 +09:30
Cubicake 085fa59e42 Disable logging temp 2025-09-05 10:00:32 +09:30
Cubicake 2db88a4498 lazy load debug particles 2025-09-03 09:00:29 +09:30
Cubicake e9935f0350 Update latest version to v1.6.1 2025-08-26 08:42:50 +09:30
Cubicake 8d39fa5427 Bump version 2025-08-13 10:55:53 +09:30
Cubicake b958d0dc46 Make intellij shut up 2025-08-12 12:05:36 +09:30
Cubicake e9adb65690 Instead of throwing an error, try and fx the situation. 2025-08-12 12:03:16 +09:30
Cubicake 6a289c81a9 Check world so that distance check doesn't error 2025-08-12 10:40:05 +09:30
Cubicake 34b04ff059 Include update link in update checker 2025-08-11 21:17:52 +09:30
Cubicake 1a73c2509a Fix the previous commit 2025-08-11 20:49:45 +09:30
Cubicake e3731f76f0 Debug mode logging 2025-08-11 20:49:14 +09:30
Cubicake bd1f6ad482 Don't spawn a new thread for each tile entity update 2025-08-11 20:36:26 +09:30
Cubicake 951e4f4ad9 Fix change delta being ignored 2025-08-11 20:28:22 +09:30
Cubicake 114746aeaf Resolves #11 2025-08-11 20:08:06 +09:30
Cubicake 9dc9652917 Use snapshotChunk 2025-08-11 18:03:29 +09:30
Cubicake b97f675159 Bump version 2025-08-11 18:03:08 +09:30
Cubicake f5e16fc75d Resolves #10
OMFG I hate myself
2025-08-11 18:02:48 +09:30
Cubicake c228cef24a Merge remote-tracking branch 'origin/main' 2025-08-09 16:19:36 +09:30
Cubicake 098aab5e31 Don't hardcode plugin name 2025-08-09 16:19:20 +09:30
Cubicake 31b500bc7b Fix bug in issue #9 2025-08-04 11:35:13 +09:30
Cubicake d5e3281cf2 new config layout, to replace config.yml at a later date 2025-08-04 11:33:47 +09:30
Cubicake 98dbefd576 For future packet handling 2025-08-04 11:33:17 +09:30
Cubicake 4dce9b3278 WIP improved debugging 2025-08-04 11:32:45 +09:30
Cubicake d5bf02b4ea Merge remote-tracking branch 'origin/main' 2025-07-27 18:52:36 +09:30
Cubicake ed98e2abeb Update README.md 2025-07-27 17:39:13 +09:30
Cubicake 9a07bd0119 v1.6.0 release 2025-07-27 17:21:42 +09:30
Cubicake 74aca26910 Update .gitignore 2025-07-27 16:32:49 +09:30
Cubicake 25f5652a12 Kinda crappy way to hopefully fix the missing snapshots while I work on a more permanant fix 2025-07-27 16:08:40 +09:30
Cubicake 7679f08d06 Use the new logger to format messages 2025-07-27 16:07:26 +09:30
Cubicake 7ad99917d1 Might use this later? 2025-07-27 16:06:44 +09:30
Cubicake ce56eb316e Might use this later? 2025-07-27 16:06:39 +09:30
Cubicake 74426d80af Mark as mojmapped 2025-07-27 16:06:13 +09:30
Cubicake fdb1f567ac Snapshot changes 2025-07-26 16:26:14 +09:30
Cubicake e823f7a2f7 Move string operations to their own methods 2025-07-26 16:25:15 +09:30
Cubicake 7c1f7fd2a6 Version bump 2025-07-25 20:35:25 +09:30
Cubicake c26e6a1623 Oops forgot to pass config to movement tracker 2025-07-25 20:35:16 +09:30
Cubicake 8155903342 More readable imports 2025-07-25 20:32:53 +09:30
Cubicake f2ade6b0b8 Merge remote-tracking branch 'origin/main' 2025-07-25 20:31:26 +09:30
Cubicake f486d1fc2e Stop intellij from complaining 2025-07-25 20:30:09 +09:30
Cubicake 50eeab8cfe Bump api version 2025-07-25 20:26:37 +09:30
Cubicake 4009fe6d02 Use built in bukkit chunk keys instead of making custom ones 2025-07-25 20:26:25 +09:30
Cubicake b7e6fa9c5f Stop using * imports, use plugin logger, use built in bukkit chunk keys instead of making custom ones, hopefully fix chunks not being snapshotted. 2025-07-25 20:25:44 +09:30
Cubicake dcc986c232 Stop using * imports 2025-07-23 13:47:52 +09:30
Cubicake 95cea9f875 Stop using * imports 2025-07-23 13:47:20 +09:30
220 changed files with 20122 additions and 4024 deletions

No files matched your search

+2 -2
View File
@@ -3,7 +3,7 @@
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: cubicake
ko_fi: #cubicake
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
@@ -12,4 +12,4 @@ lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cl
polar: # Replace with a single Polar username
buy_me_a_coffee: # Replace with a single Buy Me a Coffee username
thanks_dev: # Replace with a single thanks.dev username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
custom: ['https://cubi.games/donate/variable']# Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
+26
View File
@@ -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.
+20
View File
@@ -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.
+5 -2
View File
@@ -3,6 +3,7 @@
README.md
*.md
*.toml
*.iml
*.ipr
@@ -105,6 +106,7 @@ $RECYCLE.BIN/
*.lnk
.gradle
.gradle-user/
build/
# Ignore Gradle GUI config
@@ -116,8 +118,9 @@ gradle-app.setting
**/build/
# Common working directory
run/
runs/
run*/
# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
!gradle-wrapper.jar
# Libraries are supposed to be committed
!libraries/*/*
+10
View File
@@ -0,0 +1,10 @@
[submodule "logging"]
path = logging
url = https://github.com/Cubicake/CubiLogging.git
[submodule "leafpile"]
path = leafpile
url = https://github.com/Cubicake/ParallelepipedLeafPile.git
branch = java-21-main
[submodule "locatables"]
path = locatables
url = https://github.com/Cubicake/Locatables.git
+19
View File
@@ -0,0 +1,19 @@
## Contributions
Contributions via pull requests are welcome. Please join our [discord](https://discord.cubi.games) or make an `issue` to discuss any contributions beforehand to make sure they will not conflict with or hinder existing plans.
A good place to start with contributions is to look for `issue`s flagged with the label `Outside Help Welcome`. These have been deemed as uninvasive changes, typically not requiring a complete understanding of the project. You are welcome to send a PR resolving these issues without first discussing changes with a maintainer.
You must hold the rights to any code you contribute, and must agree to licence it under the same licence as the rest of the project in perpetuity, explicitly including any and all changes to the project's licence by project maintainers in the future. The project's licence can always be found at [LICENSE](LICENSE).
### Attribution
Code files may have a copyright notice at the head of the file as follows.
```java
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP.
* RaycastedAntiESP is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at https://www.gnu.org/licenses/agpl-3.0.html.
* See README.md for warranty disclaimer and further information.
*/
```
If you made a significant contribution to a file with such a header, you may add your name to the list of names in the copyright notice. Contributing project maintainers should be listed first. All other names should be listed in descending order of contribution to the file, adjudicated by `Cubicake` if necessary. If the list of contributors reaches six names, do not add any more names to the list. You may instead append the text `and other contributors`.
+88 -16
View File
@@ -1,24 +1,96 @@
Latest version: v1.6.0
RaycastedAntiESP is a packet-based plugin for Paper, Folia, and its forks that hides entities (including players) and tile entities (blocks such as chests, banners, signs, etc) from players if they would not be visible to a legitimate player. It is **unbypassable** by design, as packets sent by the server are blocked from reaching the client unless the block/entity has been confirmed to be visible.
This limits the usefulness of unfair advantages such as cheat clients, freecam, and x-ray, and completely blocks pie-ray.
The latest version can currently only be found on Modrinth https://modrinth.com/plugin/raycasted-entity-occlusions/
### Supported Versions
While the current "stable" plugin version is v1.6.5, it is strongly recommended that you use the [alpha-channel builds](https://modrinth.com/plugin/raycasted-anti-esp/versions?c=alpha) instead. Since v1.6.5, RaycastedAntiESP has been:
- Renamed from RaycastedEntityOcclusions to RaycastedAntiESP
- Been almost completely rewritten to be faster and more correct
This is 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.
The supported minecraft versions are 1.21.4+. Only Paper and derivative software (including Folia/Canvas) is supported, not Spigot.
The supported versions are 1.21.x PaperMC and Pufferfish. Other server versions and software may work too.
Use cases:
## Use cases:
- Prevent cheating (anti-esp hacks)
- Block usage of pie-ray to locate underground bases
- Prevent mods such as mini-maps or cheat clients from displaying the locations of hidden entities
- This is the plugin's primary purpose.
- Block usage of pie-ray to locate underground bases or farms.
- Prevent mods such as mini-maps or cheat clients from displaying the locations of entities which would not be visible to vanilla players.
- Increase client-side performance for low-end devices
- Massive megabases containing hundreds of armour stands, item frames, banners etc can cause performance issues on low-end devices unable to process so many entities. REO will cull those entities for the client, reducing the number of entities to process.
- Massive megabases containing hundreds of armour stands, item frames, banners etc can cause performance issues on low-end devices unable to process so many entities. Raycasted AntiESP will cull those entities for the client, reducing the number of entities to process.
- Reduce network load by limiting packets
- With `keep-client-entity-when-hidden` set to true, running RaycastedAntiESP will significantly reduce the number of entity packets sent to the client.
- While entity packets are only a small portion of network bandwidth, this will still have a measurable impact and may be useful on extremely bandwidth-limited servers.
- Unless you are extremely limited by bandwidth, this will probably be unnoticeable.
- Hide nametags behind walls
- Yes, this plugin is a bit overkill for doing that, yes you can do it anyways.
Dependencies:
- Packetevents (soft depend)
- Only needed if you are using the cull-players option and wish for the players to remain in the tablist
- Yes, this plugin is overkill for doing that, yes you can do it anyways.
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.
## Configuration
RaycastedAntiESP has many configuration options. A full list with explanations can be found at https://raycastedantiesp.cubi.games/config/.
## Dependencies:
- Packetevents
- Required for all features, as packets are intercepted and rewritten to make sure that clients never learn about anything they should not be able to see.
## Known issues:
- There will be a short delay once an entity should be visible before it appears, causing it to appear like it "popped" into view. Various config options exist to partially address this issue, though all such options necessarily weaken the plugin's ability to block cheaters.
## Versioning:
Note that the following versioning information only applies to v2 and beyond, and alpha versions of v2 start with a major version number of 0 rather than 2.
RaycastedAntiESP binaries are composed of four distinct modules: the core, Locatable-lib (used for platform-independent location objects), [CubiLogging](https://github.com/Cubicake/CubiLogging/tree/main), and a platform adapter.
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.
## Credits:
- Cubicake (Sole developer and maintainer of RaycastedAntiESP)
### Special mentions:
- Strokkur424 and other contributors to [StrokkCommands](https://github.com/Strokkur424/StrokkCommands), an LGPL-licensed open-source annotation-based brigadier command tree generator.
- While StrokkCommands is not essential for the functioning of the project, it makes handling commands infinitely easier.
- Retrooper, Booky10, and all other contributors to [PacketEvents](https://github.com/retrooper/packetevents), a GPL-licensed open-source library for handling minecraft packets.
- PacketEvents is essential for the functioning of the plugin, as it allows for handling of packets across multiple platforms and Minecraft versions.
- All contributors to Paper and its upstream projects Spigot and Bukkit, without which none of this would be possible.
### Note about in-game attributions and other (A)GPL requirements:
The plugin includes the command `/raycastedantiespCredits`, which displays a list of all authors and contributors, the license and a link to the source code. It can be run by all players. This command is intended to satisfy the "preservation of specified reasonable legal notices or author attributions" requirement of the AGPLv3 license in an easily accessible way for all users of the plugin, including players on a multiplayer server. If you fork this repository and remove the command you must include some other easily accessible way for all users of your fork to view the same information, as required by the AGPLv3.
This command has been deliberately named a long and unwieldy name to avoid clashing with any commands your server may wish to add, and does not pose any risks to your server as there is no unfair advantage which can be gained due to knowledge of the plugin's existence on your server.
It is **illegal** to remove the credits without providing an alternative, equally prominent way for users to view the same information. If for some reason crediting people who have worked on a feature for your server for free is a problem for you, you can contact Cubicake on discord (@cubicake) or make an issue to discuss receiving a specially licensed version with all attributions, credits, and source code links removed.
Using external software such as a command-hiding plugin to hide the command is **still illegal**, so please do not try to circumvent the requirement to provide attributions, credits, and source code links to users of your server.
Requesting a custom license is also required if you wish to link (as defined by the AGPL) a closed source project to this project.
An example of a suitable alternative to the command would be a single book-gui or dialog which contains all attributions, licenses, disclaimers, and source code links for all programs used by the server as long as the gui is easily accessible to all users of the server. Another example would be an NPC placed somewhere at your server's spawn which provides the information, as long as the NPC is not hidden somewhere difficult to access.
## Contributions:
Contributions via pull requests are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md) for details.
## Forking:
Please see the [AGPLv3 license](LICENSE)—especially section 5, section 7, and section 13—before forking this repository, as there are some specific legal requirements for forks.
In summary, translated into layman, plugin-specific terms, the most important requirements for forks are as follows:
1. Forks must not remove any names currently present in the authors/contributors list in the plugin's description, as this falls under the "preservation of specified reasonable legal notices or author attributions".
2. Forks must not claim to be the original software, as this falls under the "no misrepresentation of the origin of the material".
3. Per section 5 subsection c, derivative works such as forks must remain licenced under AGPLv3, and must include a copy of the license with the work. To be clear, copying any non-trivial amount of code from this repository into your own repository, whether via making a fork, directly copying and pasting or other means, makes it a derivative work and obligates you to license your derivative work under the AGPL v3. You must then include a copy of the license and make the source code (not decompiled code) accessible to all users of your program, explicitly including players on a multiplayer server as well as the server owners.
4. "Appropriate Legal Notices" such as the copyright notice, license notice, disclaimer, and link to the source code must be preserved. Currently this is implemented via the `/raycastedantiespCredits` command, and while you are not obligated to keep this specific implementation, if you remove the command you must provide an equally prominent way for all users of the plugin (including players on a multiplayer server) to easily view the same information.
`games.cubi.raycastedantiesp.paper.commands.Attribution` has been written with forks in mind, and a template has been left for forks to modify so that the AGPLv3 license can be obeyed with minimal effort.
## Copyright and Disclaimer:
Copyright © 2025-2026 Cubicake
This project is licensed under the GNU Affero General Public License v3.0 only (AGPLv3). You may copy, modify, and redistribute this software only in compliance with the terms of that licence. A copy of the licence is provided in the [LICENSE](LICENSE) file.
If you modify and deploy this software for remote network interaction, including operating a public multiplayer server, you must make the complete corresponding source code of the modified version available to all users interacting with the software over the network, as required by section 13 of the AGPLv3.
Any modified versions must be clearly marked as modified and must not be misrepresented as the original project.
This software is provided “as is”, without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages, or other liability arising from, out of, or in connection with the software or the use of the software.
The AGPL is the sole license this program is governed by. All statements found in this copyright notice and disclaimer, the above forking guidelines, or anywhere else in this program should only be considered guidelines and interpretations of the AGPL unless they are direct extracts of the AGPL. If any statement conflicts with the AGPL, the AGPL takes legal precedence over any such statement. However, any such conflicting statements should be taken as good-faith non-binding requests by the authors.
-69
View File
@@ -1,69 +0,0 @@
plugins {
id 'java'
id("xyz.jpenilla.run-paper") version "2.3.1"
}
group = 'games.cubi'
version = '1.7.0-pre-alpha'
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.8-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
}
}
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.
minecraftVersion("1.21.8")
}
}
jar {
manifest {
attributes "paperweight-mappings-namespace": "mojang"
}
}
+1
View File
@@ -0,0 +1 @@
extra["patchedConfigurateYaml"] = files("libraries/configurate-yaml/yaml-4.3.0-SNAPSHOT-cubi.jar")
+102
View File
@@ -0,0 +1,102 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
import java.time.Instant
import org.gradle.api.file.FileCollection
plugins {
id("java-library")
}
val patchedConfigurateYaml = rootProject.extra["patchedConfigurateYaml"] as FileCollection
repositories {
mavenCentral()
maven { url = uri("https://repo.codemc.io/repository/maven-releases/") }
maven { url = uri("https://repo.codemc.io/repository/maven-snapshots/") }
}
dependencies {
compileOnly("org.spongepowered:configurate-core:4.2.0")
compileOnly(patchedConfigurateYaml)
compileOnly("it.unimi.dsi:fastutil:8.5.18")
implementation(project(":locatables"))
compileOnly(project(":leafpile"))
compileOnly(project(":logging"))
testImplementation(platform("org.junit:junit-bom:5.10.2"))
testImplementation("org.junit.jupiter:junit-jupiter-api")
testImplementation(project(":leafpile"))
testImplementation(project(":logging"))
testImplementation("org.spongepowered:configurate-core:4.2.0")
testImplementation(patchedConfigurateYaml)
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
testImplementation("it.unimi.dsi:fastutil:8.5.18")
}
val coreVersion = "0.7.2-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)
}
}
test {
useJUnitPlatform()
}
}
java {
toolchain.languageVersion = JavaLanguageVersion.of(21)
}
@@ -0,0 +1,38 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core;
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,17 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core;
import java.util.function.IntSupplier;
/**
* Implementations should increment (starting from 0) once a tick, and should call AsyncEngine's tick method each time the tick increments.
*/
public interface Ticker extends IntSupplier {
}
@@ -0,0 +1,45 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.chunks;
import games.cubi.raycastedantiesp.core.chunks.blocks.BlockChunkDataBuilder;
import games.cubi.raycastedantiesp.core.chunks.blocks.SingleBlockChunkData;
import java.util.function.IntUnaryOperator;
public interface BlockChunkData extends ChunkOcclusionView {
/**
* char is used to denote an unsigned 16-bit integer.
*/
char getBlockID(int x, int y, int z);
/**
* char is used to denote an unsigned 16-bit integer.
*/
BlockChunkData setBlockID(int x, int y, int z, char blockID, BlockInfoResolver blockInfoResolver);
static BlockChunkData filled(char blockID, BlockInfoResolver blockInfoResolver) {
return new SingleBlockChunkData(blockID, blockInfoResolver.isOccluding(blockID));
}
/**
* Builds chunk data from a source palette. The index reader receives core-packed positions and returns an index into {@code sourcePalette}.
* Unused source entries are discarded before choosing the smallest representation.
*/
static BlockChunkData copyOfPalette(char[] sourcePalette, IntUnaryOperator paletteIndexAtPacked, BlockInfoResolver blockInfoResolver) {
return BlockChunkDataBuilder.copyOfPalette(sourcePalette, paletteIndexAtPacked, blockInfoResolver);
}
/**
* Builds chunk data from a block-state reader. The reader receives core-packed positions.
*/
static BlockChunkData copyOfStates(IntUnaryOperator blockStateAtPacked, BlockInfoResolver blockInfoResolver) {
return BlockChunkDataBuilder.copyOfStates(blockStateAtPacked, blockInfoResolver);
}
}
@@ -0,0 +1,28 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.chunks;
import org.jetbrains.annotations.Contract;
public interface BlockInfoResolver {
@Contract(pure = true)
boolean isOccluding(int blockStateID);
/**
* Anti-ESP managed tile entity state after config exemptions and force-includes.
*/
@Contract(pure = true)
boolean isTileEntity(int blockStateID);
/**
* Raw block entity capability before anti-ESP config overrides.
*/
@Contract(pure = true)
boolean hasBlockEntityData(int blockStateID);
}
@@ -0,0 +1,60 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.chunks;
public final class ChunkData {
public static final int CHUNK_SIZE = 16;
public static final int LOCAL_MASK = CHUNK_SIZE - 1;
public static final int BLOCK_COUNT = CHUNK_SIZE * CHUNK_SIZE * CHUNK_SIZE;
public static final int WORD_COUNT = BLOCK_COUNT / Long.SIZE;
private ChunkData() {
}
public static int packLocalChecked(int x, int y, int z) {
checkLocalCoordinate(x, "x");
checkLocalCoordinate(y, "y");
checkLocalCoordinate(z, "z");
return packUncheckedGuarded(x, y, z);
}
/**
* Packs the local coordinates into a single integer without checking bounds. Coordinates outside the range will be correctly packed.
*/
public static int packUncheckedGuarded(int x, int y, int z) {
return (z & LOCAL_MASK) << 8 | (y & LOCAL_MASK) << 4 | (x & LOCAL_MASK);
}
public static int unpackX(int packed) {
checkPacked(packed);
return packed & LOCAL_MASK;
}
public static int unpackY(int packed) {
checkPacked(packed);
return packed >> 4 & LOCAL_MASK;
}
public static int unpackZ(int packed) {
checkPacked(packed);
return packed >> 8 & LOCAL_MASK;
}
public static void checkPacked(int packed) {
if (packed < 0 || packed >= BLOCK_COUNT) {
throw new IllegalArgumentException("packed local block index must be in [0, " + (BLOCK_COUNT - 1) + "], but was " + packed);
}
}
private static void checkLocalCoordinate(int coordinate, String name) {
if (coordinate < 0 || coordinate >= CHUNK_SIZE) {
throw new IllegalArgumentException(name + " local coordinate must be in [0, " + LOCAL_MASK + "], but was " + coordinate);
}
}
}
@@ -0,0 +1,30 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.chunks;
import org.jetbrains.annotations.Range;
import static games.cubi.raycastedantiesp.core.chunks.ChunkData.LOCAL_MASK;
public interface ChunkOcclusionView {
/**
* The parameters here are local coordinates within the chunk section, so they must be in the range [0, 15].
*
* @return true if the block at the given local coordinates is occluding, false otherwise.
*/
boolean isOccludingLocal(@Range(from = 0, to = 15) int x, @Range(from = 0, to = 15) int y, @Range(from = 0, to = 15) int z);
default boolean isOccludingGlobal(int x, int y, int z) {
return isOccludingLocal(x & LOCAL_MASK, y & LOCAL_MASK, z & LOCAL_MASK);
}
default boolean isSolid() {
return false;
}
}
@@ -0,0 +1,62 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.chunks;
import org.jetbrains.annotations.Range;
import java.util.BitSet;
public sealed interface OccludingChunkData extends ChunkOcclusionView permits OccludingChunkData.Solid, OccludingChunkDataImpl {
/**
* The parameters here are local coordinates within the chunk, so they should be in the range [0, 15].
* @return The object to be stored. Mutations may require upgrading the object to a more complex implementation, so the returned object may not be the same as the current one.
*/
OccludingChunkData setOccluding(@Range(from = 0, to = 15) int x, @Range(from = 0, to = 15) int y, @Range(from = 0, to = 15) int z, boolean occluding);
static OccludingChunkDataImpl empty() {
return new OccludingChunkDataImpl();
}
static OccludingChunkData filled() {
return OccludingChunkDataImpl.solid();
}
OccludingChunkData SOLID = new Solid();
static OccludingChunkData solid() {
return SOLID;
}
static OccludingChunkData copyOf(BitSet bitSet) {
long[] words = bitSet.toLongArray();
if (words.length != ChunkData.WORD_COUNT) {
long[] resized = new long[ChunkData.WORD_COUNT];
System.arraycopy(words, 0, resized, 0, Math.min(words.length, resized.length));
words = resized;
}
return new OccludingChunkDataImpl(words);
}
final class Solid implements OccludingChunkData {
@Override
public boolean isOccludingLocal(int x, int y, int z) {
return true;
}
@Override
public OccludingChunkData setOccluding(int x, int y, int z, boolean occluding) {
return filled().setOccluding(x, y, z, occluding);
}
@Override
public boolean isSolid() {
return true;
}
}
}
@@ -0,0 +1,70 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.chunks;
import java.util.Arrays;
import static games.cubi.utils.VarHandler.LONG_ARRAY_HANDLE;
/**
* A 4096-bit bitset, where 1 indicates occluding and 0 indicates not occluding.
* Safe for single-writer, multiple-reader setups
*/
public final class OccludingChunkDataImpl implements OccludingChunkData {
// Plain reads/writes would probably be fine as occluding state being stale for a few seconds causes no issues, and tearing is a non-issue as this is a bitset, so only a single bit value matters at a time.
// However, plain reads can technically be cached indefinitely, so opaque reads are more correct.
private final long[] occlusionData;
public OccludingChunkDataImpl() {
this.occlusionData = new long[ChunkData.WORD_COUNT];
}
public OccludingChunkDataImpl(long[] occlusionData) {
if (occlusionData.length != ChunkData.WORD_COUNT) {
throw new IllegalArgumentException("occlusionData must contain " + ChunkData.WORD_COUNT + " longs");
}
this.occlusionData = Arrays.copyOf(occlusionData, occlusionData.length);
}
static OccludingChunkDataImpl solid() {
// Make every bit 1, which is the same as making every long -1
long[] solidData = new long[ChunkData.WORD_COUNT];
Arrays.fill(solidData, -1L);
return new OccludingChunkDataImpl(solidData);
}
@Override
public boolean isOccludingLocal(int x, int y, int z) {
int packed = ChunkData.packLocalChecked(x, y, z);
// >>> 6 divides the packed block index by 64 to select the containing long.
int wordIndex = packed >>> 6;
// 1L << packed creates a mask with only the packed block's bit set.
long mask = 1L << packed;
long word = (long) LONG_ARRAY_HANDLE.getOpaque(occlusionData, wordIndex);
// & keeps only the target bit; non-zero means that bit is set.
return (word & mask) != 0;
}
@Override
public OccludingChunkData setOccluding(int x, int y, int z, boolean occluding) {
int packed = ChunkData.packLocalChecked(x, y, z);
// >>> 6 divides the packed block index by 64 to select the containing long. Avoids signed division; probably an unnecessary optimisation but why not
int wordIndex = packed >>> 6;
// 1L << packed creates a mask for only the packed block's bit.
long mask = 1L << packed;
long word = (long) LONG_ARRAY_HANDLE.getOpaque(occlusionData, wordIndex);
// If occluding is true, OR the mask in to set the bit; otherwise AND with ~mask to clear it.
// ~ flips all bits, so mask becomes all 1 except for the bit being set to 0. ANDing this means that anything in word which was already true stays true and already false stays false, except for the bit being set to false.
long updated = occluding ? word | mask : word & ~mask;
// Not an atomicity issue since writes are single-threaded
LONG_ARRAY_HANDLE.setOpaque(occlusionData, wordIndex, updated);
return this;
}
}
@@ -0,0 +1,152 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.chunks.blocks;
import games.cubi.raycastedantiesp.core.chunks.BlockChunkData;
import games.cubi.raycastedantiesp.core.chunks.BlockInfoResolver;
import games.cubi.raycastedantiesp.core.chunks.ChunkData;
import java.util.Arrays;
import static games.cubi.utils.VarHandler.CHAR_ARRAY_HANDLE;
import static games.cubi.utils.VarHandler.LONG_ARRAY_HANDLE;
abstract class AbstractPalettedBlockChunkData implements BlockChunkData {
// Each concrete palette store allocates its maximum palette size up front. Adding a block only fills another slot in this array.
// When the palette is full, the chunk upgrades to the next implementation.
protected final char[] palette;
protected final long[] occlusionData;
private int paletteSize; //netty reads only
protected AbstractPalettedBlockChunkData(char blockID, int paletteCapacity, BlockInfoResolver blockInfoResolver) {
if (paletteCapacity < 1 || paletteCapacity > 256) {
throw new IllegalArgumentException("paletteCapacity must be in [1, 256]");
}
this.palette = new char[paletteCapacity];
this.occlusionData = new long[ChunkData.WORD_COUNT];
setPaletteBlock(0, blockID);
paletteSize = 1;
if (blockInfoResolver.isOccluding(blockID)) {
Arrays.fill(this.occlusionData, -1L);
}
}
protected AbstractPalettedBlockChunkData(char[] palette, int paletteSize, int paletteCapacity, long[] occlusionData) {
if (paletteCapacity < 1 || paletteCapacity > 256) {
throw new IllegalArgumentException("paletteCapacity must be in [1, 256]");
}
if (paletteSize < 1 || paletteSize > paletteCapacity || palette.length < paletteSize) {
throw new IllegalArgumentException("paletteSize must be in [1, paletteCapacity]");
}
if (occlusionData.length != ChunkData.WORD_COUNT) {
throw new IllegalArgumentException("occlusionData must contain " + ChunkData.WORD_COUNT + " longs");
}
this.palette = new char[paletteCapacity];
for (int i = 0; i < paletteSize; i++) {
setPaletteBlock(i, palette[i]);
}
this.occlusionData = Arrays.copyOf(occlusionData, occlusionData.length);
this.paletteSize = paletteSize;
}
protected AbstractPalettedBlockChunkData(AbstractPalettedBlockChunkData source, int paletteCapacity) {
this(source.palette, source.paletteSize, paletteCapacity, source.occlusionData);
}
@Override
public final char getBlockID(int x, int y, int z) {
return getBlockIDPackedUnchecked(ChunkData.packLocalChecked(x, y, z));
}
protected final char getBlockIDPacked(int packed) {
ChunkData.checkPacked(packed);
return paletteBlock(getPaletteIndex(packed));
}
private char getBlockIDPackedUnchecked(int packed) {
return paletteBlock(getPaletteIndex(packed));
}
@Override
public final boolean isOccludingLocal(int x, int y, int z) {
int packed = ChunkData.packLocalChecked(x, y, z);
return isOccludingPacked(packed);
}
@Override
public final BlockChunkData setBlockID(int x, int y, int z, char blockID, BlockInfoResolver blockInfoResolver) {
int packed = ChunkData.packLocalChecked(x, y, z);
int paletteIndex = indexOf(blockID);
if (paletteIndex >= 0) {
setPaletteIndex(packed, paletteIndex);
setOccludingPacked(packed, blockInfoResolver.isOccluding(blockID));
return this;
}
if (!canAddPaletteEntry()) {
return upgrade().setBlockID(x, y, z, blockID, blockInfoResolver);
}
paletteIndex = addPaletteEntry(blockID);
setPaletteIndex(packed, paletteIndex);
setOccludingPacked(packed, blockInfoResolver.isOccluding(blockID));
return this;
}
protected abstract int getPaletteIndex(int packed);
protected abstract void setPaletteIndex(int packed, int paletteIndex);
protected abstract BlockChunkData upgrade();
private int indexOf(char blockID) {
int size = paletteSize;
for (int i = 0; i < size; i++) {
if (paletteBlock(i) == blockID) {
return i;
}
}
return -1;
}
private boolean canAddPaletteEntry() {
return paletteSize < palette.length;
}
private int addPaletteEntry(char blockID) {
int size = paletteSize;
setPaletteBlock(size, blockID);
paletteSize = size + 1;
return size;
}
protected final boolean isOccludingPacked(int packed) {
ChunkData.checkPacked(packed);
int wordIndex = packed >>> 6;
long mask = 1L << packed;
long word = (long) LONG_ARRAY_HANDLE.getOpaque(occlusionData, wordIndex);
return (word & mask) != 0;
}
protected final void setOccludingPacked(int packed, boolean occluding) {
ChunkData.checkPacked(packed);
int wordIndex = packed >>> 6;
long mask = 1L << packed;
long word = (long) LONG_ARRAY_HANDLE.getOpaque(occlusionData, wordIndex);
long updated = occluding ? word | mask : word & ~mask;
LONG_ARRAY_HANDLE.setOpaque(occlusionData, wordIndex, updated);
}
protected final char paletteBlock(int index) {
return (char) CHAR_ARRAY_HANDLE.getAcquire(palette, index);
}
protected final void setPaletteBlock(int index, char blockID) {
CHAR_ARRAY_HANDLE.setRelease(palette, index, blockID);
}
}
@@ -0,0 +1,133 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.chunks.blocks;
import games.cubi.raycastedantiesp.core.chunks.BlockChunkData;
import games.cubi.raycastedantiesp.core.chunks.BlockInfoResolver;
import games.cubi.raycastedantiesp.core.chunks.ChunkData;
import java.util.Arrays;
import java.util.function.IntUnaryOperator;
public final class BlockChunkDataBuilder {
private static final int BYTE_PALETTE_LIMIT = 256;
private BlockChunkDataBuilder() {
}
public static BlockChunkData copyOfPalette(char[] sourcePalette, IntUnaryOperator sourceIndexAtPacked, BlockInfoResolver blockInfoResolver) {
if (sourcePalette.length == 0 || sourcePalette.length > BYTE_PALETTE_LIMIT) {
throw new IllegalArgumentException("sourcePalette must contain between 1 and " + BYTE_PALETTE_LIMIT + " entries");
}
// First compact only the source entries actually referenced by the 4,096 blocks.
int[] remap = new int[sourcePalette.length];
Arrays.fill(remap, -1);
char[] compactPalette = new char[sourcePalette.length];
int compactSize = 0;
for (int packed = 0; packed < ChunkData.BLOCK_COUNT; packed++) {
int sourceIndex = checkedPaletteIndex(sourceIndexAtPacked.applyAsInt(packed), sourcePalette.length);
if (remap[sourceIndex] == -1) {
remap[sourceIndex] = compactSize;
compactPalette[compactSize++] = sourcePalette[sourceIndex];
}
}
final int usedPaletteSize = compactSize;
// Readers are intentionally invoked again below; rescanning avoids a 4,096-entry temporary index array.
IntUnaryOperator compactIndexAtPacked = packed -> {
int sourceIndex = checkedPaletteIndex(sourceIndexAtPacked.applyAsInt(packed), sourcePalette.length);
return remap[sourceIndex];
};
char[] usedPalette = Arrays.copyOf(compactPalette, usedPaletteSize);
if (usedPaletteSize == 1) {
return new SingleBlockChunkData(usedPalette[0], blockInfoResolver.isOccluding(usedPalette[0]));
}
if (usedPaletteSize == 2) {
long[] bitData = new long[ChunkData.WORD_COUNT];
for (int packed = 0; packed < ChunkData.BLOCK_COUNT; packed++) {
if (compactIndexAtPacked.applyAsInt(packed) == 1) {
setPackedBit(bitData, packed);
}
}
return new TwoBlockChunkData(usedPalette[1], usedPalette[0], blockInfoResolver.isOccluding(usedPalette[1]), blockInfoResolver.isOccluding(usedPalette[0]), bitData);
}
if (usedPaletteSize <= 4) {
return new FourBlockChunkData(usedPalette, usedPaletteSize, compactIndexAtPacked, blockInfoResolver);
}
if (usedPaletteSize <= 16) {
return new SixteenBlockChunkData(usedPalette, usedPaletteSize, compactIndexAtPacked, blockInfoResolver);
}
return new ByteArrayBlockChunkData(usedPalette, usedPaletteSize, compactIndexAtPacked, blockInfoResolver);
}
public static BlockChunkData copyOfStates(IntUnaryOperator blockStateAtPacked, BlockInfoResolver blockInfoResolver) {
char[] palette = new char[BYTE_PALETTE_LIMIT];
int paletteSize = 0;
boolean overflow = false;
// Global palettes have no local index table. Discover whether a byte palette is possible without storing 4,096 indices.
for (int packed = 0; packed < ChunkData.BLOCK_COUNT; packed++) {
char blockID = checkedBlockID(blockStateAtPacked.applyAsInt(packed));
if (!overflow && indexOf(palette, paletteSize, blockID) < 0) {
if (paletteSize == BYTE_PALETTE_LIMIT) {
overflow = true;
} else {
palette[paletteSize++] = blockID;
}
}
}
if (!overflow) {
// Delegate to the compact palette path; the state reader is rescanned to keep temporary allocation bounded by palette size.
final int size = paletteSize;
char[] sourcePalette = Arrays.copyOf(palette, size);
return copyOfPalette(sourcePalette, packed -> indexOf(sourcePalette, size, checkedBlockID(blockStateAtPacked.applyAsInt(packed))), blockInfoResolver);
}
// More than 256 states require final direct storage, populated together with its occlusion mask.
char[] blockData = new char[ChunkData.BLOCK_COUNT];
long[] occlusionData = new long[ChunkData.WORD_COUNT];
for (int packed = 0; packed < ChunkData.BLOCK_COUNT; packed++) {
char blockID = checkedBlockID(blockStateAtPacked.applyAsInt(packed));
blockData[packed] = blockID;
if (blockInfoResolver.isOccluding(blockID)) {
setPackedBit(occlusionData, packed);
}
}
return new CharArrayBlockChunkData(blockData, occlusionData, true);
}
private static int indexOf(char[] palette, int paletteSize, char blockID) {
for (int index = 0; index < paletteSize; index++) {
if (palette[index] == blockID) {
return index;
}
}
return -1;
}
private static int checkedPaletteIndex(int paletteIndex, int paletteSize) {
if (paletteIndex < 0 || paletteIndex >= paletteSize) {
throw new IllegalArgumentException("palette index must be in [0, " + (paletteSize - 1) + "], but was " + paletteIndex);
}
return paletteIndex;
}
private static char checkedBlockID(int blockID) {
if (blockID < 0 || blockID > Character.MAX_VALUE) {
throw new IllegalArgumentException("blockID must fit in an unsigned 16-bit value, but was " + blockID);
}
return (char) blockID;
}
private static void setPackedBit(long[] data, int packed) {
// packed >>> 6 selects the 64-bit word; Java masks the long shift distance to packed & 63 for the bit.
data[packed >>> 6] |= 1L << packed;
}
}
@@ -0,0 +1,62 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.chunks.blocks;
import games.cubi.raycastedantiesp.core.chunks.BlockChunkData;
import games.cubi.raycastedantiesp.core.chunks.BlockInfoResolver;
import games.cubi.raycastedantiesp.core.chunks.ChunkData;
import java.util.function.IntUnaryOperator;
import static games.cubi.utils.VarHandler.BYTE_ARRAY_HANDLE;
public class ByteArrayBlockChunkData extends AbstractPalettedBlockChunkData {
private final byte[] blockData = new byte[ChunkData.BLOCK_COUNT];
public ByteArrayBlockChunkData(char blockID, BlockInfoResolver blockInfoResolver) {
super(blockID, 256, blockInfoResolver);
}
ByteArrayBlockChunkData(char[] palette, int paletteSize, IntUnaryOperator indexAtPacked, BlockInfoResolver blockInfoResolver) {
super(palette, paletteSize, 256, new long[ChunkData.WORD_COUNT]);
for (int packed = 0; packed < ChunkData.BLOCK_COUNT; packed++) {
int paletteIndex = indexAtPacked.applyAsInt(packed);
setPaletteIndex(packed, paletteIndex);
setOccludingPacked(packed, blockInfoResolver.isOccluding(palette[paletteIndex]));
}
}
private ByteArrayBlockChunkData(SixteenBlockChunkData old) {
super(old, 256);
for (int packed = 0; packed < ChunkData.BLOCK_COUNT; packed++) {
setPaletteIndex(packed, old.getPaletteIndex(packed));
}
}
static ByteArrayBlockChunkData upgradeFromSixteenBlock(SixteenBlockChunkData old) {
return new ByteArrayBlockChunkData(old);
}
@Override
protected int getPaletteIndex(int packed) {
// Each block gets one byte, so the packed block index directly selects the byte containing its palette index.
// Byte.toUnsignedInt converts Java's signed byte back to the intended 0-255 palette index.
return Byte.toUnsignedInt((byte) BYTE_ARRAY_HANDLE.getOpaque(blockData, packed));
}
@Override
protected void setPaletteIndex(int packed, int paletteIndex) {
// Each block gets one byte, so the packed block index directly selects where to store the 0-255 palette index.
BYTE_ARRAY_HANDLE.setOpaque(blockData, packed, (byte) paletteIndex);
}
@Override
protected BlockChunkData upgrade() {
return CharArrayBlockChunkData.upgradeFromByteArrayBlock(this);
}
}
@@ -0,0 +1,90 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.chunks.blocks;
import games.cubi.raycastedantiesp.core.chunks.BlockChunkData;
import games.cubi.raycastedantiesp.core.chunks.BlockInfoResolver;
import games.cubi.raycastedantiesp.core.chunks.ChunkData;
import java.util.Arrays;
import static games.cubi.utils.VarHandler.CHAR_ARRAY_HANDLE;
import static games.cubi.utils.VarHandler.LONG_ARRAY_HANDLE;
public class CharArrayBlockChunkData implements BlockChunkData {
private final char[] blockData;
private final long[] occlusionData;
public CharArrayBlockChunkData(char blockID, BlockInfoResolver blockInfoResolver) {
this.blockData = new char[ChunkData.BLOCK_COUNT];
Arrays.fill(this.blockData, blockID);
this.occlusionData = new long[ChunkData.WORD_COUNT];
if (blockInfoResolver.isOccluding(blockID)) {
Arrays.fill(this.occlusionData, -1L);
}
}
CharArrayBlockChunkData(char[] blockData, long[] occlusionData) {
this(blockData, occlusionData, false);
}
CharArrayBlockChunkData(char[] blockData, long[] occlusionData, boolean takeOwnership) {
if (blockData.length != ChunkData.BLOCK_COUNT) {
throw new IllegalArgumentException("blockData must contain " + ChunkData.BLOCK_COUNT + " entries");
}
if (occlusionData.length != ChunkData.WORD_COUNT) {
throw new IllegalArgumentException("occlusionData must contain " + ChunkData.WORD_COUNT + " longs");
}
this.blockData = takeOwnership ? blockData : Arrays.copyOf(blockData, blockData.length);
this.occlusionData = takeOwnership ? occlusionData : Arrays.copyOf(occlusionData, occlusionData.length);
}
static CharArrayBlockChunkData upgradeFromByteArrayBlock(ByteArrayBlockChunkData old) {
char[] blockData = new char[ChunkData.BLOCK_COUNT];
for (int packed = 0; packed < ChunkData.BLOCK_COUNT; packed++) {
blockData[packed] = old.getBlockIDPacked(packed);
}
return new CharArrayBlockChunkData(blockData, old.occlusionData);
}
@Override
public char getBlockID(int x, int y, int z) {
return (char) CHAR_ARRAY_HANDLE.getOpaque(blockData, ChunkData.packLocalChecked(x, y, z));
}
@Override
public BlockChunkData setBlockID(int x, int y, int z, char blockID, BlockInfoResolver blockInfoResolver) {
int packed = ChunkData.packLocalChecked(x, y, z);
CHAR_ARRAY_HANDLE.setOpaque(blockData, packed, blockID);
setOccludingPacked(packed, blockInfoResolver.isOccluding(blockID));
return this;
}
@Override
public boolean isOccludingLocal(int x, int y, int z) {
int packed = ChunkData.packLocalChecked(x, y, z);
// >>> 6 divides the packed block index by 64 to select the containing long.
int wordIndex = packed >>> 6;
// 1L << packed creates a mask with only the packed block's bit set.
long mask = 1L << packed;
long word = (long) LONG_ARRAY_HANDLE.getOpaque(occlusionData, wordIndex);
// & keeps only the target bit; non-zero means that bit is set.
return (word & mask) != 0;
}
private void setOccludingPacked(int packed, boolean occluding) {
// >>> 6 divides the packed block index by 64 to select the containing long.
int wordIndex = packed >>> 6;
// 1L << packed creates a mask for only the packed block's bit.
long mask = 1L << packed;
long word = (long) LONG_ARRAY_HANDLE.getOpaque(occlusionData, wordIndex);
// If occluding is true, OR the mask in to set the bit; otherwise AND with ~mask to clear it.
long updated = occluding ? word | mask : word & ~mask;
LONG_ARRAY_HANDLE.setOpaque(occlusionData, wordIndex, updated);
}
}
@@ -0,0 +1,85 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.chunks.blocks;
import games.cubi.raycastedantiesp.core.chunks.BlockChunkData;
import games.cubi.raycastedantiesp.core.chunks.BlockInfoResolver;
import games.cubi.raycastedantiesp.core.chunks.ChunkData;
import java.util.function.IntUnaryOperator;
import static games.cubi.utils.VarHandler.BYTE_ARRAY_HANDLE;
public class FourBlockChunkData extends AbstractPalettedBlockChunkData {
private static final int ENTRIES_PER_BYTE = 4;
private static final int BITS_PER_ENTRY = 2;
private static final int PALETTE_MASK = 0b11;
private final byte[] blockData = new byte[ChunkData.BLOCK_COUNT / ENTRIES_PER_BYTE];
public FourBlockChunkData(char blockID, BlockInfoResolver blockInfoResolver) {
super(blockID, 4, blockInfoResolver);
}
FourBlockChunkData(char[] palette, int paletteSize, int[] indices, long[] occlusionData) {
super(palette, paletteSize, 4, occlusionData);
if (indices.length != ChunkData.BLOCK_COUNT) {
throw new IllegalArgumentException("indices must contain " + ChunkData.BLOCK_COUNT + " entries");
}
for (int packed = 0; packed < ChunkData.BLOCK_COUNT; packed++) {
setPaletteIndex(packed, indices[packed]);
}
}
FourBlockChunkData(char[] palette, int paletteSize, IntUnaryOperator indexAtPacked, BlockInfoResolver blockInfoResolver) {
super(palette, paletteSize, 4, new long[ChunkData.WORD_COUNT]);
for (int packed = 0; packed < ChunkData.BLOCK_COUNT; packed++) {
int paletteIndex = indexAtPacked.applyAsInt(packed);
setPaletteIndex(packed, paletteIndex);
setOccludingPacked(packed, blockInfoResolver.isOccluding(palette[paletteIndex]));
}
}
static FourBlockChunkData upgradeFromTwoBlock(TwoBlockChunkData old) {
int[] indices = new int[ChunkData.BLOCK_COUNT];
for (int packed = 0; packed < ChunkData.BLOCK_COUNT; packed++) {
indices[packed] = old.bitIsSet(packed) ? 1 : 0;
}
return new FourBlockChunkData(new char[]{old.falseBitBlock(), old.trueBitBlock()}, 2, indices, old.copyOcclusionData());
}
@Override
protected int getPaletteIndex(int packed) {
// >>> 2 divides the packed block index by 4 to select the byte containing this block's 2-bit palette index.
int byteIndex = packed >>> 2;
// packed & 0b11 gets the block's position inside that byte, then * 2 converts it to a bit offset.
int shift = (packed & 0b11) * BITS_PER_ENTRY;
int packedByte = Byte.toUnsignedInt((byte) BYTE_ARRAY_HANDLE.getOpaque(blockData, byteIndex));
// >>> moves the target 2-bit index to the bottom, and & keeps only those 2 bits.
return (packedByte >>> shift) & PALETTE_MASK;
}
@Override
protected void setPaletteIndex(int packed, int paletteIndex) {
// >>> 2 divides the packed block index by 4 to select the byte containing this block's 2-bit palette index.
int byteIndex = packed >>> 2;
// packed & 0b11 gets the block's position inside that byte, then * 2 converts it to a bit offset.
int shift = (packed & 0b11) * BITS_PER_ENTRY;
// PALETTE_MASK << shift creates 1s over the old 2-bit index; ~ flips that to 0s over only the target index.
int clearMask = ~(PALETTE_MASK << shift);
int packedByte = Byte.toUnsignedInt((byte) BYTE_ARRAY_HANDLE.getOpaque(blockData, byteIndex));
// & clearMask clears the old index, then | writes the new 2-bit palette index into the cleared slot.
int updated = (packedByte & clearMask) | ((paletteIndex & PALETTE_MASK) << shift);
BYTE_ARRAY_HANDLE.setOpaque(blockData, byteIndex, (byte) updated);
}
@Override
protected BlockChunkData upgrade() {
return SixteenBlockChunkData.upgradeFromFourBlock(this);
}
}
@@ -0,0 +1,46 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.chunks.blocks;
import games.cubi.raycastedantiesp.core.chunks.BlockChunkData;
import games.cubi.raycastedantiesp.core.chunks.BlockInfoResolver;
import games.cubi.raycastedantiesp.core.chunks.ChunkData;
// If it is air, just use a null reference
public class SingleBlockChunkData implements BlockChunkData {
final char blockID;
private final boolean occluding;
public SingleBlockChunkData(char blockID, boolean occluding) {
this.blockID = blockID;
this.occluding = occluding;
}
@Override
public char getBlockID(int x, int y, int z) {
ChunkData.packLocalChecked(x, y, z);
return blockID;
}
@Override
public BlockChunkData setBlockID(int x, int y, int z, char newBlockID, BlockInfoResolver blockInfoResolver) {
ChunkData.packLocalChecked(x, y, z);
if (newBlockID == this.blockID) {
return this; // Chunk data did not change, no need to resize
}
return TwoBlockChunkData.upgradeFromSingleBlock(this, newBlockID, x, y, z, blockInfoResolver);
}
@Override
public boolean isOccludingLocal(int x, int y, int z) {
ChunkData.packLocalChecked(x, y, z);
return occluding;
}
}
@@ -0,0 +1,78 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.chunks.blocks;
import games.cubi.raycastedantiesp.core.chunks.BlockChunkData;
import games.cubi.raycastedantiesp.core.chunks.BlockInfoResolver;
import games.cubi.raycastedantiesp.core.chunks.ChunkData;
import java.util.function.IntUnaryOperator;
import static games.cubi.utils.VarHandler.BYTE_ARRAY_HANDLE;
public class SixteenBlockChunkData extends AbstractPalettedBlockChunkData {
private static final int ENTRIES_PER_BYTE = 2;
private static final int BITS_PER_ENTRY = 4;
private static final int PALETTE_MASK = 0b1111;
private final byte[] blockData = new byte[ChunkData.BLOCK_COUNT / ENTRIES_PER_BYTE];
public SixteenBlockChunkData(char blockID, BlockInfoResolver blockInfoResolver) {
super(blockID, 16, blockInfoResolver);
}
SixteenBlockChunkData(char[] palette, int paletteSize, IntUnaryOperator indexAtPacked, BlockInfoResolver blockInfoResolver) {
super(palette, paletteSize, 16, new long[ChunkData.WORD_COUNT]);
for (int packed = 0; packed < ChunkData.BLOCK_COUNT; packed++) {
int paletteIndex = indexAtPacked.applyAsInt(packed);
setPaletteIndex(packed, paletteIndex);
setOccludingPacked(packed, blockInfoResolver.isOccluding(palette[paletteIndex]));
}
}
private SixteenBlockChunkData(FourBlockChunkData old) {
super(old, 16);
for (int packed = 0; packed < ChunkData.BLOCK_COUNT; packed++) {
setPaletteIndex(packed, old.getPaletteIndex(packed));
}
}
static SixteenBlockChunkData upgradeFromFourBlock(FourBlockChunkData old) {
return new SixteenBlockChunkData(old);
}
@Override
protected int getPaletteIndex(int packed) {
// >>> 1 divides the packed block index by 2 to select the byte containing this block's 4-bit palette index.
int byteIndex = packed >>> 1;
// packed & 1 selects the low or high nibble, then * 4 converts it to a bit offset.
int shift = (packed & 1) * BITS_PER_ENTRY;
int packedByte = Byte.toUnsignedInt((byte) BYTE_ARRAY_HANDLE.getOpaque(blockData, byteIndex));
// >>> moves the target nibble to the bottom, and & keeps only those 4 bits.
return (packedByte >>> shift) & PALETTE_MASK;
}
@Override
protected void setPaletteIndex(int packed, int paletteIndex) {
// >>> 1 divides the packed block index by 2 to select the byte containing this block's 4-bit palette index.
int byteIndex = packed >>> 1;
// packed & 1 selects the low or high nibble, then * 4 converts it to a bit offset.
int shift = (packed & 1) * BITS_PER_ENTRY;
// PALETTE_MASK << shift creates 1s over the old nibble; ~ flips that to 0s over only the target nibble.
int clearMask = ~(PALETTE_MASK << shift);
int packedByte = Byte.toUnsignedInt((byte) BYTE_ARRAY_HANDLE.getOpaque(blockData, byteIndex));
// & clearMask clears the old nibble, then | writes the new 4-bit palette index into the cleared slot.
int updated = (packedByte & clearMask) | ((paletteIndex & PALETTE_MASK) << shift);
BYTE_ARRAY_HANDLE.setOpaque(blockData, byteIndex, (byte) updated);
}
@Override
protected BlockChunkData upgrade() {
return ByteArrayBlockChunkData.upgradeFromSixteenBlock(this);
}
}
@@ -0,0 +1,123 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.chunks.blocks;
import games.cubi.raycastedantiesp.core.chunks.BlockChunkData;
import games.cubi.raycastedantiesp.core.chunks.BlockInfoResolver;
import games.cubi.raycastedantiesp.core.chunks.ChunkData;
import java.util.Arrays;
import static games.cubi.raycastedantiesp.core.chunks.ChunkData.packLocalChecked;
import static games.cubi.raycastedantiesp.core.chunks.ChunkData.packUncheckedGuarded;
import static games.cubi.utils.VarHandler.LONG_ARRAY_HANDLE;
//functionally a bitset
public class TwoBlockChunkData implements BlockChunkData {
// Plain reads/writes would probably be fine as occluding state being stale for a few seconds causes no issues, and tearing is a non-issue as this is a bitset, so only a single bit value matters at a time.
// However, plain reads can technically be cached indefinitely, so opaque reads are more correct.
private final char trueBitBlock;
private final char falseBitBlock;
private final boolean trueBitBlockIsOccluding;
private final boolean falseBitBlockIsOccluding;
private final long[] blockData;
TwoBlockChunkData(char trueBitBlock, char falseBitBlock, boolean trueBitBlockIsOccluding, boolean falseBitBlockIsOccluding, long[] blockData) {
this.trueBitBlock = trueBitBlock;
this.falseBitBlock = falseBitBlock;
this.trueBitBlockIsOccluding = trueBitBlockIsOccluding;
this.falseBitBlockIsOccluding = falseBitBlockIsOccluding;
if (blockData.length != ChunkData.WORD_COUNT) {
throw new IllegalArgumentException("blockData must have length " + ChunkData.WORD_COUNT + ", but has length " + blockData.length);
}
this.blockData = Arrays.copyOf(blockData, blockData.length);
}
static TwoBlockChunkData upgradeFromSingleBlock(SingleBlockChunkData old, char newBlockID, int newX, int newY, int newZ, BlockInfoResolver blockInfoResolver) {
long[] blockData = new long[ChunkData.WORD_COUNT];
TwoBlockChunkData upgraded = new TwoBlockChunkData(newBlockID, old.blockID, blockInfoResolver.isOccluding(newBlockID), blockInfoResolver.isOccluding(old.blockID), blockData);
upgraded.setBit(packLocalChecked(newX, newY, newZ), true);
return upgraded;
}
public static TwoBlockChunkData upgradeFromAir(char newBlockID, int newXGlobal, int newYGlobal, int newZGlobal, BlockInfoResolver blockInfoResolver) {
long[] blockData = new long[ChunkData.WORD_COUNT];
TwoBlockChunkData upgraded = new TwoBlockChunkData(newBlockID, (char) 0, blockInfoResolver.isOccluding(newBlockID), blockInfoResolver.isOccluding(0), blockData);
upgraded.setBit(packUncheckedGuarded(newXGlobal, newYGlobal, newZGlobal), true);
return upgraded;
}
@Override
public char getBlockID(int x, int y, int z) {
return bitIsSet(packLocalChecked(x, y, z)) ? trueBitBlock : falseBitBlock;
}
@Override
public boolean isOccludingLocal(int x, int y, int z) {
return bitIsSet(packLocalChecked(x, y, z)) ? trueBitBlockIsOccluding : falseBitBlockIsOccluding;
}
@Override
public BlockChunkData setBlockID(int x, int y, int z, char blockID, BlockInfoResolver blockInfoResolver) {
int packed = packLocalChecked(x, y, z);
if (blockID == trueBitBlock) {
setBit(packed, true);
return this;
}
if (blockID == falseBitBlock) {
setBit(packed, false);
return this;
}
return FourBlockChunkData.upgradeFromTwoBlock(this).setBlockID(x, y, z, blockID, blockInfoResolver);
}
char trueBitBlock() {
return trueBitBlock;
}
char falseBitBlock() {
return falseBitBlock;
}
long[] copyOcclusionData() {
long[] copied = new long[ChunkData.WORD_COUNT];
if (trueBitBlockIsOccluding == falseBitBlockIsOccluding) {
if (trueBitBlockIsOccluding) {
Arrays.fill(copied, -1L);
}
return copied;
}
for (int wordIndex = 0; wordIndex < blockData.length; wordIndex++) {
long word = (long) LONG_ARRAY_HANDLE.getOpaque(blockData, wordIndex);
copied[wordIndex] = trueBitBlockIsOccluding ? word : ~word;
}
return copied;
}
boolean bitIsSet(int packed) {
// >>> 6 divides the packed block index by 64 to select the containing long.
int wordIndex = packed >>> 6;
// 1L << packed creates a mask with only the packed block's bit set.
long mask = 1L << packed;
long word = (long) LONG_ARRAY_HANDLE.getOpaque(blockData, wordIndex);
// & keeps only the target bit; non-zero means that bit is set.
return (word & mask) != 0;
}
private void setBit(int packed, boolean value) {
// >>> 6 divides the packed block index by 64 to select the containing long. Avoids signed division; probably an unnecessary optimisation but why not
int wordIndex = packed >>> 6;
// 1L << packed creates a mask for only the packed block's bit.
long mask = 1L << packed;
long word = (long) LONG_ARRAY_HANDLE.getOpaque(blockData, wordIndex);
long updated = value ? word | mask : word & ~mask;
LONG_ARRAY_HANDLE.setOpaque(blockData, wordIndex, updated);
}
}
@@ -0,0 +1,22 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.config;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Comment;
@ConfigSerializable
public record BlockProcessorConfig(
@Comment("Block processor implementation used by the plugin.")
BlockProcessorMode mode,
@Comment("Track every block rather than only tile entities.")
boolean trackAllBlocks
) implements Config {
public static final BlockProcessorConfig DEFAULT = new BlockProcessorConfig(BlockProcessorMode.PACKETEVENTS, false);
}
@@ -0,0 +1,39 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.config;
import org.jetbrains.annotations.Nullable;
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,40 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.config;
import games.cubi.raycastedantiesp.core.config.raycast.ChunkSectionConfig;
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.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Setting;
@ConfigSerializable
public record ChecksConfig(
@Setting("player") PlayerConfig playerConfig,
@Setting("entity") EntityConfig entityConfig,
@Setting("tile-entity") TileEntityConfig tileEntityConfig,
@Setting("sound-effects") SoundEffectsConfig soundEffectsConfig,
@Setting("chunk-section") ChunkSectionConfig chunkSectionConfig
) implements Config {
public static final ChecksConfig DEFAULT = new ChecksConfig(
PlayerConfig.DEFAULT,
EntityConfig.DEFAULT,
TileEntityConfig.DEFAULT,
SoundEffectsConfig.DEFAULT,
ChunkSectionConfig.DEFAULT
);
public boolean hasEnabledStatusChanges(ChecksConfig startup) {
return playerConfig.enabled() != startup.playerConfig.enabled()
|| entityConfig.enabled() != startup.entityConfig.enabled()
|| chunkSectionConfig.enabled() != startup.chunkSectionConfig.enabled();
}
}
@@ -0,0 +1,12 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.config;
public interface Config {
}
@@ -0,0 +1,327 @@
package games.cubi.raycastedantiesp.core.config;
import org.spongepowered.configurate.CommentedConfigurationNode;
import org.spongepowered.configurate.ConfigurationNode;
import org.spongepowered.configurate.NodePath;
import org.spongepowered.configurate.serialize.SerializationException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* A mutable configuration under preparation, separate from the active runtime snapshot.
* Used only during a load or edit; ConfigManager owns synchronization, persistence, and publication.
*/
final class ConfigCandidate {
private final CommentedConfigurationNode node;
private final CommentedConfigurationNode defaults;
private final List<Repair> repairs = new ArrayList<>();
private boolean dirty;
ConfigCandidate(CommentedConfigurationNode node, CommentedConfigurationNode defaults) {
this.node = node;
this.defaults = defaults;
dirty |= ConfigMigration.migrate(node);
dirty |= ConfigMapping.removeDuplicateHeader(node);
mergeDefaults();
}
CommentedConfigurationNode node() {
return node;
}
List<Repair> repairs() {
return repairs;
}
boolean isDirty() {
return dirty;
}
void markDirty() {
dirty = true;
}
boolean hasDefault(NodePath path) {
return !defaults.node(path.array()).virtual();
}
void mergeDefaults() {
dirty |= mergeMissing(defaults, node);
}
LoggingConfig parseLoggingConfig() {
return deserializeWithRepairs(NodePath.path("logging"), LoggingConfig.class);
}
RootConfig parseReadyConfig() {
// Hiding sounds from hidden entities is currently unsupported; persist the false defaults.
for (String section : List.of("player", "entity")) {
repair(NodePath.path("checks", section, "hide-sounds-when-hidden"), "hiding sounds from hidden entities is currently unsupported");
}
int attemptsRemaining = Math.max(2, countLeaves(defaults) + 1);
while (attemptsRemaining-- > 0) {
RootConfig root = deserializeWithRepairs(NodePath.path(), RootConfig.class);
if (!RootConfig.CURRENT_VERSION.equals(root.configVersion())) {
throw ConfigMigration.unsupportedVersion(root.configVersion());
}
List<AbsoluteViolation> violations = validate(root);
if (violations.isEmpty()) {
canonicalizeEnums(root);
return root;
}
boolean repaired = false;
for (AbsoluteViolation violation : violations) {
repaired |= repair(violation.path, violation.message);
}
if (!repaired) {
throw new ConfigLoadException("Configuration validation failed without a repairable default");
}
}
throw new ConfigLoadException("Configuration could not be repaired after exhausting the available defaults");
}
private void canonicalizeEnums(RootConfig root) {
canonicalizeValue(NodePath.path("engine", "mode"), root.engineConfig().mode().getName());
canonicalizeValue(NodePath.path("block-processor", "mode"), root.blockProcessorConfig().mode().getName());
}
private void canonicalizeValue(NodePath path, String value) {
ConfigurationNode target = node.node(path.array());
if (!Objects.equals(target.raw(), value)) {
target.raw(value);
dirty = true;
}
}
private <T> T deserializeWithRepairs(NodePath mappingPath, Class<T> type) {
int attemptsRemaining = Math.max(1, countLeaves(defaults.node(mappingPath.array())) + 1);
while (attemptsRemaining-- > 0) {
try {
T value = node.node(mappingPath.array()).get(type);
if (value == null) {
throw new ConfigLoadException("Configuration mapper returned null for " + pathToString(mappingPath));
}
return value;
} catch (SerializationException exception) {
boolean repaired = false;
for (SerializationException failure : leafFailures(exception)) {
NodePath failurePath = normalizePath(failure.path(), mappingPath);
repaired |= repair(failurePath, failure.rawMessage());
}
if (!repaired) {
throw new ConfigLoadException("Invalid configuration at " + pathToString(mappingPath), exception);
}
}
}
throw new ConfigLoadException("Configuration at " + pathToString(mappingPath) + " could not be repaired");
}
private List<AbsoluteViolation> validate(RootConfig root) {
List<AbsoluteViolation> violations = new ArrayList<>();
if (!root.blockProcessorConfig().trackAllBlocks() && root.checksConfig().chunkSectionConfig().enabled()) {
violations.add(new AbsoluteViolation(
NodePath.path("checks", "chunk-section", "enabled"),
"must be false when block-processor.track-all-blocks is false"
));
}
return violations;
}
boolean repair(NodePath failedPath, String reason) {
NodePath repairPath = findRepairPath(failedPath);
if (repairPath == null) {
return false;
}
ConfigurationNode target = node.node(repairPath.array());
ConfigurationNode replacement = defaults.node(repairPath.array());
if (Objects.equals(target.raw(), replacement.raw())) {
return false;
}
String existingComment = target instanceof CommentedConfigurationNode commented ? commented.comment() : null;
target.from(replacement);
copyComments(replacement, target);
if (existingComment != null && target instanceof CommentedConfigurationNode commented) {
commented.comment(existingComment);
}
dirty = true;
repairs.add(new Repair(repairPath, reason, replacement.raw()));
return true;
}
private NodePath findRepairPath(NodePath failedPath) {
Object[] parts = failedPath.array();
for (int index = 0; index < parts.length; index++) {
if (parts[index] instanceof Number) {
parts = Arrays.copyOf(parts, index);
break;
}
}
for (int length = parts.length; length >= 0; length--) {
NodePath candidate = NodePath.path(Arrays.copyOf(parts, length));
if (!defaults.node(candidate.array()).virtual()) {
return candidate;
}
}
return null;
}
private List<SerializationException> leafFailures(SerializationException root) {
List<SerializationException> failures = new ArrayList<>();
ArrayDeque<SerializationException> pending = new ArrayDeque<>();
pending.add(root);
while (!pending.isEmpty()) {
SerializationException current = pending.removeFirst();
boolean hasNested = false;
for (Throwable suppressed : current.getSuppressed()) {
if (suppressed instanceof SerializationException nested) {
pending.addLast(nested);
hasNested = true;
}
}
if (!hasNested) {
failures.add(current);
}
}
return failures;
}
private NodePath normalizePath(NodePath failurePath, NodePath mappingPath) {
if (failurePath == null || failurePath.size() == 0) {
return mappingPath;
}
if (startsWith(failurePath, mappingPath)) {
return failurePath;
}
return mappingPath.plus(failurePath);
}
private boolean startsWith(NodePath path, NodePath prefix) {
if (prefix.size() > path.size()) {
return false;
}
for (int index = 0; index < prefix.size(); index++) {
if (!Objects.equals(path.get(index), prefix.get(index))) {
return false;
}
}
return true;
}
private boolean mergeMissing(ConfigurationNode defaults, ConfigurationNode target) {
if (target.virtual() || target.raw() == null && target.childrenMap().isEmpty() && target.childrenList().isEmpty()) {
target.from(defaults);
copyComments(defaults, target);
return true;
}
boolean changed = mergeComment(defaults, target);
if (!defaults.childrenMap().isEmpty()) {
Object raw = target.raw();
if (target.childrenMap().isEmpty() && !(raw instanceof Map<?, ?>)) {
return repair(target.path(), "expected a mapping");
}
for (Map.Entry<Object, ? extends ConfigurationNode> entry : defaults.childrenMap().entrySet()) {
changed |= mergeMissing(entry.getValue(), target.node(entry.getKey()));
}
} else if (!defaults.childrenList().isEmpty() && target.isList()) {
// Entries can be reordered or removed, so default comments must follow values rather than indices.
Map<String, ConfigurationNode> commentedDefaults = new LinkedHashMap<>();
for (ConfigurationNode child : defaults.childrenList()) {
if (child.rawScalar() instanceof String value && child instanceof CommentedConfigurationNode commented && commented.comment() != null) {
commentedDefaults.put(value, child);
}
}
for (ConfigurationNode child : target.childrenList()) {
if (child.rawScalar() instanceof String value) {
ConfigurationNode defaultChild = commentedDefaults.get(value);
if (defaultChild != null) {
changed |= mergeComment(defaultChild, child);
}
}
}
}
return changed;
}
private boolean mergeComment(ConfigurationNode defaults, ConfigurationNode target) {
if (!(defaults instanceof CommentedConfigurationNode defaultCommented) || !(target instanceof CommentedConfigurationNode targetCommented)) {
return false;
}
if (targetCommented.comment() == null && defaultCommented.comment() != null) {
targetCommented.comment(defaultCommented.comment());
return true;
}
return false;
}
private void copyComments(ConfigurationNode source, ConfigurationNode target) {
if (source instanceof CommentedConfigurationNode sourceCommented
&& target instanceof CommentedConfigurationNode targetCommented
&& sourceCommented.comment() != null) {
targetCommented.commentIfAbsent(sourceCommented.comment());
}
for (Map.Entry<Object, ? extends ConfigurationNode> entry : source.childrenMap().entrySet()) {
copyComments(entry.getValue(), target.node(entry.getKey()));
}
List<? extends ConfigurationNode> sourceChildren = source.childrenList();
List<? extends ConfigurationNode> targetChildren = target.childrenList();
for (int index = 0; index < Math.min(sourceChildren.size(), targetChildren.size()); index++) {
copyComments(sourceChildren.get(index), targetChildren.get(index));
}
}
private int countLeaves(ConfigurationNode node) {
if (node.childrenMap().isEmpty() && node.childrenList().isEmpty()) {
return 1;
}
int count = 0;
for (ConfigurationNode child : node.childrenMap().values()) {
count += countLeaves(child);
}
for (ConfigurationNode child : node.childrenList()) {
count += countLeaves(child);
}
return Math.max(1, count);
}
private static String pathToString(NodePath path) {
if (path.size() == 0) {
return "<root>";
}
StringBuilder result = new StringBuilder();
for (Object part : path) {
if (part instanceof Number) {
result.append('[').append(part).append(']');
} else {
if (!result.isEmpty()) {
result.append('.');
}
result.append(part);
}
}
return result.toString();
}
record Repair(NodePath path, String reason, Object defaultValue) {
Repair {
path = path.copy();
}
String pathString() {
return pathToString(path);
}
}
private record AbsoluteViolation(NodePath path, String message) {
}
}
@@ -0,0 +1,41 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.config;
import java.util.Arrays;
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,78 @@
package games.cubi.raycastedantiesp.core.config;
import org.spongepowered.configurate.CommentedConfigurationNode;
import org.spongepowered.configurate.loader.HeaderMode;
import org.spongepowered.configurate.serialize.SerializationException;
import org.spongepowered.configurate.yaml.NodeStyle;
import org.spongepowered.configurate.yaml.YamlConfigurationLoader;
import java.io.IOException;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Objects;
/** Owns YAML loading, default-node creation, and replacement of config.yml through a temporary file. */
final class ConfigFile {
private final Path dataFolder;
private final Path configPath;
private final YamlConfigurationLoader loader;
ConfigFile(Path dataFolder) {
this.dataFolder = Objects.requireNonNull(dataFolder, "dataFolder");
configPath = dataFolder.resolve("config.yml");
loader = createLoader(configPath);
}
private YamlConfigurationLoader createLoader(Path path) {
return YamlConfigurationLoader.builder()
.path(path)
.nodeStyle(NodeStyle.BLOCK)
.headerMode(HeaderMode.PRESERVE)
.defaultOptions(ConfigMapping.options())
.build();
}
CommentedConfigurationNode createDefaultNode() {
CommentedConfigurationNode defaults = loader.createNode();
try {
defaults.set(RootConfig.class, RootConfig.DEFAULT);
} catch (SerializationException e) {
throw new ConfigLoadException("Code-defined configuration defaults could not be serialized", e);
}
return defaults;
}
CommentedConfigurationNode load() {
try {
Files.createDirectories(dataFolder);
return Files.exists(configPath) ? loader.load() : loader.createNode();
} catch (IOException e) {
throw new ConfigLoadException("Failed to load config.yml", e);
}
}
void save(CommentedConfigurationNode node) {
Path temporaryPath = null;
try {
temporaryPath = Files.createTempFile(dataFolder, "config-", ".yml.tmp");
createLoader(temporaryPath).save(node);
try {
Files.move(temporaryPath, configPath, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
} catch (AtomicMoveNotSupportedException exception) {
Files.move(temporaryPath, configPath, StandardCopyOption.REPLACE_EXISTING);
}
temporaryPath = null;
} catch (IOException e) {
throw new ConfigLoadException("Failed to save config.yml", e);
} finally {
if (temporaryPath != null) {
try {
Files.deleteIfExists(temporaryPath);
} catch (IOException ignored) {
}
}
}
}
}
@@ -0,0 +1,19 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.config;
public class ConfigLoadException extends RuntimeException {
public ConfigLoadException(String message) {
super(message);
}
public ConfigLoadException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,391 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.config;
import games.cubi.logs.Logger;
import games.cubi.raycastedantiesp.core.config.engine.EngineConfig;
import games.cubi.raycastedantiesp.core.config.raycast.ChunkSectionConfig;
import games.cubi.raycastedantiesp.core.config.raycast.EntityConfig;
import games.cubi.raycastedantiesp.core.config.raycast.PlayerConfig;
import games.cubi.raycastedantiesp.core.config.raycast.SoundEffectsConfig;
import games.cubi.raycastedantiesp.core.config.raycast.TileEntityConfig;
import games.cubi.utils.VarHandler;
import org.spongepowered.configurate.CommentedConfigurationNode;
import org.spongepowered.configurate.ConfigurationNode;
import org.spongepowered.configurate.ConfigurateException;
import org.spongepowered.configurate.NodePath;
import org.spongepowered.configurate.serialize.SerializationException;
import org.spongepowered.configurate.yaml.YamlConfigurationLoader;
import java.lang.invoke.VarHandle;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Coordinates startup, runtime edits, and publication of configuration snapshots.
* ConfigCandidate prepares values and repairs; ConfigFile handles persistence.
*/
public class ConfigManager {
private static volatile ConfigManager instance;
private static final VarHandle INSTANCE = VarHandler.$tatic(ConfigManager.class, "instance", ConfigManager.class);
private final ConfigFile configFile;
private volatile ActiveState activeState = new ActiveState(LoggingConfig.DEFAULT, null);
private static final VarHandle ACTIVE_STATE = VarHandler.get(ConfigManager.class, "activeState", ActiveState.class);
private RootConfig startupConfig;
private CommentedConfigurationNode configNode;
ConfigManager(Path dataFolder) {
configFile = new ConfigFile(dataFolder);
}
public static synchronized ConfigManager initialiseConfigManager(Path dataFolder) {
ConfigManager current = (ConfigManager) INSTANCE.getAcquire();
if (current == null) {
ConfigManager manager = new ConfigManager(dataFolder);
INSTANCE.setRelease(manager);
try {
manager.loadLoggingConfig();
} catch (RuntimeException exception) {
INSTANCE.setRelease(null);
throw exception;
}
current = manager;
}
return current;
}
public static ConfigManager get() {
ConfigManager current = (ConfigManager) INSTANCE.getAcquire();
if (current == null) {
Logger.errorAndReturn(new RuntimeException("ConfigManager accessed before being initiated. Please report this."), 2, ConfigManager.class);
}
return current;
}
public static LoggingConfig getLoggingConfigOrDefault() {
ConfigManager current = (ConfigManager) INSTANCE.getAcquire();
return current == null ? LoggingConfig.DEFAULT : current.getLoggingConfig();
}
public synchronized void completeInitialLoad() {
if (startupConfig != null) {
throw new IllegalStateException("Configuration loading has already been completed");
}
ConfigCandidate candidate = prepare();
RootConfig ready = candidate.parseReadyConfig();
saveIfChanged(candidate);
startupConfig = ready;
configNode = candidate.node();
ACTIVE_STATE.setRelease(this, new ActiveState(ready.loggingConfig(), ready));
logRepairs(candidate.repairs());
}
/**
* Reloads the complete configuration. The active snapshot is replaced only after parsing and validation succeed.
*/
public synchronized void load() {
requireReady();
ConfigCandidate candidate = prepare();
RootConfig ready = candidate.parseReadyConfig();
saveIfChanged(candidate);
configNode = candidate.node();
logRepairs(candidate.repairs());
validateReload(ready);
ACTIVE_STATE.setRelease(this, new ActiveState(ready.loggingConfig(), ready));
}
public synchronized SetConfigResult setConfigValue(String path, String rawValue) {
requireReady();
ConfigCandidate candidate = prepare();
ConfigurationNode target = node(candidate.node(), path);
if (target.virtual()) {
return SetConfigResult.invalid("Unknown config path: " + path);
}
try {
Object parsedValue = parseRawValue(rawValue);
target.set(parsedValue);
candidate.markDirty();
NodePath targetPath = NodePath.path((Object[]) path.split("\\."));
if (parsedValue == null && candidate.hasDefault(targetPath)) {
candidate.repair(targetPath, "value cannot be null");
}
} catch (ConfigurateException e) {
return SetConfigResult.invalid("Invalid YAML value: " + rawValue);
}
return applyCandidate(candidate, false);
}
public synchronized SetConfigResult addConfigListValue(String path, String rawValue) {
requireReady();
return mutateConfigListValue(path, rawValue, ListMutation.ADD);
}
public synchronized SetConfigResult removeConfigListValue(String path, String rawValue) {
requireReady();
return mutateConfigListValue(path, rawValue, ListMutation.REMOVE);
}
private SetConfigResult mutateConfigListValue(String path, String rawValue, ListMutation mutation) {
ConfigCandidate candidate = prepare();
ConfigurationNode target = node(candidate.node(), 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;
try {
parsedValue = parseRawValue(rawValue);
} catch (ConfigurateException e) {
return SetConfigResult.invalid("Invalid YAML value: " + 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);
}
try {
target.set(values);
candidate.markDirty();
} catch (SerializationException e) {
return SetConfigResult.invalid("Failed to update " + path);
}
return applyCandidate(candidate, true);
}
private SetConfigResult applyCandidate(ConfigCandidate candidate, boolean allowRestartRequired) {
candidate.mergeDefaults();
RootConfig ready;
try {
ready = candidate.parseReadyConfig();
validateReload(ready);
} catch (RestartRequiredException e) {
if (!allowRestartRequired) {
return SetConfigResult.invalid(e.getMessage());
}
saveIfChanged(candidate);
configNode = candidate.node();
logRepairs(candidate.repairs());
return SetConfigResult.restartRequired(e.getMessage(), candidate.repairs());
} catch (ConfigLoadException e) {
return SetConfigResult.invalid(e.getMessage());
}
saveIfChanged(candidate);
configNode = candidate.node();
ACTIVE_STATE.setRelease(this, new ActiveState(ready.loggingConfig(), ready));
logRepairs(candidate.repairs());
return SetConfigResult.ok(candidate.repairs());
}
public LoggingConfig getLoggingConfig() {
return ((ActiveState) ACTIVE_STATE.getAcquire(this)).loggingConfig;
}
public PlayerConfig getPlayerConfig() {
return requireReady().checksConfig().playerConfig();
}
public EntityConfig getEntityConfig() {
return requireReady().checksConfig().entityConfig();
}
public TileEntityConfig getTileEntityConfig() {
return requireReady().checksConfig().tileEntityConfig();
}
public SoundEffectsConfig getSoundEffectsConfig() {
return requireReady().checksConfig().soundEffectsConfig();
}
public ChunkSectionConfig getChunkSectionConfig() {
return requireReady().checksConfig().chunkSectionConfig();
}
public DebugConfig getDebugConfig() {
return requireReady().debugConfig();
}
public UpdateConfig getUpdateConfig() {
return requireReady().updateConfig();
}
public EngineConfig getEngineConfig() {
return requireReady().engineConfig();
}
public BlockProcessorConfig getBlockProcessorConfig() {
return requireReady().blockProcessorConfig();
}
public synchronized Map<String, Object> getConfigValues() {
requireReady();
Map<String, Object> values = new LinkedHashMap<>();
collectConfigValues(configNode, "", values);
return Collections.unmodifiableMap(values);
}
void loadLoggingConfig() {
ConfigCandidate candidate = prepare();
LoggingConfig logging = candidate.parseLoggingConfig();
saveIfChanged(candidate);
configNode = candidate.node();
ACTIVE_STATE.setRelease(this, new ActiveState(logging, null));
logRepairs(candidate.repairs());
}
private ConfigCandidate prepare() {
return new ConfigCandidate(configFile.load(), configFile.createDefaultNode());
}
private void saveIfChanged(ConfigCandidate candidate) {
if (candidate.isDirty()) {
configFile.save(candidate.node());
}
}
private Object parseRawValue(String rawValue) throws ConfigurateException {
ConfigurationNode parsed = YamlConfigurationLoader.builder()
.defaultOptions(ConfigMapping.options())
.buildAndLoadString("value: " + rawValue);
return parsed.node("value").raw();
}
private void validateReload(RootConfig next) {
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().entityConfig().excludedTypes().equals(startupConfig.checksConfig().entityConfig().excludedTypes())) {
throw new RestartRequiredException("excluded entity types cannot be changed without a restart.");
}
if (!next.checksConfig().tileEntityConfig().excludedBlocks().equals(startupConfig.checksConfig().tileEntityConfig().excludedBlocks())) {
throw new RestartRequiredException("excluded tile-entity blocks cannot be changed without a restart.");
}
if (next.checksConfig().hasEnabledStatusChanges(startupConfig.checksConfig())) {
throw new RestartRequiredException("player and entity checks cannot be enabled or disabled without a restart.");
}
}
private RootConfig requireReady() {
RootConfig ready = ((ActiveState) ACTIVE_STATE.getAcquire(this)).readyConfig;
if (ready == null) {
throw new IllegalStateException("Configuration is not available until completeInitialLoad has finished");
}
return ready;
}
private void logRepairs(List<ConfigCandidate.Repair> repairs) {
for (ConfigCandidate.Repair repair : repairs) {
String reason = repair.reason() == null || repair.reason().isBlank() ? "invalid value" : repair.reason();
String message = "Invalid config value at " + repair.pathString() + ": " + reason
+ ". Replaced it with the default " + displayValue(repair.defaultValue()) + ".";
Logger.warning(message, 4, ConfigManager.class);
}
}
private String displayValue(Object value) {
String displayed = String.valueOf(value);
return displayed.length() <= 160 ? displayed : displayed.substring(0, 157) + "...";
}
private void collectConfigValues(ConfigurationNode node, String path, Map<String, Object> values) {
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());
collectConfigValues(entry.getValue(), path.isEmpty() ? key : path + "." + key, values);
}
}
private ConfigurationNode node(ConfigurationNode root, String path) {
return root.node((Object[]) path.split("\\."));
}
private enum ListMutation {
ADD,
REMOVE
}
private record ActiveState(LoggingConfig loggingConfig, RootConfig readyConfig) {
}
private static final class RestartRequiredException extends ConfigLoadException {
private RestartRequiredException(String message) {
super(message);
}
}
public record SetConfigResult(boolean success, boolean restartRequired, boolean repaired, String message) {
private static SetConfigResult ok(List<ConfigCandidate.Repair> repairs) {
if (repairs.isEmpty()) {
return new SetConfigResult(true, false, false, "Config value updated.");
}
return new SetConfigResult(true, false, true, repairMessage(repairs));
}
private static SetConfigResult restartRequired(String message, List<ConfigCandidate.Repair> repairs) {
String result = repairs.isEmpty() ? message : message + " " + repairMessage(repairs);
return new SetConfigResult(true, true, !repairs.isEmpty(), result);
}
public static SetConfigResult invalid(String message) {
return new SetConfigResult(false, false, false, message);
}
private static String repairMessage(List<ConfigCandidate.Repair> repairs) {
Set<String> paths = new LinkedHashSet<>();
for (ConfigCandidate.Repair repair : repairs) {
paths.add(repair.pathString());
}
return "Invalid values at " + String.join(", ", paths) + " were replaced with defaults.";
}
}
}
@@ -0,0 +1,234 @@
package games.cubi.raycastedantiesp.core.config;
import games.cubi.raycastedantiesp.core.config.engine.EngineMode;
import games.cubi.raycastedantiesp.core.config.raycast.BlockSelector;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.configurate.CommentedConfigurationNode;
import org.spongepowered.configurate.ConfigurationOptions;
import org.spongepowered.configurate.ConfigurationNode;
import org.spongepowered.configurate.objectmapping.ObjectMapper;
import org.spongepowered.configurate.serialize.SerializationException;
import org.spongepowered.configurate.serialize.TypeSerializer;
import org.spongepowered.configurate.serialize.TypeSerializerCollection;
import org.spongepowered.configurate.util.NamingSchemes;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.function.LongFunction;
final class ConfigMapping {
private static final String HEADER = "An explanation of this configuration file and what all the options do can be found at https://raycastedantiesp.cubi.games/config/";
private static final String LEGACY_HEADER = "An explanation of this configuration file and what the options do can be found at https://raycastedantiesp.cubi.games/config/";
private static final ConfigurationOptions OPTIONS = createOptions();
private ConfigMapping() {
}
static ConfigurationOptions options() {
return OPTIONS;
}
static boolean removeDuplicateHeader(CommentedConfigurationNode node) {
// Without a blank line, the legacy YAML header is loaded as a comment on config-version.
CommentedConfigurationNode version = node.node("config-version");
String comment = version.comment();
if (comment == null) {
return false;
}
var lines = comment.lines().toList();
var remaining = lines.stream().filter(line -> {
String normalized = line.strip().replace("https\\://", "https://");
return !LEGACY_HEADER.equals(normalized) && !HEADER.equals(normalized);
}).toList();
if (remaining.size() == lines.size()) {
return false;
}
String retainedComment = String.join("\n", remaining);
version.comment(retainedComment.isBlank() ? null : retainedComment);
return true;
}
private static ConfigurationOptions createOptions() {
ObjectMapper.Factory mapper = ObjectMapper.factoryBuilder()
.defaultNamingScheme(NamingSchemes.LOWER_CASE_DASHED)
.addProcessor(ListEntryComments.class, (annotation, type) -> {
Map<String, String> comments = new HashMap<>();
for (ListEntryComments.Entry entry : annotation.value()) {
comments.put(entry.value(), entry.comment());
}
return (value, node) -> {
for (ConfigurationNode child : node.childrenList()) {
if (child.rawScalar() instanceof String entry && child instanceof CommentedConfigurationNode commented) {
String comment = comments.get(entry);
if (comment != null) {
commented.commentIfAbsent(comment);
}
}
}
};
})
.addConstraint(ConfigRange.class, (annotation, type) -> value -> {
if (!(value instanceof Number number)) {
throw new SerializationException(type, "Expected a numeric value");
}
long numericValue = number.longValue();
if (numericValue < annotation.min() || numericValue > annotation.max()) {
throw new SerializationException(type, "Value must be between " + annotation.min() + " and " + annotation.max());
}
})
.build();
TypeSerializer<String> stringSerializer = strictScalarSerializer(
String.class,
"a string",
String.class::cast,
value -> value
);
TypeSerializer<Boolean> booleanSerializer = strictScalarSerializer(
Boolean.class,
"a boolean",
Boolean.class::cast,
value -> value
);
TypeSerializer<Byte> byteSerializer = strictIntegerSerializer("a byte", Byte.MIN_VALUE, Byte.MAX_VALUE, value -> (byte) value);
TypeSerializer<Short> shortSerializer = strictIntegerSerializer("a short", Short.MIN_VALUE, Short.MAX_VALUE, value -> (short) value);
TypeSerializer<Integer> integerSerializer = strictIntegerSerializer("an integer", Integer.MIN_VALUE, Integer.MAX_VALUE, value -> (int) value);
TypeSerializerCollection serializers = TypeSerializerCollection.defaults().childBuilder()
.registerExact(String.class, stringSerializer)
.registerExact(boolean.class, booleanSerializer)
.registerExact(Boolean.class, booleanSerializer)
.registerExact(byte.class, byteSerializer)
.registerExact(Byte.class, byteSerializer)
.registerExact(short.class, shortSerializer)
.registerExact(Short.class, shortSerializer)
.registerExact(int.class, integerSerializer)
.registerExact(Integer.class, integerSerializer)
.registerExact(BlockSelector.class, blockSelectorSerializer())
.registerExact(EngineMode.class, enumSerializer(EngineMode::fromString, EngineMode::getName))
.registerExact(BlockProcessorMode.class, enumSerializer(BlockProcessorMode::fromString, BlockProcessorMode::getName))
.registerAnnotatedObjects(mapper)
.build();
return ConfigurationOptions.defaults()
.header(HEADER)
.serializers(serializers)
.shouldCopyDefaults(true);
}
private static <T> TypeSerializer<T> strictScalarSerializer(
Class<T> type,
String expected,
Function<Object, T> reader,
Function<T, Object> writer
) {
return new TypeSerializer<>() {
@Override
public T deserialize(@NotNull Type expectedType, @NotNull ConfigurationNode node) throws SerializationException {
Object raw = node.rawScalar();
if (!type.isInstance(raw)) {
throw new SerializationException(expectedType, "Expected " + expected);
}
return reader.apply(raw);
}
@Override
public void serialize(@NotNull Type expectedType, T value, @NotNull ConfigurationNode node) {
node.raw(value == null ? null : writer.apply(value));
}
};
}
private static <T extends Number> TypeSerializer<T> strictIntegerSerializer(String expected, long minimum, long maximum, LongFunction<T> converter) {
return new TypeSerializer<>() {
@Override
public T deserialize(@NotNull Type expectedType, @NotNull ConfigurationNode node) throws SerializationException {
Object raw = node.rawScalar();
if (!(raw instanceof Number number)) {
throw new SerializationException(expectedType, "Expected " + expected);
}
long value = exactLong(expectedType, number);
if (value < minimum || value > maximum) {
throw new SerializationException(expectedType, "Value is outside the supported range for " + expected);
}
return converter.apply(value);
}
@Override
public void serialize(@NotNull Type expectedType, T value, @NotNull ConfigurationNode node) {
node.raw(value == null ? null : value.intValue());
}
};
}
private static long exactLong(Type expectedType, Number number) throws SerializationException {
try {
return switch (number) {
case Byte ignored -> number.longValue();
case Short ignored -> number.longValue();
case Integer ignored -> number.longValue();
case Long ignored -> number.longValue();
case BigInteger value -> value.longValueExact();
case BigDecimal value -> value.longValueExact();
default -> exactLongFromFloatingPoint(expectedType, number.doubleValue());
};
} catch (ArithmeticException exception) {
throw new SerializationException(expectedType, "Expected an integer", exception);
}
}
private static long exactLongFromFloatingPoint(Type expectedType, double value) throws SerializationException {
if (!Double.isFinite(value) || Math.rint(value) != value || value < Long.MIN_VALUE || value > Long.MAX_VALUE) {
throw new SerializationException(expectedType, "Expected an integer");
}
return (long) value;
}
private static <T> TypeSerializer<T> enumSerializer(Function<String, T> parser, Function<T, String> writer) {
return new TypeSerializer<>() {
@Override
public T deserialize(@NotNull Type expectedType, @NotNull ConfigurationNode node) throws SerializationException {
Object raw = node.rawScalar();
if (!(raw instanceof String string)) {
throw new SerializationException(expectedType, "Expected a string");
}
T parsed = parser.apply(string);
if (parsed == null) {
throw new SerializationException(expectedType, "Unsupported value '" + string + "'");
}
return parsed;
}
@Override
public void serialize(@NotNull Type expectedType, T value, @NotNull ConfigurationNode node) {
node.raw(value == null ? null : writer.apply(value));
}
};
}
private static TypeSerializer<BlockSelector> blockSelectorSerializer() {
return new TypeSerializer<>() {
@Override
public BlockSelector deserialize(@NotNull Type expectedType, @NotNull ConfigurationNode node) throws SerializationException {
Object raw = node.rawScalar();
if (!(raw instanceof String value)) {
throw new SerializationException(expectedType, "Expected a namespaced block selector");
}
try {
return BlockSelector.parse(value);
} catch (IllegalArgumentException exception) {
throw new SerializationException(expectedType, exception.getMessage(), exception);
}
}
@Override
public void serialize(@NotNull Type expectedType, BlockSelector value, @NotNull ConfigurationNode node) {
node.raw(value == null ? null : value.toString());
}
};
}
}
@@ -0,0 +1,69 @@
package games.cubi.raycastedantiesp.core.config;
import org.spongepowered.configurate.CommentedConfigurationNode;
import org.spongepowered.configurate.ConfigurationNode;
import org.spongepowered.configurate.ConfigurateException;
import org.spongepowered.configurate.NodePath;
import org.spongepowered.configurate.transformation.ConfigurationTransformation;
import org.spongepowered.configurate.transformation.MoveStrategy;
/** Upgrades supported on-disk schemas before defaults are merged or objects are mapped. */
final class ConfigMigration {
private static final String PREVIOUS_CONFIG_VERSION = "2.0";
private static final ConfigurationTransformation VERSION_2_1_TRANSFORMATION = createVersion21Transformation();
private ConfigMigration() {
}
static boolean migrate(CommentedConfigurationNode node) {
ConfigurationNode versionNode = node.node("config-version");
Object rawVersion = versionNode.raw();
if (rawVersion == null) {
versionNode.raw(RootConfig.CURRENT_VERSION);
return true;
}
if (!(rawVersion instanceof String version)) {
throw new ConfigLoadException("config-version must be a string");
}
if (RootConfig.CURRENT_VERSION.equals(version)) {
return false;
}
if (!PREVIOUS_CONFIG_VERSION.equals(version)) {
throw unsupportedVersion(version);
}
try {
VERSION_2_1_TRANSFORMATION.apply(node);
} catch (ConfigurateException e) {
throw new ConfigLoadException("Failed to migrate config-version '" + PREVIOUS_CONFIG_VERSION + "' to '" + RootConfig.CURRENT_VERSION + "'", e);
}
versionNode.raw(RootConfig.CURRENT_VERSION);
return true;
}
static ConfigLoadException unsupportedVersion(String version) {
return new ConfigLoadException(
"Unsupported config-version '" + version + "'. RaycastedAntiESP requires config-version '"
+ RootConfig.CURRENT_VERSION + "'."
);
}
private static ConfigurationTransformation createVersion21Transformation() {
ConfigurationTransformation.Builder builder = ConfigurationTransformation.builder().moveStrategy(MoveStrategy.MERGE);
addMove(builder, "info-level", "info", "level");
addMove(builder, "info-exempted-classes", "info", "exempted-classes");
addMove(builder, "warn-level", "warn", "level");
addMove(builder, "warn-exempted-classes", "warn", "exempted-classes");
addMove(builder, "error-level", "error", "level");
addMove(builder, "error-exempted-classes", "error", "exempted-classes");
builder.addAction(NodePath.path("block-processor", "packetevents"), (path, value) -> {
value.raw(null);
return null;
});
return builder.build();
}
private static void addMove(ConfigurationTransformation.Builder builder, String oldKey, String severity, String newKey) {
builder.addAction(NodePath.path("debug", oldKey), (path, value) -> new Object[] {"logging", severity, newKey});
}
}
@@ -0,0 +1,16 @@
package games.cubi.raycastedantiesp.core.config;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.RECORD_COMPONENT})
public @interface ConfigRange {
long min();
long max();
}
@@ -0,0 +1,30 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.config;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Comment;
@ConfigSerializable
public record DebugConfig(
@Comment("Show raycast debug particles.")
boolean particles,
@Comment("Record and report engine timing information.")
boolean timings
) implements Config {
public static final DebugConfig DEFAULT = new DebugConfig(false, false);
public boolean showDebugParticles() {
return particles;
}
public boolean recordTimings() {
return timings;
}
}
@@ -0,0 +1,23 @@
package games.cubi.raycastedantiesp.core.config;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/** Adds comments to collection entries matched by their serialized string values, without replacing existing comments. */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.RECORD_COMPONENT})
public @interface ListEntryComments {
Entry[] value();
@Retention(RetentionPolicy.RUNTIME)
@Target({})
@interface Entry {
String value();
String comment();
}
}
@@ -0,0 +1,33 @@
package games.cubi.raycastedantiesp.core.config;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Comment;
import java.util.List;
@ConfigSerializable
public record LogLevelConfig(
@Comment("Messages above this level are suppressed. Set to 0 to suppress this severity.")
@ConfigRange(min = 0, max = 10)
byte level,
@Comment("Simple or fully qualified class names whose messages should be suppressed.")
List<String> exemptedClasses
) implements Config {
public static final LogLevelConfig DEFAULT = new LogLevelConfig((byte) 5, List.of());
public LogLevelConfig {
exemptedClasses = List.copyOf(exemptedClasses);
}
public boolean isExempted(Class<?>... sources) {
if (sources == null || exemptedClasses.isEmpty()) {
return false;
}
for (Class<?> source : sources) {
if (source != null && (exemptedClasses.contains(source.getSimpleName()) || exemptedClasses.contains(source.getName()))) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,22 @@
package games.cubi.raycastedantiesp.core.config;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
@ConfigSerializable
public record LoggingConfig(LogLevelConfig info, LogLevelConfig warn, LogLevelConfig error) implements Config {
public static final LoggingConfig DEFAULT = new LoggingConfig(LogLevelConfig.DEFAULT, LogLevelConfig.DEFAULT, LogLevelConfig.DEFAULT);
public LogLevelConfig forSeverity(Severity severity) {
return switch (severity) {
case INFO -> info;
case WARN -> warn;
case ERROR -> error;
};
}
public enum Severity {
INFO,
WARN,
ERROR
}
}
@@ -0,0 +1,35 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.config;
import games.cubi.raycastedantiesp.core.config.engine.EngineConfig;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Setting;
@ConfigSerializable
public record RootConfig(
String configVersion,
@Setting("logging") LoggingConfig loggingConfig,
@Setting("checks") ChecksConfig checksConfig,
@Setting("engine") EngineConfig engineConfig,
@Setting("block-processor") BlockProcessorConfig blockProcessorConfig,
@Setting("debug") DebugConfig debugConfig,
@Setting("updates") UpdateConfig updateConfig
) implements Config {
public static final String CURRENT_VERSION = "2.1";
public static final RootConfig DEFAULT = new RootConfig(
CURRENT_VERSION,
LoggingConfig.DEFAULT,
ChecksConfig.DEFAULT,
EngineConfig.DEFAULT,
BlockProcessorConfig.DEFAULT,
DebugConfig.DEFAULT,
UpdateConfig.DEFAULT
);
}
@@ -0,0 +1,27 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.config;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Comment;
@ConfigSerializable
public record UpdateConfig(
boolean checkRelease,
boolean checkBeta,
boolean checkAlpha,
@Comment("When true, players with permission are notified; otherwise only the console is notified.")
boolean notifyInGame
) implements Config {
public static final UpdateConfig DEFAULT = new UpdateConfig(true, true, true, true);
public boolean anyChannelEnabled() {
return checkRelease || checkBeta || checkAlpha;
}
}
@@ -0,0 +1,25 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.config.engine;
import games.cubi.raycastedantiesp.core.config.Config;
import games.cubi.raycastedantiesp.core.config.ConfigRange;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Comment;
import org.spongepowered.configurate.objectmapping.meta.Setting;
@ConfigSerializable
public record AsyncEngineConfig(
@Setting("processing-threads")
@Comment("Number of async processing threads. One is sufficient for hundreds of players.")
@ConfigRange(min = 1, max = 64)
int asyncProcessingThreads
) implements Config {
public static final AsyncEngineConfig DEFAULT = new AsyncEngineConfig(1);
}
@@ -0,0 +1,25 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.config.engine;
import games.cubi.raycastedantiesp.core.config.Config;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Setting;
@ConfigSerializable
public record EngineConfig(
EngineMode mode,
@Setting("async") AsyncEngineConfig asyncConfig
) implements Config {
public static final EngineConfig DEFAULT = new EngineConfig(EngineMode.ASYNC, AsyncEngineConfig.DEFAULT);
public EngineMode getMode() {
return mode;
}
}
@@ -0,0 +1,49 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.config.engine;
import games.cubi.raycastedantiesp.core.config.ConfigEnum;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public enum EngineMode implements ConfigEnum {
ASYNC("async", "simple"),
NETTY("netty");
private final String configName;
private final @Nullable String aliasName;
EngineMode(String configName) {
this.configName = configName;
aliasName = null;
}
EngineMode(String configName, @NotNull String aliasName) {
this.configName = configName;
this.aliasName = aliasName;
}
public String getName() {
return configName;
}
public static @Nullable EngineMode fromString(String name) {
for (EngineMode mode : values()) {
if (mode.configName.equalsIgnoreCase(name) || name.equalsIgnoreCase(mode.aliasName)) {
return mode;
}
}
return null;
}
@Override
public String[] getValues() {
return new String[] {NETTY.configName, ASYNC.configName};
}
}
@@ -0,0 +1,93 @@
package games.cubi.raycastedantiesp.core.config.raycast;
import org.jetbrains.annotations.NotNull;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.regex.Pattern;
/**
* A namespaced block key, optionally restricted by property values. Omitted properties match any value.
*/
public record BlockSelector(String value) {
private static final Pattern NAMESPACE = Pattern.compile("[a-z0-9_.-]+");
private static final Pattern PATH = Pattern.compile("[a-z0-9/._-]+");
private static final Pattern PROPERTY = Pattern.compile("[a-z0-9_]+");
public BlockSelector {
validate(value);
}
public static BlockSelector parse(String input) {
return new BlockSelector(input);
}
public String blockKey() {
int openingBracket = value.indexOf('[');
return openingBracket < 0 ? value : value.substring(0, openingBracket);
}
public boolean matchesAllStates() {
return value.indexOf('[') < 0;
}
@Override
public @NotNull String toString() {
return value;
}
private static void validate(String input) {
Objects.requireNonNull(input, "value");
int openingBracket = input.indexOf('[');
if (openingBracket < 0) {
if (input.indexOf(']') >= 0) {
throw new IllegalArgumentException("Unexpected closing bracket in block selector");
}
validateBlockKey(input);
return;
}
if (!input.endsWith("]") || input.indexOf('[', openingBracket + 1) >= 0
|| input.indexOf(']', openingBracket) != input.length() - 1) {
throw new IllegalArgumentException("Malformed block-state properties");
}
String propertyText = input.substring(openingBracket + 1, input.length() - 1);
if (propertyText.isEmpty()) {
throw new IllegalArgumentException("Block-state properties cannot be empty");
}
validateBlockKey(input.substring(0, openingBracket));
Set<String> properties = new HashSet<>();
for (String assignment : propertyText.split(",", -1)) {
int equals = assignment.indexOf('=');
if (equals <= 0 || equals != assignment.lastIndexOf('=') || equals == assignment.length() - 1) {
throw new IllegalArgumentException("Invalid block-state property '" + assignment + "'");
}
String name = validateProperty(assignment.substring(0, equals), "property name");
validateProperty(assignment.substring(equals + 1), "property value");
if (!properties.add(name)) {
throw new IllegalArgumentException("Duplicate block property '" + name + "'");
}
}
}
private static String validateBlockKey(String blockKey) {
Objects.requireNonNull(blockKey, "blockKey");
int separator = blockKey.indexOf(':');
if (separator <= 0 || separator != blockKey.lastIndexOf(':') || separator == blockKey.length() - 1
|| !NAMESPACE.matcher(blockKey.substring(0, separator)).matches()
|| !PATH.matcher(blockKey.substring(separator + 1)).matches()) {
throw new IllegalArgumentException("Invalid namespaced block key '" + blockKey + "'");
}
return blockKey;
}
private static String validateProperty(String value, String description) {
Objects.requireNonNull(value, description);
if (!PROPERTY.matcher(value).matches()) {
throw new IllegalArgumentException("Invalid block-state " + description + " '" + value + "'");
}
return value;
}
}
@@ -0,0 +1,27 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.config.raycast;
import games.cubi.raycastedantiesp.core.config.Config;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Comment;
@ConfigSerializable
public record ChunkSectionConfig(
@Comment("Whether chunk sections are hidden when they cannot be seen. This feature is not implemented yet.")
boolean enabled,
@Comment("Maximum number of occluding blocks permitted by a successful raycast.")
int maxOccludingCount,
@Comment("Radius in chunks within which chunk sections are always visible.")
int alwaysShowRadiusChunks,
@Comment("Ticks between checks of visible chunk sections. -1 disables visible rechecks.")
int visibleRecheckIntervalTicks
) implements Config {
public static final ChunkSectionConfig DEFAULT = new ChunkSectionConfig(false, 6, 2, -1);
}
@@ -0,0 +1,91 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.config.raycast;
import games.cubi.raycastedantiesp.core.config.ListEntryComments;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Comment;
import org.spongepowered.configurate.objectmapping.meta.Setting;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
@ConfigSerializable
public record EntityConfig(
@Setting(nodeFromParent = true)
RaycastSettings raycastSettings,
@Comment("Suppress sounds produced by hidden entities.")
boolean hideSoundsWhenHidden,
@Comment("Retain hidden entities client-side instead of destroying them. This will cause a non-moving \"ghost player\" to persist until the real player is visible again, but can reduce network load around large mob farms or bases.")
boolean keepClientEntityWhenHidden,
@Comment("""
Entity types that must always remain visible.
Falling blocks are also often used in custom mechanics, especially by plugins predating display entities. However, they occur in regular gameplay and can reveal information about hidden players, so they are not excluded by default. To exclude them, add minecraft:falling_block.
Add further exclusions using the namespaced entity name accepted by the /summon command.
""")
@ListEntryComments({
@ListEntryComments.Entry(value = "minecraft:arrow", comment =
"Projectiles move very quickly, giving the raycast engine limited time to process them. "
+ "This could leave players without enough time to dodge, so projectiles are always visible by default."),
@ListEntryComments.Entry(value = "minecraft:area_effect_cloud", comment =
"Potions and area-effect clouds can damage players even when not visible. "
+ "A reasonable always-show-radius mitigates this, so exempting them is not always necessary. "
+ "Servers where knowing the exact number of potions another player has used is an unfair advantage may want to remove these exclusions."),
@ListEntryComments.Entry(value = "minecraft:potion", comment =
"The minecraft:potion entity was removed in 1.21.5 and replaced by minecraft:splash_potion and minecraft:lingering_potion. "
+ "On 1.21.4, remove the latter two entries; on 1.21.5 and newer, remove minecraft:potion instead."),
@ListEntryComments.Entry(value = "minecraft:lightning_bolt", comment = "Lightning is short-lived and expected to be visible to players who cannot see the block being struck."),
@ListEntryComments.Entry(value = "minecraft:ender_dragon", comment = "Boss entities are also always visible by default."),
@ListEntryComments.Entry(value = "minecraft:block_display", comment =
"Display, interaction, and mannequin entities are not normally seen in vanilla gameplay and are commonly used for custom mechanics. "
+ "Removing these exclusions is likely to break plugins such as hologram or NPC plugins.")
})
Set<String> excludedTypes
) implements RaycastConfig {
public static final EntityConfig DEFAULT = new EntityConfig(
new RaycastSettings(true, (byte) 3, (short) 8, (short) 92, (short) 24, (short) 5),
false,
false,
new LinkedHashSet<>(List.of(
"minecraft:arrow",
"minecraft:spectral_arrow",
"minecraft:fireball",
"minecraft:dragon_fireball",
"minecraft:small_fireball",
"minecraft:firework_rocket",
"minecraft:wither_skull",
"minecraft:breeze_wind_charge",
"minecraft:wind_charge",
"minecraft:ender_pearl",
"minecraft:evoker_fangs",
"minecraft:shulker_bullet",
"minecraft:area_effect_cloud",
"minecraft:lingering_potion",
"minecraft:splash_potion",
"minecraft:potion",
"minecraft:lightning_bolt",
"minecraft:ender_dragon",
"minecraft:wither",
"minecraft:warden",
"minecraft:block_display",
"minecraft:text_display",
"minecraft:item_display",
"minecraft:interaction",
"minecraft:mannequin"
))
);
public EntityConfig {
excludedTypes = Collections.unmodifiableSet(new LinkedHashSet<>(excludedTypes));
}
}
@@ -0,0 +1,42 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.config.raycast;
import games.cubi.logs.Logger;
import it.unimi.dsi.fastutil.ints.IntSet;
import it.unimi.dsi.fastutil.ints.IntSets;
/**
* Immutable entity-type exclusion policy resolved during plugin startup.
*/
public final class EntityTypeExclusions {
public static volatile IntSet volatileExclusionSet = null;
// Is this sort of an insane approach? Yes. But it works.
static class FakeLazyConstant {
private static final IntSet finalEntityTypeExclusions = init();
private static IntSet init() {
IntSet set = volatileExclusionSet;
if (set == null) {
Logger.error(new RuntimeException("Exclusion set was not initialised before being read"), 4, EntityTypeExclusions.class);
return IntSets.emptySet();
}
return set;
}
}
public static boolean excludes(int entityType) {
return FakeLazyConstant.finalEntityTypeExclusions.contains(entityType);
}
public static int size() {
return FakeLazyConstant.finalEntityTypeExclusions.size();
}
}
@@ -0,0 +1,32 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.config.raycast;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Comment;
import org.spongepowered.configurate.objectmapping.meta.Setting;
@ConfigSerializable
public record PlayerConfig(
@Setting(nodeFromParent = true)
RaycastSettings raycastSettings,
@Comment("Suppress sounds produced by hidden players.")
boolean hideSoundsWhenHidden,
@Comment("Retain hidden players client-side instead of destroying their entities. This will cause a non-moving \"ghost player\" to persist until the real player is visible again.")
boolean keepClientEntityWhenHidden,
@Comment("Only raycast other players while the viewing player is sneaking.")
boolean onlyCheckSneaking
) implements RaycastConfig {
public static final PlayerConfig DEFAULT = new PlayerConfig(
new RaycastSettings(true, (byte) 3, (short) 8, (short) 128, (short) 24, (short) 5),
false,
false,
true
);
}
@@ -0,0 +1,62 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.config.raycast;
import games.cubi.raycastedantiesp.core.config.Config;
public interface RaycastConfig extends Config {
RaycastSettings raycastSettings();
default boolean enabled() {
return raycastSettings().enabled();
}
default boolean hideSoundsWhenHidden() {
return false;
}
default byte getMaxOccludingCount() {
return raycastSettings().maxOccludingCount();
}
default short getAlwaysShowRadius() {
return raycastSettings().alwaysShowRadius();
}
default short getRaycastRadius() {
return raycastSettings().raycastRadius();
}
default short hideOnSpawnDistance() {
return raycastSettings().hideOnSpawnDistance();
}
default short getVisibleRecheckIntervalTicks() {
return raycastSettings().visibleRecheckIntervalTicks();
}
default boolean keepClientEntityWhenHidden() {
return false;
}
default int alwaysShowRadiusSquared() {
int radius = getAlwaysShowRadius();
return radius * radius;
}
default int raycastRadiusSquared() {
int radius = getRaycastRadius();
return radius * radius;
}
default int hideOnSpawnDistanceSquared() {
int distance = hideOnSpawnDistance();
return distance * distance;
}
}
@@ -0,0 +1,27 @@
package games.cubi.raycastedantiesp.core.config.raycast;
import games.cubi.raycastedantiesp.core.config.ConfigRange;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Comment;
@ConfigSerializable
public record RaycastSettings(
@Comment("Whether this category is checked.")
boolean enabled,
@Comment("Maximum number of occluding blocks permitted by a successful raycast.")
@ConfigRange(min = 0, max = Byte.MAX_VALUE)
byte maxOccludingCount,
@Comment("Distance in blocks within which targets are always visible.")
@ConfigRange(min = 0, max = Short.MAX_VALUE)
short alwaysShowRadius,
@Comment("Maximum distance in blocks at which targets are raycasted.")
@ConfigRange(min = 0, max = Short.MAX_VALUE)
short raycastRadius,
@Comment("Distance in blocks beyond which a newly spawned target starts hidden.")
@ConfigRange(min = 0, max = Short.MAX_VALUE)
short hideOnSpawnDistance,
@Comment("Ticks between checks of visible targets. -1 keeps a shown target visible permanently.")
@ConfigRange(min = -1, max = Short.MAX_VALUE)
short visibleRecheckIntervalTicks
) {
}
@@ -0,0 +1,27 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.config.raycast;
import games.cubi.raycastedantiesp.core.config.Config;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Comment;
@ConfigSerializable
public record SoundEffectsConfig(
@Comment("Whether sounds should be hidden when their source cannot be seen. This feature is not implemented yet.")
boolean enabled,
@Comment("Maximum number of occluding blocks permitted by a successful sound raycast.")
int maxOccludingCount,
@Comment("Distance in blocks within which sounds are always played.")
int alwaysPlayRadius,
@Comment("Maximum distance in blocks at which sounds are raycasted.")
int raycastRadius
) implements Config {
public static final SoundEffectsConfig DEFAULT = new SoundEffectsConfig(false, 3, 8, 48);
}
@@ -0,0 +1,36 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.config.raycast;
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
import org.spongepowered.configurate.objectmapping.meta.Comment;
import org.spongepowered.configurate.objectmapping.meta.Setting;
import java.util.List;
@ConfigSerializable
public record TileEntityConfig(
@Setting(nodeFromParent = true)
RaycastSettings raycastSettings,
@Comment("Blocks that should not be managed as tile entities. Use namespaced block keys.\n"
+ "\"minecraft:chest\" matches every chest state.\n"
+ "\"minecraft:chest[waterlogged=true]\" matches all waterlogged chests, regardless of facing or chest type.\n"
+ "Omitted properties are wildcards. All specified properties must match. Specify every property to select one exact state.\n"
+ "A block is excluded if any list entry matches. Changes require a server restart.")
List<BlockSelector> excludedBlocks
) implements RaycastConfig {
public static final TileEntityConfig DEFAULT = new TileEntityConfig(
new RaycastSettings(true, (byte) 3, (short) 8, (short) 64, (short) 24, (short) -1),
List.of(BlockSelector.parse("minecraft:beacon"))
);
public TileEntityConfig {
excludedBlocks = List.copyOf(excludedBlocks);
}
}
@@ -0,0 +1,489 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.engine;
import games.cubi.locatables.api.Locatable;
import games.cubi.logs.Logger;
import games.cubi.raycastedantiesp.core.config.ConfigManager;
import games.cubi.raycastedantiesp.core.config.DebugConfig;
import games.cubi.raycastedantiesp.core.config.raycast.EntityConfig;
import games.cubi.raycastedantiesp.core.config.raycast.PlayerConfig;
import games.cubi.raycastedantiesp.core.config.raycast.TileEntityConfig;
import games.cubi.raycastedantiesp.core.entity.EntityBypassRegistry;
import games.cubi.raycastedantiesp.core.tracked.NettyEntity;
import games.cubi.raycastedantiesp.core.players.PlayerData;
import games.cubi.raycastedantiesp.core.players.PlayerRegistry;
import games.cubi.raycastedantiesp.core.raycast.ParticleSpawner;
import games.cubi.raycastedantiesp.core.raycast.RaycastUtil;
import games.cubi.utils.lists.PrimitiveIntArrayList;
import games.cubi.raycastedantiesp.core.view.BlockView;
import games.cubi.raycastedantiesp.core.view.EntityView;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.IntSupplier;
public abstract class AsyncEngine implements Engine {
private static final long SLOW_TICK_NANOS = 40 * 1_000_000L;
//Literally just magic numbers I made by keyboard mashing
private static final int TICK_IDLE = 1872;
private static final int TICK_PENDING = -129;
private static final int TICK_RUNNING = 34892;
private final ConfigManager config;
private final ParticleSpawner particleSpawner;
private final IntSupplier currentTickSupplier;
private final AtomicInteger tickThreadsRunning = new AtomicInteger(0);
private final AtomicInteger runningTick = new AtomicInteger(-1);
private final AtomicInteger tickState = new AtomicInteger(TICK_IDLE);
private final AtomicLong tickNanos = new AtomicLong(0);
private final AsyncRunner asyncRunner;
private final TimingStatsSelector timingStatsSelector = new TimingStatsSelector();
public AsyncEngine(ConfigManager config, ParticleSpawner particleSpawner, IntSupplier currentTickSupplier, AsyncRunner asyncRunner) {
this.config = config;
this.particleSpawner = particleSpawner;
this.currentTickSupplier = currentTickSupplier;
this.asyncRunner = asyncRunner;
}
/**
* Reserves the next engine tick before it is handed to the async scheduler.
*
* @return true if the caller now owns the only pending tick slot; false if an existing pending
* or running tick should cover this attempt.
*/
public boolean markTickRunning() {
if (tickState.compareAndSet(TICK_IDLE, TICK_PENDING)) {
return true;
}
recordSkippedTick(-1, System.nanoTime());
return false;
}
/**
* Releases a pending tick reservation when async scheduling fails before {@link #tick(int, long)}
* can claim it.
*/
public void cancelPendingTickReservation() {
if (!tickState.compareAndSet(TICK_PENDING, TICK_IDLE)) {
Logger.warning("Attempted to cancel a pending tick reservation, but the tick was no longer pending.", 5, AsyncEngine.class);
}
}
/**
* Runs the tick which was reserved using {@link #markTickRunning} and, if the engine falls behind the server clock, keeps the
* same worker on the latest tick instead of yielding back to the scheduler.
*
* @param scheduledTick the server tick captured before async handoff.
* @param scheduledNanos the time captured before async handoff, used to separate queue delay from engine work.
*/
@Override
public void tick(int scheduledTick, long scheduledNanos) {
boolean runTick = true;
boolean expectPending = true;
int startTick = currentTickSupplier.getAsInt();
while (runTick) {
if (!startTickState(scheduledTick, expectPending)) {
return;
}
if (!dispatchTick(scheduledTick, startTick, scheduledNanos)) {
return;
}
int latestTick = currentTickSupplier.getAsInt();
if (latestTick > startTick) {
// If running behind, don't yield the thread, just run the next tick immediately
Logger.warning("Tick thread completed tick #" + startTick + " after tick #" + latestTick + " had already begun. Starting next tick immediately instead of yielding thread to scheduler. This is probably safe to ignore but may suggest that your server is overloaded.", 5, AsyncEngine.class);
startTick = latestTick;
scheduledNanos = System.nanoTime();
scheduledTick = latestTick;
if (tickState.get() == TICK_RUNNING) {
// This means that there is already a tick running, so we should exit
Logger.info("Tick finished behind but another thread had already begun ticking the next tick.", 5, AsyncEngine.class);
return;
}
expectPending = false; //Next call to startTickState should not expect to see status set to pending
}
else runTick = false;
}
}
/**
* Claims worker capacity and either runs work immediately or schedules worker batches.
*
* @return true if at least one sub-tick worker accepted responsibility for completing the tick
* lifecycle; false if this attempt was skipped or cleaned up during setup.
*/
private boolean dispatchTick(int scheduledTick, int startTick, long scheduledNanos) {
int threads = config.getEngineConfig().asyncConfig().asyncProcessingThreads();
if (threads < 1) threads = 1;
DebugConfig debugConfig = config.getDebugConfig();
TimingStats tickTimingStats = timingStats(debugConfig);
boolean recordTimings = tickTimingStats != TimingStatsNoOp.INSTANCE;
long startNanos = System.nanoTime();
int tickAlreadyRunning = runningTick.get();
// First guard for the current tick already being processed (can happen if the previous tick ran overtime and thus didn't yield the thread)
if (scheduledTick == tickAlreadyRunning) {
logAggregateReport(tickTimingStats.recordSkipped(threads, startNanos));
Logger.info("RaycastedAntiESP is already processing this tick; skipping duplicate same-tick attempt."
+ " scheduledTick=" + scheduledTick
+ " currentServerTick=" + startTick
+ " currentRunningTick=" + tickAlreadyRunning, 6, AsyncEngine.class);
finishTickState();
return false;
}
int runningThreads = tickThreadsRunning.compareAndExchange(0, threads);
// Now guard for previous tick still running
if (runningThreads != 0) {
long queueNanos = Math.max(0, startNanos - scheduledNanos);
Logger.warning("RaycastedAntiESP is still ticking from the last tick! Skipping this tick to avoid concurrent modification issues."
+ " scheduledTick=" + scheduledTick
+ " currentServerTick=" + currentTickSupplier.getAsInt()
+ " currentRunningTick=" + tickAlreadyRunning
+ " runningThreads=" + runningThreads
+ " timeSpentInQueue=" + TickTimingFormatter.formatMillis(queueNanos) + "ms", 5, AsyncEngine.class);
logAggregateReport(tickTimingStats.recordSkipped(threads, startNanos));
finishTickState();
return false;
}
TickTimings timings = null;
boolean handedOffToSubTick = false;
boolean claimedRunningTick = false;
try {
tickNanos.set(startNanos);
final int currentTick = startTick;
runningTick.set(currentTick);
claimedRunningTick = true;
PlayerData[] allPlayers = PlayerRegistry.get().getPlayerDataArray();
EntityConfig entityConfig = config.getEntityConfig();
PlayerConfig playerConfig = config.getPlayerConfig();
TileEntityConfig tileEntityConfig = config.getTileEntityConfig();
if (recordTimings) {
timings = new TickTimings(scheduledTick, scheduledNanos, currentTick, startNanos, threads, allPlayers.length);
}
/*
Logger.debug("Tick #" + currentTick);
if (currentTick % 1200 == 0) {
Logger.debug("Printing player data");
for (PlayerData playerData : allPlayers) {
Logger.debug("Player " + playerData.getPlayerUUID() + " location=" + playerData.ownLocation());
Logger.debug("EntityView:" + playerData.entityView().getStringDataForDebugging());
Logger.debug("PlayerView:" + playerData.playerView().getStringDataForDebugging());
}
}*/
// If only one thread is configured, just use the current async thread to avoid the overhead of scheduling tasks and context switching.
if (threads == 1) {
handedOffToSubTick = true;
subTick(allPlayers, entityConfig, playerConfig, tileEntityConfig, debugConfig, currentTick, timings, tickTimingStats);
return true;
}
List<PlayerData[]> batches = new ArrayList<>(threads);
int playerCount = allPlayers.length;
for (int i = 0; i < threads; i++) {
int batchSize = (playerCount + threads - 1 - i) / threads;
batches.add(new PlayerData[batchSize]);
}
int index = 0;
for (PlayerData playerData : allPlayers) {
int batchIndex = index % threads;
int position = index / threads;
batches.get(batchIndex)[position] = playerData;
index++;
}
TickTimings tickTimings = timings; // needs to be effectively-final for lambda
int scheduledBatches = 0;
try {
for (PlayerData[] batch : batches) {
asyncRunner.runNow(() -> subTick(batch, entityConfig, playerConfig, tileEntityConfig, debugConfig, currentTick, tickTimings, tickTimingStats));
scheduledBatches++;
}
handedOffToSubTick = true;
}
finally {
if (scheduledBatches < threads) {
tickThreadsRunning.addAndGet(-(threads - scheduledBatches));
handedOffToSubTick = scheduledBatches > 0;
}
}
return handedOffToSubTick;
}
finally {
if (!handedOffToSubTick) {
tickThreadsRunning.set(0);
if (claimedRunningTick) {
finaliseTick(startTick);
} else {
finishTickState();
}
Logger.error("An error occurred during tick scheduling before handing off to sub-tick processing. Resetting tickThreadsRunning to 0 to avoid deadlock. Current tick: " + currentTickSupplier.getAsInt(), 2, AsyncEngine.class);
}
}
}
/**
* Processes one worker batch and lets the final batch publish timing data and release the tick reservation.
*
* @param timingStats the timing sink selected when this tick started, so config changes during
* worker execution do not split one tick across sinks.
*/
private void subTick(PlayerData[] batch, EntityConfig entityConfig, PlayerConfig playerConfig, TileEntityConfig tileEntityConfig, DebugConfig debugConfig, int currentTick, TickTimings timings, TimingStats timingStats) {
TickTimingBatch batchTimings = timings == null ? TickTimingBatchNoOp.INSTANCE : new TickTimingBatch();
long batchStartNanos = batchTimings.startBatch();
try {
processTickForPlayers(batch, entityConfig, playerConfig, tileEntityConfig, debugConfig.showDebugParticles(), currentTick, batchTimings);
}
finally {
if (timings != null) {
timings.recordBatch(batchTimings, batchTimings.elapsedSince(batchStartNanos));
}
int threadsRemaining = tickThreadsRunning.decrementAndGet();
if (threadsRemaining < 0) {
Logger.error("tickThreadsRunning went below 0! This should never happen. Resetting to 0 to avoid further issues.", 2, AsyncEngine.class);
tickThreadsRunning.set(0);
finaliseTick(currentTick);
}
if (threadsRemaining == 0) {
try {
long completionNanos = System.nanoTime();
if (timings != null) {
TickTimingSnapshot snapshot = timings.snapshot(currentTickSupplier.getAsInt(), completionNanos);
String aggregateReport = timingStats.recordCompleted(snapshot, completionNanos);
if (snapshot.wallNanos() > SLOW_TICK_NANOS) {
Logger.warning(snapshot.toSlowTickMessage(), 5, AsyncEngine.class);
}
logAggregateReport(aggregateReport);
} else {
long elapsedNanos = completionNanos - tickNanos.get();
if (elapsedNanos > SLOW_TICK_NANOS) {
Logger.warning("Tick completed in " + (elapsedNanos / 1_000_000.0) + " ms. If you see this warning frequently, consider reducing the raycasting load by adjusting the configuration.", 5, AsyncEngine.class);
}
}
} finally {
finaliseTick(currentTick);
}
}
}
}
/**
* Moves the reserved tick into the running state. Catch-up iterations may start from idle
* because they are created by the current worker instead of by the server tick event.
*
* @return true if this thread now owns the running state; false if another pending or running
* tick should take precedence.
*/
private boolean startTickState(int scheduledTick, boolean expectPending) {
if (expectPending) {
if (tickState.compareAndSet(TICK_PENDING, TICK_RUNNING)) {
return true;
}
if (tickState.compareAndSet(TICK_IDLE, TICK_RUNNING)) {
// This means that this tick was dispatched but not marked as such, or was unmarked at some point.
Logger.warning("Tick " + scheduledTick + " was dispatched but not marked as pending. This suggests a race condition. Please report this on our GitHub or Discord.", 5, AsyncEngine.class);
return true;
}
} else if (tickState.compareAndSet(TICK_IDLE, TICK_RUNNING)) {
return true;
}
// This means there is already a tick pending or running, so we should exit.
recordSkippedTick(-1, System.nanoTime());
Logger.info("Tick " + scheduledTick + " is pending but another tick is already pending or running. Exiting now.", 6, AsyncEngine.class);
return false;
}
/**
* Releases ownership for the tick that completed, without clearing a newer running tick that
* may have already taken over.
*/
private void finaliseTick(int currentTick) {
runningTick.compareAndSet(currentTick, -1);
finishTickState();
}
/**
* Returns the reservation state to idle after the active tick has stopped touching shared player visibility data.
*/
private void finishTickState() {
if (!tickState.compareAndSet(TICK_RUNNING, TICK_IDLE)) {
// This should never happen as it means the tick was marked as completed before processing was completed
Logger.warning("tickState was not running when completing tick! This should never happen. Please report this on our GitHub or Discord.", 5, AsyncEngine.class);
}
}
private void processTickForPlayers(PlayerData[] playerDataList, EntityConfig entityConfig, PlayerConfig playerConfig, TileEntityConfig tileEntityConfig,
boolean debugParticles, int currentTick, TickTimingBatch timings) {
for (PlayerData playerData : playerDataList) {
if (!playerData.isConnected()) {
continue;
}
playerData.nettyData().markPendingPostSpawnTasksForEviction();
if (playerData.hasBypassPermission()) {
timings.incrementBypassSkippedPlayers();
continue;
}
BlockView blockView = playerData.blockView();
Locatable playerLocation = playerData.ownLocation();
if (playerLocation == null || playerLocation.world() == null) {
timings.incrementNullLocationSkippedPlayers();
continue;
}
int worldEpoch = playerData.tryAcquireWorldEpochFor(playerLocation.world());
if (worldEpoch == PlayerData.INVALID_WORLD_EPOCH) {
if (tileEntityConfig.enabled()) timings.incrementTileWorldSkipped();
continue;
}
timings.incrementProcessedPlayers();
try {
if (entityConfig.enabled()) {
long sectionStartNanos = timings.startEntitySection();
checkEntities(playerData, playerLocation, entityConfig, debugParticles, blockView, currentTick, worldEpoch, timings);
timings.finishEntitySection(sectionStartNanos);
}
if (playerConfig.enabled()) {
long sectionStartNanos = timings.startPlayerSection();
checkPlayers(playerData, playerLocation, playerConfig, debugParticles, blockView, currentTick, worldEpoch, timings);
timings.finishPlayerSection(sectionStartNanos);
}
if (tileEntityConfig.enabled()) {
long sectionStartNanos = timings.startTileSection();
checkTileEntities(playerData, playerLocation, tileEntityConfig, debugParticles, blockView, currentTick, worldEpoch, timings);
timings.finishTileSection(sectionStartNanos);
}
} finally {
playerData.entityView().flushPendingTransitions();
playerData.playerView().flushPendingTransitions();
blockView.flushPendingTransitions();
}
}
}
private void checkEntities(PlayerData player, Locatable playerLocation, EntityConfig entityConfig, boolean debugParticles, BlockView blockView, int currentTick, int worldEpoch, TickTimingBatch timings) {
EntityView<?> entityView = player.entityView();
int alwaysShowRadiusSquared = entityConfig.alwaysShowRadiusSquared();
int raycastRadiusSquared = entityConfig.raycastRadiusSquared();
int checked = entityView.forEachNeedingRecheckEntity(entityConfig.getVisibleRecheckIntervalTicks(), currentTick, !(timings instanceof TickTimingBatchNoOp), worldEpoch, entity -> {
if (entity.glowing()) {
entityView.setVisibility(entity, true, currentTick, worldEpoch);
return;
}
if (attachedToAlwaysVisibleEntityOrSelf(player, entityView, entity, currentTick, worldEpoch)) {
return;
}
timings.incrementEntityRaycasts();
boolean canSee = RaycastUtil.raycastUnrolledAccumulated(entityConfig.getMaxOccludingCount(), alwaysShowRadiusSquared, raycastRadiusSquared, debugParticles, entity.getYOffset(), blockView, playerLocation, entity, particleSpawner);
entityView.setVisibility(entity, canSee, currentTick, worldEpoch);
});
timings.addEntityChecked(checked);
}
private void checkPlayers(PlayerData player, Locatable playerLocation, PlayerConfig playerConfig, boolean debugParticles, BlockView blockView, int currentTick, int worldEpoch, TickTimingBatch timings) {
EntityView<?> playerView = player.playerView();
int alwaysShowRadiusSquared = playerConfig.alwaysShowRadiusSquared();
int raycastRadiusSquared = playerConfig.raycastRadiusSquared();
int checked = playerView.forEachNeedingRecheckEntity(playerConfig.getVisibleRecheckIntervalTicks(), currentTick, !(timings instanceof TickTimingBatchNoOp), worldEpoch, otherPlayer -> {
if (otherPlayer.glowing() || (playerConfig.onlyCheckSneaking() && !otherPlayer.sneaking())) {
playerView.setVisibility(otherPlayer, true, currentTick, worldEpoch);
return;
}
if (attachedToAlwaysVisibleEntityOrSelf(player, playerView, otherPlayer, currentTick, worldEpoch)) {
return;
}
timings.incrementPlayerRaycasts();
boolean canSee = RaycastUtil.raycastUnrolledAccumulated(playerConfig.getMaxOccludingCount(), alwaysShowRadiusSquared, raycastRadiusSquared, debugParticles, 1.5f, blockView, playerLocation, otherPlayer, particleSpawner);
playerView.setVisibility(otherPlayer, canSee, currentTick, worldEpoch);
});
timings.addPlayerChecked(checked);
}
private boolean attachedToAlwaysVisibleEntityOrSelf(PlayerData player, EntityView<?> view, NettyEntity<?> entity, int currentTick, int worldEpoch) {
int selfEntityID = player.nettyData().getSelfEntityID();
if (!player.nettyData().isSelfEntityID(entity.leashingEntity())
&& !player.nettyData().isSelfEntityID(entity.vehicleID())
&& !EntityBypassRegistry.isBypassed(entity.vehicleID())
&& !PrimitiveIntArrayList.contains(entity.passengerIDsNoAlloc(), selfEntityID)) {
return false;
}
view.setVisibility(entity, true, currentTick, worldEpoch);
return true;
}
private void checkTileEntities(PlayerData player, Locatable playerLocation, TileEntityConfig tileEntityConfig, boolean debugParticles, BlockView blockView, int currentTick, int worldEpoch, TickTimingBatch timings) {
long modeToken = blockView.tileEntityCheckModeToken();
int alwaysShowRadiusSquared = tileEntityConfig.alwaysShowRadiusSquared();
int raycastRadiusSquared = tileEntityConfig.raycastRadiusSquared();
int checked = blockView.updateVisibilityForEachNeedingRecheck(tileEntityConfig.getVisibleRecheckIntervalTicks(), currentTick, modeToken, worldEpoch, tileEntityLocation -> {
if (playerLocation.distanceSquared(tileEntityLocation) > raycastRadiusSquared) {
timings.incrementTileRadiusSkipped();
return BlockView.VisibilityResolver.HIDE;
}
timings.incrementTileRaycasts();
boolean canSee = RaycastUtil.raycastUnrolledAccumulated(tileEntityConfig.getMaxOccludingCount(), alwaysShowRadiusSquared, raycastRadiusSquared, debugParticles, 0, blockView, playerLocation, tileEntityLocation, particleSpawner);
return canSee ? BlockView.VisibilityResolver.SHOW : BlockView.VisibilityResolver.HIDE;
});
timings.addTileChecked(checked);
}
private static void logAggregateReport(String aggregateReport) {
if (aggregateReport != null) {
Logger.info(aggregateReport, 4, AsyncEngine.class);
}
}
/**
* Counts a skipped tick against the currently configured timing sink.
*/
private void recordSkippedTick(int threads, long nowNanos) {
logAggregateReport(timingStats().recordSkipped(threads, nowNanos));
}
/**
* Selects the timing sink from the current debug config.
*
* @return a collecting {@link TimingStats} while timing diagnostics are enabled, otherwise the
* no-op singleton.
*/
private TimingStats timingStats() {
return timingStats(config.getDebugConfig());
}
/**
* Keeps disabled timing diagnostics allocation-free and starts a fresh collection window when
* diagnostics are re-enabled.
*
* @return the timing sink that should be used for a newly starting tick or skip record.
*/
private TimingStats timingStats(DebugConfig debugConfig) {
return timingStatsSelector.select(debugConfig.recordTimings());
}
}
@@ -0,0 +1,13 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.engine;
public interface AsyncRunner {
void runNow(Runnable task);
}
@@ -0,0 +1,13 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.engine;
public interface Engine {
void tick(int scheduledTick, long scheduledNanos);
}
@@ -0,0 +1,110 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.engine;
public class TickTimingBatch {
long entityNanos;
long playerNanos;
long tileNanos;
int processedPlayers;
int bypassSkippedPlayers;
int nullLocationSkippedPlayers;
int entityChecked;
int entityRaycasts;
int entityNullTargets;
int playerChecked;
int playerRaycasts;
int playerNullTargets;
int tileChecked;
int tileRaycasts;
int tileWorldSkipped;
int tileRadiusSkipped;
TickTimingBatch() {}
public long startBatch() {
return System.nanoTime();
}
public long elapsedSince(long startNanos) {
return System.nanoTime() - startNanos;
}
public long startEntitySection() {
return System.nanoTime();
}
public void finishEntitySection(long startNanos) {
entityNanos += Math.max(0, System.nanoTime() - startNanos);
}
public long startPlayerSection() {
return System.nanoTime();
}
public void finishPlayerSection(long startNanos) {
playerNanos += Math.max(0, System.nanoTime() - startNanos);
}
public long startTileSection() {
return System.nanoTime();
}
public void finishTileSection(long startNanos) {
tileNanos += Math.max(0, System.nanoTime() - startNanos);
}
public void incrementProcessedPlayers() {
processedPlayers++;
}
public void incrementBypassSkippedPlayers() {
bypassSkippedPlayers++;
}
public void incrementNullLocationSkippedPlayers() {
nullLocationSkippedPlayers++;
}
public void addEntityChecked(int count) {
entityChecked += count;
}
public void incrementEntityRaycasts() {
entityRaycasts++;
}
public void addPlayerChecked(int count) {
playerChecked += count;
}
public void incrementPlayerRaycasts() {
playerRaycasts++;
}
public void addTileChecked(int count) {
tileChecked += count;
}
public void incrementTileWorldSkipped() {
tileWorldSkipped++;
}
public void incrementTileRadiusSkipped() {
tileRadiusSkipped++;
}
public void incrementTileRaycasts() {
tileRaycasts++;
}
}
@@ -0,0 +1,34 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.engine;
public class TickTimingBatchNoOp extends TickTimingBatch {
public static final TickTimingBatchNoOp INSTANCE = new TickTimingBatchNoOp();
public long startBatch() {return 0;}
public long elapsedSince(long startNanos) {return 0;}
public long startEntitySection() {return 0;}
public void finishEntitySection(long startNanos) {}
public long startPlayerSection() {return 0;}
public void finishPlayerSection(long startNanos) {}
public long startTileSection() {return 0;}
public void finishTileSection(long startNanos) {}
public void incrementProcessedPlayers() {}
public void incrementBypassSkippedPlayers() {}
public void incrementNullLocationSkippedPlayers() {}
public void addEntityChecked(int count) {}
public void incrementEntityNullTargets() {}
public void incrementEntityRaycasts() {}
public void addPlayerChecked(int count) {}
public void incrementPlayerNullTargets() {}
public void incrementPlayerRaycasts() {}
public void addTileChecked(int count) {}
public void incrementTileWorldSkipped() {}
public void incrementTileRadiusSkipped() {}
public void incrementTileRaycasts() {}
}
@@ -0,0 +1,23 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.engine;
import java.util.Locale;
final class TickTimingFormatter {
private TickTimingFormatter() {}
static String formatMillis(long nanos) {
return String.format(Locale.ROOT, "%.3f", nanos / 1_000_000.0);
}
static String formatSeconds(long nanos) {
return String.format(Locale.ROOT, "%.3f", nanos / 1_000_000_000.0);
}
}
@@ -0,0 +1,70 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.engine;
record TickTimingSnapshot(
int scheduledTick,
int startTick,
int completionTick,
int threads,
int registeredPlayers,
long queueNanos,
long wallNanos,
long maxBatchNanos,
long entityNanos,
long playerNanos,
long tileNanos,
int processedPlayers,
int bypassSkippedPlayers,
int nullLocationSkippedPlayers,
int entityChecked,
int entityRaycasts,
int playerChecked,
int playerRaycasts,
int tileChecked,
int tileRaycasts,
int tileWorldSkipped,
int tileRadiusSkipped
) {
String toSlowTickMessage() {
return "Tick completed slowly."
+ " scheduledTick=" + scheduledTick
+ " startTick=" + startTick
+ " completionTick=" + completionTick
+ " threads=" + threads
+ " wallTimeTaken=" + TickTimingFormatter.formatMillis(wallNanos) + "ms"
+ " schedulerWait=" + TickTimingFormatter.formatMillis(queueNanos) + "ms"
+ " slowestWorkerBatch=" + TickTimingFormatter.formatMillis(maxBatchNanos) + "ms"
+ " entityProcessingTime=" + TickTimingFormatter.formatMillis(entityNanos) + "ms"
+ " playerProcessingTime=" + TickTimingFormatter.formatMillis(playerNanos) + "ms"
+ " tileProcessingTime=" + TickTimingFormatter.formatMillis(tileNanos) + "ms"
+ " playerCount=" + registeredPlayers
+ " processedPlayers=" + processedPlayers
+ " bypassSkippedPlayers=" + bypassSkippedPlayers
+ " nullLocationSkippedPlayers=" + nullLocationSkippedPlayers
+ " entityRecheckCandidates=" + entityChecked
+ " entityRaycasts=" + entityRaycasts
+ " playerRecheckCandidates=" + playerChecked
+ " playerRaycasts=" + playerRaycasts
+ " tileRecheckCandidates=" + tileChecked
+ " tileRaycasts=" + tileRaycasts
+ " tileWorldSkipped=" + tileWorldSkipped
+ " tileRadiusSkipped=" + tileRadiusSkipped;
}
String toSlowestSummary() {
return "scheduledTick=" + scheduledTick
+ ", startedAtTick=" + startTick
+ ", totalWallTime=" + TickTimingFormatter.formatMillis(wallNanos) + " ms"
+ ", schedulerWait=" + TickTimingFormatter.formatMillis(queueNanos) + " ms"
+ ", slowestWorkerBatch=" + TickTimingFormatter.formatMillis(maxBatchNanos) + " ms"
+ ", processingTime(entity/player/tile)=" + TickTimingFormatter.formatMillis(entityNanos) + "/" + TickTimingFormatter.formatMillis(playerNanos) + "/" + TickTimingFormatter.formatMillis(tileNanos) + " ms"
+ ", raycasts(entity/player/tile)=" + entityRaycasts + "/" + playerRaycasts + "/" + tileRaycasts;
}
}
@@ -0,0 +1,97 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.engine;
final class TickTimings {
private final int scheduledTick;
private final long scheduledNanos;
private final int startTick;
private final long startNanos;
private final int threads;
private final int registeredPlayers;
private long maxBatchNanos;
private long entityNanos;
private long playerNanos;
private long tileNanos;
private int processedPlayers;
private int bypassSkippedPlayers;
private int nullLocationSkippedPlayers;
private int entityChecked;
private int entityRaycasts;
private int playerChecked;
private int playerRaycasts;
private int tileChecked;
private int tileRaycasts;
private int tileWorldSkipped;
private int tileRadiusSkipped;
TickTimings(int scheduledTick, long scheduledNanos, int startTick, long startNanos, int threads, int registeredPlayers) {
this.scheduledTick = scheduledTick;
this.scheduledNanos = scheduledNanos;
this.startTick = startTick;
this.startNanos = startNanos;
this.threads = threads;
this.registeredPlayers = registeredPlayers;
}
synchronized void recordBatch(TickTimingBatch batch, long batchNanos) {
// Batch-local primitive counters avoid atomic writes in the raycast loop, where the work being measured is sub-microsecond.
maxBatchNanos = Math.max(maxBatchNanos, Math.max(0, batchNanos));
entityNanos += batch.entityNanos;
playerNanos += batch.playerNanos;
tileNanos += batch.tileNanos;
processedPlayers += batch.processedPlayers;
bypassSkippedPlayers += batch.bypassSkippedPlayers;
nullLocationSkippedPlayers += batch.nullLocationSkippedPlayers;
entityChecked += batch.entityChecked;
entityRaycasts += batch.entityRaycasts;
playerChecked += batch.playerChecked;
playerRaycasts += batch.playerRaycasts;
tileChecked += batch.tileChecked;
tileRaycasts += batch.tileRaycasts;
tileWorldSkipped += batch.tileWorldSkipped;
tileRadiusSkipped += batch.tileRadiusSkipped;
}
synchronized TickTimingSnapshot snapshot(int completionTick, long completionNanos) {
return new TickTimingSnapshot(
scheduledTick,
startTick,
completionTick,
threads,
registeredPlayers,
Math.max(0, startNanos - scheduledNanos),
Math.max(0, completionNanos - scheduledNanos),
maxBatchNanos,
entityNanos,
playerNanos,
tileNanos,
processedPlayers,
bypassSkippedPlayers,
nullLocationSkippedPlayers,
entityChecked,
entityRaycasts,
playerChecked,
playerRaycasts,
tileChecked,
tileRaycasts,
tileWorldSkipped,
tileRadiusSkipped
);
}
}
@@ -0,0 +1,157 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.engine;
import it.unimi.dsi.fastutil.longs.LongArrayList;
import it.unimi.dsi.fastutil.longs.LongComparators;
import it.unimi.dsi.fastutil.longs.LongIterator;
import it.unimi.dsi.fastutil.longs.LongList;
public class TimingStats {
private static final long REPORT_INTERVAL_NANOS = 30_000_000_000L;
private final LongArrayList wallSamples = new LongArrayList();
private final LongArrayList schedulerWaitSamples = new LongArrayList();
private final LongArrayList slowestWorkerBatchSamples = new LongArrayList();
private final LongArrayList entityWorkerSamples = new LongArrayList();
private final LongArrayList playerWorkerSamples = new LongArrayList();
private final LongArrayList tileWorkerSamples = new LongArrayList();
private long intervalStartNanos = 0;
private long nextReportNanos = 0;
private int completedTicks = 0;
private int skippedTicks = 0;
private int lastThreads = 0;
private long entityRaycastsTotal = 0;
private long playerRaycastsTotal = 0;
private long tileRaycastsTotal = 0;
private TickTimingSnapshot slowestTick = null;
/**
* Drops the current reporting window so later samples do not mix with data collected under a previous timing configuration.
*/
synchronized void reset() {
wallSamples.clear();
schedulerWaitSamples.clear();
slowestWorkerBatchSamples.clear();
entityWorkerSamples.clear();
playerWorkerSamples.clear();
tileWorkerSamples.clear();
intervalStartNanos = 0;
nextReportNanos = 0;
completedTicks = 0;
skippedTicks = 0;
lastThreads = 0;
entityRaycastsTotal = 0;
playerRaycastsTotal = 0;
tileRaycastsTotal = 0;
slowestTick = null;
}
/**
* Adds a completed tick to the active reporting window.
*
* @return a formatted aggregate report when the reporting interval has elapsed; otherwise null.
*/
synchronized String recordCompleted(TickTimingSnapshot snapshot, long nowNanos) {
ensureInterval(nowNanos);
completedTicks++;
lastThreads = snapshot.threads();
wallSamples.add(snapshot.wallNanos());
schedulerWaitSamples.add(snapshot.queueNanos());
slowestWorkerBatchSamples.add(snapshot.maxBatchNanos());
entityWorkerSamples.add(snapshot.entityNanos());
playerWorkerSamples.add(snapshot.playerNanos());
tileWorkerSamples.add(snapshot.tileNanos());
entityRaycastsTotal += snapshot.entityRaycasts();
playerRaycastsTotal += snapshot.playerRaycasts();
tileRaycastsTotal += snapshot.tileRaycasts();
if (slowestTick == null || snapshot.wallNanos() > slowestTick.wallNanos()) {
slowestTick = snapshot;
}
return reportIfDue(nowNanos);
}
/**
* Adds a skipped tick attempt to the active reporting window without creating worker timing samples.
*
* @return a formatted aggregate report when the reporting interval has elapsed; otherwise null.
*/
synchronized String recordSkipped(int threads, long nowNanos) {
ensureInterval(nowNanos);
skippedTicks++;
if (threads != -1) lastThreads = threads;
return reportIfDue(nowNanos);
}
private void ensureInterval(long nowNanos) {
if (nextReportNanos == 0) {
intervalStartNanos = nowNanos;
nextReportNanos = nowNanos + REPORT_INTERVAL_NANOS;
}
}
private String reportIfDue(long nowNanos) {
if (nextReportNanos == 0 || nowNanos < nextReportNanos) {
return null;
}
String report = buildReport(nowNanos);
reset();
intervalStartNanos = nowNanos;
nextReportNanos = nowNanos + REPORT_INTERVAL_NANOS;
return report;
}
private String buildReport(long nowNanos) {
long intervalNanos = Math.max(1, nowNanos - intervalStartNanos);
String slowestSummary = slowestTick == null ? "n/a" : slowestTick.toSlowestSummary();
return "Raycasted Anti-ESP tick timing summary for the last " + TickTimingFormatter.formatSeconds(intervalNanos) + "s:\n"
+ "Completed Anti-ESP ticks: " + completedTicks + "\n"
+ "Skipped tick attempts: " + skippedTicks + "\n"
+ "Configured worker threads: " + lastThreads + "\n\n"
+ "Total time from server tick event to Anti-ESP completion (avg / p50 / p95 / max): " + formatStats(wallSamples) + "\n"
+ "Time spent waiting in the async scheduler before Anti-ESP work started (avg / p50 / p95 / max): " + formatStats(schedulerWaitSamples) + "\n"
+ "Slowest worker batch processing time after work started (avg / p50 / p95 / max): " + formatStats(slowestWorkerBatchSamples) + "\n\n"
+ "Worker section times are summed across worker batches for multi-threaded ticks, not wall-clock critical-path time.\n"
+ "Worker time spent checking entities per completed tick (avg / p50 / p95 / max): " + formatStats(entityWorkerSamples) + "\n"
+ "Worker time spent checking players per completed tick (avg / p50 / p95 / max): " + formatStats(playerWorkerSamples) + "\n"
+ "Worker time spent checking tile entities per completed tick (avg / p50 / p95 / max): " + formatStats(tileWorkerSamples) + "\n\n"
+ "Total raycasts performed, entity / player / tile: " + entityRaycastsTotal + " / " + playerRaycastsTotal + " / " + tileRaycastsTotal + "\n"
+ "Slowest tick in this interval: " + slowestSummary;
}
private String formatStats(LongList samples) {
if (samples.isEmpty()) {
return "n/a";
}
LongArrayList sorted = new LongArrayList(samples);
sorted.sort(LongComparators.NATURAL_COMPARATOR);
long total = 0;
LongIterator iterator = sorted.longIterator();
while (iterator.hasNext()) {
total += iterator.nextLong();
}
int sampleCount = sorted.size();
return TickTimingFormatter.formatMillis(total / sorted.size())
+ " / " + TickTimingFormatter.formatMillis(percentile(sorted, 0.50))
+ " / " + TickTimingFormatter.formatMillis(percentile(sorted, 0.95))
+ " / " + TickTimingFormatter.formatMillis(sorted.getLong(sampleCount - 1))
+ " ms";
}
private long percentile(LongList sorted, double percentile) {
int index = Math.min(sorted.size() - 1, Math.max(0, (int) Math.ceil(sorted.size() * percentile) - 1));
return sorted.getLong(index);
}
}
@@ -0,0 +1,28 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.engine;
public class TimingStatsNoOp extends TimingStats {
static final TimingStatsNoOp INSTANCE = new TimingStatsNoOp();
private TimingStatsNoOp() {}
@Override
void reset() {}
@Override
String recordCompleted(TickTimingSnapshot snapshot, long nowNanos) {
return null;
}
@Override
String recordSkipped(int threads, long nowNanos) {
return null;
}
}
@@ -0,0 +1,32 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.engine;
import java.util.concurrent.atomic.AtomicReference;
/** Lock-free selection of the timing sink used by a newly starting tick or skip record. */
final class TimingStatsSelector {
private final AtomicReference<TimingStats> current = new AtomicReference<>(TimingStatsNoOp.INSTANCE);
TimingStats select(boolean enabled) {
if (!enabled) {
current.set(TimingStatsNoOp.INSTANCE);
return TimingStatsNoOp.INSTANCE;
}
TimingStats existing = current.get();
if (existing != TimingStatsNoOp.INSTANCE) {
return existing;
}
TimingStats created = new TimingStats();
TimingStats witness = current.compareAndExchange(TimingStatsNoOp.INSTANCE, created);
return witness == TimingStatsNoOp.INSTANCE ? created : witness;
}
}
@@ -0,0 +1,38 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.entity;
import games.cubi.utils.sets.CopyOnWriteMTIntSet;
/**
* Global registry of entity IDs which RaycastedAntiESP must ignore.
*/
public final class EntityBypassRegistry {
private static final CopyOnWriteMTIntSet BYPASSED_ENTITY_IDS = CopyOnWriteMTIntSet.get();
// Technically, (26.2+) Minecraft only guarantees that an entity ID corresponds to one-and-only-one entity within a single world, and entities in different worlds can have the same ID.
// (26.1.2-) Minecraft does not guarantee that an entity ID is unique.
// However, this requires the int id counter to overflow from Integer.MAX_VALUE all the way back to 0. This is unlikely to occur, and even if it does occur, it is unlikely that the original entities are still alive.
private EntityBypassRegistry() {
}
public static void addEntity(int entityID) {
BYPASSED_ENTITY_IDS.add(entityID);
}
/**
* For use when an entity is despawned/killed, or in other words completely gone from the server.
*/
public static boolean markEntityDespawned(int entityID) {
return BYPASSED_ENTITY_IDS.remove(entityID);
}
public static boolean isBypassed(int entityID) {
return BYPASSED_ENTITY_IDS.contains(entityID);
}
}
@@ -0,0 +1,399 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.players;
import games.cubi.logs.Logger;
import games.cubi.raycastedantiesp.core.tracked.EntitySpawnTask;
import games.cubi.raycastedantiesp.core.tracked.NettyEntity;
import games.cubi.raycastedantiesp.core.utils.Packet.Packets;
import games.cubi.utils.Clearable;
import games.cubi.utils.VarHandler;
import games.cubi.utils.lists.IntArrayListMarker;
import games.cubi.utils.lists.PrimitiveIntArrayList;
import it.unimi.dsi.fastutil.ints.Int2IntArrayMap;
import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.objects.ObjectIterator;
import org.jetbrains.annotations.Nullable;
import java.lang.invoke.VarHandle;
import static games.cubi.raycastedantiesp.core.tracked.NettyEntity.NO_LEASHER;
import static games.cubi.raycastedantiesp.core.tracked.NettyEntity.NO_VEHICLE;
/**
* Per-player mutable state intended for Netty-side packet tracking and deferred reconciliation.
*/
public class NettyData implements Clearable {
//
public boolean packetsAreWithinBundle = false;
//
private static final int DEFAULT_MAP_SIZE = 16;
//
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// START Leash tracking:
//
private final Int2ObjectArrayMap<int[]> unresolvedLeashedEntityIDsByHolderID = new Int2ObjectArrayMap<>(DEFAULT_MAP_SIZE);
private final Int2IntArrayMap unresolvedHolderIDsByLeashedEntityID = new Int2IntArrayMap(DEFAULT_MAP_SIZE);
public void addUnresolvedLeash(int holderEntityID, int leashedEntityID) {
int previousHolderEntityID = unresolvedHolderIDsByLeashedEntityID.put(leashedEntityID, holderEntityID);
if (previousHolderEntityID != NO_LEASHER && previousHolderEntityID != holderEntityID) {
removeLeashedEntityFromUnresolvedHolder(previousHolderEntityID, leashedEntityID);
}
unresolvedLeashedEntityIDsByHolderID.compute(holderEntityID, (ignored, existing) -> {
if (PrimitiveIntArrayList.contains(existing, leashedEntityID)) {
return existing;
}
return PrimitiveIntArrayList.add(existing, leashedEntityID);
});
}
public boolean removeUnresolvedLeash(int holderEntityID, int leashedEntityID) {
if (unresolvedHolderIDsByLeashedEntityID.get(leashedEntityID) != holderEntityID) {
return false;
}
unresolvedHolderIDsByLeashedEntityID.remove(leashedEntityID);
removeLeashedEntityFromUnresolvedHolder(holderEntityID, leashedEntityID);
return true;
}
public int getUnresolvedHolderForLeashedEntity(int leashedEntityID) {
return unresolvedHolderIDsByLeashedEntityID.get(leashedEntityID);
}
public int[] getUnresolvedLeashes(int holderEntityID) {
return PrimitiveIntArrayList.getCopyOrNull(unresolvedLeashedEntityIDsByHolderID.get(holderEntityID));
}
/**
* Returns internal Netty-thread reconciliation state without copying it.
* Callers must not mutate the returned array.
*/
public int[] getUnresolvedLeashesNoAlloc(int holderEntityID) {
return unresolvedLeashedEntityIDsByHolderID.get(holderEntityID);
}
public int[] consumeUnresolvedLeashes(int holderEntityID) {
int[] existing = unresolvedLeashedEntityIDsByHolderID.remove(holderEntityID);
if (PrimitiveIntArrayList.isEmpty(existing)) {
return existing;
}
for (int leashedEntityID : existing) {
if (unresolvedHolderIDsByLeashedEntityID.get(leashedEntityID) == holderEntityID) {
unresolvedHolderIDsByLeashedEntityID.remove(leashedEntityID);
}
}
return existing;
}
public int consumeUnresolvedHolderForLeashedEntity(int leashedEntityID) {
int holderEntityID = unresolvedHolderIDsByLeashedEntityID.remove(leashedEntityID);
if (holderEntityID == NO_LEASHER) {
return NO_LEASHER;
}
removeLeashedEntityFromUnresolvedHolder(holderEntityID, leashedEntityID);
return holderEntityID;
}
private void removeLeashedEntityFromUnresolvedHolder(int holderEntityID, int leashedEntityID) {
unresolvedLeashedEntityIDsByHolderID.computeIfPresent(holderEntityID, (ignored, existing) -> {
int[] updated = PrimitiveIntArrayList.remove(existing, leashedEntityID);
return PrimitiveIntArrayList.isEmpty(updated) ? null : updated;
});
}
//
// END Leash tracking.
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//
//
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// START Passenger tracking:
//
/**
* Latest full passenger list for a vehicle that is not represented by a tracked entity.
* Normally this is temporary reconciliation state while a vehicle or passenger is waiting to spawn.
* Bypassed vehicles remain untracked, so their authoritative passenger list stays here until it is
* replaced by another passenger packet or cleared by the vehicle's destroy packet.
*/
private final Int2ObjectArrayMap<int[]> unresolvedPassengerIDsByVehicleID = new Int2ObjectArrayMap<>(DEFAULT_MAP_SIZE);
/**
* Reverse lookup for passenger relationships stored above.
* Lets a later passenger spawn discover which untracked vehicle most recently claimed it as a passenger.
* This may grow larger than {@link #unresolvedPassengerIDsByVehicleID} if vehicles have several passengers, so it's an open hash map.
*/
private final Int2IntOpenHashMap unresolvedVehicleIDsByPassengerID = new Int2IntOpenHashMap(DEFAULT_MAP_SIZE);
{
unresolvedHolderIDsByLeashedEntityID.defaultReturnValue(NO_LEASHER);
unresolvedVehicleIDsByPassengerID.defaultReturnValue(NO_VEHICLE);
}
public int[] getUnresolvedPassengers(int vehicleEntityID) {
return PrimitiveIntArrayList.getCopyOrNull(unresolvedPassengerIDsByVehicleID.get(vehicleEntityID));
}
/**
* Returns internal Netty-thread reconciliation state without copying it.
* Callers must not mutate the returned array.
*/
public int[] getUnresolvedPassengersNoAlloc(int vehicleEntityID) {
return unresolvedPassengerIDsByVehicleID.get(vehicleEntityID);
}
/**
* Replaces any previous unresolved passenger state for this vehicle.
* The passenger packet is authoritative, so the latest packet wins.
*/
public void setUnresolvedPassengers(int vehicleEntityID, int[] passengerIDs) {
consumeUnresolvedPassengers(vehicleEntityID);
if (PrimitiveIntArrayList.isEmpty(passengerIDs)) {
return;
}
int[] copiedPassengerIDs = passengerIDs.clone();
unresolvedPassengerIDsByVehicleID.put(vehicleEntityID, copiedPassengerIDs);
for (int passengerID : copiedPassengerIDs) {
int previousVehicleID = unresolvedVehicleIDsByPassengerID.put(passengerID, vehicleEntityID);
if (previousVehicleID != NO_VEHICLE && previousVehicleID != vehicleEntityID) {
removePassengerFromUnresolvedVehicle(previousVehicleID, passengerID);
}
}
}
public int[] consumeUnresolvedPassengers(int vehicleEntityID) {
int[] existing = unresolvedPassengerIDsByVehicleID.remove(vehicleEntityID);
if (PrimitiveIntArrayList.isEmpty(existing)) {
return existing;
}
for (int passengerID : existing) {
if (unresolvedVehicleIDsByPassengerID.get(passengerID) == vehicleEntityID) {
unresolvedVehicleIDsByPassengerID.remove(passengerID);
}
}
return existing;
}
public int getUnresolvedVehicleForPassenger(int passengerEntityID) {
return unresolvedVehicleIDsByPassengerID.get(passengerEntityID);
}
public boolean removeUnresolvedPassengerLink(int passengerEntityID, int vehicleEntityID) {
if (unresolvedVehicleIDsByPassengerID.get(passengerEntityID) != vehicleEntityID) {
return false;
}
unresolvedVehicleIDsByPassengerID.remove(passengerEntityID);
removePassengerFromUnresolvedVehicle(vehicleEntityID, passengerEntityID);
return true;
}
public int consumeUnresolvedVehicleForPassenger(int passengerEntityID) {
int vehicleEntityID = unresolvedVehicleIDsByPassengerID.remove(passengerEntityID);
if (vehicleEntityID == NO_VEHICLE) {
return NO_VEHICLE;
}
removePassengerFromUnresolvedVehicle(vehicleEntityID, passengerEntityID);
return vehicleEntityID;
}
private void removePassengerFromUnresolvedVehicle(int vehicleEntityID, int passengerEntityID) {
unresolvedPassengerIDsByVehicleID.computeIfPresent(vehicleEntityID, (ignored, existing) -> {
if (!PrimitiveIntArrayList.contains(existing, passengerEntityID)) {
return existing;
}
int[] updated = PrimitiveIntArrayList.remove(existing, passengerEntityID);
return PrimitiveIntArrayList.isEmpty(updated) ? null : updated;
});
}
//
// END Passenger tracking.
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//
//
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// START Netty entity spawn task queue:
//
private final Int2ObjectArrayMap<EntitySpawnTask> pendingPostEntitySpawnTasksByEntityID = new Int2ObjectArrayMap<>(16); // shot in the dark guess at capacity here. Can't be the more generic Int2ObjectMap because that doesn't expose a fast iterator.
private volatile boolean evictPendingPostSpawnTasksOnNextPacket; private static final VarHandle EVICT_PENDING_POST_SPAWN_TASKS_ON_NEXT_PACKET_HANDLE = VarHandler.get(NettyData.class, "evictPendingPostSpawnTasksOnNextPacket", boolean.class);
/**
* This is intended for reconciliation tasks due to Minecraft sending packets out of order. For example, {@link Packets#ENTITY_EQUIPMENT} is sent before the corresponding {@link Packets#SPAWN_ENTITY} packet, so caching of the equipment packet must await the spawn packet.
* @param entityID The entity ID to associate the task with. Immediately after a {@link Packets#SPAWN_ENTITY} packet is processed for this entity ID, the task will be consumed and run.
* @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 ((boolean) EVICT_PENDING_POST_SPAWN_TASKS_ON_NEXT_PACKET_HANDLE.getOpaque(this)
&& (boolean) EVICT_PENDING_POST_SPAWN_TASKS_ON_NEXT_PACKET_HANDLE.compareAndExchangeAcquire(this, true, false)) evictOldPendingPostSpawnTasks(currentTick);
}
public void markPendingPostSpawnTasksForEviction() {
EVICT_PENDING_POST_SPAWN_TASKS_ON_NEXT_PACKET_HANDLE.setOpaque(this, 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.
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//
//
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// START Self entity tracking:
//
private final NettyEntity<?> selfEntity;
private final int selfEntityID;
public NettyData(NettyEntity<?> selfEntity) {
this.selfEntity = selfEntity;
this.selfEntityID = selfEntity.entityID();
}
public NettyEntity<?> getSelfEntity() {
return selfEntity;
}
public int getSelfEntityID() {
return selfEntityID;
}
public boolean isSelfEntityID(int entityID) {
return entityID == selfEntityID;
}
//
// END Self entity tracking.
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//
//
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// START World-transition destroy tracking:
//
private int @IntArrayListMarker [] expectedWorldTransitionDestroyEntityIDs;
/**
* When changing worlds, the server sends destroy packets for all the entities in the old world, but we want to clear the view. Tracking them here allows those destroy packets to be handled correctly.
*/
public void setExpectedWorldTransitionDestroyEntityIDs(int[] expectedEntityIDs) {
expectedWorldTransitionDestroyEntityIDs = PrimitiveIntArrayList.isEmpty(expectedEntityIDs) ? null : expectedEntityIDs.clone();
}
public boolean consumeExpectedWorldTransitionDestroyEntityID(int entityID) {
if (!PrimitiveIntArrayList.contains(expectedWorldTransitionDestroyEntityIDs, entityID)) {
return false;
}
expectedWorldTransitionDestroyEntityIDs = PrimitiveIntArrayList.remove(expectedWorldTransitionDestroyEntityIDs, entityID);
if (PrimitiveIntArrayList.isEmpty(expectedWorldTransitionDestroyEntityIDs)) {
expectedWorldTransitionDestroyEntityIDs = null;
}
return true;
}
//
// END World-transition destroy tracking.
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//
//
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// START World tracking:
//
private int currentWorldMinHeight = Integer.MIN_VALUE; // Netty thread access only
private String currentWorldName = null; // Netty thread access only
public int getCurrentWorldMinHeight() {
if (currentWorldMinHeight == Integer.MIN_VALUE) {
Logger.error(new IllegalStateException("Current world min height was requested before it was set"), 3, NettyData.class);
return -64;
}
return currentWorldMinHeight;
}
public NettyData setCurrentWorldMinHeight(int currentWorldMinHeight) {
this.currentWorldMinHeight = currentWorldMinHeight;
return this;
}
/**
*
* @return The current world name, or null if the player is still in the process of joining the server.
*/
public @Nullable String getCurrentWorldName() {
return currentWorldName;
}
public NettyData setCurrentWorldName(String currentWorldName) {
this.currentWorldName = currentWorldName;
return this;
}
//
// END World tracking.
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//
public void clearPendingReconciliationState() {
unresolvedLeashedEntityIDsByHolderID.clear();
unresolvedHolderIDsByLeashedEntityID.clear();
unresolvedPassengerIDsByVehicleID.clear();
unresolvedVehicleIDsByPassengerID.clear();
pendingPostEntitySpawnTasksByEntityID.clear();
evictPendingPostSpawnTasksOnNextPacket = false;
}
@Override
public void clear() {
clearPendingReconciliationState();
expectedWorldTransitionDestroyEntityIDs = null;
if (selfEntity != null) {
selfEntity.clear();
}
currentWorldMinHeight = Integer.MIN_VALUE;
currentWorldName = null;
}
}
@@ -0,0 +1,205 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.players;
import games.cubi.locatables.api.Locatable;
import games.cubi.locatables.implementations.ThreadSafeLocatable;
import games.cubi.logs.Logger;
import games.cubi.raycastedantiesp.core.tracked.NettyEntity;
import games.cubi.utils.VarHandler;
import games.cubi.raycastedantiesp.core.view.BlockView;
import games.cubi.raycastedantiesp.core.view.EntityView;
import games.cubi.raycastedantiesp.core.view.ViewRegistry;
import games.cubi.raycastedantiesp.core.view.controller.PacketEntityViewController;
import org.jetbrains.annotations.Nullable;
import java.lang.invoke.VarHandle;
import java.util.Objects;
import java.util.UUID;
import java.util.function.IntSupplier;
public class PlayerData {
public static final int INVALID_WORLD_EPOCH = -1;
private final UUID playerUUID;
private final int joinTick;
private volatile boolean hasBypassPermission;
private volatile boolean connected;
private final ThreadSafeLocatable ownLocation;
private final BlockView blockView;
private final EntityView<?> entityView;
private final EntityView<?> playerView;
private final NettyData nettyData;
// Even positive values are stable world sessions; odd values mean the views are being replaced.
private volatile int worldEpoch; private static final VarHandle WORLD_EPOCH = VarHandler.get(PlayerData.class, "worldEpoch", int.class);
private UUID viewWorld;
PlayerData(UUID player, boolean hasBypassPermission, int joinTick, int selfEntityID, PlayerRegistry.SelfEntityCreator selfEntityCreator) {
this.joinTick = joinTick;
this.playerUUID = player;
this.hasBypassPermission = hasBypassPermission;
connected = true;
IntSupplier worldEpochSupplier = this::acquireWorldEpoch;
blockView = ViewRegistry.createBlockView(worldEpochSupplier);
entityView = ViewRegistry.createEntityView(worldEpochSupplier);
playerView = ViewRegistry.createPlayerEntityView(worldEpochSupplier);
ownLocation = new ThreadSafeLocatable(null, 0, 0, 0);
NettyEntity<?> selfEntity = Logger.requireNonNull(
selfEntityCreator.createSelfEntity(this, selfEntityID, player),
"Self entity creator returned null",
3,
PlayerData.class
);
nettyData = new NettyData(selfEntity);
}
public EntityView<?> entityView() {
return entityView;
}
public EntityView<?> playerView() {
return playerView;
}
public NettyData nettyData() {
return nettyData;
}
public BlockView blockView() {
return blockView;
}
/** Acquire-reads the current player-wide view epoch. */
public int acquireWorldEpoch() {
return (int) WORLD_EPOCH.getAcquire(this);
}
/**
* Returns a stable epoch for {@code expectedWorld}, or {@link #INVALID_WORLD_EPOCH} when the world session is not usable.
*/
public int tryAcquireWorldEpochFor(UUID expectedWorld) {
int before = acquireWorldEpoch();
if (!isStableWorldEpoch(before)) {
return INVALID_WORLD_EPOCH;
}
UUID currentWorld = viewWorld;
int after = acquireWorldEpoch();
if (before != after || !Objects.equals(currentWorld, expectedWorld)) {
return INVALID_WORLD_EPOCH;
}
return before;
}
public static boolean isStableWorldEpoch(int epoch) {
return epoch != 0 && (epoch & 1) == 0;
}
/** Structural-writer operation performed before clearing all world-scoped views. */
public void beginWorldTransition() {
int current = acquireWorldEpoch();
if ((current & 1) != 0) { //current is odd
throw new IllegalStateException("World transition already in progress");
}
WORLD_EPOCH.setRelease(this, current + 1);
// Keep subsequent view-clearing writes behind the invalidating odd epoch.
VarHandle.releaseFence();
viewWorld = null;
}
/** Structural-writer operation performed after all world-scoped views have been cleared. */
public void completeWorldTransition(UUID world) {
int current = acquireWorldEpoch();
if ((current & 1) == 0) { //current is even
throw new IllegalStateException("No world transition in progress");
}
viewWorld = world;
WORLD_EPOCH.setRelease(this, current + 1);
}
public void updateOwnLocation(UUID world, double x, double y, double z) {
ownLocation.set(x, y, z, world);
}
/**
* Returns a live, thread-safe view of the player's current location.
* Casting the result to a mutable type and modifying it is unsupported.
*/
public Locatable ownLocation() {
return ownLocation;
}
public UUID getPlayerUUID() {
return playerUUID;
}
public boolean hasBypassPermission() {
return hasBypassPermission;
}
public int getJoinTick() {
return joinTick;
}
public boolean isConnected() {
return connected;
}
public void markDisconnected() {
connected = false;
int current = acquireWorldEpoch();
if ((current & 1) == 0) {
WORLD_EPOCH.setRelease(this, current + 1);
}
}
/**
* @return Either the entity or player view for this player, depending on the entity ID
*/
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 @Nullable NettyEntity<?> entityFromID(int entityID) {
if (nettyData.isSelfEntityID(entityID)) {
return nettyData.getSelfEntity();
}
EntityView<?> entityView = viewFromEntityID(entityID);
if (entityView == null) {
return null;
}
return (NettyEntity<?>) 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,355 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.players;
import games.cubi.locatables.api.FloatingLocatableEquality;
import games.cubi.locatables.api.Locatable;
import games.cubi.locatables.api.MutableFloatingLocatable;
import games.cubi.locatables.api.Spatial;
import games.cubi.utils.VarHandler;
import java.lang.invoke.VarHandle;
import java.util.Objects;
import java.util.UUID;
/**
* A mutable, thread-safe location and view state for a player.
*
* <p>Mutations are serialized because platform and packet lifecycle callbacks
* may write from different threads. World and scalar reads use relaxed
* per-field access: a read may combine values from adjacent updates.</p>
* <p></p>
* Reads of several fields are not coherently published. This is acceptable
* since players typically move in small increments, so an old x and new z
* still closely approximate the player's actual position. In less-frequent
* cases such as teleports or dimension switches, raycasts may use the incorrect
* position briefly. This does not matter, as incorrect state will be fixed by next tick's raycast.
*/
public final class PlayerLocatable implements MutableFloatingLocatable, FloatingLocatableEquality {
private final Object writerMonitor = new Object();
private volatile UUID world; private static final VarHandle WORLD = VarHandler.get(PlayerLocatable.class, "world", UUID.class);
private volatile double x; private static final VarHandle X = VarHandler.get(PlayerLocatable.class, "x", double.class);
private volatile double y; private static final VarHandle Y = VarHandler.get(PlayerLocatable.class, "y", double.class);
private volatile double z; private static final VarHandle Z = VarHandler.get(PlayerLocatable.class, "z", double.class);
private volatile float yaw; private static final VarHandle YAW = VarHandler.get(PlayerLocatable.class, "yaw", float.class);
private volatile float pitch; private static final VarHandle PITCH = VarHandler.get(PlayerLocatable.class, "pitch", float.class);
private volatile PlayerPose pose; private static final VarHandle POSE = VarHandler.get(PlayerLocatable.class, "pose", PlayerPose.class);
public PlayerLocatable() {
}
/** Initialises or replaces the complete valid player state. */
public void initialise(UUID world, double footX, double footY, double footZ, float yaw, float pitch, PlayerPose pose) {
validateFullState(world, footX, footY, footZ, yaw, pitch, pose);
synchronized (writerMonitor) {
writeFullState(world, footX, footY, footZ, yaw, pitch, pose);
}
}
/** Updates the complete state for a world change. */
public void worldChange(UUID world, double footX, double footY, double footZ, float yaw, float pitch, PlayerPose pose) {
validateFullState(world, footX, footY, footZ, yaw, pitch, pose);
synchronized (writerMonitor) {
writeFullState(world, footX, footY, footZ, yaw, pitch, pose);
}
}
/** Updates the player's foot position while retaining rotation and pose. */
public void updateFoot(double footX, double footY, double footZ) {
validateFinite(footX, footY, footZ);
synchronized (writerMonitor) {
X.setOpaque(this, footX);
Y.setOpaque(this, footY);
Z.setOpaque(this, footZ);
}
}
/** Updates the player's rotation while retaining position and pose. */
public void updateRotation(float yaw, float pitch) {
validateRotation(yaw, pitch);
synchronized (writerMonitor) {
YAW.setOpaque(this, yaw);
PITCH.setOpaque(this, pitch);
}
}
/** Updates the player's pose while retaining position and rotation. */
public void updatePose(PlayerPose pose) {
Objects.requireNonNull(pose, "pose");
synchronized (writerMonitor) {
POSE.setOpaque(this, pose);
}
}
/** Updates position and rotation in one logical operation. */
public void updateFootAndRotation(double footX, double footY, double footZ, float yaw, float pitch) {
validateFinite(footX, footY, footZ);
validateRotation(yaw, pitch);
synchronized (writerMonitor) {
X.setOpaque(this, footX);
Y.setOpaque(this, footY);
Z.setOpaque(this, footZ);
YAW.setOpaque(this, yaw);
PITCH.setOpaque(this, pitch);
}
}
/** Invalidates and clears the complete player state. */
public void invalidate() {
synchronized (writerMonitor) {
WORLD.setOpaque(this, null);
X.setOpaque(this, 0.0);
Y.setOpaque(this, 0.0);
Z.setOpaque(this, 0.0);
YAW.setOpaque(this, 0.0f);
PITCH.setOpaque(this, 0.0f);
POSE.setOpaque(this, null);
}
}
@Override
public UUID world() {
return (UUID) WORLD.getOpaque(this);
}
@Override
public double x() {
return (double) X.getOpaque(this);
}
@Override
public double y() {
return (double) Y.getOpaque(this);
}
@Override
public double z() {
return (double) Z.getOpaque(this);
}
public float yaw() {
return (float) YAW.getOpaque(this);
}
public float pitch() {
return (float) PITCH.getOpaque(this);
}
public PlayerPose pose() {
return (PlayerPose) POSE.getOpaque(this);
}
public float cameraYOffset() {
PlayerPose currentPose = (PlayerPose) POSE.getOpaque(this);
return currentPose == null ? 0.0f : currentPose.cameraYOffset();
}
public double cameraX() {
return (double) X.getOpaque(this);
}
public double cameraY() {
double currentY = (double) Y.getOpaque(this);
PlayerPose currentPose = (PlayerPose) POSE.getOpaque(this);
return currentY + (currentPose == null ? 0.0 : (double) currentPose.cameraYOffset());
}
public double cameraZ() {
return (double) Z.getOpaque(this);
}
public double cameraDistanceSquared(Spatial spatial) {
Objects.requireNonNull(spatial, "spatial");
double targetX = spatial.x();
double targetY = spatial.y();
double targetZ = spatial.z();
double currentX = (double) X.getOpaque(this);
double currentY = (double) Y.getOpaque(this);
double currentZ = (double) Z.getOpaque(this);
PlayerPose currentPose = (PlayerPose) POSE.getOpaque(this);
double dx = currentX - targetX;
double dy = currentY + (currentPose == null ? 0.0 : (double) currentPose.cameraYOffset()) - targetY;
double dz = currentZ - targetZ;
return dx * dx + dy * dy + dz * dz;
}
@Override
public PlayerLocatable setX(double x) {
validateFinite(x);
synchronized (writerMonitor) {
X.setOpaque(this, x);
return this;
}
}
@Override
public PlayerLocatable setY(double y) {
validateFinite(y);
synchronized (writerMonitor) {
Y.setOpaque(this, y);
return this;
}
}
@Override
public PlayerLocatable setZ(double z) {
validateFinite(z);
synchronized (writerMonitor) {
Z.setOpaque(this, z);
return this;
}
}
@Override
public PlayerLocatable setPosition(double x, double y, double z) {
validateFinite(x, y, z);
synchronized (writerMonitor) {
X.setOpaque(this, x);
Y.setOpaque(this, y);
Z.setOpaque(this, z);
return this;
}
}
@Override
public PlayerLocatable setPosition(Spatial spatial) {
Objects.requireNonNull(spatial, "spatial");
return setPosition(spatial.x(), spatial.y(), spatial.z());
}
@Override
public PlayerLocatable setWorld(UUID world) {
if (world == null) {
invalidate();
return this;
}
synchronized (writerMonitor) {
WORLD.setOpaque(this, world);
return this;
}
}
@Override
public PlayerLocatable setLocation(Locatable locatable) {
Objects.requireNonNull(locatable, "locatable");
return setLocation(locatable.world(), locatable.x(), locatable.y(), locatable.z());
}
@Override
public PlayerLocatable setLocation(UUID world, double x, double y, double z) {
validateFinite(x, y, z);
if (world == null) {
invalidate();
return this;
}
synchronized (writerMonitor) {
X.setOpaque(this, x);
Y.setOpaque(this, y);
Z.setOpaque(this, z);
WORLD.setOpaque(this, world);
return this;
}
}
@Override
public PlayerLocatable set(Locatable locatable) {
return setLocation(locatable);
}
@Override
public PlayerLocatable set(double x, double y, double z) {
return setPosition(x, y, z);
}
@Override
public PlayerLocatable set(int x, int y, int z) {
return setPosition(x, y, z);
}
@Override
public PlayerLocatable set(double x, double y, double z, UUID world) {
return setLocation(world, x, y, z);
}
@Override
public LocatableType getType() {
return LocatableType.ThreadSafe;
}
@Override
public boolean equals(Object other) {
return isEqualTo(other);
}
@Override
public int hashCode() {
return makeHash();
}
@Override
public boolean strictlyEquals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof PlayerLocatable that)) {
return false;
}
UUID thisWorld = world();
double thisX = x();
double thisY = y();
double thisZ = z();
return Objects.equals(thisWorld, that.world())
&& Double.doubleToLongBits(thisX) == Double.doubleToLongBits(that.x())
&& Double.doubleToLongBits(thisY) == Double.doubleToLongBits(that.y())
&& Double.doubleToLongBits(thisZ) == Double.doubleToLongBits(that.z());
}
@Override
public String toString() {
return toStringForm();
}
/** This method must only be called while holding {@link #writerMonitor}. */
private void writeFullState(UUID world, double footX, double footY, double footZ, float yaw, float pitch, PlayerPose pose) {
WORLD.setOpaque(this, null);
X.setOpaque(this, footX);
Y.setOpaque(this, footY);
Z.setOpaque(this, footZ);
YAW.setOpaque(this, yaw);
PITCH.setOpaque(this, pitch);
POSE.setOpaque(this, pose);
WORLD.setOpaque(this, world);
}
private static void validateFullState(UUID world, double footX, double footY, double footZ, float yaw, float pitch, PlayerPose pose) {
Objects.requireNonNull(world, "world");
Objects.requireNonNull(pose, "pose");
validateFinite(footX, footY, footZ);
validateRotation(yaw, pitch);
}
private static void validateFinite(double x, double y, double z) {
if (!Double.isFinite(x) || !Double.isFinite(y) || !Double.isFinite(z)) {
throw new IllegalArgumentException("Coordinates must be finite");
}
}
private static void validateFinite(double value) {
if (!Double.isFinite(value)) {
throw new IllegalArgumentException("Coordinate must be finite");
}
}
private static void validateRotation(float yaw, float pitch) {
if (!Float.isFinite(yaw) || !Float.isFinite(pitch) || pitch < -90.0f || pitch > 90.0f) {
throw new IllegalArgumentException("Rotation must be finite and pitch must be between -90 and 90 degrees");
}
}
}
@@ -0,0 +1,31 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.players;
/** Player body poses and the corresponding camera height above the feet. */
public enum PlayerPose {
UNKNOWN(1.62f),
STANDING(1.62f),
SNEAKING(1.27f),
SWIMMING(0.40f),
FALL_FLYING(0.40f),
SPIN_ATTACK(0.40f),
SLEEPING(0.20f),
DYING(0.20f);
private final float cameraYOffset;
PlayerPose(float cameraYOffset) {
this.cameraYOffset = cameraYOffset;
}
public float cameraYOffset() {
return cameraYOffset;
}
}
@@ -0,0 +1,97 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.players;
import games.cubi.raycastedantiesp.core.tracked.NettyEntity;
import games.cubi.utils.VarHandler;
import java.lang.invoke.VarHandle;
import java.util.Collection;
import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
public final class PlayerRegistry {
@FunctionalInterface
public interface SelfEntityCreator {
NettyEntity<?> createSelfEntity(PlayerData playerData, int selfEntityID, UUID playerUUID);
}
private static final PlayerRegistry instance = new PlayerRegistry();
private PlayerRegistry() {}
public static PlayerRegistry get() {
return instance;
}
private final ConcurrentHashMap<UUID, PlayerData> playerDataMap = new ConcurrentHashMap<>();
private final Collection<PlayerData> unmodifiablePlayerData = Collections.unmodifiableCollection(playerDataMap.values());
private volatile PlayerData[] playerDataArray = new PlayerData[0]; private static final VarHandle PLAYER_DATA_ARRAY = VarHandler.get(PlayerRegistry.class, "playerDataArray", PlayerData[].class);
/** Forcefully registers a player and returns the new PlayerData, even if they were already registered.**/
public synchronized PlayerData registerAndGetPlayer(UUID playerUUID, int joinTick, int selfEntityID, SelfEntityCreator selfEntityCreator) {
PlayerData newData = new PlayerData(playerUUID, false, joinTick, selfEntityID, selfEntityCreator);
PlayerData old = playerDataMap.put(playerUUID, newData);
if (old != null) old.markDisconnected();
updatePlayerDataArray();
return newData;
}
public synchronized void unregisterPlayer(UUID playerUUID) {
PlayerData unregisteredPlayer = playerDataMap.remove(playerUUID);
if (unregisteredPlayer == null) {
return;
}
unregisteredPlayer.markDisconnected();
updatePlayerDataArray();
}
public PlayerData getPlayerData(UUID playerUUID) {
return playerDataMap.get(playerUUID);
}
public boolean isPlayerRegistered(UUID playerUUID) {
return playerDataMap.containsKey(playerUUID);
}
/**
* @return Live, unmodifiable view of all PlayerData instances.
* **/
public Collection<PlayerData> getAllPlayerData() {
return unmodifiablePlayerData;
}
private void updatePlayerDataArray() {
PLAYER_DATA_ARRAY.setRelease(this, playerDataMap.values().toArray(PlayerData[]::new));
}
/**
* Do not mutate this array, all changes must go through {@link #registerAndGetPlayer(UUID, int, int, SelfEntityCreator)} /
* {@link #unregisterPlayer(UUID)}.
* <p></p>
* Changes to this array will be lost on next player join/leave, and will not apply everywhere.
*/
public PlayerData[] getPlayerDataArray() {
return (PlayerData[]) PLAYER_DATA_ARRAY.getAcquire(this);
}
public void forEachPlayer(Consumer<PlayerData> consumer) {
PlayerData[] data = getPlayerDataArray();
for (PlayerData player : data) {
consumer.accept(player);
}
}
public int getPlayerCount() {
return playerDataMap.size();
}
}
@@ -0,0 +1,27 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.raycast;
import games.cubi.locatables.api.Locatable;
import games.cubi.locatables.api.Spatial;
import java.util.UUID;
public interface ParticleSpawner {
enum Colour {
RED, GREEN, BLUE,
}
void spawnParticleAt(Locatable locatable, Colour colour);
void spawnParticleAt(UUID world, Spatial spatial, Colour colour);
void spawnParticleAt(UUID world, double x, double y, double z, Colour colour);
}
@@ -0,0 +1,175 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.raycast;
import games.cubi.locatables.api.Locatable;
import games.cubi.locatables.api.Spatial;
import games.cubi.locatables.api.BlockSpatial;
import games.cubi.raycastedantiesp.core.chunks.ChunkOcclusionView;
import games.cubi.raycastedantiesp.core.view.BlockView;
import java.util.UUID;
public class RaycastUtil {
//True: Has line-of-sight
//This is deliberately a ray-stepping algorithm rather than DDA as it is much faster (2x in benchmarking)
//Missing blocks is acceptable, as it will be assumed the player can see past those corners.
//While this uses objects, JHM and in-game profiling have both shown that all objects used here are consistently scalarised by the JVM.
/**
* Mutable position and chunk-section state is flattened into the advancer so C2 only
* needs to scalarise one state holder while retaining a readable ray-stepping method.
*/
public static boolean raycastUnrolledAccumulated(int maxOccluding, final int alwaysShowRadiusSquared, final int maxRaycastRadiusSquared, boolean debug,
float yOffsetEnd, final BlockView snap, final Locatable start, final Spatial end, ParticleSpawner spawner) {
double startX = start.x();
double startY = start.y();
double startZ = start.z();
double endOffset = end instanceof BlockSpatial ? 0.5 : 0.0;
RayDirection direction = RayDirection.from(end.x() + endOffset, end.y() + endOffset + yOffsetEnd, end.z() + endOffset, startX, startY, startZ);
double lengthSquared = direction.getLengthSquared();
if (lengthSquared <= alwaysShowRadiusSquared) return true;
if (lengthSquared > maxRaycastRadiusSquared) return false;
double total = direction.normaliseAndGetLength(lengthSquared);
float finalDist = (float) (total - 1);
final RayAdvancer rayAdvancer = debug ? new DebugRayAdvancer(startX, startY, startZ, direction, snap, start.world(), spawner) : new RayAdvancer(startX, startY, startZ, direction, snap);
int remainingSteps = (int) Math.floor(finalDist);
while (remainingSteps >= 4) {
rayAdvancer.advance();
rayAdvancer.advance();
rayAdvancer.advance();
rayAdvancer.advance();
if (rayAdvancer.occluded > maxOccluding) return false;
remainingSteps -= 4;
}
while (remainingSteps-- > 0) rayAdvancer.advance();
return rayAdvancer.occluded <= maxOccluding;
}
private static sealed class RayAdvancer extends RayPosition permits DebugRayAdvancer {
private final RayDirection direction;
private final BlockView blockView;
private int chunkX, chunkY, chunkZ;
private ChunkOcclusionView currentOcclusionView;
private int occluded = 0;
private RayAdvancer(double startX, double startY, double startZ, RayDirection direction, BlockView blockView) {
super(startX, startY, startZ);
this.direction = direction;
chunkX = blockX() >> 4;
chunkY = blockY() >> 4;
chunkZ = blockZ() >> 4;
currentOcclusionView = blockView.getChunkOcclusionView(chunkX, chunkY, chunkZ);
this.blockView = blockView;
}
private void advance() {
add(direction);
int blockX = blockX();
int blockY = blockY();
int blockZ = blockZ();
if (!isCurrentChunk(blockX, blockY, blockZ)) {
moveToChunk(blockX, blockY, blockZ);
currentOcclusionView = blockView.getChunkOcclusionView(chunkX, chunkY, chunkZ);
}
if (currentOcclusionView != null && currentOcclusionView.isOccludingGlobal(blockX, blockY, blockZ)) {
occluded++;
particleRed();
} else particleGreen();
}
private boolean isCurrentChunk(int blockX, int blockY, int blockZ) {
return blockX >> 4 == chunkX && blockY >> 4 == chunkY && blockZ >> 4 == chunkZ;
// ((nextChunkX ^ chunkX) | (nextChunkY ^ chunkY) | (nextChunkZ ^ chunkZ)) != 0 is slower than this
}
private void moveToChunk(int blockX, int blockY, int blockZ) {
chunkX = blockX >> 4;
chunkY = blockY >> 4;
chunkZ = blockZ >> 4;
}
void particleGreen() {}
void particleRed() {}
}
private static final class DebugRayAdvancer extends RayAdvancer {
private final UUID world;
private final ParticleSpawner particleSpawner;
private DebugRayAdvancer(double startX, double startY, double startZ, RayDirection direction, BlockView blockView, UUID world, ParticleSpawner particleSpawner) {
super(startX, startY, startZ, direction, blockView);
this.world = world;
this.particleSpawner = particleSpawner;
}
void particleGreen() {
particleSpawner.spawnParticleAt(world, x, y, z, ParticleSpawner.Colour.GREEN);
}
void particleRed() {
particleSpawner.spawnParticleAt(world, x, y, z, ParticleSpawner.Colour.RED);
}
}
private static sealed class RayPosition permits RayAdvancer {
double x, y, z;
private RayPosition(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
final void add(RayDirection direction) {
x += direction.x;
y += direction.y;
z += direction.z;
}
final int blockX() {
return (int) Math.floor(x);
}
final int blockY() {
return (int) Math.floor(y);
}
final int blockZ() {
return (int) Math.floor(z);
}
}
private static final class RayDirection {
private double x, y, z;
private RayDirection(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
private static RayDirection from(double endX, double endY, double endZ, double startX, double startY, double startZ) {
return new RayDirection(endX - startX, endY - startY, endZ - startZ);
}
private double getLengthSquared() {
return x * x + y * y + z * z;
}
private double normaliseAndGetLength(double lengthSquared) {
double len = Math.sqrt(lengthSquared);
double scale = 1 / len;
x *= scale;
y *= scale;
z *= scale;
return len;
}
}
}
@@ -0,0 +1,42 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.tracked;
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,84 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.tracked;
import games.cubi.logs.Logger;
import org.jetbrains.annotations.Nullable;
/**
* For runnable tasks which should be run immediately after an entity is spawned.
*/
public interface EntitySpawnTask extends Runnable {
int TICKS_BEFORE_EVICTION = 16;
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);
try {
current.run(); // perhaps the task is salvageable even if we missed the correct caller
} catch (Exception e) {
Logger.error("Error while running evicted future netty task " + current, e, 3, EntitySpawnTask.class);
}
current = next;
}
return current;
}
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,480 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.tracked;
import games.cubi.locatables.api.MutableFloatingSpatial;
import games.cubi.raycastedantiesp.core.players.PlayerData;
import games.cubi.utils.Clearable;
import games.cubi.utils.lists.PrimitiveIntArrayList;
import games.cubi.utils.lists.IntArrayListMarker;
import games.cubi.utils.VarHandler;
import org.jetbrains.annotations.Nullable;
import java.lang.invoke.VarHandle;
import java.util.UUID;
/**
* Designed for use with netty-based systems, where entity data updates only ever come from one thread, but reads may come from multiple threads. This is however not enforced, and must be kept in mind when using this class.
* A representation of an entity for a specific player.
*/
public abstract class NettyEntity<PacketReplayData extends Clearable> implements TrackedEntity<PacketReplayData> {
// immutable fields
private final int entityID; // Note that, while rare, entity ids will be negative once the entity id counter overflows.
private final UUID entityUUID;
private final boolean isSelfEntity;
private final int entityType;
private final PlayerData owningPlayer;
// Netty mutatable fields. Should NEVER be mutated from the engine thread, but reads are fine.
private volatile double x; private static final VarHandle X = VarHandler.get(NettyEntity.class, "x", double.class);
private volatile double y; private static final VarHandle Y = VarHandler.get(NettyEntity.class, "y", double.class);
private volatile double z; private static final VarHandle Z = VarHandler.get(NettyEntity.class, "z", double.class);
// Packet-derived state shared with the engine.
private static final byte FLAG_SNEAKING = 1;
private static final byte FLAG_GLOWING = 1 << 1;
private volatile byte trackedFlags; private static final VarHandle TRACKED_FLAGS = VarHandler.get(NettyEntity.class, "trackedFlags", byte.class);
// Packet-thread-only replay and client state.
private float yaw;
private float pitch;
private float headYaw;
private double velocityX;
private double velocityY;
private double velocityZ;
private boolean onGround = true;
private int@IntArrayListMarker[] leashedIDs;
// Netty-written attachment state shared with the engine thread.
private volatile int leasherID = NO_LEASHER; private static final VarHandle LEASHER_ID = VarHandler.get(NettyEntity.class, "leasherID", int.class);
private volatile int[] passengerIDs; private static final VarHandle PASSENGER_IDS = VarHandler.get(NettyEntity.class, "passengerIDs", int[].class);
private volatile int vehicleID = NO_VEHICLE; private static final VarHandle VEHICLE_ID = VarHandler.get(NettyEntity.class, "vehicleID", int.class);
private int entityData;
private PacketReplayData packetReplayData; // For use storing the packets we can't be bothered to directly store, with all cached packets being sent back out to the client when entity is visible again.
// Mutable by the engine and packet threads.
private volatile int lastChecked; private static final VarHandle LAST_CHECKED = VarHandler.get(NettyEntity.class, "lastChecked", int.class);
private boolean clientVisible = true;
// engine thread mutable, reads from netty and engine.
private volatile boolean visible;
// Constants
public static final int NEVER_CHECKED = Integer.MIN_VALUE;
public static final int NO_VEHICLE = -1;
public static final int NO_LEASHER = -2;
public static final int SELF_ENTITY_TYPE = -29;
public NettyEntity(PlayerData owningPlayer, double x, double y, double z, int entityID, UUID entityUUID, boolean isSelfEntity, int entityType, boolean visible) {
X.set(this, x); Y.set(this, y); Z.set(this, z);
this.entityID = entityID;
this.entityUUID = entityUUID;
this.isSelfEntity = isSelfEntity;
this.entityType = entityType;
this.visible = visible;
this.owningPlayer = owningPlayer;
}
// For creating the self entity, where we don't have access to its position. Always visible.
protected NettyEntity(PlayerData selfData, int selfPlayerID, UUID ownUUID) {
entityID = selfPlayerID;
entityUUID = ownUUID;
owningPlayer = selfData;
isSelfEntity = true;
entityType = SELF_ENTITY_TYPE;
visible = true;
}
@Override
public int entityID() {
return entityID;
}
@Override
public UUID entityUUID() {
return entityUUID;
}
@Override
public boolean visible() {
return visible;
}
/**
* Wherever possible, effort should be made to only call this from the engine thread, for thread safety reasons.
*/
@Override
public TrackedEntity<?> setVisible(boolean visible) {
this.visible = visible;
return this;
}
@Override
public boolean glowing() {
return (((byte) TRACKED_FLAGS.getOpaque(this)) & FLAG_GLOWING) != 0;
}
@Override
public boolean sneaking() {
return (((byte) TRACKED_FLAGS.getOpaque(this)) & FLAG_SNEAKING) != 0;
}
public boolean setGlowing(boolean glowing) {
return setTrackedFlag(FLAG_GLOWING, glowing);
}
public boolean setSneaking(boolean sneaking) {
return setTrackedFlag(FLAG_SNEAKING, sneaking);
}
private boolean setTrackedFlag(byte mask, boolean enabled) {
byte previous = enabled
? (byte) TRACKED_FLAGS.getAndBitwiseOrRelease(this, mask)
: (byte) TRACKED_FLAGS.getAndBitwiseAndRelease(this, (byte) ~mask);
boolean changed = (previous & mask) != (enabled ? mask : 0);
if (changed) {
// A concurrent engine check may overwrite this marker. Hidden entities retry next tick; visible entities
// may wait for their configured recheck or remain visible if rechecks are disabled.
// This is acceptable and not considered an issue.
LAST_CHECKED.setOpaque(this, NEVER_CHECKED);
}
return changed;
}
@Override
public int lastChecked() {
return (int) LAST_CHECKED.getOpaque(this);
}
@Override
public TrackedEntity<?> setLastChecked(int lastChecked) {
LAST_CHECKED.setOpaque(this, lastChecked);
return this;
}
@Override
public boolean clientVisible() {
return clientVisible;
}
@Override
public TrackedEntity<?> setClientVisible(boolean clientVisible) {
this.clientVisible = clientVisible;
return this;
}
@Override
public boolean isSelfEntity() {
return isSelfEntity;
}
@Override
public float yaw() {
return yaw;
}
/**
* THIS METHOD IS ONLY SAFE TO CALL FROM THE PLAYER's NETTY THREAD
*/
@Override
public TrackedEntity<?> setYaw(float yaw) {
this.yaw = yaw;
return this;
}
@Override
public float pitch() {
return pitch;
}
/**
* THIS METHOD IS ONLY SAFE TO CALL FROM THE PLAYER's NETTY THREAD
*/
@Override
public TrackedEntity<?> setPitch(float pitch) {
this.pitch = pitch;
return this;
}
@Override
public float headYaw() {
return headYaw;
}
/**
* THIS METHOD IS ONLY SAFE TO CALL FROM THE PLAYER's NETTY THREAD
*/
@Override
public TrackedEntity<?> setHeadYaw(float headYaw) {
this.headYaw = headYaw;
return this;
}
@Override
public double velocityX() {
return velocityX;
}
@Override
public double velocityY() {
return velocityY;
}
@Override
public double velocityZ() {
return velocityZ;
}
/**
* THIS METHOD IS ONLY SAFE TO CALL FROM THE PLAYER's NETTY THREAD
*/
@Override
public TrackedEntity<?> setVelocity(double velocityX, double velocityY, double velocityZ) {
this.velocityX = velocityX;
this.velocityY = velocityY;
this.velocityZ = velocityZ;
return this;
}
@Override
public boolean onGround() {
return onGround;
}
/**
* THIS METHOD IS ONLY SAFE TO CALL FROM THE PLAYER's NETTY THREAD
*/
@Override
public TrackedEntity<?> setOnGround(boolean onGround) {
this.onGround = onGround;
return this;
}
public int entityType() {
return entityType;
}
@Override
public int entityData() {
return entityData;
}
@Override
public TrackedEntity<?> setEntityData(int entityData) {
this.entityData = entityData;
return this;
}
/**
* @return a clone of the passenger ID array, which may be null
*/
@Override
public int[] passengerIDs() {
int[] current = passengerIDsAcquire();
return current == null ? null : current.clone();
}
/**
* Do not mutate this.
* <p></p>
* This method is not considered public api.
* <p>
* Returned array may be null
* </p>
*/
public int[] passengerIDsNoAlloc() {
return passengerIDsAcquire();
}
@Override
public TrackedEntity<?> setPassengerIDs(int[] passengerIDs) {
PASSENGER_IDS.setRelease(this, passengerIDs == null ? new int[0] : passengerIDs.clone());
return this;
}
@Override
public void setVehicleID(int vehicleID) {
VEHICLE_ID.setOpaque(this, vehicleID);
}
@Override
public int vehicleID() {
return (int) VEHICLE_ID.getOpaque(this);
}
@Override
public void addLeashedEntity(int leashedEntityID) {
if (PrimitiveIntArrayList.contains(leashedIDs, leashedEntityID)) {
return;
}
leashedIDs = PrimitiveIntArrayList.add(leashedIDs, leashedEntityID);
}
@Override
public void removeLeashedEntity(int leashedEntityID) {
leashedIDs = PrimitiveIntArrayList.remove(leashedIDs, leashedEntityID);
}
public int@Nullable[] leashedEntityIDsOrNull() {
return PrimitiveIntArrayList.getCopyOrNull(leashedIDs);
}
/**
* Returns internal Netty-thread leash state without copying it.
* Callers must not mutate the returned array.
* <p>
* This is not considered public API.
* </p>
*/
public int@Nullable[] leashedEntityIDsOrNullNoAlloc() {
return leashedIDs;
}
@Override
public int leashingEntity() {
return (int) LEASHER_ID.getOpaque(this);
}
@Override
public void setLeashingEntity(int leashingEntityID) {
LEASHER_ID.setOpaque(this, leashingEntityID);
}
@Override
public PacketReplayData packetReplayData() {
return packetReplayData;
}
@Override
public TrackedEntity<?> setPacketReplayData(PacketReplayData packetReplayData) {
this.packetReplayData = packetReplayData;
return this;
}
@Override
public float getYOffset() {
return 0.5f; //todo: move away from hardcoded offset
}
@Override
public double x() {
return (double) X.getOpaque(this);
}
@Override
public double y() {
return (double) Y.getOpaque(this);
}
@Override
public double z() {
return (double) Z.getOpaque(this);
}
@Override
public MutableFloatingSpatial setX(double x) {
X.setOpaque(this, x);
return this;
}
@Override
public MutableFloatingSpatial setY(double y) {
Y.setOpaque(this, y);
return this;
}
@Override
public MutableFloatingSpatial setZ(double z) {
Z.setOpaque(this, z);
return this;
}
@Override
public MutableFloatingSpatial setPosition(double x, double y, double z) {
X.setOpaque(this, x);
Y.setOpaque(this, y);
Z.setOpaque(this, z);
updatePassengerPositions();
return this;
}
@Override
public MutableFloatingSpatial add(double x, double y, double z) {
X.setOpaque(this, x() + x);
Y.setOpaque(this, y() + y);
Z.setOpaque(this, z() + z);
updatePassengerPositions();
return this;
}
// This does not correctly set the passenger position, as the passenger is above the vehicle. It is however close enough to minimise annoying interpolation on show.
private void updatePassengerPositions() {
int[] currentPassengerIDs = passengerIDsAcquire();
if (currentPassengerIDs == null || currentPassengerIDs.length == 0) return;
double currentX = x();
double currentY = y();
double currentZ = z();
for (int passengerID : currentPassengerIDs) {
NettyEntity<?> passenger = owningPlayer.entityFromID(passengerID);
if (passenger != null) {
passenger.setVehicleID(entityID);
passenger.setX(currentX);
passenger.setY(currentY);
passenger.setZ(currentZ);
passenger.updatePassengerPositions();
}
}
}
@Override
public void clear() {
if (packetReplayData != null) packetReplayData.clear();
packetReplayData = null;
TRACKED_FLAGS.setOpaque(this, (byte) 0);
VEHICLE_ID.setOpaque(this, NO_VEHICLE);
PASSENGER_IDS.setRelease(this, null);
leashedIDs = null;
LEASHER_ID.setOpaque(this, NO_LEASHER);
}
@Override
public String toString() {
return "NettyEntity{" +
"entityID=" + entityID +
", entityUUID=" + entityUUID +
", isSelfEntity=" + isSelfEntity +
", entityType=" + entityType +
", x=" + x() +
", y=" + y() +
", z=" + z() +
", yaw=" + yaw() +
", pitch=" + pitch() +
", headYaw=" + headYaw() +
", velocityX=" + velocityX() +
", velocityY=" + velocityY() +
", velocityZ=" + velocityZ() +
", onGround=" + onGround() +
", leashedIDs=" + PrimitiveIntArrayList.toString(leashedIDs) +
", leasherID=" + leashingEntity() +
", passengerIDs=" + PrimitiveIntArrayList.toString(passengerIDsAcquire()) +
", vehicleID=" + vehicleID() +
", entityData=" + entityData() +
'}';
}
private int[] passengerIDsAcquire() {
return (int[]) PASSENGER_IDS.getAcquire(this);
}
}
@@ -0,0 +1,155 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.tracked;
import games.cubi.locatables.api.BlockSpatial;
import games.cubi.utils.Clearable;
import games.cubi.utils.lists.InvasivelyLinkedSWMRList;
import games.cubi.utils.VarHandler;
import java.lang.invoke.VarHandle;
/** Tile desired visibility and lifecycle are shared with the engine; client, block, and replay data are packet-thread-only. */
public abstract class NettyTileEntity<PacketReplayData extends Clearable> extends InvasivelyLinkedSWMRList<NettyTileEntity<PacketReplayData>> implements TrackedTileEntity<PacketReplayData> {
private volatile boolean visible;
private boolean clientVisible;
private volatile int lastChecked; private static final VarHandle LAST_CHECKED = VarHandler.get(NettyTileEntity.class, "lastChecked", int.class);
private char blockID;
private PacketReplayData extraData;
private static final int REMOVED = Integer.MIN_VALUE + 11;
private final int x, y, z;
public NettyTileEntity(BlockSpatial position, boolean visible, int lastChecked, char blockID) {
x = position.blockX();
y = position.blockY();
z = position.blockZ();
this.blockID = blockID;
this.visible = visible;
this.clientVisible = visible;
LAST_CHECKED.set(this, lastChecked);
}
public NettyTileEntity(int x, int y, int z, boolean visible, char blockID) {
this.x = x;
this.y = y;
this.z = z;
this.visible = visible;
this.clientVisible = visible;
this.blockID = blockID;
LAST_CHECKED.set(this, NEVER_CHECKED);
}
@Override
public boolean visible() {
return visible;
}
@Override
public TrackedTileEntity<PacketReplayData> setVisible(boolean visible) {
this.visible = visible;
return this;
}
@Override
public boolean clientVisible() {
return clientVisible;
}
@Override
public TrackedTileEntity<PacketReplayData> setClientVisible(boolean clientVisible) {
this.clientVisible = clientVisible;
return this;
}
@Override
public int lastChecked() {
return (int) LAST_CHECKED.getAcquire(this);
}
@Override
public TrackedTileEntity<PacketReplayData> setLastChecked(int checkedTick) {
int current = (int) LAST_CHECKED.getAcquire(this);
while (current != REMOVED) {
if (LAST_CHECKED.weakCompareAndSetRelease(this, current, checkedTick)) {
break;
}
current = (int) LAST_CHECKED.getAcquire(this);
}
return this;
}
/** Marks this allocation as detached. This state is absorbing because removed nodes are never reused. */
public final void markRemoved() {
LAST_CHECKED.setRelease(this, REMOVED);
}
/** Consumer-side lifecycle check performed immediately before emitting a queued transition. */
public final boolean isRemoved() {
return (int) LAST_CHECKED.getAcquire(this) == REMOVED;
}
@Override
public int blockID() {
return blockID;
}
@Override
public TrackedTileEntity<PacketReplayData> setBlockID(char blockID) {
this.blockID = blockID;
return this;
}
@Override
public PacketReplayData extraData() {
return extraData;
}
@Override
public TrackedTileEntity<PacketReplayData> setExtraData(PacketReplayData extraData) {
this.extraData = extraData;
return this;
}
@Override
public void clearExtraData() {
if (extraData != null) {
//extraData.clear(); probs not needed
extraData = null;
}
}
@Override
public int blockX() {
return x;
}
@Override
public int blockY() {
return y;
}
@Override
public int blockZ() {
return z;
}
@Override
public void clear() {
if (extraData != null) {
extraData.clear();
}
}
@Override
public String toString() {
return toStringForm();
}
}
@@ -0,0 +1,94 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.tracked;
import games.cubi.locatables.api.MutableFloatingSpatial;
import org.jetbrains.annotations.Nullable;
import java.util.UUID;
/**
* Per-player platform-independent representation of an entity
*/
public interface TrackedEntity<PacketReplayData> extends MutableFloatingSpatial {
int entityID();
UUID entityUUID();
boolean visible();
TrackedEntity<?> setVisible(boolean visible);
boolean glowing();
boolean sneaking();
int lastChecked();
TrackedEntity<?> setLastChecked(int lastChecked);
/** Packet-thread-only client state. */
boolean clientVisible();
TrackedEntity<?> setClientVisible(boolean clientVisible);
boolean isSelfEntity();
/** Packet-thread-only replay state. */
float yaw();
TrackedEntity<?> setYaw(float yaw);
/** Packet-thread-only replay state. */
float pitch();
TrackedEntity<?> setPitch(float pitch);
/** Packet-thread-only replay state. */
float headYaw();
TrackedEntity<?> setHeadYaw(float headYaw);
/** Packet-thread-only replay state. */
double velocityX();
double velocityY();
double velocityZ();
TrackedEntity<?> setVelocity(double velocityX, double velocityY, double velocityZ);
/** Packet-thread-only replay state. */
boolean onGround();
TrackedEntity<?> setOnGround(boolean onGround);
/** Packet-thread-only replay state. */
int entityData();
TrackedEntity<?> setEntityData(int entityData);
int[] passengerIDs();
TrackedEntity<?> setPassengerIDs(int[] passengerIDs);
void setVehicleID(int vehicleID);
int vehicleID();
/** Packet-thread-only holder-side relationship state. */
void addLeashedEntity(int leashedEntityID);
void removeLeashedEntity(int leashedEntityID);
int@Nullable[] leashedEntityIDsOrNull();
int leashingEntity();
void setLeashingEntity(int leashingEntityID);
/** Packet-thread-only cached packet state. */
PacketReplayData packetReplayData();
TrackedEntity<?> setPacketReplayData(PacketReplayData packetReplayData);
float getYOffset();
/**
* For use when the player disconnects, clears all data.
*/
void clear();
default <T> T cast() {
return (T) this;
}
}
@@ -0,0 +1,35 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.tracked;
import games.cubi.locatables.api.ImmutableBlockSpatial;
import games.cubi.utils.Clearable;
public interface TrackedTileEntity<T> extends ImmutableBlockSpatial, Clearable {
int NEVER_CHECKED = Integer.MIN_VALUE;
boolean visible();
TrackedTileEntity<T> setVisible(boolean visible);
/** Packet-thread-only client state. */
boolean clientVisible();
TrackedTileEntity<T> setClientVisible(boolean clientVisible);
int lastChecked();
TrackedTileEntity<T> setLastChecked(int lastChecked);
/** Packet-thread-only structural state. */
int blockID();
TrackedTileEntity<T> setBlockID(char blockID);
/** Packet-thread-only replay state. */
T extraData();
TrackedTileEntity<T> setExtraData(T extraData);
void clearExtraData();
}
@@ -0,0 +1,111 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.utils;
import games.cubi.logs.Logger;
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));
}
public record Version(short major, short minor, short patch, boolean snapshot) implements Comparable<Version> {
public Version(int major, int minor, int patch, boolean snapshot) {
this((short) major, (short) minor, (short) patch, snapshot);
}
public static Version parse(String versionString) {
String[] parts = versionString.replaceFirst("[+-].*$", "").split("\\.");
if (parts.length != 3) {
throw new IllegalArgumentException("Version string must be in the format 'major.minor.patch'. Attempted: " + versionString);
}
try {
short major = Short.parseShort(parts[0]);
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) {
throw new IllegalArgumentException("Version parts must be valid short integers. Attempted: " + versionString, e);
}
}
@Override
public int compareTo(Version other) {
int majorDifference = Short.compare(major, other.major);
if (majorDifference != 0) return majorDifference;
int minorDifference = Short.compare(minor, other.minor);
if (minorDifference != 0) return minorDifference;
return Short.compare(patch, other.patch);
}
}
}
@@ -0,0 +1,326 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.utils;
import it.unimi.dsi.fastutil.Hash;
import it.unimi.dsi.fastutil.longs.Long2ObjectMap;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.longs.LongObjectBiConsumer;
import it.unimi.dsi.fastutil.objects.ObjectIterator;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.StampedLock;
import java.util.function.LongFunction;
import java.util.function.LongPredicate;
/**
* A small thread-safe utility map for primitive {@code long} keys backed by a {@link StampedLock} and a {@link Long2ObjectOpenHashMap}.
*
* <p>Reads use optimistic locking where possible. Mutations use the write lock. Tests indicate that
* even under heavy read-write contention, optimistic reading works almost all the time.
*
* <p>Callback-based methods such as {@link #computeIfAbsent(long, LongFunction)}, {@link #forEach(LongObjectBiConsumer)},
* and {@link #removeIfKey(LongPredicate)} run their callbacks while holding the write lock, so those
* callbacks must not call back into this same map instance or deadlock may occur as StampedLock is not reentrant.
*
* <p>This class only synchronizes access to the map structure itself. Stored values are returned by
* reference and are not made thread-safe by this map.
*
* @param <V> the type of mapped values
*/
public class Long2ObjectMTHashMap<V> {
private final Long2ObjectOpenHashMap<V> backingMap;
private final StampedLock lock = new StampedLock();
private final ThreadLocal<Integer> writeLockedCallbackDepth = ThreadLocal.withInitial(() -> 0);
public Long2ObjectMTHashMap(final int expected, final float loadFactor) {
this.backingMap = new Long2ObjectOpenHashMap<>(expected, loadFactor);
}
public Long2ObjectMTHashMap(final int expected) {
this(expected, Hash.DEFAULT_LOAD_FACTOR);
}
public Long2ObjectMTHashMap() {
this(Hash.DEFAULT_INITIAL_SIZE, Hash.DEFAULT_LOAD_FACTOR);
}
public V get(final long key) {
long stamp = lock.tryOptimisticRead();
V value = backingMap.get(key);
if (failsValidation(stamp)) {
assertNoWriteLockedCallbackReentry();
stamp = lock.readLock();
try {
value = backingMap.get(key);
} finally {
lock.unlockRead(stamp);
}
}
return value;
}
public V getOrDefault(final long key, final V defaultValue) {
long stamp = lock.tryOptimisticRead();
V value = getOrDefaultInternal(key, defaultValue);
if (failsValidation(stamp)) {
assertNoWriteLockedCallbackReentry();
stamp = lock.readLock();
try {
value = getOrDefaultInternal(key, defaultValue);
} finally {
lock.unlockRead(stamp);
}
}
return value;
}
public boolean containsKey(final long key) {
long stamp = lock.tryOptimisticRead();
boolean contains = backingMap.containsKey(key);
if (failsValidation(stamp)) {
assertNoWriteLockedCallbackReentry();
stamp = lock.readLock();
try {
contains = backingMap.containsKey(key);
} finally {
lock.unlockRead(stamp);
}
}
return contains;
}
public int size() {
long stamp = lock.tryOptimisticRead();
int size = backingMap.size();
if (failsValidation(stamp)) {
assertNoWriteLockedCallbackReentry();
stamp = lock.readLock();
try {
size = backingMap.size();
} finally {
lock.unlockRead(stamp);
}
}
return size;
}
public boolean isEmpty() {
long stamp = lock.tryOptimisticRead();
boolean empty = backingMap.isEmpty();
if (failsValidation(stamp)) {
assertNoWriteLockedCallbackReentry();
stamp = lock.readLock();
try {
empty = backingMap.isEmpty();
} finally {
lock.unlockRead(stamp);
}
}
return empty;
}
public V put(final long key, final V value) {
assertNoWriteLockedCallbackReentry();
long stamp = lock.writeLock();
try {
return backingMap.put(key, value);
} finally {
lock.unlockWrite(stamp);
}
}
public V putIfAbsent(final long key, final V value) {
assertNoWriteLockedCallbackReentry();
long stamp = lock.writeLock();
try {
if (backingMap.containsKey(key)) {
return backingMap.get(key);
}
backingMap.put(key, value);
return null;
} finally {
lock.unlockWrite(stamp);
}
}
public V replace(final long key, final V value) {
assertNoWriteLockedCallbackReentry();
long stamp = lock.writeLock();
try {
if (!backingMap.containsKey(key)) {
return null;
}
return backingMap.put(key, value);
} finally {
lock.unlockWrite(stamp);
}
}
public boolean replace(final long key, final V oldValue, final V value) {
assertNoWriteLockedCallbackReentry();
long stamp = lock.writeLock();
try {
if (!backingMap.containsKey(key) || !Objects.equals(backingMap.get(key), oldValue)) {
return false;
}
backingMap.put(key, value);
return true;
} finally {
lock.unlockWrite(stamp);
}
}
public V remove(final long key) {
assertNoWriteLockedCallbackReentry();
long stamp = lock.writeLock();
try {
return backingMap.remove(key);
} finally {
lock.unlockWrite(stamp);
}
}
public boolean remove(final long key, final Object value) {
assertNoWriteLockedCallbackReentry();
long stamp = lock.writeLock();
try {
if (!backingMap.containsKey(key) || !Objects.equals(backingMap.get(key), value)) {
return false;
}
backingMap.remove(key);
return true;
} finally {
lock.unlockWrite(stamp);
}
}
public void clear() {
assertNoWriteLockedCallbackReentry();
long stamp = lock.writeLock();
try {
backingMap.clear();
} finally {
lock.unlockWrite(stamp);
}
}
public V computeIfAbsent(final long key, final LongFunction<? extends V> mappingFunction) {
assertNoWriteLockedCallbackReentry();
Objects.requireNonNull(mappingFunction, "mappingFunction");
long stamp = lock.writeLock();
try {
if (backingMap.containsKey(key)) {
return backingMap.get(key);
}
V value = invokeWriteLockedCallback(() -> mappingFunction.apply(key));
backingMap.put(key, value);
return value;
} finally {
lock.unlockWrite(stamp);
}
}
public void forEach(final LongObjectBiConsumer<? super V> consumer) {
assertNoWriteLockedCallbackReentry();
Objects.requireNonNull(consumer, "consumer");
long stamp = lock.writeLock();
try {
ObjectIterator<Long2ObjectMap.Entry<V>> iterator = backingMap.long2ObjectEntrySet().fastIterator();
while (iterator.hasNext()) {
Long2ObjectMap.Entry<V> entry = iterator.next();
invokeWriteLockedCallback(() -> {
consumer.accept(entry.getLongKey(), entry.getValue());
return null;
});
}
} finally {
lock.unlockWrite(stamp);
}
}
public int removeIfKey(final LongPredicate predicate) {
assertNoWriteLockedCallbackReentry();
Objects.requireNonNull(predicate, "predicate");
long stamp = lock.writeLock();
try {
int removed = 0;
ObjectIterator<Long2ObjectMap.Entry<V>> iterator = backingMap.long2ObjectEntrySet().fastIterator();
while (iterator.hasNext()) {
Long2ObjectMap.Entry<V> entry = iterator.next();
if (invokeWriteLockedCallback(() -> predicate.test(entry.getLongKey()))) {
iterator.remove();
removed++;
}
}
return removed;
} finally {
lock.unlockWrite(stamp);
}
}
private V getOrDefaultInternal(final long key, final V defaultValue) {
V value = backingMap.get(key);
return value != null || backingMap.containsKey(key) ? value : defaultValue;
}
private void assertNoWriteLockedCallbackReentry() {
if (writeLockedCallbackDepth.get() > 0) {
throw new IllegalStateException(
"Callbacks executed under the write lock must not reenter this Long2ObjectMTHashMap instance."
);
}
}
private <T> T invokeWriteLockedCallback(final Long2ObjectMTHashMapCallback<T> callback) {
writeLockedCallbackDepth.set(writeLockedCallbackDepth.get() + 1);
try {
return callback.invoke();
} finally {
int depth = writeLockedCallbackDepth.get() - 1;
if (depth == 0) {
writeLockedCallbackDepth.remove();
} else {
writeLockedCallbackDepth.set(depth);
}
}
}
final AtomicInteger successfulOptimisticReads = new AtomicInteger();
final AtomicInteger failedOptimisticReads = new AtomicInteger();
private boolean failsValidation(long stamp) {
boolean valid = lock.validate(stamp);
if (!valid) {
failedOptimisticReads.incrementAndGet();
} else {
successfulOptimisticReads.incrementAndGet();
}
return !valid;
//return !lock.validate(stamp);
}
@FunctionalInterface
private interface Long2ObjectMTHashMapCallback<T> {
T invoke();
}
}
@@ -0,0 +1,48 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.utils;
import java.lang.annotation.Documented;
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,27 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.utils;
/**
* Classes where specific methods must be called from a single thread can extend this class and call {@link #guardThread()}
* at the start of those methods to ensure that they are only called from the permitted thread.
*/
public abstract class SingleThreadedGuard {
private final Thread permittedThread;
protected SingleThreadedGuard(Thread thread) {
permittedThread = thread;
}
protected void guardThread() {
if (Thread.currentThread() != permittedThread) {
throw new IllegalStateException("Method called from wrong thread. Expected: " + permittedThread + ", actual: " + Thread.currentThread());
}
}
}
@@ -0,0 +1,27 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.utils;
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,467 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.view;
import ca.spottedleaf.concurrentutil.map.SWMRInt2ObjectHashTable;
import games.cubi.locatables.api.BlockLocatable;
import games.cubi.locatables.api.BlockSpatial;
import games.cubi.logs.Logger;
import games.cubi.raycastedantiesp.core.chunks.BlockInfoResolver;
import games.cubi.raycastedantiesp.core.chunks.BlockChunkData;
import games.cubi.raycastedantiesp.core.chunks.ChunkOcclusionView;
import games.cubi.raycastedantiesp.core.chunks.OccludingChunkData;
import games.cubi.raycastedantiesp.core.tracked.TrackedTileEntity;
import games.cubi.raycastedantiesp.core.tracked.NettyTileEntity;
import games.cubi.raycastedantiesp.core.players.PlayerData;
import games.cubi.utils.Clearable;
import games.cubi.utils.lists.InvasivelyLinkedSWMRList;
import games.cubi.utils.VarHandler;
import games.cubi.raycastedantiesp.core.view.chunks.BlockChunkSectionStore;
import games.cubi.raycastedantiesp.core.view.chunks.ChunkSectionStore;
import games.cubi.raycastedantiesp.core.view.chunks.OccludingChunkSectionStore;
import java.lang.invoke.VarHandle;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.function.IntSupplier;
import static games.cubi.raycastedantiesp.core.chunks.ChunkData.packUncheckedGuarded;
public abstract class AbstractBlockView<R extends Clearable, T extends NettyTileEntity<R>> implements BlockView {
private final ChunkSectionStore chunks;
private final boolean trackAllBlocks;
/**
* The int key represents a packed chunk column bucket, with (signed) 16 bits allocated for x and z respectively. While chunk columns over 60k chunks apart may overlap, this is unlikely to ever actually occur.
* <p> {@code NettyTileEntity<R>} is an {@link InvasivelyLinkedSWMRList}, so all tile entities in the column chain from the head entry.
* <p> Since direct access to this object outside {@link AbstractBlockView} is impossible, a marker head object is skipped, and head removal is handled separately.
* **/
private final SWMRInt2ObjectHashTable<NettyTileEntity<R>> knownTileEntitiesByColumnBucket = new SWMRInt2ObjectHashTable<>();
private final PackedBlockTransitionQueue transitions = new PackedBlockTransitionQueue();
private final IntSupplier worldEpochSupplier;
private volatile UUID trackedWorld;
// Bit 0 is enabled; higher bits are a generation. The generation prevents enabled -> disabled -> enabled ABA from
// accepting an old raycast and also tags transitions that may be drained after their originating mode was replaced.
private volatile long tileEntityCheckModeToken; private static final VarHandle TILE_ENTITY_CHECK_MODE_TOKEN = VarHandler.get(AbstractBlockView.class, "tileEntityCheckModeToken", long.class);
protected AbstractBlockView(BlockInfoResolver blockInfoResolver, boolean trackAllBlocks, IntSupplier worldEpochSupplier) {
Logger.requireNonNull(blockInfoResolver, "blockInfoResolver was null", 1, AbstractBlockView.class);
Logger.requireNonNull(worldEpochSupplier, "worldEpochSupplier was null", 1, AbstractBlockView.class);
this.trackAllBlocks = trackAllBlocks;
this.worldEpochSupplier = worldEpochSupplier;
this.chunks = trackAllBlocks
? new BlockChunkSectionStore(blockInfoResolver)
: new OccludingChunkSectionStore(blockInfoResolver);
}
protected abstract T createTrackedTileEntity(BlockSpatial position, char blockID, boolean visible);
@Override
public ChunkOcclusionView getChunkOcclusionView(int chunkX, int chunkY, int chunkZ) {
return chunks.getSection(chunkX, chunkY, chunkZ);
}
@Override
public boolean isBlockOccluding(int x, int y, int z) {
return chunks.isOccluding(x, y, z);
}
@Override
public boolean isBlockOccluding(BlockLocatable location) {
if (location == null || !isTrackedWorld(location.world())) {
return false;
}
return isBlockOccluding(location.blockX(), location.blockY(), location.blockZ());
}
public int loadedChunkCount() {
return chunks.loadedSectionCount();
}
@Override
public T updateOrInsertTileEntity(UUID world, BlockSpatial position, char blockID, boolean visibleIfNew) {
if (position == null || !ensureTrackedWorld(world)) {
return null;
}
SWMRInt2ObjectHashTable<NettyTileEntity<R>> map = knownTileEntitiesByColumnBucket;
int bucketKey = packColumnBucket(position.chunkX(), position.chunkZ());
NettyTileEntity<R> head = map.get(bucketKey);
T tileEntity = findTileEntityInBucket(head, position);
if (tileEntity == null) {
tileEntity = createTrackedTileEntity(position, blockID, visibleIfNew);
if (tileEntity == null) {
Logger.error("createTrackedTileEntity returned null", 3, AbstractBlockView.class);
return null;
}
if (head == null) {
map.put(bucketKey, tileEntity);
} else {
head.linkAfter(tileEntity);
}
}
tileEntity.clearExtraData();
tileEntity.setBlockID(blockID);
return tileEntity;
}
@Override
public void removeTileEntity(UUID world, BlockSpatial position) {
if (position == null || !isTrackedWorld(world)) {
return;
}
SWMRInt2ObjectHashTable<NettyTileEntity<R>> map = knownTileEntitiesByColumnBucket;
int bucketKey = packColumnBucket(position.chunkX(), position.chunkZ());
NettyTileEntity<R> head = map.get(bucketKey);
T tileEntity = findTileEntityInBucket(head, position);
if (tileEntity != null) {
removeNode(map, bucketKey, head, tileEntity);
}
}
@Override
public T getTrackedTileEntity(UUID world, BlockSpatial position) {
if (position == null || !isTrackedWorld(world)) {
return null;
}
return findTileEntityInBucket(knownTileEntitiesByColumnBucket.get(packColumnBucket(position.chunkX(), position.chunkZ())), position);
}
@Override
public boolean isVisible(UUID world, BlockSpatial position, int currentTick) {
if (position == null || !isTrackedWorld(world)) {
return true;
}
T state = getTrackedTileEntity(world, position);
return state == null || state.visible();
}
private void commitTileEntityVisibilityDecision(T tileEntity, boolean currentVisibility, boolean shouldBeVisible, int currentTick, long modeToken, int expectedWorldEpoch) {
if (!isCurrentWorldEpoch(expectedWorldEpoch) || tileEntityCheckModeTokenAcquire() != modeToken) {
return;
}
if (!modeEnabled(modeToken)) {
shouldBeVisible = true;
}
boolean visibilityChanged = currentVisibility != shouldBeVisible;
tileEntity.setVisible(shouldBeVisible);
tileEntity.setLastChecked(currentTick);
if (visibilityChanged) {
TransitionType.Tile type = shouldBeVisible ? TransitionType.Tile.SHOW : TransitionType.Tile.HIDE;
transitions.add(type, tileEntity, modeToken, expectedWorldEpoch);
}
}
@Override
// Only used on non-mutation paths
public void recordOutboundTileEntityVisibility(TrackedTileEntity<?> tileEntity, boolean visible) {
if (tileEntity != null) {
tileEntity.setVisible(visible);
tileEntity.setClientVisible(visible);
tileEntity.setLastChecked(TrackedTileEntity.NEVER_CHECKED);
}
}
@Override
public void applyTileEntityCheckMode(boolean enabled, int currentTick, Consumer<TrackedTileEntity<?>> visibilityRepairConsumer) {
long current = tileEntityCheckModeTokenAcquire();
if (modeEnabled(current) == enabled) {
return;
}
// Drop the enabled bit, increment the generation, then restore bit 0 below only for enabled mode.
long next = ((current >>> 1) + 1L) << 1;
if (enabled) {
forEachTileEntity(tileEntity -> tileEntity.setLastChecked(TrackedTileEntity.NEVER_CHECKED));
TILE_ENTITY_CHECK_MODE_TOKEN.setRelease(this, next | 1L);
return;
}
TILE_ENTITY_CHECK_MODE_TOKEN.setRelease(this, next);
forEachTileEntity(tileEntity -> {
if (!tileEntity.visible()) {
tileEntity.setVisible(true);
tileEntity.setLastChecked(currentTick);
}
if (!tileEntity.clientVisible()) {
visibilityRepairConsumer.accept(tileEntity);
}
});
}
@Override
public long tileEntityCheckModeToken() {
return tileEntityCheckModeTokenAcquire();
}
@Override
public boolean isCurrentEnabledTileEntityMode(long modeToken) {
return modeEnabled(modeToken) && tileEntityCheckModeTokenAcquire() == modeToken;
}
@Override
public Collection<TrackedTileEntity<?>> getKnownTileEntities() {
ArrayList<TrackedTileEntity<?>> snapshot = new ArrayList<>();
forEachTileEntity(snapshot::add);
return List.copyOf(snapshot);
}
@Override
public int forEachNeedingRecheck(int recheckTicks, int currentTick, Consumer<TrackedTileEntity<?>> action) {
return knownTileEntitiesByColumnBucket.forEachValueSummed(head -> {
int processed = 0;
for (NettyTileEntity<R> tileEntity = head; tileEntity != null; tileEntity = tileEntity.nextAcquire()) {
int lastChecked = tileEntity.lastChecked();
if (tileEntity.visible() && lastChecked != TrackedTileEntity.NEVER_CHECKED && (recheckTicks < 0 || currentTick - lastChecked < recheckTicks)) {
continue;
}
action.accept(tileEntity);
processed++;
}
return processed;
});
}
@Override
public int updateVisibilityForEachNeedingRecheck(int recheckTicks, int currentTick, long modeToken, int expectedWorldEpoch, VisibilityResolver action) {
if (!isCurrentEnabledTileEntityMode(modeToken) || !isCurrentWorldEpoch(expectedWorldEpoch)) {
return 0;
}
return knownTileEntitiesByColumnBucket.forEachValueSummed(head -> {
int processed = 0;
for (NettyTileEntity<R> tileEntity = head; tileEntity != null; tileEntity = tileEntity.nextAcquire()) {
boolean currentVisibility = tileEntity.visible();
int lastChecked = tileEntity.lastChecked();
if (currentVisibility && lastChecked != TrackedTileEntity.NEVER_CHECKED && (recheckTicks < 0 || currentTick - lastChecked < recheckTicks)) {
continue;
}
byte shouldBeVisible = action.setVisible(tileEntity);
if (shouldBeVisible != VisibilityResolver.SKIPPED) {
@SuppressWarnings("unchecked") T typed = (T) tileEntity;
commitTileEntityVisibilityDecision(typed, currentVisibility, shouldBeVisible == VisibilityResolver.SHOW, currentTick, modeToken, expectedWorldEpoch);
}
processed++;
}
return processed;
});
}
@Override
public boolean hasPendingTransitions() {
return transitions.hasPendingTransitions();
}
@Override
public void flushPendingTransitions() {
transitions.flushPendingTransitions();
}
@Override
public void drainTransitions(BlockView.TransitionConsumer consumer) {
transitions.drainTransitions(consumer);
}
@Override
public void upsertBlock(UUID world, int x, int y, int z, int blockID) {
if (!ensureTrackedWorld(world)) {
return;
}
chunks.setBlockID(x, y, z, blockID);
}
@Override
public void removeChunk(UUID world, int chunkX, int chunkZ) {
if (!isTrackedWorld(world)) {
return;
}
chunks.removeColumn(chunkX, chunkZ);
removeTileEntitiesInChunk(chunkX, chunkZ);
}
@Override
public void removeChunkSection(UUID world, int chunkX, int chunkY, int chunkZ) {
if (!isTrackedWorld(world)) {
return;
}
chunks.removeSection(chunkX, chunkY, chunkZ);
}
@Override
public void pruneTileEntitiesAbsentFromChunkSections(UUID world, int chunkX, int chunkZ, int minimumSectionY, int sectionCount, long[][] presentBySection) {
if (!isTrackedWorld(world) || sectionCount < 0 || (presentBySection != null && presentBySection.length != sectionCount)) {
return;
}
SWMRInt2ObjectHashTable<NettyTileEntity<R>> map = knownTileEntitiesByColumnBucket;
int bucketKey = packColumnBucket(chunkX, chunkZ);
// The wrapped key selects a collision bucket; full chunk coordinates below establish ownership.
NettyTileEntity<R> head = map.get(bucketKey);
NettyTileEntity<R> currentHead = head;
for (NettyTileEntity<R> current = head; current != null; ) {
NettyTileEntity<R> next = current.nextAcquire();
if (current.chunkX() == chunkX && current.chunkZ() == chunkZ) {
int sectionIndex = current.chunkY() - minimumSectionY;
long[] present = sectionIndex >= 0 && sectionIndex < sectionCount && presentBySection != null
? presentBySection[sectionIndex]
: null;
if (sectionIndex < 0 || sectionIndex >= sectionCount || present == null) {
currentHead = removeNode(map, bucketKey, currentHead, current);
} else {
int packed = packUncheckedGuarded(current.blockX(), current.blockY(), current.blockZ());
// Guarded packing masks the full coordinates to local x/y/z. The high bits choose the 64-bit word;
// Java masks the long shift distance to the low six bits, selecting the bit within that word.
if ((present[packed >>> 6] & 1L << packed) == 0L) {
currentHead = removeNode(map, bucketKey, currentHead, current);
}
}
}
current = next;
}
}
@Override
public void replaceChunkSection(UUID world, int chunkX, int chunkY, int chunkZ, BlockChunkData data) {
if (!ensureTrackedWorld(world)) {
return;
}
chunks.replaceSection(chunkX, chunkY, chunkZ, data);
}
@Override
public void replaceChunkSectionOcclusion(UUID world, int chunkX, int chunkY, int chunkZ, OccludingChunkData data) {
if (trackAllBlocks) {
throw new UnsupportedOperationException("Block chunk storage requires full block IDs for section replacement");
}
if (!ensureTrackedWorld(world)) {
return;
}
chunks.replaceSectionOcclusion(chunkX, chunkY, chunkZ, data);
}
@Override
public void clear() {
trackedWorld = null;
clearTrackedState();
}
private boolean isTrackedWorld(UUID world) {
UUID current = trackedWorld;
return world != null && current != null && current.equals(world);
}
private boolean ensureTrackedWorld(UUID world) {
if (world == null) {
return false;
}
if (world.equals(trackedWorld)) {
return true;
}
trackedWorld = null;
clearTrackedState();
trackedWorld = world;
return true;
}
private void clearTrackedState() {
chunks.clear();
forEachTileEntity(NettyTileEntity::markRemoved);
knownTileEntitiesByColumnBucket.clear();
transitions.clearPublishedTransitions();
}
private void removeTileEntitiesInChunk(int chunkX, int chunkZ) {
SWMRInt2ObjectHashTable<NettyTileEntity<R>> map = knownTileEntitiesByColumnBucket;
int bucketKey = packColumnBucket(chunkX, chunkZ);
NettyTileEntity<R> head = map.get(bucketKey);
if (head == null) {
return;
}
boolean collision = false;
for (NettyTileEntity<R> current = head; current != null; current = current.nextAcquire()) {
if (current.chunkX() != chunkX || current.chunkZ() != chunkZ) {
collision = true;
break;
}
}
if (!collision) {
// Removing the map entry publishes removal of the whole bucket. Keep the old chain intact so readers that
// already acquired its head can finish their weakly-consistent traversal; detached nodes are never reused.
map.remove(bucketKey, head);
for (NettyTileEntity<R> current = head; current != null; current = current.nextAcquire()) {
current.markRemoved();
}
return;
}
Logger.info("Chunk collision occured, failing back to linear scan for tile entity removal in chunk " + chunkX + ", " + chunkZ, 5, AbstractBlockView.class); // I want to see if this occurs frequently
// Wrapped-key collisions are rare. Remove matching nodes individually while preserving other columns.
NettyTileEntity<R> currentHead = head;
for (NettyTileEntity<R> current = head; current != null; ) {
NettyTileEntity<R> next = current.nextAcquire();
if (current.chunkX() == chunkX && current.chunkZ() == chunkZ) {
currentHead = removeNode(map, bucketKey, currentHead, current);
}
current = next;
}
}
private NettyTileEntity<R> removeNode(SWMRInt2ObjectHashTable<NettyTileEntity<R>> map, int bucketKey, NettyTileEntity<R> head, NettyTileEntity<R> node) {
node.markRemoved();
if (node != head) {
node.unlink();
return head;
}
NettyTileEntity<R> successor = node.nextAcquire();
if (successor == null) {
map.remove(bucketKey, node);
} else {
map.put(bucketKey, successor);
}
node.detachHeadWriterOnly();
return successor;
}
@SuppressWarnings("unchecked")
private T findTileEntityInBucket(NettyTileEntity<R> bucketHead, BlockSpatial position) {
for (NettyTileEntity<R> current = bucketHead; current != null; current = current.nextAcquire()) {
if (current.blockX() == position.blockX() && current.blockY() == position.blockY() && current.blockZ() == position.blockZ()) {
return (T) current;
}
}
return null;
}
private boolean isCurrentWorldEpoch(int expectedWorldEpoch) {
return PlayerData.isStableWorldEpoch(expectedWorldEpoch) && worldEpochSupplier.getAsInt() == expectedWorldEpoch;
}
private long tileEntityCheckModeTokenAcquire() {
return (long) TILE_ENTITY_CHECK_MODE_TOKEN.getAcquire(this);
}
private void forEachTileEntity(Consumer<NettyTileEntity<R>> action) {
knownTileEntitiesByColumnBucket.forEachValue(head -> {
for (NettyTileEntity<R> current = head; current != null; current = current.nextAcquire()) {
action.accept(current);
}
});
}
private static int packColumnBucket(int chunkX, int chunkZ) {
// Keep the low 16 bits of X, then put the low 16 bits of Z in the upper half of the int.
// Full coordinates on every tile disambiguate columns whose wrapped keys collide.
return (chunkX & 0xFFFF) | (chunkZ & 0xFFFF) << 16;
}
private static boolean modeEnabled(long modeToken) {
return (modeToken & 1L) != 0L;
}
}
@@ -0,0 +1,150 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.view;
import games.cubi.locatables.api.BlockLocatable;
import games.cubi.locatables.api.BlockSpatial;
import games.cubi.locatables.api.SpatialChunkSection;
import games.cubi.raycastedantiesp.core.chunks.ChunkOcclusionView;
import games.cubi.raycastedantiesp.core.tracked.TrackedTileEntity;
import games.cubi.raycastedantiesp.core.chunks.BlockChunkData;
import games.cubi.raycastedantiesp.core.chunks.OccludingChunkData;
import games.cubi.utils.Clearable;
import java.util.Collection;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.function.IntSupplier;
/**
* A per-player block view with one structural writer and concurrent weakly-consistent readers.
*
* <p>Packet-driven structural mutations, including chunk and tile membership changes, must all be performed by the
* same outbound Netty thread. At most one engine worker concurrently traverses a player's view and commits visibility
* decisions; visibility fields and the transition queue are safe for that Netty/engine overlap.</p>
*/
public interface BlockView extends Clearable {
/**
* Parameters are chunk coordinates
*/
ChunkOcclusionView getChunkOcclusionView(int chunkX, int chunkY, int chunkZ);
default ChunkOcclusionView getChunkOcclusionView(SpatialChunkSection chunkSection) {
return getChunkOcclusionView(chunkSection.chunkX(), chunkSection.chunkY(), chunkSection.chunkZ());
}
boolean isBlockOccluding(BlockLocatable location);
boolean isBlockOccluding(int x, int y, int z);
/**
* Constructs a new tile entity with the provided id and visibility, or updates the block id for an existing tile
* entity. This is a structural-writer operation.
*
* @return the current tracked tile entity, or null when the location cannot be tracked.
*/
TrackedTileEntity<?> updateOrInsertTileEntity(UUID world, BlockSpatial position, char blockID, boolean visibleIfNew);
/** Structural-writer operation. */
void removeTileEntity(UUID world, BlockSpatial position);
TrackedTileEntity<?> getTrackedTileEntity(UUID world, BlockSpatial position);
/** Returns the engine's desired visibility, not the state currently applied to the client. */
boolean isVisible(UUID world, BlockSpatial position, int currentTick);
/**
* Records visibility established by the current outbound packet without queuing another packet. This synchronizes
* both desired and client visibility and resets the check timestamp because the transmitted state supersedes the
* result of any previous visibility check. The tile entity must be the current state returned by this view's
* structural-writer operations.
*/
void recordOutboundTileEntityVisibility(TrackedTileEntity<?> tileEntity, boolean visible);
/**
* Applies a mode change from the structural writer.
*
* Sets every desired state visible when checks are disabled and invokes {@code visibilityRepairConsumer} for each
* tile entity still hidden from the client. The structural writer must send their current state directly rather
* than publishing them to the engine transition queue.
*/
void applyTileEntityCheckMode(boolean enabled, int currentTick, Consumer<TrackedTileEntity<?>> visibilityRepairConsumer);
/** Returns an opaque enabled-state/generation snapshot for rejecting results that cross a mode change. */
long tileEntityCheckModeToken();
/** Returns whether {@code modeToken} is still the current enabled generation. */
boolean isCurrentEnabledTileEntityMode(long modeToken);
Collection<TrackedTileEntity<?>> getKnownTileEntities();
/**
* Iterates currently tracked tile entities that should be visibility-checked.
*
* @return number of tile entities passed to {@code action}.
*/
int forEachNeedingRecheck(int recheckTicks, int currentTick, Consumer<TrackedTileEntity<?>> action);
@FunctionalInterface
interface VisibilityResolver {
byte SKIPPED = 78;
byte HIDE = -23;
byte SHOW = 42;
byte setVisible(TrackedTileEntity<?> tileEntity);
}
/**
* Iterates currently tracked tile entities that should be visibility-checked.
*
* @return number of tile entities passed to {@code action}.
*/
int updateVisibilityForEachNeedingRecheck(int recheckTicks, int currentTick, long modeToken, int expectedWorldEpoch, VisibilityResolver action);
boolean hasPendingTransitions();
/** Publishes the partial transition batch owned by the current engine producer. */
void flushPendingTransitions();
@FunctionalInterface
interface TransitionConsumer {
void accept(TransitionType.Tile type, TrackedTileEntity<?> tileEntity, long modeToken, int worldEpoch);
}
void drainTransitions(TransitionConsumer consumer);
/** Structural-writer operation. */
void upsertBlock(UUID world, int x, int y, int z, int blockID);
/** Structural-writer operation. */
void removeChunk(UUID world, int chunkX, int chunkZ);
/** Structural-writer operation. */
void removeChunkSection(UUID world, int chunkX, int chunkY, int chunkZ);
/**
* Removes tracked tile entities absent from an authoritative chunk column. A null {@code presentBySection} means
* the entire column has no managed tiles; a null entry means that section has none. This is a structural-writer
* operation.
*/
void pruneTileEntitiesAbsentFromChunkSections(UUID world, int chunkX, int chunkZ, int minimumSectionY, int sectionCount, long[][] presentBySection);
/** Structural-writer operation. */
void replaceChunkSection(UUID world, int chunkX, int chunkY, int chunkZ, BlockChunkData data);
/** Structural-writer operation. */
void replaceChunkSectionOcclusion(UUID world, int chunkX, int chunkY, int chunkZ, OccludingChunkData data);
default <T> T cast() {
return (T) this;
}
interface Factory {
BlockView createBlockView(IntSupplier worldEpochSupplier);
}
}
@@ -0,0 +1,102 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.view;
import games.cubi.raycastedantiesp.core.tracked.TrackedEntity;
import games.cubi.locatables.api.Spatial;
import games.cubi.raycastedantiesp.core.tracked.NettyEntity;
import games.cubi.utils.Clearable;
import java.util.Collection;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.function.IntSupplier;
public interface EntityView<T extends TrackedEntity<?>> extends Clearable {
void insertEntity(UUID world, T entity);
void removeEntity(int entityID, int currentTick);
void removeEntity(int entityID);
void removeEntity(UUID entityUUID, int currentTick);
T getEntity(UUID entityUUID);
T getEntity(int entityID);
Spatial getPosition(UUID entityUUID);
int getEntityID(UUID entityUUID);
boolean exists(UUID entityUUID);
boolean exists(int entityID);
/**
* Returns a weakly consistent count of the entities currently tracked by this view.
* This operation is safe to call from threads other than the structural writer.
*/
int size();
boolean isVisible(UUID entityUUID);
boolean isVisible(int entityID);
void setVisibility(NettyEntity<?> entity, boolean visible, int currentTick, int expectedWorldEpoch);
/**
* Applies visibility from the Netty structural writer without publishing an engine transition.
*
* @return whether the entity and epoch were current and the visibility was applied
*/
boolean recordDirectVisibility(NettyEntity<?> entity, boolean visible, int currentTick, int expectedWorldEpoch);
Collection<UUID> getKnownEntities();
int[] getKnownEntityIDs();
/**
* Iterates currently tracked entities that should be visibility-checked.
*
* @return number of entities passed to {@code action}.
*/
int forEachNeedingRecheck(int visibleRecheckTicks, int currentTick, Consumer<UUID> action);
/**
* Iterates currently tracked entities that should be visibility-checked.
*
* @return number of entities passed to {@code action}, or 0 if {@code countingActuallyNeeded} is false.
*/
int forEachNeedingRecheckEntity(int visibleRecheckTicks, int currentTick, boolean countingActuallyNeeded, int expectedWorldEpoch, Consumer<NettyEntity<?>> action);
boolean hasPendingTransitions();
/** Publishes the partial transition batch owned by the current engine producer. */
void flushPendingTransitions();
@FunctionalInterface
interface TransitionConsumer {
void accept(TransitionType.Entity type, TrackedEntity<?> entity, int worldEpoch);
}
void drainTransitions(TransitionConsumer consumer);
boolean isPlayerView();
default <T> T cast() {
return (T) this;
}
String getStringDataForDebugging();
interface Factory {
EntityView<?> createEntityView(IntSupplier worldEpochSupplier);
}
}
@@ -0,0 +1,185 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.view;
import games.cubi.utils.Clearable;
import games.cubi.utils.IntrusiveSPSCQueue;
import games.cubi.raycastedantiesp.core.tracked.TrackedTileEntity;
import java.util.Objects;
/**
* Queues tile-entity visibility transitions without allocating a record for every transition.
*
* <p>Exactly one engine thread at a time owns the pending batch and publishes it to the intrusive SPSC queue. The
* producer role may migrate between engine threads, while the player's Netty thread exclusively drains published
* entries. Producer and consumer methods must not be called from the opposite role.</p>
*/
public final class PackedBlockTransitionQueue {
private static final int BATCH_MIN_SIZE = 3;
private static final int BATCH_SIZE = 8;
private final IntrusiveSPSCQueue<QueueEntry> publishedEntries = new IntrusiveSPSCQueue<>();
private final PendingBatch pending = new PendingBatch();
public void add(TransitionType.Tile type, TrackedTileEntity<?> tileEntity, long modeToken, int worldEpoch) {
Objects.requireNonNull(type, "type");
Objects.requireNonNull(tileEntity, "tileEntity");
if (pending.count != 0 && (pending.modeToken != modeToken || pending.worldEpoch != worldEpoch)) {
flushPending();
}
if (pending.count == 0) {
pending.modeToken = modeToken;
pending.worldEpoch = worldEpoch;
}
pending.add(type, tileEntity);
if (pending.count == BATCH_SIZE) {
flushPending();
}
}
/** Publishes the producer-owned partial batch. Only the engine producer may call this method. */
public void flushPendingTransitions() {
flushPending();
}
public boolean hasPendingTransitions() {
return !publishedEntries.isEmpty();
}
/**
* Drains published entries in FIFO order. A claimed queue entry is consumed at most once if a callback throws while
* processing it, and any unvisited transitions packed into that entry are discarded.
*/
public void drainTransitions(BlockView.TransitionConsumer consumer) {
Objects.requireNonNull(consumer, "consumer");
QueueEntry entry;
while ((entry = publishedEntries.poll()) != null) {
entry.drain(consumer);
}
}
/**
* Discards transitions already published to the consumer. The producer-owned pending batch is intentionally left
* untouched: a structural clear can race an engine flush, and that in-flight batch must retain its old epoch and
* mode token so the consumer can reject it normally after it is published.
*/
public void clearPublishedTransitions() {
publishedEntries.clear();
}
private void flushPending() {
switch (pending.count) {
case 0 -> {
return;
}
case 1 -> publishedEntries.offer(new SingleEntry(pending.t1, pending.e1, pending.modeToken, pending.worldEpoch));
case 2 -> {
publishedEntries.offer(new SingleEntry(pending.t1, pending.e1, pending.modeToken, pending.worldEpoch));
publishedEntries.offer(new SingleEntry(pending.t2, pending.e2, pending.modeToken, pending.worldEpoch));
}
case BATCH_MIN_SIZE, 4, 5, 6, 7, BATCH_SIZE -> publishedEntries.offer(new BatchEntry(pending));
default -> throw new IllegalStateException("Tile transition batch exceeded eight entries");
}
pending.clear();
}
private abstract static sealed class QueueEntry extends IntrusiveSPSCQueue.Node {
abstract void drain(BlockView.TransitionConsumer consumer);
}
private static final class SingleEntry extends QueueEntry {
private final TransitionType.Tile type;
private final TrackedTileEntity<?> tileEntity;
private final long modeToken;
private final int worldEpoch;
private SingleEntry(TransitionType.Tile type, TrackedTileEntity<?> tileEntity, long modeToken, int worldEpoch) {
this.type = type;
this.tileEntity = tileEntity;
this.modeToken = modeToken;
this.worldEpoch = worldEpoch;
}
@Override
public void drain(BlockView.TransitionConsumer consumer) {
consumer.accept(type, tileEntity, modeToken, worldEpoch);
}
}
private static final class PendingBatch implements Clearable {
private TransitionType.Tile t1, t2, t3, t4, t5, t6, t7, t8;
private TrackedTileEntity<?> e1, e2, e3, e4, e5, e6, e7, e8;
private long modeToken;
private int worldEpoch;
private int count;
private void add(TransitionType.Tile type, TrackedTileEntity<?> tileEntity) {
switch (++count) {
case 1 -> { t1 = type; e1 = tileEntity; }
case 2 -> { t2 = type; e2 = tileEntity; }
case 3 -> { t3 = type; e3 = tileEntity; }
case 4 -> { t4 = type; e4 = tileEntity; }
case 5 -> { t5 = type; e5 = tileEntity; }
case 6 -> { t6 = type; e6 = tileEntity; }
case 7 -> { t7 = type; e7 = tileEntity; }
case 8 -> { t8 = type; e8 = tileEntity; }
default -> throw new IllegalStateException("Tile transition batch exceeded eight entries");
}
}
public void clear() {
t1 = null; t2 = null; t3 = null; t4 = null;
t5 = null; t6 = null; t7 = null; t8 = null;
e1 = null; e2 = null; e3 = null; e4 = null;
e5 = null; e6 = null; e7 = null; e8 = null;
modeToken = 0L;
worldEpoch = 0;
count = 0;
}
}
private static final class BatchEntry extends QueueEntry {
private final TransitionType.Tile t1, t2, t3, t4, t5, t6, t7, t8;
private final TrackedTileEntity<?> e1, e2, e3, e4, e5, e6, e7, e8;
private final long modeToken;
private final int worldEpoch;
private final int count;
private BatchEntry(PendingBatch pending) {
t1 = pending.t1; t2 = pending.t2;
t3 = pending.t3; t4 = pending.t4;
t5 = pending.t5; t6 = pending.t6;
t7 = pending.t7; t8 = pending.t8;
e1 = pending.e1; e2 = pending.e2;
e3 = pending.e3; e4 = pending.e4;
e5 = pending.e5; e6 = pending.e6;
e7 = pending.e7; e8 = pending.e8;
modeToken = pending.modeToken;
worldEpoch = pending.worldEpoch;
count = pending.count;
}
@Override
public void drain(BlockView.TransitionConsumer consumer) {
consumer.accept(t1, e1, modeToken, worldEpoch);
if (count >= 2) consumer.accept(t2, e2, modeToken, worldEpoch);
if (count >= 3) consumer.accept(t3, e3, modeToken, worldEpoch);
if (count >= 4) consumer.accept(t4, e4, modeToken, worldEpoch);
if (count >= 5) consumer.accept(t5, e5, modeToken, worldEpoch);
if (count >= 6) consumer.accept(t6, e6, modeToken, worldEpoch);
if (count >= 7) consumer.accept(t7, e7, modeToken, worldEpoch);
if (count >= 8) consumer.accept(t8, e8, modeToken, worldEpoch);
}
}
}
@@ -0,0 +1,178 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.view;
import games.cubi.utils.Clearable;
import games.cubi.utils.IntrusiveSPSCQueue;
import games.cubi.raycastedantiesp.core.tracked.TrackedEntity;
import java.util.Objects;
/**
* Queues entity visibility transitions without allocating a record for every transition.
*
* <p>Exactly one engine thread at a time owns the pending batch and publishes it to the intrusive SPSC queue. The
* producer role may migrate between engine threads, while the player's Netty thread exclusively drains published
* entries. Producer and consumer methods must not be called from the opposite role.</p>
*/
public final class PackedEntityTransitionQueue { //todo: potentially merge this with PackedBlockTransitionQueue, and add a mode token to entities
private static final int BATCH_MIN_SIZE = 3;
private static final int BATCH_SIZE = 8;
private final IntrusiveSPSCQueue<QueueEntry> publishedEntries = new IntrusiveSPSCQueue<>();
private final PendingBatch pending = new PendingBatch();
public void add(TransitionType.Entity type, TrackedEntity<?> entity, int worldEpoch) {
Objects.requireNonNull(type, "type");
Objects.requireNonNull(entity, "entity");
if (pending.count != 0 && pending.worldEpoch != worldEpoch) {
flushPending();
}
if (pending.count == 0) {
pending.worldEpoch = worldEpoch;
}
pending.add(type, entity);
if (pending.count == BATCH_SIZE) {
flushPending();
}
}
/** Publishes the producer-owned partial batch. Only the engine producer may call this method. */
public void flushPendingTransitions() {
flushPending();
}
public boolean hasPendingTransitions() {
return !publishedEntries.isEmpty();
}
/**
* Drains published entries in FIFO order. A claimed queue entry is consumed at most once if a callback throws while
* processing it, and any unvisited transitions packed into that entry are discarded.
*/
public void drainTransitions(EntityView.TransitionConsumer consumer) {
Objects.requireNonNull(consumer, "consumer");
QueueEntry entry;
while ((entry = publishedEntries.poll()) != null) {
entry.drain(consumer);
}
}
/**
* Discards transitions already published to the consumer. The producer-owned pending batch is intentionally left
* untouched: a structural clear can race an engine flush, and that in-flight batch must retain its old epoch so
* the consumer can reject it normally after it is published.
*/
public void clearPublishedTransitions() {
publishedEntries.clear();
}
private void flushPending() {
switch (pending.count) {
case 0 -> {
return;
}
case 1 -> publishedEntries.offer(new SingleEntry(pending.t1, pending.e1, pending.worldEpoch));
case 2 -> {
publishedEntries.offer(new SingleEntry(pending.t1, pending.e1, pending.worldEpoch));
publishedEntries.offer(new SingleEntry(pending.t2, pending.e2, pending.worldEpoch));
}
case BATCH_MIN_SIZE, 4, 5, 6, 7, BATCH_SIZE -> publishedEntries.offer(new BatchEntry(pending));
default -> throw new IllegalStateException("Entity transition batch exceeded eight entries");
}
pending.clear();
}
private abstract static class QueueEntry extends IntrusiveSPSCQueue.Node {
abstract void drain(EntityView.TransitionConsumer consumer);
}
private static final class SingleEntry extends QueueEntry {
private final TransitionType.Entity type;
private final TrackedEntity<?> entity;
private final int worldEpoch;
private SingleEntry(TransitionType.Entity type, TrackedEntity<?> entity, int worldEpoch) {
this.type = type;
this.entity = entity;
this.worldEpoch = worldEpoch;
}
@Override
public void drain(EntityView.TransitionConsumer consumer) {
consumer.accept(type, entity, worldEpoch);
}
}
private static final class PendingBatch implements Clearable {
private TransitionType.Entity t1, t2, t3, t4, t5, t6, t7, t8;
private TrackedEntity<?> e1, e2, e3, e4, e5, e6, e7, e8;
private int worldEpoch;
private int count;
private void add(TransitionType.Entity type, TrackedEntity<?> entity) {
switch (++count) {
case 1 -> { t1 = type; e1 = entity; }
case 2 -> { t2 = type; e2 = entity; }
case 3 -> { t3 = type; e3 = entity; }
case 4 -> { t4 = type; e4 = entity; }
case 5 -> { t5 = type; e5 = entity; }
case 6 -> { t6 = type; e6 = entity; }
case 7 -> { t7 = type; e7 = entity; }
case 8 -> { t8 = type; e8 = entity; }
default -> throw new IllegalStateException("Entity transition batch exceeded eight entries");
}
}
public void clear() {
t1 = null; t2 = null; t3 = null; t4 = null;
t5 = null; t6 = null; t7 = null; t8 = null;
e1 = null; e2 = null; e3 = null; e4 = null;
e5 = null; e6 = null; e7 = null; e8 = null;
worldEpoch = 0;
count = 0;
}
}
private static final class BatchEntry extends QueueEntry {
private final TransitionType.Entity t1, t2, t3, t4, t5, t6, t7, t8;
private final TrackedEntity<?> e1, e2, e3, e4, e5, e6, e7, e8;
private final int worldEpoch;
private final int count;
private BatchEntry(PendingBatch pending) {
t1 = pending.t1; t2 = pending.t2;
t3 = pending.t3; t4 = pending.t4;
t5 = pending.t5; t6 = pending.t6;
t7 = pending.t7; t8 = pending.t8;
e1 = pending.e1; e2 = pending.e2;
e3 = pending.e3; e4 = pending.e4;
e5 = pending.e5; e6 = pending.e6;
e7 = pending.e7; e8 = pending.e8;
worldEpoch = pending.worldEpoch;
count = pending.count;
}
@Override
public void drain(EntityView.TransitionConsumer consumer) {
consumer.accept(t1, e1, worldEpoch);
if (count >= 2) consumer.accept(t2, e2, worldEpoch);
if (count >= 3) consumer.accept(t3, e3, worldEpoch);
if (count >= 4) consumer.accept(t4, e4, worldEpoch);
if (count >= 5) consumer.accept(t5, e5, worldEpoch);
if (count >= 6) consumer.accept(t6, e6, worldEpoch);
if (count >= 7) consumer.accept(t7, e7, worldEpoch);
if (count >= 8) consumer.accept(t8, e8, worldEpoch);
}
}
}
@@ -0,0 +1,21 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.view;
public interface TransitionType {
enum Entity {
SHOW,
HIDE,
FORGET,
}
enum Tile {
SHOW,
HIDE,
}
}
@@ -0,0 +1,48 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.view;
import games.cubi.logs.Logger;
import java.util.function.IntSupplier;
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(IntSupplier worldEpochSupplier) {
if (blockViewFactory == null) {
Logger.error(new IllegalStateException("Block view factory is null. Did you forget to initialise ViewRegistry?"), 1, ViewRegistry.class);
}
return blockViewFactory.createBlockView(worldEpochSupplier);
}
public static EntityView<?> createEntityView(IntSupplier worldEpochSupplier) {
if (entityViewFactory == null) {
Logger.error(new IllegalStateException("Entity view factory is null. Did you forget to initialise ViewRegistry?"), 1, ViewRegistry.class);
}
return entityViewFactory.createEntityView(worldEpochSupplier);
}
public static EntityView<?> createPlayerEntityView(IntSupplier worldEpochSupplier) {
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(worldEpochSupplier);
}
}
@@ -0,0 +1,106 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.view.chunks;
import ca.spottedleaf.concurrentutil.map.SWMRLong2ObjectHashTable;
import games.cubi.raycastedantiesp.core.chunks.BlockChunkData;
import games.cubi.raycastedantiesp.core.chunks.BlockInfoResolver;
import games.cubi.raycastedantiesp.core.chunks.ChunkData;
import games.cubi.raycastedantiesp.core.chunks.ChunkOcclusionView;
import games.cubi.raycastedantiesp.core.chunks.blocks.TwoBlockChunkData;
import static games.cubi.raycastedantiesp.core.view.chunks.ChunkSectionStore.packChunkCoords;
import static games.cubi.raycastedantiesp.core.view.chunks.ChunkSectionStore.packGlobalCoords;
public final class BlockChunkSectionStore extends SWMRLong2ObjectHashTable<BlockChunkData> implements ChunkSectionStore {
private final BlockInfoResolver blockInfoResolver;
public BlockChunkSectionStore(BlockInfoResolver blockInfoResolver) {
this.blockInfoResolver = blockInfoResolver;
}
@Override
public ChunkOcclusionView getSection(int chunkX, int chunkY, int chunkZ) {
long key = packChunkCoords(chunkX, chunkY, chunkZ);
return get(key);
}
@Override
public boolean isOccluding(int x, int y, int z) {
long key = packGlobalCoords(x, y, z);
BlockChunkData chunk = get(key);
return chunk != null && chunk.isOccludingLocal(x & ChunkData.LOCAL_MASK, y & ChunkData.LOCAL_MASK, z & ChunkData.LOCAL_MASK);
}
/**
* This method is not thread-safe and should only be called from the netty thread.
*/
@Override
public void setBlockID(int x, int y, int z, int blockID) {
long key = packGlobalCoords(x, y, z);
char storedBlockID = toStoredBlockID(blockID);
BlockChunkData existing = get(key);
if (existing == null) { // this means the chunk is currently air (or something's gone horribly wrong)
if (storedBlockID == 0) {
return;
}
TwoBlockChunkData newChunk = TwoBlockChunkData.upgradeFromAir(storedBlockID, x, y, z, blockInfoResolver);
put(key, newChunk);
return;
}
BlockChunkData updated = existing.setBlockID(x & ChunkData.LOCAL_MASK, y & ChunkData.LOCAL_MASK, z & ChunkData.LOCAL_MASK, storedBlockID, blockInfoResolver);
if (updated != existing) {
put(key, updated);
}
}
@Override
public void replaceSection(int chunkX, int sectionY, int chunkZ, BlockChunkData data) {
put(packChunkCoords(chunkX, sectionY, chunkZ), data);
}
@Override
public void replaceSectionOcclusion(int chunkX, int sectionY, int chunkZ, games.cubi.raycastedantiesp.core.chunks.OccludingChunkData data) {
throw new UnsupportedOperationException("Block chunk storage requires full block IDs for section replacement");
}
@Override
public void removeSection(int chunkX, int sectionY, int chunkZ) {
remove(packChunkCoords(chunkX, sectionY, chunkZ));
}
@Override
public void removeColumn(int chunkX, int chunkZ) {
// Start at the raw 8-bit Y value 0. Incrementing visits 0..255, which represents signed section Y values 0..127 then -128..-1.
long key = packChunkCoords(chunkX, 0, chunkZ);
for (int i = 0; i < SECTION_Y_COUNT; i++) {
remove(key);
key += SECTION_Y_INCREMENT;
}
}
@Override
public int loadedSectionCount() {
return size();
}
@Override
public void clear() {
super.clear();
}
private static char toStoredBlockID(int blockID) {
if (blockID < 0 || blockID > Character.MAX_VALUE) {
throw new IllegalArgumentException("blockID must fit in an unsigned 16-bit value, but was " + blockID);
}
return (char) blockID;
}
}
@@ -0,0 +1,84 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.view.chunks;
import games.cubi.raycastedantiesp.core.chunks.BlockChunkData;
import games.cubi.raycastedantiesp.core.chunks.ChunkOcclusionView;
import games.cubi.raycastedantiesp.core.chunks.OccludingChunkData;
public interface ChunkSectionStore {
/**
* Coordinates are chunk coordinates
*/
ChunkOcclusionView getSection(int chunkX, int chunkY, int chunkZ);
boolean isOccluding(int x, int y, int z);
void setBlockID(int x, int y, int z, int blockID);
void replaceSection(int chunkX, int sectionY, int chunkZ, BlockChunkData data);
void replaceSectionOcclusion(int chunkX, int sectionY, int chunkZ, OccludingChunkData data);
void removeSection(int chunkX, int sectionY, int chunkZ);
void removeColumn(int chunkX, int chunkZ);
int loadedSectionCount();
void clear();
static final int HORIZONTAL_BITS = 28;
static final int SECTION_Y_BITS = 8;
static final int HORIZONTAL_MIN = -(1 << (HORIZONTAL_BITS - 1));
static final int HORIZONTAL_MAX = (1 << (HORIZONTAL_BITS - 1)) - 1;
static final int SECTION_Y_MIN = -(1 << (SECTION_Y_BITS - 1));
static final int SECTION_Y_MAX = (1 << (SECTION_Y_BITS - 1)) - 1;
static final int SECTION_Y_COUNT = 1 << SECTION_Y_BITS;
static final long SECTION_Y_INCREMENT = 1L << HORIZONTAL_BITS;
static final long HORIZONTAL_MASK = (1L << HORIZONTAL_BITS) - 1L;
static final long SECTION_Y_MASK = (1L << SECTION_Y_BITS) - 1L;
static long packChunkCoords(int chunkX, int sectionY, int chunkZ) {
checkHorizontal(chunkX, "chunkX");
checkSectionY(sectionY);
checkHorizontal(chunkZ, "chunkZ");
return ((long) chunkX & HORIZONTAL_MASK) << (SECTION_Y_BITS + HORIZONTAL_BITS)
| ((long) sectionY & SECTION_Y_MASK) << HORIZONTAL_BITS
| ((long) chunkZ & HORIZONTAL_MASK);
}
static long packGlobalCoords(int x, int y, int z) {
return packChunkCoords(x >> 4, y >> 4, z >> 4);
}
static int unpackChunkX(long key) {
return (int) (key >> (SECTION_Y_BITS + HORIZONTAL_BITS));
}
static int unpackSectionY(long key) {
return (int) (key << HORIZONTAL_BITS >> (HORIZONTAL_BITS + HORIZONTAL_BITS));
}
static int unpackChunkZ(long key) {
return (int) (key << (Long.SIZE - HORIZONTAL_BITS) >> (Long.SIZE - HORIZONTAL_BITS));
}
private static void checkHorizontal(int value, String name) {
if (value < HORIZONTAL_MIN || value > HORIZONTAL_MAX) {
throw new IllegalArgumentException(name + " must be in [" + HORIZONTAL_MIN + ", " + HORIZONTAL_MAX + "], but was " + value);
}
}
private static void checkSectionY(int sectionY) {
if (sectionY < SECTION_Y_MIN || sectionY > SECTION_Y_MAX) {
throw new IllegalArgumentException("sectionY must be in [" + SECTION_Y_MIN + ", " + SECTION_Y_MAX + "], but was " + sectionY);
}
}
}
@@ -0,0 +1,90 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.view.chunks;
import ca.spottedleaf.concurrentutil.map.SWMRLong2ObjectHashTable;
import games.cubi.raycastedantiesp.core.chunks.*;
import static games.cubi.raycastedantiesp.core.view.chunks.ChunkSectionStore.packChunkCoords;
import static games.cubi.raycastedantiesp.core.view.chunks.ChunkSectionStore.packGlobalCoords;
public final class OccludingChunkSectionStore extends SWMRLong2ObjectHashTable<OccludingChunkData> implements ChunkSectionStore {
private final BlockInfoResolver blockInfoResolver;
public OccludingChunkSectionStore(BlockInfoResolver blockInfoResolver) {
this.blockInfoResolver = blockInfoResolver;
}
@Override
public ChunkOcclusionView getSection(int chunkX, int chunkY, int chunkZ) {
long key = packChunkCoords(chunkX, chunkY, chunkZ);
return get(key);
}
@Override
public boolean isOccluding(int x, int y, int z) {
long key = packGlobalCoords(x, y, z);
OccludingChunkData chunk = get(key);
return chunk != null && chunk.isOccludingLocal(x & ChunkData.LOCAL_MASK, y & ChunkData.LOCAL_MASK, z & ChunkData.LOCAL_MASK);
}
@Override
public void setBlockID(int x, int y, int z, int blockID) {
long key = packGlobalCoords(x, y, z);
boolean occluding = blockID != 0 && blockInfoResolver.isOccluding(blockID);
OccludingChunkData existing = get(key);
if (existing == null) {
if (!occluding) {
return;
}
existing = OccludingChunkData.empty();
put(key, existing);
}
OccludingChunkData updated = existing.setOccluding(x & ChunkData.LOCAL_MASK, y & ChunkData.LOCAL_MASK, z & ChunkData.LOCAL_MASK, occluding);
if (updated != existing) {
put(key, updated);
}
}
@Override
public void replaceSection(int chunkX, int sectionY, int chunkZ, BlockChunkData data) {
throw new UnsupportedOperationException("Occlusion chunk storage requires occlusion data for section replacement");
}
@Override
public void replaceSectionOcclusion(int chunkX, int sectionY, int chunkZ, OccludingChunkData data) {
put(packChunkCoords(chunkX, sectionY, chunkZ), data);
}
@Override
public void removeSection(int chunkX, int sectionY, int chunkZ) {
remove(packChunkCoords(chunkX, sectionY, chunkZ));
}
@Override
public void removeColumn(int chunkX, int chunkZ) {
// Start at raw Y 0 so the increment covers every possible 8-bit signed section coordinate exactly once.
long key = packChunkCoords(chunkX, 0, chunkZ);
for (int i = 0; i < SECTION_Y_COUNT; i++) {
remove(key);
key += SECTION_Y_INCREMENT;
}
}
@Override
public int loadedSectionCount() {
return size();
}
@Override
public void clear() {
super.clear();
}
}
@@ -0,0 +1,825 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.view.controller;
import games.cubi.locatables.api.Locatable;
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.entity.EntityBypassRegistry;
import games.cubi.raycastedantiesp.core.tracked.NettyEntity;
import games.cubi.raycastedantiesp.core.players.NettyData;
import games.cubi.raycastedantiesp.core.players.PlayerData;
import games.cubi.raycastedantiesp.core.players.PlayerRegistry;
import games.cubi.utils.lists.PrimitiveIntArrayList;
import games.cubi.raycastedantiesp.core.utils.Packet;
import games.cubi.raycastedantiesp.core.view.EntityView;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import java.util.UUID;
import static games.cubi.raycastedantiesp.core.tracked.NettyEntity.NO_LEASHER;
import static games.cubi.raycastedantiesp.core.tracked.NettyEntity.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 void handleWorldStatePacket(UUID player, String world, UUID worldUUID, int minWorldHeight, int currentTick) {
PlayerData playerData = PlayerRegistry.get().getPlayerData(player);
if (playerData == null) {
Logger.error("Received world state packet for unknown player, uuid=" + player, 2, PacketEntityViewController.class);
return;
}
if (world == null) {
Logger.error("Received world state packet without a world name, uuid=" + player, 2, PacketEntityViewController.class);
return;
}
NettyData nettyData = playerData.nettyData();
String previousWorld = nettyData.getCurrentWorldName();
if (world.equals(previousWorld)) {
nettyData.setCurrentWorldMinHeight(minWorldHeight);
return;
}
int[] remainingEntityIDs = previousWorld == null ? null : drainRemainingEntityIDs(playerData);
playerData.beginWorldTransition();
try {
if (previousWorld != null) {
nettyData.setExpectedWorldTransitionDestroyEntityIDs(remainingEntityIDs);
playerData.blockView().clear();
playerData.entityView().clear();
playerData.playerView().clear();
nettyData.clearPendingReconciliationState();
nettyData.getSelfEntity().clear();
}
nettyData.setCurrentWorldName(world).setCurrentWorldMinHeight(minWorldHeight);
} catch (Exception e) {
Logger.error(e, 1, PacketEntityViewController.class);
} finally {
playerData.completeWorldTransition(worldUUID); //Don't leave the player stuck on an odd world epoch
}
}
protected PlayerData handlePlayPhaseLoginPacket(int entityID, UUID playerUUID, int currentTick) {
return PlayerRegistry.get().registerAndGetPlayer(playerUUID, currentTick, entityID, this::createSelfEntity);
}
protected abstract NettyEntity<?> createSelfEntity(PlayerData ownData, int entityID, UUID playerUUID);
/** Applies a SHOW transition immediately on the Netty thread without publishing it to the engine SPSC queue. */
protected abstract void processDirectEntityShow(PlayerData playerData, EntityView<?> view, NettyEntity<?> entity, int worldEpoch);
protected void handlePlayerDisconnect(UUID player) {
if (player == null) {
return;
}
PlayerRegistry.get().unregisterPlayer(player);
}
/**
* @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;
}
NettyEntity<?> entity = Logger.requireNonNull(processEntitySpawn(playerData, packet, world, currentTick), "processEntitySpawn returned null", 3, PacketEntityViewController.class);
RaycastConfig config = (isPlayer) ? playerConfig : entityConfig;
if (config.enabled()) {
Locatable ownLocation = playerData.ownLocation();
boolean staleOwnLocation = ownLocation == null || ownLocation.world() == null || !ownLocation.world().equals(world);
double distanceSquared = staleOwnLocation ? Double.POSITIVE_INFINITY : ownLocation.distanceSquared(entity);
if (distanceSquared > config.hideOnSpawnDistanceSquared()) {
entity.setVisible(false);
entity.setClientVisible(false);
if (isPlayer) {
insertEntityToPlayerView(entity, playerData, world);
return true;
}
insertEntityToEntityView(entity, playerData, world);
return true;
}
} else {
entity.setClientVisible(true);
}
if (isPlayer) {
insertEntityToPlayerView(entity, playerData, world);
return false;
}
insertEntityToEntityView(entity, playerData, world);
return false;
}
@Packet(Packet.Packets.ENTITY_ANIMATION)
protected boolean handleEntityAnimation(int entityID, PlayerData playerData) {
return cancelIfEnabledAndHidden(entityID, playerData);
}
protected boolean handleCollectItem(int collectedEntityID, int collectorEntityID, PlayerData playerData) {
// Pickup animations do not imply removal; full pickups have a separate destroy packet.
return collectItemEndpointHidden(collectedEntityID, playerData) || collectItemEndpointHidden(collectorEntityID, playerData);
}
private boolean collectItemEndpointHidden(int entityID, PlayerData playerData) {
if (EntityBypassRegistry.isBypassed(entityID)) {
return false;
}
NettyEntity<?> entity = playerData.entityFromID(entityID);
return entity != null && !entity.isSelfEntity() && (!entity.clientVisible());
}
@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) {
NettyEntity<?> entity = playerData.entityFromID(entityID);
if (entity != null) {
processTrackedMetadata(packet, entity);
}
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);
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) {
boolean bypassedVehicle = EntityBypassRegistry.isBypassed(entityID);
NettyEntity<?> vehicle = bypassedVehicle ? null : playerData.entityFromID(entityID);
final int[] previousPassengers = getPreviousPassengerState(entityID, vehicle, playerData);
playerData.nettyData().consumeUnresolvedPassengers(entityID); // throw away any unresolved passengers as this new packet will have the correct passenger list
// "Stale" passengers are passengers that the previous authoritative state said were mounted,
// but the new full replacement passenger list no longer contains.
clearStalePassengerReferences(entityID, previousPassengers, passengers, playerData);
if (vehicle == null) {
playerData.nettyData().setUnresolvedPassengers(entityID, passengers);
if (bypassedVehicle) {
for (int passengerID : passengers) {
NettyEntity<?> passenger = playerData.entityFromID(passengerID);
if (passenger == null) {
continue;
}
passenger.setVehicleID(entityID);
forceVisibleBecauseAttached(passenger, playerData, currentTick, "bypassed vehicle passenger");
}
}
return false;
}
return handleEntityPassengersNow(vehicle, 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(NettyEntity<?> entity, int[] passengers, PlayerData playerData, int currentTick) {
int entityID = entity.entityID();
entity.setPassengerIDs(passengers);
int[] unresolvedPassengers = null;
boolean selfIsPassenger = false;
for (int passengerID : passengers) {
NettyEntity<?> passenger = playerData.entityFromID(passengerID);
if (passenger == null) {
unresolvedPassengers = PrimitiveIntArrayList.add(unresolvedPassengers, passengerID);
continue;
}
if (passenger.isSelfEntity()) {
selfIsPassenger = true;
}
passenger.setVehicleID(entityID);
}
playerData.nettyData().setUnresolvedPassengers(entityID, unresolvedPassengers);
checkVehicle(entity, playerData);
boolean cancelForForcedVehicleShow = selfIsPassenger && forceVisibleBecauseAttached(entity, playerData, currentTick, "self-passenger vehicle");
if (cancelForForcedVehicleShow) {
return true;
}
if (cancelIfEnabledAndHidden(entityID, playerData)) return true;
boolean passengersNotVisible = false;
IntArrayList visiblePassengers = new IntArrayList(passengers.length);
for (int passengerID : passengers) {
if (EntityBypassRegistry.isBypassed(passengerID)) {
visiblePassengers.add(passengerID);
}
else {
NettyEntity<?> passenger = playerData.entityFromID(passengerID);
if (passenger == null) {
visiblePassengers.add(passengerID);
}
else if (entity.isSelfEntity() && forceVisibleBecauseAttached(passenger, playerData, currentTick, "self-vehicle passenger")) {
passengersNotVisible = true;
// The direct SHOW path already makes this passenger client-visible. Keep it in the
// replacement relationship packet so the packet does not undo the newly established mount.
visiblePassengers.add(passengerID);
}
else if (entity.isSelfEntity() || passenger.isSelfEntity()) {
visiblePassengers.add(passengerID);
}
else if (cancelIfEnabledAndHidden(passenger, 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 int[] getPreviousPassengerState(int vehicleID, NettyEntity<?> vehicle, PlayerData playerData) {
if (vehicle != null) {
final int[] previousPassengerIDs = vehicle.passengerIDsNoAlloc();
if (!PrimitiveIntArrayList.isEmpty(previousPassengerIDs)) {
return previousPassengerIDs;
}
}
return playerData.nettyData().getUnresolvedPassengersNoAlloc(vehicleID);
}
/**
* Clears reverse vehicle links for passengers that were part of the previous vehicle state,
* but are absent from the new authoritative replacement list.
*/
private void clearStalePassengerReferences(int vehicleID, final int[] previousPassengers, int[] newPassengers, PlayerData playerData) {
if (PrimitiveIntArrayList.isEmpty(previousPassengers)) {
return;
}
for (int previousPassengerID : previousPassengers) {
if (PrimitiveIntArrayList.contains(newPassengers, previousPassengerID)) {
continue;
}
NettyEntity<?> previousPassenger = playerData.entityFromID(previousPassengerID);
if (previousPassenger != null && previousPassenger.vehicleID() == vehicleID) {
previousPassenger.setVehicleID(NO_VEHICLE);
}
}
}
private void checkVehicle(NettyEntity<?> entity, PlayerData playerData) {
int vehicleID = entity.vehicleID();
if (vehicleID == NO_VEHICLE) {
return;
}
NettyEntity<?> vehicle = playerData.entityFromID(vehicleID);
if (vehicle == null) {
return;
}
resendPassengerStateIfClientVisible(vehicle, playerData);
}
protected void handleDestroyEntities(int[] entityIDs, PlayerData playerData, int currentTick) {
for (int entityID : entityIDs) {
if (playerData.nettyData().consumeExpectedWorldTransitionDestroyEntityID(entityID)) {
playerData.nettyData().clearPendingPostSpawnTasksForEntity(entityID);
playerData.entityView().removeEntity(entityID);
playerData.playerView().removeEntity(entityID); // If not present, this fails silently, so no need to check for correct view first.
continue;
}
clearPassengerReferencesForDestroyedEntity(entityID, playerData);
clearLeashReferencesForDestroyedEntity(entityID, playerData);
playerData.nettyData().clearPendingPostSpawnTasksForEntity(entityID);
EntityView<?> view = playerData.viewFromEntityID(entityID);
if (view == null) continue;
Logger.debug("Removing entity from view due to destroy packet, entityID=" + entityID + " player=" + playerData.getPlayerUUID() + " tick=" + currentTick);
view.removeEntity(entityID, currentTick);
}
}
private int[] drainRemainingEntityIDs(PlayerData playerData) {
int[] entityIDs = playerData.entityView().getKnownEntityIDs();
int[] playerEntityIDs = playerData.playerView().getKnownEntityIDs();
int[] remainingEntityIDs = new int[entityIDs.length + playerEntityIDs.length];
int offset = 0;
System.arraycopy(entityIDs, 0, remainingEntityIDs, offset, entityIDs.length);
offset += entityIDs.length;
System.arraycopy(playerEntityIDs, 0, remainingEntityIDs, offset, playerEntityIDs.length);
return remainingEntityIDs;
}
private void clearPassengerReferencesForDestroyedEntity(int entityID, PlayerData playerData) {
int[] unresolvedPassengers = playerData.nettyData().consumeUnresolvedPassengers(entityID);
if (!PrimitiveIntArrayList.isEmpty(unresolvedPassengers)) {
for (int passengerID : unresolvedPassengers) {
NettyEntity<?> passenger = playerData.entityFromID(passengerID);
if (passenger != null && passenger.vehicleID() == entityID) {
passenger.setVehicleID(NO_VEHICLE);
}
}
}
int unresolvedVehicleID = playerData.nettyData().consumeUnresolvedVehicleForPassenger(entityID);
if (unresolvedVehicleID != NO_VEHICLE) {
NettyEntity<?> unresolvedVehicle = playerData.entityFromID(unresolvedVehicleID);
if (unresolvedVehicle != null) {
// this can occur if the vehicle existed at the time of the passenger packet but not the passenger, and somehow the passenger never got resolved to the vehicle (missing spawn packets etc). In reality this should never happen.
unresolvedVehicle.setPassengerIDs(PrimitiveIntArrayList.remove(unresolvedVehicle.passengerIDsNoAlloc(), entityID));
}
}
NettyEntity<?> entity = playerData.entityFromID(entityID);
if (entity == null) {
return;
}
int[] currentPassengerIDs = entity.passengerIDsNoAlloc();
if (!PrimitiveIntArrayList.isEmpty(currentPassengerIDs)) {
for (int passengerID : currentPassengerIDs) {
NettyEntity<?> passenger = playerData.entityFromID(passengerID);
if (passenger != null && passenger.vehicleID() == entityID) {
passenger.setVehicleID(NO_VEHICLE);
}
}
}
int vehicleID = entity.vehicleID();
if (vehicleID == NO_VEHICLE) {
return;
}
NettyEntity<?> vehicle = playerData.entityFromID(vehicleID);
if (vehicle != null) {
vehicle.setPassengerIDs(PrimitiveIntArrayList.remove(vehicle.passengerIDsNoAlloc(), entityID));
}
entity.setVehicleID(NO_VEHICLE);
}
/**
* Clears both sides of resolved and unresolved leash relationships so a reused entity ID
* cannot inherit relationships belonging to the destroyed entity.
*/
private void clearLeashReferencesForDestroyedEntity(int entityID, PlayerData playerData) {
// Deferred relationships are indexed by both endpoints, so clear the cases where this ID
// was the holder and where it was the leashed entity.
int[] pendingLeashedEntityIDs = playerData.nettyData().consumeUnresolvedLeashes(entityID);
if (!PrimitiveIntArrayList.isEmpty(pendingLeashedEntityIDs)) {
for (int leashedEntityID : pendingLeashedEntityIDs) {
NettyEntity<?> leashedEntity = playerData.entityFromID(leashedEntityID);
if (leashedEntity != null && leashedEntity.leashingEntity() == entityID) {
leashedEntity.setLeashingEntity(NO_LEASHER);
}
}
}
int pendingHolderEntityID = playerData.nettyData().consumeUnresolvedHolderForLeashedEntity(entityID);
if (pendingHolderEntityID != NO_LEASHER) {
NettyEntity<?> pendingHolder = playerData.entityFromID(pendingHolderEntityID);
if (pendingHolder != null) {
pendingHolder.removeLeashedEntity(entityID);
}
}
NettyEntity<?> entity = playerData.entityFromID(entityID);
if (entity == null) {
return;
}
// A tracked entity owns the same two relationship directions in its resolved state.
final int[] currentLeashedEntityIDs = entity.leashedEntityIDsOrNullNoAlloc();
if (!PrimitiveIntArrayList.isEmpty(currentLeashedEntityIDs)) {
for (int leashedEntityID : currentLeashedEntityIDs) {
NettyEntity<?> leashedEntity = playerData.entityFromID(leashedEntityID);
if (leashedEntity != null && leashedEntity.leashingEntity() == entityID) {
leashedEntity.setLeashingEntity(NO_LEASHER);
}
}
}
int holderEntityID = entity.leashingEntity();
if (holderEntityID != NO_LEASHER) {
NettyEntity<?> holder = playerData.entityFromID(holderEntityID);
if (holder != null) {
holder.removeLeashedEntity(entityID);
}
entity.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 leashedEntityID, int holderEntityID, PlayerData playerData, int currentTick) {
if (playerData.nettyData().isSelfEntityID(leashedEntityID) && playerData.nettyData().isSelfEntityID(holderEntityID)) {
return false;
}
NettyEntity<?> leashedEntity = playerData.entityFromID(leashedEntityID);
removeExistingLeashReference(leashedEntityID, leashedEntity, playerData);
if (holderEntityID == NO_LEASHER) {
return leashedEntity != null && cancelIfEnabledAndHidden(leashedEntity, playerData);
}
NettyEntity<?> holderEntity = playerData.entityFromID(holderEntityID);
if (leashedEntity != null) {
leashedEntity.setLeashingEntity(holderEntityID);
}
if (holderEntity != null) {
holderEntity.addLeashedEntity(leashedEntityID);
}
if (leashedEntity == null || holderEntity == null) {
playerData.nettyData().addUnresolvedLeash(holderEntityID, leashedEntityID);
}
if (holderEntity != null && holderEntity.isSelfEntity() && leashedEntity != null
&& forceVisibleBecauseAttached(leashedEntity, playerData, currentTick, "self-held leash")) {
return true; // The visibility update repairs leash state, so suppress the packet to avoid sending it twice and before the client is aware of the entity.
}
return leashedEntity != null && cancelIfEnabledAndHidden(leashedEntity, playerData)
|| holderEntity != null && cancelIfEnabledAndHidden(holderEntity, playerData);
}
private boolean forceVisibleBecauseAttached(NettyEntity<?> entity, PlayerData self, int currentTick, String reason) {
if (entity.isSelfEntity()) {
return false;
}
boolean wasClientVisible = entity.clientVisible();
EntityView<?> view = self.viewFromEntityID(entity.entityID());
if (view == null) {
Logger.warning("Could not find owning view while forcing attached entity visible, id=" + entity.entityID() + " player=" + self.getPlayerUUID() + " reason=" + reason, 6, PacketEntityViewController.class);
// Note that this path can fire when a vehicle is bypassed, so its log level must be higher than default.
return false;
}
boolean wasVisible = entity.visible();
int worldEpoch = self.acquireWorldEpoch();
if (!view.recordDirectVisibility(entity, true, currentTick, worldEpoch)) {
return false;
}
if (!wasVisible || !wasClientVisible) {
processDirectEntityShow(self, view, entity, worldEpoch);
}
return !wasClientVisible;
}
private void removeExistingLeashReference(int leashedEntityID, NettyEntity<?> leashedEntity, PlayerData playerData) {
int previousLeashingEntityID = leashedEntity == null
? playerData.nettyData().getUnresolvedHolderForLeashedEntity(leashedEntityID)
: leashedEntity.leashingEntity();
if (previousLeashingEntityID == NO_LEASHER) {
return;
}
playerData.nettyData().removeUnresolvedLeash(previousLeashingEntityID, leashedEntityID);
NettyEntity<?> previousHolder = playerData.entityFromID(previousLeashingEntityID);
if (previousHolder != null) {
previousHolder.removeLeashedEntity(leashedEntityID);
}
if (leashedEntity != null) {
leashedEntity.setLeashingEntity(NO_LEASHER);
}
}
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) {
if (playerData.nettyData().isSelfEntityID(entityID)) {
return false;
}
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(NettyEntity<?> entity, PlayerData playerData) {
if (entity.isSelfEntity()) {
return false;
}
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.
}
/**
* Replays any passenger relationship that was blocked earlier because either:
* 1. this entity is the vehicle and one or more passengers were missing, or
* 2. this entity is the passenger and the vehicle was already known.
*/
protected void reconcileUnresolvedPassengers(NettyEntity<?> insertedEntity, PlayerData playerData) {
int[] pendingPassengers = playerData.nettyData().getUnresolvedPassengersNoAlloc(insertedEntity.entityID());
if (!PrimitiveIntArrayList.isEmpty(pendingPassengers)) {
playerData.nettyData().consumeUnresolvedPassengers(insertedEntity.entityID());
handleEntityPassengersNow(insertedEntity, pendingPassengers, playerData, insertedEntity.lastChecked());
}
int unresolvedVehicleID = playerData.nettyData().getUnresolvedVehicleForPassenger(insertedEntity.entityID());
if (unresolvedVehicleID == NO_VEHICLE) {
return;
}
if (EntityBypassRegistry.isBypassed(unresolvedVehicleID)) {
insertedEntity.setVehicleID(unresolvedVehicleID);
forceVisibleBecauseAttached(insertedEntity, playerData, insertedEntity.lastChecked(), "bypassed vehicle unresolved passenger");
return;
}
NettyEntity<?> vehicle = playerData.entityFromID(unresolvedVehicleID);
if (vehicle == null) {
return;
}
insertedEntity.setVehicleID(unresolvedVehicleID);
playerData.nettyData().removeUnresolvedPassengerLink(insertedEntity.entityID(), unresolvedVehicleID);
if (vehicle.isSelfEntity() && forceVisibleBecauseAttached(insertedEntity, playerData, insertedEntity.lastChecked(), "self-vehicle unresolved passenger")) {
return;
}
}
/**
* Reconciles relationship state which arrived before this entity was identified as bypassed.
* The pending records are retained because a bypassed entity will never have a tracked entity
* to own the authoritative relationship state.
*/
protected void handleBypassedEntitySpawn(int entityID, PlayerData playerData, int currentTick) {
// Vanilla may send entity state before its spawn packet, and those packets were already
// forwarded to the client. Discard deferred tracking work rather than replaying duplicates.
playerData.nettyData().clearPendingPostSpawnTasksForEntity(entityID);
int[] pendingPassengers = playerData.nettyData().getUnresolvedPassengersNoAlloc(entityID);
if (!PrimitiveIntArrayList.isEmpty(pendingPassengers)) {
for (int passengerID : pendingPassengers) {
NettyEntity<?> passenger = playerData.entityFromID(passengerID);
if (passenger == null) {
continue;
}
passenger.setVehicleID(entityID);
forceVisibleBecauseAttached(passenger, playerData, currentTick, "bypassed vehicle passenger");
}
}
int holderEntityID = playerData.nettyData().getUnresolvedHolderForLeashedEntity(entityID);
if (holderEntityID != NO_LEASHER) {
NettyEntity<?> holder = playerData.entityFromID(holderEntityID);
if (holder != null) {
holder.addLeashedEntity(entityID);
}
}
int[] pendingLeashedEntityIDs = playerData.nettyData().getUnresolvedLeashesNoAlloc(entityID);
if (!PrimitiveIntArrayList.isEmpty(pendingLeashedEntityIDs)) {
for (int leashedEntityID : pendingLeashedEntityIDs) {
NettyEntity<?> leashedEntity = playerData.entityFromID(leashedEntityID);
if (leashedEntity != null) {
leashedEntity.setLeashingEntity(entityID);
}
}
}
}
/**
* Moves deferred leash state into a newly tracked entity while retaining relationships whose
* other endpoint is still untracked or permanently bypassed.
*/
protected void reconcileUnresolvedLeashes(NettyEntity<?> insertedEntity, PlayerData playerData) {
int entityID = insertedEntity.entityID();
int pendingHolderEntityID = playerData.nettyData().getUnresolvedHolderForLeashedEntity(entityID);
if (pendingHolderEntityID != NO_LEASHER) {
insertedEntity.setLeashingEntity(pendingHolderEntityID);
NettyEntity<?> holder = playerData.entityFromID(pendingHolderEntityID);
if (holder != null) {
holder.addLeashedEntity(entityID);
playerData.nettyData().removeUnresolvedLeash(pendingHolderEntityID, entityID);
if (holder.isSelfEntity()) {
forceVisibleBecauseAttached(insertedEntity, playerData, insertedEntity.lastChecked(), "self-held unresolved leash");
}
}
}
int[] pendingLeashedEntityIDs = playerData.nettyData().getUnresolvedLeashesNoAlloc(entityID);
if (PrimitiveIntArrayList.isEmpty(pendingLeashedEntityIDs)) {
return;
}
for (int leashedEntityID : pendingLeashedEntityIDs) {
NettyEntity<?> leashedEntity = playerData.entityFromID(leashedEntityID);
if (leashedEntity == null) {
if (EntityBypassRegistry.isBypassed(leashedEntityID)) {
insertedEntity.addLeashedEntity(leashedEntityID);
}
continue;
}
leashedEntity.setLeashingEntity(entityID);
insertedEntity.addLeashedEntity(leashedEntityID);
playerData.nettyData().removeUnresolvedLeash(entityID, leashedEntityID);
if (insertedEntity.isSelfEntity()) {
forceVisibleBecauseAttached(leashedEntity, playerData, leashedEntity.lastChecked(), "self-held unresolved leash");
}
}
}
private boolean keepingClientEntityWhenHidden(NettyEntity<?> entity, PlayerData data) {
if (entityConfig.keepClientEntityWhenHidden() == playerConfig.keepClientEntityWhenHidden()) {
return entityConfig.keepClientEntityWhenHidden();
}
EntityView<?> view = data.viewFromEntityID(entity.entityID());
return getCorrectConfig(view).keepClientEntityWhenHidden();
}
protected void resendPassengerStateIfClientVisible(NettyEntity<?> vehicle, PlayerData playerData) {
if (!vehicle.clientVisible() || (keepingClientEntityWhenHidden(vehicle, playerData) && !vehicle.visible())) {
return;
}
sendEntityPassengerPacket(vehicle.entityID(), collectClientVisiblePassengers(vehicle.passengerIDsNoAlloc(), playerData), playerData);
}
protected IntArrayList collectClientVisiblePassengers(final int[] passengerIDs, PlayerData playerData) {
// HackyEntityIDGuard reserves -1, so it cannot accidentally match an entity being shown.
return collectClientVisiblePassengers(passengerIDs, playerData, -1);
}
protected IntArrayList collectClientVisiblePassengers(final int[] passengerIDs, PlayerData playerData, int entityBeingShownID) {
int size = passengerIDs == null ? 0 : passengerIDs.length;
IntArrayList visiblePassengers = new IntArrayList(size);
if (passengerIDs == null) {
return visiblePassengers;
}
for (int passengerID : passengerIDs) {
if (EntityBypassRegistry.isBypassed(passengerID)) {
visiblePassengers.add(passengerID);
continue;
}
NettyEntity<?> passenger = playerData.entityFromID(passengerID);
if (passenger != null && ((passenger.clientVisible() && (!keepingClientEntityWhenHidden(passenger, playerData) || passenger.visible())) || passenger.entityID() == entityBeingShownID)) {
visiblePassengers.add(passengerID);
}
}
return visiblePassengers;
}
/**
* @return The created entity, with a default visibility of <code>true</code>. Must not return null. Does not insert the entity into any views, that is the responsibility of the caller.
*/
protected abstract NettyEntity<?> 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 processTrackedMetadata(P packet, NettyEntity<?> entity);
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, IntArrayList passengers, PlayerData playerData);
protected abstract void insertEntityToPlayerView(NettyEntity<?> entity, PlayerData playerData, UUID world);
protected abstract void insertEntityToEntityView(NettyEntity<?> entity, PlayerData playerData, UUID world);
}
@@ -0,0 +1,4 @@
short-git: ${short_git}
long-git: ${long_git}
build-time: ${build_time}
version: ${version}
@@ -0,0 +1,237 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright © 2026 Cubicake.
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
*/
package games.cubi.raycastedantiesp.core.chunks;
import games.cubi.raycastedantiesp.core.chunks.blocks.ByteArrayBlockChunkData;
import games.cubi.raycastedantiesp.core.chunks.blocks.CharArrayBlockChunkData;
import games.cubi.raycastedantiesp.core.chunks.blocks.FourBlockChunkData;
import games.cubi.raycastedantiesp.core.chunks.blocks.SingleBlockChunkData;
import games.cubi.raycastedantiesp.core.chunks.blocks.SixteenBlockChunkData;
import games.cubi.raycastedantiesp.core.chunks.blocks.TwoBlockChunkData;
import org.junit.jupiter.api.Test;
import java.util.function.IntPredicate;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class BlockChunkDataTest {
private static final BlockInfoResolver FIRST_255_OCCLUDING = resolver(blockStateID -> blockStateID >= 0 && blockStateID < 255);
private static final BlockInfoResolver ALL_SMALL_OCCLUDING = resolver(blockStateID -> blockStateID >= 0 && blockStateID < 512);
@Test
void factorySelectsSmallestRepresentations() {
assertInstanceOf(SingleBlockChunkData.class, fromStates(repeating(0), FIRST_255_OCCLUDING));
assertInstanceOf(TwoBlockChunkData.class, fromStates(repeating(0, 1), FIRST_255_OCCLUDING));
assertInstanceOf(FourBlockChunkData.class, fromStates(repeating(0, 1, 2, 3), FIRST_255_OCCLUDING));
assertInstanceOf(SixteenBlockChunkData.class, fromStates(repeating(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15), FIRST_255_OCCLUDING));
assertInstanceOf(ByteArrayBlockChunkData.class, fromStates(repeating(uniqueWithNonOccludingTail(256)), FIRST_255_OCCLUDING));
assertInstanceOf(CharArrayBlockChunkData.class, fromStates(repeating(uniqueWithNonOccludingTail(257)), FIRST_255_OCCLUDING));
}
@Test
void upgradesPreserveBlockIdsAndOcclusion() {
char[] expected = new char[ChunkData.BLOCK_COUNT];
BlockChunkData data = BlockChunkData.filled((char) 0, FIRST_255_OCCLUDING);
for (int packed = 1; packed <= 256; packed++) {
data = setPacked(data, packed, (char) packed);
expected[packed] = (char) packed;
if (packed == 1) {
assertInstanceOf(TwoBlockChunkData.class, data);
} else if (packed == 2 || packed == 3) {
assertInstanceOf(FourBlockChunkData.class, data);
} else if (packed >= 4 && packed <= 15) {
assertInstanceOf(SixteenBlockChunkData.class, data);
} else if (packed >= 16 && packed <= 255) {
assertInstanceOf(ByteArrayBlockChunkData.class, data);
} else {
assertInstanceOf(CharArrayBlockChunkData.class, data);
}
}
assertMatches(expected, data, FIRST_255_OCCLUDING);
}
@Test
void quarterByteWritesDoNotCorruptNeighboringCells() {
BlockChunkData data = fromStates(repeating(0, 1, 2, 3), FIRST_255_OCCLUDING);
assertInstanceOf(FourBlockChunkData.class, data);
data = setPacked(data, 0, (char) 2);
assertEquals(2, getPacked(data, 0));
assertEquals(1, getPacked(data, 1));
assertEquals(2, getPacked(data, 2));
assertEquals(3, getPacked(data, 3));
data = setPacked(data, 3, (char) 0);
assertEquals(2, getPacked(data, 0));
assertEquals(1, getPacked(data, 1));
assertEquals(2, getPacked(data, 2));
assertEquals(0, getPacked(data, 3));
}
@Test
void halfByteWritesDoNotCorruptNeighboringCells() {
BlockChunkData data = fromStates(repeating(0, 1, 2, 3, 4), FIRST_255_OCCLUDING);
assertInstanceOf(SixteenBlockChunkData.class, data);
data = setPacked(data, 0, (char) 4);
assertEquals(4, getPacked(data, 0));
assertEquals(1, getPacked(data, 1));
data = setPacked(data, 1, (char) 3);
assertEquals(4, getPacked(data, 0));
assertEquals(3, getPacked(data, 1));
}
@Test
void bytePaletteIndex255Works() {
char[] blockIDs = new char[ChunkData.BLOCK_COUNT];
for (int packed = 0; packed < 255; packed++) {
blockIDs[packed] = (char) packed;
}
blockIDs[255] = 1000;
BlockChunkData data = fromStates(blockIDs, FIRST_255_OCCLUDING);
assertInstanceOf(ByteArrayBlockChunkData.class, data);
assertEquals(254, getPacked(data, 254));
assertEquals(1000, getPacked(data, 255));
assertTrue(isOccludingPacked(data, 254));
assertFalse(isOccludingPacked(data, 255));
}
@Test
void allOccludingByteBoundaryStaysByteArray() {
char[] blockIDs = new char[ChunkData.BLOCK_COUNT];
for (int packed = 0; packed < 256; packed++) {
blockIDs[packed] = (char) packed;
}
BlockChunkData data = fromStates(blockIDs, ALL_SMALL_OCCLUDING);
assertInstanceOf(ByteArrayBlockChunkData.class, data);
for (int packed = 0; packed < 256; packed++) {
assertEquals(packed, getPacked(data, packed));
assertTrue(isOccludingPacked(data, packed));
}
}
@Test
void palettedOcclusionDoesNotDependOnPaletteAppendOrder() {
BlockInfoResolver oddOccluding = resolver(blockStateID -> (blockStateID & 1) == 1);
char[] blockIDs = repeating(2, 1, 4, 3);
BlockChunkData data = fromStates(blockIDs, oddOccluding);
assertInstanceOf(FourBlockChunkData.class, data);
assertMatches(blockIDs, data, oddOccluding);
}
@Test
void invalidLocalCoordinatesThrow() {
BlockChunkData single = BlockChunkData.filled((char) 0, FIRST_255_OCCLUDING);
assertThrows(IllegalArgumentException.class, () -> single.getBlockID(-1, 0, 0));
assertThrows(IllegalArgumentException.class, () -> single.setBlockID(0, 16, 0, (char) 0, FIRST_255_OCCLUDING));
assertThrows(IllegalArgumentException.class, () -> single.isOccludingLocal(0, 0, 16));
BlockChunkData paletted = fromStates(repeating(0, 1, 2, 3), FIRST_255_OCCLUDING);
assertThrows(IllegalArgumentException.class, () -> paletted.getBlockID(-1, 0, 0));
assertThrows(IllegalArgumentException.class, () -> paletted.setBlockID(0, 16, 0, (char) 2, FIRST_255_OCCLUDING));
assertThrows(IllegalArgumentException.class, () -> paletted.isOccludingLocal(0, 0, 16));
}
@Test
void paletteFactoryDiscardsUnusedEntriesAndUsesCorePackedPositions() {
char[] sourcePalette = {(char) 0, (char) 7, (char) 8, (char) 9};
int target = ChunkData.packUncheckedGuarded(3, 2, 1);
BlockChunkData data = BlockChunkData.copyOfPalette(sourcePalette, packed -> packed == target ? 2 : 1, FIRST_255_OCCLUDING);
assertInstanceOf(TwoBlockChunkData.class, data);
assertEquals(8, data.getBlockID(3, 2, 1));
assertEquals(7, data.getBlockID(1, 2, 3));
}
private static BlockInfoResolver resolver(IntPredicate occluding) {
return new BlockInfoResolver() {
@Override
public boolean isOccluding(int blockStateID) {
return occluding.test(blockStateID);
}
@Override
public boolean isTileEntity(int blockStateID) {
return false;
}
@Override
public boolean hasBlockEntityData(int blockStateID) {
return false;
}
};
}
private static BlockChunkData fromStates(char[] blockIDs, BlockInfoResolver blockInfoResolver) {
return BlockChunkData.copyOfStates(packed -> blockIDs[packed], blockInfoResolver);
}
private static char[] repeating(int... blockIDs) {
char[] converted = new char[blockIDs.length];
for (int i = 0; i < blockIDs.length; i++) {
converted[i] = (char) blockIDs[i];
}
return repeating(converted);
}
private static char[] repeating(char[] blockIDs) {
char[] data = new char[ChunkData.BLOCK_COUNT];
for (int packed = 0; packed < data.length; packed++) {
data[packed] = blockIDs[packed % blockIDs.length];
}
return data;
}
private static char[] uniqueWithNonOccludingTail(int uniqueCount) {
char[] blockIDs = new char[uniqueCount];
int occludingCount = Math.min(uniqueCount, 255);
for (int i = 0; i < occludingCount; i++) {
blockIDs[i] = (char) i;
}
for (int i = occludingCount; i < uniqueCount; i++) {
blockIDs[i] = (char) (1000 + i);
}
return blockIDs;
}
private static BlockChunkData setPacked(BlockChunkData data, int packed, char blockID) {
return data.setBlockID(ChunkData.unpackX(packed), ChunkData.unpackY(packed), ChunkData.unpackZ(packed), blockID, FIRST_255_OCCLUDING);
}
private static char getPacked(BlockChunkData data, int packed) {
return data.getBlockID(ChunkData.unpackX(packed), ChunkData.unpackY(packed), ChunkData.unpackZ(packed));
}
private static boolean isOccludingPacked(BlockChunkData data, int packed) {
return data.isOccludingLocal(ChunkData.unpackX(packed), ChunkData.unpackY(packed), ChunkData.unpackZ(packed));
}
private static void assertMatches(char[] expected, BlockChunkData data, BlockInfoResolver blockInfoResolver) {
for (int packed = 0; packed < expected.length; packed++) {
int packedIndex = packed;
char expectedBlockID = expected[packed];
assertEquals(expectedBlockID, getPacked(data, packed), () -> "block ID mismatch at packed index " + packedIndex);
assertEquals(blockInfoResolver.isOccluding(expectedBlockID), isOccludingPacked(data, packed), () -> "occlusion mismatch at packed index " + packedIndex);
}
}
}
@@ -0,0 +1,461 @@
package games.cubi.raycastedantiesp.core.config;
import games.cubi.raycastedantiesp.core.config.engine.EngineMode;
import games.cubi.raycastedantiesp.core.config.raycast.BlockSelector;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.spongepowered.configurate.CommentedConfigurationNode;
import org.spongepowered.configurate.NodePath;
import org.spongepowered.configurate.loader.HeaderMode;
import org.spongepowered.configurate.serialize.SerializationException;
import org.spongepowered.configurate.yaml.NodeStyle;
import org.spongepowered.configurate.yaml.YamlConfigurationLoader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class ConfigManagerTest {
@TempDir
Path directory;
@Test
void freshConfigLoadsInTwoPhasesFromCodeDefaults() {
ConfigManager manager = new ConfigManager(directory);
assertEquals(LoggingConfig.DEFAULT, manager.getLoggingConfig());
assertFalse(Files.exists(configPath()));
manager.loadLoggingConfig();
assertEquals(RootConfig.DEFAULT.loggingConfig(), manager.getLoggingConfig());
assertThrows(IllegalStateException.class, manager::getDebugConfig);
assertThrows(IllegalStateException.class, manager::getConfigValues);
manager.completeInitialLoad();
assertEquals(RootConfig.DEFAULT.debugConfig(), manager.getDebugConfig());
assertEquals(RootConfig.DEFAULT.engineConfig(), manager.getEngineConfig());
assertEquals(RootConfig.DEFAULT.checksConfig().playerConfig(), manager.getPlayerConfig());
assertTrue(Files.isRegularFile(configPath()));
}
@Test
void lateCompletionCanOnlyRunOnce() {
ConfigManager manager = earlyManager();
manager.completeInitialLoad();
assertThrows(IllegalStateException.class, manager::completeInitialLoad);
}
@Test
void malformedSectionsUseTheirDefaultsWithoutLosingOtherOverrides() throws IOException {
CommentedConfigurationNode node = defaultNode();
boolean particles = !RootConfig.DEFAULT.debugConfig().particles();
node.node("logging").raw("invalid");
node.node("updates").raw(List.of("invalid"));
node.node("checks", "player").comment("User-authored comment").raw("invalid");
node.node("debug", "particles").raw(particles);
saveNode(node);
ConfigManager manager = earlyManager();
assertEquals(LoggingConfig.DEFAULT, manager.getLoggingConfig());
manager.completeInitialLoad();
assertEquals(UpdateConfig.DEFAULT, manager.getUpdateConfig());
assertEquals(RootConfig.DEFAULT.checksConfig().playerConfig(), manager.getPlayerConfig());
assertEquals(particles, manager.getDebugConfig().particles());
assertEquals("User-authored comment", loadNode().node("checks", "player").comment());
}
@Test
void commandRepairsScalarAndListSectionsBeforePublishing() {
ConfigManager manager = earlyManager();
manager.completeInitialLoad();
for (String path : List.of("logging", "updates", "checks.player")) {
for (String rawValue : List.of("invalid", "[invalid]")) {
ConfigManager.SetConfigResult result = manager.setConfigValue(path, rawValue);
assertTrue(result.success(), path + ": " + rawValue);
assertTrue(result.repaired(), path + ": " + rawValue);
assertEquals(LoggingConfig.DEFAULT, manager.getLoggingConfig());
assertEquals(UpdateConfig.DEFAULT, manager.getUpdateConfig());
assertEquals(RootConfig.DEFAULT.checksConfig().playerConfig(), manager.getPlayerConfig());
}
}
}
@Test
void invalidValueAndCrossFieldViolationRepairOnlyTheirFields() throws IOException {
ConfigManager manager = earlyManager();
CommentedConfigurationNode node = loadNode();
Object unrelatedValue = node.node("updates", "notify-in-game").raw();
node.node("block-processor", "track-all-blocks").raw(false);
node.node("checks", "chunk-section", "enabled").raw(true);
saveNode(node);
manager.completeInitialLoad();
ConfigManager.SetConfigResult result = manager.setConfigValue("engine.async.processing-threads", "0");
assertTrue(result.success());
assertTrue(result.repaired());
assertEquals(RootConfig.DEFAULT.engineConfig().asyncConfig(), manager.getEngineConfig().asyncConfig());
assertEquals(RootConfig.DEFAULT.checksConfig().chunkSectionConfig().enabled(), manager.getChunkSectionConfig().enabled());
assertEquals(unrelatedValue, loadNode().node("updates", "notify-in-game").raw());
}
@Test
void invalidListElementResetsItsListWithoutLosingOtherOverrides() throws IOException {
ConfigManager manager = earlyManager();
CommentedConfigurationNode node = loadNode();
boolean onlyCheckSneaking = !RootConfig.DEFAULT.checksConfig().playerConfig().onlyCheckSneaking();
node.node("checks", "entity", "excluded-types").raw(List.of(1));
node.node("checks", "player", "only-check-sneaking").raw(onlyCheckSneaking);
saveNode(node);
manager.completeInitialLoad();
assertEquals(RootConfig.DEFAULT.checksConfig().entityConfig().excludedTypes(), manager.getEntityConfig().excludedTypes());
assertEquals(onlyCheckSneaking, manager.getPlayerConfig().onlyCheckSneaking());
}
@Test
void invalidBlockSelectorResetsItsListWithoutLosingOtherOverrides() throws IOException {
ConfigManager manager = earlyManager();
CommentedConfigurationNode node = loadNode();
boolean onlyCheckSneaking = !RootConfig.DEFAULT.checksConfig().playerConfig().onlyCheckSneaking();
node.node("checks", "tile-entity", "excluded-blocks").raw(List.of("minecraft:chest[]"));
node.node("checks", "player", "only-check-sneaking").raw(onlyCheckSneaking);
saveNode(node);
manager.completeInitialLoad();
assertEquals(RootConfig.DEFAULT.checksConfig().tileEntityConfig().excludedBlocks(), manager.getTileEntityConfig().excludedBlocks());
assertEquals(onlyCheckSneaking, manager.getPlayerConfig().onlyCheckSneaking());
}
@Test
void excludedBlockMutationIsSavedForRestartWithoutChangingActiveSnapshot() throws IOException {
ConfigManager manager = earlyManager();
manager.completeInitialLoad();
BlockSelector added = BlockSelector.parse("example:block");
ConfigManager.SetConfigResult result = manager.addConfigListValue("checks.tile-entity.excluded-blocks", added.toString());
assertTrue(result.success());
assertTrue(result.restartRequired());
assertEquals(RootConfig.DEFAULT.checksConfig().tileEntityConfig().excludedBlocks(), manager.getTileEntityConfig().excludedBlocks());
assertTrue(loadNode().node("checks", "tile-entity", "excluded-blocks").getList(String.class).contains(added.toString()));
}
@Test
void migrationPrefersExistingDestinationAndPreservesUnrelatedValues() throws IOException {
CommentedConfigurationNode node = defaultNode();
byte destinationLevel = differentValidLevel(RootConfig.DEFAULT.loggingConfig().info().level());
byte legacyLevel = differentValidLevel(destinationLevel);
boolean soundEnabled = !RootConfig.DEFAULT.checksConfig().soundEffectsConfig().enabled();
String unknownValue = "preserve-me";
node.node("config-version").raw("2.0");
node.node("logging", "info", "level").raw(destinationLevel);
node.node("debug", "info-level").raw(legacyLevel);
node.node("checks", "sound-effects", "enabled").raw(soundEnabled);
node.node("checks", "tile-entity", "excluded-blocks").raw(null);
node.node("unknown-setting").raw(unknownValue);
node.node("block-processor", "packetevents", "tile-entity-exempted-ids").raw(List.of(1));
saveNode(node);
ConfigManager manager = earlyManager();
manager.completeInitialLoad();
CommentedConfigurationNode migrated = loadNode();
assertEquals(destinationLevel, manager.getLoggingConfig().info().level());
assertEquals(soundEnabled, manager.getSoundEffectsConfig().enabled());
assertEquals(RootConfig.CURRENT_VERSION, migrated.node("config-version").getString());
assertTrue(migrated.node("debug", "info-level").virtual());
assertTrue(migrated.node("block-processor", "packetevents").virtual());
assertEquals(
RootConfig.DEFAULT.checksConfig().tileEntityConfig().excludedBlocks().stream().map(BlockSelector::toString).toList(),
migrated.node("checks", "tile-entity", "excluded-blocks").getList(String.class)
);
assertEquals(unknownValue, migrated.node("unknown-setting").getString());
String afterMigration = Files.readString(configPath());
manager.load();
assertEquals(afterMigration, Files.readString(configPath()));
}
@Test
void acceptedEnumSpellingsArePersistedCanonically() throws IOException {
CommentedConfigurationNode node = defaultNode();
node.node("engine", "mode").raw("SiMpLe");
node.node("block-processor", "mode").raw(
RootConfig.DEFAULT.blockProcessorConfig().mode().getName().toUpperCase(java.util.Locale.ROOT)
);
saveNode(node);
ConfigManager manager = earlyManager();
manager.completeInitialLoad();
CommentedConfigurationNode canonical = loadNode();
assertEquals(EngineMode.ASYNC, manager.getEngineConfig().mode());
assertEquals(EngineMode.ASYNC.getName(), canonical.node("engine", "mode").raw());
assertEquals(
RootConfig.DEFAULT.blockProcessorConfig().mode().getName(),
canonical.node("block-processor", "mode").raw()
);
}
@Test
void invalidScalarShapeAndEnumUseTheirFieldDefaults() {
ConfigManager manager = earlyManager();
manager.completeInitialLoad();
ConfigManager.SetConfigResult scalarResult = manager.setConfigValue("debug.timings", "{invalid: shape}");
ConfigManager.SetConfigResult enumResult = manager.setConfigValue("engine.mode", "definitely-invalid");
assertTrue(scalarResult.success());
assertTrue(scalarResult.repaired());
assertEquals(RootConfig.DEFAULT.debugConfig().timings(), manager.getDebugConfig().timings());
assertTrue(enumResult.success());
assertTrue(enumResult.repaired());
assertEquals(RootConfig.DEFAULT.engineConfig().mode(), manager.getEngineConfig().mode());
}
@Test
void commandSectionsFillMissingFieldsAndNullUsesTheFieldDefault() {
ConfigManager manager = earlyManager();
manager.completeInitialLoad();
boolean particles = !RootConfig.DEFAULT.debugConfig().particles();
ConfigManager.SetConfigResult sectionResult = manager.setConfigValue(
"debug",
"{particles: " + particles + "}"
);
ConfigManager.SetConfigResult nullResult = manager.setConfigValue("updates.notify-in-game", "null");
assertTrue(sectionResult.success());
assertEquals(particles, manager.getDebugConfig().particles());
assertEquals(RootConfig.DEFAULT.debugConfig().timings(), manager.getDebugConfig().timings());
assertTrue(nullResult.success());
assertTrue(nullResult.repaired());
assertEquals(RootConfig.DEFAULT.updateConfig().notifyInGame(), manager.getUpdateConfig().notifyInGame());
}
@Test
void fatalReloadRetainsActiveSnapshotAndDoesNotRewriteFile() throws IOException {
ConfigManager manager = earlyManager();
manager.completeInitialLoad();
LoggingConfig activeLogging = manager.getLoggingConfig();
CommentedConfigurationNode node = loadNode();
String unsupportedVersion = RootConfig.CURRENT_VERSION + "-future";
node.node("config-version").raw(unsupportedVersion);
saveNode(node);
String beforeReload = Files.readString(configPath());
assertThrows(ConfigLoadException.class, manager::load);
assertEquals(activeLogging, manager.getLoggingConfig());
assertEquals(beforeReload, Files.readString(configPath()));
}
@Test
void commandCannotPublishAnUnsupportedVersion() throws IOException {
ConfigManager manager = earlyManager();
manager.completeInitialLoad();
String beforeMutation = Files.readString(configPath());
ConfigManager.SetConfigResult result = manager.setConfigValue(
"config-version",
"'" + RootConfig.CURRENT_VERSION + "-future'"
);
assertFalse(result.success());
assertEquals(beforeMutation, Files.readString(configPath()));
assertEquals(RootConfig.CURRENT_VERSION, manager.getConfigValues().get("config-version"));
}
@Test
void malformedYamlIsNotOverwritten() throws IOException {
String malformed = "invalid: [";
Files.writeString(configPath(), malformed);
ConfigManager manager = new ConfigManager(directory);
assertThrows(ConfigLoadException.class, manager::loadLoggingConfig);
assertEquals(malformed, Files.readString(configPath()));
}
@Test
void missingMappedCommentsArePersisted() throws IOException {
CommentedConfigurationNode node = defaultNode();
CommentedPath expected = firstComment(node, NodePath.path());
clearComments(node);
saveNode(node);
ConfigManager manager = earlyManager();
manager.completeInitialLoad();
assertEquals(expected.comment(), loadNode().node(expected.path().array()).comment());
}
@Test
void freshConfigWritesGuidanceAboveIndividualEntries() throws IOException {
ConfigManager manager = earlyManager();
manager.completeInitialLoad();
CommentedConfigurationNode defaults = defaultNode().node("checks", "entity", "excluded-types");
CommentedConfigurationNode saved = loadNode().node("checks", "entity", "excluded-types");
List<String> lines = Files.readAllLines(configPath()).stream().map(String::strip).toList();
assertEquals(defaults.raw(), saved.raw());
for (int index = 0; index < defaults.childrenList().size(); index++) {
String comment = defaults.node(index).comment();
assertEquals(comment, saved.node(index).comment());
if (comment != null) {
String[] commentLines = comment.split("\\R");
int line = lines.indexOf("# " + commentLines[commentLines.length - 1]);
assertTrue(line >= 0);
assertEquals("- " + defaults.node(index).getString(), lines.get(line + 1));
}
}
}
@Test
void missingEntryCommentsArePersistedWithoutOtherChanges() throws IOException {
CommentedConfigurationNode node = defaultNode();
CommentedConfigurationNode list = node.node("checks", "entity", "excluded-types");
for (CommentedConfigurationNode child : list.childrenList()) {
child.comment(null);
}
saveNode(node);
ConfigManager manager = earlyManager();
manager.completeInitialLoad();
CommentedConfigurationNode defaults = defaultNode().node("checks", "entity", "excluded-types");
CommentedConfigurationNode saved = loadNode().node("checks", "entity", "excluded-types");
assertEquals(defaults.raw(), saved.raw());
for (int index = 0; index < defaults.childrenList().size(); index++) {
assertEquals(defaults.node(index).comment(), saved.node(index).comment());
}
String content = Files.readString(configPath());
Files.setLastModifiedTime(configPath(), FileTime.fromMillis(1_000));
FileTime modified = Files.getLastModifiedTime(configPath());
manager.load();
assertEquals(content, Files.readString(configPath()));
assertEquals(modified, Files.getLastModifiedTime(configPath()));
}
@Test
void entryCommentMergePreservesReorderedSubsetAndUserComments() throws IOException {
CommentedConfigurationNode node = defaultNode();
CommentedConfigurationNode list = node.node("checks", "entity", "excluded-types");
List<String> values = List.of("minecraft:block_display", "minecraft:arrow", "example:custom", "minecraft:potion", "minecraft:wither");
list.raw(values);
clearComments(list);
list.comment("Existing consolidated guidance");
list.node(1).comment("User-authored projectile guidance");
list.node(2).comment("User-authored custom entry guidance");
saveNode(node);
ConfigManager manager = earlyManager();
manager.completeInitialLoad();
CommentedConfigurationNode saved = loadNode().node("checks", "entity", "excluded-types");
CommentedConfigurationNode defaults = defaultNode().node("checks", "entity", "excluded-types");
assertEquals(values, saved.getList(String.class));
assertEquals("Existing consolidated guidance", saved.comment());
assertEquals("User-authored projectile guidance", saved.node(1).comment());
assertEquals("User-authored custom entry guidance", saved.node(2).comment());
assertNull(saved.node(4).comment());
for (CommentedConfigurationNode child : defaults.childrenList()) {
if (values.get(0).equals(child.getString())) {
assertEquals(child.comment(), saved.node(0).comment());
} else if (values.get(3).equals(child.getString())) {
assertEquals(child.comment(), saved.node(3).comment());
}
}
}
private ConfigManager earlyManager() {
ConfigManager manager = new ConfigManager(directory);
manager.loadLoggingConfig();
return manager;
}
private Path configPath() {
return directory.resolve("config.yml");
}
private CommentedConfigurationNode defaultNode() {
CommentedConfigurationNode node = YamlConfigurationLoader.builder()
.defaultOptions(ConfigMapping.options())
.build()
.createNode();
try {
node.set(RootConfig.class, RootConfig.DEFAULT);
} catch (SerializationException e) {
throw new AssertionError("Code defaults must serialize", e);
}
return node;
}
private CommentedConfigurationNode loadNode() throws IOException {
return loader().load();
}
private void saveNode(CommentedConfigurationNode node) throws IOException {
loader().save(node);
}
private YamlConfigurationLoader loader() {
return YamlConfigurationLoader.builder()
.path(configPath())
.nodeStyle(NodeStyle.BLOCK)
.headerMode(HeaderMode.PRESERVE)
.defaultOptions(ConfigMapping.options())
.build();
}
private byte differentValidLevel(byte level) {
return level == 0 ? (byte) 1 : (byte) 0;
}
private CommentedPath firstComment(CommentedConfigurationNode node, NodePath path) {
if (node.comment() != null) {
return new CommentedPath(path, node.comment());
}
for (var entry : node.childrenMap().entrySet()) {
CommentedPath found = firstComment(
(CommentedConfigurationNode) entry.getValue(),
path.plus(NodePath.path(entry.getKey()))
);
if (found != null) {
return found;
}
}
return null;
}
private void clearComments(CommentedConfigurationNode node) {
node.comment(null);
for (var child : node.childrenMap().values()) {
clearComments((CommentedConfigurationNode) child);
}
for (var child : node.childrenList()) {
clearComments((CommentedConfigurationNode) child);
}
}
private record CommentedPath(NodePath path, String comment) {
}
}
Loaded 100 of 220 files, more files were not shown because too many files have changed in this diff. Show more