Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions src/main/java/world/bentobox/border/Border.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,14 @@ public class Border extends Addon {
private final Config<Settings> config = new Config<>(this, Settings.class);

private final @NonNull List<GameModeAddon> gameModes = new ArrayList<>();
private final Map<GameModeAddon, Settings> gameModeSettings = new HashMap<>();
/**
* How game modes are asked for the settings they want
*/
java.util.function.BiFunction<GameModeAddon, String, Map<String, Object>> requester = GameModeRequests::ask;
private static final Set<String> REQUESTABLE = Set.of("bounce-back", "return-teleport",
"return-teleport-safety-block", "use-barrier-blocks", "show-max-border", "show-particles",
"barrier-offset");

private final Set<BorderType> availableBorderTypes = EnumSet.of(BorderType.VANILLA, BorderType.BARRIER);

Expand All @@ -51,12 +59,14 @@ public void onLoad() {
@Override
public void onEnable() {
gameModes.clear();
gameModeSettings.clear();
// Register commands
getPlugin().getAddonsManager().getGameModeAddons().forEach(gameModeAddon -> {

if (!this.settings.getDisabledGameModes().contains(gameModeAddon.getDescription().getName())) {

gameModes.add(gameModeAddon);
loadRequests(gameModeAddon);

log("Border hooking into " + gameModeAddon.getDescription().getName());
gameModeAddon.getPlayerCommand().ifPresent(c -> new IslandBorderCommand(this, c, "border"));
Expand Down Expand Up @@ -116,6 +126,51 @@ public Settings getSettings() {
return this.settings;
}

/**
* Gets the settings that apply in a world. These are the settings from the config unless
* the world's game mode asked for different ones and the admin allows that. The border
* type, color and whether it is shown are each player's choice and are not affected.
* @param world a world, may be null
* @return settings for the world
*/
public Settings getSettings(World world) {
if (world != null && !gameModeSettings.isEmpty()) {
for (Map.Entry<GameModeAddon, Settings> en : gameModeSettings.entrySet()) {
if (en.getKey().inWorld(world)) {
return en.getValue();
}
}
}
return settings;
}

/**
* Settings a game mode may ask for: how the border behaves, not how it looks to a player
* or which game modes it is used in.
*/
static boolean isRequestable(String path) {
return REQUESTABLE.contains(path);
}

/**
* Asks a game mode which settings it needs and works out the settings for its worlds.
*/
void loadRequests(GameModeAddon gm) {
String name = gm.getDescription().getName();
if (!settings.isAllowRequests() || settings.getIgnoreRequests().stream().anyMatch(name::equalsIgnoreCase)) {
return;
}
Map<String, Object> requests = requester.apply(gm, getDescription().getName());
if (requests.isEmpty()) {
return;
}
GameModeRequests.Result<Settings> result = GameModeRequests.apply(settings, requests, Border::isRequestable);
result.refused().forEach(r -> logWarning(name + " asked for something that cannot be done: " + r));
log(name + " asked for these settings in its worlds: "
+ (result.applied().isEmpty() ? "none that differ from the config" : String.join(", ", result.applied())));
gameModeSettings.put(gm, result.settings());
}

/**
* @param world to check
* @return true if world is being handled by Border
Expand Down
186 changes: 186 additions & 0 deletions src/main/java/world/bentobox/border/GameModeRequests.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
package world.bentobox.border;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.function.Predicate;

import org.eclipse.jdt.annotation.NonNull;

import world.bentobox.bentobox.api.addons.GameModeAddon;
import world.bentobox.bentobox.api.configuration.ConfigEntry;

/**
* Lets game modes ask for the settings they need in their own worlds. A game mode asks by
* having a {@code getGameModeRequests(String addonName)} method, which BentoBox 3.25.0 adds
* to GameModeAddon. It returns config paths of this addon and the values wanted. The method is
* looked up by name so that this addon still builds and runs with older BentoBox versions,
* where no game mode can ask for anything.
* <p>
* Requests are applied to a copy of the settings, so the admin's config is never changed.
*
* @author tastybento
*/
public final class GameModeRequests {

private GameModeRequests() {
}

/**
* Asks a game mode which settings it wants.
* @param gm the game mode
* @param addonName name of the addon whose settings are being asked about
* @return config path to requested value, empty if the game mode asks for nothing
*/
@NonNull
public static Map<String, Object> ask(@NonNull GameModeAddon gm, @NonNull String addonName) {
try {
Method method = gm.getClass().getMethod("getRequestedSettings", String.class);
if (method.invoke(gm, addonName) instanceof Map<?, ?> map) {
Map<String, Object> requests = new java.util.LinkedHashMap<>();
map.forEach((k, v) -> requests.put(String.valueOf(k), v));
return requests;
}
} catch (ReflectiveOperationException | RuntimeException e) {
// This game mode, or this BentoBox, does not have requests
}
return Map.of();
}

/**
* What came of a set of requests.
* @param <T> the settings class
* @param settings a copy of the settings with the accepted requests applied
* @param applied the accepted requests, as "path: value", for telling the admin
* @param refused the requests that could not be applied, with the reason
*/
public record Result<T>(@NonNull T settings, @NonNull List<String> applied, @NonNull List<String> refused) {
}

/**
* Copies settings and applies requests to the copy. A request is refused if no setting has
* that path, the path is not one that may be requested, or the value is of the wrong type.
* A request that matches the current value is accepted but not listed as applied.
*
* @param <T> the settings class, which must have a constructor with no arguments
* @param settings the settings as the admin configured them. They are not changed.
* @param requests config path to requested value
* @param requestable says which config paths may be requested
* @return the copy and what was applied and refused
*/
@NonNull
public static <T> Result<T> apply(@NonNull T settings, @NonNull Map<String, Object> requests,
@NonNull Predicate<String> requestable) {
List<String> applied = new ArrayList<>();
List<String> refused = new ArrayList<>();
T copy;
try {
copy = copy(settings);
} catch (ReflectiveOperationException | RuntimeException e) {
requests.keySet().forEach(k -> refused.add(k + " (settings cannot be copied: " + e + ")"));
return new Result<>(settings, applied, refused);
}
requests.forEach((path, value) -> {
Field field = requestable.test(path) ? find(copy.getClass(), path) : null;
if (field == null) {
refused.add(path + " (not a setting that can be requested)");
return;
}
try {
Object converted = convert(field.getType(), value);
if (converted == null) {
refused.add(path + " (" + value + " is not a valid value)");
} else if (!converted.equals(field.get(copy))) {
field.set(copy, converted); // NOSONAR the field is made accessible on purpose
applied.add(path + ": " + value);
}
} catch (ReflectiveOperationException | RuntimeException e) {
refused.add(path + " (" + e + ")");
}
});
return new Result<>(copy, applied, refused);
}

@SuppressWarnings("unchecked")
private static <T> T copy(T settings) throws ReflectiveOperationException {
var constructor = settings.getClass().getDeclaredConstructor();
constructor.setAccessible(true); // NOSONAR
T copy = (T) constructor.newInstance();
for (Class<?> c = settings.getClass(); c != null && c != Object.class; c = c.getSuperclass()) {
for (Field f : c.getDeclaredFields()) {
if (!Modifier.isStatic(f.getModifiers()) && !Modifier.isFinal(f.getModifiers())) {
f.setAccessible(true); // NOSONAR
f.set(copy, f.get(settings)); // NOSONAR
}
}
}
return copy;
}

private static Field find(Class<?> clazz, String path) {
for (Class<?> c = clazz; c != null && c != Object.class; c = c.getSuperclass()) {
for (Field f : c.getDeclaredFields()) {
ConfigEntry entry = f.getAnnotation(ConfigEntry.class);
if (entry != null && entry.path().equals(path) && !Modifier.isStatic(f.getModifiers())
&& !Modifier.isFinal(f.getModifiers())) {
f.setAccessible(true); // NOSONAR
return f;
}
}
}
return null;
}

/**
* Turns a requested value into the type of the setting. Only simple settings can be
* requested: booleans, numbers, strings and enums.
* @return the value, or null if it does not fit
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
private static Object convert(Class<?> type, Object value) {
if (value == null) {
return null;
}
if (type == boolean.class || type == Boolean.class) {
return value instanceof Boolean ? value : null;
}
if (value instanceof Number n) {
return convertNumber(type, n);
}
if (type == String.class) {
return value.toString();
}
if (type.isEnum()) {
return type.isInstance(value) ? value : convertEnum((Class<Enum>) type, value.toString());
}
return null;
}

private static Object convertNumber(Class<?> type, Number n) {
if (type == int.class || type == Integer.class) {
return n.intValue();
} else if (type == long.class || type == Long.class) {
return n.longValue();
} else if (type == double.class || type == Double.class) {
return n.doubleValue();
} else if (type == float.class || type == Float.class) {
return n.floatValue();
} else if (type == String.class) {
return n.toString();
}
return null;
}

@SuppressWarnings({ "unchecked", "rawtypes" })
private static Object convertEnum(Class<Enum> type, String name) {
try {
return Enum.valueOf(type, name.toUpperCase(Locale.ENGLISH));
} catch (IllegalArgumentException e) {
return null;
}
}
}
41 changes: 41 additions & 0 deletions src/main/java/world/bentobox/border/Settings.java
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,47 @@ public enum BorderColor {
@ConfigEntry(path = "barrier-offset")
private int barrierOffset = 0;

@ConfigComment("")
@ConfigComment("Game modes can ask for the settings they need in their own worlds, so that you do not")
@ConfigComment("have to set them up by hand. Only how the border behaves can be asked for: bounce-back,")
@ConfigComment("return-teleport, return-teleport-safety-block, use-barrier-blocks, show-max-border,")
@ConfigComment("show-particles and barrier-offset. Nothing in this file is changed and other game modes")
@ConfigComment("keep the settings above. What was asked for is listed in the console at startup.")
@ConfigComment("Set to false to ignore all requests.")
@ConfigEntry(path = "game-mode-requests.allow")
private boolean allowRequests = true;
@ConfigComment("Game modes whose requests are ignored, e.g. Boxed. They use the settings above.")
@ConfigEntry(path = "game-mode-requests.ignore")
private Set<String> ignoreRequests = new HashSet<>();

/**
* @return true if game modes may ask for settings in their own worlds
*/
public boolean isAllowRequests() {
return allowRequests;
}

/**
* @param allowRequests true if game modes may ask for settings in their own worlds
*/
public void setAllowRequests(boolean allowRequests) {
this.allowRequests = allowRequests;
}

/**
* @return names of the game modes whose requests are ignored
*/
public Set<String> getIgnoreRequests() {
return ignoreRequests;
}

/**
* @param ignoreRequests names of the game modes whose requests are ignored
*/
public void setIgnoreRequests(Set<String> ignoreRequests) {
this.ignoreRequests = ignoreRequests;
}

/**
* @param disabledGameModes new disabledGameModes value.
*/
Expand Down
28 changes: 23 additions & 5 deletions src/main/java/world/bentobox/border/listeners/PlayerListener.java
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,12 @@
*/
public class PlayerListener implements Listener {

/**
* Permission, after the game mode's prefix, that lets a player walk outside the border
*/
public static final String BYPASS_PERM = "border.bypass";


private static final Vector XZ = new Vector(1, 0, 1);
/** How close to a death spot, in blocks, an item must spawn to count as a death drop. */
private static final double DEATH_DROP_RADIUS_SQUARED = 5 * 5D;
Expand Down Expand Up @@ -214,6 +220,17 @@ public void onPlayerRespawn(PlayerRespawnEvent e) {
}
}

/**
* Checks if a player is free to walk outside the border. Operators always are, so that
* admins can go anywhere, and so is anyone with the game mode's border bypass permission.
* @param player player
* @return true if the player must not be moved back inside the border
*/
boolean canBypass(Player player) {
return player.isOp() || addon.getPlugin().getIWM().getAddon(player.getWorld())
.map(gm -> player.hasPermission(gm.getPermissionPrefix() + BYPASS_PERM)).orElse(false);
}

/**
* Check if the border is on or off for a player.
*
Expand Down Expand Up @@ -303,11 +320,11 @@ public void onPlayerLeaveIsland(PlayerMoveEvent e) {
return;
}
Player p = e.getPlayer();
if (!isOn(p)) {
if (!isOn(p) || canBypass(p)) {
return;
}
Location from = e.getFrom();
if (!addon.getSettings().isReturnTeleport() || !outsideCheck(e.getPlayer(), from, e.getTo())) {
if (!addon.getSettings(e.getPlayer().getWorld()).isReturnTeleport() || !outsideCheck(e.getPlayer(), from, e.getTo())) {
return;
}
// Move the player back inside the border
Expand Down Expand Up @@ -405,7 +422,8 @@ private boolean outsideCheck(Player player, Location from, Location to) {
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onEntityMount(EntityMountEvent event) {
Entity entity = event.getEntity();
if (!(entity instanceof Player player) || !isOn(player) || !addon.getSettings().isReturnTeleport()) {
if (!(entity instanceof Player player) || !isOn(player) || canBypass(player)
|| !addon.getSettings(player.getWorld()).isReturnTeleport()) {
return;
}

Expand Down Expand Up @@ -501,7 +519,7 @@ public void onProtectionRangeChange(IslandProtectionRangeChangeEvent e) {
*/
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onItemDrop(PlayerDropItemEvent event) {
if (addon.getSettings().isBounceBack()
if (addon.getSettings(event.getPlayer().getWorld()).isBounceBack()
&& addon.inGameWorld(event.getPlayer().getWorld())
&& isOn(event.getPlayer())
) {
Expand All @@ -524,7 +542,7 @@ && isOn(event.getPlayer())
*/
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerDeath(PlayerDeathEvent event) {
if (!addon.getSettings().isBounceBack()
if (!addon.getSettings(event.getPlayer().getWorld()).isBounceBack()
|| event.getDrops().isEmpty()
|| !addon.inGameWorld(event.getPlayer().getWorld())
|| !isOn(event.getPlayer())) {
Expand Down
Loading
Loading