refactor: perform various code cleanup

This commit is contained in:
dordsor21 2023-01-17 14:02:11 +00:00
parent 746028afbc
commit 8a7c659992
No known key found for this signature in database
GPG Key ID: 1E53E88969FFCF0B
109 changed files with 361 additions and 1282 deletions

View File

@ -49,8 +49,8 @@ import com.plotsquared.bukkit.player.BukkitPlayerManager;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.bukkit.util.BukkitWorld;
import com.plotsquared.bukkit.util.SetGenCB;
import com.plotsquared.bukkit.util.UpdateUtility;
import com.plotsquared.bukkit.util.TranslationUpdateManager;
import com.plotsquared.bukkit.util.UpdateUtility;
import com.plotsquared.bukkit.util.task.BukkitTaskManager;
import com.plotsquared.bukkit.util.task.PaperTimeConverter;
import com.plotsquared.bukkit.util.task.SpigotTimeConverter;
@ -293,7 +293,8 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl
this.injector.injectMembers(this);
try {
this.injector.getInstance(TranslationUpdateManager.class).upgradeTranslationFile();
this.injector.getInstance(TranslationUpdateManager.class);
TranslationUpdateManager.upgradeTranslationFile();
} catch (IOException e) {
throw new RuntimeException(e);
}
@ -363,7 +364,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl
getServer().getPluginManager().registerEvents(injector().getInstance(ServerListener.class), this);
getServer().getPluginManager().registerEvents(injector().getInstance(EntitySpawnListener.class), this);
if (PaperLib.isPaper() && Settings.Paper_Components.PAPER_LISTENERS) {
getServer().getPluginManager().registerEvents(injector().getInstance(PaperListener.class), this);
getServer().getPluginManager().registerEvents(injector().getInstance(PaperListener.class), this);
} else {
getServer().getPluginManager().registerEvents(injector().getInstance(SpigotListener.class), this);
}
@ -1008,8 +1009,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl
}
@Override
public @Nullable
final ChunkGenerator getDefaultWorldGenerator(
public @Nullable ChunkGenerator getDefaultWorldGenerator(
final @NonNull String worldName,
final @Nullable String id
) {
@ -1176,9 +1176,17 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl
public @NonNull String worldEditImplementations() {
StringBuilder msg = new StringBuilder();
if (Bukkit.getPluginManager().getPlugin("FastAsyncWorldEdit") != null) {
msg.append("FastAsyncWorldEdit: ").append(Bukkit.getPluginManager().getPlugin("FastAsyncWorldEdit").getDescription().getVersion());
msg.append("FastAsyncWorldEdit: ").append(Bukkit
.getPluginManager()
.getPlugin("FastAsyncWorldEdit")
.getDescription()
.getVersion());
} else if (Bukkit.getPluginManager().getPlugin("AsyncWorldEdit") != null) {
msg.append("AsyncWorldEdit: ").append(Bukkit.getPluginManager().getPlugin("AsyncWorldEdit").getDescription().getVersion()).append("\n");
msg.append("AsyncWorldEdit: ").append(Bukkit
.getPluginManager()
.getPlugin("AsyncWorldEdit")
.getDescription()
.getVersion()).append("\n");
msg.append("WorldEdit: ").append(Bukkit.getPluginManager().getPlugin("WorldEdit").getDescription().getVersion());
} else {
msg.append("WorldEdit: ").append(Bukkit.getPluginManager().getPlugin("WorldEdit").getDescription().getVersion());

View File

@ -18,14 +18,9 @@
*/
package com.plotsquared.bukkit.entity;
import org.bukkit.entity.Horse;
class HorseStats {
double jump;
boolean chest;
Horse.Variant variant;
Horse.Color color;
Horse.Style style;
}

View File

@ -185,10 +185,6 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
if (horse instanceof ChestedHorse horse1) {
this.horse.chest = horse1.isCarryingChest();
}
//todo these horse features need fixing
//this.horse.variant = horse.getVariant();
//this.horse.style = horse.getStyle();
//this.horse.color = horse.getColor();
storeTameable(horse);
storeAgeable(horse);
storeLiving(horse);
@ -577,10 +573,6 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
if (horse instanceof ChestedHorse) {
((ChestedHorse) horse).setCarryingChest(this.horse.chest);
}
//todo broken as of 1.13
//horse.setVariant(this.horse.variant);
//horse.setStyle(this.horse.style);
//horse.setColor(this.horse.color);
restoreTameable(horse);
restoreAgeable(horse);
restoreLiving(horse);

View File

@ -54,7 +54,7 @@ import java.util.Set;
public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrapper<ChunkGenerator> {
private static final Logger LOGGER = LogManager.getLogger("PlotSquared/" + BukkitPlotGenerator.class.getSimpleName());
private static final Logger LOGGER = LogManager.getLogger("PlotSquared/" + BukkitPlotGenerator.class.getSimpleName());
@SuppressWarnings("unused")
public final boolean PAPER_ASYNC_SAFE = true;
@ -411,7 +411,8 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
}
PlotArea area = UncheckedWorldLocation.at(name, chunkX << 4, 0, chunkZ << 4).getPlotArea();
if (area == null) {
throw new IllegalStateException(String.format("Cannot generate chunk that does not belong to a plot area. World: %s",
throw new IllegalStateException(String.format(
"Cannot generate chunk that does not belong to a plot area. World: %s",
name
));
}

View File

@ -92,7 +92,11 @@ public class BlockEventListener117 implements Listener {
}
Plot plot = location.getOwnedPlot();
if (plot == null && !PlotFlagUtil.isAreaRoadFlagsAndFlagEquals(area, MiscInteractFlag.class, true) || plot != null && !plot.getFlag(
if (plot == null && !PlotFlagUtil.isAreaRoadFlagsAndFlagEquals(
area,
MiscInteractFlag.class,
true
) || plot != null && !plot.getFlag(
MiscInteractFlag.class)) {
if (plotPlayer != null) {
if (plot != null) {

View File

@ -67,16 +67,6 @@ public class ChunkListener implements Listener {
private RefMethod methodGetHandleChunk;
private RefMethod methodGetHandleWorld;
private RefField mustSave;
/*
private RefMethod methodGetFullChunk;
private RefMethod methodGetBukkitChunk;
private RefMethod methodGetChunkProvider;
private RefMethod methodGetVisibleMap;
private RefField worldServer;
private RefField playerChunkMap;
private RefField updatingChunks;
private RefField visibleChunks;
*/
private Chunk lastChunk;
private boolean ignoreUnload = false;
private boolean isTrueForNotSave = true;
@ -234,7 +224,8 @@ public class ChunkListener implements Listener {
Chunk chunk = event.getChunk();
if (Settings.Chunk_Processor.AUTO_TRIM) {
String world = chunk.getWorld().getName();
if ((!Settings.Enabled_Components.WORLDS || !SinglePlotArea.isSinglePlotWorld(world)) && this.plotAreaManager.hasPlotArea(world)) {
if ((!Settings.Enabled_Components.WORLDS || !SinglePlotArea.isSinglePlotWorld(world)) && this.plotAreaManager.hasPlotArea(
world)) {
if (unloadChunk(world, chunk, true)) {
return;
}

View File

@ -113,15 +113,7 @@ public class EntityEventListener implements Listener {
return;
}
Entity victim = event.getEntity();
/*
if (victim.getType().equals(EntityType.ITEM_FRAME)) {
Plot plot = BukkitUtil.getLocation(victim).getPlot();
if (plot != null && !plot.isAdded(damager.getUniqueId())) {
event.setCancelled(true);
return;
}
}
*/
if (!BukkitEntityUtil.entityDamage(damager, victim, event.getCause())) {
if (event.isCancelled()) {
if (victim instanceof Ageable ageable) {

View File

@ -43,10 +43,10 @@ import com.plotsquared.core.plot.flag.implementations.DoneFlag;
import com.plotsquared.core.plot.flag.implementations.ProjectilesFlag;
import com.plotsquared.core.plot.flag.types.BooleanFlag;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.util.PlotFlagUtil;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.tag.Tag;
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
import com.plotsquared.core.util.PlotFlagUtil;
import org.bukkit.Chunk;
import org.bukkit.block.Block;
import org.bukkit.block.TileState;
@ -457,9 +457,11 @@ public class PaperListener implements Listener {
}
}
private boolean getBooleanFlagValue(@NonNull FlagContainer container,
@NonNull Class<? extends BooleanFlag<?>> flagClass,
boolean defaultValue) {
private boolean getBooleanFlagValue(
@NonNull FlagContainer container,
@NonNull Class<? extends BooleanFlag<?>> flagClass,
boolean defaultValue
) {
BooleanFlag<?> flag = container.getFlag(flagClass);
return flag == null ? defaultValue : flag.getValue();
}

View File

@ -572,7 +572,8 @@ public class PlayerEventListener implements Listener {
if (now == null) {
try (final MetaDataAccess<Boolean> kickAccess =
pp.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_KICK)) {
if (lastPlot != null && !plotListener.plotExit(pp, lastPlot) && this.tmpTeleport && !kickAccess.get().orElse(false)) {
if (lastPlot != null && !plotListener.plotExit(pp, lastPlot) && this.tmpTeleport && !kickAccess.get().orElse(
false)) {
pp.sendMessage(
TranslatableCaption.of("permission.no_permission_event"),
TagResolver.resolver(
@ -665,7 +666,8 @@ public class PlayerEventListener implements Listener {
if (plot == null) {
try (final MetaDataAccess<Boolean> kickAccess =
pp.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_KICK)) {
if (lastPlot != null && !plotListener.plotExit(pp, lastPlot) && this.tmpTeleport && !kickAccess.get().orElse(false)) {
if (lastPlot != null && !plotListener.plotExit(pp, lastPlot) && this.tmpTeleport && !kickAccess.get().orElse(
false)) {
pp.sendMessage(
TranslatableCaption.of("permission.no_permission_event"),
TagResolver.resolver(
@ -842,10 +844,6 @@ public class PlayerEventListener implements Listener {
@SuppressWarnings("deprecation")
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onInventoryClick(InventoryClickEvent event) {
/*if (!event.isLeftClick() || (event.getAction() != InventoryAction.PLACE_ALL) || event
.isShiftClick()) {
return;
}*/
HumanEntity entity = event.getWhoClicked();
if (!(entity instanceof Player) || !this.plotAreaManager
.hasPlotArea(entity.getWorld().getName())) {

View File

@ -30,9 +30,9 @@ import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.PlotHandler;
import com.plotsquared.core.plot.flag.implementations.ProjectilesFlag;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.util.PlotFlagUtil;
import net.kyori.adventure.text.minimessage.tag.Tag;
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
import com.plotsquared.core.util.PlotFlagUtil;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;

View File

@ -89,11 +89,6 @@ public class SingleWorldListener implements Listener {
markChunkAsClean(event.getChunk());
}
// @EventHandler
// public void onPopulate(ChunkPopulateEvent event) {
// handle(event);
// }
@EventHandler(priority = EventPriority.LOWEST)
public void onChunkLoad(ChunkLoadEvent event) {
handle(event);

View File

@ -52,7 +52,7 @@ public class MVdWPlaceholders {
@Subscribe
public void onNewPlaceholder(final PlaceholderRegistry.@NonNull PlaceholderAddedEvent event) {
this.addPlaceholder(event.getPlaceholder());
this.addPlaceholder(event.placeholder());
}
private void addPlaceholder(final @NonNull Placeholder placeholder) {

View File

@ -41,13 +41,9 @@ public class BukkitOfflinePlayer implements OfflinePlotPlayer {
* @param player Bukkit OfflinePlayer player to convert
* @param permissionHandler Permission Profile to be used
*/
public BukkitOfflinePlayer(
final @NonNull OfflinePlayer player, final @NonNull
PermissionHandler permissionHandler
) {
public BukkitOfflinePlayer(final @NonNull OfflinePlayer player, final @NonNull PermissionHandler permissionHandler) {
this.player = player;
this.permissionProfile = permissionHandler.getPermissionProfile(this)
.orElse(NullPermissionProfile.INSTANCE);
this.permissionProfile = permissionHandler.getPermissionProfile(this).orElse(NullPermissionProfile.INSTANCE);
}
@NonNull

View File

@ -71,14 +71,15 @@ public class BukkitPlayer extends PlotPlayer<Player> {
* @param eventDispatcher EventDispatcher instance
* @param player Bukkit player instance
* @param permissionHandler PermissionHandler instance
*
* @deprecated Please do not use this method. Instead use {@link BukkitUtil#adapt(Player)}, as it caches player objects.
* This method will be made private in a future release.
* This method will be made private in a future release.
*/
@Deprecated(forRemoval = true, since = "TODO")
public BukkitPlayer(
final @NonNull PlotAreaManager plotAreaManager, final @NonNull EventDispatcher eventDispatcher,
final @NonNull Player player, final @NonNull PermissionHandler permissionHandler
final @NonNull PlotAreaManager plotAreaManager,
final @NonNull EventDispatcher eventDispatcher,
final @NonNull Player player,
final @NonNull PermissionHandler permissionHandler
) {
this(plotAreaManager, eventDispatcher, player, false, permissionHandler);
}
@ -88,14 +89,14 @@ public class BukkitPlayer extends PlotPlayer<Player> {
* @param eventDispatcher EventDispatcher instance
* @param player Bukkit player instance
* @param permissionHandler PermissionHandler instance
*
* @deprecated Please do not use this method. Instead use {@link BukkitUtil#adapt(Player)}, as it caches player objects.
* This method will be made private in a future release.
* This method will be made private in a future release.
*/
@Deprecated(forRemoval = true, since = "TODO")
public BukkitPlayer(
final @NonNull PlotAreaManager plotAreaManager, final @NonNull
EventDispatcher eventDispatcher, final @NonNull Player player,
final @NonNull PlotAreaManager plotAreaManager,
final @NonNull EventDispatcher eventDispatcher,
final @NonNull Player player,
final boolean realPlayer,
final @NonNull PermissionHandler permissionHandler
) {

View File

@ -270,7 +270,7 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator {
if (getChunkObject() instanceof Chunk chunkObject) {
existing = chunkObject.getBlock(x & 15, y, z & 15);
} else {
existing = getBukkitWorld().getBlockAt(x, y, z);
existing = getBukkitWorld().getBlockAt(x, y, z);
}
final BlockState existingBaseBlock = BukkitAdapter.adapt(existing.getBlockData());
if (BukkitBlockUtil.get(existing).equals(existingBaseBlock) && existing.getBlockData().matches(blockData)) {

View File

@ -62,7 +62,6 @@ public class GenChunk extends ZeroedDelegateScopedQueueCoordinator {
/**
* @param minY minimum world Y, inclusive
* @param maxY maximum world Y, inclusive
*
* @since 6.6.0
*/
public GenChunk(int minY, int maxY) {
@ -110,9 +109,9 @@ public class GenChunk extends ZeroedDelegateScopedQueueCoordinator {
*/
public void setChunk(@NonNull ChunkWrapper wrap) {
chunk = null;
world = wrap.world;
chunkX = wrap.x;
chunkZ = wrap.z;
world = wrap.world();
chunkX = wrap.x();
chunkZ = wrap.z();
}
@Override

View File

@ -69,8 +69,9 @@ public class BukkitRegionManager extends RegionManager {
@Inject
public BukkitRegionManager(
@NonNull WorldUtil worldUtil, @NonNull GlobalBlockQueue blockQueue, @NonNull
ProgressSubscriberFactory subscriberFactory
@NonNull WorldUtil worldUtil,
@NonNull GlobalBlockQueue blockQueue,
@NonNull ProgressSubscriberFactory subscriberFactory
) {
super(worldUtil, blockQueue, subscriberFactory);
this.blockQueue = blockQueue;
@ -257,7 +258,7 @@ public class BukkitRegionManager extends RegionManager {
map.saveEntitiesOut(Bukkit.getWorld(world.getName()).getChunkAt(x, z), currentPlotClear);
AugmentedUtils.bypass(
ignoreAugment,
() -> ChunkManager.setChunkInPlotArea(null, new RunnableVal<ZeroedDelegateScopedQueueCoordinator>() {
() -> ChunkManager.setChunkInPlotArea(null, new RunnableVal<>() {
@Override
public void run(ZeroedDelegateScopedQueueCoordinator value) {
Location min = value.getMin();

View File

@ -124,7 +124,7 @@ public class BukkitSetupUtils extends SetupUtils {
public String setupWorld(PlotAreaBuilder builder) {
this.updateGenerators(false);
ConfigurationNode[] steps = builder.settingsNodesWrapper() == null ?
new ConfigurationNode[0] : builder.settingsNodesWrapper().getSettingsNodes();
new ConfigurationNode[0] : builder.settingsNodesWrapper().settingsNodes();
String world = builder.worldName();
PlotAreaType type = builder.plotAreaType();
String worldPath = "worlds." + builder.worldName();

View File

@ -31,7 +31,6 @@ import org.apache.logging.log4j.Logger;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import java.util.HashMap;
import java.util.HashSet;
@ -85,28 +84,6 @@ public class ContentMap {
}
}
void saveEntitiesIn(Chunk chunk, CuboidRegion region, boolean delete) {
for (Entity entity : chunk.getEntities()) {
Location location = BukkitUtil.adapt(entity.getLocation());
int x = location.getX();
int z = location.getZ();
if (!BukkitChunkManager.isIn(region, x, z)) {
continue;
}
if (entity.getVehicle() != null) {
continue;
}
EntityWrapper wrap = new ReplicatingEntityWrapper(entity, (short) 2);
wrap.saveEntity();
this.entities.add(wrap);
if (delete) {
if (!(entity instanceof Player)) {
entity.remove();
}
}
}
}
void restoreEntities(World world) {
for (EntityWrapper entity : this.entities) {
try {

View File

@ -60,4 +60,5 @@ public class TranslationUpdateManager {
e.printStackTrace();
}
}
}

View File

@ -54,7 +54,8 @@ public class UpdateUtility implements Listener {
internalVersion = PlotSquared.get().getVersion();
}
@SuppressWarnings({"deprecation", "DefaultCharset"}) // Suppress Json deprecation, we can't use features from gson 2.8.1 and newer yet
// Suppress Json deprecation, we can't use features from gson 2.8.1 and newer yet
@SuppressWarnings({"deprecation", "DefaultCharset"})
public void updateChecker() {
task = Bukkit.getScheduler().runTaskTimerAsynchronously(this.javaPlugin, () -> {
try {

View File

@ -111,8 +111,8 @@ public class SQLiteUUIDService implements UUIDService, Consumer<List<UUIDMapping
try (final PreparedStatement statement = getConnection()
.prepareStatement("INSERT OR REPLACE INTO `usercache` (`uuid`, `username`) VALUES(?, ?)")) {
for (final UUIDMapping mapping : uuidWrappers) {
statement.setString(1, mapping.getUuid().toString());
statement.setString(2, mapping.getUsername());
statement.setString(1, mapping.uuid().toString());
statement.setString(2, mapping.username());
statement.executeUpdate();
}
} catch (SQLException e) {

View File

@ -203,7 +203,7 @@ public interface PlotPlatform<P> extends LocaleHolder {
* @return Player manager
*/
default @NonNull PlayerManager<? extends PlotPlayer<P>, ? extends P> playerManager() {
return injector().getInstance(Key.get(new TypeLiteral<PlayerManager<? extends PlotPlayer<P>, ? extends P>>() {
return injector().getInstance(Key.get(new TypeLiteral<>() {
}));
}

View File

@ -133,8 +133,6 @@ public class PlotSquared {
private final Map<String, CaptionMap> captionMaps = new HashMap<>();
public HashMap<String, HashMap<PlotId, Plot>> plots_tmp;
private CaptionLoader captionLoader;
// WorldEdit instance
private WorldEdit worldedit;
private File configFile;
private File worldsFile;
private YamlConfiguration worldConfiguration;
@ -223,11 +221,11 @@ public class PlotSquared {
}
}
this.worldedit = WorldEdit.getInstance();
WorldEdit worldedit = WorldEdit.getInstance();
WorldEdit.getInstance().getEventBus().register(new WEPlatformReadyListener());
// Create Event utility class
this.eventDispatcher = new EventDispatcher(this.worldedit);
this.eventDispatcher = new EventDispatcher(worldedit);
// Create plot listener
this.plotListener = new PlotListener(this.eventDispatcher);
@ -270,7 +268,11 @@ public class PlotSquared {
captionMap = this.captionLoader.loadAll(this.platform.getDirectory().toPath().resolve("lang"));
} else {
String fileName = "messages_" + Settings.Enabled_Components.DEFAULT_LOCALE + ".json";
captionMap = this.captionLoader.loadOrCreateSingle(this.platform.getDirectory().toPath().resolve("lang").resolve(fileName));
captionMap = this.captionLoader.loadOrCreateSingle(this.platform
.getDirectory()
.toPath()
.resolve("lang")
.resolve(fileName));
}
this.captionMaps.put(TranslatableCaption.DEFAULT_NAMESPACE, captionMap);
LOGGER.info(
@ -1521,10 +1523,6 @@ public class PlotSquared {
return this.backgroundUUIDPipeline;
}
public @NonNull WorldEdit getWorldEdit() {
return this.worldedit;
}
public @NonNull File getConfigFile() {
return this.configFile;
}

View File

@ -136,13 +136,7 @@ public class SimpleBackupManager implements BackupManager {
return this.backupLimit;
}
private static final class PlotCacheKey {
private final Plot plot;
private PlotCacheKey(Plot plot) {
this.plot = plot;
}
private record PlotCacheKey(Plot plot) {
@Override
public boolean equals(final Object o) {

View File

@ -173,7 +173,7 @@ public class QuadMap<T> {
public QuadMap<T> newInstance(int newsize, int x, int z, int min) {
try {
return new QuadMap<T>(newsize, x, z, min) {
return new QuadMap<>(newsize, x, z, min) {
@Override
public CuboidRegion getRegion(T value) {
return QuadMap.this.getRegion(value);

View File

@ -70,7 +70,8 @@ public class Add extends Command {
plot.isOwner(player.getUUID()) || player.hasPermission(Permission.PERMISSION_ADMIN_COMMAND_TRUST),
TranslatableCaption.of("permission.no_plot_perms")
);
checkTrue(args.length == 1,
checkTrue(
args.length == 1,
TranslatableCaption.of("commandconfig.command_syntax"),
TagResolver.resolver("value", Tag.inserting(Component.text("/plot add <player | *>")))
);

View File

@ -232,12 +232,13 @@ public class Area extends SubCommand {
try (final ClipboardWriter clipboardWriter = BuiltInClipboardFormat.SPONGE_SCHEMATIC.getWriter(new FileOutputStream(
file))) {
final BlockArrayClipboard clipboard = new BlockArrayClipboard(selectedRegion);
final EditSession editSession = WorldEdit
.getInstance()
.getEditSessionFactory()
.getEditSession(selectedRegion.getWorld(), -1);
final ForwardExtentCopy forwardExtentCopy =
new ForwardExtentCopy(editSession, selectedRegion, clipboard, selectedRegion.getMinimumPoint());
final EditSession editSession = WorldEdit.getInstance().newEditSession(selectedRegion.getWorld());
final ForwardExtentCopy forwardExtentCopy = new ForwardExtentCopy(
editSession,
selectedRegion,
clipboard,
selectedRegion.getMinimumPoint()
);
forwardExtentCopy.setCopyingBiomes(true);
forwardExtentCopy.setCopyingEntities(true);
Operations.complete(forwardExtentCopy);
@ -724,7 +725,7 @@ public class Area extends SubCommand {
return false;
}
final List<PlotArea> areas = new ArrayList<>(Arrays.asList(this.plotAreaManager.getAllPlotAreas()));
paginate(player, areas, 8, page, new RunnableVal3<Integer, PlotArea, CaptionHolder>() {
paginate(player, areas, 8, page, new RunnableVal3<>() {
@Override
public void run(Integer i, PlotArea area, CaptionHolder caption) {
String name;

View File

@ -83,7 +83,7 @@ public class Caps extends SubCommand {
final int current = countedEntities[type];
final int max = plot.getFlag(capFlag);
final String percentage = String.format("%.1f", 100 * ((float) current / max));
ComponentLike maxBeautified = max >= Integer.MAX_VALUE
ComponentLike maxBeautified = max == Integer.MAX_VALUE
? TranslatableCaption.of("info.infinite").toComponent(player)
: Component.text(max);
player.sendMessage(

View File

@ -46,6 +46,7 @@ import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeoutException;
@ -77,8 +78,7 @@ public class Cluster extends SubCommand {
}
String sub = args[0].toLowerCase();
switch (sub) {
case "l":
case "list": {
case "l", "list" -> {
if (!player.hasPermission(Permission.PERMISSION_CLUSTER_LIST)) {
player.sendMessage(
TranslatableCaption.of("permission.no_permission"),
@ -133,8 +133,7 @@ public class Cluster extends SubCommand {
}
return true;
}
case "c":
case "create": {
case "c", "create" -> {
if (!player.hasPermission(Permission.PERMISSION_CLUSTER_CREATE)) {
player.sendMessage(
TranslatableCaption.of("permission.no_permission"),
@ -269,9 +268,7 @@ public class Cluster extends SubCommand {
);
return true;
}
case "disband":
case "del":
case "delete": {
case "disband", "del", "delete" -> {
if (!player.hasPermission(Permission.PERMISSION_CLUSTER_DELETE)) {
player.sendMessage(
TranslatableCaption.of("permission.no_permission"),
@ -330,8 +327,7 @@ public class Cluster extends SubCommand {
));
return true;
}
case "res":
case "resize": {
case "res", "resize" -> {
if (!player.hasPermission(Permission.PERMISSION_CLUSTER_RESIZE)) {
player.sendMessage(
TranslatableCaption.of("permission.no_permission"),
@ -452,9 +448,7 @@ public class Cluster extends SubCommand {
player.sendMessage(TranslatableCaption.of("cluster.cluster_resized"));
return true;
}
case "add":
case "inv":
case "invite": {
case "add", "inv", "invite" -> {
if (!player.hasPermission(Permission.PERMISSION_CLUSTER_INVITE)) {
player.sendMessage(
TranslatableCaption.of("permission.no_permission"),
@ -523,9 +517,7 @@ public class Cluster extends SubCommand {
});
return true;
}
case "k":
case "remove":
case "kick": {
case "k", "remove", "kick" -> {
if (!player.hasPermission(Permission.PERMISSION_CLUSTER_KICK)) {
player.sendMessage(
TranslatableCaption.of("permission.no_permission"),
@ -605,8 +597,7 @@ public class Cluster extends SubCommand {
});
return true;
}
case "quit":
case "leave": {
case "quit", "leave" -> {
if (!player.hasPermission(Permission.PERMISSION_CLUSTER_LEAVE)) {
player.sendMessage(
TranslatableCaption.of("permission.no_permission"),
@ -667,7 +658,7 @@ public class Cluster extends SubCommand {
removePlayerPlots(cluster, uuid, player.getLocation().getWorldName());
return true;
}
case "members": {
case "members" -> {
if (!player.hasPermission(Permission.PERMISSION_CLUSTER_HELPERS)) {
player.sendMessage(
TranslatableCaption.of("permission.no_permission"),
@ -728,9 +719,7 @@ public class Cluster extends SubCommand {
});
return true;
}
case "spawn":
case "home":
case "tp": {
case "spawn", "home", "tp" -> {
if (!player.hasPermission(Permission.PERMISSION_CLUSTER_TP)) {
player.sendMessage(
TranslatableCaption.of("permission.no_permission"),
@ -778,10 +767,7 @@ public class Cluster extends SubCommand {
player.sendMessage(TranslatableCaption.of("cluster.cluster_teleporting"));
return true;
}
case "i":
case "info":
case "show":
case "information": {
case "i", "info", "show", "information" -> {
if (!player.hasPermission(Permission.PERMISSION_CLUSTER_INFO)) {
player.sendMessage(
TranslatableCaption.of("permission.no_permission"),
@ -827,12 +813,7 @@ public class Cluster extends SubCommand {
if (throwable instanceof TimeoutException) {
player.sendMessage(TranslatableCaption.of("players.fetching_players_timeout"));
} else {
final String owner;
if (username == null) {
owner = "unknown";
} else {
owner = username;
}
final String owner = Objects.requireNonNullElse(username, "unknown");
String name = cluster.getName();
String size = (cluster.getP2().getX() - cluster.getP1().getX() + 1) + "x" + (
cluster.getP2().getY() - cluster.getP1().getY() + 1);
@ -850,9 +831,7 @@ public class Cluster extends SubCommand {
});
return true;
}
case "sh":
case "setspawn":
case "sethome": {
case "sh", "setspawn", "sethome" -> {
if (!player.hasPermission(Permission.PERMISSION_CLUSTER_SETHOME)) {
player.sendMessage(
TranslatableCaption.of("permission.no_permission"),

View File

@ -502,9 +502,9 @@ public abstract class Command {
public String getCommandString() {
if (this.parent == null) {
return "/" + toString();
return "/" + this;
} else {
return this.parent.getCommandString() + " " + toString();
return this.parent.getCommandString() + " " + this;
}
}

View File

@ -37,7 +37,7 @@ public class Confirm extends SubCommand {
}
CmdConfirm.removePending(player);
if ((System.currentTimeMillis() - command.timestamp)
> Settings.Confirmation.CONFIRMATION_TIMEOUT_SECONDS * 1000) {
> Settings.Confirmation.CONFIRMATION_TIMEOUT_SECONDS * 1000L) {
player.sendMessage(TranslatableCaption.of("confirm.expired_confirm"));
return false;
}

View File

@ -69,7 +69,8 @@ public class Copy extends SubCommand {
plot1.getPlotModificationManager().copy(plot2, player).thenAccept(result -> {
if (result) {
player.sendMessage(TranslatableCaption.of("move.copy_success"),
player.sendMessage(
TranslatableCaption.of("move.copy_success"),
TagResolver.builder()
.tag("origin", Tag.inserting(Component.text(plot1.toString())))
.tag("target", Tag.inserting(Component.text(plot2.toString())))

View File

@ -183,24 +183,22 @@ public class Download extends SubCommand {
private void upload(PlotPlayer<?> player, Plot plot) {
if (Settings.Web.LEGACY_WEBINTERFACE) {
schematicHandler
.getCompoundTag(plot)
.whenComplete((compoundTag, throwable) -> {
schematicHandler.upload(compoundTag, null, null, new RunnableVal<>() {
@Override
public void run(URL value) {
plot.removeRunning();
player.sendMessage(
TranslatableCaption.of("web.generation_link_success"),
TagResolver.builder()
.tag("download", Tag.preProcessParsed(value.toString()))
.tag("delete", Tag.preProcessParsed("Not available"))
.build()
);
player.sendMessage(StaticCaption.of(value.toString()));
}
});
});
schematicHandler.getCompoundTag(plot).whenComplete((compoundTag, throwable) -> schematicHandler.upload(
compoundTag,
null,
null,
new RunnableVal<>() {
@Override
public void run(URL value) {
plot.removeRunning();
player.sendMessage(TranslatableCaption.of("web.generation_link_success"), TagResolver.builder().tag(
"download",
Tag.preProcessParsed(value.toString())
).tag("delete", Tag.preProcessParsed("Not available")).build());
player.sendMessage(StaticCaption.of(value.toString()));
}
}
));
return;
}
// TODO legacy support

View File

@ -132,7 +132,12 @@ public class Help extends Command {
TagResolver.builder()
.tag("command", Tag.inserting(Component.text("/plot help")))
.tag("category", Tag.inserting(Component.text("all")))
.tag("category_desc", Tag.inserting(TranslatableCaption.of("help.help_display_all_commands").toComponent(player)))
.tag(
"category_desc",
Tag.inserting(TranslatableCaption
.of("help.help_display_all_commands")
.toComponent(player))
)
.build()
));
builder.append(Component.newline()).append(MINI_MESSAGE.deserialize(TranslatableCaption

View File

@ -85,24 +85,24 @@ public class Inbox extends SubCommand {
for (int x = page * 12; x < max; x++) {
PlotComment comment = comments[x];
Component commentColored;
if (player.getName().equals(comment.senderName)) {
if (player.getName().equals(comment.senderName())) {
commentColored = MINI_MESSAGE
.deserialize(
TranslatableCaption.of("list.comment_list_by_lister").getComponent(player),
TagResolver.resolver("comment", Tag.inserting(Component.text(comment.comment)))
TagResolver.resolver("comment", Tag.inserting(Component.text(comment.comment())))
);
} else {
commentColored = MINI_MESSAGE
.deserialize(
TranslatableCaption.of("list.comment_list_by_other").getComponent(player),
TagResolver.resolver("comment", Tag.inserting(Component.text(comment.comment)))
TagResolver.resolver("comment", Tag.inserting(Component.text(comment.comment())))
);
}
TagResolver resolver = TagResolver.builder()
.tag("number", Tag.inserting(Component.text(x)))
.tag("world", Tag.inserting(Component.text(comment.world)))
.tag("plot_id", Tag.inserting(Component.text(comment.id.getX() + ";" + comment.id.getY())))
.tag("commenter", Tag.inserting(Component.text(comment.senderName)))
.tag("world", Tag.inserting(Component.text(comment.world())))
.tag("plot_id", Tag.inserting(Component.text(comment.id().getX() + ";" + comment.id().getY())))
.tag("commenter", Tag.inserting(Component.text(comment.senderName())))
.tag("comment", Tag.inserting(commentColored))
.build();
builder.append(MINI_MESSAGE
@ -137,7 +137,7 @@ public class Inbox extends SubCommand {
int unread = 0;
for (PlotComment comment : value) {
total++;
if (comment.timestamp > CommentManager
if (comment.timestamp() > CommentManager
.getTimestamp(player, inbox.toString())) {
unread++;
}
@ -242,7 +242,7 @@ public class Inbox extends SubCommand {
if (success) {
player.sendMessage(
TranslatableCaption.of("comment.comment_removed_success"),
TagResolver.resolver("value", Tag.inserting(Component.text(comment.comment)))
TagResolver.resolver("value", Tag.inserting(Component.text(comment.comment())))
);
} else {
player.sendMessage(

View File

@ -52,8 +52,9 @@ public class Info extends SubCommand {
arg = args[0];
switch (arg) {
// TODO: (re?)implement /plot info inv. (it was never properly implemented)
case "trusted", "alias", "biome", "denied", "flags", "id", "size", "members", "creationdate", "seen", "owner", "rating", "likes" -> plot = Plot
.getPlotFromString(player, null, false);
case "trusted", "alias", "biome", "denied", "flags", "id", "size", "members", "creationdate", "seen", "owner", "rating", "likes" ->
plot = Plot
.getPlotFromString(player, null, false);
default -> {
plot = Plot.getPlotFromString(player, arg, false);
if (args.length == 2) {

View File

@ -117,7 +117,7 @@ public class ListCmd extends SubCommand {
if (player.hasPermission(Permission.PERMISSION_LIST_FUZZY)) {
args.add("fuzzy <search...>");
}
return args.toArray(new String[args.size()]);
return args.toArray(new String[0]);
}
public void noArgs(PlotPlayer<?> player) {
@ -474,20 +474,20 @@ public class ListCmd extends SubCommand {
final List<UUIDMapping> names = PlotSquared.get().getImpromptuUUIDPipeline().getNames(plot.getOwners())
.get(Settings.UUID.BLOCKING_TIMEOUT, TimeUnit.MILLISECONDS);
for (final UUIDMapping uuidMapping : names) {
PlotPlayer<?> pp = PlotSquared.platform().playerManager().getPlayerIfExists(uuidMapping.getUuid());
PlotPlayer<?> pp = PlotSquared.platform().playerManager().getPlayerIfExists(uuidMapping.uuid());
TagResolver resolver = TagResolver.builder()
.tag("prefix", Tag.inserting(Component.text(prefix)))
.tag("player", Tag.inserting(Component.text(uuidMapping.getUsername())))
.build();
if (pp != null) {
builder.append(MINI_MESSAGE.deserialize(online, resolver));
} else if (uuidMapping.getUsername().equalsIgnoreCase("unknown")) {
.tag("prefix", Tag.inserting(Component.text(prefix)))
.tag("player", Tag.inserting(Component.text(uuidMapping.username())))
.build();
if (pp != null) {
builder.append(MINI_MESSAGE.deserialize(online, resolver));
} else if (uuidMapping.username().equalsIgnoreCase("unknown")) {
TagResolver unknownResolver = TagResolver.resolver(
"info.unknown",
Tag.inserting(TranslatableCaption.of("info.unknown").toComponent(player))
);
builder.append(MINI_MESSAGE.deserialize(unknown, unknownResolver));
} else if (uuidMapping.getUuid().equals(DBFunc.EVERYONE)) {
} else if (uuidMapping.uuid().equals(DBFunc.EVERYONE)) {
TagResolver everyoneResolver = TagResolver.resolver(
"info.everyone",
Tag.inserting(TranslatableCaption.of("info.everyone").toComponent(player))

View File

@ -28,7 +28,6 @@ import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.tag.Tag;
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
import java.util.List;
import java.util.concurrent.CompletableFuture;
@CommandDeclaration(command = "near",
@ -56,8 +55,4 @@ public class Near extends Command {
return CompletableFuture.completedFuture(true);
}
private List<PlotPlayer<?>> getPlayersInPlotVisible(Plot plot, PlotPlayer<?> executor) {
return plot.getPlayersInPlot().stream().filter(executor::canSee).toList();
}
}

View File

@ -127,7 +127,7 @@ public class Purge extends SubCommand {
);
return false;
}
owner = ownerMapping.getUuid();
owner = ownerMapping.uuid();
break;
case "shared":
case "s":
@ -139,7 +139,7 @@ public class Purge extends SubCommand {
);
return false;
}
added = addedMapping.getUuid();
added = addedMapping.uuid();
break;
case "clear":
case "c":
@ -236,9 +236,12 @@ public class Purge extends SubCommand {
try {
ids.add(plot.temp);
if (finalClear) {
plot.getPlotModificationManager().clear(false, true, player, () -> {
LOGGER.info("Plot {} cleared by purge", plot.getId());
});
plot.getPlotModificationManager().clear(
false,
true,
player,
() -> LOGGER.info("Plot {} cleared by purge", plot.getId())
);
} else {
plot.getPlotModificationManager().removeSign();
}

View File

@ -156,9 +156,9 @@ public class Template extends SubCommand {
ZipOutputStream zos = new ZipOutputStream(fos)) {
for (FileBytes file : files) {
ZipEntry ze = new ZipEntry(file.path);
ZipEntry ze = new ZipEntry(file.path());
zos.putNextEntry(ze);
zos.write(file.data);
zos.write(file.data());
}
zos.closeEntry();
}

View File

@ -35,28 +35,8 @@ import java.util.Map;
* the component GUI
*/
@SerializableAs("preset")
public class ComponentPreset implements ConfigurationSerializable {
private final ClassicPlotManagerComponent component;
private final String pattern;
private final double cost;
private final String permission;
private final String displayName;
private final List<String> description;
private final ItemType icon;
public ComponentPreset(
ClassicPlotManagerComponent component, String pattern, double cost,
String permission, String displayName, List<String> description, final ItemType icon
) {
this.component = component;
this.pattern = pattern;
this.cost = cost;
this.permission = permission;
this.displayName = displayName;
this.description = description;
this.icon = icon;
}
public record ComponentPreset(ClassicPlotManagerComponent component, String pattern, double cost, String permission,
String displayName, List<String> description, ItemType icon) implements ConfigurationSerializable {
@SuppressWarnings("unchecked")
public static ComponentPreset deserialize(final @NonNull Map<String, Object> map) {
@ -74,34 +54,6 @@ public class ComponentPreset implements ConfigurationSerializable {
);
}
public ClassicPlotManagerComponent getComponent() {
return this.component;
}
public String getPattern() {
return this.pattern;
}
public double getCost() {
return this.cost;
}
public String getPermission() {
return this.permission;
}
public String getDisplayName() {
return this.displayName;
}
public List<String> getDescription() {
return this.description;
}
public ItemType getIcon() {
return this.icon;
}
@Override
public Map<String, Object> serialize() {
final Map<String, Object> map = new HashMap<>();

View File

@ -165,8 +165,8 @@ public class ComponentPresetManager {
final List<ComponentPreset> allowedPresets = new ArrayList<>(this.presets.size());
for (final ComponentPreset componentPreset : this.presets) {
if (!componentPreset.getPermission().isEmpty() && !player.hasPermission(
componentPreset.getPermission()
if (!componentPreset.permission().isEmpty() && !player.hasPermission(
componentPreset.permission()
)) {
continue;
}
@ -200,30 +200,30 @@ public class ComponentPresetManager {
return false;
}
final Pattern pattern = PatternUtil.parse(null, componentPreset.getPattern(), false);
final Pattern pattern = PatternUtil.parse(null, componentPreset.pattern(), false);
if (pattern == null) {
getPlayer().sendMessage(TranslatableCaption.of("preset.preset_invalid"));
return false;
}
if (componentPreset.getCost() > 0.0D) {
if (componentPreset.cost() > 0.0D) {
if (!econHandler.isEnabled(plot.getArea())) {
getPlayer().sendMessage(
TranslatableCaption.of("preset.economy_disabled"),
TagResolver.resolver("preset", Tag.inserting(Component.text(componentPreset.getDisplayName())))
TagResolver.resolver("preset", Tag.inserting(Component.text(componentPreset.displayName())))
);
return false;
}
if (econHandler.getMoney(getPlayer()) < componentPreset.getCost()) {
if (econHandler.getMoney(getPlayer()) < componentPreset.cost()) {
getPlayer().sendMessage(TranslatableCaption.of("preset.preset_cannot_afford"));
return false;
} else {
econHandler.withdrawMoney(getPlayer(), componentPreset.getCost());
econHandler.withdrawMoney(getPlayer(), componentPreset.cost());
getPlayer().sendMessage(
TranslatableCaption.of("economy.removed_balance"),
TagResolver.resolver(
"money",
Tag.inserting(Component.text(econHandler.format(componentPreset.getCost())))
Tag.inserting(Component.text(econHandler.format(componentPreset.cost())))
)
);
}
@ -235,7 +235,7 @@ public class ComponentPresetManager {
queue.setCompleteTask(plot::removeRunning);
for (Plot current : plot.getConnectedPlots()) {
current.getPlotModificationManager().setComponent(
componentPreset.getComponent().name(),
componentPreset.component().name(),
pattern,
player,
queue
@ -252,32 +252,32 @@ public class ComponentPresetManager {
for (int i = 0; i < allowedPresets.size(); i++) {
final ComponentPreset preset = allowedPresets.get(i);
final List<String> lore = new ArrayList<>();
if (preset.getCost() > 0) {
if (preset.cost() > 0) {
if (!this.econHandler.isEnabled(plot.getArea())) {
lore.add(MINI_MESSAGE.serialize(MINI_MESSAGE.deserialize(
TranslatableCaption.of("preset.preset_lore_economy_disabled").getComponent(player))));
} else {
lore.add(MINI_MESSAGE.serialize(MINI_MESSAGE.deserialize(
TranslatableCaption.of("preset.preset_lore_cost").getComponent(player),
TagResolver.resolver("cost", Tag.inserting(Component.text(String.format("%.2f", preset.getCost()))))
TagResolver.resolver("cost", Tag.inserting(Component.text(String.format("%.2f", preset.cost()))))
)));
}
}
lore.add(MINI_MESSAGE.serialize(MINI_MESSAGE.deserialize(
TranslatableCaption.of("preset.preset_lore_component").getComponent(player),
TagResolver.builder()
.tag("component", Tag.inserting(Component.text(preset.getComponent().name().toLowerCase())))
.tag("component", Tag.inserting(Component.text(preset.component().name().toLowerCase())))
.tag("prefix", Tag.inserting(TranslatableCaption.of("core.prefix").toComponent(player)))
.build()
)));
lore.removeIf(String::isEmpty);
lore.addAll(preset.getDescription());
lore.addAll(preset.description());
plotInventory.setItem(
i,
new PlotItemStack(
preset.getIcon().getId().replace("minecraft:", ""),
preset.icon().getId().replace("minecraft:", ""),
1,
preset.getDisplayName(),
preset.displayName(),
lore.toArray(new String[0])
)
);

View File

@ -42,32 +42,6 @@ public class Config {
private static final Logger LOGGER = LogManager.getLogger("PlotSquared/" + Config.class.getSimpleName());
/**
* Get the value for a node<br>
* Probably throws some error if you try to get a non existent key
*
* @param key configuration key
* @param root configuration class
* @param <T> value type
* @return value
*/
@SuppressWarnings("unchecked")
public static <T> T get(String key, Class<?> root) {
String[] split = key.split("\\.");
Object instance = getInstance(split, root);
if (instance != null) {
Field field = getField(split, instance);
if (field != null) {
try {
return (T) field.get(instance);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
return null;
}
/**
* Set the value of a specific node<br>
* Probably throws some error if you supply non existing keys or invalid values
@ -445,10 +419,6 @@ public class Config {
return INSTANCES.values();
}
public Collection<String> getSections() {
return INSTANCES.keySet();
}
private Map<String, T> getRaw() {
return INSTANCES;
}

View File

@ -146,7 +146,6 @@ public final class CaptionLoader {
* @param reader the reader to read the map from.
* @return the translation map.
*/
@SuppressWarnings("UnstableApiUsage")
static @NonNull Map<@NonNull String, @NonNull String> loadFromReader(final @NonNull Reader reader) {
final Type type = new TypeToken<Map<String, String>>() {
}.getType();
@ -225,7 +224,7 @@ public final class CaptionLoader {
*/
public @NonNull CaptionMap loadOrCreateSingle(final @NonNull Path file) throws IOException {
final Locale locale = this.localeExtractor.apply(file);
if (!Files.exists(file) ) {
if (!Files.exists(file)) {
Map<String, String> map = new LinkedHashMap<>();
patch(map, locale);
save(file, map);

View File

@ -56,7 +56,8 @@ final class ClassLoaderCaptionProvider implements DefaultCaptionProvider {
LOGGER.info("No resource for locale '{}' found in the plugin file." +
"Please ensure you have placed the latest version of the file messages_{}.json in the 'lang' folder." +
"You may be able to find completed translations at https://intellectualsites.crowdin.com/plotsquared",
locale, locale);
locale, locale
);
return null;
}
try (final BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) {

View File

@ -2400,13 +2400,13 @@ public class SQLManager implements AbstractDB {
if (plot != null) {
statement.setString(1, plot.getArea().toString());
statement.setInt(2, plot.getId().hashCode());
statement.setString(3, comment.comment);
statement.setString(4, comment.inbox);
statement.setString(5, comment.senderName);
statement.setString(3, comment.comment());
statement.setString(4, comment.inbox());
statement.setString(5, comment.senderName());
} else {
statement.setString(1, comment.comment);
statement.setString(2, comment.inbox);
statement.setString(3, comment.senderName);
statement.setString(1, comment.comment());
statement.setString(2, comment.inbox());
statement.setString(3, comment.senderName());
}
}
@ -2499,7 +2499,7 @@ public class SQLManager implements AbstractDB {
id = null;
}
String msg = set.getString("comment");
long timestamp = set.getInt("timestamp") * 1000;
long timestamp = set.getInt("timestamp") * 1000L;
PlotComment comment =
new PlotComment(world, id, msg, sender, inbox, timestamp);
comments.add(comment);
@ -2518,10 +2518,10 @@ public class SQLManager implements AbstractDB {
public void set(PreparedStatement statement) throws SQLException {
statement.setString(1, plot.getArea().toString());
statement.setInt(2, plot.getId().hashCode());
statement.setString(3, comment.comment);
statement.setString(4, comment.inbox);
statement.setInt(5, (int) (comment.timestamp / 1000));
statement.setString(6, comment.senderName);
statement.setString(3, comment.comment());
statement.setString(4, comment.inbox());
statement.setInt(5, (int) (comment.timestamp() / 1000));
statement.setString(6, comment.senderName());
}
@Override
@ -3414,15 +3414,7 @@ public class SQLManager implements AbstractDB {
}
}
private static class LegacySettings {
public final int id;
public final PlotSettings settings;
public LegacySettings(int id, PlotSettings settings) {
this.id = id;
this.settings = settings;
}
private record LegacySettings(int id, PlotSettings settings) {
}

View File

@ -38,6 +38,7 @@ import javax.annotation.Nullable;
@SuppressWarnings("WeakerAccess")
public abstract class ClassicPlotWorld extends SquarePlotWorld {
private static final Logger LOGGER = LogManager.getLogger("PlotSquared/" + ClassicPlotWorld.class.getSimpleName());
public int ROAD_HEIGHT = 62;

View File

@ -341,7 +341,10 @@ public class HybridGen extends IndependentPlotGenerator {
for (Entity entity : hybridPlotWorld.getPlotSchematicEntities()) {
if (region.contains(entity.getLocation().toVector().toBlockPoint())) {
Vector3 pos = (entity.getLocation().toVector()
.subtract(region.getMinimumPoint().withY(hybridPlotWorld.getPlotSchematicMinPoint().getY()).toVector3()))
.subtract(region
.getMinimumPoint()
.withY(hybridPlotWorld.getPlotSchematicMinPoint().getY())
.toVector3()))
.add(min.getBlockVector3().withY(hybridPlotWorld.SCHEM_Y).toVector3());
result.setEntity(new PopulatingEntity(
entity,
@ -365,7 +368,6 @@ public class HybridGen extends IndependentPlotGenerator {
}
}
}
return;
}
@Override

View File

@ -141,7 +141,11 @@ public class HybridPlotManager extends ClassicPlotManager {
(pos1.getX() + pos2.getX()) / 2,
(pos1.getZ() + pos2.getZ()) / 2
), biome)) {
WorldUtil.setBiome(hybridPlotWorld.getWorldName(), new CuboidRegion(pos1.getBlockVector3(), pos2.getBlockVector3()), biome);
WorldUtil.setBiome(
hybridPlotWorld.getWorldName(),
new CuboidRegion(pos1.getBlockVector3(), pos2.getBlockVector3()),
biome
);
}
}
@ -203,8 +207,18 @@ public class HybridPlotManager extends ClassicPlotManager {
PlotId id2 = PlotId.of(id.getX(), id.getY() + 1);
Location bot = getPlotBottomLocAbs(id2);
Location top = getPlotTopLocAbs(id);
Location pos1 = Location.at(hybridPlotWorld.getWorldName(), bot.getX() - 1, hybridPlotWorld.getMinGenHeight(), top.getZ() + 1);
Location pos2 = Location.at(hybridPlotWorld.getWorldName(), top.getX() + 1, hybridPlotWorld.getMaxGenHeight(), bot.getZ());
Location pos1 = Location.at(
hybridPlotWorld.getWorldName(),
bot.getX() - 1,
hybridPlotWorld.getMinGenHeight(),
top.getZ() + 1
);
Location pos2 = Location.at(
hybridPlotWorld.getWorldName(),
top.getX() + 1,
hybridPlotWorld.getMaxGenHeight(),
bot.getZ()
);
this.resetBiome(hybridPlotWorld, pos1, pos2);
if (!hybridPlotWorld.ROAD_SCHEMATIC_ENABLED) {
return true;

View File

@ -344,18 +344,8 @@ public class HybridPlotWorld extends ClassicPlotWorld {
if (w3 > PLOT_WIDTH || h3 > PLOT_WIDTH) {
this.ROAD_SCHEMATIC_ENABLED = true;
}
int centerShiftZ;
if (l3 < this.PLOT_WIDTH) {
centerShiftZ = (this.PLOT_WIDTH - l3) / 2;
} else {
centerShiftZ = (PLOT_WIDTH - l3) / 2;
}
int centerShiftX;
if (w3 < this.PLOT_WIDTH) {
centerShiftX = (this.PLOT_WIDTH - w3) / 2;
} else {
centerShiftX = (PLOT_WIDTH - w3) / 2;
}
int centerShiftZ = (this.PLOT_WIDTH - l3) / 2;
int centerShiftX = (this.PLOT_WIDTH - w3) / 2;
BlockVector3 min = blockArrayClipboard3.getMinimumPoint();
for (short x = 0; x < w3; x++) {

View File

@ -37,7 +37,6 @@ import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.queue.BlockArrayCacheScopedQueueCoordinator;
import com.plotsquared.core.queue.GlobalBlockQueue;
import com.plotsquared.core.queue.QueueCoordinator;
import com.plotsquared.core.util.ChunkManager;
import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.MathMan;
import com.plotsquared.core.util.RegionManager;
@ -63,7 +62,6 @@ import org.checkerframework.checker.nullness.qual.Nullable;
import java.io.File;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
@ -88,7 +86,6 @@ public class HybridUtils {
public static boolean UPDATE = false;
private final PlotAreaManager plotAreaManager;
private final ChunkManager chunkManager;
private final GlobalBlockQueue blockQueue;
private final WorldUtil worldUtil;
private final SchematicHandler schematicHandler;
@ -97,14 +94,12 @@ public class HybridUtils {
@Inject
public HybridUtils(
final @NonNull PlotAreaManager plotAreaManager,
final @NonNull ChunkManager chunkManager,
final @NonNull GlobalBlockQueue blockQueue,
final @NonNull WorldUtil worldUtil,
final @NonNull SchematicHandler schematicHandler,
final @NonNull EventDispatcher eventDispatcher
) {
this.plotAreaManager = plotAreaManager;
this.chunkManager = chunkManager;
this.blockQueue = blockQueue;
this.worldUtil = worldUtil;
this.schematicHandler = schematicHandler;
@ -380,22 +375,6 @@ public class HybridUtils {
run.run();
}
public int checkModified(QueueCoordinator queue, int x1, int x2, int y1, int y2, int z1, int z2, BlockState[] blocks) {
int count = 0;
for (int y = y1; y <= y2; y++) {
for (int x = x1; x <= x2; x++) {
for (int z = z1; z <= z2; z++) {
BlockState block = queue.getBlock(x, y, z);
boolean same = Arrays.stream(blocks).anyMatch(p -> this.worldUtil.isBlockSame(block, p));
if (!same) {
count++;
}
}
}
}
return count;
}
public final ArrayList<BlockVector2> getChunks(BlockVector2 region) {
ArrayList<BlockVector2> chunks = new ArrayList<>();
int sx = region.getX() << 5;
@ -645,7 +624,7 @@ public class HybridUtils {
queue = queueCoordinator;
enqueue = false;
}
if (id1 == null || id2 == null || id1 != id2) {
if (id2 == null || id1 != id2) {
if (id1 != null) {
Plot p1 = area.getPlotAbs(id1);
if (p1 != null && p1.hasOwner() && p1.isMerged()) {

View File

@ -57,7 +57,8 @@ public abstract class IndependentPlotGenerator {
* @param setting PlotArea (settings)
* @since TODO
*/
public void populateChunk(ZeroedDelegateScopedQueueCoordinator result, PlotArea setting) {}
public void populateChunk(ZeroedDelegateScopedQueueCoordinator result, PlotArea setting) {
}
/**
* Return a new PlotArea object.
@ -103,9 +104,9 @@ public abstract class IndependentPlotGenerator {
* Get the biome to be generated at a specific point
*
* @param settings PlotArea settings to provide biome
* @param x World x position
* @param y World y position
* @param z World z position
* @param x World x position
* @param y World y position
* @param z World z position
* @return Biome type to be generated
* @since TODO
*/

View File

@ -64,7 +64,6 @@ import com.sk89q.worldedit.world.item.ItemType;
import com.sk89q.worldedit.world.item.ItemTypes;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.ComponentLike;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.tag.Tag;
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
import org.checkerframework.checker.nullness.qual.NonNull;
@ -80,8 +79,6 @@ import java.util.UUID;
public class PlotListener {
private static final MiniMessage MINI_MESSAGE = MiniMessage.miniMessage();
private final HashMap<UUID, Interval> feedRunnable = new HashMap<>();
private final HashMap<UUID, Interval> healRunnable = new HashMap<>();
private final Map<UUID, List<StatusEffect>> playerEffects = new HashMap<>();
@ -142,7 +139,9 @@ public class PlotListener {
Map.Entry<UUID, List<StatusEffect>> entry = iterator.next();
List<StatusEffect> effects = entry.getValue();
effects.removeIf(effect -> currentTime > effect.expiresAt);
if (effects.isEmpty()) iterator.remove();
if (effects.isEmpty()) {
iterator.remove();
}
}
}
}, TaskTime.seconds(1L));
@ -341,14 +340,14 @@ public class PlotListener {
}
TimedFlag.Timed<Integer> feed = plot.getFlag(FeedFlag.class);
if (feed.getInterval() != 0 && feed.getValue() != 0) {
if (feed.interval() != 0 && feed.value() != 0) {
feedRunnable
.put(player.getUUID(), new Interval(feed.getInterval(), feed.getValue(), 20));
.put(player.getUUID(), new Interval(feed.interval(), feed.value(), 20));
}
TimedFlag.Timed<Integer> heal = plot.getFlag(HealFlag.class);
if (heal.getInterval() != 0 && heal.getValue() != 0) {
if (heal.interval() != 0 && heal.value() != 0) {
healRunnable
.put(player.getUUID(), new Interval(heal.getInterval(), heal.getValue(), 20));
.put(player.getUUID(), new Interval(heal.interval(), heal.value(), 20));
}
return true;
}
@ -486,8 +485,9 @@ public class PlotListener {
/**
* Marks an effect as a status effect that will be removed on leaving a plot
* @param uuid The uuid of the player the effect belongs to
* @param name The name of the status effect
*
* @param uuid The uuid of the player the effect belongs to
* @param name The name of the status effect
* @param expiresAt The time when the effect expires
* @since 6.10.0
*/
@ -517,11 +517,6 @@ public class PlotListener {
private record StatusEffect(@NonNull String name, long expiresAt) {
private StatusEffect(@NonNull String name, long expiresAt) {
this.name = name;
this.expiresAt = expiresAt;
}
}
}
}

View File

@ -21,17 +21,7 @@ package com.plotsquared.core.location;
import com.plotsquared.core.util.MathMan;
import com.plotsquared.core.util.StringMan;
public class ChunkWrapper {
public final int x;
public final int z;
public final String world;
public ChunkWrapper(String world, int x, int z) {
this.world = world;
this.x = x;
this.z = z;
}
public record ChunkWrapper(String world, int x, int z) {
@Override
public int hashCode() {

View File

@ -51,7 +51,6 @@ public final class UncheckedWorldLocation extends Location {
* @param y Y coordinate
* @param z Z coordinate
* @return New location
*
* @since 6.9.0
*/
@DoNotUse

View File

@ -215,17 +215,7 @@ public final class BlockBucket implements ConfigurationSerializable {
return result;
}
private static final class Range {
private final int min;
private final int max;
private final boolean automatic;
public Range(int min, int max, boolean automatic) {
this.min = min;
this.max = max;
this.automatic = automatic;
}
private record Range(int min, int max, boolean automatic) {
public int getWeight() {
return max - min;
@ -235,14 +225,6 @@ public final class BlockBucket implements ConfigurationSerializable {
return num <= max && num >= min;
}
public int getMin() {
return this.min;
}
public int getMax() {
return this.max;
}
public boolean equals(final Object o) {
if (o == this) {
return true;
@ -250,31 +232,24 @@ public final class BlockBucket implements ConfigurationSerializable {
if (!(o instanceof final Range other)) {
return false;
}
if (this.getMin() != other.getMin()) {
if (this.min() != other.min()) {
return false;
}
if (this.getMax() != other.getMax()) {
if (this.max() != other.max()) {
return false;
}
if (this.isAutomatic() != other.isAutomatic()) {
return false;
}
return true;
return this.automatic() == other.automatic();
}
public int hashCode() {
final int PRIME = 59;
int result = 1;
result = result * PRIME + this.getMin();
result = result * PRIME + this.getMax();
result = result * PRIME + (this.isAutomatic() ? 79 : 97);
result = result * PRIME + this.min();
result = result * PRIME + this.max();
result = result * PRIME + (this.automatic() ? 79 : 97);
return result;
}
public boolean isAutomatic() {
return this.automatic;
}
}
}

View File

@ -382,9 +382,6 @@ public abstract class PlotArea implements ComponentLike {
this.defaultHome = new BlockLoc(Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MAX_VALUE);
} else {
try {
/*String[] split = homeDefault.split(",");
this.DEFAULT_HOME =
new PlotLoc(Integer.parseInt(split[0]), Integer.parseInt(split[1]));*/
this.defaultHome = BlockLoc.fromString(homeDefault);
} catch (NumberFormatException ignored) {
this.defaultHome = null;
@ -658,8 +655,10 @@ public abstract class PlotArea implements ComponentLike {
TranslatableCaption.of("height.height_limit"),
TagResolver.builder()
.tag("minHeight", Tag.inserting(Component.text(minBuildHeight)))
.tag("maxHeight",
Tag.inserting(Component.text(maxBuildHeight))).build()
.tag(
"maxHeight",
Tag.inserting(Component.text(maxBuildHeight))
).build()
);
// Return true if "failed" as the method will always be inverted otherwise
return true;
@ -1017,7 +1016,7 @@ public abstract class PlotArea implements ComponentLike {
*
* @param plotIds List of plot IDs to merge
* @param removeRoads If the roads between plots should be removed
* @param whenDone Task to run when any merge world changes are complete. Also runs if no changes were made. Does not
* @param whenDone Task to run when any merge world changes are complete. Also runs if no changes were made. Does not
* run if there was an error or if too few plots IDs were supplied.
* @return if merges were completed successfully.
* @since 6.9.0

View File

@ -100,7 +100,7 @@ public class PlotInventory {
* Put an item into this inventory
*
* @param index the index (= slot) where to place the item
* @param item the item to place
* @param item the item to place
* @see #setItemChecked(int, PlotItemStack)
*/
public void setItem(int index, PlotItemStack item) {

View File

@ -79,14 +79,6 @@ public class PlotSettings {
this.ratings = ratings;
}
public boolean setMerged(int direction, boolean merged) {
if (this.merged[direction] != merged) {
this.merged[direction] = merged;
return true;
}
return false;
}
public boolean setMerged(Direction direction, boolean merged) {
if (Direction.ALL == direction) {
throw new IllegalArgumentException("You cannot use Direction.ALL in this method!");
@ -113,13 +105,12 @@ public class PlotSettings {
this.position = position;
}
@SuppressWarnings({"UnstableApiUsage"})
public List<PlotComment> getComments(String inbox) {
if (this.comments == null) {
return Collections.emptyList();
}
return this.comments.stream().filter(comment -> comment.inbox.equals(inbox))
return this.comments.stream().filter(comment -> comment.inbox().equals(inbox))
.collect(ImmutableList.toImmutableList());
}

View File

@ -58,7 +58,7 @@ public class CommentManager {
if (value != null) {
int num = 0;
for (PlotComment comment : value) {
if (comment.timestamp > getTimestamp(player, inbox.toString())) {
if (comment.timestamp() > getTimestamp(player, inbox.toString())) {
num++;
}
}

View File

@ -20,25 +20,6 @@ package com.plotsquared.core.plot.comment;
import com.plotsquared.core.plot.PlotId;
public class PlotComment {
public final String comment;
public final String inbox;
public final String senderName;
public final PlotId id;
public final String world;
public final long timestamp;
public PlotComment(
String world, PlotId id, String comment, String senderName, String inbox,
long timestamp
) {
this.world = world;
this.id = id;
this.comment = comment;
this.senderName = senderName;
this.inbox = inbox;
this.timestamp = timestamp;
}
public record PlotComment(String world, PlotId id, String comment, String senderName, String inbox, long timestamp) {
}

View File

@ -154,6 +154,7 @@ public class ExpiryTask {
/**
* Returns {@code true} if this task respects unknown owners
*
* @return {@code true} if unknown owners should be counted as never online
* @since 6.4.0
*/

View File

@ -19,7 +19,6 @@
package com.plotsquared.core.plot.flag.implementations;
import com.plotsquared.core.configuration.caption.TranslatableCaption;
import com.plotsquared.core.plot.flag.FlagParseException;
import com.plotsquared.core.plot.flag.InternalFlag;
import com.plotsquared.core.plot.flag.types.ListFlag;
import org.checkerframework.checker.nullness.qual.NonNull;
@ -34,7 +33,7 @@ public class AnalysisFlag extends ListFlag<Integer, AnalysisFlag> implements Int
}
@Override
public AnalysisFlag parse(@NonNull String input) throws FlagParseException {
public AnalysisFlag parse(@NonNull String input) {
final String[] split = input.split(",");
final List<Integer> numbers = new ArrayList<>();
for (final String element : split) {

View File

@ -27,7 +27,7 @@ public class BeaconEffectsFlag extends BooleanFlag<BeaconEffectsFlag> {
public static final BeaconEffectsFlag BEACON_EFFECT_TRUE = new BeaconEffectsFlag(true);
public static final BeaconEffectsFlag BEACON_EFFECT_FALSE = new BeaconEffectsFlag(false);
private BeaconEffectsFlag(boolean value){
private BeaconEffectsFlag(boolean value) {
super(value, TranslatableCaption.of("flags.flag_description_beacon_effect"));
}

View File

@ -19,7 +19,6 @@
package com.plotsquared.core.plot.flag.implementations;
import com.plotsquared.core.configuration.caption.TranslatableCaption;
import com.plotsquared.core.plot.flag.FlagParseException;
import com.plotsquared.core.plot.flag.types.ListFlag;
import org.checkerframework.checker.nullness.qual.NonNull;
@ -39,7 +38,7 @@ public class BlockedCmdsFlag extends ListFlag<String, BlockedCmdsFlag> {
}
@Override
public BlockedCmdsFlag parse(@NonNull String input) throws FlagParseException {
public BlockedCmdsFlag parse(@NonNull String input) {
return flagOf(Arrays.asList(input.split(",")));
}

View File

@ -60,7 +60,7 @@ public class FeedFlag extends TimedFlag<Integer, FeedFlag> {
@Override
protected Integer mergeValue(Integer other) {
return this.getValue().getValue() + other;
return this.getValue().value() + other;
}
@Override

View File

@ -68,14 +68,11 @@ public class FlyFlag extends PlotFlag<FlyFlag.FlyStatus, FlyFlag> {
@Override
protected FlyFlag flagOf(final @NonNull FlyStatus value) {
switch (value) {
case ENABLED:
return FLIGHT_FLAG_ENABLED;
case DISABLED:
return FLIGHT_FLAG_DISABLED;
default:
return FLIGHT_FLAG_DEFAULT;
}
return switch (value) {
case ENABLED -> FLIGHT_FLAG_ENABLED;
case DISABLED -> FLIGHT_FLAG_DISABLED;
default -> FLIGHT_FLAG_DEFAULT;
};
}
@Override

View File

@ -19,7 +19,6 @@
package com.plotsquared.core.plot.flag.implementations;
import com.plotsquared.core.configuration.caption.TranslatableCaption;
import com.plotsquared.core.plot.flag.FlagParseException;
import com.plotsquared.core.plot.flag.PlotFlag;
import com.sk89q.worldedit.world.gamemode.GameMode;
import com.sk89q.worldedit.world.gamemode.GameModes;
@ -57,7 +56,7 @@ public class GamemodeFlag extends PlotFlag<GameMode, GamemodeFlag> {
}
@Override
public GamemodeFlag parse(@NonNull String input) throws FlagParseException {
public GamemodeFlag parse(@NonNull String input) {
return switch (input) {
case "creative", "c", "1" -> flagOf(GameModes.CREATIVE);
case "adventure", "a", "2" -> flagOf(GameModes.ADVENTURE);

View File

@ -19,7 +19,6 @@
package com.plotsquared.core.plot.flag.implementations;
import com.plotsquared.core.configuration.caption.TranslatableCaption;
import com.plotsquared.core.plot.flag.FlagParseException;
import com.plotsquared.core.plot.flag.PlotFlag;
import com.sk89q.worldedit.world.gamemode.GameMode;
import com.sk89q.worldedit.world.gamemode.GameModes;
@ -52,7 +51,7 @@ public class GuestGamemodeFlag extends PlotFlag<GameMode, GuestGamemodeFlag> {
}
@Override
public GuestGamemodeFlag parse(@NonNull String input) throws FlagParseException {
public GuestGamemodeFlag parse(@NonNull String input) {
return switch (input) {
case "creative", "c", "1" -> flagOf(GameModes.CREATIVE);
case "adventure", "a", "2" -> flagOf(GameModes.ADVENTURE);

View File

@ -60,7 +60,7 @@ public class HealFlag extends TimedFlag<Integer, HealFlag> {
@Override
protected Integer mergeValue(Integer other) {
return this.getValue().getValue() + other;
return this.getValue().value() + other;
}
@Override

View File

@ -27,7 +27,7 @@ public class ProjectilesFlag extends BooleanFlag<ProjectilesFlag> {
public static final ProjectilesFlag PROJECTILES_TRUE = new ProjectilesFlag(true);
public static final ProjectilesFlag PROJECTILES_FALSE = new ProjectilesFlag(false);
private ProjectilesFlag(boolean value){
private ProjectilesFlag(boolean value) {
super(value, TranslatableCaption.of("flags.flag_description_projectiles"));
}

View File

@ -30,7 +30,6 @@ import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
public abstract class BlockTypeListFlag<F extends ListFlag<BlockTypeWrapper, F>>
extends ListFlag<BlockTypeWrapper, F> {
@ -73,11 +72,9 @@ public abstract class BlockTypeListFlag<F extends ListFlag<BlockTypeWrapper, F>>
public Collection<String> getTabCompletions() {
final Collection<String> tabCompletions = new ArrayList<>();
tabCompletions.addAll(
BlockType.REGISTRY.keySet().stream().map(val -> val.replace("minecraft:", ""))
.collect(Collectors.toList()));
BlockType.REGISTRY.keySet().stream().map(val -> val.replace("minecraft:", "")).toList());
tabCompletions.addAll(
BlockCategory.REGISTRY.keySet().stream().map(val -> "#" + val.replace("minecraft:", ""))
.collect(Collectors.toList()));
BlockCategory.REGISTRY.keySet().stream().map(val -> "#" + val.replace("minecraft:", "")).toList());
return tabCompletions;
}

View File

@ -76,23 +76,7 @@ public abstract class TimedFlag<T, F extends PlotFlag<TimedFlag.Timed<T>, F>>
return getValue().toString();
}
public static final class Timed<T> {
private final int interval;
private final T value;
public Timed(int interval, T value) {
this.interval = interval;
this.value = value;
}
public int getInterval() {
return interval;
}
public T getValue() {
return value;
}
public record Timed<T>(int interval, T value) {
@Override
public String toString() {

View File

@ -76,6 +76,7 @@ public class SinglePlotArea extends GridPlotWorld {
* Returns true if the given string matches the naming system used to identify single plot worlds
* e.g. -1_5 represents plot id *;-1;5. "*" being the plot area name given to single plot world
* {@link com.plotsquared.core.plot.PlotArea}.
*
* @since 6.1.4
*/
public static boolean isSinglePlotWorld(String worldName) {
@ -193,17 +194,6 @@ public class SinglePlotArea extends GridPlotWorld {
} catch (final Exception e) {
e.printStackTrace();
}
// String worldName = plot.getWorldName();
// World world = Bukkit.getWorld(worldName);
// if (world != null) {
// return world;
// }
// WorldCreator wc = new WorldCreator(worldName);
// wc.generator("PlotSquared:single");
// wc.environment(World.Environment.NORMAL);
// wc.type(WorldType.FLAT);
// return AsyncWorld.create(wc);
}

View File

@ -36,7 +36,7 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* The min and max points of this queue are offset according to the minimum point given in the constructor, and the offsets set
* in {@link BlockArrayCacheScopedQueueCoordinator#setOffsetX(int)} and
* {@link BlockArrayCacheScopedQueueCoordinator#setOffsetZ(int)}
*
* <p>
* Internal use only. Subject to change at any time and created for specific use cases.
*/
@NotPublic
@ -54,6 +54,7 @@ public class BlockArrayCacheScopedQueueCoordinator extends ZeroedDelegateScopedQ
private final int scopeMaxZ;
private int offsetX = 0;
private int offsetZ = 0;
/**
* Construct a new instance
*

View File

@ -29,6 +29,7 @@ public abstract class ChunkCoordinator implements Runnable {
/**
* Cancel the chunk coordinator.
*
* @since 6.0.10
*/
public abstract void cancel();

View File

@ -41,9 +41,6 @@ public class ZeroedDelegateScopedQueueCoordinator extends DelegateQueueCoordinat
private final int minX;
private final int minZ;
private final int maxX;
private final int maxZ;
private final int dx;
private final int dz;
@ -59,11 +56,8 @@ public class ZeroedDelegateScopedQueueCoordinator extends DelegateQueueCoordinat
this.minX = min.getX();
this.minZ = min.getZ();
this.maxX = max.getX();
this.maxZ = max.getZ();
this.dx = maxX - minX;
this.dz = maxZ - minZ;
this.dx = max.getX() - minX;
this.dz = max.getZ() - minZ;
}
@Override

View File

@ -36,6 +36,7 @@ import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
import org.checkerframework.checker.nullness.qual.NonNull;
import javax.annotation.Nullable;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
/**
@ -92,11 +93,7 @@ public class DefaultProgressSubscriber implements ProgressSubscriber {
this.actor = actor;
this.interval = TaskTime.ms(interval);
this.wait = TaskTime.ms(wait);
if (caption == null) {
this.caption = TranslatableCaption.of("working.progress");
} else {
this.caption = caption;
}
this.caption = Objects.requireNonNullElse(caption, TranslatableCaption.of("working.progress"));
}
@Override

View File

@ -40,13 +40,7 @@ public interface AutoService extends Service<AutoService.AutoQuery, List<Plot>>
.expireAfterWrite(20, TimeUnit.SECONDS).build();
Object plotLock = new Object();
final class AutoQuery {
private final PlotPlayer<?> player;
private final PlotId startId;
private final int sizeX;
private final int sizeZ;
private final PlotArea plotArea;
record AutoQuery(PlotPlayer<?> player, PlotId startId, int sizeX, int sizeZ, PlotArea plotArea) {
/**
* Crate a new auto query
@ -73,7 +67,8 @@ public interface AutoService extends Service<AutoService.AutoQuery, List<Plot>>
*
* @return Player
*/
public @NonNull PlotPlayer<?> getPlayer() {
@Override
public @NonNull PlotPlayer<?> player() {
return this.player;
}
@ -82,7 +77,8 @@ public interface AutoService extends Service<AutoService.AutoQuery, List<Plot>>
*
* @return Start ID
*/
public @Nullable PlotId getStartId() {
@Override
public @Nullable PlotId startId() {
return this.startId;
}
@ -91,7 +87,8 @@ public interface AutoService extends Service<AutoService.AutoQuery, List<Plot>>
*
* @return Number of plots along the X axis
*/
public int getSizeX() {
@Override
public int sizeX() {
return this.sizeX;
}
@ -100,7 +97,8 @@ public interface AutoService extends Service<AutoService.AutoQuery, List<Plot>>
*
* @return Number of plots along the Z axis
*/
public int getSizeZ() {
@Override
public int sizeZ() {
return this.sizeZ;
}
@ -109,7 +107,8 @@ public interface AutoService extends Service<AutoService.AutoQuery, List<Plot>>
*
* @return Plot area
*/
public @NonNull PlotArea getPlotArea() {
@Override
public @NonNull PlotArea plotArea() {
return this.plotArea;
}
@ -132,10 +131,10 @@ public interface AutoService extends Service<AutoService.AutoQuery, List<Plot>>
@Override
public List<Plot> handle(@NonNull AutoQuery autoQuery) {
Plot plot;
PlotId nextId = autoQuery.getStartId();
PlotId nextId = autoQuery.startId();
do {
synchronized (plotLock) {
plot = autoQuery.getPlotArea().getNextFreePlot(autoQuery.getPlayer(), nextId);
plot = autoQuery.plotArea().getNextFreePlot(autoQuery.player(), nextId);
if (plot != null && plotCandidateCache.getIfPresent(plot.getId()) == null) {
plotCandidateCache.put(plot.getId(), plot);
return Collections.singletonList(plot);
@ -166,14 +165,14 @@ public interface AutoService extends Service<AutoService.AutoQuery, List<Plot>>
while (true) {
synchronized (plotLock) {
final PlotId start =
autoQuery.getPlotArea().getMeta("lastPlot", PlotId.of(0, 0)).getNextId();
autoQuery.plotArea().getMeta("lastPlot", PlotId.of(0, 0)).getNextId();
final PlotId end = PlotId.of(
start.getX() + autoQuery.getSizeX() - 1,
start.getY() + autoQuery.getSizeZ() - 1
start.getX() + autoQuery.sizeX() - 1,
start.getY() + autoQuery.sizeZ() - 1
);
final List<Plot> plots =
autoQuery.getPlotArea().canClaim(autoQuery.getPlayer(), start, end);
autoQuery.getPlotArea().setMeta("lastPlot", start); // set entry point for next try
autoQuery.plotArea().canClaim(autoQuery.player(), start, end);
autoQuery.plotArea().setMeta("lastPlot", start); // set entry point for next try
if (plots != null && !plots.isEmpty()) {
for (final Plot plot : plots) {
if (plotCandidateCache.getIfPresent(plot.getId()) != null) {
@ -189,7 +188,7 @@ public interface AutoService extends Service<AutoService.AutoQuery, List<Plot>>
@Override
public boolean test(final @NonNull AutoQuery autoQuery) {
return autoQuery.getPlotArea().getType() != PlotAreaType.PARTIAL;
return autoQuery.plotArea().getType() != PlotAreaType.PARTIAL;
}
}

View File

@ -72,7 +72,7 @@ public enum CommonSetupSteps implements SetupStep {
@Override
public SetupStep handleInput(PlotPlayer<?> plotPlayer, PlotAreaBuilder builder, String arg) {
Optional<PlotAreaType> plotAreaType = PlotAreaType.fromString(arg);
if (!plotAreaType.isPresent()) {
if (plotAreaType.isEmpty()) {
plotPlayer.sendMessage(TranslatableCaption.of("setup.setup_world_type_error"));
return this;
}
@ -180,8 +180,7 @@ public enum CommonSetupSteps implements SetupStep {
@Override
public SetupStep handleInput(PlotPlayer<?> plotPlayer, PlotAreaBuilder builder, String argument) {
Optional<PlotAreaTerrainType> optTerrain;
if (!(optTerrain = PlotAreaTerrainType.fromString(argument))
.isPresent()) {
if ((optTerrain = PlotAreaTerrainType.fromString(argument)).isEmpty()) {
plotPlayer.sendMessage(TranslatableCaption.of("setup.setup_partial_area_error"));
return this;
}

View File

@ -48,10 +48,10 @@ public class SettingsNodeStep implements SetupStep {
) {
this.configurationNode = configurationNode;
this.id = id;
if (wrapper.getSettingsNodes().length > id + 1) {
this.next = new SettingsNodeStep(wrapper.getSettingsNodes()[id + 1], id + 1, wrapper);
if (wrapper.settingsNodes().length > id + 1) {
this.next = new SettingsNodeStep(wrapper.settingsNodes()[id + 1], id + 1, wrapper);
} else {
this.next = wrapper.getAfterwards();
this.next = wrapper.afterwards();
}
}

View File

@ -23,15 +23,7 @@ import com.plotsquared.core.configuration.ConfigurationNode;
/**
* This class wraps an array of {@link ConfigurationNode}s.
*/
public class SettingsNodesWrapper {
private final ConfigurationNode[] settingsNodes;
private final SetupStep afterwards;
public SettingsNodesWrapper(final ConfigurationNode[] settingsNodes, final SetupStep afterwards) {
this.settingsNodes = settingsNodes;
this.afterwards = afterwards;
}
public record SettingsNodesWrapper(ConfigurationNode[] settingsNodes, SetupStep afterwards) {
/**
* Returns the first step of this wrapper or the step or the
@ -43,12 +35,4 @@ public class SettingsNodesWrapper {
return this.settingsNodes.length == 0 ? this.afterwards : new SettingsNodeStep(this.settingsNodes[0], 0, this);
}
public ConfigurationNode[] getSettingsNodes() {
return this.settingsNodes;
}
public SetupStep getAfterwards() {
return this.afterwards;
}
}

View File

@ -65,9 +65,9 @@ public final class LockRepository {
* @param runnable Action to run when the lock is available
*/
public void useLock(final @NonNull LockKey key, final @NonNull Runnable runnable) {
try (LockAccess ignored = lock(key)) {
runnable.run();
}
try (LockAccess ignored = lock(key)) {
runnable.run();
}
}
/**

View File

@ -31,8 +31,6 @@ import com.sk89q.worldedit.world.registry.LegacyMapper;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.Map;
/**
* {@link BlockState} related utility methods
*/
@ -109,34 +107,4 @@ public final class BlockUtil {
}
}
/**
* Parse a comma delimited list of block states
*
* @param commaDelimited List of block states
* @return Parsed block states
*/
public static @NonNull BlockState[] parse(final @NonNull String commaDelimited) {
final String[] split = commaDelimited.split(",(?![^\\(\\[]*[\\]\\)])");
final BlockState[] result = new BlockState[split.length];
for (int i = 0; i < split.length; i++) {
result[i] = get(split[i]);
}
return result;
}
/**
* Deserialize a serialized {@link BlockState}
*
* @param map Serialized block state
* @return Deserialized block state, or {@code null} if the map is
* not a properly serialized block state
*/
public static @Nullable BlockState deserialize(final @NonNull Map<String, Object> map) {
if (map.containsKey("material")) {
final Object object = map.get("material");
return get(object.toString());
}
return null;
}
}

View File

@ -18,10 +18,6 @@
*/
package com.plotsquared.core.util;
import com.plotsquared.core.location.Location;
import com.sk89q.worldedit.math.BlockVector2;
import org.checkerframework.checker.nullness.qual.NonNull;
/**
* This cache is used for world generation and just saves a bit of calculation time when checking if something is in the plot area.
*/
@ -107,22 +103,4 @@ public class ChunkUtil {
return z_loc[j];
}
/**
* Returns true if the region pos1-pos2 contains the chunk
*
* @param pos1 Region minimum point
* @param pos2 Region maximum point
* @param chunk BlockVector2 of chunk coordinates
* @return {@code true} if the region pos1-pos2 contains the chunk
*/
public static boolean isWholeChunk(@NonNull Location pos1, @NonNull Location pos2, @NonNull BlockVector2 chunk) {
int x1 = pos1.getX();
int z1 = pos1.getZ();
int x2 = pos2.getX();
int z2 = pos2.getZ();
int cx = chunk.getX() << 4;
int cz = chunk.getZ() << 4;
return cx > x1 && cz > z1 && cx < x2 && cz < z2;
}
}

View File

@ -42,27 +42,15 @@ public class EntityUtil {
}
private static int capNumeral(final @NonNull String flagName) {
int i;
switch (flagName) {
case "mob-cap":
i = CAP_MOB;
break;
case "hostile-cap":
i = CAP_MONSTER;
break;
case "animal-cap":
i = CAP_ANIMAL;
break;
case "vehicle-cap":
i = CAP_VEHICLE;
break;
case "misc-cap":
i = CAP_MISC;
break;
case "entity-cap":
default:
i = CAP_ENTITY;
}
int i = switch (flagName) {
case "mob-cap" -> CAP_MOB;
case "hostile-cap" -> CAP_MONSTER;
case "animal-cap" -> CAP_ANIMAL;
case "vehicle-cap" -> CAP_VEHICLE;
case "misc-cap" -> CAP_MISC;
// "entity-cap"
default -> CAP_ENTITY;
};
return i;
}

View File

@ -18,14 +18,6 @@
*/
package com.plotsquared.core.util;
public class FileBytes {
public final String path;
public final byte[] data;
public FileBytes(String path, byte[] data) {
this.path = path;
this.data = data;
}
public record FileBytes(String path, byte[] data) {
}

View File

@ -35,8 +35,8 @@ public abstract class InventoryUtil {
* Attempts to set an item into a {@link PlotInventory} while also checking the existence of the material
*
* @param plotInventory The inventory where the item should be placed
* @param index The index where to place the item
* @param item The item to place into the inventory
* @param index The index where to place the item
* @param item The item to place into the inventory
* @return {@code true} if the item could be placed, {@code false} otherwise (e.g. item not available in current version)
* @since 6.5.0
*/
@ -49,12 +49,14 @@ public abstract class InventoryUtil {
* Attempts to set an item into a {@link PlotInventory}
*
* @param plotInventory The inventory where the item should be placed
* @param index The index where to place the item
* @param item The item to place into the inventory
* @param index The index where to place the item
* @param item The item to place into the inventory
* @see #setItemChecked(PlotInventory, int, PlotItemStack)
*/
public void setItem(final PlotInventory plotInventory, final int index,
final PlotItemStack item) {
public void setItem(
final PlotInventory plotInventory, final int index,
final PlotItemStack item
) {
setItemChecked(plotInventory, index, item);
}

View File

@ -56,7 +56,7 @@ public final class ItemUtil {
return ItemTypes.get(input);
}
public static final ItemType[] parse(String commaDelimited) {
public static ItemType[] parse(String commaDelimited) {
String[] split = commaDelimited.split(",(?![^\\(\\[]*[\\]\\)])");
ItemType[] result = new ItemType[split.length];
for (int i = 0; i < split.length; i++) {

View File

@ -20,49 +20,14 @@ package com.plotsquared.core.util;
public class MathMan {
private static final int ATAN2_BITS = 7;
private static final int ATAN2_BITS2 = ATAN2_BITS << 1;
private static final int ATAN2_MASK = ~(-1 << ATAN2_BITS2);
private static final int ATAN2_COUNT = ATAN2_MASK + 1;
private static final int ATAN2_DIM = (int) Math.sqrt(ATAN2_COUNT);
private static final float INV_ATAN2_DIM_MINUS_1 = 1.0f / (ATAN2_DIM - 1);
private static final float[] atan2 = new float[ATAN2_COUNT];
private static final int[] table =
{0, 16, 22, 27, 32, 35, 39, 42, 45, 48, 50, 53, 55, 57, 59, 61, 64, 65, 67, 69, 71, 73, 75,
76, 78, 80, 81, 83, 84, 86, 87, 89, 90, 91, 93, 94, 96, 97, 98, 99, 101, 102, 103, 104,
106, 107, 108, 109, 110, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123,
124, 125, 126, 128, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140,
141, 142, 143, 144, 144, 145, 146, 147, 148, 149, 150, 150, 151, 152, 153, 154, 155,
155, 156, 157, 158, 159, 160, 160, 161, 162, 163, 163, 164, 165, 166, 167, 167, 168,
169, 170, 170, 171, 172, 173, 173, 174, 175, 176, 176, 177, 178, 178, 179, 180, 181,
181, 182, 183, 183, 184, 185, 185, 186, 187, 187, 188, 189, 189, 190, 191, 192, 192,
193, 193, 194, 195, 195, 196, 197, 197, 198, 199, 199, 200, 201, 201, 202, 203, 203,
204, 204, 205, 206, 206, 207, 208, 208, 209, 209, 210, 211, 211, 212, 212, 213, 214,
214, 215, 215, 216, 217, 217, 218, 218, 219, 219, 220, 221, 221, 222, 222, 223, 224,
224, 225, 225, 226, 226, 227, 227, 228, 229, 229, 230, 230, 231, 231, 232, 232, 233,
234, 234, 235, 235, 236, 236, 237, 237, 238, 238, 239, 240, 240, 241, 241, 242, 242,
243, 243, 244, 244, 245, 245, 246, 246, 247, 247, 248, 248, 249, 249, 250, 250, 251,
251, 252, 252, 253, 253, 254, 254, 255};
static {
for (int i = 0; i < ATAN2_DIM; i++) {
for (int j = 0; j < ATAN2_DIM; j++) {
float x0 = (float) i / ATAN2_DIM;
float y0 = (float) j / ATAN2_DIM;
atan2[(j * ATAN2_DIM) + i] = (float) Math.atan2(y0, x0);
}
}
}
public static final int gcd(int a, int b) {
public static int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static final int gcd(int[] a) {
public static int gcd(int[] a) {
int result = a[0];
for (int i = 1; i < a.length; i++) {
result = gcd(result, a[i]);
@ -70,103 +35,6 @@ public class MathMan {
return result;
}
public static long pairInt(int x, int y) {
return (((long) x) << 32) | (y & 0xffffffffL);
}
public static int unpairIntX(long pair) {
return (int) (pair >> 32);
}
public static int unpairIntY(long pair) {
return (int) pair;
}
public static byte pair16(byte x, byte y) {
return (byte) (x + (y << 4));
}
public static byte unpair16x(byte value) {
return (byte) (value & 0xF);
}
public static byte unpair16y(byte value) {
return (byte) ((value >> 4) & 0xF);
}
public static long inverseRound(double val) {
long round = Math.round(val);
return (long) (round + Math.signum(val - round));
}
public static int sqrt(int x) {
int xn;
if (x >= 0x10000) {
if (x >= 0x1000000) {
if (x >= 0x10000000) {
if (x >= 0x40000000) {
xn = table[x >> 24] << 8;
} else {
xn = table[x >> 22] << 7;
}
} else {
if (x >= 0x4000000) {
xn = table[x >> 20] << 6;
} else {
xn = table[x >> 18] << 5;
}
}
xn = (xn + 1 + (x / xn)) >> 1;
xn = (xn + 1 + (x / xn)) >> 1;
return ((xn * xn) > x) ? --xn : xn;
} else {
if (x >= 0x100000) {
if (x >= 0x400000) {
xn = table[x >> 16] << 4;
} else {
xn = table[x >> 14] << 3;
}
} else {
if (x >= 0x40000) {
xn = table[x >> 12] << 2;
} else {
xn = table[x >> 10] << 1;
}
}
xn = (xn + 1 + (x / xn)) >> 1;
return ((xn * xn) > x) ? --xn : xn;
}
} else {
if (x >= 0x100) {
if (x >= 0x1000) {
if (x >= 0x4000) {
xn = (table[x >> 8]) + 1;
} else {
xn = (table[x >> 6] >> 1) + 1;
}
} else {
if (x >= 0x400) {
xn = (table[x >> 4] >> 2) + 1;
} else {
xn = (table[x >> 2] >> 3) + 1;
}
}
return ((xn * xn) > x) ? --xn : xn;
} else {
if (x >= 0) {
return table[x] >> 4;
}
}
}
throw new IllegalArgumentException("Invalid number:" + x);
}
public static double getMean(int[] array) {
double count = 0;
for (int i : array) {
@ -175,121 +43,18 @@ public class MathMan {
return count / array.length;
}
public static double getMean(double[] array) {
double count = 0;
for (double i : array) {
count += i;
}
return count / array.length;
}
public static int pair(short x, short y) {
return (x << 16) | (y & 0xFFFF);
}
public static final int average(int a, int b) {
public static int average(int a, int b) {
return (a & b) + (a ^ b) / 2;
}
public static short unpairX(int hash) {
return (short) (hash >> 16);
}
public static short unpairY(int hash) {
return (short) (hash & 0xFFFF);
}
/**
* get the x,y,z unit vector from pitch and yaw specified
*
* @param yaw yaw
* @param pitch pitch
* @return x, y, z unit vector
*/
public static float[] getDirection(float yaw, float pitch) {
double pitch_sin = Math.sin(pitch);
return new float[]{(float) (pitch_sin * Math.cos(yaw)),
(float) (pitch_sin * Math.sin(yaw)), (float) Math.cos(pitch)};
}
public static int floorMod(int x, int y) {
int i = x % y;
if (i < 0) {
i += y;
}
return i;
}
public static int roundInt(double value) {
return (int) (value < 0 ? (value == (int) value) ? value : value - 1 : value);
}
/**
* Returns [ pitch, yaw ]
*
* @param x x
* @param y y
* @param z z
* @return pitch and yaw of x,y,z from 0,0,0
*/
public static float[] getPitchAndYaw(float x, float y, float z) {
float distance = sqrtApprox((z * z) + (x * x));
return new float[]{atan2(y, distance), atan2(x, z)};
}
public static final float atan2(float y, float x) {
float add;
float mul;
if (x < 0.0f) {
if (y < 0.0f) {
x = -x;
y = -y;
mul = 1.0f;
} else {
x = -x;
mul = -1.0f;
}
add = -3.141592653f;
} else {
if (y < 0.0f) {
y = -y;
mul = -1.0f;
} else {
mul = 1.0f;
}
add = 0.0f;
}
float invDiv = 1.0f / (((x < y) ? y : x) * INV_ATAN2_DIM_MINUS_1);
int xi = (int) (x * invDiv);
int yi = (int) (y * invDiv);
return (atan2[(yi * ATAN2_DIM) + xi] + add) * mul;
}
public static float sqrtApprox(float f) {
return f * Float.intBitsToFloat(0x5f375a86 - (Float.floatToIntBits(f) >> 1));
}
public static double sqrtApprox(double d) {
return Double
.longBitsToDouble(((Double.doubleToLongBits(d) - (1L << 52)) >> 1) + (1L << 61));
}
public static float invSqrt(float x) {
float xhalf = 0.5f * x;
int i = Float.floatToIntBits(x);
i = 0x5f3759df - (i >> 1);
x = Float.intBitsToFloat(i);
x = x * (1.5f - (xhalf * x * x));
return x;
}
public static int getPositiveId(int i) {
if (i < 0) {
return (-i * 2) - 1;
@ -321,14 +86,6 @@ public class MathMan {
return true;
}
public static double getSD(double[] array, double av) {
double sd = 0;
for (double element : array) {
sd += Math.pow(Math.abs(element - av), 2);
}
return Math.sqrt(sd / array.length);
}
public static double getSD(int[] array, double av) {
double sd = 0;
for (int element : array) {
@ -337,22 +94,4 @@ public class MathMan {
return Math.sqrt(sd / array.length);
}
public static int mod(int x, int y) {
if (isPowerOfTwo(y)) {
return x & (y - 1);
}
return x % y;
}
public static int unsignedmod(int x, int y) {
if (isPowerOfTwo(y)) {
return x & (y - 1);
}
return x % y;
}
public static boolean isPowerOfTwo(int number) {
return (number & (number - 1)) == 0;
}
}

View File

@ -98,7 +98,7 @@ public abstract class PlayerManager<P extends PlotPlayer<? extends T>, T> {
consumer.accept(null, throwable);
} else {
for (final UUIDMapping uuid : uuids) {
result.add(uuid.getUuid());
result.add(uuid.uuid());
}
consumer.accept(result, null);
}
@ -136,7 +136,7 @@ public abstract class PlayerManager<P extends PlotPlayer<? extends T>, T> {
try {
for (final UUIDMapping mapping : PlotSquared.get().getImpromptuUUIDPipeline()
.getNames(players).get(Settings.UUID.BLOCKING_TIMEOUT, TimeUnit.MILLISECONDS)) {
users.add(Component.text(mapping.getUsername()));
users.add(Component.text(mapping.username()));
}
} catch (final Exception e) {
e.printStackTrace();
@ -200,7 +200,7 @@ public abstract class PlayerManager<P extends PlotPlayer<? extends T>, T> {
final UUIDMapping uuidMapping =
PlotSquared.get().getImpromptuUUIDPipeline().getImmediately(owner);
if (uuidMapping != null) {
name = uuidMapping.getUsername();
name = uuidMapping.username();
} else {
name = null;
}

View File

@ -272,7 +272,8 @@ public abstract class RegionManager {
fromQueue1.addReadChunks(new CuboidRegion(pos1.getBlockVector3(), pos2.getBlockVector3()).getChunks());
fromQueue2.addReadChunks(new CuboidRegion(
swapPos.getBlockVector3(),
BlockVector3.at(swapPos.getX() + pos2.getX() - pos1.getX(),
BlockVector3.at(
swapPos.getX() + pos2.getX() - pos1.getX(),
pos1.getY(),
swapPos.getZ() + pos2.getZ() - pos1.getZ()
)

View File

@ -19,12 +19,10 @@
package com.plotsquared.core.util;
import com.plotsquared.core.location.Location;
import com.sk89q.worldedit.math.BlockVector2;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.CuboidRegion;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.awt.geom.Rectangle2D;
import java.util.Collection;
import java.util.Iterator;
@ -90,12 +88,6 @@ public class RegionUtil {
.getY() && y <= max.getY();
}
public static @NonNull Rectangle2D toRectangle(final @NonNull CuboidRegion region) {
final BlockVector2 min = region.getMinimumPoint().toBlockVector2();
final BlockVector2 max = region.getMaximumPoint().toBlockVector2();
return new Rectangle2D.Double(min.getX(), min.getZ(), max.getX(), max.getZ());
}
// Because WorldEdit (not FastAsyncWorldEdit) lack this for CuboidRegion
public static boolean intersects(CuboidRegion region, CuboidRegion other) {
BlockVector3 regionMin = region.getMinimumPoint();

View File

@ -429,9 +429,7 @@ public abstract class SchematicHandler {
if (parent.exists()) {
final String[] rawNames = parent.list((dir, name) -> name.endsWith(".schematic") || name.endsWith(".schem"));
if (rawNames != null) {
final List<String> transformed = Arrays.stream(rawNames)
//.map(rawName -> rawName.substring(0, rawName.length() - 10))
.collect(Collectors.toList());
final List<String> transformed = Arrays.stream(rawNames).toList();
names.addAll(transformed);
}
}
@ -727,10 +725,7 @@ public abstract class SchematicHandler {
}
BaseBlock block = aabb.getWorld().getFullBlock(point);
if (block.getNbtData() != null) {
Map<String, Tag> values = new HashMap<>();
for (Map.Entry<String, Tag> entry : block.getNbtData().getValue().entrySet()) {
values.put(entry.getKey(), entry.getValue());
}
Map<String, Tag> values = new HashMap<>(block.getNbtData().getValue());
// Positions are kept in NBT, we don't want that.
values.remove("x");

View File

@ -18,19 +18,13 @@
*/
package com.plotsquared.core.util;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.caption.Caption;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Pattern;
@ -39,27 +33,6 @@ public class StringMan {
// Stolen from https://stackoverflow.com/a/366532/12620913 | Debug: https://regex101.com/r/DudJLb/1
private static final Pattern STRING_SPLIT_PATTERN = Pattern.compile("[^\\s\"]+|\"([^\"]*)\"");
public static String replaceFromMap(String string, Map<String, String> replacements) {
StringBuilder sb = new StringBuilder(string);
int size = string.length();
for (Entry<String, String> entry : replacements.entrySet()) {
if (size == 0) {
break;
}
String key = entry.getKey();
String value = entry.getValue();
int start = sb.indexOf(key, 0);
while (start > -1) {
int end = start + key.length();
int nextSearchStart = start + value.length();
sb.replace(start, end, value);
size -= end - start;
start = sb.indexOf(key, nextSearchStart);
}
}
return sb.toString();
}
public static int intersection(Set<String> options, String[] toCheck) {
int count = 0;
for (String check : toCheck) {
@ -70,91 +43,6 @@ public class StringMan {
return count;
}
public static String getString(Object obj) {
if (obj == null) {
return "null";
}
if (obj instanceof String) {
return (String) obj;
}
if (obj instanceof Caption) {
return ((Caption) obj).getComponent(PlotSquared.platform());
}
if (obj.getClass().isArray()) {
StringBuilder result = new StringBuilder();
String prefix = "";
for (int i = 0; i < Array.getLength(obj); i++) {
result.append(prefix).append(getString(Array.get(obj, i)));
prefix = ",";
}
return "( " + result + " )";
} else if (obj instanceof Collection<?>) {
StringBuilder result = new StringBuilder();
String prefix = "";
for (Object element : (Collection<?>) obj) {
result.append(prefix).append(getString(element));
prefix = ",";
}
return "[ " + result + " ]";
} else {
return obj.toString();
}
}
public static String replaceFirst(char c, String s) {
if (s == null) {
return "";
}
if (s.isEmpty()) {
return s;
}
char[] chars = s.toCharArray();
char[] newChars = new char[chars.length];
int used = 0;
boolean found = false;
for (char cc : chars) {
if (!found && (c == cc)) {
found = true;
} else {
newChars[used++] = cc;
}
}
if (found) {
chars = new char[newChars.length - 1];
System.arraycopy(newChars, 0, chars, 0, chars.length);
return String.valueOf(chars);
}
return s;
}
public static String replaceAll(String string, Object... pairs) {
StringBuilder sb = new StringBuilder(string);
for (int i = 0; i < pairs.length; i += 2) {
String key = pairs[i] + "";
String value = pairs[i + 1] + "";
int start = sb.indexOf(key, 0);
while (start > -1) {
int end = start + key.length();
int nextSearchStart = start + value.length();
sb.replace(start, end, value);
start = sb.indexOf(key, nextSearchStart);
}
}
return sb.toString();
}
public static boolean isAlphanumeric(String str) {
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if ((c < 0x30) || ((c >= 0x3a) && (c <= 0x40)) || ((c > 0x5a) && (c <= 0x60)) || (c
> 0x7a)) {
return false;
}
}
return true;
}
public static boolean isAlphanumericUnd(String str) {
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
@ -165,16 +53,6 @@ public class StringMan {
return true;
}
public static boolean isAlpha(String str) {
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if ((c <= 0x40) || ((c > 0x5a) && (c <= 0x60)) || (c > 0x7a)) {
return false;
}
}
return true;
}
public static String join(Collection<?> collection, String delimiter) {
return join(collection.toArray(), delimiter);
}
@ -185,23 +63,6 @@ public class StringMan {
return join(array, delimiter);
}
public static String join(Collection<?> collection, char delimiter) {
return join(collection.toArray(), delimiter + "");
}
public static boolean isAsciiPrintable(char c) {
return (c >= ' ') && (c < '');
}
public static boolean isAsciiPrintable(String s) {
for (char c : s.toCharArray()) {
if (!isAsciiPrintable(c)) {
return false;
}
}
return true;
}
public static int getLevenshteinDistance(String s, String t) {
int n = s.length();
int m = t.length();
@ -249,23 +110,6 @@ public class StringMan {
return result.toString();
}
public static String join(int[] array, String delimiter) {
Integer[] wrapped = new Integer[array.length];
for (int i = 0; i < array.length; i++) {
wrapped[i] = array[i];
}
return join(wrapped, delimiter);
}
public static boolean isEqualToAny(String a, String... args) {
for (String arg : args) {
if (StringMan.isEqual(a, arg)) {
return true;
}
}
return false;
}
public static boolean isEqualIgnoreCaseToAny(@NonNull String a, String... args) {
for (String arg : args) {
if (a.equalsIgnoreCase(arg)) {
@ -284,39 +128,8 @@ public class StringMan {
return a.equals(b);
}
public static boolean isEqualIgnoreCase(String a, String b) {
return a.equals(b) || ((a != null) && (b != null) && (a.length() == b.length()) && a
.equalsIgnoreCase(b));
}
public static String repeat(String s, int n) {
StringBuilder sb = new StringBuilder();
sb.append(String.valueOf(s).repeat(Math.max(0, n)));
return sb.toString();
}
public static boolean contains(String name, char c) {
for (char current : name.toCharArray()) {
if (c == current) {
return true;
}
}
return false;
}
public <T> Collection<T> match(Collection<T> col, String startsWith) {
if (col == null) {
return null;
}
startsWith = startsWith.toLowerCase();
Iterator<?> iterator = col.iterator();
while (iterator.hasNext()) {
Object item = iterator.next();
if (item == null || !item.toString().toLowerCase().startsWith(startsWith)) {
iterator.remove();
}
}
return col;
return String.valueOf(s).repeat(Math.max(0, n));
}
/**

View File

@ -238,8 +238,8 @@ public final class TabCompletions {
PlotSquared.get().getImpromptuUUIDPipeline().getAllImmediately();
players = new ArrayList<>(mappings.size());
for (final UUIDMapping mapping : mappings) {
if (uuidFilter.test(mapping.getUuid())) {
players.add(mapping.getUsername());
if (uuidFilter.test(mapping.uuid())) {
players.add(mapping.username());
}
}
cachedCompletionValues.put(cacheIdentifier, players);

View File

@ -92,23 +92,23 @@ public final class TimeUtil {
case "wks":
case "w":
time += 604800 * numbers;
time += 604800L * numbers;
case "days":
case "day":
case "d":
time += 86400 * numbers;
time += 86400L * numbers;
case "hour":
case "hr":
case "hrs":
case "hours":
case "h":
time += 3600 * numbers;
time += 3600L * numbers;
case "minutes":
case "minute":
case "mins":
case "min":
case "m":
time += 60 * numbers;
time += 60L * numbers;
case "seconds":
case "second":
case "secs":

View File

@ -58,29 +58,6 @@ public class WEManager {
return false;
}
public static boolean maskContains(Set<CuboidRegion> mask, double dx, double dy, double dz) {
int x = Math.toIntExact(Math.round(dx >= 0 ? dx - 0.5 : dx + 0.5));
int y = Math.toIntExact(Math.round(dy - 0.5));
int z = Math.toIntExact(Math.round(dz >= 0 ? dz - 0.5 : dz + 0.5));
for (CuboidRegion region : mask) {
if (RegionUtil.contains(region, x, y, z)) {
return true;
}
}
return false;
}
public static boolean maskContains(Set<CuboidRegion> mask, double dx, double dz) {
int x = Math.toIntExact(Math.round(dx >= 0 ? dx - 0.5 : dx + 0.5));
int z = Math.toIntExact(Math.round(dz >= 0 ? dz - 0.5 : dz + 0.5));
for (CuboidRegion region : mask) {
if (RegionUtil.contains(region, x, z)) {
return true;
}
}
return false;
}
public static HashSet<CuboidRegion> getMask(PlotPlayer<?> player) {
HashSet<CuboidRegion> regions = new HashSet<>();
UUID uuid = player.getUUID();
@ -116,17 +93,4 @@ public class WEManager {
return regions;
}
public static boolean intersects(CuboidRegion region1, CuboidRegion region2) {
return RegionUtil.intersects(region1, region2);
}
public static boolean regionContains(CuboidRegion selection, HashSet<CuboidRegion> mask) {
for (CuboidRegion region : mask) {
if (intersects(region, selection)) {
return true;
}
}
return false;
}
}

View File

@ -281,7 +281,8 @@ public abstract class WorldUtil {
int trz = top.getZ() >> 9;
Set<BlockVector2> files = getChunkChunks(bot.getWorldName());
for (BlockVector2 mca : files) {
if (mca.getX() >= brx && mca.getX() <= trx && mca.getZ() >= brz && mca.getZ() <= trz && !added.contains(mca)) {
if (mca.getX() >= brx && mca.getX() <= trx && mca.getZ() >= brz && mca.getZ() <= trz && !added.contains(
mca)) {
final File file = getMcr(plot.getWorldName(), mca.getX(), mca.getZ());
if (file != null) {
//final String name = "r." + (x - cx) + "." + (z - cz) + ".mca";

Some files were not shown because too many files have changed in this diff Show More