Compare commits

...
143 Commits
Author SHA1 Message Date
wizjany 1cff55f355 Release 7.0.6. 2021-09-16 18:45:05 -04:00
wizjany f4fb78c7f5 Changelog for 7.0.6. 2021-09-16 18:44:42 -04:00
wizjany 56086b0878 Protect light from everything.
Thanks Mojang.
2021-09-16 14:54:36 -04:00
wizjany 51fa25dd03 Protect light from light.
Closes #1828.
2021-09-13 19:12:54 -04:00
wizjany 5b0fdb6801 Include GLOW_ITEM_FRAME in item-frame-rotation flag.
Closes #1832.
2021-09-13 18:57:33 -04:00
stonar96 cb69ab73a7 Fix perms NPE 2021-08-31 16:49:40 -04:00
stonar96 5a6b6eb81b Use QueryOption.SORT for region commands (#1817) 2021-08-22 10:14:40 -04:00
stonar96 75774dbbb0 Fix redefinition of parent regions (#1814) 2021-08-15 17:19:01 -04:00
wizjany fe0fd17d37 Cover additional case for blacklist on-equip. 2021-08-15 11:06:27 -04:00
stonar96 5e702f80a6 Add inheritance for all flags (#1787) 2021-08-08 23:00:02 -04:00
Wyatt Childers 0165175a2e Additionally block other explosion if the defender is a block like entity to be consitent with "block" explosion protections (#1812) 2021-08-08 22:58:34 -04:00
wizjany 821c3e689e Convert listeners to use AbstractListener and add shortcuts to get config. (#1808)
Closes #1780.
2021-08-08 22:58:22 -04:00
stonar96andwizjany 4644268214 Fix member inheritance for non-player associables (#1804)
* Add options to query region sets unsorted and without parents

* Fix member inheritance for non-player associables

* Add member inheritance for non-player associables

* Rename Option to QueryOption, remove functional definitions, bit of cleanup.

Co-authored-by: wizjany <wizjany@gmail.com>
2021-08-08 22:58:09 -04:00
wizjany c81f5892eb Add jsr305 back for annotations.
Blame those pesky WorldEdit devs breaking our builds :^)
2021-08-02 13:21:33 -04:00
LoaiDev 88854592ce Fix handlers order when registering one with after.
I am not sure exactly if this is the source of the problem, but when i tried registering my handlers using ExitFlag.FACTORY as "after" like how the javadocs said it, it seemed that my handler was running before the ExitFlag handler which means mine will run even if ExitFlag returns false. I used null as after and it worked then. Maybe i understand the "after" incorrectly but in my mind my customHandler should run after the "after" not the other way around if that makes sense. Let me know if I didn't undertstand it correctly.
Sorry for my english!
2021-08-01 16:59:56 -04:00
wizjany 8efc2e6539 Revert "Add member inheritance for non-player associables"
This reverts commit b1cd1303d1.
2021-07-25 23:31:44 -04:00
stonar96 b1cd1303d1 Add member inheritance for non-player associables 2021-07-25 10:06:09 -04:00
wizjany c98f9eda7e Check all effects for lingering potion clouds.
Fixes #1797.
2021-07-24 11:36:25 -04:00
JOO200 682942b965 Added NPE error message and javadoc hint for WorldGuard.getPlatform 2021-07-15 19:48:34 +02:00
JOO200 7e817c3330 Protect signs against usage of (glowing) ink sac 2021-07-10 11:09:05 +02:00
wizjany 5302bcb132 Changelog for 7.0.6 beta 1. 2021-07-07 10:17:08 -04:00
stonar96 bcac63dcaa Fix regions in negative heights (#1792) 2021-07-07 10:17:08 -04:00
JOO200 37906c0fc4 Added use-dripleaf flag, Handle Deepslate Redstone Ore correctly 2021-07-07 10:17:08 -04:00
wizjany 6879f10de6 Fix crop growth config option. 2021-07-07 10:17:08 -04:00
JOO200 7155ef5833 Protect cave vines and glow berries correctly 2021-07-07 10:17:08 -04:00
JOO200 e2f775c952 Fixed wrong dependencies, removed not needed repository 2021-07-07 10:17:08 -04:00
JOO200 c5dad7476d Compare items for /stack with ItemStack.isSimilar 2021-07-07 10:17:08 -04:00
JOO200 4dfb9bea38 Switch back dependency from Spigot to Paper 2021-07-07 10:17:08 -04:00
JOO200 7436d5064e Fixed incorrectly shaded squirrelid 2021-07-07 10:17:08 -04:00
JOO200 621c1289b3 Bump squirrelid to 0.3.0, Deprecated PaperProfileServer (replaced by squirrelid) 2021-07-07 10:17:08 -04:00
JOO200 093e282e13 relocate bstats like worldedit 2021-07-07 10:17:08 -04:00
JOO200 2958c2526c Shade correctly bstats 2021-07-07 10:17:08 -04:00
wizjany d21ee98624 Re-add shade config, fix some other gradle black magic. 2021-07-07 10:17:08 -04:00
wizjany dd90fa21c7 Cover item dispense behaviors.
Depends on spigot throwing events.
2021-07-07 10:17:08 -04:00
JOO200 34ed6175e5 Bump api version to 1.17 2021-07-07 10:17:08 -04:00
JOO200 0818b3c262 Update to Java 16, Gradle 7.0.2 and Bstats 2.1.0 2021-07-07 10:17:08 -04:00
JOO200 04541ed5a6 Updated build environment, switched to Jupiter Unit Tests 2021-07-07 10:17:08 -04:00
JOO200 f17f1fc8c8 bump travis-ci to jdk11 2021-07-07 10:17:08 -04:00
JOO200 9defab65d1 Fix protections for copper and rooted dirt 2021-07-07 10:17:08 -04:00
JOO200 a225d1b2d3 Added 1.17 materials 2021-07-07 10:17:08 -04:00
JOO200 bcab33c12c Updated dependencies and gradle 2021-07-07 10:17:08 -04:00
JOO200 3cb83465d1 Update dependencies to 1.17 2021-07-07 10:17:08 -04:00
wizjany 32d16a7eaa Bump to snapshot. 2021-06-07 23:03:37 -04:00
wizjany 3827266eb3 Release 7.0.5. 2021-06-07 22:52:20 -04:00
wizjany c3dbfdd699 Changelog for 7.0.5. 2021-06-07 22:49:23 -04:00
wizjany f19ebab0e1 Handle spigot's entity mount event (#1755)
* Add handler for spigot's EntityMountEvent.

Closes #1677.

* checkstyle.
2021-06-06 19:34:26 -04:00
stonar96andwizjany f8f95a44f0 Fix Iron Doors (#1781)
Co-authored-by: wizjany <wizjany@gmail.com>
2021-06-06 19:30:40 -04:00
stonar96 0a74d02fc9 Add nonplayer-protection-domains flag (#1763) 2021-06-06 19:28:00 -04:00
stonar96 46a662e1a7 Fix Dispenser Shulker Box bug and cleanup (#1776) 2021-06-06 19:27:48 -04:00
stonar96 149d1f84e8 Remove unused RegionGroup.MEMBERS from the teleport flag (#1769) 2021-05-23 12:37:06 -04:00
stonar96andwizjany c4e76af5f4 Fix Cause#isKnown() (#1768)
* Fix Cause#isKnown()

* Grammar

Co-authored-by: wizjany <wizjany@gmail.com>
2021-05-15 15:03:55 -04:00
stonar96 c1c26360e3 Remove unnecessary FlagValueCalculator#getPriority(ProtectedRegion) calls 2021-05-15 15:03:02 -04:00
stonar96 65c894cfe9 Fix doc comment of FlagValueCalculator#getMembership(RegionAssociable) 2021-05-15 15:02:08 -04:00
TheBusyBiscuitandwizjany 7dcec2b3b4 Small performance improvement for PlayerDomain#contains() (#1765)
* Improve performance by putting UUID checks first.

* Added wizjany's suggestion

Co-authored-by: wizjany <wizjany@gmail.com>
2021-05-15 15:01:15 -04:00
stonar96 09ce3b6373 Update Java version in CONTRIBUTING.md (#1764) 2021-05-10 11:22:38 +10:00
wizjany de22a5cd25 Deprecate and immediately void setMin/MaxPoint in ProtectedCuboidRegion.
Not sure why these were here to begin with, Poly doesn't have them either
and mutating regions after creation leads to undefined behavior.
2021-04-12 14:18:11 -04:00
JOO200 d2c2bfbab2 Deprecate flags (replaced by RegistryFlag), added some null checks (#1747) 2021-04-10 13:58:39 -04:00
wizjany 528ba32a93 Also change paperlib to shade.
This change has been sitting here for a while uncommitted and unpushed.
2021-03-06 15:36:25 -05:00
JOO200 f37fbb1ae8 Fix Falling blocks may change snow layers to that block 2021-03-06 15:31:06 -05:00
wizjany f1f8b625a8 Gradle cleanup/unfuckery.
Fixes #1729
2021-02-10 15:21:03 -05:00
wizjany e933050436 Change relocated/shaded artifacts to compileOnly. 2021-02-10 13:33:48 -05:00
wizjany 59d4c7b96d Fix nullability annotation. 2021-02-10 00:02:28 -05:00
Shane Freeder 0c7f4bb8f7 Fix TimedHandler not calling delegated handler (#1727)
The original commit was calling super, which means that the actual
registered handlers were not called, also, added getInvincibility
which was originally missing
2021-02-09 23:48:03 -05:00
wizjany 3c9b21d01f Add timings to third-party session handlers (#1717)
* Add Timings for third-party session handlers.

These often cause WorldGuard to get blamed by timings.

* Add config option to turn off extra timings.

* Move relocation to the right build file.

* Move config to a map for potential future expansion.

* Calculate timing immediately per-factory.

Instead of on each handler creation.
2021-02-06 11:10:04 -05:00
wizjany aeea455560 Ignore BlockFertilizeEvent with empty list.
Plugins can clear this list without fully cancelling the event.
Fixes #1723
2021-02-06 10:58:29 -05:00
wizjany 129d27351a Don't send empty messages from chorus-fruit/enderpearl teleports. 2021-02-02 19:44:38 -05:00
wizjany 310ce9a662 Make UUIDFlag ctors public.
smh.
2021-01-26 16:18:07 -05:00
kikelkik e04c654cde Added arguments to /rg toggle-bypass: on, off 2021-01-23 22:01:28 -05:00
JOO200 b1674e5cb7 Added test cases for FlagValueCalculator and MapFlags 2021-01-23 21:43:44 -05:00
JOO200 89c6a33b90 Improved queryMapValue to return defaultValue instead of null 2021-01-23 21:43:44 -05:00
JOO200 88c91ce3fc Add fallback value to queryMapValue, use Flag$chooseValue 2021-01-23 21:43:44 -05:00
JOO200 b70f5a73ce Added methods to query values from map flags 2021-01-23 21:43:44 -05:00
JOO200 b6fc9ddd93 Add UUIDFlag 2021-01-23 21:33:29 -05:00
wizjany cbb3212082 Don't throw error when swapping armor slots into the offhand.
Lots of conflicting info here, but the offhand slot is in fact part of
the quickbar/hotbar (yay bukkit naming) but does *not* use a hotbar "button",
since it has its own hotkey (i.e., F by default instead of 0-8).
The result is a hotbar_swap *action* with a swap_offhand *clicktype*.

Fixes #1698.
2021-01-09 18:16:40 -05:00
Intelli 04d5a3b437 Fixed NoClassDefFoundError if WorldEdit failed to initialize 2021-01-03 17:46:29 -05:00
Matthew Millerandwizjany 282425f3cf Move the Mob Blocker feature from CraftBook to WorldGuard (#1695)
* Move the Mob Blocker feature from CraftBook to WorldGuard

* Formatting.

Co-authored-by: wizjany <wizjany@gmail.com>
2020-12-31 10:51:49 +10:00
wizjany 15a08097ae Small readme tweaks.
Fix dead/outdated links, clarify deps.
2020-12-09 11:28:13 -05:00
wizjany 035a645de0 Deal with bamboo as growth from spread event listener.
Closes #1673, #1674.
2020-11-27 09:10:28 -05:00
wizjany 59c146f59a Don't allow setting unknown flags in FlagHelperBox. 2020-11-17 18:53:22 -05:00
wizjany d313f2caad Add nether warts to crop list.
Closes #1669.
2020-11-17 18:50:35 -05:00
wizjany 8350267b10 Don't marshal SetFlag in FlagHelperBox. 2020-11-17 18:50:35 -05:00
JOO200 e98196af40 Catch Throwables instead of Exceptions while (un)marshalling flags 2020-11-17 17:17:26 -05:00
wizjany 3879772103 Move /rg bypass perm check inside the command.
Using @CommandPermissions would cause the root command to be excluded
from the client. This is a temp workaround until piston/proper perms
are somehow implemented.
2020-11-17 16:36:36 -05:00
wizjany 48233c3327 Make resource processing update with project version.
Should prevent old version strings from finding their way into plugin.yml
2020-11-03 14:42:39 -05:00
wizjany 664ab18f00 Fix sponge-simulation clearing NBT of waterlogged blocks.
Fixes #1659.
Didn't realize people still used this feature.
2020-10-23 23:41:56 -04:00
Matthew Miller 07bf1871ab Add an SVG logo 2020-10-23 21:44:09 +10:00
JOO200 5921be432c Change anvil usage to build permissions and add use-anvil flag (#1644) 2020-10-17 17:51:39 -04:00
wizjany 60b16fc4c7 Add sweet berry bush to crop list. 2020-09-26 22:16:19 -04:00
wizjany 746b630d01 Note the new region converter class for devs. 2020-09-26 16:05:27 -04:00
wizjany 0b362088f4 Bump to snapshot version. 2020-09-26 12:57:03 -04:00
wizjany 014277fb2f Release 7.0.4. 2020-09-26 12:55:18 -04:00
wizjany f7ff984c34 Update changelog for release. 2020-09-26 12:46:20 -04:00
Pisich d4b2060766 Removed extra ";" 2020-09-26 12:06:06 -04:00
JOO200 0e73b50d6f Moved default bypass options to global configuration section 2020-09-16 13:34:56 -04:00
JOO200 136ec31f38 Add configurable announcement for current bypass status 2020-09-16 13:34:56 -04:00
JOO200andwizjany ad000ab051 Rename config option for default bypass option
Co-authored-by: wizjany <wizjany@gmail.com>
2020-09-16 13:34:56 -04:00
JOO200 af67f1dd6a Add config option to deny region bypass by default 2020-09-16 13:34:56 -04:00
wizjany 8dee2ad3b8 Don't check ride for unsaddled striders. 2020-09-11 20:44:47 -04:00
wizjany c860fce299 Document ProtectedRegion's comparable behavior.
ProtectedRegion's compareTo is inconsistent with equals when comparing regions across managers.
2020-09-09 15:16:15 -04:00
wizjany 0cb84927a3 Don't fire xp spawn events for fishing where xp was already 0.
Dedicated to @mikroskeem who let me forget about this.
2020-08-30 13:25:36 -04:00
wizjany 2ed60eba02 Add deprecation warnings for names in Domains. 2020-08-21 15:51:33 -04:00
wizjany 91a1494634 Add piglin brutes. 2020-08-16 18:03:05 -04:00
Matthew Miller 5b8c3e7f70 Use a lower level exception in BukkitWorldConfiguration to get a printout when more severe YAML issues occur 2020-08-16 16:55:19 +10:00
Matthew Miller c1ff4fc3d3 s/WorlGuard/WorldGuard 2020-08-16 14:44:57 +10:00
JOO200andwizjany 691325c8f0 Update worldguard-bukkit/src/main/java/com/sk89q/worldguard/bukkit/BukkitWorldConfiguration.java
fixed typo

Co-authored-by: wizjany <wizjany@gmail.com>
2020-08-14 14:01:58 -04:00
JOO200 3da19a7ff0 Added world option to block turtle egg trampling 2020-08-14 14:01:58 -04:00
wizjany f677af566f Don't try dropping items from falling blocks that won't drop one.
To quote myself from the adjacent commit almost exactly one year ago,
"some plugins do weird things with falling blocks."

Fixes #1624.
2020-08-07 13:59:22 -04:00
wizjany 58eaf31879 Merge pull request #1618 from JOO200/piston
Implement new alternative association mode to limit piston movement
2020-08-03 10:53:31 -04:00
wizjany 6708b21016 Abstract RegionOverlapAssociation, deprecate/fix packaging. 2020-08-03 10:46:40 -04:00
wizjany ed4287ace7 Cleanup use-max-prio algorithm, add tests. 2020-08-03 10:21:35 -04:00
wizjany 03f05d3a4e Simplify and remove duplicate code. 2020-08-03 07:21:56 -04:00
JOO200 c8bde17994 Fixed "null" output for invalid worldedit selections 2020-08-01 16:55:37 +02:00
JOO200 449145ba1f Renamed option to use-max-priority-association, Code cleanup 2020-08-01 13:54:27 +02:00
JOO200 85c5f53d29 only detect max priority once 2020-07-30 20:37:49 +02:00
JOO200 5162ce3dbd Implement new alternative association mode to limit piston movement 2020-07-30 20:24:18 +02:00
wizjany efe1e48bd4 Merge pull request #1615 from JOO200/toRegionSelector
Add Helper to convert WorldGuard's ProtectedRegion to WorldEdit's Region and RegionSelector
2020-07-29 23:42:00 -04:00
wizjany 1710c07623 Check non-waterloggable waterlogged blocks for liquid flow.
Fixes #1616.
2020-07-29 23:39:04 -04:00
JOO200 6f9ed5d10f Private ctor to match checkstyle. 2020-07-27 17:55:11 +02:00
JOO200 f0ec54af49 Added missing license to WorldEditRegionConverter 2020-07-27 17:17:20 +02:00
JOO200 e9e1885f2e Moved toRegion and toRegionSelector in a helper class 2020-07-27 17:03:50 +02:00
wizjany f8e2d8d6b7 Redstone wire is toggled between dot and cross on interact now. 2020-07-19 16:47:30 -04:00
wizjany 2c0b592b19 Declare some recently hidden dependencies. 2020-07-17 01:11:12 -04:00
wizjany 46e230e625 Missed import. 2020-07-16 21:41:08 -04:00
wizjany fe24668c6a Re-add pom-switcheroo to expose spigot as a dep instead of paper.
Makes it easier for downstream projects that don't have paper-repo.
2020-07-15 19:23:44 -04:00
wizjany 23efd5fec2 Fireworks are now projectiles.
Only use paper-api for fallback.
2020-07-15 19:23:01 -04:00
JOO200 e54235a65e Removed unnecessary relevant flag as it's checked by the UseBlockEvent listener 2020-07-15 18:43:25 -04:00
JOO200 5ec3ed6092 Changed handling von PlayerTakeLecternBookEvent to match the chest-access flag 2020-07-15 18:43:25 -04:00
TheMolkaPL 1652c9bfc0 Allocate WorldPlayerTuple only when using cache 2020-07-03 20:26:56 -04:00
TheMolkaPL a97db0ede9 Add an option to disable bypass permission cache 2020-07-03 20:26:56 -04:00
wizjany 36e42eefd0 Update gradle wrapper, more buildscript fixes. 2020-07-03 17:06:31 -04:00
wizjany 5b8eef92b8 Build script cleanup/updates. 2020-07-02 19:09:09 -04:00
wizjany d73dc6d719 Cleanup issue template a bit. 2020-07-02 18:55:08 -04:00
wizjany 74d8a4f0e7 Typo. 2020-06-27 19:55:34 -04:00
JOO200 613406aab4 Add Weeping Vines and Twisting Vines to vine-growth flag 2020-06-27 18:19:11 -04:00
wizjany 66fd84ba2f Add GitHub Sponsors link. 2020-06-27 00:24:46 -04:00
wizjany 53abb6c4ad Back to snapshot. 2020-06-26 02:09:36 -04:00
wizjany 923369e28c Release 7.0.4-beta1. 2020-06-26 02:02:48 -04:00
wizjany bc551da903 Update buildscript and WE dep. 2020-06-26 01:21:30 -04:00
wizjany bffe5e76f2 Additional 1.16 material defs. 2020-06-26 00:52:29 -04:00
JOO200 8722322cd8 Added new flag respawn-anchors similar to block respawn anchor usage 2020-06-26 00:02:50 -04:00
JOO200 0fa92d4836 Removed unnecessary if branch 2020-06-26 00:02:49 -04:00
JOO200 e52875bd0b Removed duplicate pressure plates check 2020-06-26 00:02:49 -04:00
JOO200 dbad328d0d Update to Minecraft 1 16, PaperLib to 1 0 4 2020-06-26 00:02:49 -04:00
107 changed files with 2964 additions and 1341 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
github: enginehub
+5 -2
View File
@@ -8,11 +8,14 @@ assignees: ''
---
**Versions**
<!-- Please include the full version of WorldEdit, WorldGuard and the platform (Bukkit/Spigot/Paper) you are running, e.g. output from `/we version`, `/wg version` `/version` commands. Please ensure you are running up to date software before making a bug report. Old versions will recieve little to no support. -->
<!-- Please include the full version of WorldEdit, WorldGuard and the platform (Bukkit/Spigot/Paper) you are running, e.g. output from `/we version`, `/wg version` `/version` commands. Please ensure you are running up to date software before making a bug report. Old versions will receive little to no support. -->
WorldEdit version:
WorldGuard version:
Platform version:
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
@@ -25,7 +28,7 @@ Platform version:
<!-- A clear and concise description of what you expected to happen. -->
**Screenshots**
<!-- If applicable, add screenshots to help explain your problem. -->
<!-- If applicable, add screenshots to help explain your problem. Screenshots of `/rg info` for any applicable regions (or simply the link from `/wg report -p`) are good to include. -->
**Additional context**
<!-- Add any other context about the problem here. -->
+1 -1
View File
@@ -1,6 +1,6 @@
---
name: Feature request
about: Suggest an idea for WorlGuard
about: Suggest an idea for WorldGuard
title: ''
labels: type:feature-request, status:pending
assignees: ''
+1 -1
View File
@@ -1,7 +1,7 @@
language: java
dist: trusty
jdk:
- oraclejdk8
- oraclejdk11
notifications:
email: false
before_install: chmod +x gradlew
+50
View File
@@ -1,5 +1,55 @@
# Changelog
## 7.0.6
* Add support for 1.17 blocks/items, drop support for 1.16.
* Add use-dripleaf flag for "toggling" big dripleaf blocks.
* Fix support for fully negative-height regions.
* Fix crop-growth config option.
* Be more rigorous with protecting blocks against dispenser behaviors.
* Fix handling of lingering splash potion effects.
* Handle other-explosion flag consistently for block-like entities (armor frames etc.)
* Allow inheriting values for all flags (previously wasn't used for things like teleport.)
* Region commands that defaulted to the region the player was standing in no longer check parents.
* Fix child regions being unlinked when redefining a parent region.
## 7.0.5
* Add a use-anvil flag and exclude it from the use flag (since they can break on use.)
* Add nonplayer-protection-domains flag which allows merging region borders from the perspective of pistons, saplings, etc.
* Expand crop-related options (crop-growth, etc) to sweet berry bushes, nether wart, and bamboo.
* Add a config option (`mobs.block-vehicle-entry`) to prevent non-players from entering vehicles.
* Add a UUID flag (for developers/API usage).
* Add map query methods with fallback flag (for developers/API usage).
* Add `on` and `off` optional arguments for `/rg toggle-bypass` command.
* Add additional timings info for session handlers.
* Fix sponge-simulation clearing NBT from blocks. Note that if you are using sponge simulation you should switch to something like CraftBook as the feature will be removed from WorldGuard in a future (major) version.
* Fix the `/rg` command showing up as unknown client-side to players without bypass perms.
* Fix error propagation from third-party flag loading causing WG to error.
* Fix a (harmless) exception that occurred when swapping armor slots to the offhand slot.
* Fix empty lines being sent on enderpearl/chorus-fruit teleport if the deny messages were empty.
* Fix an issue with falling blocks when using max-priority-association.
* Fix performance issues with third-party plugins querying protection for offline players.
* Fix dispensing shulkers over region boundaries.
* Fix iron door interaction being denied as if it were a regular door.
* Fix being able to enter/exit regions with the flag denied by using entity mounting functions in other plugins.
## 7.0.4 (including beta1)
* Add support for MC 1.16. Dropped support for previous versions.
* Add respawn-anchors flag mirroring the sleep flag (e.g. to prevent using respawn anchors to cause explosions in the overworld)
* Add nether vines to vine-growth flag.
* Add config option to disable the bypass permission cache.
* Fix water-flow flags not checking waterlogged blocks.
* Add config option to consider non-player causes (e.g. pistons, flowing water) to only be members of the highest priority region. This should be enabled for plots-within-city-like setups to prevent things in plots from modifying the city.
* Fix items dropping from falling blocks that were suppressed by other plugins.
* Add config option to block turtle egg trampling.
* Fix ride flag being checked on striders that didn't have saddles.
* Add config option to have /rg bypass toggled off on login.
* Developer changes: Methods taking names in Domains are now explicitly deprecated (was previously just a javadoc comment.); These will eventually be removed: there is no reason to use names over UUIDs. Offline players and NPCs alike have stable UUIDs.
* Also for developers; The new `com.sk89q.worldguard.protection.util.WorldEditRegionConverter` class has some useful static methods to convert to and from WorldEdit's Region and WorldGuard's ProtectedRegion classes.
## 7.0.3
* This is the last release supporting MC 1.14 and 1.15.
+2 -2
View File
@@ -7,9 +7,9 @@ ask that you make note of the following guidelines.
* **Follow the [Oracle coding conventions](https://www.oracle.com/technetwork/java/javase/documentation/codeconvtoc-136057.html).**
We can't stress this enough; if your code has notable issues, it may delay
the process significantly.
* **Target Java 6 for source and compilation.** Make sure to mark methods with
* **Target Java 8 for source and compilation.** Make sure to mark methods with
` @Override` that override methods of parent classes, or that implement
methods of interfaces (Java 6+).
methods of interfaces.
* **Use only spaces for indentation.** Our indents are 4-spaces long, and tabs
are unacceptable.
* **Wrap code to a 89 column limit.** We do this to make side by side diffs
+15 -14
View File
@@ -1,22 +1,24 @@
# ![WorldGuard](worldguard-logo.png)
<h1>
<img src="worldguard-logo.svg" alt="WorldGuard" width="400" />
</h1>
WorldGuard lets you and players guard areas of land against griefers and undesirables, as well as tweak and disable various gameplay features of Minecraft.
* Block creeper and wither block damage, falling damage, etc.;
* Disable fire spread, lava fire spread, ice formation, Endermen picking up blocks, etc.;
* Blacklist certain items and blocks so they can't be used;
* Warn moderators when certain items and blocks are used;
* Protect areas of your world so only certain people can build in them;
* Set areas where PVP, TNT, mob damage, and other features are disabled;
* Protect your server from various 'exploits' like magical obsidian creation machines;
* Disable, or enable, various Minecraft features, like sponges from classic;
* Add useful commands like an immediate "STOP ALL FIRE SPREAD" command.
* Enable only features you want! Everything is off by default.
* Block creeper and wither block damage, falling damage, etc.
* Disable fire spread, lava fire spread, ice formation, Endermen picking up blocks, etc.
* Blacklist certain items and blocks so they can't be used
* Warn moderators when certain items and blocks are used
* Protect areas of your world so only certain people can build in them
* Set areas where PVP, TNT, mob damage, and other features are disabled
* Protect your server from various 'exploits' like magical obsidian creation machines
* Disable, or enable, various Minecraft features, like sponges from classic
* Add useful commands like an immediate "STOP ALL FIRE SPREAD" command
* Enable only features you want! Everything is off by default
WorldGuard is open source and is available under the GNU Lesser
General Public License v3.
Currently, Bukkit is required to use WorldGuard. You can get a release copy of WorldGuard from the [BukkitDev site](http://dev.bukkit.org/bukkit-plugins/worldguard/).
A Bukkit server implementation (such as [Paper](https://papermc.io)) and the [WorldEdit plugin](https://dev.bukkit.org/projects/worldedit) are required to use WorldGuard. You can get a release copy of WorldGuard from the [BukkitDev site](https://dev.bukkit.org/projects/worldguard).
Compiling
---------
@@ -40,7 +42,6 @@ Links
* [Homepage](http://enginehub.org/worldguard)
* [Discord](https://discord.gg/enginehub)
* [IRC channel](https://webchat.esper.net/?join=sk89q) (#sk89q on irc.esper.net)
* [Issue tracker](https://dev.enginehub.org/issues/WORLDGUARD)
* [Issue tracker](https://github.com/EngineHub/WorldGuard/issues)
* [Continuous integration](http://builds.enginehub.org) [![Build Status](https://ci.enginehub.org/app/rest/builds/buildType:bt11,branch:master/statusIcon.svg)](http://ci.enginehub.org/viewType.html?buildTypeId=bt11&guest=1)
* [End-user documentation](https://worldguard.enginehub.org/en/latest/)
+2 -2
View File
@@ -17,10 +17,10 @@ applyRootArtifactoryConfig()
if (!project.hasProperty("gitCommitHash")) {
apply(plugin = "org.ajoberstar.grgit")
ext["gitCommitHash"] = try {
(ext["grgit"] as Grgit?)?.head()?.abbreviatedId
Grgit.open(mapOf("currentDir" to project.rootDir))?.head()?.abbreviatedId
} catch (e: Exception) {
logger.warn("Error getting commit hash", e)
"no_git_id"
"no.git.id"
}
}
+5 -7
View File
@@ -4,16 +4,14 @@ plugins {
}
repositories {
jcenter()
mavenCentral()
gradlePluginPortal()
}
dependencies {
implementation(gradleApi())
implementation("gradle.plugin.net.minecrell:licenser:0.4.1")
implementation("org.ajoberstar.grgit:grgit-gradle:3.1.1")
implementation("com.github.jengelman.gradle.plugins:shadow:5.1.0")
implementation("net.ltgt.apt-eclipse:net.ltgt.apt-eclipse.gradle.plugin:0.21")
implementation("net.ltgt.apt-idea:net.ltgt.apt-idea.gradle.plugin:0.21")
implementation("org.jfrog.buildinfo:build-info-extractor-gradle:4.9.7")
implementation("gradle.plugin.org.cadixdev.gradle:licenser:0.6.0")
implementation("org.ajoberstar.grgit:grgit-gradle:4.1.0")
implementation("com.github.jengelman.gradle.plugins:shadow:6.1.0")
implementation("org.jfrog.buildinfo:build-info-extractor-gradle:4.21.0")
}
@@ -34,7 +34,7 @@ fun Project.applyRootArtifactoryConfig() {
}
fun Project.applyCommonArtifactoryConfig() {
val named = tasks.named<ArtifactoryTask>("artifactoryPublish") {
publishConfigs("archives")
tasks.named<ArtifactoryTask>("artifactoryPublish") {
publications("maven")
}
}
}
+22 -2
View File
@@ -1,5 +1,11 @@
import org.cadixdev.gradle.licenser.LicenseExtension
import org.gradle.api.Project
import org.gradle.api.plugins.JavaPluginExtension
import org.gradle.jvm.toolchain.JavaLanguageVersion
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.repositories
import org.gradle.kotlin.dsl.the
fun Project.applyCommonConfiguration() {
group = rootProject.group
@@ -7,12 +13,26 @@ fun Project.applyCommonConfiguration() {
repositories {
mavenCentral()
maven { url = uri("https://maven.sk89q.com/repo/") }
maven { url = uri("https://maven.enginehub.org/repo/") }
maven { url = uri("https://oss.sonatype.org/content/repositories/snapshots/") }
}
configurations.all {
resolutionStrategy {
cacheChangingModulesFor(5, "minutes")
cacheChangingModulesFor(5, "MINUTES")
}
}
plugins.withId("java") {
the<JavaPluginExtension>().toolchain {
languageVersion.set(JavaLanguageVersion.of(16))
}
}
apply(plugin = "org.cadixdev.licenser")
configure<LicenseExtension> {
header(rootProject.file("HEADER.txt"))
include("**/*.java")
include("**/*.kt")
}
}
+102 -27
View File
@@ -1,39 +1,54 @@
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.artifacts.ModuleDependency
import org.gradle.api.internal.HasConvention
import org.gradle.api.plugins.MavenRepositoryHandlerConvention
import org.gradle.api.tasks.Upload
import org.gradle.api.attributes.Bundling
import org.gradle.api.attributes.Category
import org.gradle.api.attributes.DocsType
import org.gradle.api.attributes.LibraryElements
import org.gradle.api.attributes.Usage
import org.gradle.api.attributes.java.TargetJvmVersion
import org.gradle.api.component.AdhocComponentWithVariants
import org.gradle.api.component.SoftwareComponentFactory
import org.gradle.api.publish.PublishingExtension
import org.gradle.api.publish.maven.MavenPublication
import org.gradle.api.tasks.bundling.Jar
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.get
import org.gradle.kotlin.dsl.getPlugin
import org.gradle.kotlin.dsl.invoke
import org.gradle.kotlin.dsl.named
import org.gradle.kotlin.dsl.register
import javax.inject.Inject
fun Project.applyLibrariesConfiguration() {
applyCommonConfiguration()
apply(plugin = "java-base")
apply(plugin = "maven")
apply(plugin = "maven-publish")
apply(plugin = "com.github.johnrengelman.shadow")
apply(plugin = "com.jfrog.artifactory")
configurations {
create("shade")
getByName("archives").extendsFrom(getByName("default"))
}
group = "${rootProject.group}.worldguard-libs"
val relocations = mapOf(
"org.enginehub.squirrelid" to "com.sk89q.worldguard.util.profile"
)
tasks.register<ShadowJar>("jar") {
configurations = listOf(project.configurations["shade"])
archiveClassifier.set("")
dependencies {
exclude(dependency("com.google.code.findbugs:jsr305:1.3.9"))
exclude(dependency("com.google.code.findbugs:jsr305"))
}
relocate("com.sk89q.squirrelid", "com.sk89q.worldguard.util.profile")
relocations.forEach { (from, to) ->
relocate(from, to)
}
}
val altConfigFiles = { artifactType: String ->
val deps = configurations["shade"].incoming.dependencies
@@ -58,13 +73,15 @@ fun Project.applyLibrariesConfiguration() {
from({
altConfigFiles("sources")
})
val filePattern = Regex("(.*)com/sk89q/squirrelid((?:/|$).*)")
val textPattern = Regex("com\\.sk89q\\.squirrelid")
eachFile {
filter {
it.replaceFirst(textPattern, "com.sk89q.worldguard.util.profile")
relocations.forEach { (from, to) ->
val filePattern = Regex("(.*)${from.replace('.', '/')}((?:/|$).*)")
val textPattern = Regex.fromLiteral(from)
eachFile {
filter {
it.replaceFirst(textPattern, to)
}
path = path.replaceFirst(filePattern, "$1${to.replace('.', '/')}$2")
}
path = path.replaceFirst(filePattern, "$1com/sk89q/worldguard/util/profile$2")
}
archiveClassifier.set("sources")
}
@@ -73,24 +90,82 @@ fun Project.applyLibrariesConfiguration() {
dependsOn("jar", "sourcesJar")
}
artifacts {
val jar = tasks.named("jar")
add("default", jar) {
builtBy(jar)
}
val sourcesJar = tasks.named("sourcesJar")
add("archives", sourcesJar) {
builtBy(sourcesJar)
project.apply<LibsConfigPluginHack>()
val libsComponent = project.components["libs"] as AdhocComponentWithVariants
val apiElements = project.configurations.register("apiElements") {
isVisible = false
description = "API elements for libs"
isCanBeResolved = false
isCanBeConsumed = true
attributes {
attribute(Usage.USAGE_ATTRIBUTE, project.objects.named(Usage.JAVA_API))
attribute(Category.CATEGORY_ATTRIBUTE, project.objects.named(Category.LIBRARY))
attribute(Bundling.BUNDLING_ATTRIBUTE, project.objects.named(Bundling.SHADOWED))
attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, project.objects.named(LibraryElements.JAR))
attribute(TargetJvmVersion.TARGET_JVM_VERSION_ATTRIBUTE, 8)
}
outgoing.artifact(tasks.named("jar"))
}
tasks.register<Upload>("install") {
configuration = configurations["archives"]
(repositories as HasConvention).convention.getPlugin<MavenRepositoryHandlerConvention>().mavenInstaller {
pom.version = project.version.toString()
pom.artifactId = project.name
val runtimeElements = project.configurations.register("runtimeElements") {
isVisible = false
description = "Runtime elements for libs"
isCanBeResolved = false
isCanBeConsumed = true
attributes {
attribute(Usage.USAGE_ATTRIBUTE, project.objects.named(Usage.JAVA_RUNTIME))
attribute(Category.CATEGORY_ATTRIBUTE, project.objects.named(Category.LIBRARY))
attribute(Bundling.BUNDLING_ATTRIBUTE, project.objects.named(Bundling.SHADOWED))
attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, project.objects.named(LibraryElements.JAR))
attribute(TargetJvmVersion.TARGET_JVM_VERSION_ATTRIBUTE, 8)
}
outgoing.artifact(tasks.named("jar"))
}
val sourcesElements = project.configurations.register("sourcesElements") {
isVisible = false
description = "Source elements for libs"
isCanBeResolved = false
isCanBeConsumed = true
attributes {
attribute(Usage.USAGE_ATTRIBUTE, project.objects.named(Usage.JAVA_RUNTIME))
attribute(Category.CATEGORY_ATTRIBUTE, project.objects.named(Category.DOCUMENTATION))
attribute(Bundling.BUNDLING_ATTRIBUTE, project.objects.named(Bundling.SHADOWED))
attribute(DocsType.DOCS_TYPE_ATTRIBUTE, project.objects.named(DocsType.SOURCES))
}
outgoing.artifact(tasks.named("sourcesJar"))
}
libsComponent.addVariantsFromConfiguration(apiElements.get()) {
mapToMavenScope("compile")
}
libsComponent.addVariantsFromConfiguration(runtimeElements.get()) {
mapToMavenScope("runtime")
}
libsComponent.addVariantsFromConfiguration(sourcesElements.get()) {
mapToMavenScope("runtime")
}
configure<PublishingExtension> {
publications {
register<MavenPublication>("maven") {
from(libsComponent)
}
}
}
applyCommonArtifactoryConfig()
}
internal open class LibsConfigPluginHack @Inject constructor(
private val softwareComponentFactory: SoftwareComponentFactory
) : Plugin<Project> {
override fun apply(project: Project) {
val libsComponents = softwareComponentFactory.adhoc("libs")
project.components.add(libsComponents)
}
}
+48 -54
View File
@@ -1,105 +1,95 @@
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import net.minecrell.gradle.licenser.LicenseExtension
import org.gradle.api.JavaVersion
import org.gradle.api.Project
import org.gradle.api.plugins.JavaPluginConvention
import org.gradle.api.component.AdhocComponentWithVariants
import org.gradle.api.plugins.JavaPluginExtension
import org.gradle.api.plugins.quality.CheckstyleExtension
import org.gradle.api.tasks.bundling.Jar
import org.gradle.api.publish.PublishingExtension
import org.gradle.api.publish.maven.MavenPublication
import org.gradle.api.tasks.javadoc.Javadoc
import org.gradle.api.tasks.testing.Test
import org.gradle.external.javadoc.CoreJavadocOptions
import org.gradle.external.javadoc.StandardJavadocDocletOptions
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.dependencies
import org.gradle.kotlin.dsl.get
import org.gradle.kotlin.dsl.getByName
import org.gradle.kotlin.dsl.named
import org.gradle.kotlin.dsl.register
import org.gradle.kotlin.dsl.withType
import org.gradle.kotlin.dsl.the
fun Project.applyPlatformAndCoreConfiguration() {
applyCommonConfiguration()
apply(plugin = "java")
apply(plugin = "eclipse")
apply(plugin = "idea")
apply(plugin = "maven")
apply(plugin = "maven-publish")
apply(plugin = "checkstyle")
apply(plugin = "com.github.johnrengelman.shadow")
apply(plugin = "com.jfrog.artifactory")
apply(plugin = "net.minecrell.licenser")
ext["internalVersion"] = "$version;${rootProject.ext["gitCommitHash"]}"
configure<JavaPluginConvention> {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
ext["internalVersion"] = "$version+${rootProject.ext["gitCommitHash"]}"
configure<CheckstyleExtension> {
configFile = rootProject.file("config/checkstyle/checkstyle.xml")
toolVersion = "7.6.1"
toolVersion = "8.34"
}
tasks.withType<Test>().configureEach {
useJUnit()
useJUnitPlatform()
}
dependencies {
"testCompile"("junit:junit:${Versions.JUNIT}")
// TODO switch to jupiter - doesn't support abstract test classes so tests need rewriting
//"testImplementation"("org.junit.jupiter:junit-jupiter-api:${Versions.JUNIT}")
//"testRuntime"("org.junit.jupiter:junit-jupiter-engine:${Versions.JUNIT}")
"compileOnly"("com.google.code.findbugs:jsr305:3.0.2")
"testCompileOnly"("com.google.code.findbugs:jsr305:3.0.2")
"testImplementation"("org.junit.jupiter:junit-jupiter-api:${Versions.JUNIT}")
"testImplementation"("org.junit.jupiter:junit-jupiter-params:${Versions.JUNIT}")
"testImplementation"("org.mockito:mockito-core:${Versions.MOCKITO}")
"testImplementation"("org.mockito:mockito-junit-jupiter:${Versions.MOCKITO}")
"testRuntimeOnly"("org.junit.jupiter:junit-jupiter-engine:${Versions.JUNIT}")
}
// Java 8 turns on doclint which we fail
tasks.withType<Javadoc>().configureEach {
(options as CoreJavadocOptions).addStringOption("Xdoclint:none", "-quiet")
(options as StandardJavadocDocletOptions).apply {
addStringOption("Xdoclint:none", "-quiet")
tags(
"apiNote:a:API Note:",
"implSpec:a:Implementation Requirements:",
"implNote:a:Implementation Note:"
)
}
}
tasks.register<Jar>("javadocJar") {
dependsOn("javadoc")
archiveClassifier.set("javadoc")
from(tasks.getByName<Javadoc>("javadoc").destinationDir)
}
tasks.named("assemble").configure {
dependsOn("javadocJar")
}
artifacts {
add("archives", tasks.named("jar"))
add("archives", tasks.named("javadocJar"))
}
the<JavaPluginExtension>().withJavadocJar()
if (name == "worldguard-core" || name == "worldguard-bukkit") {
tasks.register<Jar>("sourcesJar") {
dependsOn("classes")
archiveClassifier.set("sources")
from(sourceSets["main"].allSource)
}
artifacts {
add("archives", tasks.named("sourcesJar"))
}
tasks.named("assemble").configure {
dependsOn("sourcesJar")
}
the<JavaPluginExtension>().withSourcesJar()
}
tasks.named("check").configure {
dependsOn("checkstyleMain", "checkstyleTest")
}
applyCommonArtifactoryConfig()
configure<LicenseExtension> {
header = rootProject.file("HEADER.txt")
include("**/*.java")
configure<PublishingExtension> {
publications {
register<MavenPublication>("maven") {
from(components["java"])
versionMapping {
usage("java-api") {
fromResolutionOf("runtimeClasspath")
}
usage("java-runtime") {
fromResolutionResult()
}
}
}
}
}
applyCommonArtifactoryConfig()
}
fun Project.applyShadowConfiguration() {
apply(plugin = "com.github.johnrengelman.shadow")
tasks.named<ShadowJar>("shadowJar") {
archiveClassifier.set("dist")
dependencies {
@@ -110,10 +100,14 @@ fun Project.applyShadowConfiguration() {
relocate("org.flywaydb", "com.sk89q.worldguard.internal.flywaydb") {
include(dependency("org.flywaydb:flyway-core:3.0"))
}
relocate("com.sk89q.squirrelid", "com.sk89q.worldguard.util.profile")
exclude("com.google.code.findbugs:jsr305")
}
exclude("GradleStart**")
exclude(".cache")
exclude("LICENSE*")
}
val javaComponent = components["java"] as AdhocComponentWithVariants
javaComponent.withVariantsFromConfiguration(configurations["shadowRuntimeElements"]) {
skip()
}
}
+5 -3
View File
@@ -1,7 +1,9 @@
object Versions {
// const val PISTON = "0.4.3"
// const val AUTO_VALUE = "1.6.5"
const val WORLDEDIT = "7.1.0-SNAPSHOT"
const val JUNIT = "4.11"
const val SQUIRRELID = "0.2.0"
const val WORLDEDIT = "7.2.6-SNAPSHOT"
const val JUNIT = "5.7.0"
const val SQUIRRELID = "0.3.0"
const val GUAVA = "21.0"
const val MOCKITO = "3.7.7"
}
+3
View File
@@ -27,8 +27,11 @@
<subpackage name="bukkit">
<allow pkg="org.bukkit"/>
<allow pkg="org.bstats.bukkit"/>
<allow pkg="org.bstats.charts"/>
<allow pkg="io.papermc.lib"/>
<allow pkg="com.destroystokyo.paper"/>
<allow pkg="co.aikar.timings.lib" />
<allow pkg="org.spigotmc" />
</subpackage>
</subpackage>
+1 -1
View File
@@ -1,2 +1,2 @@
group=com.sk89q.worldguard
version=7.0.3
version=7.0.6
Binary file not shown.
+1 -1
View File
@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.5.1-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-7.0.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored
+17 -1
View File
@@ -1,5 +1,21 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
@@ -28,7 +44,7 @@ APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m"'
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
Vendored
+17 -1
View File
@@ -1,3 +1,19 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@@ -14,7 +30,7 @@ set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m"
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
+37 -33
View File
@@ -1,10 +1,7 @@
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import org.gradle.api.internal.HasConvention
plugins {
id("java-library")
id("net.ltgt.apt-eclipse")
id("net.ltgt.apt-idea")
`java-library`
}
applyPlatformAndCoreConfiguration()
@@ -19,56 +16,63 @@ repositories {
name = "bstats"
url = uri("https://repo.codemc.org/repository/maven-public")
}
}
dependencies {
"compile"(project(":worldguard-core"))
//"compile"(project(":worldguard-libs:bukkit"))
"api"("com.destroystokyo.paper:paper-api:1.15.2-R0.1-SNAPSHOT")
"implementation"("io.papermc:paperlib:1.0.4")
"api"("com.sk89q.worldedit:worldedit-bukkit:${Versions.WORLDEDIT}") { isTransitive = false }
"implementation"("com.sk89q:commandbook:2.3") { isTransitive = false }
"implementation"("org.bstats:bstats-bukkit:1.7")
}
tasks.named<Upload>("install") {
(repositories as HasConvention).convention.getPlugin<MavenRepositoryHandlerConvention>().mavenInstaller {
pom.whenConfigured {
dependencies.firstOrNull { dep ->
dep!!.withGroovyBuilder {
getProperty("groupId") == "com.destroystokyo.paper" && getProperty("artifactId") == "paper-api"
}
}?.withGroovyBuilder {
setProperty("groupId", "org.bukkit")
setProperty("artifactId", "bukkit")
}
}
maven {
name = "aikar-timings"
url = uri("https://repo.aikar.co/nexus/content/groups/aikar/")
}
}
configurations {
compileClasspath.get().extendsFrom(create("shadeOnly"))
}
dependencies {
"api"(project(":worldguard-core"))
"compileOnly"("io.papermc.paper:paper-api:1.17-R0.1-SNAPSHOT")
"runtimeOnly"("org.spigotmc:spigot-api:1.17-R0.1-SNAPSHOT") {
exclude("junit", "junit")
}
"api"("com.sk89q.worldedit:worldedit-bukkit:${Versions.WORLDEDIT}") { isTransitive = false }
"implementation"("com.google.guava:guava:${Versions.GUAVA}")
"compileOnly"("com.sk89q:commandbook:2.3") { isTransitive = false }
"shadeOnly"("io.papermc:paperlib:1.0.6")
"shadeOnly"("org.bstats:bstats-bukkit:2.1.0")
"shadeOnly"("co.aikar:minecraft-timings:1.0.4")
}
tasks.named<Copy>("processResources") {
val internalVersion = project.ext["internalVersion"]
inputs.property("internalVersion", internalVersion)
filesMatching("plugin.yml") {
expand("internalVersion" to project.ext["internalVersion"])
expand("internalVersion" to internalVersion)
}
}
tasks.named<Jar>("jar") {
val projectVersion = project.version
inputs.property("projectVersion", projectVersion)
manifest {
attributes("Implementation-Version" to project.version)
attributes("Implementation-Version" to projectVersion)
}
}
tasks.named<ShadowJar>("shadowJar") {
configurations = listOf(project.configurations["shadeOnly"], project.configurations["runtimeClasspath"])
dependencies {
include(dependency(":worldguard-core"))
relocate("org.bstats", "com.sk89q.worldguard.bukkit.bstats") {
include(dependency("org.bstats:bstats-bukkit:1.7"))
include(dependency("org.bstats:"))
}
relocate ("io.papermc.lib", "com.sk89q.worldguard.bukkit.paperlib") {
include(dependency("io.papermc:paperlib:1.0.4"))
include(dependency("io.papermc:paperlib"))
}
relocate ("co.aikar.timings.lib", "com.sk89q.worldguard.bukkit.timingslib") {
include(dependency("co.aikar:minecraft-timings"))
}
}
}
tasks.named("assemble").configure {
dependsOn("shadowJar")
}
}
@@ -37,6 +37,7 @@ public class BukkitConfigurationManager extends YamlConfigurationManager {
private boolean hasCommandBookGodMode;
boolean extraStats;
boolean timedSessionHandlers;
/**
* Construct the object.
@@ -56,6 +57,7 @@ public class BukkitConfigurationManager extends YamlConfigurationManager {
public void load() {
super.load();
this.extraStats = getConfig().getBoolean("custom-metrics-charts", true);
this.timedSessionHandlers = getConfig().getBoolean("extra-timings.session-handlers", true);
}
@Override
@@ -92,6 +94,10 @@ public class BukkitConfigurationManager extends YamlConfigurationManager {
@Override
public BukkitWorldConfiguration get(World world) {
String worldName = world.getName();
return get(worldName);
}
public BukkitWorldConfiguration get(String worldName) {
BukkitWorldConfiguration config = worlds.get(worldName);
BukkitWorldConfiguration newConfig = null;
@@ -99,8 +105,8 @@ public class BukkitConfigurationManager extends YamlConfigurationManager {
if (newConfig == null) {
newConfig = new BukkitWorldConfiguration(plugin, worldName, this.getConfig());
}
worlds.putIfAbsent(world.getName(), newConfig);
config = worlds.get(world.getName());
worlds.putIfAbsent(worldName, newConfig);
config = worlds.get(worldName);
}
return config;
@@ -40,7 +40,7 @@ import com.sk89q.worldguard.chest.ChestProtection;
import com.sk89q.worldguard.commands.CommandUtils;
import com.sk89q.worldguard.config.YamlWorldConfiguration;
import org.bukkit.potion.PotionEffectType;
import org.yaml.snakeyaml.parser.ParserException;
import org.yaml.snakeyaml.error.YAMLException;
import java.io.File;
import java.io.FileNotFoundException;
@@ -135,7 +135,7 @@ public class BukkitWorldConfiguration extends YamlWorldConfiguration {
config.load();
} catch (IOException e) {
log.log(Level.SEVERE, "Error reading configuration for world " + worldName + ": ", e);
} catch (ParserException e) {
} catch (YAMLException e) {
log.severe("Error parsing configuration for world " + worldName + ". ");
throw e;
}
@@ -160,6 +160,8 @@ public class BukkitWorldConfiguration extends YamlWorldConfiguration {
disableExpDrops = getBoolean("protection.disable-xp-orb-drops", false);
disableObsidianGenerators = getBoolean("protection.disable-obsidian-generators", false);
useMaxPriorityAssociation = getBoolean("protection.use-max-priority-association", false);
blockPotions = new HashSet<>();
for (String potionName : getStringList("gameplay.block-potions", null)) {
PotionEffectType effect = PotionEffectType.getByName(potionName);
@@ -216,6 +218,7 @@ public class BukkitWorldConfiguration extends YamlWorldConfiguration {
blockGroundSlimes = getBoolean("mobs.block-above-ground-slimes", false);
blockOtherExplosions = getBoolean("mobs.block-other-explosions", false);
blockZombieDoorDestruction = getBoolean("mobs.block-zombie-door-destruction", false);
blockEntityVehicleEntry = getBoolean("mobs.block-vehicle-entry", false);
disableFallDamage = getBoolean("player-damage.disable-fall-damage", false);
disableLavaDamage = getBoolean("player-damage.disable-lava-damage", false);
@@ -238,6 +241,9 @@ public class BukkitWorldConfiguration extends YamlWorldConfiguration {
disableCreatureCropTrampling = getBoolean("crops.disable-creature-trampling", false);
disablePlayerCropTrampling = getBoolean("crops.disable-player-trampling", false);
disableCreatureTurtleEggTrampling = getBoolean("turtle-egg.disable-creature-trampling", false);
disablePlayerTurtleEggTrampling = getBoolean("turtle-egg.disable-player-trampling", false);
disallowedLightningBlocks = new HashSet<>(convertLegacyBlocks(getStringList("weather.prevent-lightning-strike-blocks", null)));
preventLightningFire = getBoolean("weather.disable-lightning-strike-fire", false);
disableThunder = getBoolean("weather.disable-thunderstorm", false);
@@ -31,7 +31,7 @@ import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.util.profile.resolver.PaperProfileService;
import com.sk89q.worldguard.util.profile.resolver.PaperPlayerService;
import com.sk89q.worldguard.bukkit.protection.events.flags.FlagContextCreateEvent;
import com.sk89q.worldguard.bukkit.session.BukkitSessionManager;
import com.sk89q.worldguard.bukkit.util.report.PerformanceReport;
@@ -67,7 +67,7 @@ import java.util.stream.Collectors;
public class BukkitWorldGuardPlatform implements WorldGuardPlatform {
private SessionManager sessionManager;
private BukkitSessionManager sessionManager;
private BukkitConfigurationManager configuration;
private BukkitRegionContainer regionContainer;
private BukkitDebugHandler debugHandler;
@@ -138,6 +138,7 @@ public class BukkitWorldGuardPlatform implements WorldGuardPlatform {
sessionManager = new BukkitSessionManager();
configuration = new BukkitConfigurationManager(WorldGuardPlugin.inst());
configuration.load();
sessionManager.setUsingTimings(configuration.timedSessionHandlers);
regionContainer = new BukkitRegionContainer(WorldGuardPlugin.inst());
regionContainer.initialize();
debugHandler = new BukkitDebugHandler(WorldGuardPlugin.inst());
@@ -172,7 +173,6 @@ public class BukkitWorldGuardPlatform implements WorldGuardPlatform {
@Override
public void stackPlayerInventory(LocalPlayer localPlayer) {
boolean ignoreMax = localPlayer.hasPermission("worldguard.stack.illegitimate");
boolean ignoreDamaged = localPlayer.hasPermission("worldguard.stack.damaged");
Player player = ((BukkitPlayer) localPlayer).getPlayer();
@@ -206,12 +206,7 @@ public class BukkitWorldGuardPlatform implements WorldGuardPlatform {
}
// Same type?
// Blocks store their color in the damage value
if (item2.getType() == item.getType() &&
(ignoreDamaged || item.getDurability() == item2.getDurability()) &&
((item.getItemMeta() == null && item2.getItemMeta() == null)
|| (item.getItemMeta() != null &&
item.getItemMeta().equals(item2.getItemMeta())))) {
if (item2.isSimilar(item)) {
// This stack won't fit in the parent stack
if (item2.getAmount() > needed) {
item.setAmount(max);
@@ -250,7 +245,7 @@ public class BukkitWorldGuardPlatform implements WorldGuardPlatform {
List<ProfileService> services = new ArrayList<>();
if (PaperLib.isPaper()) {
// Paper has a shared cache
services.add(PaperProfileService.getInstance());
services.add(PaperPlayerService.getInstance());
} else {
services.add(BukkitPlayerService.getInstance());
}
@@ -75,6 +75,9 @@ import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.util.logging.RecordMessagePrefixer;
import org.bstats.bukkit.Metrics;
import org.bstats.charts.DrilldownPie;
import org.bstats.charts.SimplePie;
import org.bstats.charts.SingleLineChart;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
@@ -105,6 +108,8 @@ public class WorldGuardPlugin extends JavaPlugin {
private final CommandsManager<Actor> commands;
private PlayerMoveListener playerMoveListener;
private static final int BSTATS_PLUGIN_ID = 3283;
/**
* Construct objects. Actual loading occurs when the plugin is enabled, so
* this merely instantiates the objects.
@@ -212,20 +217,20 @@ public class WorldGuardPlugin extends JavaPlugin {
((SimpleFlagRegistry) WorldGuard.getInstance().getFlagRegistry()).setInitialized(true);
// Enable metrics
final Metrics metrics = new Metrics(this, 3283); // bStats plugin id
if (metrics.isEnabled() && platform.getGlobalStateManager().extraStats) {
final Metrics metrics = new Metrics(this, BSTATS_PLUGIN_ID); // bStats plugin id
if (platform.getGlobalStateManager().extraStats) {
setupCustomCharts(metrics);
}
}
private void setupCustomCharts(Metrics metrics) {
metrics.addCustomChart(new Metrics.SingleLineChart("region_count", () ->
metrics.addCustomChart(new SingleLineChart("region_count", () ->
platform.getRegionContainer().getLoaded().stream().mapToInt(RegionManager::size).sum()));
metrics.addCustomChart(new Metrics.SimplePie("region_driver", () -> {
metrics.addCustomChart(new SimplePie("region_driver", () -> {
RegionDriver driver = platform.getGlobalStateManager().selectedRegionStoreDriver;
return driver instanceof DirectoryYamlDriver ? "yaml" : driver instanceof SQLDriver ? "sql" : "unknown";
}));
metrics.addCustomChart(new Metrics.DrilldownPie("blacklist", () -> {
metrics.addCustomChart(new DrilldownPie("blacklist", () -> {
int empty = 0;
Map<String, Integer> blacklistMap = new HashMap<>();
Map<String, Integer> whitelistMap = new HashMap<>();
@@ -248,14 +253,14 @@ public class WorldGuardPlugin extends JavaPlugin {
blacklistCounts.put("whitelist", whitelistMap);
return blacklistCounts;
}));
metrics.addCustomChart(new Metrics.SimplePie("chest_protection", () ->
metrics.addCustomChart(new SimplePie("chest_protection", () ->
"" + platform.getGlobalStateManager().getWorldConfigs().stream().anyMatch(cfg -> cfg.signChestProtection)));
metrics.addCustomChart(new Metrics.SimplePie("build_permissions", () ->
metrics.addCustomChart(new SimplePie("build_permissions", () ->
"" + platform.getGlobalStateManager().getWorldConfigs().stream().anyMatch(cfg -> cfg.buildPermissions)));
metrics.addCustomChart(new Metrics.SimplePie("custom_flags", () ->
metrics.addCustomChart(new SimplePie("custom_flags", () ->
"" + (WorldGuard.getInstance().getFlagRegistry().size() > Flags.INBUILT_FLAGS.size())));
metrics.addCustomChart(new Metrics.SimplePie("custom_handlers", () ->
metrics.addCustomChart(new SimplePie("custom_handlers", () ->
"" + (WorldGuard.getInstance().getPlatform().getSessionManager().customHandlersRegistered())));
}
@@ -385,6 +390,8 @@ public class WorldGuardPlugin extends JavaPlugin {
Plugin worldEdit = getServer().getPluginManager().getPlugin("WorldEdit");
if (worldEdit == null) {
throw new CommandException("WorldEdit does not appear to be installed.");
} else if (!worldEdit.isEnabled()) {
throw new CommandException("WorldEdit does not appear to be enabled.");
}
if (worldEdit instanceof WorldEditPlugin) {
@@ -450,6 +457,13 @@ public class WorldGuardPlugin extends JavaPlugin {
return new BukkitOfflinePlayer(this, player);
}
/**
* Internal method. Do not use as API.
*/
public BukkitConfigurationManager getConfigManager() {
return platform.getGlobalStateManager();
}
/**
* Return a protection query helper object that can be used by another
* plugin to test whether WorldGuard permits an action at a particular
@@ -37,6 +37,7 @@ import org.bukkit.entity.Tameable;
import org.bukkit.entity.Vehicle;
import org.bukkit.metadata.Metadatable;
import org.bukkit.projectiles.BlockProjectileSource;
import org.bukkit.projectiles.ProjectileSource;
import javax.annotation.Nullable;
import java.util.ArrayList;
@@ -89,26 +90,15 @@ public final class Cause {
}
/**
* Return whether a cause is known. This method will return true if
* the list of causes is empty or the list of causes only contains
* objects that really are not root causes (i.e primed TNT).
* Return whether a cause is known. This method will return false if
* the list of causes is empty or the root cause is really not known
* (e.g. primed TNT).
*
* @return true if known
*/
public boolean isKnown() {
if (causes.isEmpty()) {
return false;
}
boolean found = false;
for (Object object : causes) {
if (!(object instanceof TNTPrimed) && !(object instanceof Vehicle)) {
found = true;
break;
}
}
return found;
Object object = getRootCause();
return !(object == null || object instanceof TNTPrimed || object instanceof Vehicle);
}
@Nullable
@@ -270,13 +260,15 @@ public final class Cause {
if (o instanceof TNTPrimed) {
addAll(((TNTPrimed) o).getSource());
} else if (o instanceof Projectile) {
addAll(((Projectile) o).getShooter());
} else if (o instanceof Firework && PaperLib.isPaper()) {
UUID spawningUUID = ((Firework) o).getSpawningEntity();
if (spawningUUID != null) {
Entity spawningEntity = Bukkit.getEntity(spawningUUID);
if (spawningEntity != null) {
addAll(spawningEntity);
ProjectileSource shooter = ((Projectile) o).getShooter();
addAll(shooter);
if (shooter == null && o instanceof Firework && PaperLib.isPaper()) {
UUID spawningUUID = ((Firework) o).getSpawningEntity();
if (spawningUUID != null) {
Entity spawningEntity = Bukkit.getEntity(spawningUUID);
if (spawningEntity != null) {
addAll(spawningEntity);
}
}
}
} else if (o instanceof Vehicle) {
@@ -22,16 +22,16 @@ package com.sk89q.worldguard.bukkit.listener;
import static com.google.common.base.Preconditions.checkNotNull;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.BukkitConfigurationManager;
import com.sk89q.worldguard.bukkit.BukkitPlayer;
import com.sk89q.worldguard.bukkit.BukkitWorldConfiguration;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.cause.Cause;
import com.sk89q.worldguard.config.ConfigurationManager;
import com.sk89q.worldguard.config.WorldConfiguration;
import com.sk89q.worldguard.domains.Association;
import com.sk89q.worldguard.protection.DelayedRegionOverlapAssociation;
import com.sk89q.worldguard.protection.association.DelayedRegionOverlapAssociation;
import com.sk89q.worldguard.protection.association.Associables;
import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.regions.RegionQuery;
@@ -72,8 +72,8 @@ class AbstractListener implements Listener {
*
* @return the plugin
*/
protected WorldGuardPlugin getPlugin() {
return plugin;
protected static WorldGuardPlugin getPlugin() {
return WorldGuardPlugin.inst();
}
/**
@@ -81,8 +81,8 @@ class AbstractListener implements Listener {
*
* @return the configuration
*/
protected static ConfigurationManager getConfig() {
return WorldGuard.getInstance().getPlatform().getGlobalStateManager();
protected static BukkitConfigurationManager getConfig() {
return getPlugin().getConfigManager();
}
/**
@@ -91,18 +91,22 @@ class AbstractListener implements Listener {
* @param world The world to get the configuration for.
* @return The configuration for {@code world}
*/
protected static WorldConfiguration getWorldConfig(World world) {
protected static BukkitWorldConfiguration getWorldConfig(String world) {
return getConfig().get(world);
}
protected static BukkitWorldConfiguration getWorldConfig(org.bukkit.World world) {
return getWorldConfig(world.getName());
}
/**
* Get the world configuration given a player.
*
* @param player The player to get the wold from
* @return The {@link WorldConfiguration} for the player's world
*/
protected static WorldConfiguration getWorldConfig(LocalPlayer player) {
return getWorldConfig((World) player.getExtent());
protected static BukkitWorldConfiguration getWorldConfig(LocalPlayer player) {
return getWorldConfig(((BukkitPlayer) player).getPlayer().getWorld());
}
/**
@@ -111,7 +115,7 @@ class AbstractListener implements Listener {
* @param world the world
* @return true if region support is enabled
*/
protected static boolean isRegionSupportEnabled(World world) {
protected static boolean isRegionSupportEnabled(org.bukkit.World world) {
return getWorldConfig(world).useRegions;
}
@@ -127,9 +131,9 @@ class AbstractListener implements Listener {
} else if (rootCause instanceof Entity) {
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
final Entity entity = (Entity) rootCause;
BukkitWorldConfiguration config = getWorldConfig(entity.getWorld());
Location loc;
if (PaperLib.isPaper()
&& ((BukkitWorldConfiguration) getWorldConfig(BukkitAdapter.adapt(entity.getWorld()))).usePaperEntityOrigin) {
if (PaperLib.isPaper() && config.usePaperEntityOrigin) {
loc = entity.getOrigin();
if (loc == null) {
loc = entity.getLocation();
@@ -137,10 +141,13 @@ class AbstractListener implements Listener {
} else {
loc = entity.getLocation();
}
return new DelayedRegionOverlapAssociation(query, BukkitAdapter.adapt(loc));
return new DelayedRegionOverlapAssociation(query, BukkitAdapter.adapt(loc),
config.useMaxPriorityAssociation);
} else if (rootCause instanceof Block) {
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
return new DelayedRegionOverlapAssociation(query, BukkitAdapter.adapt(((Block) rootCause).getLocation()));
Location loc = ((Block) rootCause).getLocation();
return new DelayedRegionOverlapAssociation(query, BukkitAdapter.adapt(loc),
getWorldConfig(loc.getWorld()).useMaxPriorityAssociation);
} else {
return Associables.constant(Association.NON_MEMBER);
}
@@ -31,6 +31,7 @@ import com.sk89q.worldguard.blacklist.event.ItemDestroyWithBlacklistEvent;
import com.sk89q.worldguard.blacklist.event.ItemDropBlacklistEvent;
import com.sk89q.worldguard.blacklist.event.ItemEquipBlacklistEvent;
import com.sk89q.worldguard.blacklist.event.ItemUseBlacklistEvent;
import com.sk89q.worldguard.bukkit.BukkitWorldConfiguration;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.event.block.BreakBlockEvent;
import com.sk89q.worldguard.bukkit.event.block.PlaceBlockEvent;
@@ -49,6 +50,7 @@ import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.block.BlockDispenseArmorEvent;
import org.bukkit.event.block.BlockDispenseEvent;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.event.inventory.InventoryAction;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCreativeEvent;
@@ -58,6 +60,7 @@ import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerItemHeldEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import static com.sk89q.worldguard.bukkit.BukkitUtil.createTarget;
@@ -77,20 +80,19 @@ public class BlacklistListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onBreakBlock(final BreakBlockEvent event) {
final Player player = event.getCause().getFirstPlayer();
final WorldConfiguration wcfg = getWorldConfig(event.getWorld());
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
Player player = event.getCause().getFirstPlayer();
if (player == null) {
return;
}
final LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
final WorldConfiguration wcfg = getWorldConfig(localPlayer);
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
event.filter(target -> {
if (!wcfg.getBlacklist().check(
new BlockBreakBlacklistEvent(localPlayer, BukkitAdapter.asBlockVector(target),
@@ -108,6 +110,12 @@ public class BlacklistListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onPlaceBlock(final PlaceBlockEvent event) {
final WorldConfiguration wcfg = getWorldConfig(event.getWorld());
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
Player player = event.getCause().getFirstPlayer();
if (player == null) {
@@ -115,19 +123,18 @@ public class BlacklistListener extends AbstractListener {
}
final LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
final WorldConfiguration wcfg = getWorldConfig(localPlayer);
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
event.filter(target -> wcfg.getBlacklist().check(new BlockPlaceBlacklistEvent(
localPlayer, BukkitAdapter.asBlockVector(target), createTarget(target.getBlock(), event.getEffectiveMaterial())), false, false));
}
@EventHandler(ignoreCancelled = true)
public void onUseBlock(final UseBlockEvent event) {
final WorldConfiguration wcfg = getWorldConfig(event.getWorld());
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
Player player = event.getCause().getFirstPlayer();
if (player == null) {
@@ -135,33 +142,25 @@ public class BlacklistListener extends AbstractListener {
}
final LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
final WorldConfiguration wcfg = getWorldConfig(localPlayer);
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
event.filter(target -> wcfg.getBlacklist().check(new BlockInteractBlacklistEvent(
localPlayer, BukkitAdapter.asBlockVector(target), createTarget(target.getBlock(), event.getEffectiveMaterial())), false, false));
}
@EventHandler(ignoreCancelled = true)
public void onSpawnEntity(SpawnEntityEvent event) {
final WorldConfiguration wcfg = getWorldConfig(event.getWorld());
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
Player player = event.getCause().getFirstPlayer();
if (player == null) {
return;
}
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
WorldConfiguration wcfg = getWorldConfig(localPlayer);
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
final LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
Material material = Materials.getRelatedMaterial(event.getEffectiveType());
if (material != null) {
if (!wcfg.getBlacklist().check(new ItemUseBlacklistEvent(
@@ -173,21 +172,20 @@ public class BlacklistListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onDestroyEntity(DestroyEntityEvent event) {
final WorldConfiguration wcfg = getWorldConfig(event.getWorld());
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
Player player = event.getCause().getFirstPlayer();
if (player == null) {
return;
}
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
final LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
Entity target = event.getEntity();
WorldConfiguration wcfg = getWorldConfig(localPlayer);
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
if (target instanceof Item) {
Item item = (Item) target;
if (!wcfg.getBlacklist().check(
@@ -210,21 +208,20 @@ public class BlacklistListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onUseItem(UseItemEvent event) {
final WorldConfiguration wcfg = getWorldConfig(event.getWorld());
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
Player player = event.getCause().getFirstPlayer();
if (player == null) {
return;
}
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
final LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
ItemStack target = event.getItemStack();
WorldConfiguration wcfg = getWorldConfig(localPlayer);
// Blacklist guard
if (wcfg.getBlacklist() == null) {
return;
}
if (!wcfg.getBlacklist().check(new ItemUseBlacklistEvent(
localPlayer, BukkitAdapter.asBlockVector(player.getLocation()), createTarget(target)), false, false)) {
event.setCancelled(true);
@@ -239,8 +236,7 @@ public class BlacklistListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onPlayerDropItem(PlayerDropItemEvent event) {
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(event.getPlayer().getWorld()));
WorldConfiguration wcfg = getWorldConfig(event.getPlayer().getWorld());
if (wcfg.getBlacklist() != null) {
Item ci = event.getItemDrop();
@@ -255,8 +251,7 @@ public class BlacklistListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onBlockDispense(BlockDispenseEvent event) {
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(event.getBlock().getWorld()));
BukkitWorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(new BlockDispenseBlacklistEvent(null, BukkitAdapter.asBlockVector(event.getBlock().getLocation()),
@@ -275,8 +270,7 @@ public class BlacklistListener extends AbstractListener {
if (item != null && inventory.getHolder() != null) {
Player player = (Player) entity;
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(entity.getWorld()));
WorldConfiguration wcfg = getWorldConfig(player.getWorld());
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
if (wcfg.getBlacklist() != null && !wcfg.getBlacklist().check(
@@ -330,12 +324,16 @@ public class BlacklistListener extends AbstractListener {
return cursor;
}
case HOTBAR_SWAP:
if (event.getClick() == ClickType.SWAP_OFFHAND) {
return clickedInventory == null ? null : ((PlayerInventory) clickedInventory).getItemInOffHand();
}
return clickedInventory == null ? null : clickedInventory.getItem(event.getHotbarButton());
default:
break;
}
} else if (clickedInventory != null && clickedInventory.getType() == InventoryType.PLAYER
&& event.getView().getTopInventory().getType() == InventoryType.PLAYER
&& (event.getView().getTopInventory().getType() == InventoryType.PLAYER
|| event.getView().getTopInventory().getType() == InventoryType.CRAFTING)
&& event.getAction() == InventoryAction.MOVE_TO_OTHER_INVENTORY) {
return event.getCurrentItem();
}
@@ -349,8 +347,7 @@ public class BlacklistListener extends AbstractListener {
if (item.getType() != Material.AIR && entity instanceof Player) {
Player player = (Player) entity;
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(entity.getWorld()));
WorldConfiguration wcfg = getWorldConfig(player.getWorld());
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
if (wcfg.getBlacklist() != null && !wcfg.getBlacklist().check(
@@ -367,8 +364,7 @@ public class BlacklistListener extends AbstractListener {
ItemStack item = inventory.getItem(event.getNewSlot());
if (item != null) {
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(player.getWorld()));
WorldConfiguration wcfg = getWorldConfig(player.getWorld());
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
if (wcfg.getBlacklist() != null && !wcfg.getBlacklist().check(
@@ -384,8 +380,7 @@ public class BlacklistListener extends AbstractListener {
Player player = ((Player) event.getTargetEntity());
ItemStack stack = event.getItem();
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(player.getWorld()));
WorldConfiguration wcfg = getWorldConfig(player.getWorld());
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
if (wcfg.getBlacklist() != null && !wcfg.getBlacklist().check(
new ItemEquipBlacklistEvent(localPlayer, BukkitAdapter.asBlockVector(player.getLocation()), createTarget(stack)), false, true)) {
@@ -19,14 +19,11 @@
package com.sk89q.worldguard.bukkit.listener;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.BukkitWorldConfiguration;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.event.entity.DamageEntityEvent;
import com.sk89q.worldguard.bukkit.event.inventory.UseItemEvent;
import com.sk89q.worldguard.bukkit.util.Entities;
import com.sk89q.worldguard.config.ConfigurationManager;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Arrow;
@@ -58,8 +55,7 @@ public class BlockedPotionsListener extends AbstractListener {
if (event.getOriginalEvent() instanceof EntityDamageByEntityEvent) {
EntityDamageByEntityEvent originalEvent = (EntityDamageByEntityEvent) event.getOriginalEvent();
if (Entities.isPotionArrow(originalEvent.getDamager())) { // should take care of backcompat
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
BukkitWorldConfiguration wcfg = (BukkitWorldConfiguration) cfg.get(BukkitAdapter.adapt(event.getWorld()));
BukkitWorldConfiguration wcfg = getWorldConfig(event.getWorld());
PotionEffectType blockedEffect = null;
if (originalEvent.getDamager() instanceof SpectralArrow) {
if (wcfg.blockPotions.contains(PotionEffectType.GLOWING)) {
@@ -96,8 +92,7 @@ public class BlockedPotionsListener extends AbstractListener {
@EventHandler
public void onItemInteract(UseItemEvent event) {
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
BukkitWorldConfiguration wcfg = (BukkitWorldConfiguration) cfg.get(BukkitAdapter.adapt(event.getWorld()));
BukkitWorldConfiguration wcfg = getWorldConfig(event.getWorld());
ItemStack item = event.getItemStack();
if (item.getType() != Material.POTION
@@ -19,7 +19,6 @@
package com.sk89q.worldguard.bukkit.listener;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.event.block.BreakBlockEvent;
import com.sk89q.worldguard.bukkit.event.block.PlaceBlockEvent;
@@ -52,7 +51,7 @@ public class BuildPermissionListener extends AbstractListener {
}
private void tellErrorMessage(CommandSender sender, World world) {
String message = getWorldConfig(BukkitAdapter.adapt(world)).buildPermissionDenyMessage;
String message = getWorldConfig(world).buildPermissionDenyMessage;
if (!message.isEmpty()) {
sender.sendMessage(message);
}
@@ -60,7 +59,7 @@ public class BuildPermissionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onPlaceBlock(final PlaceBlockEvent event) {
if (!getWorldConfig(BukkitAdapter.adapt(event.getWorld())).buildPermissions) return;
if (!getWorldConfig(event.getWorld()).buildPermissions) return;
Object rootCause = event.getCause().getRootCause();
@@ -78,7 +77,7 @@ public class BuildPermissionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onBreakBlock(final BreakBlockEvent event) {
if (!getWorldConfig(BukkitAdapter.adapt(event.getWorld())).buildPermissions) return;
if (!getWorldConfig(event.getWorld()).buildPermissions) return;
Object rootCause = event.getCause().getRootCause();
@@ -96,7 +95,7 @@ public class BuildPermissionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onUseBlock(final UseBlockEvent event) {
if (!getWorldConfig(BukkitAdapter.adapt(event.getWorld())).buildPermissions) return;
if (!getWorldConfig(event.getWorld()).buildPermissions) return;
Object rootCause = event.getCause().getRootCause();
@@ -114,7 +113,7 @@ public class BuildPermissionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onSpawnEntity(SpawnEntityEvent event) {
if (!getWorldConfig(BukkitAdapter.adapt(event.getWorld())).buildPermissions) return;
if (!getWorldConfig(event.getWorld()).buildPermissions) return;
Object rootCause = event.getCause().getRootCause();
@@ -132,7 +131,7 @@ public class BuildPermissionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onDestroyEntity(DestroyEntityEvent event) {
if (!getWorldConfig(BukkitAdapter.adapt(event.getWorld())).buildPermissions) return;
if (!getWorldConfig(event.getWorld()).buildPermissions) return;
Object rootCause = event.getCause().getRootCause();
@@ -150,7 +149,7 @@ public class BuildPermissionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onUseEntity(UseEntityEvent event) {
if (!getWorldConfig(BukkitAdapter.adapt(event.getWorld())).buildPermissions) return;
if (!getWorldConfig(event.getWorld()).buildPermissions) return;
Object rootCause = event.getCause().getRootCause();
@@ -168,7 +167,7 @@ public class BuildPermissionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onDamageEntity(DamageEntityEvent event) {
if (!getWorldConfig(BukkitAdapter.adapt(event.getWorld())).buildPermissions) return;
if (!getWorldConfig(event.getWorld()).buildPermissions) return;
Object rootCause = event.getCause().getRootCause();
@@ -186,7 +185,7 @@ public class BuildPermissionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onUseItem(UseItemEvent event) {
if (!getWorldConfig(BukkitAdapter.adapt(event.getWorld())).buildPermissions) return;
if (!getWorldConfig(event.getWorld()).buildPermissions) return;
Object rootCause = event.getCause().getRootCause();
@@ -59,7 +59,7 @@ public class ChestProtectionListener extends AbstractListener {
final Player player = event.getCause().getFirstPlayer();
if (player != null) {
final BukkitWorldConfiguration wcfg = (BukkitWorldConfiguration) getWorldConfig(WorldGuardPlugin.inst().wrapPlayer(player));
final BukkitWorldConfiguration wcfg = getWorldConfig(event.getWorld());
// Early guard
if (!wcfg.signChestProtection) {
@@ -82,7 +82,7 @@ public class ChestProtectionListener extends AbstractListener {
public void onBreakBlock(final BreakBlockEvent event) {
final Player player = event.getCause().getFirstPlayer();
final BukkitWorldConfiguration wcfg = (BukkitWorldConfiguration) getWorldConfig(BukkitAdapter.adapt(event.getWorld()));
final BukkitWorldConfiguration wcfg = getWorldConfig(event.getWorld());
// Early guard
if (!wcfg.signChestProtection) {
@@ -108,7 +108,7 @@ public class ChestProtectionListener extends AbstractListener {
public void onUseBlock(final UseBlockEvent event) {
final Player player = event.getCause().getFirstPlayer();
final BukkitWorldConfiguration wcfg = (BukkitWorldConfiguration) getWorldConfig(BukkitAdapter.adapt(event.getWorld()));
final BukkitWorldConfiguration wcfg = getWorldConfig(event.getWorld());
// Early guard
if (!wcfg.signChestProtection) {
@@ -133,7 +133,7 @@ public class ChestProtectionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onSignChange(SignChangeEvent event) {
Player player = event.getPlayer();
BukkitWorldConfiguration wcfg = (BukkitWorldConfiguration) getWorldConfig(WorldGuardPlugin.inst().wrapPlayer(player));
final BukkitWorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
if (wcfg.signChestProtection) {
if ("[Lock]".equalsIgnoreCase(event.getLine(0))) {
@@ -22,7 +22,6 @@ package com.sk89q.worldguard.bukkit.listener;
import static com.sk89q.worldguard.bukkit.cause.Cause.create;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.BukkitWorldConfiguration;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.cause.Cause;
@@ -53,6 +52,7 @@ import org.bukkit.Effect;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Tag;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
@@ -142,6 +142,8 @@ import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.projectiles.ProjectileSource;
import org.bukkit.util.Vector;
@@ -244,7 +246,7 @@ public class EventAbstractionListener extends AbstractListener {
boolean allowed = false;
for (Block source : adjacent) {
if (source.getType() == Material.FIRE) {
if (Materials.isFire(source.getType())) {
found++;
if (Events.fireAndTestCancel(new BreakBlockEvent(event, create(source), target))) {
source.setType(Material.AIR);
@@ -273,6 +275,42 @@ public class EventAbstractionListener extends AbstractListener {
}
}
private void handleFallingBlock(EntityChangeBlockEvent event, boolean dropItem) {
Entity entity = event.getEntity();
Block block = event.getBlock();
if (entity instanceof FallingBlock) {
try {
if (dropItem) {
FallingBlock fallingBlock = (FallingBlock) entity;
if (!fallingBlock.getDropItem()) return;
final Material material = fallingBlock.getBlockData().getMaterial();
if (!material.isItem()) return;
ItemStack itemStack = new ItemStack(material, 1);
Item item = block.getWorld().dropItem(fallingBlock.getLocation(), itemStack);
item.setVelocity(new Vector());
if (Events.fireAndTestCancel(new SpawnEntityEvent(event, create(block, entity), item))) {
item.remove();
}
}
} finally {
Cause.untrackParentCause(entity);
}
}
}
private void setDelegateEventMaterialOptions(DelegateEvent event, Material fromType, Material toType) {
if (fromType == Material.FARMLAND && toType == Material.DIRT) {
event.setSilent(true);
event.getRelevantFlags().add(Flags.TRAMPLE_BLOCKS);
} else if (Tag.REDSTONE_ORES.isTagged(fromType)) {
event.setSilent(true);
} else if (fromType == Material.BIG_DRIPLEAF && toType == Material.BIG_DRIPLEAF) {
event.setSilent(true);
event.getRelevantFlags().add(Flags.USE_DRIPLEAF);
}
}
@EventHandler(ignoreCancelled = true)
public void onEntityChangeBlock(EntityChangeBlockEvent event) {
Block block = event.getBlock();
@@ -283,61 +321,35 @@ public class EventAbstractionListener extends AbstractListener {
// Fire two events: one as BREAK and one as PLACE
if (toType != Material.AIR && fromType != Material.AIR) {
boolean trample = fromType == Material.FARMLAND && toType == Material.DIRT;
BreakBlockEvent breakDelagate = new BreakBlockEvent(event, cause, block);
if (trample) {
breakDelagate.setSilent(true);
breakDelagate.getRelevantFlags().add(Flags.TRAMPLE_BLOCKS);
} else if (fromType == Material.REDSTONE_ORE) {
breakDelagate.setSilent(true);
}
setDelegateEventMaterialOptions(breakDelagate, fromType, toType);
boolean denied;
if (!(denied = Events.fireToCancel(event, breakDelagate))) {
PlaceBlockEvent placeDelegate = new PlaceBlockEvent(event, cause, block.getLocation(), toType);
if (trample) {
placeDelegate.setSilent(true);
placeDelegate.getRelevantFlags().add(Flags.TRAMPLE_BLOCKS);
} else if (fromType == Material.REDSTONE_ORE) {
placeDelegate.setSilent(true);
}
setDelegateEventMaterialOptions(placeDelegate, fromType, toType);
denied = Events.fireToCancel(event, placeDelegate);
}
if (denied && entity instanceof Player) {
playDenyEffect((Player) entity, block.getLocation());
}
} else {
if (toType == Material.AIR) {
// Track the source so later we can create a proper chain of causes
if (entity instanceof FallingBlock) {
Cause.trackParentCause(entity, block);
// Switch around the event
Events.fireToCancel(event, new SpawnEntityEvent(event, create(block), entity));
} else {
entityBreakBlockDebounce.debounce(
block, event.getEntity(), event, new BreakBlockEvent(event, cause, block));
}
handleFallingBlock(event, denied);
} else if (toType == Material.AIR) {
// Track the source so later we can create a proper chain of causes
if (entity instanceof FallingBlock) {
Cause.trackParentCause(entity, block);
// Switch around the event
Events.fireToCancel(event, new SpawnEntityEvent(event, create(block), entity));
} else {
boolean wasCancelled = event.isCancelled();
Events.fireToCancel(event, new PlaceBlockEvent(event, cause, block.getLocation(), toType));
if (entity instanceof FallingBlock) {
if (event.isCancelled() && !wasCancelled) {
FallingBlock fallingBlock = (FallingBlock) entity;
final Material material = fallingBlock.getBlockData().getMaterial();
if (!material.isItem()) return;
ItemStack itemStack = new ItemStack(material, 1);
Item item = block.getWorld().dropItem(fallingBlock.getLocation(), itemStack);
item.setVelocity(new Vector());
if (Events.fireAndTestCancel(new SpawnEntityEvent(event, create(block, entity), item))) {
item.remove();
}
}
Cause.untrackParentCause(entity);
}
entityBreakBlockDebounce.debounce(
block, event.getEntity(), event, new BreakBlockEvent(event, cause, block));
}
} else { // toType != Material.AIR && fromType == Material.AIR
boolean denied = Events.fireToCancel(event, new PlaceBlockEvent(event, cause, block.getLocation(), toType));
handleFallingBlock(event, denied);
}
}
@EventHandler(ignoreCancelled = true)
@@ -458,7 +470,11 @@ public class EventAbstractionListener extends AbstractListener {
return;
}
DelegateEvent firedEvent = new UseBlockEvent(event, cause, clicked).setAllowed(hasInteractBypass(clicked));
if (clicked.getType() == Material.REDSTONE_ORE) {
if (Tag.REDSTONE_ORES.isTagged(clicked.getType())) {
firedEvent.setSilent(true);
}
if (clicked.getType() == Material.BIG_DRIPLEAF) {
firedEvent.getRelevantFlags().add(Flags.USE_DRIPLEAF);
firedEvent.setSilent(true);
}
interactDebounce.debounce(clicked, event.getPlayer(), event, firedEvent);
@@ -506,7 +522,7 @@ public class EventAbstractionListener extends AbstractListener {
}
// Special handling of putting out fires
if (event.getAction() == Action.LEFT_CLICK_BLOCK && placed.getType() == Material.FIRE) {
if (event.getAction() == Action.LEFT_CLICK_BLOCK && Materials.isFire(placed.getType())) {
if (Events.fireAndTestCancel(new BreakBlockEvent(event, create(event.getPlayer()), placed))) {
event.setUseInteractedBlock(Result.DENY);
break;
@@ -530,7 +546,7 @@ public class EventAbstractionListener extends AbstractListener {
// emit a "use block here" event where the player is
// standing, which is a hack to protect items that don't
// throw events
if (item != null && ((BukkitWorldConfiguration) getWorldConfig(BukkitAdapter.adapt(player.getWorld()))).blockUseAtFeet.test(item)) {
if (item != null && getWorldConfig(player.getWorld()).blockUseAtFeet.test(item)) {
if (Events.fireAndTestCancel(new UseBlockEvent(event, cause, player.getLocation().getBlock()))) {
event.setUseInteractedBlock(Result.DENY);
}
@@ -556,6 +572,7 @@ public class EventAbstractionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onBlockFertilize(BlockFertilizeEvent event) {
if (event.getBlocks().isEmpty()) return;
Cause cause = create(event.getPlayer(), event.getBlock());
Events.fireToCancel(event, new PlaceBlockEvent(event, cause, event.getBlock().getWorld(), event.getBlocks()));
}
@@ -650,7 +667,7 @@ public class EventAbstractionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onBlockFromTo(BlockFromToEvent event) {
WorldConfiguration config = getWorldConfig(BukkitAdapter.adapt(event.getBlock().getWorld()));
WorldConfiguration config = getWorldConfig(event.getBlock().getWorld());
// This only applies to regions but nothing else cares about high
// frequency events at the moment
@@ -696,7 +713,7 @@ public class EventAbstractionListener extends AbstractListener {
case DISPENSE_EGG:
case EGG:
case SPAWNER_EGG:
if (getWorldConfig(BukkitAdapter.adapt(event.getEntity().getWorld())).strictEntitySpawn) {
if (getWorldConfig(event.getEntity().getWorld()).strictEntitySpawn) {
Events.fireToCancel(event, new SpawnEntityEvent(event, Cause.unknown(), event.getEntity()));
}
break;
@@ -757,7 +774,7 @@ public class EventAbstractionListener extends AbstractListener {
event.setCancelled(true);
}
} else if (event.getState() == PlayerFishEvent.State.CAUGHT_FISH) {
if (Events.fireAndTestCancel(new SpawnEntityEvent(event, create(event.getPlayer(), event.getHook()), event.getHook().getLocation(), EntityType.EXPERIENCE_ORB))) {
if (event.getExpToDrop() > 0 && Events.fireAndTestCancel(new SpawnEntityEvent(event, create(event.getPlayer(), event.getHook()), event.getHook().getLocation(), EntityType.EXPERIENCE_ORB))) {
event.setExpToDrop(0);
}
} else if (event.getState() == PlayerFishEvent.State.CAUGHT_ENTITY) {
@@ -940,10 +957,10 @@ public class EventAbstractionListener extends AbstractListener {
WorldConfiguration wcfg = null;
if (causeHolder instanceof Hopper
&& (wcfg = getWorldConfig(BukkitAdapter.adapt((((Hopper) causeHolder).getWorld())))).ignoreHopperMoveEvents) {
&& (wcfg = getWorldConfig((((Hopper) causeHolder).getWorld()))).ignoreHopperMoveEvents) {
return;
} else if (causeHolder instanceof HopperMinecart
&& (wcfg = getWorldConfig(BukkitAdapter.adapt((((HopperMinecart) causeHolder).getWorld())))).ignoreHopperMoveEvents) {
&& (wcfg = getWorldConfig((((HopperMinecart) causeHolder).getWorld()))).ignoreHopperMoveEvents) {
return;
}
@@ -952,13 +969,13 @@ public class EventAbstractionListener extends AbstractListener {
if ((entry = moveItemDebounce.tryDebounce(event)) != null) {
InventoryHolder sourceHolder;
InventoryHolder targetHolder;
if (HAS_SNAPSHOT_INVHOLDER) {
/*if (HAS_SNAPSHOT_INVHOLDER) {
sourceHolder = event.getSource().getHolder(false);
targetHolder = event.getDestination().getHolder(false);
} else {
} else {*/
sourceHolder = event.getSource().getHolder();
targetHolder = event.getDestination().getHolder();
}
//}
Cause cause;
@@ -1038,6 +1055,17 @@ public class EventAbstractionListener extends AbstractListener {
Block placed = dispenserBlock.getRelative(dispenser.getFacing());
Block clicked = placed.getRelative(dispenser.getFacing());
handleBlockRightClick(event, cause, item, clicked, placed);
// handle special dispenser behavior
if (Materials.isShulkerBox(item.getType())) {
if (Events.fireToCancel(event, new PlaceBlockEvent(event, cause, placed.getLocation(), item.getType()))) {
playDenyEffect(placed.getLocation());
}
} else if (isItemAppliedToBlock(item, placed)) {
if (Events.fireToCancel(event, new PlaceBlockEvent(event, cause, placed.getLocation(), placed.getType()))) {
playDenyEffect(placed.getLocation());
}
}
}
}
@@ -1060,7 +1088,16 @@ public class EventAbstractionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onLingeringApply(AreaEffectCloudApplyEvent event) {
if (!Materials.hasDamageEffect(event.getEntity().getCustomEffects())) {
AreaEffectCloud entity = event.getEntity();
List<PotionEffect> effects = new ArrayList<>();
PotionEffectType baseEffectType = entity.getBasePotionData().getType().getEffectType();
if (baseEffectType != null) {
effects.add(new PotionEffect(baseEffectType, 0, 0));
}
if (entity.hasCustomEffects()) {
effects.addAll(entity.getCustomEffects());
}
if (!Materials.hasDamageEffect(effects)) {
return;
}
Cause cause = create(event.getEntity());
@@ -1084,7 +1121,6 @@ public class EventAbstractionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onTakeLecternBook(PlayerTakeLecternBookEvent event) {
final UseBlockEvent useEvent = new UseBlockEvent(event, create(event.getPlayer()), event.getLectern().getBlock());
useEvent.getRelevantFlags().add(Flags.CHEST_ACCESS);
Events.fireToCancel(event, useEvent);
}
@@ -1194,15 +1230,15 @@ public class EventAbstractionListener extends AbstractListener {
}
private static boolean hasInteractBypass(Block block) {
return ((BukkitWorldConfiguration) getWorldConfig(BukkitAdapter.adapt(block.getWorld()))).allowAllInteract.test(block);
return getWorldConfig(block.getWorld()).allowAllInteract.test(block);
}
private static boolean hasInteractBypass(World world, Material material) {
return ((BukkitWorldConfiguration) getWorldConfig(BukkitAdapter.adapt(world))).allowAllInteract.test(material);
return getWorldConfig(world).allowAllInteract.test(material);
}
private static boolean hasInteractBypass(World world, ItemStack item) {
return ((BukkitWorldConfiguration) getWorldConfig(BukkitAdapter.adapt(world))).allowAllInteract.test(item);
return getWorldConfig(world).allowAllInteract.test(item);
}
private static boolean isBlockModifiedOnClick(Block block, boolean rightClick) {
@@ -1217,13 +1253,13 @@ public class EventAbstractionListener extends AbstractListener {
private static void playDenyEffect(Player player, Location location) {
//player.playSound(location, Sound.SUCCESSFUL_HIT, 0.2f, 0.4f);
if (WorldGuard.getInstance().getPlatform().getGlobalStateManager().particleEffects) {
if (getConfig().particleEffects) {
player.playEffect(location, Effect.SMOKE, BlockFace.UP);
}
}
private static void playDenyEffect(Location location) {
if (WorldGuard.getInstance().getPlatform().getGlobalStateManager().particleEffects) {
if (getConfig().particleEffects) {
location.getWorld().playEffect(location, Effect.SMOKE, BlockFace.UP);
}
}
@@ -19,10 +19,8 @@
package com.sk89q.worldguard.bukkit.listener;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.BukkitWorldConfiguration;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
@@ -64,9 +62,6 @@ public class InvincibilityListener extends AbstractListener {
Player player = (Player) victim;
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
BukkitWorldConfiguration worldConfig =
(BukkitWorldConfiguration) WorldGuard.getInstance().getPlatform().getGlobalStateManager().get((World) localPlayer.getExtent());
if (isInvincible(localPlayer)) {
player.setFireTicks(0);
event.setCancelled(true);
@@ -79,7 +74,7 @@ public class InvincibilityListener extends AbstractListener {
attacker = (Entity) ((Projectile) attacker).getShooter();
}
if (worldConfig.regionInvinciblityRemovesMobs
if (getWorldConfig(player.getWorld()).regionInvinciblityRemovesMobs
&& attacker instanceof LivingEntity && !(attacker instanceof Player)
&& !(attacker instanceof Tameable && ((Tameable) attacker).isTamed())) {
attacker.remove();
@@ -25,6 +25,7 @@ import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.session.MoveType;
import com.sk89q.worldguard.session.Session;
import io.papermc.lib.PaperLib;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
@@ -40,25 +41,28 @@ import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.vehicle.VehicleEnterEvent;
import org.bukkit.plugin.PluginManager;
import org.bukkit.util.Vector;
import org.spigotmc.event.entity.EntityMountEvent;
public class PlayerMoveListener implements Listener {
private final WorldGuardPlugin plugin;
public class PlayerMoveListener extends AbstractListener {
public PlayerMoveListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
super(plugin);
}
@Override
public void registerEvents() {
if (WorldGuard.getInstance().getPlatform().getGlobalStateManager().usePlayerMove) {
PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvents(this, plugin);
PluginManager pm = getPlugin().getServer().getPluginManager();
pm.registerEvents(this, getPlugin());
if (PaperLib.isSpigot()) {
pm.registerEvents(new EntityMountListener(), getPlugin());
}
}
}
@EventHandler
public void onPlayerRespawn(PlayerRespawnEvent event) {
LocalPlayer player = plugin.wrapPlayer(event.getPlayer());
LocalPlayer player = getPlugin().wrapPlayer(event.getPlayer());
Session session = WorldGuard.getInstance().getPlatform().getSessionManager().get(player);
session.testMoveTo(player, BukkitAdapter.adapt(event.getRespawnLocation()), MoveType.RESPAWN, true);
@@ -68,7 +72,7 @@ public class PlayerMoveListener implements Listener {
public void onVehicleEnter(VehicleEnterEvent event) {
Entity entity = event.getEntered();
if (entity instanceof Player) {
LocalPlayer player = plugin.wrapPlayer((Player) entity);
LocalPlayer player = getPlugin().wrapPlayer((Player) entity);
Session session = WorldGuard.getInstance().getPlatform().getSessionManager().get(player);
if (null != session.testMoveTo(player, BukkitAdapter.adapt(event.getVehicle().getLocation()), MoveType.EMBARK, true)) {
event.setCancelled(true);
@@ -87,7 +91,7 @@ public class PlayerMoveListener implements Listener {
}
final Player player = event.getPlayer();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
Session session = WorldGuard.getInstance().getPlatform().getSessionManager().get(localPlayer);
MoveType moveType = MoveType.MOVE;
@@ -128,7 +132,7 @@ public class PlayerMoveListener implements Listener {
player.teleport(override.clone().add(0, 1, 0));
Bukkit.getScheduler().runTaskLater(plugin, () -> player.teleport(override.clone().add(0, 1, 0)), 1);
Bukkit.getScheduler().runTaskLater(getPlugin(), () -> player.teleport(override.clone().add(0, 1, 0)), 1);
}
}
}
@@ -136,7 +140,7 @@ public class PlayerMoveListener implements Listener {
@EventHandler
public void onPlayerQuit(PlayerQuitEvent event) {
final Player player = event.getPlayer();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
Session session = WorldGuard.getInstance().getPlatform().getSessionManager().get(localPlayer);
com.sk89q.worldedit.util.Location loc = session.testMoveTo(localPlayer,
@@ -145,4 +149,18 @@ public class PlayerMoveListener implements Listener {
player.teleport(BukkitAdapter.adapt(loc));
}
}
private class EntityMountListener implements Listener {
@EventHandler
public void onEntityMount(EntityMountEvent event) {
Entity entity = event.getEntity();
if (entity instanceof Player) {
LocalPlayer player = getPlugin().wrapPlayer((Player) entity);
Session session = WorldGuard.getInstance().getPlatform().getSessionManager().get(player);
if (null != session.testMoveTo(player, BukkitAdapter.adapt(event.getMount().getLocation()), MoveType.EMBARK, true)) {
event.setCancelled(true);
}
}
}
}
}
@@ -57,8 +57,7 @@ public class RegionFlagsListener extends AbstractListener {
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onPlaceBlock(final PlaceBlockEvent event) {
com.sk89q.worldedit.world.World weWorld = BukkitAdapter.adapt(event.getWorld());
if (!isRegionSupportEnabled(weWorld)) return; // Region support disabled
if (!isRegionSupportEnabled(event.getWorld())) return; // Region support disabled
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
@@ -80,10 +79,9 @@ public class RegionFlagsListener extends AbstractListener {
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onBreakBlock(final BreakBlockEvent event) {
com.sk89q.worldedit.world.World weWorld = BukkitAdapter.adapt(event.getWorld());
if (!isRegionSupportEnabled(weWorld)) return; // Region support disabled
if (!isRegionSupportEnabled(event.getWorld())) return; // Region support disabled
WorldConfiguration config = getWorldConfig(weWorld);
WorldConfiguration config = getWorldConfig(event.getWorld());
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
Block block;
@@ -118,8 +116,8 @@ public class RegionFlagsListener extends AbstractListener {
public void onEntityDamage(EntityDamageEvent event) {
Entity entity = event.getEntity();
World world = entity.getWorld();
if (!isRegionSupportEnabled(world)) return; // Region support disabled
if (!isRegionSupportEnabled(BukkitAdapter.adapt(world))) return; // Region support disabled
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
if (entity instanceof Player && event.getCause() == DamageCause.FALL) {
@@ -58,8 +58,10 @@ import org.bukkit.entity.Item;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.Player;
import org.bukkit.entity.Tameable;
import org.bukkit.event.Event;
import org.bukkit.event.Event.Result;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerTakeLecternBookEvent;
import org.bukkit.event.vehicle.VehicleExitEvent;
import java.util.ArrayList;
@@ -134,15 +136,14 @@ public class RegionProtectionListener extends AbstractListener {
if (rootCause instanceof Player) {
Player player = (Player) rootCause;
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
com.sk89q.worldedit.world.World localWorld = BukkitAdapter.adapt(world);
WorldConfiguration config = getWorldConfig(localWorld);
WorldConfiguration config = getWorldConfig(world);
if (config.fakePlayerBuildOverride && InteropUtils.isFakePlayer(player)) {
return true;
}
return !pvp && WorldGuard.getInstance().getPlatform().getSessionManager().hasBypass(localPlayer, localWorld);
LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
return !pvp && WorldGuard.getInstance().getPlatform().getSessionManager().hasBypass(localPlayer, localPlayer.getWorld());
} else {
return false;
}
@@ -151,7 +152,7 @@ public class RegionProtectionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onPlaceBlock(final PlaceBlockEvent event) {
if (event.getResult() == Result.ALLOW) return; // Don't care about events that have been pre-allowed
if (!isRegionSupportEnabled(BukkitAdapter.adapt(event.getWorld()))) return; // Region support disabled
if (!isRegionSupportEnabled(event.getWorld())) return; // Region support disabled
if (isWhitelisted(event.getCause(), event.getWorld(), false)) return; // Whitelisted cause
final Material type = event.getEffectiveMaterial();
@@ -161,7 +162,7 @@ public class RegionProtectionListener extends AbstractListener {
// Don't check liquid flow unless it's enabled
if (event.getCause().getRootCause() instanceof Block
&& Materials.isLiquid(type)
&& !getWorldConfig(BukkitAdapter.adapt(event.getWorld())).checkLiquidFlow) {
&& !getWorldConfig(event.getWorld()).checkLiquidFlow) {
return;
}
@@ -170,9 +171,9 @@ public class RegionProtectionListener extends AbstractListener {
String what;
/* Flint and steel, fire charge, etc. */
if (type == Material.FIRE) {
if (Materials.isFire(type)) {
Block block = event.getCause().getFirstBlock();
boolean fire = block != null && block.getType() == Material.FIRE;
boolean fire = block != null && Materials.isFire(type);
boolean lava = block != null && Materials.isLava(block.getType());
List<StateFlag> flags = new ArrayList<>();
flags.add(Flags.BLOCK_PLACE);
@@ -204,7 +205,7 @@ public class RegionProtectionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onBreakBlock(final BreakBlockEvent event) {
if (event.getResult() == Result.ALLOW) return; // Don't care about events that have been pre-allowed
if (!isRegionSupportEnabled(BukkitAdapter.adapt(event.getWorld()))) return; // Region support disabled
if (!isRegionSupportEnabled(event.getWorld())) return; // Region support disabled
if (isWhitelisted(event.getCause(), event.getWorld(), false)) return; // Whitelisted cause
final RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
@@ -240,7 +241,7 @@ public class RegionProtectionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onUseBlock(final UseBlockEvent event) {
if (event.getResult() == Result.ALLOW) return; // Don't care about events that have been pre-allowed
if (!isRegionSupportEnabled(BukkitAdapter.adapt(event.getWorld()))) return; // Region support disabled
if (!isRegionSupportEnabled(event.getWorld())) return; // Region support disabled
if (isWhitelisted(event.getCause(), event.getWorld(), false)) return; // Whitelisted cause
final Material type = event.getEffectiveMaterial();
@@ -261,11 +262,26 @@ public class RegionProtectionListener extends AbstractListener {
canUse = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.CHEST_ACCESS));
what = "open that";
/* Inventory for blocks with the possibility to be only use, e.g. lectern */
} else if (handleAsInventoryUsage(event.getOriginalEvent())) {
canUse = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.CHEST_ACCESS));
what = "take that";
/* Anvils */
} else if (Materials.isAnvil(type)) {
canUse = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.USE_ANVIL));
what = "use that";
/* Beds */
} else if (Materials.isBed(type)) {
canUse = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.INTERACT, Flags.SLEEP));
what = "sleep";
/* Respawn Anchors */
} else if(type == Material.RESPAWN_ANCHOR) {
canUse = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.INTERACT, Flags.RESPAWN_ANCHORS));
what = "use anchors";
/* TNT */
} else if (type == Material.TNT) {
canUse = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.INTERACT, Flags.TNT));
@@ -294,7 +310,7 @@ public class RegionProtectionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onSpawnEntity(SpawnEntityEvent event) {
if (event.getResult() == Result.ALLOW) return; // Don't care about events that have been pre-allowed
if (!isRegionSupportEnabled(BukkitAdapter.adapt(event.getWorld()))) return; // Region support disabled
if (!isRegionSupportEnabled(event.getWorld())) return; // Region support disabled
if (isWhitelisted(event.getCause(), event.getWorld(), false)) return; // Whitelisted cause
Location target = event.getTarget();
@@ -328,12 +344,7 @@ public class RegionProtectionListener extends AbstractListener {
/* Everything else */
} else {
canSpawn = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event));
if (event.getEntity() instanceof Item) {
what = "drop items";
} else {
what = "place things";
}
what = "place things";
}
if (!canSpawn) {
@@ -345,7 +356,7 @@ public class RegionProtectionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onDestroyEntity(DestroyEntityEvent event) {
if (event.getResult() == Result.ALLOW) return; // Don't care about events that have been pre-allowed
if (!isRegionSupportEnabled(BukkitAdapter.adapt(event.getWorld()))) return; // Region support disabled
if (!isRegionSupportEnabled(event.getWorld())) return; // Region support disabled
if (isWhitelisted(event.getCause(), event.getWorld(), false)) return; // Whitelisted cause
Location target = event.getTarget();
@@ -381,7 +392,7 @@ public class RegionProtectionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onUseEntity(UseEntityEvent event) {
if (event.getResult() == Result.ALLOW) return; // Don't care about events that have been pre-allowed
if (!isRegionSupportEnabled(BukkitAdapter.adapt(event.getWorld()))) return; // Region support disabled
if (!isRegionSupportEnabled(event.getWorld())) return; // Region support disabled
if (isWhitelisted(event.getCause(), event.getWorld(), false)) return; // Whitelisted cause
Location target = event.getTarget();
@@ -400,7 +411,8 @@ public class RegionProtectionListener extends AbstractListener {
what = "use that";
/* Paintings, item frames, etc. */
} else if (Entities.isConsideredBuildingIfUsed(entity)) {
if (type == EntityType.ITEM_FRAME && event.getCause().getFirstPlayer() != null
if ((type == EntityType.ITEM_FRAME || type == EntityType.GLOW_ITEM_FRAME)
&& event.getCause().getFirstPlayer() != null
&& ((ItemFrame) entity).getItem().getType() != Material.AIR) {
canUse = query.testBuild(BukkitAdapter.adapt(target), associable, combine(event, Flags.ITEM_FRAME_ROTATE));
what = "change that";
@@ -431,7 +443,7 @@ public class RegionProtectionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onDamageEntity(DamageEntityEvent event) {
if (event.getResult() == Result.ALLOW) return; // Don't care about events that have been pre-allowed
if (!isRegionSupportEnabled(BukkitAdapter.adapt(event.getWorld()))) return; // Region support disabled
if (!isRegionSupportEnabled(event.getWorld())) return; // Region support disabled
// Whitelist check is below
com.sk89q.worldedit.util.Location target = BukkitAdapter.adapt(event.getTarget());
@@ -507,7 +519,7 @@ public class RegionProtectionListener extends AbstractListener {
@EventHandler(ignoreCancelled = true)
public void onVehicleExit(VehicleExitEvent event) {
Entity vehicle = event.getVehicle();
if (!isRegionSupportEnabled(BukkitAdapter.adapt(vehicle.getWorld()))) return; // Region support disabled
if (!isRegionSupportEnabled(vehicle.getWorld())) return; // Region support disabled
Entity exited = event.getExited();
if (vehicle instanceof Tameable && exited instanceof Player) {
@@ -530,10 +542,6 @@ public class RegionProtectionListener extends AbstractListener {
}
}
private boolean isWhitelistedEntity(Entity entity) {
return Entities.isNonPlayerCreature(entity);
}
/**
* Combine the flags from a delegate event with an array of flags.
*
@@ -552,4 +560,14 @@ public class RegionProtectionListener extends AbstractListener {
return flags;
}
/**
* Check if that event should be handled as inventory usage, e.g. if a player takes a book from a lectern
*
* @param event the event to handle
* @return whether it should be handled as inventory usage
*/
private static boolean handleAsInventoryUsage(Event event) {
return event instanceof PlayerTakeLecternBookEvent;
}
}
@@ -31,15 +31,16 @@ import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.util.SpongeUtil;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.data.Waterlogged;
import org.bukkit.entity.Player;
import org.bukkit.entity.Snowman;
import org.bukkit.event.Cancellable;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockExplodeEvent;
@@ -61,12 +62,9 @@ import org.bukkit.inventory.meta.ItemMeta;
/**
* The listener for block events.
*
* @author sk89q
*/
public class WorldGuardBlockListener implements Listener {
public class WorldGuardBlockListener extends AbstractListener {
private WorldGuardPlugin plugin;
/**
* Construct the object.
@@ -74,34 +72,7 @@ public class WorldGuardBlockListener implements Listener {
* @param plugin The plugin instance
*/
public WorldGuardBlockListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Register events.
*/
public void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
/**
* Get the world configuration given a world.
*
* @param world The world to get the configuration for.
* @return The configuration for {@code world}
*/
private WorldConfiguration getWorldConfig(World world) {
return WorldGuard.getInstance().getPlatform().getGlobalStateManager().get(BukkitAdapter.adapt(world));
}
/**
* Get the world configuration given a player.
*
* @param player The player to get the wold from
* @return The {@link BukkitWorldConfiguration} for the player's world
*/
private WorldConfiguration getWorldConfig(Player player) {
return getWorldConfig(player.getWorld());
super(plugin);
}
/*
@@ -110,7 +81,7 @@ public class WorldGuardBlockListener implements Listener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent event) {
Player player = event.getPlayer();
WorldConfiguration wcfg = getWorldConfig(player);
WorldConfiguration wcfg = getWorldConfig(player.getWorld());
if (!wcfg.itemDurability) {
ItemStack held = player.getInventory().getItemInMainHand();
@@ -132,18 +103,20 @@ public class WorldGuardBlockListener implements Listener {
Block blockFrom = event.getBlock();
Block blockTo = event.getToBlock();
boolean isWater = blockFrom.getType() == Material.WATER;
boolean isLava = blockFrom.getType() == Material.LAVA;
boolean isAir = blockFrom.getType() == Material.AIR;
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
ConfigurationManager cfg = getConfig();
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
Material fromType = blockFrom.getType();
boolean isWater = Materials.isWater(fromType);
boolean isLava = fromType == Material.LAVA;
boolean isAir = fromType == Material.AIR;
WorldConfiguration wcfg = getWorldConfig(world);
if (wcfg.simulateSponge && isWater) {
int ox = blockTo.getX();
int oy = blockTo.getY();
@@ -217,13 +190,14 @@ public class WorldGuardBlockListener implements Listener {
Block block = event.getBlock();
World world = block.getWorld();
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = getWorldConfig(world);
ConfigurationManager cfg = getConfig();
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
WorldConfiguration wcfg = getWorldConfig(world);
boolean isFireSpread = cause == IgniteCause.SPREAD;
if (wcfg.preventLightningFire && cause == IgniteCause.LIGHTNING) {
@@ -243,7 +217,7 @@ public class WorldGuardBlockListener implements Listener {
if (wcfg.blockLighter && (cause == IgniteCause.FLINT_AND_STEEL || cause == IgniteCause.FIREBALL)
&& event.getPlayer() != null
&& !plugin.hasPermission(event.getPlayer(), "worldguard.override.lighter")) {
&& !getPlugin().hasPermission(event.getPlayer(), "worldguard.override.lighter")) {
event.setCancelled(true);
return;
}
@@ -304,14 +278,15 @@ public class WorldGuardBlockListener implements Listener {
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockBurn(BlockBurnEvent event) {
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
BukkitWorldConfiguration wcfg = (BukkitWorldConfiguration) getWorldConfig(event.getBlock().getWorld());
ConfigurationManager cfg = getConfig();
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
BukkitWorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
if (wcfg.disableFireSpread) {
event.setCancelled(true);
return;
@@ -320,7 +295,7 @@ public class WorldGuardBlockListener implements Listener {
if (wcfg.fireSpreadDisableToggle) {
Block block = event.getBlock();
event.setCancelled(true);
checkAndDestroyAround(block.getWorld(), block.getX(), block.getY(), block.getZ(), Material.FIRE);
checkAndDestroyFireAround(block.getWorld(), block.getX(), block.getY(), block.getZ());
return;
}
@@ -329,7 +304,7 @@ public class WorldGuardBlockListener implements Listener {
if (wcfg.disableFireSpreadBlocks.contains(BukkitAdapter.asBlockType(block.getType()).getId())) {
event.setCancelled(true);
checkAndDestroyAround(block.getWorld(), block.getX(), block.getY(), block.getZ(), Material.FIRE);
checkAndDestroyFireAround(block.getWorld(), block.getX(), block.getY(), block.getZ());
return;
}
}
@@ -348,24 +323,24 @@ public class WorldGuardBlockListener implements Listener {
WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().getApplicableRegions(BukkitAdapter.adapt(block.getLocation()));
if (!set.testState(null, Flags.FIRE_SPREAD)) {
checkAndDestroyAround(block.getWorld(), x, y, z, Material.FIRE);
checkAndDestroyFireAround(block.getWorld(), x, y, z);
event.setCancelled(true);
}
}
}
private void checkAndDestroyAround(World world, int x, int y, int z, Material required) {
checkAndDestroy(world, x, y, z + 1, required);
checkAndDestroy(world, x, y, z - 1, required);
checkAndDestroy(world, x, y + 1, z, required);
checkAndDestroy(world, x, y - 1, z, required);
checkAndDestroy(world, x + 1, y, z, required);
checkAndDestroy(world, x - 1, y, z, required);
private void checkAndDestroyFireAround(World world, int x, int y, int z) {
checkAndDestroyFire(world, x, y, z + 1);
checkAndDestroyFire(world, x, y, z - 1);
checkAndDestroyFire(world, x, y + 1, z);
checkAndDestroyFire(world, x, y - 1, z);
checkAndDestroyFire(world, x + 1, y, z);
checkAndDestroyFire(world, x - 1, y, z);
}
private void checkAndDestroy(World world, int x, int y, int z, Material required) {
if (world.getBlockAt(x, y, z).getType() == required) {
private void checkAndDestroyFire(World world, int x, int y, int z) {
if (Materials.isFire(world.getBlockAt(x, y, z).getType())) {
world.getBlockAt(x, y, z).setType(Material.AIR);
}
}
@@ -375,15 +350,15 @@ public class WorldGuardBlockListener implements Listener {
*/
@EventHandler(ignoreCancelled = true)
public void onBlockPhysics(BlockPhysicsEvent event) {
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
ConfigurationManager cfg = getConfig();
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
Material id = event.getBlock().getType();
WorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
final Material id = event.getBlock().getType();
if (id == Material.GRAVEL && wcfg.noPhysicsGravel) {
event.setCancelled(true);
@@ -400,7 +375,7 @@ public class WorldGuardBlockListener implements Listener {
return;
}
if (wcfg.ropeLadders && event.getBlock().getType() == Material.LADDER) {
if (id == Material.LADDER && wcfg.ropeLadders) {
if (event.getBlock().getRelative(0, 1, 0).getType() == Material.LADDER) {
event.setCancelled(true);
return;
@@ -467,14 +442,15 @@ public class WorldGuardBlockListener implements Listener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onLeavesDecay(LeavesDecayEvent event) {
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
ConfigurationManager cfg = getConfig();
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
WorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
if (wcfg.disableLeafDecay) {
event.setCancelled(true);
return;
@@ -492,14 +468,16 @@ public class WorldGuardBlockListener implements Listener {
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockForm(BlockFormEvent event) {
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
ConfigurationManager cfg = getConfig();
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
WorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
Material type = event.getNewState().getType();
if (event instanceof EntityBlockFormEvent) {
@@ -550,14 +528,14 @@ public class WorldGuardBlockListener implements Listener {
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockSpread(BlockSpreadEvent event) {
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
ConfigurationManager cfg = getConfig();
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
WorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
Material newType = event.getNewState().getType(); // craftbukkit randomly gives AIR as event.getSource even if that block is not air
if (Materials.isMushroom(newType)) {
@@ -597,7 +575,7 @@ public class WorldGuardBlockListener implements Listener {
}
}
if (newType == Material.VINE || newType == Material.KELP) {
if (Materials.isVine(newType)) {
if (wcfg.disableVineGrowth) {
event.setCancelled(true);
return;
@@ -609,21 +587,28 @@ public class WorldGuardBlockListener implements Listener {
return;
}
}
handleGrow(event, event.getBlock().getLocation(), newType);
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockGrow(BlockGrowEvent event) {
WorldConfiguration wcfg = getWorldConfig(event.getBlock().getWorld());
Location loc = event.getBlock().getLocation();
final Material type = event.getNewState().getType();
handleGrow(event, loc, type);
}
private void handleGrow(Cancellable event, Location loc, Material type) {
WorldConfiguration wcfg = getWorldConfig(loc.getWorld());
if (Materials.isCrop(type)) {
if (wcfg.disableCropGrowth) {
event.setCancelled(false);
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.queryState(BukkitAdapter.adapt(event.getBlock().getLocation()), (RegionAssociable) null, Flags.CROP_GROWTH))) {
.queryState(BukkitAdapter.adapt(loc), (RegionAssociable) null, Flags.CROP_GROWTH))) {
event.setCancelled(true);
return;
}
@@ -691,7 +676,7 @@ public class WorldGuardBlockListener implements Listener {
@EventHandler(ignoreCancelled = true)
public void onBlockExplode(BlockExplodeEvent event) {
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
ConfigurationManager cfg = getConfig();
if (cfg.activityHaltToggle) {
event.setCancelled(true);
@@ -62,7 +62,6 @@ import org.bukkit.entity.Wolf;
import org.bukkit.entity.minecart.ExplosiveMinecart;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import org.bukkit.event.entity.CreeperPowerEvent;
@@ -82,6 +81,7 @@ import org.bukkit.event.entity.ExplosionPrimeEvent;
import org.bukkit.event.entity.FoodLevelChangeEvent;
import org.bukkit.event.entity.PigZapEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.vehicle.VehicleEnterEvent;
import org.bukkit.event.world.PortalCreateEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.projectiles.ProjectileSource;
@@ -90,12 +90,8 @@ import java.util.Set;
/**
* Listener for entity related events.
*
* @author sk89q
*/
public class WorldGuardEntityListener implements Listener {
private WorldGuardPlugin plugin;
public class WorldGuardEntityListener extends AbstractListener {
/**
* Construct the object;
@@ -103,36 +99,28 @@ public class WorldGuardEntityListener implements Listener {
* @param plugin The plugin instance
*/
public WorldGuardEntityListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Register events.
*/
public void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
super(plugin);
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityInteract(EntityInteractEvent event) {
Entity entity = event.getEntity();
Block block = event.getBlock();
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(entity.getWorld()));
WorldConfiguration wcfg = getWorldConfig(block.getWorld());
if (block.getType() == Material.FARMLAND) {
if (/* entity instanceof Creature && // catch for any entity (not thrown for players) */
wcfg.disableCreatureCropTrampling) {
event.setCancelled(true);
}
if (block.getType() == Material.FARMLAND && wcfg.disableCreatureCropTrampling) {
event.setCancelled(true);
return;
}
if (block.getType() == Material.TURTLE_EGG && wcfg.disableCreatureTurtleEggTrampling) {
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onEntityDeath(EntityDeathEvent event) {
WorldConfiguration wcfg =
WorldGuard.getInstance().getPlatform().getGlobalStateManager().get(BukkitAdapter.adapt(event.getEntity().getWorld()));
WorldConfiguration wcfg = getWorldConfig(event.getEntity().getWorld());
if (event instanceof PlayerDeathEvent && wcfg.disableDeathMessages) {
((PlayerDeathEvent) event).setDeathMessage("");
@@ -143,8 +131,7 @@ public class WorldGuardEntityListener implements Listener {
Entity defender = event.getEntity();
DamageCause type = event.getCause();
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(defender.getWorld()));
WorldConfiguration wcfg = getWorldConfig(defender.getWorld());
if (defender instanceof Wolf && ((Wolf) defender).isTamed()) {
if (wcfg.antiWolfDumbness && !(type == DamageCause.VOID)) {
@@ -194,7 +181,7 @@ public class WorldGuardEntityListener implements Listener {
// handled anywhere else
if (type == DamageCause.BLOCK_EXPLOSION
&& (wcfg.blockOtherExplosions
|| (wcfg.explosionFlagCancellation
|| ((wcfg.explosionFlagCancellation || Entities.isConsideredBuildingIfUsed(defender))
&& !StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery()
.queryState(BukkitAdapter.adapt(defender.getLocation()), (RegionAssociable) null, Flags.OTHER_EXPLOSION))))) {
event.setCancelled(true);
@@ -214,8 +201,7 @@ public class WorldGuardEntityListener implements Listener {
Entity attacker = event.getDamager();
Entity defender = event.getEntity();
WorldConfiguration wcfg =
WorldGuard.getInstance().getPlatform().getGlobalStateManager().get(BukkitAdapter.adapt(defender.getWorld()));
WorldConfiguration wcfg = getWorldConfig(defender.getWorld());
if (defender instanceof ItemFrame) {
if (checkItemFrameProtection(attacker, (ItemFrame) defender)) {
@@ -243,7 +229,7 @@ public class WorldGuardEntityListener implements Listener {
if (defender instanceof Player) {
Player player = (Player) defender;
LocalPlayer localPlayer = plugin.wrapPlayer(player);
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
if (wcfg.disableLightningDamage && event.getCause() == DamageCause.LIGHTNING) {
event.setCancelled(true);
@@ -302,11 +288,10 @@ public class WorldGuardEntityListener implements Listener {
return;
}
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(defender.getWorld()));
WorldConfiguration wcfg = getWorldConfig(defender.getWorld());
if (defender instanceof Player) {
Player player = (Player) defender;
LocalPlayer localPlayer = plugin.wrapPlayer(player);
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
// Check Mob
@@ -371,8 +356,7 @@ public class WorldGuardEntityListener implements Listener {
Entity defender = event.getEntity();
DamageCause type = event.getCause();
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(defender.getWorld()));
WorldConfiguration wcfg = getWorldConfig(defender.getWorld());
if (defender instanceof Wolf && ((Wolf) defender).isTamed()) {
if (wcfg.antiWolfDumbness) {
@@ -393,14 +377,14 @@ public class WorldGuardEntityListener implements Listener {
if (wcfg.useRegions) {
ApplicableRegionSet set = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().getApplicableRegions(localPlayer.getLocation());
if (!set.testState(plugin.wrapPlayer(player), Flags.MOB_DAMAGE)) {
if (!set.testState(getPlugin().wrapPlayer(player), Flags.MOB_DAMAGE)) {
event.setCancelled(true);
return;
}
}
}
if (type == DamageCause.DROWNING && cfg.hasAmphibiousMode(localPlayer)) {
if (type == DamageCause.DROWNING && getConfig().hasAmphibiousMode(localPlayer)) {
player.setRemainingAir(player.getMaximumAir());
event.setCancelled(true);
return;
@@ -452,10 +436,7 @@ public class WorldGuardEntityListener implements Listener {
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityExplode(EntityExplodeEvent event) {
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
Location l = event.getLocation();
World world = l.getWorld();
BukkitWorldConfiguration wcfg = (BukkitWorldConfiguration) cfg.get(BukkitAdapter.adapt(world));
ConfigurationManager cfg = getConfig();
Entity ent = event.getEntity();
if (cfg.activityHaltToggle) {
@@ -464,6 +445,7 @@ public class WorldGuardEntityListener implements Listener {
return;
}
BukkitWorldConfiguration wcfg = getWorldConfig(event.getLocation().getWorld());
if (ent instanceof Creeper) {
if (wcfg.blockCreeperExplosions) {
event.setCancelled(true);
@@ -570,8 +552,7 @@ public class WorldGuardEntityListener implements Listener {
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onExplosionPrime(ExplosionPrimeEvent event) {
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(event.getEntity().getWorld()));
ConfigurationManager cfg = getConfig();
Entity ent = event.getEntity();
if (cfg.activityHaltToggle) {
@@ -580,6 +561,7 @@ public class WorldGuardEntityListener implements Listener {
return;
}
BukkitWorldConfiguration wcfg = getWorldConfig(ent.getWorld());
if (event.getEntityType() == EntityType.WITHER) {
if (wcfg.blockWitherExplosions) {
event.setCancelled(true);
@@ -611,14 +593,14 @@ public class WorldGuardEntityListener implements Listener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onCreatureSpawn(CreatureSpawnEvent event) {
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
ConfigurationManager cfg = getConfig();
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(event.getEntity().getWorld()));
WorldConfiguration wcfg = getWorldConfig(event.getEntity().getWorld());
// allow spawning of creatures from plugins
if (!wcfg.blockPluginSpawning && event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.CUSTOM) {
@@ -673,19 +655,18 @@ public class WorldGuardEntityListener implements Listener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onCreatePortal(PortalCreateEvent event) {
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
final com.sk89q.worldedit.world.World world = BukkitAdapter.adapt(event.getWorld());
WorldConfiguration wcfg = cfg.get(world);
WorldConfiguration wcfg = getWorldConfig(event.getWorld());
if (wcfg.regionNetherPortalProtection
&& event.getReason() == PortalCreateEvent.CreateReason.NETHER_PAIR
&& !event.getBlocks().isEmpty()) {
final com.sk89q.worldedit.world.World world = BukkitAdapter.adapt(event.getWorld());
final RegionManager regionManager = WorldGuard.getInstance().getPlatform().getRegionContainer()
.get(world);
if (regionManager == null) return;
LocalPlayer associable = null;
if (event.getEntity() instanceof Player) {
associable = plugin.wrapPlayer(((Player) event.getEntity()));
associable = getPlugin().wrapPlayer(((Player) event.getEntity()));
if (WorldGuard.getInstance().getPlatform().getSessionManager().hasBypass(associable, world)) {
return;
}
@@ -718,9 +699,8 @@ public class WorldGuardEntityListener implements Listener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityTransform(EntityTransformEvent event) {
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
final Entity entity = event.getEntity();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(entity.getWorld()));
WorldConfiguration wcfg = getWorldConfig(entity.getWorld());
final EntityType type = entity.getType();
if (wcfg.disableVillagerZap && type == EntityType.VILLAGER
@@ -731,9 +711,8 @@ public class WorldGuardEntityListener implements Listener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPigZap(PigZapEvent event) {
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
final Entity entity = event.getEntity();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(entity.getWorld()));
WorldConfiguration wcfg = getWorldConfig(entity.getWorld());
if (wcfg.disablePigZap) {
event.setCancelled(true);
@@ -742,8 +721,8 @@ public class WorldGuardEntityListener implements Listener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onCreeperPower(CreeperPowerEvent event) {
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(event.getEntity().getWorld()));
final Entity entity = event.getEntity();
WorldConfiguration wcfg = getWorldConfig(entity.getWorld());
if (wcfg.disableCreeperPower) {
event.setCancelled(true);
@@ -758,10 +737,8 @@ public class WorldGuardEntityListener implements Listener {
}
Entity ent = event.getEntity();
World world = ent.getWorld();
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(world));
WorldConfiguration wcfg = getWorldConfig(ent.getWorld());
if (wcfg.disableHealthRegain) {
event.setCancelled(true);
@@ -781,11 +758,10 @@ public class WorldGuardEntityListener implements Listener {
if (event.getItem() != null) return;
HumanEntity ent = event.getEntity();
if (!(ent instanceof Player)) return;
LocalPlayer player = WorldGuardPlugin.inst().wrapPlayer((Player) ent);
if (event.getFoodLevel() > player.getFoodLevel()) return;
if (event.getFoodLevel() > ent.getFoodLevel()) return;
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
LocalPlayer player = WorldGuardPlugin.inst().wrapPlayer((Player) ent);
WorldConfiguration wcfg = getWorldConfig(ent.getWorld());
if (wcfg.useRegions
&& !WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().testState(
@@ -802,11 +778,8 @@ public class WorldGuardEntityListener implements Listener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityChangeBlock(EntityChangeBlockEvent event) {
Entity ent = event.getEntity();
Block block = event.getBlock();
Location location = block.getLocation();
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(ent.getWorld()));
WorldConfiguration wcfg = getWorldConfig(ent.getWorld());
if (ent instanceof FallingBlock) {
Material id = event.getBlock().getType();
@@ -830,6 +803,7 @@ public class WorldGuardEntityListener implements Listener {
return;
}
if (wcfg.useRegions) {
Location location = event.getBlock().getLocation();
if (!StateFlag.test(WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().queryState(BukkitAdapter.adapt(location), (RegionAssociable) null, Flags.WITHER_DAMAGE))) {
event.setCancelled(true);
return;
@@ -843,6 +817,15 @@ public class WorldGuardEntityListener implements Listener {
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onVehicleEnter(VehicleEnterEvent event) {
BukkitWorldConfiguration wcfg = getWorldConfig(event.getEntered().getWorld());
if (wcfg.blockEntityVehicleEntry && !(event.getEntered() instanceof Player)) {
event.setCancelled(true);
}
}
/**
* Checks regions and config settings to protect items from being knocked
* out of item frames.
@@ -851,9 +834,8 @@ public class WorldGuardEntityListener implements Listener {
* @return true if the event should be cancelled
*/
private boolean checkItemFrameProtection(Entity attacker, ItemFrame defender) {
World world = attacker.getWorld();
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(world));
World world = defender.getWorld();
WorldConfiguration wcfg = getWorldConfig(world);
if (wcfg.useRegions) {
// bukkit throws this event when a player attempts to remove an item from a frame
if (!(attacker instanceof Player)) {
@@ -22,7 +22,6 @@ package com.sk89q.worldguard.bukkit.listener;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.config.ConfigurationManager;
import com.sk89q.worldguard.config.WorldConfiguration;
import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.flags.Flags;
@@ -38,7 +37,6 @@ import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.hanging.HangingBreakByEntityEvent;
import org.bukkit.event.hanging.HangingBreakEvent;
import org.bukkit.event.hanging.HangingBreakEvent.RemoveCause;
@@ -46,35 +44,18 @@ import org.bukkit.projectiles.ProjectileSource;
/**
* Listener for painting related events.
*
* @author BangL <henno.rickowski@gmail.com>
*/
public class WorldGuardHangingListener implements Listener {
public class WorldGuardHangingListener extends AbstractListener {
private WorldGuardPlugin plugin;
/**
* Construct the object;
*
* @param plugin The plugin instance
*/
public WorldGuardHangingListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Register events.
*/
public void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
super(plugin);
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onHangingBreak(HangingBreakEvent event) {
Hanging hanging = event.getEntity();
World world = hanging.getWorld();
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(world));
WorldConfiguration wcfg = getWorldConfig(world);
if (event instanceof HangingBreakByEntityEvent) {
HangingBreakByEntityEvent entityEvent = (HangingBreakByEntityEvent) event;
@@ -48,7 +48,6 @@ import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
@@ -61,45 +60,31 @@ import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.PluginManager;
import javax.annotation.Nullable;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
/**
* Handles all events thrown in relation to a player.
*/
public class WorldGuardPlayerListener implements Listener {
public class WorldGuardPlayerListener extends AbstractListener {
private static final Logger log = Logger.getLogger(WorldGuardPlayerListener.class.getCanonicalName());
private static final Pattern opPattern = Pattern.compile("^/(?:minecraft:)?(?:bukkit:)?(?:de)?op(?:\\s.*)?$", Pattern.CASE_INSENSITIVE);
private WorldGuardPlugin plugin;
/**
* Construct the object;
*
* @param plugin
*/
public WorldGuardPlayerListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
super(plugin);
}
/**
* Register events.
*/
public void registerEvents() {
PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvents(this, plugin);
}
@EventHandler
public void onPlayerGameModeChange(PlayerGameModeChangeEvent event) {
Player player = event.getPlayer();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
WorldConfiguration wcfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager().get(localPlayer.getWorld());
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
WorldConfiguration wcfg = getWorldConfig(player.getWorld());
Session session = WorldGuard.getInstance().getPlatform().getSessionManager().getIfPresent(localPlayer);
if (session != null) {
GameModeFlag handler = session.getHandler(GameModeFlag.class);
@@ -117,11 +102,10 @@ public class WorldGuardPlayerListener implements Listener {
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
World world = player.getWorld();
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(localPlayer.getWorld());
ConfigurationManager cfg = getConfig();
WorldConfiguration wcfg = getWorldConfig(world);
if (cfg.activityHaltToggle) {
player.sendMessage(ChatColor.YELLOW
@@ -155,9 +139,8 @@ public class WorldGuardPlayerListener implements Listener {
@EventHandler(ignoreCancelled = true)
public void onPlayerChat(AsyncPlayerChatEvent event) {
Player player = event.getPlayer();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
WorldConfiguration wcfg =
WorldGuard.getInstance().getPlatform().getGlobalStateManager().get(localPlayer.getWorld());
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
WorldConfiguration wcfg = getWorldConfig(player.getWorld());
if (wcfg.useRegions) {
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
ApplicableRegionSet chatFrom = query.getApplicableRegions(localPlayer.getLocation());
@@ -172,7 +155,7 @@ public class WorldGuardPlayerListener implements Listener {
boolean anyRemoved = false;
for (Iterator<Player> i = event.getRecipients().iterator(); i.hasNext();) {
Player rPlayer = i.next();
LocalPlayer rLocal = plugin.wrapPlayer(rPlayer);
LocalPlayer rLocal = getPlugin().wrapPlayer(rPlayer);
if (!query.testState(rLocal.getLocation(), rLocal, Flags.RECEIVE_CHAT)) {
i.remove();
anyRemoved = true;
@@ -187,7 +170,7 @@ public class WorldGuardPlayerListener implements Listener {
@EventHandler(ignoreCancelled = true)
public void onPlayerLogin(PlayerLoginEvent event) {
Player player = event.getPlayer();
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
ConfigurationManager cfg = getConfig();
String hostKey = cfg.hostKeys.get(player.getUniqueId().toString());
if (hostKey == null) {
@@ -229,11 +212,11 @@ public class WorldGuardPlayerListener implements Listener {
handlePhysicalInteract(event);
}
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(world));
ConfigurationManager cfg = getConfig();
WorldConfiguration wcfg = getWorldConfig(world);
if (wcfg.removeInfiniteStacks
&& !plugin.hasPermission(player, "worldguard.override.infinite-stack")) {
&& !getPlugin().hasPermission(player, "worldguard.override.infinite-stack")) {
int slot = player.getInventory().getHeldItemSlot();
ItemStack heldItem = player.getInventory().getItem(slot);
if (heldItem != null && heldItem.getAmount() < 0) {
@@ -259,13 +242,12 @@ public class WorldGuardPlayerListener implements Listener {
Player player = event.getPlayer();
@Nullable ItemStack item = event.getItem();
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(world));
WorldConfiguration wcfg = getWorldConfig(world);
// Infinite stack removal
if (Materials.isInventoryBlock(type)
&& wcfg.removeInfiniteStacks
&& !plugin.hasPermission(player, "worldguard.override.infinite-stack")) {
&& !getPlugin().hasPermission(player, "worldguard.override.infinite-stack")) {
for (int slot = 0; slot < 40; slot++) {
ItemStack heldItem = player.getInventory().getItem(slot);
if (heldItem != null && heldItem.getAmount() < 0) {
@@ -280,9 +262,9 @@ public class WorldGuardPlayerListener implements Listener {
ApplicableRegionSet set =
WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().getApplicableRegions(BukkitAdapter.adapt(block.getLocation()));
//ApplicableRegionSet placedInSet = plugin.getRegionContainer().createQuery().getApplicableRegions(placedIn.getLocation());
LocalPlayer localPlayer = plugin.wrapPlayer(player);
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
if (item != null && item.getType().getKey().toString().equals(wcfg.regionWand) && plugin.hasPermission(player, "worldguard.region.wand")) {
if (item != null && item.getType().getKey().toString().equals(wcfg.regionWand) && getPlugin().hasPermission(player, "worldguard.region.wand")) {
if (set.size() > 0) {
player.sendMessage(ChatColor.YELLOW + "Can you build? " + (set.testState(localPlayer, Flags.BUILD) ? "Yes" : "No"));
@@ -314,13 +296,16 @@ public class WorldGuardPlayerListener implements Listener {
Player player = event.getPlayer();
Block block = event.getClickedBlock(); //not actually clicked but whatever
//int type = block.getTypeId();
Material type = block.getType();
World world = player.getWorld();
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(world));
WorldConfiguration wcfg = getWorldConfig(world);
if (block.getType() == Material.FARMLAND && wcfg.disablePlayerCropTrampling) {
if (type == Material.FARMLAND && wcfg.disablePlayerCropTrampling) {
event.setCancelled(true);
return;
}
if (type == Material.TURTLE_EGG && wcfg.disablePlayerTurtleEggTrampling) {
event.setCancelled(true);
return;
}
@@ -329,12 +314,10 @@ public class WorldGuardPlayerListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerRespawn(PlayerRespawnEvent event) {
Player player = event.getPlayer();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(localPlayer.getWorld());
WorldConfiguration wcfg = getWorldConfig(player.getWorld());
if (wcfg.useRegions) {
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
ApplicableRegionSet set =
WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().getApplicableRegions(localPlayer.getLocation());
@@ -349,12 +332,10 @@ public class WorldGuardPlayerListener implements Listener {
@EventHandler(priority = EventPriority.HIGH)
public void onItemHeldChange(PlayerItemHeldEvent event) {
Player player = event.getPlayer();
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(player.getWorld()));
WorldConfiguration wcfg = getWorldConfig(player.getWorld());
if (wcfg.removeInfiniteStacks
&& !plugin.hasPermission(player, "worldguard.override.infinite-stack")) {
&& !getPlugin().hasPermission(player, "worldguard.override.infinite-stack")) {
int newSlot = event.getNewSlot();
ItemStack heldItem = player.getInventory().getItem(newSlot);
if (heldItem != null && heldItem.getAmount() < 0) {
@@ -367,15 +348,14 @@ public class WorldGuardPlayerListener implements Listener {
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onPlayerTeleport(PlayerTeleportEvent event) {
Player player = event.getPlayer();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(localPlayer.getWorld());
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
ConfigurationManager cfg = getConfig();
WorldConfiguration wcfg = getWorldConfig(player.getWorld());
if (wcfg.useRegions && cfg.usePlayerTeleports) {
ApplicableRegionSet set =
WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().getApplicableRegions(BukkitAdapter.adapt(event.getTo()));
ApplicableRegionSet setFrom =
WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery().getApplicableRegions(BukkitAdapter.adapt(event.getFrom()));
RegionQuery query = WorldGuard.getInstance().getPlatform().getRegionContainer().createQuery();
ApplicableRegionSet set = query.getApplicableRegions(BukkitAdapter.adapt(event.getTo()));
ApplicableRegionSet setFrom = query.getApplicableRegions(BukkitAdapter.adapt(event.getFrom()));
if (event.getCause() == TeleportCause.ENDER_PEARL) {
if (!WorldGuard.getInstance().getPlatform().getSessionManager().hasBypass(localPlayer, localPlayer.getWorld())) {
@@ -389,7 +369,7 @@ public class WorldGuardPlayerListener implements Listener {
message = set.queryValue(localPlayer, Flags.ENTRY_DENY_MESSAGE);
}
if (cancel) {
if (message != null) {
if (message != null && !message.isEmpty()) {
player.sendMessage(message);
}
event.setCancelled(true);
@@ -408,7 +388,7 @@ public class WorldGuardPlayerListener implements Listener {
message = set.queryValue(localPlayer, Flags.ENTRY_DENY_MESSAGE);
}
if (cancel) {
if (message != null) {
if (message != null && !message.isEmpty()) {
player.sendMessage(message);
}
event.setCancelled(true);
@@ -427,9 +407,9 @@ public class WorldGuardPlayerListener implements Listener {
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
Player player = event.getPlayer();
LocalPlayer localPlayer = plugin.wrapPlayer(player);
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(localPlayer.getWorld());
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
ConfigurationManager cfg = getConfig();
WorldConfiguration wcfg = getWorldConfig(player.getWorld());
if (wcfg.useRegions && !WorldGuard.getInstance().getPlatform().getSessionManager().hasBypass(localPlayer, localPlayer.getWorld())) {
ApplicableRegionSet set =
@@ -19,42 +19,28 @@
package com.sk89q.worldguard.bukkit.listener;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.BukkitConfigurationManager;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.event.server.PluginEnableEvent;
import org.bukkit.plugin.PluginManager;
/**
* @author zml2008
*/
public class WorldGuardServerListener implements Listener {
private final WorldGuardPlugin plugin;
public class WorldGuardServerListener extends AbstractListener {
public WorldGuardServerListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
public void registerEvents() {
PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvents(this, plugin);
super(plugin);
}
@EventHandler
public void onPluginEnable(PluginEnableEvent event) {
if (event.getPlugin().getDescription().getName().equalsIgnoreCase("CommandBook")) {
((BukkitConfigurationManager) WorldGuard.getInstance().getPlatform().getGlobalStateManager()).updateCommandBookGodMode();
getConfig().updateCommandBookGodMode();
}
}
@EventHandler
public void onPluginDisable(PluginDisableEvent event) {
if (event.getPlugin().getDescription().getName().equalsIgnoreCase("CommandBook")) {
((BukkitConfigurationManager) WorldGuard.getInstance().getPlatform().getGlobalStateManager()).updateCommandBookGodMode();
getConfig().updateCommandBookGodMode();
}
}
}
@@ -24,7 +24,6 @@ import com.sk89q.worldedit.util.Location;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.config.ConfigurationManager;
import com.sk89q.worldguard.config.WorldConfiguration;
import com.sk89q.worldguard.session.MoveType;
import com.sk89q.worldguard.util.Locations;
@@ -32,31 +31,16 @@ import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.entity.Vehicle;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.vehicle.VehicleMoveEvent;
import org.bukkit.util.Vector;
import java.util.List;
import java.util.stream.Collectors;
public class WorldGuardVehicleListener implements Listener {
public class WorldGuardVehicleListener extends AbstractListener {
private WorldGuardPlugin plugin;
/**
* Construct the object;
*
* @param plugin
*/
public WorldGuardVehicleListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Register events.
*/
public void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
super(plugin);
}
@EventHandler
@@ -69,14 +53,13 @@ public class WorldGuardVehicleListener implements Listener {
return;
}
World world = vehicle.getWorld();
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(world));
WorldConfiguration wcfg = getWorldConfig(world);
if (wcfg.useRegions) {
// Did we move a block?
if (Locations.isDifferentBlock(BukkitAdapter.adapt(event.getFrom()), BukkitAdapter.adapt(event.getTo()))) {
for (Player player : playerPassengers) {
LocalPlayer localPlayer = plugin.wrapPlayer(player);
LocalPlayer localPlayer = getPlugin().wrapPlayer(player);
Location lastValid;
if ((lastValid = WorldGuard.getInstance().getPlatform().getSessionManager().get(localPlayer)
.testMoveTo(localPlayer, BukkitAdapter.adapt(event.getTo()), MoveType.RIDE)) != null) {
@@ -22,7 +22,6 @@ package com.sk89q.worldguard.bukkit.listener;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.config.ConfigurationManager;
import com.sk89q.worldguard.config.WorldConfiguration;
import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.flags.Flags;
@@ -33,35 +32,19 @@ import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.weather.LightningStrikeEvent;
import org.bukkit.event.weather.ThunderChangeEvent;
import org.bukkit.event.weather.WeatherChangeEvent;
public class WorldGuardWeatherListener implements Listener {
public class WorldGuardWeatherListener extends AbstractListener {
/**
* Plugin.
*/
private WorldGuardPlugin plugin;
/**
* Construct the object;
*
* @param plugin The plugin instance
*/
public WorldGuardWeatherListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
public void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
super(plugin);
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onWeatherChange(WeatherChangeEvent event) {
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(event.getWorld()));
WorldConfiguration wcfg = getWorldConfig(event.getWorld());
if (event.toWeatherState()) {
if (wcfg.disableWeather) {
@@ -76,8 +59,7 @@ public class WorldGuardWeatherListener implements Listener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onThunderChange(ThunderChangeEvent event) {
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(event.getWorld()));
WorldConfiguration wcfg = getWorldConfig(event.getWorld());
if (event.toThunderState()) {
if (wcfg.disableThunder) {
@@ -92,8 +74,7 @@ public class WorldGuardWeatherListener implements Listener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onLightningStrike(LightningStrikeEvent event) {
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(event.getWorld()));
WorldConfiguration wcfg = getWorldConfig(event.getWorld());
if (!wcfg.disallowedLightningBlocks.isEmpty()) {
final Block target = event.getLightning().getLocation().getBlock();
@@ -34,30 +34,17 @@ import org.bukkit.event.world.WorldLoadEvent;
import java.util.logging.Logger;
public class WorldGuardWorldListener implements Listener {
public class WorldGuardWorldListener extends AbstractListener {
private static final Logger log = Logger.getLogger(WorldGuardWorldListener.class.getCanonicalName());
private WorldGuardPlugin plugin;
/**
* Construct the object;
*
* @param plugin The plugin instance
*/
public WorldGuardWorldListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Register events.
*/
public void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
super(plugin);
}
@EventHandler
public void onChunkLoad(ChunkLoadEvent event) {
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
ConfigurationManager cfg = getConfig();
if (cfg.activityHaltToggle) {
int removed = 0;
@@ -89,8 +76,7 @@ public class WorldGuardWorldListener implements Listener {
* @param world The specified world
*/
public void initWorld(World world) {
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(BukkitAdapter.adapt(world));
WorldConfiguration wcfg = getWorldConfig(world);
if (wcfg.alwaysRaining && !wcfg.disableWeather) {
world.setStorm(true);
} else if (wcfg.disableWeather && !wcfg.alwaysRaining) {
@@ -19,7 +19,6 @@
package com.sk89q.worldguard.bukkit.listener;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.event.entity.SpawnEntityEvent;
import com.sk89q.worldguard.config.WorldConfiguration;
@@ -42,7 +41,7 @@ public class WorldRulesListener extends AbstractListener {
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onSpawnEntity(final SpawnEntityEvent event) {
if (event.getEffectiveType() == EntityType.EXPERIENCE_ORB) {
WorldConfiguration config = getWorldConfig(BukkitAdapter.adapt(event.getWorld()));
WorldConfiguration config = getWorldConfig(event.getWorld());
if (config.disableExpDrops) {
event.setCancelled(true);
@@ -53,7 +52,7 @@ public class WorldRulesListener extends AbstractListener {
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPotionEffect(EntityPotionEffectEvent event) {
if (event.getCause() == EntityPotionEffectEvent.Cause.CONDUIT) {
WorldConfiguration config = getWorldConfig(BukkitAdapter.adapt(event.getEntity().getWorld()));
WorldConfiguration config = getWorldConfig(event.getEntity().getWorld());
if (config.disableConduitEffects) {
event.setCancelled(true);
@@ -27,6 +27,7 @@ import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.bukkit.event.player.ProcessPlayerEvent;
import com.sk89q.worldguard.session.AbstractSessionManager;
import com.sk89q.worldguard.session.Session;
import com.sk89q.worldguard.session.handler.Handler;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
@@ -40,6 +41,13 @@ import java.util.Collection;
*/
public class BukkitSessionManager extends AbstractSessionManager implements Runnable, Listener {
private boolean useTimings;
@Override
protected Handler.Factory<? extends Handler> wrapForRegistration(Handler.Factory<? extends Handler> factory) {
return useTimings ? new TimedHandlerFactory(factory) : factory;
}
/**
* Re-initialize handlers and clear "last position," "last state," etc.
* information for all players.
@@ -75,9 +83,17 @@ public class BukkitSessionManager extends AbstractSessionManager implements Runn
public boolean hasBypass(LocalPlayer player, World world) {
if (player instanceof BukkitPlayer) {
if (((BukkitPlayer) player).getPlayer().hasMetadata("NPC")
&& WorldGuard.getInstance().getPlatform().getGlobalStateManager().get(world).fakePlayerBuildOverride)
&& WorldGuard.getInstance().getPlatform().getGlobalStateManager().get(world).fakePlayerBuildOverride)
return true;
}
return super.hasBypass(player, world);
}
public boolean isUsingTimings() {
return useTimings;
}
public void setUsingTimings(boolean useTimings) {
this.useTimings = useTimings;
}
}
@@ -0,0 +1,132 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit.session;
import co.aikar.timings.lib.MCTiming;
import co.aikar.timings.lib.TimingManager;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.session.MoveType;
import com.sk89q.worldguard.session.Session;
import com.sk89q.worldguard.session.handler.Handler;
import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
import javax.annotation.Nullable;
import java.security.CodeSource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
class TimedHandlerFactory extends Handler.Factory<Handler> {
private static final TimingManager TIMINGS = TimingManager.of(WorldGuardPlugin.inst());
private static final MCTiming UNKNOWN_SOURCE = TIMINGS.of("Third-Party Session Handlers");
private static final Map<CodeSource, TimingManager> PLUGIN_SOURCES = new HashMap<>();
private final Handler.Factory<?> factory;
private final MCTiming timing;
TimedHandlerFactory(Handler.Factory<?> factory) {
this.factory = factory;
this.timing = makeTiming();
}
private MCTiming makeTiming() {
CodeSource codeSource = factory.getClass().getProtectionDomain().getCodeSource();
TimingManager owner = PLUGIN_SOURCES.computeIfAbsent(codeSource, source -> {
for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
CodeSource pluginSource = plugin.getClass().getProtectionDomain().getCodeSource();
if (Objects.equals(pluginSource, source)) {
return TimingManager.of(plugin);
}
}
return null;
});
String handlerName = factory.getClass().getEnclosingClass().getSimpleName();
return owner == null
? TIMINGS.of(handlerName, UNKNOWN_SOURCE)
: owner.of(handlerName, owner.of("Session Handlers"));
}
@Override
public Handler create(Session session) {
return new TimedHandler(factory.create(session), session, timing);
}
static class TimedHandler extends Handler {
private final Handler handler;
private final MCTiming timing;
TimedHandler(Handler innerHandler, Session session, MCTiming timing) {
super(session);
this.handler = innerHandler;
this.timing = timing;
}
@Override
public void initialize(LocalPlayer player, Location current, ApplicableRegionSet set) {
try (MCTiming ignored = timing.startTiming()) {
handler.initialize(player, current, set);
}
}
@Override
public boolean testMoveTo(LocalPlayer player, Location from, Location to, ApplicableRegionSet toSet, MoveType moveType) {
try (MCTiming ignored = timing.startTiming()) {
return handler.testMoveTo(player, from, to, toSet, moveType);
}
}
@Override
public boolean onCrossBoundary(LocalPlayer player, Location from, Location to, ApplicableRegionSet toSet, Set<ProtectedRegion> entered, Set<ProtectedRegion> exited, MoveType moveType) {
try (MCTiming ignored = timing.startTiming()) {
return handler.onCrossBoundary(player, from, to, toSet, entered, exited, moveType);
}
}
@Override
public void tick(LocalPlayer player, ApplicableRegionSet set) {
try (MCTiming ignored = timing.startTiming()) {
handler.tick(player, set);
}
}
@Nullable
@Override
public StateFlag.State getInvincibility(LocalPlayer player) {
try (MCTiming ignored = timing.startTiming()) {
return handler.getInvincibility(player);
}
}
@Override
public Handler getWrappedHandler() {
return handler;
}
}
}
@@ -33,12 +33,12 @@ import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Minecart;
import org.bukkit.entity.Monster;
import org.bukkit.entity.NPC;
import org.bukkit.entity.Pig;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.Shulker;
import org.bukkit.entity.Slime;
import org.bukkit.entity.SpectralArrow;
import org.bukkit.entity.Steerable;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.entity.Tameable;
import org.bukkit.entity.Vehicle;
@@ -91,7 +91,7 @@ public final class Entities {
* @return true if the entity can be ridden
*/
public static boolean isRiddenOnUse(Entity entity) {
return entity instanceof Pig ? ((Pig) entity).hasSaddle() : entity instanceof Vehicle;
return entity instanceof Steerable ? ((Steerable) entity).hasSaddle() : entity instanceof Vehicle;
}
/**
@@ -52,27 +52,7 @@ public final class Materials {
private static final Map<Material, Integer> MATERIAL_FLAGS = new EnumMap<>(Material.class);
private static final Set<PotionEffectType> DAMAGE_EFFECTS = new HashSet<>();
private static Set<Material> shulkerBoxes = new HashSet<>();
static {
shulkerBoxes.add(Material.SHULKER_BOX);
shulkerBoxes.add(Material.WHITE_SHULKER_BOX);
shulkerBoxes.add(Material.ORANGE_SHULKER_BOX);
shulkerBoxes.add(Material.MAGENTA_SHULKER_BOX);
shulkerBoxes.add(Material.LIGHT_BLUE_SHULKER_BOX);
shulkerBoxes.add(Material.YELLOW_SHULKER_BOX);
shulkerBoxes.add(Material.LIME_SHULKER_BOX);
shulkerBoxes.add(Material.PINK_SHULKER_BOX);
shulkerBoxes.add(Material.GRAY_SHULKER_BOX);
shulkerBoxes.add(Material.LIGHT_GRAY_SHULKER_BOX);
shulkerBoxes.add(Material.CYAN_SHULKER_BOX);
shulkerBoxes.add(Material.PURPLE_SHULKER_BOX);
shulkerBoxes.add(Material.BLUE_SHULKER_BOX);
shulkerBoxes.add(Material.BROWN_SHULKER_BOX);
shulkerBoxes.add(Material.GREEN_SHULKER_BOX);
shulkerBoxes.add(Material.RED_SHULKER_BOX);
shulkerBoxes.add(Material.BLACK_SHULKER_BOX);
ENTITY_ITEMS.put(EntityType.PAINTING, Material.PAINTING);
ENTITY_ITEMS.put(EntityType.ARROW, Material.ARROW);
ENTITY_ITEMS.put(EntityType.SNOWBALL, Material.SNOWBALL);
@@ -80,6 +60,7 @@ public final class Materials {
ENTITY_ITEMS.put(EntityType.ENDER_PEARL, Material.ENDER_PEARL);
ENTITY_ITEMS.put(EntityType.THROWN_EXP_BOTTLE, Material.EXPERIENCE_BOTTLE);
ENTITY_ITEMS.put(EntityType.ITEM_FRAME, Material.ITEM_FRAME);
ENTITY_ITEMS.put(EntityType.GLOW_ITEM_FRAME, Material.GLOW_ITEM_FRAME);
ENTITY_ITEMS.put(EntityType.PRIMED_TNT, Material.TNT);
ENTITY_ITEMS.put(EntityType.FIREWORK, Material.FIREWORK_ROCKET);
ENTITY_ITEMS.put(EntityType.MINECART_COMMAND, Material.COMMAND_BLOCK_MINECART);
@@ -104,12 +85,8 @@ public final class Materials {
MATERIAL_FLAGS.put(Material.LAVA, 0);
MATERIAL_FLAGS.put(Material.SAND, 0);
MATERIAL_FLAGS.put(Material.GRAVEL, 0);
MATERIAL_FLAGS.put(Material.GOLD_ORE, 0);
MATERIAL_FLAGS.put(Material.IRON_ORE, 0);
MATERIAL_FLAGS.put(Material.COAL_ORE, 0);
MATERIAL_FLAGS.put(Material.SPONGE, 0);
MATERIAL_FLAGS.put(Material.GLASS, 0);
MATERIAL_FLAGS.put(Material.LAPIS_ORE, 0);
MATERIAL_FLAGS.put(Material.LAPIS_BLOCK, 0);
MATERIAL_FLAGS.put(Material.DISPENSER, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.SANDSTONE, 0);
@@ -140,8 +117,7 @@ public final class Materials {
MATERIAL_FLAGS.put(Material.FIRE, 0);
MATERIAL_FLAGS.put(Material.SPAWNER, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.CHEST, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.REDSTONE_WIRE, 0);
MATERIAL_FLAGS.put(Material.DIAMOND_ORE, 0);
MATERIAL_FLAGS.put(Material.REDSTONE_WIRE, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.DIAMOND_BLOCK, 0);
MATERIAL_FLAGS.put(Material.CRAFTING_TABLE, 0);
MATERIAL_FLAGS.put(Material.WHEAT, 0);
@@ -152,7 +128,6 @@ public final class Materials {
MATERIAL_FLAGS.put(Material.COBBLESTONE_STAIRS, 0);
MATERIAL_FLAGS.put(Material.LEVER, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.STONE_PRESSURE_PLATE, 0);
MATERIAL_FLAGS.put(Material.REDSTONE_ORE, 0);
MATERIAL_FLAGS.put(Material.REDSTONE_WALL_TORCH, 0);
MATERIAL_FLAGS.put(Material.REDSTONE_TORCH, 0);
MATERIAL_FLAGS.put(Material.SNOW, 0);
@@ -161,7 +136,6 @@ public final class Materials {
MATERIAL_FLAGS.put(Material.CACTUS, 0);
MATERIAL_FLAGS.put(Material.CLAY, 0);
MATERIAL_FLAGS.put(Material.JUKEBOX, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.OAK_FENCE, 0);
MATERIAL_FLAGS.put(Material.PUMPKIN, 0);
MATERIAL_FLAGS.put(Material.NETHERRACK, 0);
MATERIAL_FLAGS.put(Material.SOUL_SAND, 0);
@@ -195,21 +169,13 @@ public final class Materials {
MATERIAL_FLAGS.put(Material.PUMPKIN_STEM, 0);
MATERIAL_FLAGS.put(Material.MELON_STEM, 0);
MATERIAL_FLAGS.put(Material.VINE, 0);
MATERIAL_FLAGS.put(Material.SPRUCE_FENCE_GATE, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.ACACIA_FENCE_GATE, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.BIRCH_FENCE_GATE, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.DARK_OAK_FENCE_GATE, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.JUNGLE_FENCE_GATE, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.OAK_FENCE_GATE, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.BRICK_STAIRS, 0);
MATERIAL_FLAGS.put(Material.MYCELIUM, 0);
MATERIAL_FLAGS.put(Material.LILY_PAD, 0);
MATERIAL_FLAGS.put(Material.NETHER_BRICK, 0);
MATERIAL_FLAGS.put(Material.NETHER_BRICK_FENCE, 0);
MATERIAL_FLAGS.put(Material.NETHER_BRICK_STAIRS, 0);
MATERIAL_FLAGS.put(Material.ENCHANTING_TABLE, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.BREWING_STAND, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.CAULDRON, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.END_PORTAL, 0);
MATERIAL_FLAGS.put(Material.END_PORTAL_FRAME, 0);
MATERIAL_FLAGS.put(Material.END_STONE, 0);
@@ -217,7 +183,6 @@ public final class Materials {
MATERIAL_FLAGS.put(Material.REDSTONE_LAMP, 0);
MATERIAL_FLAGS.put(Material.COCOA, 0);
MATERIAL_FLAGS.put(Material.SANDSTONE_STAIRS, 0);
MATERIAL_FLAGS.put(Material.EMERALD_ORE, 0);
MATERIAL_FLAGS.put(Material.ENDER_CHEST, 0);
MATERIAL_FLAGS.put(Material.TRIPWIRE_HOOK, 0);
MATERIAL_FLAGS.put(Material.TRIPWIRE, 0);
@@ -257,18 +222,13 @@ public final class Materials {
MATERIAL_FLAGS.put(Material.IRON_TRAPDOOR, 0);
MATERIAL_FLAGS.put(Material.RED_SANDSTONE, 0);
MATERIAL_FLAGS.put(Material.RED_SANDSTONE_STAIRS, 0);
MATERIAL_FLAGS.put(Material.SPRUCE_FENCE, 0);
MATERIAL_FLAGS.put(Material.BIRCH_FENCE, 0);
MATERIAL_FLAGS.put(Material.JUNGLE_FENCE, 0);
MATERIAL_FLAGS.put(Material.DARK_OAK_FENCE, 0);
MATERIAL_FLAGS.put(Material.ACACIA_FENCE, 0);
MATERIAL_FLAGS.put(Material.SPRUCE_DOOR, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.BIRCH_DOOR, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.JUNGLE_DOOR, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.ACACIA_DOOR, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.DARK_OAK_DOOR, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.GRASS_PATH, 0);
MATERIAL_FLAGS.put(Material.DIRT_PATH, 0);
MATERIAL_FLAGS.put(Material.CHORUS_PLANT, 0);
MATERIAL_FLAGS.put(Material.CHORUS_FLOWER, 0);
MATERIAL_FLAGS.put(Material.BEETROOTS, 0);
@@ -693,24 +653,156 @@ public final class Materials {
MATERIAL_FLAGS.put(Material.SWEET_BERRIES, 0);
// 1.15
try {
MATERIAL_FLAGS.put(Material.BEEHIVE, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.BEE_NEST, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.HONEY_BLOCK, 0);
MATERIAL_FLAGS.put(Material.HONEYCOMB_BLOCK, 0);
MATERIAL_FLAGS.put(Material.HONEY_BOTTLE, 0);
MATERIAL_FLAGS.put(Material.HONEYCOMB, 0);
} catch (NoSuchFieldError ignored) {
}
MATERIAL_FLAGS.put(Material.BEEHIVE, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.BEE_NEST, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.HONEY_BLOCK, 0);
MATERIAL_FLAGS.put(Material.HONEYCOMB_BLOCK, 0);
MATERIAL_FLAGS.put(Material.HONEY_BOTTLE, 0);
MATERIAL_FLAGS.put(Material.HONEYCOMB, 0);
// Fake tags
for (Material m : shulkerBoxes) {
MATERIAL_FLAGS.put(m, MODIFIED_ON_RIGHT);
}
// 1.16
MATERIAL_FLAGS.put(Material.ANCIENT_DEBRIS, 0);
MATERIAL_FLAGS.put(Material.BASALT, 0);
MATERIAL_FLAGS.put(Material.BLACKSTONE, 0);
MATERIAL_FLAGS.put(Material.CHAIN, 0);
MATERIAL_FLAGS.put(Material.CHISELED_NETHER_BRICKS, 0);
MATERIAL_FLAGS.put(Material.CHISELED_POLISHED_BLACKSTONE, 0);
MATERIAL_FLAGS.put(Material.CRACKED_NETHER_BRICKS, 0);
MATERIAL_FLAGS.put(Material.CRACKED_POLISHED_BLACKSTONE_BRICKS, 0);
MATERIAL_FLAGS.put(Material.CRIMSON_FUNGUS, 0);
MATERIAL_FLAGS.put(Material.CRIMSON_NYLIUM, 0);
MATERIAL_FLAGS.put(Material.CRIMSON_ROOTS, 0);
MATERIAL_FLAGS.put(Material.CRIMSON_TRAPDOOR, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.CRYING_OBSIDIAN, 0);
MATERIAL_FLAGS.put(Material.GILDED_BLACKSTONE, 0);
MATERIAL_FLAGS.put(Material.LODESTONE, 0);
MATERIAL_FLAGS.put(Material.NETHERITE_AXE, 0);
MATERIAL_FLAGS.put(Material.NETHERITE_BLOCK, 0);
MATERIAL_FLAGS.put(Material.NETHERITE_BOOTS, 0);
MATERIAL_FLAGS.put(Material.NETHERITE_CHESTPLATE, 0);
MATERIAL_FLAGS.put(Material.NETHERITE_HELMET, 0);
MATERIAL_FLAGS.put(Material.NETHERITE_HOE, 0);
MATERIAL_FLAGS.put(Material.NETHERITE_INGOT, 0);
MATERIAL_FLAGS.put(Material.NETHERITE_LEGGINGS, 0);
MATERIAL_FLAGS.put(Material.NETHERITE_PICKAXE, 0);
MATERIAL_FLAGS.put(Material.NETHERITE_SCRAP, 0);
MATERIAL_FLAGS.put(Material.NETHERITE_SHOVEL, 0);
MATERIAL_FLAGS.put(Material.NETHERITE_SWORD, 0);
MATERIAL_FLAGS.put(Material.NETHER_SPROUTS, 0);
MATERIAL_FLAGS.put(Material.PIGLIN_BANNER_PATTERN, 0);
MATERIAL_FLAGS.put(Material.POLISHED_BASALT, 0);
MATERIAL_FLAGS.put(Material.POLISHED_BLACKSTONE, 0);
MATERIAL_FLAGS.put(Material.POLISHED_BLACKSTONE_BRICKS, 0);
MATERIAL_FLAGS.put(Material.POLISHED_BLACKSTONE_PRESSURE_PLATE, 0);
MATERIAL_FLAGS.put(Material.QUARTZ_BRICKS, 0);
MATERIAL_FLAGS.put(Material.RESPAWN_ANCHOR, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.SHROOMLIGHT, 0);
MATERIAL_FLAGS.put(Material.SOUL_CAMPFIRE, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.SOUL_FIRE, 0);
MATERIAL_FLAGS.put(Material.SOUL_LANTERN, 0);
MATERIAL_FLAGS.put(Material.SOUL_SOIL, 0);
MATERIAL_FLAGS.put(Material.SOUL_TORCH, 0);
MATERIAL_FLAGS.put(Material.SOUL_WALL_TORCH, 0);
MATERIAL_FLAGS.put(Material.TARGET, 0);
MATERIAL_FLAGS.put(Material.TWISTING_VINES, 0);
MATERIAL_FLAGS.put(Material.TWISTING_VINES_PLANT, 0);
MATERIAL_FLAGS.put(Material.WARPED_FUNGUS, 0);
MATERIAL_FLAGS.put(Material.WARPED_FUNGUS_ON_A_STICK, 0);
MATERIAL_FLAGS.put(Material.WARPED_NYLIUM, 0);
MATERIAL_FLAGS.put(Material.WARPED_ROOTS, 0);
MATERIAL_FLAGS.put(Material.WARPED_TRAPDOOR, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.WARPED_WART_BLOCK, 0);
MATERIAL_FLAGS.put(Material.WEEPING_VINES, 0);
MATERIAL_FLAGS.put(Material.WEEPING_VINES_PLANT, 0);
// 1.17
MATERIAL_FLAGS.put(Material.DEEPSLATE, 0);
MATERIAL_FLAGS.put(Material.COBBLED_DEEPSLATE, 0);
MATERIAL_FLAGS.put(Material.POLISHED_DEEPSLATE, 0);
MATERIAL_FLAGS.put(Material.CALCITE, 0);
MATERIAL_FLAGS.put(Material.TUFF, 0);
MATERIAL_FLAGS.put(Material.DRIPSTONE_BLOCK, 0);
MATERIAL_FLAGS.put(Material.ROOTED_DIRT, 0);
MATERIAL_FLAGS.put(Material.RAW_IRON_BLOCK, 0);
MATERIAL_FLAGS.put(Material.RAW_COPPER_BLOCK, 0);
MATERIAL_FLAGS.put(Material.RAW_GOLD_BLOCK, 0);
MATERIAL_FLAGS.put(Material.AMETHYST_BLOCK, 0);
MATERIAL_FLAGS.put(Material.BUDDING_AMETHYST, 0);
MATERIAL_FLAGS.put(Material.EXPOSED_COPPER, 0);
MATERIAL_FLAGS.put(Material.WEATHERED_COPPER, 0);
MATERIAL_FLAGS.put(Material.OXIDIZED_COPPER, 0);
MATERIAL_FLAGS.put(Material.CUT_COPPER, 0);
MATERIAL_FLAGS.put(Material.EXPOSED_CUT_COPPER, 0);
MATERIAL_FLAGS.put(Material.WEATHERED_CUT_COPPER, 0);
MATERIAL_FLAGS.put(Material.OXIDIZED_CUT_COPPER, 0);
MATERIAL_FLAGS.put(Material.WAXED_COPPER_BLOCK, 0);
MATERIAL_FLAGS.put(Material.WAXED_EXPOSED_COPPER, 0);
MATERIAL_FLAGS.put(Material.WAXED_WEATHERED_COPPER, 0);
MATERIAL_FLAGS.put(Material.WAXED_OXIDIZED_COPPER, 0);
MATERIAL_FLAGS.put(Material.AZALEA, 0);
MATERIAL_FLAGS.put(Material.FLOWERING_AZALEA, 0);
MATERIAL_FLAGS.put(Material.COPPER_BLOCK, 0);
MATERIAL_FLAGS.put(Material.WAXED_CUT_COPPER, 0);
MATERIAL_FLAGS.put(Material.WAXED_EXPOSED_CUT_COPPER, 0);
MATERIAL_FLAGS.put(Material.WAXED_WEATHERED_CUT_COPPER, 0);
MATERIAL_FLAGS.put(Material.WAXED_OXIDIZED_CUT_COPPER, 0);
MATERIAL_FLAGS.put(Material.TINTED_GLASS, 0);
MATERIAL_FLAGS.put(Material.SPORE_BLOSSOM, 0);
MATERIAL_FLAGS.put(Material.MOSS_CARPET, 0);
MATERIAL_FLAGS.put(Material.BIG_DRIPLEAF, 0);
MATERIAL_FLAGS.put(Material.BIG_DRIPLEAF_STEM, 0);
MATERIAL_FLAGS.put(Material.SMALL_DRIPLEAF, 0);
MATERIAL_FLAGS.put(Material.SMOOTH_BASALT, 0);
MATERIAL_FLAGS.put(Material.INFESTED_DEEPSLATE, 0);
MATERIAL_FLAGS.put(Material.DEEPSLATE_BRICKS, 0);
MATERIAL_FLAGS.put(Material.CRACKED_DEEPSLATE_BRICKS, 0);
MATERIAL_FLAGS.put(Material.DEEPSLATE_TILES, 0);
MATERIAL_FLAGS.put(Material.CRACKED_DEEPSLATE_TILES, 0);
MATERIAL_FLAGS.put(Material.CHISELED_DEEPSLATE, 0);
MATERIAL_FLAGS.put(Material.GLOW_LICHEN, 0);
MATERIAL_FLAGS.put(Material.LIGHT, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.LIGHTNING_ROD, 0);
MATERIAL_FLAGS.put(Material.SCULK_SENSOR, 0);
MATERIAL_FLAGS.put(Material.AMETHYST_SHARD, 0);
MATERIAL_FLAGS.put(Material.RAW_IRON, 0);
MATERIAL_FLAGS.put(Material.RAW_COPPER, 0);
MATERIAL_FLAGS.put(Material.COPPER_INGOT, 0);
MATERIAL_FLAGS.put(Material.RAW_GOLD, 0);
MATERIAL_FLAGS.put(Material.POWDER_SNOW_BUCKET, 0);
MATERIAL_FLAGS.put(Material.AXOLOTL_BUCKET, 0);
MATERIAL_FLAGS.put(Material.BUNDLE, 0);
MATERIAL_FLAGS.put(Material.SPYGLASS, 0);
MATERIAL_FLAGS.put(Material.GLOW_INK_SAC, 0);
MATERIAL_FLAGS.put(Material.GLOW_ITEM_FRAME, 0);
MATERIAL_FLAGS.put(Material.GLOW_BERRIES, 0);
MATERIAL_FLAGS.put(Material.SMALL_AMETHYST_BUD, 0);
MATERIAL_FLAGS.put(Material.MEDIUM_AMETHYST_BUD, 0);
MATERIAL_FLAGS.put(Material.LARGE_AMETHYST_BUD, 0);
MATERIAL_FLAGS.put(Material.AMETHYST_CLUSTER, 0);
MATERIAL_FLAGS.put(Material.POWDER_SNOW, 0);
MATERIAL_FLAGS.put(Material.CAVE_VINES, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.CAVE_VINES_PLANT, MODIFIED_ON_RIGHT);
MATERIAL_FLAGS.put(Material.MOSS_BLOCK, 0);
MATERIAL_FLAGS.put(Material.HANGING_ROOTS, 0);
MATERIAL_FLAGS.put(Material.POINTED_DRIPSTONE, 0);
// Generated via tag
for (Material door : Tag.DOORS.getValues()) {
MATERIAL_FLAGS.put(door, MODIFIED_ON_RIGHT);
for (Material woodenDoor : Tag.WOODEN_DOORS.getValues()) {
MATERIAL_FLAGS.put(woodenDoor, MODIFIED_ON_RIGHT);
}
for (Material woodenTrapdoor : Tag.WOODEN_TRAPDOORS.getValues()) {
MATERIAL_FLAGS.put(woodenTrapdoor, MODIFIED_ON_RIGHT);
}
for (Material shulkerBox : Tag.SHULKER_BOXES.getValues()) {
MATERIAL_FLAGS.put(shulkerBox, MODIFIED_ON_RIGHT);
}
for (Material boat : Tag.ITEMS_BOATS.getValues()) {
MATERIAL_FLAGS.put(boat, 0);
@@ -769,6 +861,45 @@ public final class Materials {
for (Material bannerPat : Tag.ITEMS_BANNERS.getValues()) {
MATERIAL_FLAGS.put(bannerPat, 0);
}
for (Material fenceGate : Tag.FENCE_GATES.getValues()) {
MATERIAL_FLAGS.put(fenceGate, MODIFIED_ON_RIGHT);
}
for (Material fence : Tag.FENCES.getValues()) {
MATERIAL_FLAGS.put(fence, 0);
} for (Material coalOre : Tag.COAL_ORES.getValues()) {
MATERIAL_FLAGS.put(coalOre, 0);
}
for (Material ironOre : Tag.IRON_ORES.getValues()) {
MATERIAL_FLAGS.put(ironOre, 0);
}
for (Material goldOre : Tag.GOLD_ORES.getValues()) {
MATERIAL_FLAGS.put(goldOre, 0);
}
for (Material diamondOre : Tag.DIAMOND_ORES.getValues()) {
MATERIAL_FLAGS.put(diamondOre, 0);
}
for (Material redstoneOre : Tag.REDSTONE_ORES.getValues()) {
MATERIAL_FLAGS.put(redstoneOre, 0);
}
for (Material copperOre : Tag.COPPER_ORES.getValues()) {
MATERIAL_FLAGS.put(copperOre, 0);
}
for (Material emeraldOre : Tag.EMERALD_ORES.getValues()) {
MATERIAL_FLAGS.put(emeraldOre, 0);
}
for (Material lapisOre : Tag.LAPIS_ORES.getValues()) {
MATERIAL_FLAGS.put(lapisOre, 0);
}
for (Material candle : Tag.CANDLES.getValues()) {
MATERIAL_FLAGS.put(candle, MODIFIED_ON_RIGHT);
}
for (Material candleCakes : Tag.CANDLE_CAKES.getValues()) {
MATERIAL_FLAGS.put(candleCakes, MODIFIED_ON_RIGHT);
}
for (Material cauldron : Tag.CAULDRONS.getValues()) {
MATERIAL_FLAGS.put(cauldron, MODIFIED_ON_RIGHT);
}
Stream.concat(Stream.concat(
Tag.CORAL_BLOCKS.getValues().stream(),
Tag.CORALS.getValues().stream()),
@@ -912,7 +1043,8 @@ public final class Materials {
* @return true if a water block
*/
public static boolean isWater(Material material) {
return material == Material.WATER || material == Material.BUBBLE_COLUMN;
return material == Material.WATER || material == Material.BUBBLE_COLUMN
|| material == Material.KELP_PLANT || material == Material.SEAGRASS || material == Material.TALL_SEAGRASS;
}
/**
@@ -983,6 +1115,16 @@ public final class Materials {
return Tag.ITEMS_BOATS.isTagged(material);
}
/**
* Test whether the given material is a Shulker Box.
*
* @param material the material
* @return true if a Shulker Box block
*/
public static boolean isShulkerBox(Material material) {
return Tag.SHULKER_BOXES.isTagged(material);
}
/**
* Test whether the given material is an inventory block.
*
@@ -1001,12 +1143,12 @@ public final class Materials {
|| material == Material.BARREL
|| material == Material.BLAST_FURNACE
|| material == Material.SMOKER
|| shulkerBoxes.contains(material);
|| Tag.SHULKER_BOXES.isTagged(material);
}
public static boolean isSpawnEgg(Material material) {
switch (material) {
case SPIDER_SPAWN_EGG:
case AXOLOTL_SPAWN_EGG:
case BAT_SPAWN_EGG:
case BEE_SPAWN_EGG:
case BLAZE_SPAWN_EGG:
@@ -1025,7 +1167,10 @@ public final class Materials {
case EVOKER_SPAWN_EGG:
case FOX_SPAWN_EGG:
case GHAST_SPAWN_EGG:
case GLOW_SQUID_SPAWN_EGG:
case GOAT_SPAWN_EGG:
case GUARDIAN_SPAWN_EGG:
case HOGLIN_SPAWN_EGG:
case HORSE_SPAWN_EGG:
case HUSK_SPAWN_EGG:
case LLAMA_SPAWN_EGG:
@@ -1036,6 +1181,8 @@ public final class Materials {
case PANDA_SPAWN_EGG:
case PARROT_SPAWN_EGG:
case PHANTOM_SPAWN_EGG:
case PIGLIN_BRUTE_SPAWN_EGG:
case PIGLIN_SPAWN_EGG:
case PIG_SPAWN_EGG:
case PILLAGER_SPAWN_EGG:
case POLAR_BEAR_SPAWN_EGG:
@@ -1049,8 +1196,10 @@ public final class Materials {
case SKELETON_HORSE_SPAWN_EGG:
case SKELETON_SPAWN_EGG:
case SLIME_SPAWN_EGG:
case SPIDER_SPAWN_EGG:
case SQUID_SPAWN_EGG:
case STRAY_SPAWN_EGG:
case STRIDER_SPAWN_EGG:
case TRADER_LLAMA_SPAWN_EGG:
case TROPICAL_FISH_SPAWN_EGG:
case TURTLE_SPAWN_EGG:
@@ -1061,8 +1210,9 @@ public final class Materials {
case WITCH_SPAWN_EGG:
case WITHER_SKELETON_SPAWN_EGG:
case WOLF_SPAWN_EGG:
case ZOGLIN_SPAWN_EGG:
case ZOMBIE_HORSE_SPAWN_EGG:
case ZOMBIE_PIGMAN_SPAWN_EGG:
case ZOMBIFIED_PIGLIN_SPAWN_EGG:
case ZOMBIE_SPAWN_EGG:
case ZOMBIE_VILLAGER_SPAWN_EGG:
return true;
@@ -1073,6 +1223,8 @@ public final class Materials {
public static EntityType getEntitySpawnEgg(Material material) {
switch (material) {
case AXOLOTL_SPAWN_EGG:
return EntityType.AXOLOTL;
case SPIDER_SPAWN_EGG:
return EntityType.SPIDER;
case BAT_SPAWN_EGG:
@@ -1111,8 +1263,14 @@ public final class Materials {
return EntityType.FOX;
case GHAST_SPAWN_EGG:
return EntityType.GHAST;
case GLOW_SQUID_SPAWN_EGG:
return EntityType.GLOW_SQUID;
case GOAT_SPAWN_EGG:
return EntityType.GOAT;
case GUARDIAN_SPAWN_EGG:
return EntityType.GUARDIAN;
case HOGLIN_SPAWN_EGG:
return EntityType.HOGLIN;
case HORSE_SPAWN_EGG:
return EntityType.HORSE;
case HUSK_SPAWN_EGG:
@@ -1133,6 +1291,10 @@ public final class Materials {
return EntityType.PARROT;
case PHANTOM_SPAWN_EGG:
return EntityType.PHANTOM;
case PIGLIN_BRUTE_SPAWN_EGG:
return EntityType.PIGLIN_BRUTE;
case PIGLIN_SPAWN_EGG:
return EntityType.PIGLIN;
case PILLAGER_SPAWN_EGG:
return EntityType.PILLAGER;
case POLAR_BEAR_SPAWN_EGG:
@@ -1161,6 +1323,8 @@ public final class Materials {
return EntityType.SQUID;
case STRAY_SPAWN_EGG:
return EntityType.STRAY;
case STRIDER_SPAWN_EGG:
return EntityType.STRIDER;
case TRADER_LLAMA_SPAWN_EGG:
return EntityType.TRADER_LLAMA;
case TROPICAL_FISH_SPAWN_EGG:
@@ -1183,8 +1347,8 @@ public final class Materials {
return EntityType.WOLF;
case ZOMBIE_HORSE_SPAWN_EGG:
return EntityType.ZOMBIE_HORSE;
case ZOMBIE_PIGMAN_SPAWN_EGG:
return EntityType.PIG_ZOMBIE;
case ZOMBIFIED_PIGLIN_SPAWN_EGG:
return EntityType.ZOMBIFIED_PIGLIN;
case ZOMBIE_SPAWN_EGG:
return EntityType.ZOMBIE;
case ZOMBIE_VILLAGER_SPAWN_EGG:
@@ -1199,6 +1363,10 @@ public final class Materials {
return Tag.BEDS.isTagged(material);
}
public static boolean isAnvil(Material material) {
return Tag.ANVIL.isTagged(material);
}
public static boolean isCoral(Material material) {
return Tag.CORAL_BLOCKS.isTagged(material) ||
Tag.CORAL_PLANTS.isTagged(material) ||
@@ -1212,18 +1380,40 @@ public final class Materials {
* @return true if the material is a crop
*/
public static boolean isCrop(Material type) {
return type == Material.WHEAT
|| type == Material.CARROTS
|| type == Material.POTATOES
|| type == Material.BEETROOTS
|| type == Material.MELON_STEM
|| type == Material.PUMPKIN_STEM
|| type == Material.PUMPKIN
|| type == Material.MELON
|| type == Material.CACTUS
|| type == Material.SUGAR_CANE
|| type == Material.BAMBOO
|| type == Material.BAMBOO_SAPLING;
switch (type) {
case WHEAT:
case CARROTS:
case POTATOES:
case BEETROOTS:
case MELON_STEM:
case PUMPKIN_STEM:
case PUMPKIN:
case MELON:
case CACTUS:
case SUGAR_CANE:
case BAMBOO:
case BAMBOO_SAPLING:
case SWEET_BERRY_BUSH:
case NETHER_WART:
case CAVE_VINES:
case CAVE_VINES_PLANT:
return true;
}
return false;
}
/**
* Test whether the material should be handled as vine. Used by the vine-growth flag
* @param newType the material
* @return true if the material should be handled as vine
*/
public static boolean isVine(Material newType) {
return newType == Material.VINE ||
newType == Material.KELP ||
newType == Material.TWISTING_VINES ||
newType == Material.WEEPING_VINES ||
Tag.CAVE_VINES.isTagged(newType);
}
/**
@@ -1238,26 +1428,15 @@ public final class Materials {
*/
public static boolean isUseFlagApplicable(Material material) {
if (Tag.BUTTONS.isTagged(material)
|| Tag.DOORS.isTagged(material)
|| Tag.WOODEN_PRESSURE_PLATES.isTagged(material)
|| Tag.WOODEN_TRAPDOORS.isTagged(material)) {
|| Tag.WOODEN_DOORS.isTagged(material)
|| Tag.WOODEN_TRAPDOORS.isTagged(material)
|| Tag.FENCE_GATES.isTagged(material)
|| Tag.PRESSURE_PLATES.isTagged(material)) {
return true;
}
switch (material) {
case LEVER:
case LECTERN:
case ACACIA_FENCE_GATE:
case DARK_OAK_FENCE_GATE:
case JUNGLE_FENCE_GATE:
case BIRCH_FENCE_GATE:
case SPRUCE_FENCE_GATE:
case OAK_FENCE_GATE:
case LIGHT_WEIGHTED_PRESSURE_PLATE:
case HEAVY_WEIGHTED_PRESSURE_PLATE:
case STONE_PRESSURE_PLATE:
case ANVIL:
case DAMAGED_ANVIL:
case CHIPPED_ANVIL:
case ENCHANTING_TABLE:
case BELL:
case LOOM:
@@ -1363,6 +1542,10 @@ public final class Materials {
case GOLDEN_CHESTPLATE:
case GOLDEN_LEGGINGS:
case GOLDEN_BOOTS:
case NETHERITE_HELMET:
case NETHERITE_CHESTPLATE:
case NETHERITE_LEGGINGS:
case NETHERITE_BOOTS:
case TURTLE_HELMET:
case ELYTRA:
return true;
@@ -1388,10 +1571,12 @@ public final class Materials {
case IRON_HOE:
case GOLDEN_HOE:
case DIAMOND_HOE:
case NETHERITE_HOE:
switch (targetMaterial) {
case GRASS_BLOCK:
case DIRT:
case GRASS_PATH:
case DIRT_PATH:
case ROOTED_DIRT:
// case COARSE_DIRT: // already handled by the server...
return true;
}
@@ -1401,6 +1586,9 @@ public final class Materials {
case IRON_AXE:
case GOLDEN_AXE:
case DIAMOND_AXE:
case NETHERITE_AXE:
if (isWaxedCopper(targetMaterial))
return true;
switch (targetMaterial) {
case OAK_LOG:
case DARK_OAK_LOG:
@@ -1414,6 +1602,10 @@ public final class Materials {
case BIRCH_WOOD:
case SPRUCE_WOOD:
case JUNGLE_WOOD:
case CRIMSON_STEM:
case WARPED_STEM:
case CRIMSON_HYPHAE:
case WARPED_HYPHAE:
return true;
}
return false;
@@ -1422,9 +1614,11 @@ public final class Materials {
case IRON_SHOVEL:
case GOLDEN_SHOVEL:
case DIAMOND_SHOVEL:
case NETHERITE_SHOVEL:
switch (targetMaterial) {
case GRASS_BLOCK:
case CAMPFIRE:
case SOUL_CAMPFIRE:
return true;
}
return false;
@@ -1452,9 +1646,63 @@ public final class Materials {
case RED_DYE:
case WHITE_DYE:
case YELLOW_DYE:
case GLOW_INK_SAC:
case INK_SAC:
return Tag.SIGNS.isTagged(targetMaterial);
case HONEYCOMB:
return isUnwaxedCopper(targetMaterial);
default:
return false;
}
}
public static boolean isFire(Material type) {
return type == Material.FIRE || type == Material.SOUL_FIRE;
}
public static boolean isWaxedCopper(Material type) {
switch (type) {
case WAXED_COPPER_BLOCK:
case WAXED_EXPOSED_COPPER:
case WAXED_WEATHERED_COPPER:
case WAXED_OXIDIZED_COPPER:
case WAXED_CUT_COPPER:
case WAXED_EXPOSED_CUT_COPPER:
case WAXED_WEATHERED_CUT_COPPER:
case WAXED_OXIDIZED_CUT_COPPER:
case WAXED_CUT_COPPER_STAIRS:
case WAXED_EXPOSED_CUT_COPPER_STAIRS:
case WAXED_WEATHERED_CUT_COPPER_STAIRS:
case WAXED_OXIDIZED_CUT_COPPER_STAIRS:
case WAXED_CUT_COPPER_SLAB:
case WAXED_EXPOSED_CUT_COPPER_SLAB:
case WAXED_WEATHERED_CUT_COPPER_SLAB:
case WAXED_OXIDIZED_CUT_COPPER_SLAB:
return true;
}
return false;
}
public static boolean isUnwaxedCopper(Material type) {
switch (type) {
case COPPER_BLOCK:
case EXPOSED_COPPER:
case WEATHERED_COPPER:
case OXIDIZED_COPPER:
case CUT_COPPER:
case EXPOSED_CUT_COPPER:
case WEATHERED_CUT_COPPER:
case OXIDIZED_CUT_COPPER:
case CUT_COPPER_STAIRS:
case EXPOSED_CUT_COPPER_STAIRS:
case WEATHERED_CUT_COPPER_STAIRS:
case OXIDIZED_CUT_COPPER_STAIRS:
case CUT_COPPER_SLAB:
case EXPOSED_CUT_COPPER_SLAB:
case WEATHERED_CUT_COPPER_SLAB:
case OXIDIZED_CUT_COPPER_SLAB:
return true;
}
return false;
}
}
@@ -19,14 +19,19 @@
package com.sk89q.worldguard.util.profile.resolver;
import com.destroystokyo.paper.profile.PlayerProfile;
import com.sk89q.worldguard.util.profile.Profile;
import io.papermc.lib.PaperLib;
import org.bukkit.Bukkit;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.UUID;
/**
* @deprecated Use {@link com.sk89q.worldguard.util.profile.resolver.PaperPlayerService} instead
*/
@Deprecated(forRemoval = true)
public final class PaperProfileService extends SingleRequestService {
private static final PaperPlayerService SUPER = PaperPlayerService.getInstance();
private static final PaperProfileService INSTANCE = new PaperProfileService();
private PaperProfileService() {
@@ -37,18 +42,19 @@ public final class PaperProfileService extends SingleRequestService {
@Override
public int getIdealRequestLimit() {
return Integer.MAX_VALUE;
return SUPER.getIdealRequestLimit();
}
@Override
@Nullable
public Profile findByName(String name) {
PlayerProfile profile = Bukkit.createProfile(name);
if (profile.completeFromCache()) {
//noinspection ConstantConditions - completeFromCache guarantees non-null on success
return new Profile(profile.getId(), profile.getName());
}
return null;
public Profile findByName(String name) throws IOException, InterruptedException {
return SUPER.findByName(name);
}
@Nullable
@Override
public Profile findByUuid(UUID uuid) throws IOException, InterruptedException {
return SUPER.findByUuid(uuid);
}
public static PaperProfileService getInstance() {
@@ -3,4 +3,4 @@ main: com.sk89q.worldguard.bukkit.WorldGuardPlugin
version: "${internalVersion}"
depend: [WorldEdit]
softdepend: [CommandBook]
api-version: 1.13
api-version: 1.17
+5 -16
View File
@@ -1,15 +1,15 @@
plugins {
id("java-library")
id("net.ltgt.apt-eclipse")
id("net.ltgt.apt-idea")
`java-library`
}
applyPlatformAndCoreConfiguration()
dependencies {
"compile"(project(":worldguard-libs:core"))
"compile"("com.sk89q.worldedit:worldedit-core:${Versions.WORLDEDIT}")
"api"(project(":worldguard-libs:core"))
"api"("com.sk89q.worldedit:worldedit-core:${Versions.WORLDEDIT}")
"implementation"("org.flywaydb:flyway-core:3.0")
"implementation"("org.yaml:snakeyaml:1.29")
"implementation"("com.google.guava:guava:${Versions.GUAVA}")
"compileOnly"("com.google.code.findbugs:jsr305:1.3.9")
"testImplementation"("org.hamcrest:hamcrest-library:1.2.1")
@@ -17,15 +17,4 @@ dependencies {
tasks.withType<JavaCompile>().configureEach {
dependsOn(":worldguard-libs:build")
}
sourceSets {
main {
java {
srcDir("src/main/java")
}
resources {
srcDir("src/main/resources")
}
}
}
@@ -93,11 +93,12 @@ public final class WorldGuard {
/**
* The WorldGuard Platform.
* The Platform is only available after WorldGuard is enabled.
*
* @return The platform
*/
public WorldGuardPlatform getPlatform() {
checkNotNull(platform);
checkNotNull(platform, "WorldGuard is not enabled, unable to access the platform.");
return platform;
}
@@ -46,6 +46,7 @@ import com.sk89q.worldguard.protection.flags.RegistryFlag;
import com.sk89q.worldguard.protection.flags.SetFlag;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.flags.StringFlag;
import com.sk89q.worldguard.protection.flags.registry.UnknownFlag;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import javax.annotation.Nullable;
@@ -108,7 +109,7 @@ class FlagHelperBox extends PaginationBox {
private Component createLine(Flag<?> flag, boolean thirdParty) {
final TextComponent.Builder builder = TextComponent.builder("");
appendFlagName(builder, flag, thirdParty ? TextColor.LIGHT_PURPLE : TextColor.GOLD);
appendFlagName(builder, flag, flag instanceof UnknownFlag ? TextColor.GRAY : thirdParty ? TextColor.LIGHT_PURPLE : TextColor.GOLD);
appendFlagValue(builder, flag);
return builder.build();
}
@@ -255,7 +256,7 @@ class FlagHelperBox extends PaginationBox {
boolean isExplicitSet = currVal != null && !inherited;
boolean maySet = perms.maySetFlag(region, flag);
boolean maySet = !(flag instanceof UnknownFlag) && perms.maySetFlag(region, flag);
TextColor col = isExplicitSet ? TextColor.WHITE : inherited ? TextColor.GRAY : TextColor.DARK_GRAY;
Set<TextDecoration> styles = currVal == defVal ? ImmutableSet.of(TextDecoration.UNDERLINED) : Collections.emptySet();
@@ -359,11 +360,9 @@ class FlagHelperBox extends PaginationBox {
if (currVal == null) {
currVal = getInheritedValue(region, flag);
}
@SuppressWarnings("unchecked")
List<V> values = currVal == null ? Collections.emptyList() : (List<V>) flag.marshal(currVal);
String display = (currVal == null ? "" : currVal.size() + "x ") + subName;
final String stringValue = currVal == null ? ""
: values.stream().map(String::valueOf).collect(Collectors.joining(","));
: currVal.stream().map(String::valueOf).collect(Collectors.joining(","));
TextComponent hoverComp = TextComponent.of("");
if (currVal != null) {
hoverComp = hoverComp.append(TextComponent.of("Current values:"))
@@ -25,7 +25,6 @@ import com.google.common.collect.Sets;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.minecraft.util.commands.CommandPermissionsException;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.command.util.AsyncCommandBuilder;
@@ -44,7 +43,6 @@ import com.sk89q.worldedit.util.formatting.text.format.TextDecoration;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.commands.CommandUtils;
import com.sk89q.worldguard.commands.task.RegionAdder;
import com.sk89q.worldguard.commands.task.RegionLister;
import com.sk89q.worldguard.commands.task.RegionManagerLoader;
@@ -54,6 +52,7 @@ import com.sk89q.worldguard.config.ConfigurationManager;
import com.sk89q.worldguard.config.WorldConfiguration;
import com.sk89q.worldguard.internal.permission.RegionPermissionModel;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.FlagValueCalculator;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.FlagContext;
import com.sk89q.worldguard.protection.flags.Flags;
@@ -645,7 +644,7 @@ public final class RegionCommands extends RegionCommandsBase {
ProtectedRegion region;
if (args.argsLength() == 0) { // Get region from where the player is
if (!(sender instanceof LocalPlayer)) {
throw new CommandException("Please specify the region with /region info -w world_name region_name.");
throw new CommandException("Please specify the region with /region flags -w world_name region_name.");
}
region = checkRegionStandingIn(manager, (LocalPlayer) sender, true,
@@ -1097,21 +1096,21 @@ public final class RegionCommands extends RegionCommandsBase {
// -s for spawn location
if (args.hasFlag('s')) {
teleportLocation = existing.getFlag(Flags.SPAWN_LOC);
teleportLocation = FlagValueCalculator.getEffectiveFlagOf(existing, Flags.SPAWN_LOC, player);
if (teleportLocation == null) {
throw new CommandException(
"The region has no spawn point associated.");
}
} else {
teleportLocation = existing.getFlag(Flags.TELE_LOC);
teleportLocation = FlagValueCalculator.getEffectiveFlagOf(existing, Flags.TELE_LOC, player);
if (teleportLocation == null) {
throw new CommandException("The region has no teleport point associated.");
}
}
String message = existing.getFlag(Flags.TELE_MESSAGE);
String message = FlagValueCalculator.getEffectiveFlagOf(existing, Flags.TELE_MESSAGE, player);
// If the flag isn't set, use the default message
// If message.isEmpty(), no message is sent by LocalPlayer#teleport(...)
@@ -1125,12 +1124,25 @@ public final class RegionCommands extends RegionCommandsBase {
}
@Command(aliases = {"toggle-bypass", "bypass"},
usage = "[on|off]",
desc = "Toggle region bypassing, effectively ignoring bypass permissions.")
@CommandPermissions({"worldguard.region.toggle-bypass"})
public void toggleBypass(CommandContext args, Actor sender) throws CommandException {
LocalPlayer player = worldGuard.checkPlayer(sender);
if (!player.hasPermission("worldguard.region.toggle-bypass")) {
throw new CommandPermissionsException();
}
Session session = WorldGuard.getInstance().getPlatform().getSessionManager().get(player);
if (session.hasBypassDisabled()) {
boolean shouldEnableBypass;
if (args.argsLength() > 0) {
String arg1 = args.getString(0);
if (!arg1.equalsIgnoreCase("on") && !arg1.equalsIgnoreCase("off")) {
throw new CommandException("Allowed optional arguments are: on, off");
}
shouldEnableBypass = arg1.equalsIgnoreCase("on");
} else {
shouldEnableBypass = session.hasBypassDisabled();
}
if (shouldEnableBypass) {
session.setBypassDisabled(false);
player.print("You are now bypassing region protection (as long as you have permission).");
} else {
@@ -31,6 +31,7 @@ import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.regions.Polygonal2DRegion;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.regions.RegionSelector;
import com.sk89q.worldedit.regions.selector.CuboidRegionSelector;
import com.sk89q.worldedit.regions.selector.Polygonal2DRegionSelector;
import com.sk89q.worldedit.util.formatting.component.ErrorFormat;
@@ -54,6 +55,8 @@ import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import com.sk89q.worldguard.protection.regions.ProtectedPolygonalRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.regions.RegionContainer;
import com.sk89q.worldguard.protection.regions.RegionQuery.QueryOption;
import com.sk89q.worldguard.protection.util.WorldEditRegionConverter;
import java.util.Set;
import java.util.stream.Collectors;
@@ -198,7 +201,7 @@ class RegionCommandsBase {
* @throws CommandException thrown if no region was found
*/
protected static ProtectedRegion checkRegionStandingIn(RegionManager regionManager, LocalPlayer player, boolean allowGlobal, String rgCmd) throws CommandException {
ApplicableRegionSet set = regionManager.getApplicableRegions(player.getLocation().toVector().toBlockPoint());
ApplicableRegionSet set = regionManager.getApplicableRegions(player.getLocation().toVector().toBlockPoint(), QueryOption.SORT);
if (set.size() == 0) {
if (allowGlobal) {
@@ -228,7 +231,7 @@ class RegionCommandsBase {
builder.append(regionComp);
}
player.print(builder.build());
throw new CommandException("Several regions affect your current location (please pick one).");
throw new CommandException("You're standing in several regions (please pick one).");
}
return set.iterator().next();
@@ -243,14 +246,16 @@ class RegionCommandsBase {
* @throws CommandException thrown on an error
*/
protected static Region checkSelection(Actor actor) throws CommandException {
LocalSession localSession = WorldEdit.getInstance().getSessionManager().get(actor);
try {
LocalSession localSession = WorldEdit.getInstance().getSessionManager().get(actor);
if (localSession == null || localSession.getSelectionWorld() == null) {
throw new IncompleteRegionException();
}
return localSession.getRegionSelector(localSession.getSelectionWorld()).getRegion();
} catch (IncompleteRegionException e) {
throw new CommandException(
"Please select an area first. " +
"Use WorldEdit to make a selection! " +
"(see: https://worldedit.enginehub.org/en/latest/usage/regions/selections/).");
throw new CommandException("Please select an area first. " +
"Use WorldEdit to make a selection! " +
"(see: https://worldedit.enginehub.org/en/latest/usage/regions/selections/).");
}
}
@@ -394,35 +399,15 @@ class RegionCommandsBase {
protected static void setPlayerSelection(Actor actor, ProtectedRegion region, World world) throws CommandException {
LocalSession session = WorldEdit.getInstance().getSessionManager().get(actor);
// Set selection
if (region instanceof ProtectedCuboidRegion) {
ProtectedCuboidRegion cuboid = (ProtectedCuboidRegion) region;
BlockVector3 pt1 = cuboid.getMinimumPoint();
BlockVector3 pt2 = cuboid.getMaximumPoint();
CuboidRegionSelector selector = new CuboidRegionSelector(world, pt1, pt2);
RegionSelector selector = WorldEditRegionConverter.convertToSelector(region);
if (selector != null) {
selector.setWorld(world);
session.setRegionSelector(world, selector);
selector.explainRegionAdjust(actor, session);
actor.print("Region selected as a cuboid.");
} else if (region instanceof ProtectedPolygonalRegion) {
ProtectedPolygonalRegion poly2d = (ProtectedPolygonalRegion) region;
Polygonal2DRegionSelector selector = new Polygonal2DRegionSelector(
world, poly2d.getPoints(),
poly2d.getMinimumPoint().getBlockY(),
poly2d.getMaximumPoint().getBlockY());
session.setRegionSelector(world, selector);
selector.explainRegionAdjust(actor, session);
actor.print("Region selected as a polygon.");
} else if (region instanceof GlobalProtectedRegion) {
throw new CommandException(
"Can't select global regions! " +
"That would cover the entire world.");
actor.print("Region selected as " + region.getType().getName());
} else {
throw new CommandException("Unknown region type: " +
region.getClass().getCanonicalName());
throw new CommandException("Can't select that region! " +
"The region type '" + region.getType().getName() + "' can't be selected.");
}
}
@@ -36,6 +36,8 @@ import com.sk89q.worldedit.util.formatting.text.format.TextColor;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.domains.DefaultDomain;
import com.sk89q.worldguard.internal.permission.RegionPermissionModel;
import com.sk89q.worldguard.protection.FlagValueCalculator;
import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.flags.RegionGroupFlag;
@@ -315,7 +317,7 @@ public class RegionPrintoutBuilder implements Callable<TextComponent> {
.clickEvent(ClickEvent.of(ClickEvent.Action.RUN_COMMAND, "/rg select " + region.getId()));
}
builder.append(bound);
final Location teleFlag = region.getFlag(Flags.TELE_LOC);
final Location teleFlag = FlagValueCalculator.getEffectiveFlagOf(region, Flags.TELE_LOC, perms != null && perms.getSender() instanceof RegionAssociable ? (RegionAssociable) perms.getSender() : null);
if (teleFlag != null && perms != null && perms.mayTeleportTo(region)) {
builder.append(TextComponent.space().append(TextComponent.of("[Teleport]", TextColor.GRAY)
.hoverEvent(HoverEvent.of(HoverEvent.Action.SHOW_TEXT,
@@ -24,6 +24,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.worldguard.util.profile.Profile;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.util.formatting.component.PaginationBox;
import com.sk89q.worldedit.util.formatting.text.Component;
import com.sk89q.worldedit.util.formatting.text.TextComponent;
@@ -33,6 +34,8 @@ import com.sk89q.worldedit.util.formatting.text.format.TextColor;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.domains.DefaultDomain;
import com.sk89q.worldguard.internal.permission.RegionPermissionModel;
import com.sk89q.worldguard.protection.FlagValueCalculator;
import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
@@ -261,7 +264,8 @@ public class RegionLister implements Callable<Integer> {
.clickEvent(ClickEvent.of(ClickEvent.Action.RUN_COMMAND,
"/rg info -w \"" + world + "\" " + entry.region.getId()))));
}
if (perms != null && entry.region.getFlag(Flags.TELE_LOC) != null && perms.mayTeleportTo(entry.region)) {
final Location teleFlag = FlagValueCalculator.getEffectiveFlagOf(entry.region, Flags.TELE_LOC, perms != null && perms.getSender() instanceof RegionAssociable ? (RegionAssociable) perms.getSender() : null);
if (perms != null && teleFlag != null && perms.mayTeleportTo(entry.region)) {
builder.append(TextComponent.space().append(TextComponent.of("[TP]", TextColor.GRAY)
.hoverEvent(HoverEvent.of(HoverEvent.Action.SHOW_TEXT, TextComponent.of("Click to teleport")))
.clickEvent(ClickEvent.of(ClickEvent.Action.RUN_COMMAND,
@@ -76,6 +76,9 @@ public abstract class ConfigurationManager {
public boolean migrateRegionsToUuid;
public boolean keepUnresolvedNames;
public boolean particleEffects;
public boolean disablePermissionCache;
public boolean disableDefaultBypass;
public boolean announceBypassStatus;
@Unreported public Map<String, String> hostKeys = new HashMap<>();
public boolean hostKeysAllowFMLClients;
@@ -105,6 +105,7 @@ public abstract class WorldConfiguration {
public boolean blockEntityPaintingDestroy;
public boolean blockEntityItemFrameDestroy;
public boolean blockEntityArmorStandDestroy;
public boolean blockEntityVehicleEntry;
public boolean blockPluginSpawning;
public boolean blockGroundSlimes;
public boolean blockZombieDoorDestruction;
@@ -135,6 +136,8 @@ public abstract class WorldConfiguration {
public boolean removeInfiniteStacks;
public boolean disableCreatureCropTrampling;
public boolean disablePlayerCropTrampling;
public boolean disableCreatureTurtleEggTrampling;
public boolean disablePlayerTurtleEggTrampling;
public boolean preventLightningFire;
public Set<String> disallowedLightningBlocks;
public boolean disableThunder;
@@ -171,6 +174,7 @@ public abstract class WorldConfiguration {
public boolean strictEntitySpawn;
public boolean ignoreHopperMoveEvents;
public boolean breakDeniedHoppers;
public boolean useMaxPriorityAssociation;
protected Map<String, Integer> maxRegionCounts;
/**
@@ -56,6 +56,9 @@ public abstract class YamlConfigurationManager extends ConfigurationManager {
migrateRegionsToUuid = config.getBoolean("regions.uuid-migration.perform-on-next-start", true);
keepUnresolvedNames = config.getBoolean("regions.uuid-migration.keep-names-that-lack-uuids", true);
useRegionsCreatureSpawnEvent = config.getBoolean("regions.use-creature-spawn-event", true);
disableDefaultBypass = config.getBoolean("regions.disable-bypass-by-default", false);
announceBypassStatus = config.getBoolean("regions.announce-bypass-status", false);
useGodPermission = config.getBoolean("auto-invincible", config.getBoolean("auto-invincible-permission", false));
useGodGroup = config.getBoolean("auto-invincible-group", false);
useAmphibiousGroup = config.getBoolean("auto-no-drowning-group", false);
@@ -63,6 +66,7 @@ public abstract class YamlConfigurationManager extends ConfigurationManager {
usePlayerMove = config.getBoolean("use-player-move-event", true);
usePlayerTeleports = config.getBoolean("use-player-teleports", true);
particleEffects = config.getBoolean("use-particle-effects", true);
disablePermissionCache = config.getBoolean("disable-permission-cache", false);
deopOnJoin = config.getBoolean("security.deop-everyone-on-join", false);
blockInGameOp = config.getBoolean("security.block-in-game-op-command", false);
@@ -73,7 +73,9 @@ public class PlayerDomain implements Domain, ChangeTracked {
* Add the given player to the domain, identified by the player's name.
*
* @param name the name of the player
* @deprecated names are deprecated in favor of UUIDs in MC 1.7+
*/
@Deprecated
public void addPlayer(String name) {
checkNotNull(name);
if (!name.trim().isEmpty()) {
@@ -111,7 +113,9 @@ public class PlayerDomain implements Domain, ChangeTracked {
* Remove the given player from the domain, identified by the player's name.
*
* @param name the name of the player
* @deprecated names are deprecated in favor of UUIDs in MC 1.7+
*/
@Deprecated
public void removePlayer(String name) {
checkNotNull(name);
setDirty(true);
@@ -145,14 +149,16 @@ public class PlayerDomain implements Domain, ChangeTracked {
@Override
public boolean contains(LocalPlayer player) {
checkNotNull(player);
return contains(player.getName().trim().toLowerCase()) || contains(player.getUniqueId());
return contains(player.getUniqueId()) || (!names.isEmpty() && contains(player.getName()));
}
/**
* Get the set of player names.
*
* @return the set of player names
* @deprecated names are deprecated in favor of UUIDs in MC 1.7+
*/
@Deprecated
public Set<String> getPlayers() {
return Collections.unmodifiableSet(names);
}
@@ -23,6 +23,8 @@ import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.MapFlag;
import com.sk89q.worldguard.protection.flags.RegionGroup;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.flags.StateFlag.State;
import com.sk89q.worldguard.protection.managers.RegionManager;
@@ -119,6 +121,50 @@ public interface ApplicableRegionSet extends Iterable<ProtectedRegion> {
@Nullable
<V> V queryValue(@Nullable RegionAssociable subject, Flag<V> flag);
/**
* Get the effective value for a key in a {@link MapFlag}. If there are multiple values
* (for example, if there are multiple regions with the same priority
* but with different farewell messages set, there would be multiple
* completing values), then the selected (or "winning") value will be undefined.
*
* <p>A subject can be provided that is used to determine whether the value
* of a flag on a particular region should be used. For example, if a
* flag's region group is set to {@link RegionGroup#MEMBERS} and the given
* subject is not a member, then the region would be skipped when
* querying that flag. If {@code null} is provided for the subject, then
* only flags that use {@link RegionGroup#ALL},
* {@link RegionGroup#NON_MEMBERS}, etc. will apply.</p>
*
* @param subject an optional subject, which would be used to determine the region group to apply
* @param flag the flag of type {@link MapFlag}
* @param key the key for the map flag
* @return a value, which could be {@code null}
*/
@Nullable
<V, K> V queryMapValue(@Nullable RegionAssociable subject, MapFlag<K, V> flag, K key);
/**
* Get the effective value for a key in a {@link MapFlag}. If there are multiple values
* (for example, if there are multiple regions with the same priority
* but with different farewell messages set, there would be multiple
* completing values), then the selected (or "winning") value will be undefined.
*
* <p>A subject can be provided that is used to determine whether the value
* of a flag on a particular region should be used. For example, if a
* flag's region group is set to {@link RegionGroup#MEMBERS} and the given
* subject is not a member, then the region would be skipped when
* querying that flag. If {@code null} is provided for the subject, then
* only flags that use {@link RegionGroup#ALL},
* {@link RegionGroup#NON_MEMBERS}, etc. will apply.</p>
*
* @param subject an optional subject, which would be used to determine the region group to apply
* @param flag the flag of type {@link MapFlag}
* @param key the key for the map flag
* @return a value, which could be {@code null}
*/
@Nullable
<V, K> V queryMapValue(@Nullable RegionAssociable subject, MapFlag<K, V> flag, K key, @Nullable Flag<V> fallback);
/**
* Get the effective values for a flag, returning a collection of all
* values. It is up to the caller to determine which value, if any,
@@ -21,16 +21,8 @@ package com.sk89q.worldguard.protection;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldguard.protection.regions.RegionQuery;
import com.sk89q.worldguard.domains.Association;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import javax.annotation.Nullable;
import java.util.List;
import java.util.Set;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Determines that the association to a region is {@code OWNER} if the input
@@ -38,41 +30,18 @@ import static com.google.common.base.Preconditions.checkNotNull;
*
* <p>This class only performs a spatial query if its
* {@link #getAssociation(List)} method is called.</p>
*
* @deprecated Use {@link com.sk89q.worldguard.protection.association.DelayedRegionOverlapAssociation} instead. This class is mis-packaged.
*/
public class DelayedRegionOverlapAssociation implements RegionAssociable {
private final RegionQuery query;
private final Location location;
@Nullable
private Set<ProtectedRegion> source;
@Deprecated
public class DelayedRegionOverlapAssociation extends com.sk89q.worldguard.protection.association.DelayedRegionOverlapAssociation {
/**
* Create a new instance.
*
* @param query the query
* @param location the location
*/
public DelayedRegionOverlapAssociation(RegionQuery query, Location location) {
checkNotNull(query);
checkNotNull(location);
this.query = query;
this.location = location;
}
@Override
public Association getAssociation(List<ProtectedRegion> regions) {
if (source == null) {
ApplicableRegionSet result = query.getApplicableRegions(location);
source = result.getRegions();
}
for (ProtectedRegion region : regions) {
if ((region.getId().equals(ProtectedRegion.GLOBAL_REGION) && source.isEmpty()) || source.contains(region)) {
return Association.OWNER;
}
}
return Association.NON_MEMBER;
super(query, location, false);
}
}
@@ -24,6 +24,7 @@ import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.MapFlag;
import com.sk89q.worldguard.protection.flags.StateFlag.State;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
@@ -31,6 +32,7 @@ import javax.annotation.Nullable;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
@@ -65,6 +67,19 @@ public class FailedLoadRegionSet extends AbstractRegionSet {
return flag.getDefault();
}
@Nullable
@Override
public <V, K> V queryMapValue(@Nullable RegionAssociable subject, MapFlag<K, V> flag, K key) {
return queryMapValue(subject, flag, key, null);
}
@Nullable
@Override
public <V, K> V queryMapValue(@Nullable RegionAssociable subject, MapFlag<K, V> flag, K key, @Nullable Flag<V> fallback) {
Map<K, V> defaultVal = flag.getDefault();
return defaultVal != null ? defaultVal.get(key) : fallback != null ? fallback.getDefault() : null;
}
@SuppressWarnings("unchecked")
@Override
public <V> Collection<V> queryAllValues(@Nullable RegionAssociable subject, Flag<V> flag) {
@@ -26,6 +26,7 @@ import com.sk89q.worldguard.domains.Association;
import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.MapFlag;
import com.sk89q.worldguard.protection.flags.RegionGroup;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.flags.StateFlag.State;
@@ -89,13 +90,14 @@ public class FlagValueCalculator {
/**
* Return the membership status of the given subject, indicating
* whether there are no (counted) regions in the list of regions,
* whether the subject is a member of all regions, or whether
* the region is not a member of all regions.
* whether the subject is a member of all (counted) regions, or
* whether the subject is not a member of all (counted) regions.
*
* <p>A region is "counted" if it doesn't have the
* {@link Flags#PASSTHROUGH} flag set to {@code ALLOW}. (The
* explicit purpose of the PASSTHROUGH flag is to have the region
* be skipped over in this check.)</p>
* {@link Flags#PASSTHROUGH} flag set to {@code ALLOW} and if
* there isn't another "counted" region with a higher priority.
* (The explicit purpose of the PASSTHROUGH flag is to have the
* region be skipped over in this check.)</p>
*
* <p>This method is mostly for internal use. It's not particularly
* useful.</p>
@@ -112,11 +114,13 @@ public class FlagValueCalculator {
Set<ProtectedRegion> ignoredRegions = Sets.newHashSet();
for (ProtectedRegion region : getApplicable()) {
int priority = getPriority(region);
// Don't consider lower priorities below minimumPriority
// (which starts at Integer.MIN_VALUE). A region that "counts"
// (has the flag set OR has members) will raise minimumPriority
// to its own priority.
if (getPriority(region) < minimumPriority) {
if (priority < minimumPriority) {
break;
}
@@ -129,7 +133,7 @@ public class FlagValueCalculator {
continue;
}
minimumPriority = getPriority(region);
minimumPriority = priority;
boolean member = RegionGroup.MEMBERS.contains(subject.getAssociation(Collections.singletonList(region)));
@@ -224,6 +228,117 @@ public class FlagValueCalculator {
return flag.chooseValue(values);
}
/**
* Get the effective value for a key in a {@link MapFlag}. If there are multiple values
* (for example, if there are multiple regions with the same priority
* but with different farewell messages set, there would be multiple
* completing values), then the selected (or "winning") value will be undefined.
*
* <p>A subject can be provided that is used to determine whether the value
* of a flag on a particular region should be used. For example, if a
* flag's region group is set to {@link RegionGroup#MEMBERS} and the given
* subject is not a member, then the region would be skipped when
* querying that flag. If {@code null} is provided for the subject, then
* only flags that use {@link RegionGroup#ALL},
* {@link RegionGroup#NON_MEMBERS}, etc. will apply.</p>
*
* @param subject an optional subject, which would be used to determine the region group to apply
* @param flag the flag of type {@link MapFlag}
* @param key the key for the map flag
* @return a value, which could be {@code null}
*/
@Nullable
public <V, K> V queryMapValue(@Nullable RegionAssociable subject, MapFlag<K, V> flag, K key, Flag<V> fallback) {
checkNotNull(flag);
checkNotNull(key);
Map<ProtectedRegion, V> consideredValues = new HashMap<>();
Map<ProtectedRegion, V> fallbackValues = new HashMap<>();
int minimumPriority = Integer.MIN_VALUE;
Set<ProtectedRegion> ignoredParents = new HashSet<>();
for(ProtectedRegion region : getApplicable()) {
int priority = getPriority(region);
if (priority < minimumPriority) {
break;
}
if (ignoredParents.contains(region)) {
continue;
}
V effectiveValue = getEffectiveMapValue(region, flag, key, subject);
if (effectiveValue != null) {
minimumPriority = priority;
consideredValues.put(region, effectiveValue);
} else if (fallback != null) {
effectiveValue = getEffectiveFlag(region, fallback, subject);
if (effectiveValue != null) {
minimumPriority = priority;
fallbackValues.put(region, effectiveValue);
}
}
addParents(ignoredParents, region);
}
if (consideredValues.isEmpty()) {
if (fallback != null && !fallbackValues.isEmpty()) {
return fallback.chooseValue(fallbackValues.values());
}
V defaultValue = flag.getValueFlag().getDefault();
return defaultValue != null ? defaultValue : fallback != null ? fallback.getDefault() : null;
}
return flag.getValueFlag().chooseValue(consideredValues.values());
}
@Nullable
public <V, K> V getEffectiveMapValue(ProtectedRegion region, MapFlag<K, V> mapFlag, K key, RegionAssociable subject) {
return getEffectiveMapValueOf(region, mapFlag, key, subject);
}
@Nullable
public static <V, K> V getEffectiveMapValueOf(ProtectedRegion region, MapFlag<K, V> mapFlag, K key, RegionAssociable subject) {
List<ProtectedRegion> seen = new ArrayList<>();
ProtectedRegion current = region;
while (current != null) {
seen.add(current);
Map<K, V> mapValue = current.getFlag(mapFlag);
if (mapValue != null && mapValue.containsKey(key)) {
boolean use = true;
if (mapFlag.getRegionGroupFlag() != null) {
RegionGroup group = current.getFlag(mapFlag.getRegionGroupFlag());
if (group == null) {
group = mapFlag.getRegionGroupFlag().getDefault();
}
if (group == null) {
use = false;
} else if (subject == null) {
use = group.contains(Association.NON_MEMBER);
} else if (!group.contains(subject.getAssociation(seen))) {
use = false;
}
}
if (use) {
return mapValue.get(key);
}
}
current = current.getParent();
}
return null;
}
/**
* Get the effective values for a flag, returning a collection of all
* values. It is up to the caller to determine which value, if any,
@@ -283,7 +398,9 @@ public class FlagValueCalculator {
Set<ProtectedRegion> ignoredParents = new HashSet<>();
for (ProtectedRegion region : getApplicable()) {
if (getPriority(region) < minimumPriority) {
int priority = getPriority(region);
if (priority < minimumPriority) {
break;
}
@@ -292,7 +409,6 @@ public class FlagValueCalculator {
}
V value = getEffectiveFlag(region, flag, subject);
int priority = getPriority(region);
if (value != null) {
minimumPriority = priority;
@@ -310,7 +426,7 @@ public class FlagValueCalculator {
// PASSTHROUGH is not set to ALLOW
if (priority != minimumPriority && flag.implicitlySetWithMembership()
&& getEffectiveFlag(region, Flags.PASSTHROUGH, subject) != State.ALLOW) {
minimumPriority = getPriority(region);
minimumPriority = priority;
}
}
@@ -339,7 +455,11 @@ public class FlagValueCalculator {
* @return the priority
*/
public int getPriority(final ProtectedRegion region) {
if (region == globalRegion) {
return getPriorityOf(region);
}
public static int getPriorityOf(final ProtectedRegion region) {
if (region.getId().equals(ProtectedRegion.GLOBAL_REGION)) {
return Integer.MIN_VALUE;
} else {
return region.getPriority();
@@ -355,9 +475,15 @@ public class FlagValueCalculator {
* @param subject an subject object
* @return the value
*/
@SuppressWarnings("unchecked")
@Nullable
public <V> V getEffectiveFlag(final ProtectedRegion region, Flag<V> flag, @Nullable RegionAssociable subject) {
if (region == globalRegion) {
return getEffectiveFlagOf(region, flag, subject);
}
@SuppressWarnings("unchecked")
@Nullable
public static <V> V getEffectiveFlagOf(final ProtectedRegion region, Flag<V> flag, @Nullable RegionAssociable subject) {
if (region.getId().equals(ProtectedRegion.GLOBAL_REGION)) {
if (flag == Flags.PASSTHROUGH) {
// Has members/owners -> the global region acts like
// a regular region without PASSTHROUGH
@@ -24,6 +24,7 @@ import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.MapFlag;
import com.sk89q.worldguard.protection.flags.StateFlag.State;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
@@ -31,6 +32,7 @@ import javax.annotation.Nullable;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
@@ -59,6 +61,19 @@ public class PermissiveRegionSet extends AbstractRegionSet {
return flag.getDefault();
}
@Nullable
@Override
public <V, K> V queryMapValue(@Nullable RegionAssociable subject, MapFlag<K, V> flag, K key) {
return queryMapValue(subject, flag, key, null);
}
@Nullable
@Override
public <V, K> V queryMapValue(@Nullable RegionAssociable subject, MapFlag<K, V> flag, K key, @Nullable Flag<V> fallback) {
Map<K, V> defaultVal = flag.getDefault();
return defaultVal != null ? defaultVal.get(key) : fallback != null ? fallback.getDefault() : null;
}
@SuppressWarnings("unchecked")
@Override
public <V> Collection<V> queryAllValues(@Nullable RegionAssociable subject, Flag<V> flag) {
@@ -19,16 +19,22 @@
package com.sk89q.worldguard.protection;
import com.google.common.collect.ImmutableSet;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.MapFlag;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.flags.StateFlag.State;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.util.NormativeOrders;
import javax.annotation.Nullable;
import java.util.*;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import static com.google.common.base.Preconditions.checkNotNull;
@@ -63,7 +69,7 @@ public class RegionResultSet extends AbstractRegionSet {
*/
public RegionResultSet(Set<ProtectedRegion> applicable, @Nullable ProtectedRegion globalRegion) {
this(NormativeOrders.fromSet(applicable), globalRegion, true);
this.regionSet = applicable;
this.regionSet = ImmutableSet.copyOf(applicable);
}
/**
@@ -82,7 +88,7 @@ public class RegionResultSet extends AbstractRegionSet {
if (!sorted) {
NormativeOrders.sort(applicable);
}
this.applicable = applicable;
this.applicable = Collections.unmodifiableList(applicable);
this.flagValueCalculator = new FlagValueCalculator(applicable, globalRegion);
}
@@ -108,6 +114,18 @@ public class RegionResultSet extends AbstractRegionSet {
return flagValueCalculator.queryAllValues(subject, flag);
}
@Override
@Nullable
public <V, K> V queryMapValue(@Nullable RegionAssociable subject, MapFlag<K, V> flag, K key) {
return flagValueCalculator.queryMapValue(subject, flag, key, null);
}
@Override
@Nullable
public <V, K> V queryMapValue(@Nullable RegionAssociable subject, MapFlag<K, V> flag, K key, Flag<V> fallback) {
return flagValueCalculator.queryMapValue(subject, flag, key, fallback);
}
@Override
public boolean isOwnerOfAll(LocalPlayer player) {
checkNotNull(player);
@@ -144,7 +162,7 @@ public class RegionResultSet extends AbstractRegionSet {
if (regionSet != null) {
return regionSet;
}
regionSet = Collections.unmodifiableSet(new HashSet<>(applicable));
regionSet = ImmutableSet.copyOf(applicable);
return regionSet;
}
@@ -0,0 +1,127 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection.association;
import static com.google.common.base.Preconditions.checkNotNull;
import com.sk89q.worldguard.domains.Association;
import com.sk89q.worldguard.protection.FlagValueCalculator;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import javax.annotation.Nullable;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public abstract class AbstractRegionOverlapAssociation implements RegionAssociable {
@Nullable
protected Set<ProtectedRegion> source;
private boolean useMaxPriorityAssociation;
private int maxPriority;
private Set<ProtectedRegion> maxPriorityRegions;
protected AbstractRegionOverlapAssociation(@Nullable Set<ProtectedRegion> source, boolean useMaxPriorityAssociation) {
this.source = source;
this.useMaxPriorityAssociation = useMaxPriorityAssociation;
}
protected void calcMaxPriority() {
checkNotNull(source);
int best = 0;
Set<ProtectedRegion> bestRegions = new HashSet<>();
for (ProtectedRegion region : source) {
int priority = region.getPriority();
if (priority > best) {
best = priority;
bestRegions.clear();
bestRegions.add(region);
} else if (priority == best) {
bestRegions.add(region);
}
}
this.maxPriority = best;
this.maxPriorityRegions = bestRegions;
}
private boolean checkNonplayerProtectionDomains(Iterable<? extends ProtectedRegion> source, Collection<?> domains) {
if (source == null || domains == null || domains.isEmpty()) {
return false;
}
for (ProtectedRegion region : source) {
// Potential endless recurrence? No, because there is no region group flag.
Set<String> regionDomains = FlagValueCalculator.getEffectiveFlagOf(region, Flags.NONPLAYER_PROTECTION_DOMAINS, this);
if (regionDomains == null || regionDomains.isEmpty()) {
continue;
}
if (!Collections.disjoint(regionDomains, domains)) {
return true;
}
}
return false;
}
@Override
public Association getAssociation(List<ProtectedRegion> regions) {
checkNotNull(source);
for (ProtectedRegion region : regions) {
while (region != null) {
if ((region.getId().equals(ProtectedRegion.GLOBAL_REGION) && source.isEmpty())) {
return Association.OWNER;
}
if (source.contains(region)) {
if (useMaxPriorityAssociation) {
int priority = region.getPriority();
if (priority == maxPriority) {
return Association.OWNER;
}
} else {
return Association.OWNER;
}
}
Set<ProtectedRegion> source;
if (useMaxPriorityAssociation) {
source = maxPriorityRegions;
} else {
source = this.source;
}
// Potential endless recurrence? No, because there is no region group flag.
if (checkNonplayerProtectionDomains(source, FlagValueCalculator.getEffectiveFlagOf(region, Flags.NONPLAYER_PROTECTION_DOMAINS, this))) {
return Association.OWNER;
}
region = region.getParent();
}
}
return Association.NON_MEMBER;
}
}
@@ -0,0 +1,79 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection.association;
import static com.google.common.base.Preconditions.checkNotNull;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldguard.domains.Association;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.regions.RegionQuery;
import com.sk89q.worldguard.protection.regions.RegionQuery.QueryOption;
import java.util.List;
/**
* Determines that the association to a region is {@code OWNER} if the input
* region is in a set of source regions.
*
* <p>This class only performs a spatial query if its
* {@link #getAssociation(List)} method is called.</p>
*/
public class DelayedRegionOverlapAssociation extends AbstractRegionOverlapAssociation {
private final RegionQuery query;
private final Location location;
/**
* Create a new instance.
* @param query the query
* @param location the location
*/
public DelayedRegionOverlapAssociation(RegionQuery query, Location location) {
this(query, location, false);
}
/**
* Create a new instance.
* @param query the query
* @param location the location
* @param useMaxPriorityAssociation whether to use the max priority from regions to determine association
*/
public DelayedRegionOverlapAssociation(RegionQuery query, Location location, boolean useMaxPriorityAssociation) {
super(null, useMaxPriorityAssociation);
checkNotNull(query);
checkNotNull(location);
this.query = query;
this.location = location;
}
@Override
public Association getAssociation(List<ProtectedRegion> regions) {
if (source == null) {
ApplicableRegionSet result = query.getApplicableRegions(location, QueryOption.NONE);
source = result.getRegions();
calcMaxPriority();
}
return super.getAssociation(regions);
}
}
@@ -19,41 +19,35 @@
package com.sk89q.worldguard.protection.association;
import com.sk89q.worldguard.domains.Association;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import java.util.List;
import javax.annotation.Nonnull;
import java.util.Set;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Determines that the association to a region is {@code OWNER} if the input
* region is in a set of source regions.
*/
public class RegionOverlapAssociation implements RegionAssociable {
private final Set<ProtectedRegion> source;
public class RegionOverlapAssociation extends AbstractRegionOverlapAssociation {
/**
* Create a new instance.
*
* @param source set of regions that input regions must be contained within
*/
public RegionOverlapAssociation(Set<ProtectedRegion> source) {
checkNotNull(source);
this.source = source;
public RegionOverlapAssociation(@Nonnull Set<ProtectedRegion> source) {
this(source, false);
}
@Override
public Association getAssociation(List<ProtectedRegion> regions) {
for (ProtectedRegion region : regions) {
if ((region.getId().equals(ProtectedRegion.GLOBAL_REGION) && source.isEmpty()) || source.contains(region)) {
return Association.OWNER;
}
}
return Association.NON_MEMBER;
/**
* Create a new instance.
*
* @param source set of regions that input regions must be contained within
* @param useMaxPriorityAssociation whether to use the max priority from regions to determine association
*/
public RegionOverlapAssociation(@Nonnull Set<ProtectedRegion> source, boolean useMaxPriorityAssociation) {
super(source, useMaxPriorityAssociation);
calcMaxPriority();
}
}
@@ -26,7 +26,9 @@ import javax.annotation.Nullable;
/**
* Stores an entity type.
* @deprecated replaced by {@link RegistryFlag<EntityType>}, will be removed in WorldGuard 8
*/
@Deprecated
public class EntityTypeFlag extends Flag<EntityType> {
protected EntityTypeFlag(String name, @Nullable RegionGroup defaultGroup) {
@@ -48,7 +48,7 @@ public final class FlagUtil {
for (Entry<Flag<?>, Object> entry : values.entrySet()) {
try {
rawValues.put(entry.getKey().getName(), marshal(entry.getKey(), entry.getValue()));
} catch (Exception e) {
} catch (Throwable e) {
log.log(Level.WARNING, "Failed to marshal flag value for " + entry.getKey() + "; value is " + entry.getValue(), e);
}
}
@@ -46,6 +46,7 @@ public final class Flags {
// Overrides membership check
public static final StateFlag PASSTHROUGH = register(new StateFlag("passthrough", false));
public static final SetFlag<String> NONPLAYER_PROTECTION_DOMAINS = register(new SetFlag<>("nonplayer-protection-domains", null, new StringFlag(null)));
// This flag is unlike the others. It forces the checking of region membership
public static final StateFlag BUILD = register(new BuildFlag("build", true));
@@ -60,6 +61,7 @@ public final class Flags {
public static final StateFlag DAMAGE_ANIMALS = register(new StateFlag("damage-animals", false));
public static final StateFlag PVP = register(new StateFlag("pvp", false));
public static final StateFlag SLEEP = register(new StateFlag("sleep", false));
public static final StateFlag RESPAWN_ANCHORS = register(new StateFlag("respawn-anchors", false));
public static final StateFlag TNT = register(new StateFlag("tnt", false));
public static final StateFlag CHEST_ACCESS = register(new StateFlag("chest-access", false));
public static final StateFlag PLACE_VEHICLE = register(new StateFlag("vehicle-place", false));
@@ -70,6 +72,8 @@ public final class Flags {
public static final StateFlag ITEM_FRAME_ROTATE = register(new StateFlag("item-frame-rotation", false));
public static final StateFlag TRAMPLE_BLOCKS = register(new StateFlag("block-trampling", false));
public static final StateFlag FIREWORK_DAMAGE = register(new StateFlag("firework-damage", false));
public static final StateFlag USE_ANVIL = register(new StateFlag("use-anvil", false));
public static final StateFlag USE_DRIPLEAF = register(new StateFlag("use-dripleaf", false));
// These flags are similar to the ones above (used in tandem with BUILD),
// but their defaults are set to TRUE because it is more user friendly.
@@ -132,7 +136,7 @@ public final class Flags {
public static final SetFlag<String> ALLOWED_CMDS = register(new SetFlag<>("allowed-cmds", new CommandStringFlag(null)));
// locations
public static final LocationFlag TELE_LOC = register(new LocationFlag("teleport", RegionGroup.MEMBERS));
public static final LocationFlag TELE_LOC = register(new LocationFlag("teleport"));
public static final LocationFlag SPAWN_LOC = register(new LocationFlag("spawn", RegionGroup.MEMBERS));
/**
@@ -24,6 +24,11 @@ import com.sk89q.worldedit.world.gamemode.GameModes;
import javax.annotation.Nullable;
/**
* Stores an gamemode type.
* @deprecated replaced by {@link RegistryFlag<GameMode>}, will be removed in WorldGuard 8
*/
@Deprecated
public class GameModeTypeFlag extends Flag<GameMode> {
protected GameModeTypeFlag(String name, @Nullable RegionGroup defaultGroup) {
@@ -25,6 +25,8 @@ import javax.annotation.Nullable;
import java.util.Map;
import java.util.Map.Entry;
import static java.util.Objects.requireNonNull;
/**
* Stores a key value map of typed {@link Flag}s.
*/
@@ -35,12 +37,16 @@ public class MapFlag<K, V> extends Flag<Map<K, V>> {
public MapFlag(final String name, final Flag<K> keyFlag, final Flag<V> valueFlag) {
super(name);
requireNonNull(keyFlag, "keyFlag cannot be null.");
requireNonNull(valueFlag, "valueFlag cannot be null.");
this.keyFlag = keyFlag;
this.valueFlag = valueFlag;
}
public MapFlag(final String name, @Nullable final RegionGroup defaultGroup, final Flag<K> keyFlag, final Flag<V> valueFlag) {
super(name, defaultGroup);
requireNonNull(keyFlag, "keyFlag cannot be null.");
requireNonNull(valueFlag, "valueFlag cannot be null.");
this.keyFlag = keyFlag;
this.valueFlag = valueFlag;
}
@@ -26,16 +26,20 @@ import javax.annotation.Nullable;
import java.util.Locale;
import java.util.Optional;
import static java.util.Objects.requireNonNull;
public class RegistryFlag<T extends Keyed> extends Flag<T> {
private final Registry<T> registry;
public RegistryFlag(String name, Registry<T> registry) {
super(name);
requireNonNull(registry, "registry cannot be null.");
this.registry = registry;
}
public RegistryFlag(String name, @Nullable RegionGroup defaultGroup, Registry<T> registry) {
super(name, defaultGroup);
requireNonNull(registry, "registry cannot be null.");
this.registry = registry;
}
@@ -27,6 +27,8 @@ import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static java.util.Objects.requireNonNull;
/**
* Stores a set of types.
*/
@@ -36,11 +38,13 @@ public class SetFlag<T> extends Flag<Set<T>> {
public SetFlag(String name, RegionGroup defaultGroup, Flag<T> subFlag) {
super(name, defaultGroup);
requireNonNull(subFlag, "SubFlag cannot be null.");
this.subFlag = subFlag;
}
public SetFlag(String name, Flag<T> subFlag) {
super(name);
requireNonNull(subFlag, "SubFlag cannot be null.");
this.subFlag = subFlag;
}
@@ -0,0 +1,64 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection.flags;
import javax.annotation.Nullable;
import java.util.UUID;
public class UUIDFlag extends Flag<UUID> {
public UUIDFlag(String name, @Nullable RegionGroup defaultGroup) {
super(name, defaultGroup);
}
public UUIDFlag(String name) {
super(name);
}
@Override
public UUID parseInput(FlagContext context) throws InvalidFlagFormat {
String input = context.getUserInput();
if ("self".equalsIgnoreCase(input)) {
return context.getSender().getUniqueId();
}
try {
return UUID.fromString(input);
} catch (IllegalArgumentException e) {
throw new InvalidFlagFormat("Not a valid uuid: " + input);
}
}
@Override
public UUID unmarshal(@Nullable Object o) {
if (!(o instanceof String)) {
return null;
}
try {
return UUID.fromString((String)o);
} catch (IllegalArgumentException e) {
return null;
}
}
@Override
public Object marshal(UUID o) {
return o.toString();
}
}
@@ -24,6 +24,11 @@ import com.sk89q.worldedit.world.weather.WeatherTypes;
import javax.annotation.Nullable;
/**
* Stores an weather type.
* @deprecated replaced by {@link RegistryFlag<WeatherType>}, will be removed in WorldGuard 8
*/
@Deprecated
public class WeatherTypeFlag extends Flag<WeatherType> {
protected WeatherTypeFlag(String name, @Nullable RegionGroup defaultGroup) {
@@ -144,7 +144,7 @@ public class SimpleFlagRegistry implements FlagRegistry {
} else {
log.warning("Failed to parse flag '" + flag.getName() + "' with value '" + entry.getValue() + "'");
}
} catch (Exception e) {
} catch (Throwable e) {
log.log(Level.WARNING, "Failed to unmarshal flag value for " + flag, e);
}
}
@@ -34,7 +34,7 @@ import com.sk89q.worldguard.protection.managers.storage.DifferenceSaveException;
import com.sk89q.worldguard.protection.managers.storage.RegionDatabase;
import com.sk89q.worldguard.protection.managers.storage.StorageException;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.util.RegionCollectionConsumer;
import com.sk89q.worldguard.protection.regions.RegionQuery.QueryOption;
import com.sk89q.worldguard.util.Normal;
import javax.annotation.Nullable;
@@ -293,32 +293,60 @@ public final class RegionManager {
}
/**
* Query for effective flags and owners for the given positive.
* Query for effective flags and members for the given position.
*
* <p>{@link QueryOption#COMPUTE_PARENTS} is used.</p>
*
* @param position the position
* @return the query object
*/
public ApplicableRegionSet getApplicableRegions(BlockVector3 position) {
checkNotNull(position);
Set<ProtectedRegion> regions = Sets.newHashSet();
index.applyContaining(position, new RegionCollectionConsumer(regions, true));
return new RegionResultSet(regions, index.get("__global__"));
return getApplicableRegions(position, QueryOption.COMPUTE_PARENTS);
}
/**
* Query for effective flags and owners for the area represented
* Return a region set for the given position.
*
* @param position the position
* @param option the option
* @return a region set
*/
public ApplicableRegionSet getApplicableRegions(BlockVector3 position, QueryOption option) {
checkNotNull(position);
checkNotNull(option);
Set<ProtectedRegion> regions = Sets.newHashSet();
index.applyContaining(position, option.createIndexConsumer(regions));
return new RegionResultSet(option.constructResult(regions), index.get("__global__"), true);
}
/**
* Query for effective flags and members for the area represented
* by the given region.
*
* <p>{@link QueryOption#COMPUTE_PARENTS} is used.</p>
*
* @param region the region
* @return the query object
*/
public ApplicableRegionSet getApplicableRegions(ProtectedRegion region) {
return getApplicableRegions(region, QueryOption.COMPUTE_PARENTS);
}
/**
* Return a region set for the area represented by the given region.
*
* @param region the region
* @param option the option
* @return a region set
*/
public ApplicableRegionSet getApplicableRegions(ProtectedRegion region, QueryOption option) {
checkNotNull(region);
checkNotNull(option);
Set<ProtectedRegion> regions = Sets.newHashSet();
index.applyIntersecting(region, new RegionCollectionConsumer(regions, true));
return new RegionResultSet(regions, index.get("__global__"));
index.applyIntersecting(region, option.createIndexConsumer(regions));
return new RegionResultSet(option.constructResult(regions), index.get("__global__"), true);
}
/**
@@ -316,7 +316,7 @@ public class ChunkHashTable implements ConcurrentRegionIndex {
List<ProtectedRegion> regions = new ArrayList<>();
ProtectedRegion chunkRegion = new ProtectedCuboidRegion(
"_",
position.multiply(16).toBlockVector3(0),
position.multiply(16).toBlockVector3(Integer.MIN_VALUE),
position.add(1, 1).multiply(16).toBlockVector3(Integer.MAX_VALUE));
index.applyIntersecting(chunkRegion, new RegionCollectionConsumer(regions, false));
Collections.sort(regions);
@@ -24,9 +24,11 @@ import static com.sk89q.worldguard.util.Normal.normalize;
import com.sk89q.worldedit.math.BlockVector2;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.protection.managers.RegionDifference;
import com.sk89q.worldguard.protection.managers.RemovalStrategy;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion.CircularInheritanceException;
import javax.annotation.Nullable;
import java.util.Collection;
@@ -38,6 +40,7 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.logging.Level;
/**
* An index that stores regions in a hash map, which allows for fast lookup
@@ -74,9 +77,13 @@ public class HashMapIndex extends AbstractRegionIndex implements ConcurrentRegio
ProtectedRegion existing = regions.get(normalId);
// Casing / form of ID has changed
if (existing != null && !existing.getId().equals(region.getId())) {
removed.add(existing);
if (existing != null) {
removeAndReplaceParents(existing.getId(), RemovalStrategy.UNSET_PARENT_IN_CHILDREN, region, false);
// Casing / form of ID has not changed
if (existing.getId().equals(region.getId())) {
removed.remove(existing);
}
}
regions.put(normalId, region);
@@ -134,6 +141,10 @@ public class HashMapIndex extends AbstractRegionIndex implements ConcurrentRegio
@Override
public Set<ProtectedRegion> remove(String id, RemovalStrategy strategy) {
return removeAndReplaceParents(id, strategy, null, true);
}
private Set<ProtectedRegion> removeAndReplaceParents(String id, RemovalStrategy strategy, @Nullable ProtectedRegion replacement, boolean rebuildIndex) {
checkNotNull(id);
checkNotNull(strategy);
@@ -161,7 +172,12 @@ public class HashMapIndex extends AbstractRegionIndex implements ConcurrentRegio
it.remove();
break;
case UNSET_PARENT_IN_CHILDREN:
current.clearParent();
try {
current.setParent(replacement);
} catch (CircularInheritanceException e) {
WorldGuard.logger.log(Level.WARNING, "Failed to replace parent '" + parent.getId() + "' of child '" + current.getId() + "' with replacement '" + replacement.getId() + "'", e);
current.clearParent();
}
}
}
}
@@ -174,7 +190,9 @@ public class HashMapIndex extends AbstractRegionIndex implements ConcurrentRegio
this.removed.addAll(removedSet);
rebuildIndex();
if (rebuildIndex) {
rebuildIndex();
}
}
return removedSet;
@@ -23,6 +23,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import com.sk89q.worldedit.math.BlockVector2;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.util.MathUtils;
import java.awt.Rectangle;
@@ -84,18 +85,24 @@ public class ProtectedCuboidRegion extends ProtectedRegion {
* Set the lower point of the cuboid.
*
* @param position the point to set as the minimum point
* @deprecated ProtectedRegion bounds should never be mutated. Regions must be redefined to move them.
* This method will be removed in a future release.
*/
@Deprecated
public void setMinimumPoint(BlockVector3 position) {
setMinMaxPoints(position, max);
WorldGuard.logger.warning("ProtectedCuboidRegion#setMinimumPoint call ignored. Mutating regions leads to undefined behavior.");
}
/**
* Set the upper point of the cuboid.
*
* @param position the point to set as the maximum point
* @deprecated ProtectedRegion bounds should never be mutated. Regions must be redefined to move them.
* This method will be removed in a future release.
*/
@Deprecated
public void setMaximumPoint(BlockVector3 position) {
setMinMaxPoints(min, position);
WorldGuard.logger.warning("ProtectedCuboidRegion#setMaximumPoint call ignored. Mutating regions leads to undefined behavior.");
}
@Override
@@ -46,6 +46,10 @@ import javax.annotation.Nullable;
* against it.
*
* <p>Instances can be modified and access from several threads at a time.</p>
*
* Note: this class has a natural ordering that is inconsistent with equals.
* Regions with identical ids (and also the same priority) may exist in different managers (or no manager at all),
* so care should be taken when comparing regions that have not been obtained from a single manager.
*/
public abstract class ProtectedRegion implements ChangeTracked, Comparable<ProtectedRegion> {
@@ -24,7 +24,9 @@ import com.sk89q.worldedit.world.World;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.RegionResultSet;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.RegionQuery.QueryOption;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
@@ -38,7 +40,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
*/
public class QueryCache {
private final ConcurrentMap<CacheKey, ApplicableRegionSet> cache = new ConcurrentHashMap<>(16, 0.75f, 2);
private final ConcurrentMap<CacheKey, Map<QueryOption, ApplicableRegionSet>> cache = new ConcurrentHashMap<>(16, 0.75f, 2);
/**
* Get from the cache a {@code ApplicableRegionSet} if an entry exists;
@@ -46,20 +48,16 @@ public class QueryCache {
*
* @param manager the region manager
* @param location the location
* @param option the option
* @return a result
*/
public ApplicableRegionSet queryContains(RegionManager manager, Location location) {
public ApplicableRegionSet queryContains(RegionManager manager, Location location, QueryOption option) {
checkNotNull(manager);
checkNotNull(location);
checkNotNull(option);
CacheKey key = new CacheKey(location);
ApplicableRegionSet result = cache.get(key);
if (result == null) {
result = manager.getApplicableRegions(location.toVector().toBlockPoint());
cache.put(key, result);
}
return result;
return cache.compute(key, (k, v) -> option.createCache(manager, location, v)).get(option);
}
/**
@@ -21,6 +21,7 @@ package com.sk89q.worldguard.protection.regions;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.collect.ImmutableList;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldguard.LocalPlayer;
@@ -34,11 +35,21 @@ import com.sk89q.worldguard.protection.RegionResultSet;
import com.sk89q.worldguard.protection.association.RegionAssociable;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.flags.MapFlag;
import com.sk89q.worldguard.protection.flags.RegionGroup;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.flags.StateFlag.State;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.managers.index.RegionIndex;
import com.sk89q.worldguard.protection.util.NormativeOrders;
import com.sk89q.worldguard.protection.util.RegionCollectionConsumer;
import java.util.Collection;
import java.util.EnumMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
@@ -72,17 +83,37 @@ public class RegionQuery {
/**
* Query for regions containing the given location.
*
* <p>An instance of {@link RegionResultSet} will always be returned,
* <p>{@link QueryOption#COMPUTE_PARENTS} is used.</p>
*
* <p>An instance of {@link ApplicableRegionSet} will always be returned,
* even if regions are disabled or region data failed to load. An
* appropriate "virtual" set will be returned in such a case
* (for example, if regions are disabled, the returned set
* would permit all activities).</p>
* appropriate "virtual" set will be returned in such a case (for example,
* if regions are disabled, the returned set would permit all
* activities).</p>
*
* @param location the location
* @return a region set
*/
public ApplicableRegionSet getApplicableRegions(Location location) {
return getApplicableRegions(location, QueryOption.COMPUTE_PARENTS);
}
/**
* Query for regions containing the given location.
*
* <p>An instance of {@link ApplicableRegionSet} will always be returned,
* even if regions are disabled or region data failed to load. An
* appropriate "virtual" set will be returned in such a case (for example,
* if regions are disabled, the returned set would permit all
* activities).</p>
*
* @param location the location
* @param option the option
* @return a region set
*/
public ApplicableRegionSet getApplicableRegions(Location location, QueryOption option) {
checkNotNull(location);
checkNotNull(option);
World world = (World) location.getExtent();
WorldConfiguration worldConfig = config.get(world);
@@ -93,7 +124,7 @@ public class RegionQuery {
RegionManager manager = WorldGuard.getInstance().getPlatform().getRegionContainer().get((World) location.getExtent());
if (manager != null) {
return cache.queryContains(manager, location);
return cache.queryContains(manager, location, option);
} else {
return FailedLoadRegionSet.getInstance();
}
@@ -171,6 +202,56 @@ public class RegionQuery {
queryState(location, associable, flag)));
}
/**
* Returns true if the BUILD flag allows the action in the location, but it
* can be overridden by a list of other flags. The BUILD flag will not
* override the other flags, but the other flags can override BUILD. If
* neither BUILD or any of the flags permit the action, then false will
* be returned.
*
* <p>Use this method when checking flags that are related to build
* protection. For example, lighting fire in a region should not be
* permitted unless the player is a member of the region or the
* LIGHTER flag allows it. However, the LIGHTER flag should be able
* to allow lighting fires even if BUILD is set to DENY.</p>
*
* <p>This method does include parameters for a {@link MapFlag}.</p>
*
* <p>How this method works (BUILD can be overridden by other flags but
* not the other way around) is inconsistent, but it's required for
* legacy reasons.</p>
*
* <p>This method does not check the region bypass permission. That must
* be done by the calling code.</p>
*
* @param location the location
* @param associable an optional associable
* @param mapFlag the MapFlag
* @param key the key for the MapFlag
* @param fallback the fallback flag for MapFlag
* @param flag the flags
* @return true if the result was {@code ALLOW}
* @see RegionResultSet#queryValue(RegionAssociable, Flag)
*/
public <K> boolean testBuild(Location location, RegionAssociable associable, MapFlag<K, State> mapFlag, K key,
@Nullable StateFlag fallback, StateFlag... flag) {
if (mapFlag == null)
return testBuild(location, associable, flag);
if (flag.length == 0) {
return StateFlag.test(StateFlag.combine(
StateFlag.denyToNone(queryState(location, associable, Flags.BUILD)),
queryMapValue(location, associable, mapFlag, key, fallback)
));
}
return StateFlag.test(StateFlag.combine(
StateFlag.denyToNone(queryState(location, associable, Flags.BUILD)),
queryMapValue(location, associable, mapFlag, key, fallback),
queryState(location, associable, flag)
));
}
/**
* Test whether the (effective) value for a list of state flags equals
* {@code ALLOW}.
@@ -319,6 +400,58 @@ public class RegionQuery {
return getApplicableRegions(location).queryValue(associable, flag);
}
/**
* Get the effective value for a key in a {@link MapFlag}. If there are multiple values
* (for example, if there are multiple regions with the same priority
* but with different farewell messages set, there would be multiple
* completing values), then the selected (or "winning") value will be undefined.
*
* <p>A subject can be provided that is used to determine whether the value
* of a flag on a particular region should be used. For example, if a
* flag's region group is set to {@link RegionGroup#MEMBERS} and the given
* subject is not a member, then the region would be skipped when
* querying that flag. If {@code null} is provided for the subject, then
* only flags that use {@link RegionGroup#ALL},
* {@link RegionGroup#NON_MEMBERS}, etc. will apply.</p>
*
* @param subject an optional subject, which would be used to determine the region group to apply
* @param flag the flag of type {@link MapFlag}
* @param key the key for the map flag
* @return a value, which could be {@code null}
*/
@Nullable
public <V, K> V queryMapValue(Location location, @Nullable RegionAssociable subject, MapFlag<K, V> flag, K key) {
return getApplicableRegions(location).queryMapValue(subject, flag, key);
}
/**
* Get the effective value for a key in a {@link MapFlag}. If there are multiple values
* (for example, if there are multiple regions with the same priority
* but with different farewell messages set, there would be multiple
* completing values), then the selected (or "winning") value will be undefined.
*
* <p>A subject can be provided that is used to determine whether the value
* of a flag on a particular region should be used. For example, if a
* flag's region group is set to {@link RegionGroup#MEMBERS} and the given
* subject is not a member, then the region would be skipped when
* querying that flag. If {@code null} is provided for the subject, then
* only flags that use {@link RegionGroup#ALL},
* {@link RegionGroup#NON_MEMBERS}, etc. will apply.</p>
*
* <p>It's possible to provide a fallback flag for the case when the key doesn't
* exist in the {@link MapFlag}.</p>
*
* @param subject an optional subject, which would be used to determine the region group to apply
* @param flag the flag of type {@link MapFlag}
* @param key the key for the map flag
* @param fallback the fallback flag
* @return a value, which could be {@code null}
*/
@Nullable
public <V, K> V queryMapValue(Location location, @Nullable RegionAssociable subject, MapFlag<K, V> flag, K key, Flag<V> fallback) {
return getApplicableRegions(location).queryMapValue(subject, flag, key, fallback);
}
/**
* Get the effective values for a flag, returning a collection of all
* values. It is up to the caller to determine which value, if any,
@@ -361,4 +494,150 @@ public class RegionQuery {
return getApplicableRegions(location).queryAllValues(associable, flag);
}
/**
* Options for constructing a region set via
* {@link #getApplicableRegions(Location, QueryOption)} for example.
*/
public enum QueryOption {
/**
* Constructs a region set that does not include parent regions and
* may be left unsorted (but a cached, sorted set of the same regions
* may be returned).
*/
NONE(false) {
@Override
public List<ProtectedRegion> constructResult(Set<ProtectedRegion> applicable) {
return ImmutableList.copyOf(applicable);
}
@Override
Map<QueryOption, ApplicableRegionSet> createCache(RegionManager manager, Location location, Map<QueryOption, ApplicableRegionSet> cache) {
if (cache == null) {
cache = new EnumMap<>(QueryOption.class);
cache.put(QueryOption.NONE, manager.getApplicableRegions(location.toVector().toBlockPoint(), QueryOption.NONE));
}
// If c != null, we can assume that Option.NONE is present.
return cache;
}
},
/**
* Constructs a region set that does not include parent regions and is
* sorted by {@link NormativeOrders}.
*/
SORT(false) {
@Override
Map<QueryOption, ApplicableRegionSet> createCache(RegionManager manager, Location location, Map<QueryOption, ApplicableRegionSet> cache) {
if (cache == null) {
Map<QueryOption, ApplicableRegionSet> newCache = new EnumMap<>(QueryOption.class);
ApplicableRegionSet result = manager.getApplicableRegions(location.toVector().toBlockPoint(), QueryOption.SORT);
newCache.put(QueryOption.NONE, result);
newCache.put(QueryOption.SORT, result);
return newCache;
} else {
// If c != null, we can assume that Option.NONE is present.
cache.computeIfAbsent(QueryOption.SORT, k -> new RegionResultSet(cache.get(QueryOption.NONE).getRegions(), manager.getRegion("__global__")));
return cache;
}
}
},
/**
* Constructs a region set that includes parent regions and is sorted by
* {@link NormativeOrders}.
*/
COMPUTE_PARENTS(true) {
@Override
Map<QueryOption, ApplicableRegionSet> createCache(RegionManager manager, Location location, Map<QueryOption, ApplicableRegionSet> cache) {
if (cache == null) {
Map<QueryOption, ApplicableRegionSet> newCache = new EnumMap<>(QueryOption.class);
ApplicableRegionSet noParResult = manager.getApplicableRegions(location.toVector().toBlockPoint(), QueryOption.NONE);
Set<ProtectedRegion> noParRegions = noParResult.getRegions();
Set<ProtectedRegion> regions = new HashSet<>();
noParRegions.forEach(new RegionCollectionConsumer(regions, true)::apply);
ApplicableRegionSet result = new RegionResultSet(regions, manager.getRegion("__global__"));
if (regions.size() == noParRegions.size()) {
newCache.put(QueryOption.NONE, result);
newCache.put(QueryOption.SORT, result);
} else {
newCache.put(QueryOption.NONE, noParResult);
}
newCache.put(QueryOption.COMPUTE_PARENTS, result);
return newCache;
}
cache.computeIfAbsent(QueryOption.COMPUTE_PARENTS, k -> {
Set<ProtectedRegion> regions = new HashSet<>();
ApplicableRegionSet result = cache.get(QueryOption.SORT);
boolean sorted = true;
if (result == null) {
// If c != null, we can assume that Option.NONE is present.
result = cache.get(QueryOption.NONE);
sorted = false;
}
Set<ProtectedRegion> noParRegions = result.getRegions();
noParRegions.forEach(new RegionCollectionConsumer(regions, true)::apply);
if (sorted && regions.size() == noParRegions.size()) {
return result;
}
result = new RegionResultSet(regions, manager.getRegion("__global__"));
if (regions.size() == noParRegions.size()) {
cache.put(QueryOption.SORT, result);
}
return result;
});
return cache;
}
};
private final boolean collectParents;
QueryOption(boolean collectParents) {
this.collectParents = collectParents;
}
/**
* Create a {@link RegionCollectionConsumer} with the given collection
* used for the {@link RegionIndex}. Internal API.
*
* @param collection the collection
* @return a region collection consumer
*/
public RegionCollectionConsumer createIndexConsumer(Collection<? super ProtectedRegion> collection) {
return new RegionCollectionConsumer(collection, collectParents);
}
/**
* Convert the set of regions to a list. Sort and add parents if
* necessary. Internal API.
*
* @param applicable the set of regions
* @return a list of regions
*/
public List<ProtectedRegion> constructResult(Set<ProtectedRegion> applicable) {
return NormativeOrders.fromSet(applicable);
}
/**
* Create (if null) or update the given cache map with at least an entry
* for this option if necessary and return it.
*
* @param manager the manager
* @param location the location
* @param cache the cache map
* @return a cache map
*/
abstract Map<QueryOption, ApplicableRegionSet> createCache(RegionManager manager, Location location, Map<QueryOption, ApplicableRegionSet> cache);
}
}
@@ -35,7 +35,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
*/
public class RegionCollectionConsumer implements Predicate<ProtectedRegion> {
private final Collection<ProtectedRegion> collection;
private final Collection<? super ProtectedRegion> collection;
private final boolean addParents;
/**
@@ -44,7 +44,7 @@ public class RegionCollectionConsumer implements Predicate<ProtectedRegion> {
* @param collection the collection to add regions to
* @param addParents true to also add the parents to the collection
*/
public RegionCollectionConsumer(Collection<ProtectedRegion> collection, boolean addParents) {
public RegionCollectionConsumer(Collection<? super ProtectedRegion> collection, boolean addParents) {
checkNotNull(collection);
this.collection = collection;
@@ -0,0 +1,75 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection.util;
import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.regions.Polygonal2DRegion;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.regions.RegionSelector;
import com.sk89q.worldedit.regions.selector.CuboidRegionSelector;
import com.sk89q.worldedit.regions.selector.Polygonal2DRegionSelector;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import com.sk89q.worldguard.protection.regions.ProtectedPolygonalRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
/**
* A helper class to convert regions from WorldGuard to WorldEdit
*/
public final class WorldEditRegionConverter {
private WorldEditRegionConverter() {
}
/**
* Converts a ProtectedRegion to a WorldEdit Region, otherwise null if
* the ProtectedRegion can't be converted to a RegionSelector.
*
* @param region the WorldGuard region
* @return the WorldEdit Region
*/
public static Region convertToRegion(ProtectedRegion region) {
if (region instanceof ProtectedCuboidRegion) {
return new CuboidRegion(null, region.getMinimumPoint(), region.getMaximumPoint());
}
if (region instanceof ProtectedPolygonalRegion) {
return new Polygonal2DRegion(null, region.getPoints(),
region.getMinimumPoint().getY(), region.getMaximumPoint().getY());
}
return null;
}
/**
* Converts a ProtectedRegion to a WorldEdit RegionSelector, otherwise null if
* the ProtectedRegion can't be converted to a RegionSelector.
*
* @param region the WorldGuard region
* @return the WorldEdit Region
*/
public static RegionSelector convertToSelector(ProtectedRegion region) {
if (region instanceof ProtectedCuboidRegion) {
return new CuboidRegionSelector(null, region.getMinimumPoint(), region.getMaximumPoint());
}
if (region instanceof ProtectedPolygonalRegion) {
return new Polygonal2DRegionSelector(null, region.getPoints(),
region.getMinimumPoint().getY(), region.getMaximumPoint().getY());
}
return null;
}
}
@@ -44,10 +44,13 @@ import com.sk89q.worldguard.session.handler.WeatherLockFlag;
import javax.annotation.Nullable;
import java.lang.ref.WeakReference;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.BiPredicate;
import java.util.logging.Level;
import static com.google.common.base.Preconditions.checkNotNull;
@@ -57,11 +60,14 @@ public abstract class AbstractSessionManager implements SessionManager {
public static final int RUN_DELAY = 20;
public static final long SESSION_LIFETIME = 10;
private static final BiPredicate<World, LocalPlayer> BYPASS_PERMISSION_TEST = (world, player) -> {
return player.hasPermission("worldguard.region.bypass." + world.getName());
};
private final LoadingCache<WorldPlayerTuple, Boolean> bypassCache = CacheBuilder.newBuilder()
.maximumSize(1000)
.expireAfterWrite(2, TimeUnit.SECONDS)
.build(CacheLoader.from(tuple ->
tuple.getPlayer().hasPermission("worldguard.region.bypass." + tuple.getWorld().getName())));
.build(CacheLoader.from(tuple -> BYPASS_PERMISSION_TEST.test(tuple.getWorld(), tuple.getPlayer())));
private final LoadingCache<CacheKey, Session> sessions = CacheBuilder.newBuilder()
.expireAfterAccess(SESSION_LIFETIME, TimeUnit.MINUTES)
@@ -69,6 +75,8 @@ public abstract class AbstractSessionManager implements SessionManager {
createSession(key.playerRef.get())));
private boolean hasCustom = false;
// <original handler, wrapped handler>
private Map<Handler.Factory<? extends Handler>, Handler.Factory<? extends Handler>> wrappedHandlers = new HashMap<>();
private List<Handler.Factory<? extends Handler>> handlers = new LinkedList<>();
private static final List<Handler.Factory<? extends Handler>> defaultHandlers = new LinkedList<>();
@@ -102,20 +110,27 @@ public abstract class AbstractSessionManager implements SessionManager {
return hasCustom;
}
protected Handler.Factory<? extends Handler> wrapForRegistration(Handler.Factory<? extends Handler> factory) {
return factory;
}
@Override
public boolean registerHandler(Handler.Factory<? extends Handler> factory, @Nullable Handler.Factory<? extends Handler> after) {
if (factory == null) return false;
WorldGuard.logger.log(Level.INFO, "Registering session handler "
+ factory.getClass().getEnclosingClass().getName());
hasCustom = true;
Handler.Factory<? extends Handler> wrappedFactory = wrapForRegistration(factory);
if (after == null) {
handlers.add(factory);
handlers.add(wrappedFactory);
} else {
int index = handlers.indexOf(after);
Handler.Factory<? extends Handler> wrappedAfter = wrappedHandlers.get(after);
int index = handlers.indexOf(wrappedAfter != null ? wrappedAfter : after);
if (index == -1) return false;
handlers.add(index, factory); // shifts "after" right one, and everything after "after" right one
handlers.add(index + 1, factory); // shifts "after" right one, and everything after "after" right one
}
wrappedHandlers.put(factory, wrappedFactory);
return true;
}
@@ -127,6 +142,7 @@ public abstract class AbstractSessionManager implements SessionManager {
} else {
WorldGuard.logger.log(Level.INFO, "Unregistering session handler "
+ factory.getClass().getEnclosingClass().getName());
factory = wrappedHandlers.remove(factory);
}
return handlers.remove(factory);
}
@@ -134,8 +150,15 @@ public abstract class AbstractSessionManager implements SessionManager {
@Override
public boolean hasBypass(LocalPlayer player, World world) {
Session sess = getIfPresent(player);
return sess != null && !sess.hasBypassDisabled()
&& bypassCache.getUnchecked(new WorldPlayerTuple(world, player));
if (sess == null || sess.hasBypassDisabled()) {
return false;
}
if (WorldGuard.getInstance().getPlatform().getGlobalStateManager().disablePermissionCache) {
return BYPASS_PERMISSION_TEST.test(world, player);
}
return bypassCache.getUnchecked(new WorldPlayerTuple(world, player));
}
@Override
@@ -22,8 +22,11 @@ package com.sk89q.worldguard.session;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.util.formatting.text.TextComponent;
import com.sk89q.worldedit.util.formatting.text.format.TextColor;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.config.ConfigurationManager;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.StateFlag.State;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
@@ -31,10 +34,10 @@ import com.sk89q.worldguard.protection.regions.RegionQuery;
import com.sk89q.worldguard.session.handler.Handler;
import com.sk89q.worldguard.util.Locations;
import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkNotNull;
@@ -66,7 +69,7 @@ public class Session {
* @param handler A new handler
*/
public void register(Handler handler) {
handlers.put(handler.getClass(), handler);
handlers.put(handler.getWrappedHandler().getClass(), handler);
}
/**
@@ -88,7 +91,7 @@ public class Session {
@Nullable
@SuppressWarnings("unchecked")
public <T extends Handler> T getHandler(Class<T> type) {
return (T) handlers.get(type);
return (T) handlers.get(type).getWrappedHandler();
}
/**
@@ -103,6 +106,14 @@ public class Session {
lastValid = location;
lastRegionSet = set.getRegions();
ConfigurationManager cfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
disableBypass = cfg.disableDefaultBypass;
if (cfg.announceBypassStatus && player.hasPermission("worldguard.region.toggle-bypass")) {
player.printInfo(TextComponent.of(
"You are " + (disableBypass ? "not" : "") + " bypassing region protection. " +
"You can toggle this with /rg bypass", TextColor.DARK_PURPLE));
}
for (Handler handler : handlers.values()) {
handler.initialize(player, location, set);
@@ -138,4 +138,11 @@ public abstract class Handler {
return null;
}
/**
* Get the handler wrapped by this handler object, if applicable, or just return this if no handler is wrapped.
* @return any wrapped handler, or this handler itself
*/
public Handler getWrappedHandler() {
return this;
}
}
@@ -24,7 +24,7 @@ import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.registry.state.Property;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockType;
import com.sk89q.worldedit.world.block.BlockTypes;
import com.sk89q.worldguard.WorldGuard;
@@ -60,7 +60,7 @@ public final class SpongeUtil {
for (int cy = -wcfg.spongeRadius; cy <= wcfg.spongeRadius; cy++) {
for (int cz = -wcfg.spongeRadius; cz <= wcfg.spongeRadius; cz++) {
BlockVector3 vector = BlockVector3.at(ox + cx, oy + cy, oz + cz);
BlockState block = world.getBlock(vector);
BaseBlock block = world.getFullBlock(vector);
BlockType blockType = block.getBlockType();
if (isReplacable(blockType)) {
try {
@@ -30,7 +30,6 @@ import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.util.formatting.text.Component;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldedit.world.weather.WeatherType;
import org.junit.Ignore;
import java.util.HashSet;
import java.util.Locale;
@@ -39,7 +38,7 @@ import java.util.UUID;
import javax.annotation.Nullable;
@Ignore
public class TestPlayer extends AbstractPlayerActor implements LocalPlayer {
private final UUID uuid = UUID.randomUUID();
@@ -250,6 +249,7 @@ public class TestPlayer extends AbstractPlayerActor implements LocalPlayer {
}
@Override
@Deprecated
public void setPosition(Vector3 pos, float pitch, float yaw) {
}
@@ -20,13 +20,14 @@
package com.sk89q.worldguard.domains;
import com.sk89q.worldguard.TestPlayer;
import junit.framework.TestCase;
import org.junit.jupiter.api.Test;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class DefaultDomainTest extends TestCase {
public class DefaultDomainTest {
@Test
public void testContains() throws Exception {
TestPlayer player1 = new TestPlayer("test1");
TestPlayer player2 = new TestPlayer("test2");
@@ -40,81 +41,76 @@ public class DefaultDomainTest extends TestCase {
domain = new DefaultDomain();
domain.addGroup("group1");
assertThat(domain.contains(player1), is(false));
assertThat(domain.contains(player2), is(true));
assertThat(domain.contains(player3), is(true));
assertFalse(domain.contains(player1));
assertTrue(domain.contains(player2));
assertTrue(domain.contains(player3));
domain = new DefaultDomain();
domain.addGroup("group1");
domain.addGroup("group2");
assertThat(domain.contains(player1), is(false));
assertThat(domain.contains(player2), is(true));
assertThat(domain.contains(player3), is(true));
assertFalse(domain.contains(player1));
assertTrue(domain.contains(player2));
assertTrue(domain.contains(player3));
domain = new DefaultDomain();
domain.addGroup("group1");
domain.addGroup("group3");
assertThat(domain.contains(player1), is(false));
assertThat(domain.contains(player2), is(true));
assertThat(domain.contains(player3), is(true));
assertFalse(domain.contains(player1));
assertTrue(domain.contains(player2));
assertTrue(domain.contains(player3));
domain = new DefaultDomain();
domain.addGroup("group3");
assertThat(domain.contains(player1), is(false));
assertThat(domain.contains(player2), is(false));
assertThat(domain.contains(player3), is(true));
assertFalse(domain.contains(player1));
assertFalse(domain.contains(player2));
assertTrue(domain.contains(player3));
domain = new DefaultDomain();
domain.addPlayer(player1.getName());
assertThat(domain.contains(player1), is(true));
assertThat(domain.contains(player2), is(false));
assertThat(domain.contains(player3), is(false));
assertTrue(domain.contains(player1));
assertFalse(domain.contains(player2));
assertFalse(domain.contains(player3));
domain = new DefaultDomain();
domain.addGroup("group3");
domain.addPlayer(player1.getName());
assertThat(domain.contains(player1), is(true));
assertThat(domain.contains(player2), is(false));
assertThat(domain.contains(player3), is(true));
assertTrue(domain.contains(player1));
assertFalse(domain.contains(player2));
assertTrue(domain.contains(player3));
domain = new DefaultDomain();
domain.addGroup("group3");
domain.addPlayer(player1.getUniqueId());
assertThat(domain.contains(player1), is(true));
assertThat(domain.contains(player2), is(false));
assertThat(domain.contains(player3), is(true));
assertTrue(domain.contains(player1));
assertFalse(domain.contains(player2));
assertTrue(domain.contains(player3));
domain = new DefaultDomain();
domain.addGroup("group3");
domain.addPlayer(player1.getName());
domain.addPlayer(player1.getUniqueId());
assertThat(domain.contains(player1), is(true));
assertThat(domain.contains(player2), is(false));
assertThat(domain.contains(player3), is(true));
assertTrue(domain.contains(player1));
assertFalse(domain.contains(player2));
assertTrue(domain.contains(player3));
domain = new DefaultDomain();
domain.addGroup("group3");
domain.addPlayer(player1);
assertThat(domain.contains(player1), is(true));
assertThat(domain.contains(player2), is(false));
assertThat(domain.contains(player3), is(true));
assertTrue(domain.contains(player1));
assertFalse(domain.contains(player2));
assertTrue(domain.contains(player3));
domain = new DefaultDomain();
domain.addPlayer(player1);
assertThat(domain.contains(player1), is(true));
assertThat(domain.contains(player2), is(false));
assertThat(domain.contains(player3), is(false));
assertTrue(domain.contains(player1));
assertFalse(domain.contains(player2));
assertFalse(domain.contains(player3));
domain = new DefaultDomain();
domain.addPlayer(player2);
domain.addPlayer(player3);
assertThat(domain.contains(player1), is(false));
assertThat(domain.contains(player2), is(true));
assertThat(domain.contains(player3), is(true));
assertFalse(domain.contains(player1));
assertTrue(domain.contains(player2));
assertTrue(domain.contains(player3));
}
public void testSize() throws Exception {
}
}
@@ -25,13 +25,15 @@ import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.flags.StringFlag;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.util.command.CommandFilter;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.HashSet;
import java.util.Set;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
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.assertTrue;
public class ApplicableRegionSetTest {
@@ -42,7 +44,7 @@ public class ApplicableRegionSetTest {
LocalPlayer player = mock.createPlayer();
ApplicableRegionSet set = mock.getApplicableSet();
assertThat(set.testState(player, Flags.BUILD), is(true));
assertTrue(set.testState(player, Flags.BUILD));
}
@Test
@@ -54,7 +56,7 @@ public class ApplicableRegionSetTest {
ProtectedRegion global = mock.global();
ApplicableRegionSet set = mock.getApplicableSet();
assertThat(set.testState(player, Flags.BUILD), is(true));
assertTrue(set.testState(player, Flags.BUILD));
}
@Test
@@ -68,8 +70,8 @@ public class ApplicableRegionSetTest {
region.getMembers().addPlayer(member);
ApplicableRegionSet set = mock.getApplicableSet();
assertThat(set.testState(member, Flags.BUILD), is(true));
assertThat(set.testState(nonMember, Flags.BUILD), is(false));
assertTrue(set.testState(member, Flags.BUILD));
assertFalse(set.testState(nonMember, Flags.BUILD));
}
@Test
@@ -80,15 +82,15 @@ public class ApplicableRegionSetTest {
ApplicableRegionSet set = mock.getApplicableSet();
assertThat(set.testState(player, Flags.MOB_DAMAGE), is(true));
assertThat(set.testState(player, Flags.ENTRY), is(true));
assertThat(set.testState(player, Flags.EXIT), is(true));
assertThat(set.testState(player, Flags.LEAF_DECAY), is(true));
assertThat(set.testState(player, Flags.RECEIVE_CHAT), is(true));
assertThat(set.testState(player, Flags.SEND_CHAT), is(true));
assertThat(set.testState(player, Flags.INVINCIBILITY), is(false));
assertTrue(set.testState(player, Flags.MOB_DAMAGE));
assertTrue(set.testState(player, Flags.ENTRY));
assertTrue(set.testState(player, Flags.EXIT));
assertTrue(set.testState(player, Flags.LEAF_DECAY));
assertTrue(set.testState(player, Flags.RECEIVE_CHAT));
assertTrue(set.testState(player, Flags.SEND_CHAT));
assertFalse(set.testState(player, Flags.INVINCIBILITY));
assertThat(set.testState(player, Flags.BUILD), is(true));
assertTrue(set.testState(player, Flags.BUILD));
}
@Test
@@ -101,15 +103,15 @@ public class ApplicableRegionSetTest {
ApplicableRegionSet set = mock.getApplicableSet();
assertThat(set.testState(player, Flags.MOB_DAMAGE), is(true));
assertThat(set.testState(player, Flags.ENTRY), is(true));
assertThat(set.testState(player, Flags.EXIT), is(true));
assertThat(set.testState(player, Flags.LEAF_DECAY), is(true));
assertThat(set.testState(player, Flags.RECEIVE_CHAT), is(true));
assertThat(set.testState(player, Flags.SEND_CHAT), is(true));
assertThat(set.testState(player, Flags.INVINCIBILITY), is(false));
assertTrue(set.testState(player, Flags.MOB_DAMAGE));
assertTrue(set.testState(player, Flags.ENTRY));
assertTrue(set.testState(player, Flags.EXIT));
assertTrue(set.testState(player, Flags.LEAF_DECAY));
assertTrue(set.testState(player, Flags.RECEIVE_CHAT));
assertTrue(set.testState(player, Flags.SEND_CHAT));
assertFalse(set.testState(player, Flags.INVINCIBILITY));
assertThat(set.testState(player, Flags.BUILD), is(true));
assertTrue(set.testState(player, Flags.BUILD));
}
@Test
@@ -124,25 +126,25 @@ public class ApplicableRegionSetTest {
ApplicableRegionSet set = mock.getApplicableSet();
assertThat(set.testState(member, Flags.MOB_DAMAGE), is(true));
assertThat(set.testState(member, Flags.ENTRY), is(true));
assertThat(set.testState(member, Flags.EXIT), is(true));
assertThat(set.testState(member, Flags.LEAF_DECAY), is(true));
assertThat(set.testState(member, Flags.RECEIVE_CHAT), is(true));
assertThat(set.testState(member, Flags.SEND_CHAT), is(true));
assertThat(set.testState(member, Flags.INVINCIBILITY), is(false));
assertTrue(set.testState(member, Flags.MOB_DAMAGE));
assertTrue(set.testState(member, Flags.ENTRY));
assertTrue(set.testState(member, Flags.EXIT));
assertTrue(set.testState(member, Flags.LEAF_DECAY));
assertTrue(set.testState(member, Flags.RECEIVE_CHAT));
assertTrue(set.testState(member, Flags.SEND_CHAT));
assertFalse(set.testState(member, Flags.INVINCIBILITY));
assertThat(set.testState(member, Flags.BUILD), is(true));
assertTrue(set.testState(member, Flags.BUILD));
assertThat(set.testState(nonMember, Flags.MOB_DAMAGE), is(true));
assertThat(set.testState(nonMember, Flags.ENTRY), is(true));
assertThat(set.testState(nonMember, Flags.EXIT), is(true));
assertThat(set.testState(nonMember, Flags.LEAF_DECAY), is(true));
assertThat(set.testState(nonMember, Flags.RECEIVE_CHAT), is(true));
assertThat(set.testState(nonMember, Flags.SEND_CHAT), is(true));
assertThat(set.testState(nonMember, Flags.INVINCIBILITY), is(false));
assertTrue(set.testState(nonMember, Flags.MOB_DAMAGE));
assertTrue(set.testState(nonMember, Flags.ENTRY));
assertTrue(set.testState(nonMember, Flags.EXIT));
assertTrue(set.testState(nonMember, Flags.LEAF_DECAY));
assertTrue(set.testState(nonMember, Flags.RECEIVE_CHAT));
assertTrue(set.testState(nonMember, Flags.SEND_CHAT));
assertFalse(set.testState(nonMember, Flags.INVINCIBILITY));
assertThat(set.testState(nonMember, Flags.BUILD), is(false));
assertFalse(set.testState(nonMember, Flags.BUILD));
}
@Test
@@ -623,19 +625,19 @@ public class ApplicableRegionSetTest {
test = new CommandFilter(
set.queryValue(nonMember, Flags.ALLOWED_CMDS),
set.queryValue(nonMember, Flags.BLOCKED_CMDS));
assertThat(test.apply("/permit"), is(true));
assertThat(test.apply("/strange"), is(true));
assertThat(test.apply("/other"), is(false));
assertThat(test.apply("/deny"), is(false));
assertTrue(test.apply("/permit"));
assertTrue(test.apply("/strange"));
assertFalse(test.apply("/other"));
assertFalse(test.apply("/deny"));
set = mock.getApplicableSetInWilderness();
test = new CommandFilter(
set.queryValue(nonMember, Flags.ALLOWED_CMDS),
set.queryValue(nonMember, Flags.BLOCKED_CMDS));
assertThat(test.apply("/permit"), is(true));
assertThat(test.apply("/strange"), is(false));
assertThat(test.apply("/other"), is(true));
assertThat(test.apply("/deny"), is(false));
assertTrue(test.apply("/permit"));
assertFalse(test.apply("/strange"));
assertTrue(test.apply("/other"));
assertFalse(test.apply("/deny"));
}
@Test
@@ -0,0 +1,123 @@
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.protection;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.flags.MapFlag;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.flags.StringFlag;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
@SuppressWarnings({"UnusedDeclaration"})
public class FlagValueCalculatorMapFlagTest {
@Test
public void testGetEffectiveMapFlagWithFallback() throws Exception {
MockApplicableRegionSet mock = new MockApplicableRegionSet();
ProtectedRegion global = mock.global();
global.setFlag(Flags.BUILD, StateFlag.State.DENY);
MapFlag<String, StateFlag.State> mapFlag =
new MapFlag<>("test", new StringFlag(null), new StateFlag(null, true));
Map<String, StateFlag.State> map = new HashMap<>();
map.put("allow", StateFlag.State.ALLOW);
map.put("deny", StateFlag.State.DENY);
global.setFlag(mapFlag, map);
ApplicableRegionSet applicableSet = mock.getApplicableSet();
assertEquals(applicableSet.queryMapValue(null, mapFlag, "allow", Flags.BUILD),
StateFlag.State.ALLOW);
assertEquals(applicableSet.queryMapValue(null, mapFlag, "deny", Flags.BUILD),
StateFlag.State.DENY);
assertEquals(applicableSet.queryMapValue(null, mapFlag, "undefined", Flags.BUILD),
StateFlag.State.DENY);
assertEquals(applicableSet.queryMapValue(null, mapFlag, "allow", null),
StateFlag.State.ALLOW);
assertEquals(applicableSet.queryMapValue(null, mapFlag, "deny", null),
StateFlag.State.DENY);
assertEquals(applicableSet.queryMapValue(null, mapFlag, "undefined", null),
StateFlag.State.ALLOW);
}
@Test
public void testGetEffectiveMapFlagWithSamePriority() throws Exception {
MockApplicableRegionSet mock = new MockApplicableRegionSet();
ProtectedRegion region1 = mock.add(0);
ProtectedRegion region2 = mock.add(0);
MapFlag<String, StateFlag.State> mapFlag =
new MapFlag<>("test", new StringFlag(null), new StateFlag(null, true));
Map<String, StateFlag.State> map1 = new HashMap<>();
Map<String, StateFlag.State> map2 = new HashMap<>();
map1.put("should-deny", StateFlag.State.ALLOW);
map2.put("should-deny", StateFlag.State.DENY);
map1.put("should-allow", StateFlag.State.ALLOW);
map1.put("should-allow2", StateFlag.State.ALLOW);
map2.put("should-allow2", StateFlag.State.ALLOW);
region1.setFlag(mapFlag, map1);
region2.setFlag(mapFlag, map2);
ApplicableRegionSet applicableSet = mock.getApplicableSet();
assertEquals(applicableSet.queryMapValue(null, mapFlag, "should-deny", null),
StateFlag.State.DENY);
assertEquals(applicableSet.queryMapValue(null, mapFlag, "should-allow", null),
StateFlag.State.ALLOW);
assertEquals(applicableSet.queryMapValue(null, mapFlag, "should-allow2", null),
StateFlag.State.ALLOW);
}
@Test
public void testGetEffectiveMapFlagWithInheritance() throws Exception {
MockApplicableRegionSet mock = new MockApplicableRegionSet();
ProtectedRegion parent = mock.add(0);
ProtectedRegion child = mock.add(0, parent);
MapFlag<String, StateFlag.State> mapFlag =
new MapFlag<>("test", new StringFlag(null), new StateFlag(null, true));
Map<String, StateFlag.State> parentMap = new HashMap<>();
Map<String, StateFlag.State> childMap = new HashMap<>();
parentMap.put("useChildValue", StateFlag.State.ALLOW);
childMap.put("useChildValue", StateFlag.State.DENY);
parentMap.put("useParentValue", StateFlag.State.ALLOW);
parent.setFlag(mapFlag, parentMap);
child.setFlag(mapFlag, childMap);
ApplicableRegionSet applicableSet = mock.getApplicableSet();
assertEquals(applicableSet.queryMapValue(null, mapFlag, "useChildValue", null),
StateFlag.State.DENY);
assertEquals(applicableSet.queryMapValue(null, mapFlag, "useParentValue", null),
StateFlag.State.ALLOW);
}
}
@@ -28,12 +28,14 @@ import com.sk89q.worldguard.protection.flags.StateFlag.State;
import com.sk89q.worldguard.protection.flags.StringFlag;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Set;
import static com.google.common.collect.ImmutableSet.copyOf;
import static com.google.common.collect.ImmutableSet.of;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.*;
@SuppressWarnings({"UnusedAssignment", "UnusedDeclaration"})
public class FlagValueCalculatorTest {
@@ -45,7 +47,7 @@ public class FlagValueCalculatorTest {
LocalPlayer player = mock.createPlayer();
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getMembership(player), is(Result.NO_REGIONS));
assertEquals(result.getMembership(player), Result.NO_REGIONS);
}
@Test
@@ -57,7 +59,7 @@ public class FlagValueCalculatorTest {
ProtectedRegion global = mock.global();
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getMembership(player), is(Result.NO_REGIONS));
assertEquals(result.getMembership(player), Result.NO_REGIONS);
}
@Test
@@ -69,7 +71,7 @@ public class FlagValueCalculatorTest {
LocalPlayer player = mock.createPlayer();
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getMembership(player), is(Result.NO_REGIONS));
assertEquals(result.getMembership(player), Result.NO_REGIONS);
}
@Test
@@ -83,7 +85,7 @@ public class FlagValueCalculatorTest {
LocalPlayer player = mock.createPlayer();
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getMembership(player), is(Result.FAIL));
assertEquals(result.getMembership(player), Result.FAIL);
}
@Test
@@ -99,7 +101,7 @@ public class FlagValueCalculatorTest {
LocalPlayer player = mock.createPlayer();
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getMembership(player), is(Result.NO_REGIONS));
assertEquals(result.getMembership(player), Result.NO_REGIONS);
}
@Test
@@ -114,7 +116,7 @@ public class FlagValueCalculatorTest {
LocalPlayer player = mock.createPlayer();
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getMembership(player), is(Result.FAIL));
assertEquals(result.getMembership(player), Result.FAIL);
}
@Test
@@ -130,7 +132,7 @@ public class FlagValueCalculatorTest {
region.getMembers().addPlayer(player);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getMembership(player), is(Result.SUCCESS));
assertEquals(result.getMembership(player), Result.SUCCESS);
}
@Test
@@ -148,13 +150,13 @@ public class FlagValueCalculatorTest {
region = mock.add(0);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getMembership(player), is(Result.FAIL));
assertEquals(result.getMembership(player), Result.FAIL);
// Add another player (should still fail)
region.getMembers().addPlayer(mock.createPlayer());
result = mock.getFlagCalculator();
assertThat(result.getMembership(player), is(Result.FAIL));
assertEquals(result.getMembership(player), Result.FAIL);
}
@Test
@@ -172,7 +174,7 @@ public class FlagValueCalculatorTest {
region = mock.add(10);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getMembership(player), is(Result.FAIL));
assertEquals(result.getMembership(player), Result.FAIL);
}
@Test
@@ -190,7 +192,7 @@ public class FlagValueCalculatorTest {
region = mock.add(0);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getMembership(player), is(Result.SUCCESS));
assertEquals(result.getMembership(player), Result.SUCCESS);
}
@Test
@@ -209,7 +211,7 @@ public class FlagValueCalculatorTest {
region.getMembers().addPlayer(player);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getMembership(player), is(Result.SUCCESS));
assertEquals(result.getMembership(player), Result.SUCCESS);
}
@Test
@@ -228,7 +230,7 @@ public class FlagValueCalculatorTest {
parent.getMembers().addPlayer(player);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getMembership(player), is(Result.SUCCESS));
assertEquals(result.getMembership(player), Result.SUCCESS);
}
@Test
@@ -249,7 +251,7 @@ public class FlagValueCalculatorTest {
parent.getMembers().addPlayer(player);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getMembership(player), is(Result.FAIL));
assertEquals(result.getMembership(player), Result.FAIL);
}
@Test
@@ -271,7 +273,7 @@ public class FlagValueCalculatorTest {
parent.getMembers().addPlayer(player);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getMembership(player), is(Result.SUCCESS));
assertEquals(result.getMembership(player), Result.SUCCESS);
}
// ========================================================================
@@ -285,8 +287,8 @@ public class FlagValueCalculatorTest {
StateFlag flag2 = new StateFlag("test2", true);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.queryState(null, flag1), is((State) null));
assertThat(result.queryState(null, flag2), is(State.ALLOW));
assertNull(result.queryState(null, flag1));
assertEquals(result.queryState(null, flag2), State.ALLOW);
}
// ========================================================================
@@ -303,8 +305,8 @@ public class FlagValueCalculatorTest {
region.setFlag(flag2, State.DENY);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.queryValue(null, flag1), is((State) null));
assertThat(result.queryValue(null, flag2), is(State.DENY));
assertNull(result.queryValue(null, flag1));
assertEquals(result.queryValue(null, flag2), State.DENY);
}
@Test
@@ -321,8 +323,8 @@ public class FlagValueCalculatorTest {
region.setFlag(flag2, State.ALLOW);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.queryValue(null, flag1), is((State) null));
assertThat(result.queryValue(null, flag2), is(State.DENY));
assertNull(result.queryValue(null, flag1));
assertEquals(result.queryValue(null, flag2), State.DENY);
}
@Test
@@ -338,8 +340,8 @@ public class FlagValueCalculatorTest {
region.setFlag(flag2, State.ALLOW);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.queryValue(null, flag1), is((State) null));
assertThat(result.queryValue(null, flag2), is(State.ALLOW));
assertNull(result.queryValue(null, flag1));
assertEquals(result.queryValue(null, flag2), State.ALLOW);
}
@Test
@@ -358,9 +360,9 @@ public class FlagValueCalculatorTest {
region.setFlag(flag2, State.DENY);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.queryValue(null, flag1), is(State.DENY));
assertThat(result.queryValue(null, flag2), is(State.DENY));
assertThat(result.queryValue(null, flag3), is((State) null));
assertEquals(result.queryValue(null, flag1), State.DENY);
assertEquals(result.queryValue(null, flag2), State.DENY);
assertNull(result.queryValue(null, flag3));
}
@Test
@@ -381,8 +383,8 @@ public class FlagValueCalculatorTest {
region.setParent(parent);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.queryValue(nonMember, flag1), is(State.DENY));
assertThat(result.queryValue(member, flag1), is((State) null));
assertEquals(result.queryValue(nonMember, flag1), State.DENY);
assertNull(result.queryValue(member, flag1));
}
@Test
@@ -405,9 +407,9 @@ public class FlagValueCalculatorTest {
region.setParent(parent);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.queryValue(nonMember, flag1), is(State.DENY));
assertThat(result.queryValue(memberOne, flag1), is((State) null));
assertThat(result.queryValue(memberTwo, flag1), is(State.DENY));
assertEquals(result.queryValue(nonMember, flag1), State.DENY);
assertNull(result.queryValue(memberOne, flag1));
assertEquals(result.queryValue(memberTwo, flag1), State.DENY);
}
@Test
@@ -427,8 +429,8 @@ public class FlagValueCalculatorTest {
region.getMembers().addPlayer(member);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.queryValue(nonMember, flag1), is(State.DENY));
assertThat(result.queryValue(member, flag1), is(State.DENY));
assertEquals(result.queryValue(nonMember, flag1), State.DENY);
assertEquals(result.queryValue(member, flag1), State.DENY);
}
@Test
@@ -450,8 +452,8 @@ public class FlagValueCalculatorTest {
region.getMembers().addPlayer(member);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.queryValue(nonMember, flag1), is(State.DENY));
assertThat(result.queryValue(member, flag1), is(State.ALLOW));
assertEquals(result.queryValue(nonMember, flag1), State.DENY);
assertEquals(result.queryValue(member, flag1), State.ALLOW);
}
@Test
@@ -469,9 +471,9 @@ public class FlagValueCalculatorTest {
region.setFlag(stringFlag1, "test2");
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.queryValue(null, stringFlag1), isOneOf("test1", "test2"));
assertThat(result.queryValue(null, stringFlag2), is((String) null));
assertThat(result.queryValue(null, flag1), is((State) null));
assertTrue(List.of("test1", "test2").contains(result.queryValue(null, stringFlag1)));
assertNull(result.queryValue(null, stringFlag2));
assertNull(result.queryValue(null, flag1));
}
@Test
@@ -483,7 +485,7 @@ public class FlagValueCalculatorTest {
ProtectedRegion global = mock.global();
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.queryValue(null, flag), is(State.ALLOW));
assertEquals(result.queryValue(null, flag), State.ALLOW);
}
@Test
@@ -496,7 +498,7 @@ public class FlagValueCalculatorTest {
global.setFlag(flag, State.ALLOW);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.queryValue(null, flag), is(State.ALLOW));
assertEquals(result.queryValue(null, flag), State.ALLOW);
}
@Test
@@ -509,7 +511,7 @@ public class FlagValueCalculatorTest {
global.setFlag(flag, State.DENY);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.queryValue(null, flag), is(State.DENY));
assertEquals(result.queryValue(null, flag), State.DENY);
}
@Test
@@ -521,7 +523,7 @@ public class FlagValueCalculatorTest {
ProtectedRegion global = mock.global();
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.queryValue(null, flag), is((String) null));
assertNull(result.queryValue(null, flag));
}
@Test
@@ -534,7 +536,7 @@ public class FlagValueCalculatorTest {
global.setFlag(flag, "hello");
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.queryValue(null, flag), is("hello"));
assertEquals(result.queryValue(null, flag), "hello");
}
@Test
@@ -549,7 +551,7 @@ public class FlagValueCalculatorTest {
ProtectedRegion region = mock.add(0);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.queryValue(null, flag), is("hello"));
assertEquals(result.queryValue(null, flag), "hello");
}
@Test
@@ -565,7 +567,7 @@ public class FlagValueCalculatorTest {
region.setFlag(flag, "beep");
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.queryValue(null, flag), is("beep"));
assertEquals(result.queryValue(null, flag), "beep");
}
@Test
@@ -591,9 +593,9 @@ public class FlagValueCalculatorTest {
region.getMembers().addPlayer(member);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.queryValue(null, flag), is("ello there"));
assertThat(result.queryValue(nonMember, flag), is("ello there"));
assertThat(result.queryValue(member, flag), is("beep beep"));
assertEquals(result.queryValue(null, flag), "ello there");
assertEquals(result.queryValue(nonMember, flag), "ello there");
assertEquals(result.queryValue(member, flag), "beep beep");
}
@Test
@@ -603,7 +605,7 @@ public class FlagValueCalculatorTest {
LocalPlayer nonMember = mock.createPlayer();
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.queryValue(nonMember, Flags.BUILD), is(State.ALLOW));
assertEquals(result.queryValue(nonMember, Flags.BUILD), State.ALLOW);
}
@Test
@@ -615,7 +617,7 @@ public class FlagValueCalculatorTest {
ProtectedRegion global = mock.global();
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.queryValue(nonMember, Flags.BUILD), is(State.ALLOW));
assertEquals(result.queryValue(nonMember, Flags.BUILD), State.ALLOW);
}
@Test
@@ -628,7 +630,7 @@ public class FlagValueCalculatorTest {
global.setFlag(Flags.BUILD, State.DENY);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.queryValue(nonMember, Flags.BUILD), is(State.DENY));
assertEquals(result.queryValue(nonMember, Flags.BUILD), State.DENY);
}
@Test
@@ -641,7 +643,7 @@ public class FlagValueCalculatorTest {
global.setFlag(Flags.BUILD, State.ALLOW);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.queryValue(nonMember, Flags.BUILD), is(State.ALLOW));
assertEquals(result.queryValue(nonMember, Flags.BUILD), State.ALLOW);
}
@Test
@@ -655,8 +657,8 @@ public class FlagValueCalculatorTest {
global.getMembers().addPlayer(member);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.queryValue(member, Flags.BUILD), is(State.ALLOW));
assertThat(result.queryValue(nonMember, Flags.BUILD), is((State) null));
assertEquals(result.queryValue(member, Flags.BUILD), State.ALLOW);
assertNull(result.queryValue(nonMember, Flags.BUILD));
}
@Test
@@ -671,8 +673,8 @@ public class FlagValueCalculatorTest {
global.setFlag(Flags.BUILD, State.DENY);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.queryValue(member, Flags.BUILD), is(State.DENY));
assertThat(result.queryValue(nonMember, Flags.BUILD), is(State.DENY));
assertEquals(result.queryValue(member, Flags.BUILD), State.DENY);
assertEquals(result.queryValue(nonMember, Flags.BUILD), State.DENY);
}
@Test
@@ -689,8 +691,8 @@ public class FlagValueCalculatorTest {
// Cannot set ALLOW on BUILD
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.queryValue(member, Flags.BUILD), is(State.ALLOW));
assertThat(result.queryValue(nonMember, Flags.BUILD), is((State) null));
assertEquals(result.queryValue(member, Flags.BUILD), State.ALLOW);
assertNull(result.queryValue(nonMember, Flags.BUILD));
}
@Test
@@ -704,8 +706,8 @@ public class FlagValueCalculatorTest {
region.getMembers().addPlayer(member);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.queryValue(nonMember, Flags.BUILD), is((State) null));
assertThat(result.queryValue(member, Flags.BUILD), is(State.ALLOW));
assertNull(result.queryValue(nonMember, Flags.BUILD));
assertEquals(result.queryValue(member, Flags.BUILD), State.ALLOW);
}
@Test
@@ -724,9 +726,9 @@ public class FlagValueCalculatorTest {
region.getMembers().addPlayer(memberBoth);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.queryValue(nonMember, Flags.BUILD), is((State) null));
assertThat(result.queryValue(memberOne, Flags.BUILD), is((State) null));
assertThat(result.queryValue(memberBoth, Flags.BUILD), is(State.ALLOW));
assertNull(result.queryValue(nonMember, Flags.BUILD));
assertNull(result.queryValue(memberOne, Flags.BUILD));
assertEquals(result.queryValue(memberBoth, Flags.BUILD), State.ALLOW);
}
@Test
@@ -746,9 +748,9 @@ public class FlagValueCalculatorTest {
region.getMembers().addPlayer(memberBoth);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.queryValue(nonMember, Flags.BUILD), is((State) null));
assertThat(result.queryValue(memberOne, Flags.BUILD), is(State.ALLOW));
assertThat(result.queryValue(memberBoth, Flags.BUILD), is(State.ALLOW));
assertNull(result.queryValue(nonMember, Flags.BUILD));
assertEquals(result.queryValue(memberOne, Flags.BUILD), State.ALLOW);
assertEquals(result.queryValue(memberBoth, Flags.BUILD), State.ALLOW);
}
@Test
@@ -768,9 +770,9 @@ public class FlagValueCalculatorTest {
region.setParent(parent);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.queryValue(nonMember, Flags.BUILD), is((State) null));
assertThat(result.queryValue(memberOne, Flags.BUILD), is(State.ALLOW));
assertThat(result.queryValue(memberBoth, Flags.BUILD), is(State.ALLOW));
assertNull(result.queryValue(nonMember, Flags.BUILD));
assertEquals(result.queryValue(memberOne, Flags.BUILD), State.ALLOW);
assertEquals(result.queryValue(memberBoth, Flags.BUILD), State.ALLOW);
}
@Test
@@ -790,9 +792,9 @@ public class FlagValueCalculatorTest {
region.setParent(parent);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.queryValue(nonMember, Flags.BUILD), is((State) null));
assertThat(result.queryValue(memberOne, Flags.BUILD), is(State.ALLOW));
assertThat(result.queryValue(memberBoth, Flags.BUILD), is(State.ALLOW));
assertNull(result.queryValue(nonMember, Flags.BUILD));
assertEquals(result.queryValue(memberOne, Flags.BUILD), State.ALLOW);
assertEquals(result.queryValue(memberBoth, Flags.BUILD), State.ALLOW);
}
@Test
@@ -814,9 +816,9 @@ public class FlagValueCalculatorTest {
ProtectedRegion priority = mock.add(10);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.queryValue(nonMember, Flags.BUILD), is((State) null));
assertThat(result.queryValue(memberOne, Flags.BUILD), is((State) null));
assertThat(result.queryValue(memberBoth, Flags.BUILD), is((State) null));
assertNull(result.queryValue(nonMember, Flags.BUILD));
assertNull(result.queryValue(memberOne, Flags.BUILD));
assertNull(result.queryValue(memberBoth, Flags.BUILD));
}
@Test
@@ -839,9 +841,9 @@ public class FlagValueCalculatorTest {
priority.setFlag(Flags.PASSTHROUGH, State.ALLOW);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.queryValue(nonMember, Flags.BUILD), is((State) null));
assertThat(result.queryValue(memberOne, Flags.BUILD), is(State.ALLOW));
assertThat(result.queryValue(memberBoth, Flags.BUILD), is(State.ALLOW));
assertNull(result.queryValue(nonMember, Flags.BUILD));
assertEquals(result.queryValue(memberOne, Flags.BUILD), State.ALLOW);
assertEquals(result.queryValue(memberBoth, Flags.BUILD), State.ALLOW);
}
@Test
@@ -862,9 +864,9 @@ public class FlagValueCalculatorTest {
region.getMembers().addPlayer(memberBoth);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.queryValue(nonMember, Flags.BUILD), is((State) null));
assertThat(result.queryValue(memberOne, Flags.BUILD), is((State) null));
assertThat(result.queryValue(memberBoth, Flags.BUILD), is(State.ALLOW));
assertNull(result.queryValue(nonMember, Flags.BUILD));
assertNull(result.queryValue(memberOne, Flags.BUILD));
assertEquals(result.queryValue(memberBoth, Flags.BUILD), State.ALLOW);
}
@Test
@@ -887,9 +889,9 @@ public class FlagValueCalculatorTest {
region.setFlag(Flags.BUILD, State.ALLOW);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.queryValue(nonMember, Flags.BUILD), is(State.ALLOW));
assertThat(result.queryValue(memberOne, Flags.BUILD), is(State.ALLOW));
assertThat(result.queryValue(memberBoth, Flags.BUILD), is(State.ALLOW));
assertEquals(result.queryValue(nonMember, Flags.BUILD), State.ALLOW);
assertEquals(result.queryValue(memberOne, Flags.BUILD), State.ALLOW);
assertEquals(result.queryValue(memberBoth, Flags.BUILD), State.ALLOW);
}
@Test
@@ -913,9 +915,9 @@ public class FlagValueCalculatorTest {
region.setFlag(Flags.BUILD, State.ALLOW);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.queryValue(nonMember, Flags.BUILD), is(State.DENY));
assertThat(result.queryValue(memberOne, Flags.BUILD), is(State.DENY));
assertThat(result.queryValue(memberBoth, Flags.BUILD), is(State.DENY));
assertEquals(result.queryValue(nonMember, Flags.BUILD), State.DENY);
assertEquals(result.queryValue(memberOne, Flags.BUILD), State.DENY);
assertEquals(result.queryValue(memberBoth, Flags.BUILD), State.DENY);
}
@Test
@@ -939,9 +941,9 @@ public class FlagValueCalculatorTest {
// Disable setting ALLOW for safety reasons
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.queryValue(nonMember, Flags.BUILD), is((State) null));
assertThat(result.queryValue(memberOne, Flags.BUILD), is((State) null));
assertThat(result.queryValue(memberBoth, Flags.BUILD), is(State.ALLOW));
assertNull(result.queryValue(nonMember, Flags.BUILD));
assertNull(result.queryValue(memberOne, Flags.BUILD));
assertEquals(result.queryValue(memberBoth, Flags.BUILD), State.ALLOW);
}
@Test
@@ -964,10 +966,10 @@ public class FlagValueCalculatorTest {
region.getMembers().addPlayer(memberBoth);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.queryValue(globalMember, Flags.BUILD), is((State) null));
assertThat(result.queryValue(nonMember, Flags.BUILD), is((State) null));
assertThat(result.queryValue(memberOne, Flags.BUILD), is((State) null));
assertThat(result.queryValue(memberBoth, Flags.BUILD), is(State.ALLOW));
assertNull(result.queryValue(globalMember, Flags.BUILD));
assertNull(result.queryValue(nonMember, Flags.BUILD));
assertNull(result.queryValue(memberOne, Flags.BUILD));
assertEquals(result.queryValue(memberBoth, Flags.BUILD), State.ALLOW);
}
@Test
@@ -992,10 +994,10 @@ public class FlagValueCalculatorTest {
FlagValueCalculator result = mock.getFlagCalculator();
// Inconsistent due to legacy reasons
assertThat(result.queryValue(globalMember, Flags.BUILD), is((State) null));
assertThat(result.queryValue(nonMember, Flags.BUILD), is((State) null));
assertThat(result.queryValue(memberOne, Flags.BUILD), is((State) null));
assertThat(result.queryValue(memberBoth, Flags.BUILD), is(State.ALLOW));
assertNull(result.queryValue(globalMember, Flags.BUILD));
assertNull(result.queryValue(nonMember, Flags.BUILD));
assertNull(result.queryValue(memberOne, Flags.BUILD));
assertEquals(result.queryValue(memberBoth, Flags.BUILD), State.ALLOW);
}
@Test
@@ -1019,10 +1021,10 @@ public class FlagValueCalculatorTest {
region.getMembers().addPlayer(memberBoth);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.queryValue(globalMember, Flags.BUILD), is((State) null));
assertThat(result.queryValue(nonMember, Flags.BUILD), is((State) null));
assertThat(result.queryValue(memberOne, Flags.BUILD), is((State) null));
assertThat(result.queryValue(memberBoth, Flags.BUILD), is(State.ALLOW));
assertNull(result.queryValue(globalMember, Flags.BUILD));
assertNull(result.queryValue(nonMember, Flags.BUILD));
assertNull(result.queryValue(memberOne, Flags.BUILD));
assertEquals(result.queryValue(memberBoth, Flags.BUILD), State.ALLOW);
}
// ========================================================================
@@ -1046,8 +1048,8 @@ public class FlagValueCalculatorTest {
region.setFlag(stringFlag1, "test2");
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(copyOf(result.queryAllValues(null, stringFlag1)), equalTo(of("test1", "test2")));
assertThat(result.queryAllValues(null, stringFlag2), is(Matchers.<String>empty()));
assertEquals(copyOf(result.queryAllValues(null, stringFlag1)), Set.of("test1", "test2"));
assertTrue(result.queryAllValues(null, stringFlag2).isEmpty());
}
@Test
@@ -1068,8 +1070,8 @@ public class FlagValueCalculatorTest {
region.setFlag(stringFlag1, "test");
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(copyOf(result.queryAllValues(null, stringFlag1)), equalTo(of("test", "test")));
assertThat(result.queryAllValues(null, stringFlag2), is(Matchers.<String>empty()));
assertEquals(copyOf(result.queryAllValues(null, stringFlag1)), Set.of("test"));
assertTrue(result.queryAllValues(null, stringFlag2).isEmpty());
}
@Test
@@ -1090,8 +1092,8 @@ public class FlagValueCalculatorTest {
region.setFlag(stringFlag1, "test2");
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(copyOf(result.queryAllValues(null, stringFlag1)), equalTo(of("test1")));
assertThat(result.queryAllValues(null, stringFlag2), is(Matchers.<String>empty()));
assertEquals(copyOf(result.queryAllValues(null, stringFlag1)), Set.of("test1"));
assertTrue(result.queryAllValues(null, stringFlag2).isEmpty());
}
@Test
@@ -1115,8 +1117,8 @@ public class FlagValueCalculatorTest {
region.setFlag(stringFlag1, "test2");
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(copyOf(result.queryAllValues(null, stringFlag1)), equalTo(of("test1", "test3")));
assertThat(result.queryAllValues(null, stringFlag2), is(Matchers.<String>empty()));
assertEquals(copyOf(result.queryAllValues(null, stringFlag1)), Set.of("test1", "test3"));
assertTrue(result.queryAllValues(null, stringFlag2).isEmpty());
}
@Test
@@ -1141,8 +1143,8 @@ public class FlagValueCalculatorTest {
region.setFlag(stringFlag1, "test2");
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(copyOf(result.queryAllValues(null, stringFlag1)), equalTo(of("test1")));
assertThat(result.queryAllValues(null, stringFlag2), is(Matchers.<String>empty()));
assertEquals(copyOf(result.queryAllValues(null, stringFlag1)), Set.of("test1"));
assertTrue(result.queryAllValues(null, stringFlag2).isEmpty());
}
@Test
@@ -1167,8 +1169,8 @@ public class FlagValueCalculatorTest {
region.setFlag(stringFlag1, "test2");
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(copyOf(result.queryAllValues(null, stringFlag1)), equalTo(of("test3")));
assertThat(result.queryAllValues(null, stringFlag2), is(Matchers.<String>empty()));
assertEquals(copyOf(result.queryAllValues(null, stringFlag1)), Set.of("test3"));
assertTrue(result.queryAllValues(null, stringFlag2).isEmpty());
}
@Test
@@ -1193,8 +1195,8 @@ public class FlagValueCalculatorTest {
region.setFlag(stringFlag1, "test2");
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(copyOf(result.queryAllValues(null, stringFlag1)), equalTo(of("test1")));
assertThat(result.queryAllValues(null, stringFlag2), is(Matchers.<String>empty()));
assertEquals(copyOf(result.queryAllValues(null, stringFlag1)), Set.of("test1"));
assertTrue(result.queryAllValues(null, stringFlag2).isEmpty());
}
@Test
@@ -1219,8 +1221,8 @@ public class FlagValueCalculatorTest {
region.setFlag(stringFlag1, "test2");
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(copyOf(result.queryAllValues(null, stringFlag1)), equalTo(of("test2")));
assertThat(result.queryAllValues(null, stringFlag2), is(Matchers.<String>empty()));
assertEquals(copyOf(result.queryAllValues(null, stringFlag1)), Set.of("test2"));
assertTrue(result.queryAllValues(null, stringFlag2).isEmpty());
}
@Test
@@ -1248,8 +1250,8 @@ public class FlagValueCalculatorTest {
region.setParent(parent2);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(copyOf(result.queryAllValues(null, stringFlag1)), equalTo(of("test2", "test3")));
assertThat(result.queryAllValues(null, stringFlag2), is(Matchers.<String>empty()));
assertEquals(copyOf(result.queryAllValues(null, stringFlag1)), Set.of("test2", "test3"));
assertTrue(result.queryAllValues(null, stringFlag2).isEmpty());
}
@Test
@@ -1277,8 +1279,8 @@ public class FlagValueCalculatorTest {
region = mock.add(30);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(copyOf(result.queryAllValues(null, stringFlag1)), equalTo(of("test2")));
assertThat(result.queryAllValues(null, stringFlag2), is(Matchers.<String>empty()));
assertEquals(copyOf(result.queryAllValues(null, stringFlag1)), Set.of("test2"));
assertTrue(result.queryAllValues(null, stringFlag2).isEmpty());
}
@Test
@@ -1306,8 +1308,8 @@ public class FlagValueCalculatorTest {
region = mock.add(30);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(copyOf(result.queryAllValues(null, stringFlag1)), equalTo(of("test1")));
assertThat(result.queryAllValues(null, stringFlag2), is(Matchers.<String>empty()));
assertEquals(copyOf(result.queryAllValues(null, stringFlag1)), Set.of("test1"));
assertTrue(result.queryAllValues(null, stringFlag2).isEmpty());
}
// ========================================================================
@@ -1320,7 +1322,7 @@ public class FlagValueCalculatorTest {
ProtectedRegion region = mock.add(30);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getPriority(region), is(30));
assertEquals(result.getPriority(region), 30);
}
@Test
@@ -1330,7 +1332,7 @@ public class FlagValueCalculatorTest {
ProtectedRegion region = mock.global();
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getPriority(region), is(Integer.MIN_VALUE));
assertEquals(result.getPriority(region), Integer.MIN_VALUE);
}
// ========================================================================
@@ -1352,8 +1354,8 @@ public class FlagValueCalculatorTest {
region.setFlag(stringFlag1.getRegionGroupFlag(), RegionGroup.ALL);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getEffectiveFlag(region, stringFlag1, null), equalTo("test1"));
assertThat(result.getEffectiveFlag(region, stringFlag2, null), equalTo(null));
assertEquals(result.getEffectiveFlag(region, stringFlag1, null), "test1");
assertNull(result.getEffectiveFlag(region, stringFlag2, null));
}
@Test
@@ -1374,8 +1376,8 @@ public class FlagValueCalculatorTest {
LocalPlayer player = mock.createPlayer();
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getEffectiveFlag(region, stringFlag1, player), equalTo("test1"));
assertThat(result.getEffectiveFlag(region, stringFlag2, null), equalTo(null));
assertEquals(result.getEffectiveFlag(region, stringFlag1, player), "test1");
assertNull(result.getEffectiveFlag(region, stringFlag2, null));
}
@Test
@@ -1394,8 +1396,8 @@ public class FlagValueCalculatorTest {
region.setFlag(stringFlag1.getRegionGroupFlag(), RegionGroup.ALL);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getEffectiveFlag(region, stringFlag1, null), equalTo("test1"));
assertThat(result.getEffectiveFlag(region, stringFlag2, null), equalTo(null));
assertEquals(result.getEffectiveFlag(region, stringFlag1, null), "test1");
assertNull(result.getEffectiveFlag(region, stringFlag2, null));
}
@Test
@@ -1416,8 +1418,8 @@ public class FlagValueCalculatorTest {
LocalPlayer player = mock.createPlayer();
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getEffectiveFlag(region, stringFlag1, player), equalTo("test1"));
assertThat(result.getEffectiveFlag(region, stringFlag2, null), equalTo(null));
assertEquals(result.getEffectiveFlag(region, stringFlag1, player), "test1");
assertNull(result.getEffectiveFlag(region, stringFlag2, null));
}
@Test
@@ -1436,8 +1438,8 @@ public class FlagValueCalculatorTest {
region.setFlag(stringFlag1.getRegionGroupFlag(), RegionGroup.NON_MEMBERS);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getEffectiveFlag(region, stringFlag1, null), equalTo("test1"));
assertThat(result.getEffectiveFlag(region, stringFlag2, null), equalTo(null));
assertEquals(result.getEffectiveFlag(region, stringFlag1, null), "test1");
assertNull(result.getEffectiveFlag(region, stringFlag2, null));
}
@Test
@@ -1458,8 +1460,8 @@ public class FlagValueCalculatorTest {
LocalPlayer player = mock.createPlayer();
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getEffectiveFlag(region, stringFlag1, player), equalTo("test1"));
assertThat(result.getEffectiveFlag(region, stringFlag2, null), equalTo(null));
assertEquals(result.getEffectiveFlag(region, stringFlag1, player), "test1");
assertNull(result.getEffectiveFlag(region, stringFlag2, null));
}
@Test
@@ -1480,8 +1482,8 @@ public class FlagValueCalculatorTest {
LocalPlayer player = mock.createPlayer();
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getEffectiveFlag(region, stringFlag1, player), equalTo(null));
assertThat(result.getEffectiveFlag(region, stringFlag2, null), equalTo(null));
assertNull(result.getEffectiveFlag(region, stringFlag1, player));
assertNull(result.getEffectiveFlag(region, stringFlag2, null));
}
@Test
@@ -1500,8 +1502,8 @@ public class FlagValueCalculatorTest {
region.setFlag(stringFlag1.getRegionGroupFlag(), RegionGroup.MEMBERS);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getEffectiveFlag(region, stringFlag1, null), equalTo(null));
assertThat(result.getEffectiveFlag(region, stringFlag2, null), equalTo(null));
assertNull(result.getEffectiveFlag(region, stringFlag1, null));
assertNull(result.getEffectiveFlag(region, stringFlag2, null));
}
@Test
@@ -1523,8 +1525,8 @@ public class FlagValueCalculatorTest {
region.getMembers().addPlayer(player);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getEffectiveFlag(region, stringFlag1, player), equalTo("test1"));
assertThat(result.getEffectiveFlag(region, stringFlag2, null), equalTo(null));
assertEquals(result.getEffectiveFlag(region, stringFlag1, player), "test1");
assertNull(result.getEffectiveFlag(region, stringFlag2, null));
}
@Test
@@ -1546,8 +1548,8 @@ public class FlagValueCalculatorTest {
region.getOwners().addPlayer(player);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getEffectiveFlag(region, stringFlag1, player), equalTo("test1"));
assertThat(result.getEffectiveFlag(region, stringFlag2, null), equalTo(null));
assertEquals(result.getEffectiveFlag(region, stringFlag1, player), "test1");
assertNull(result.getEffectiveFlag(region, stringFlag2, null));
}
@Test
@@ -1569,8 +1571,8 @@ public class FlagValueCalculatorTest {
region.getOwners().addPlayer(player);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getEffectiveFlag(region, stringFlag1, player), equalTo("test1"));
assertThat(result.getEffectiveFlag(region, stringFlag2, null), equalTo(null));
assertEquals(result.getEffectiveFlag(region, stringFlag1, player), "test1");
assertNull(result.getEffectiveFlag(region, stringFlag2, null));
}
@Test
@@ -1592,8 +1594,8 @@ public class FlagValueCalculatorTest {
region.getMembers().addPlayer(player);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getEffectiveFlag(region, stringFlag1, player), equalTo(null));
assertThat(result.getEffectiveFlag(region, stringFlag2, null), equalTo(null));
assertNull(result.getEffectiveFlag(region, stringFlag1, player));
assertNull(result.getEffectiveFlag(region, stringFlag2, null));
}
@Test
@@ -1615,8 +1617,8 @@ public class FlagValueCalculatorTest {
region.getOwners().addPlayer(player);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getEffectiveFlag(region, stringFlag1, player), equalTo(null));
assertThat(result.getEffectiveFlag(region, stringFlag2, null), equalTo(null));
assertNull(result.getEffectiveFlag(region, stringFlag1, player));
assertNull(result.getEffectiveFlag(region, stringFlag2, null));
}
@Test
@@ -1638,8 +1640,8 @@ public class FlagValueCalculatorTest {
region.getOwners().addPlayer(player);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getEffectiveFlag(region, stringFlag1, player), equalTo(null));
assertThat(result.getEffectiveFlag(region, stringFlag2, null), equalTo(null));
assertNull(result.getEffectiveFlag(region, stringFlag1, player));
assertNull(result.getEffectiveFlag(region, stringFlag2, null));
}
@Test
@@ -1661,8 +1663,8 @@ public class FlagValueCalculatorTest {
region.getMembers().addPlayer(player);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getEffectiveFlag(region, stringFlag1, player), equalTo("test1"));
assertThat(result.getEffectiveFlag(region, stringFlag2, null), equalTo(null));
assertEquals(result.getEffectiveFlag(region, stringFlag1, player), "test1");
assertNull(result.getEffectiveFlag(region, stringFlag2, null));
}
@Test
@@ -1683,8 +1685,8 @@ public class FlagValueCalculatorTest {
LocalPlayer player = mock.createPlayer();
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getEffectiveFlag(region, stringFlag1, player), equalTo("test1"));
assertThat(result.getEffectiveFlag(region, stringFlag2, null), equalTo(null));
assertEquals(result.getEffectiveFlag(region, stringFlag1, player), "test1");
assertNull(result.getEffectiveFlag(region, stringFlag2, null));
}
@Test
@@ -1709,8 +1711,8 @@ public class FlagValueCalculatorTest {
region.setParent(parent2);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getEffectiveFlag(region, stringFlag1, null), equalTo("test1"));
assertThat(result.getEffectiveFlag(region, stringFlag2, null), equalTo(null));
assertEquals(result.getEffectiveFlag(region, stringFlag1, null), "test1");
assertNull(result.getEffectiveFlag(region, stringFlag2, null));
}
@Test
@@ -1737,8 +1739,8 @@ public class FlagValueCalculatorTest {
region.setParent(parent2);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getEffectiveFlag(region, stringFlag1, null), equalTo("test2"));
assertThat(result.getEffectiveFlag(region, stringFlag2, null), equalTo(null));
assertEquals(result.getEffectiveFlag(region, stringFlag1, null), "test2");
assertNull(result.getEffectiveFlag(region, stringFlag2, null));
}
@Test
@@ -1765,8 +1767,8 @@ public class FlagValueCalculatorTest {
parent1.setFlag(stringFlag1.getRegionGroupFlag(), RegionGroup.ALL);
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getEffectiveFlag(region, stringFlag1, null), equalTo("test3"));
assertThat(result.getEffectiveFlag(region, stringFlag2, null), equalTo(null));
assertEquals(result.getEffectiveFlag(region, stringFlag1, null), "test3");
assertNull(result.getEffectiveFlag(region, stringFlag2, null));
}
@Test
@@ -1798,10 +1800,10 @@ public class FlagValueCalculatorTest {
LocalPlayer player2 = mock.createPlayer();
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getEffectiveFlag(region, stringFlag1, player1), equalTo("members"));
assertThat(result.getEffectiveFlag(region, stringFlag1, player2), equalTo("everyone"));
assertThat(result.getEffectiveFlag(region, stringFlag1, null), equalTo("everyone"));
assertThat(result.getEffectiveFlag(region, stringFlag2, null), equalTo(null));
assertEquals(result.getEffectiveFlag(region, stringFlag1, player1), "members");
assertEquals(result.getEffectiveFlag(region, stringFlag1, player2), "everyone");
assertEquals(result.getEffectiveFlag(region, stringFlag1, null), "everyone");
assertNull(result.getEffectiveFlag(region, stringFlag2, null));
}
@Test
@@ -1833,10 +1835,10 @@ public class FlagValueCalculatorTest {
LocalPlayer player2 = mock.createPlayer();
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getEffectiveFlag(region, stringFlag1, player1), equalTo("members"));
assertThat(result.getEffectiveFlag(region, stringFlag1, player2), equalTo("everyone"));
assertThat(result.getEffectiveFlag(region, stringFlag1, null), equalTo("everyone"));
assertThat(result.getEffectiveFlag(region, stringFlag2, null), equalTo(null));
assertEquals(result.getEffectiveFlag(region, stringFlag1, player1), "members");
assertEquals(result.getEffectiveFlag(region, stringFlag1, player2), "everyone");
assertEquals(result.getEffectiveFlag(region, stringFlag1, null), "everyone");
assertNull(result.getEffectiveFlag(region, stringFlag2, null));
}
@Test
@@ -1864,10 +1866,10 @@ public class FlagValueCalculatorTest {
LocalPlayer player2 = mock.createPlayer();
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getEffectiveFlag(region, stringFlag1, player1), equalTo("members"));
assertThat(result.getEffectiveFlag(region, stringFlag1, player2), equalTo("everyone"));
assertThat(result.getEffectiveFlag(region, stringFlag1, null), equalTo("everyone"));
assertThat(result.getEffectiveFlag(region, stringFlag2, null), equalTo(null));
assertEquals(result.getEffectiveFlag(region, stringFlag1, player1), "members");
assertEquals(result.getEffectiveFlag(region, stringFlag1, player2), "everyone");
assertEquals(result.getEffectiveFlag(region, stringFlag1, null), "everyone");
assertNull(result.getEffectiveFlag(region, stringFlag2, null));
}
@Test
@@ -1895,10 +1897,10 @@ public class FlagValueCalculatorTest {
LocalPlayer player2 = mock.createPlayer();
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getEffectiveFlag(region, stringFlag1, player1), equalTo("members"));
assertThat(result.getEffectiveFlag(region, stringFlag1, player2), equalTo("everyone"));
assertThat(result.getEffectiveFlag(region, stringFlag1, null), equalTo("everyone"));
assertThat(result.getEffectiveFlag(region, stringFlag2, null), equalTo(null));
assertEquals(result.getEffectiveFlag(region, stringFlag1, player1), "members");
assertEquals(result.getEffectiveFlag(region, stringFlag1, player2), "everyone");
assertEquals(result.getEffectiveFlag(region, stringFlag1, null), "everyone");
assertNull(result.getEffectiveFlag(region, stringFlag2, null));
}
@Test
@@ -1926,10 +1928,10 @@ public class FlagValueCalculatorTest {
LocalPlayer player2 = mock.createPlayer();
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getEffectiveFlag(region, stringFlag1, player1), equalTo("members"));
assertThat(result.getEffectiveFlag(region, stringFlag1, player2), equalTo("everyone"));
assertThat(result.getEffectiveFlag(region, stringFlag1, null), equalTo("everyone"));
assertThat(result.getEffectiveFlag(region, stringFlag2, null), equalTo(null));
assertEquals(result.getEffectiveFlag(region, stringFlag1, player1), "members");
assertEquals(result.getEffectiveFlag(region, stringFlag1, player2), "everyone");
assertEquals(result.getEffectiveFlag(region, stringFlag1, null), "everyone");
assertNull(result.getEffectiveFlag(region, stringFlag2, null));
}
@Test
@@ -1939,7 +1941,7 @@ public class FlagValueCalculatorTest {
ProtectedRegion global = mock.global();
FlagValueCalculator result = mock.getFlagCalculator();
assertThat(result.getEffectiveFlag(global, Flags.BUILD, null), equalTo(null));
assertNull(result.getEffectiveFlag(global, Flags.BUILD, null));
}
@Test
@@ -1951,7 +1953,7 @@ public class FlagValueCalculatorTest {
FlagValueCalculator result = mock.getFlagCalculator();
// Cannot let users override BUILD on GLOBAL
assertThat(result.getEffectiveFlag(global, Flags.BUILD, null), equalTo(State.DENY));
assertEquals(result.getEffectiveFlag(global, Flags.BUILD, null), State.DENY);
}
@Test
@@ -1963,6 +1965,6 @@ public class FlagValueCalculatorTest {
FlagValueCalculator result = mock.getFlagCalculator();
// Cannot let users override BUILD on GLOBAL
assertThat(result.getEffectiveFlag(global, Flags.BUILD, null), equalTo(null));
assertNull(result.getEffectiveFlag(global, Flags.BUILD, null));
}
}
@@ -29,14 +29,14 @@ import com.sk89q.worldguard.protection.managers.storage.MemoryRegionDatabase;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion.CircularInheritanceException;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class HashMapIndexRemovalTest {
private static final String ORPHAN_ID = "orphan";
@@ -52,7 +52,7 @@ public class HashMapIndexRemovalTest {
return new RegionManager(new MemoryRegionDatabase(), new HashMapIndex.Factory(), getFlagRegistry());
}
@Before
@BeforeEach
public void setUp() {
manager = createRegionManager();
Loaded 100 of 107 files, more files were not shown because too many files have changed in this diff. Show more