Update packages. This will not be appreciated 🐱

This commit is contained in:
sauilitired
2018-08-10 17:53:14 +02:00
parent 1646cd0f5a
commit b0348cfc34
484 changed files with 4438 additions and 4433 deletions

View File

@ -0,0 +1,401 @@
package com.github.intellectualsites.plotsquared.sponge;
import com.github.intellectualsites.plotsquared.configuration.ConfigurationSection;
import com.github.intellectualsites.plotsquared.plot.IPlotMain;
import com.github.intellectualsites.plotsquared.plot.PS;
import com.github.intellectualsites.plotsquared.plot.config.C;
import com.github.intellectualsites.plotsquared.plot.config.ConfigurationNode;
import com.github.intellectualsites.plotsquared.plot.config.Settings;
import com.github.intellectualsites.plotsquared.plot.generator.GeneratorWrapper;
import com.github.intellectualsites.plotsquared.plot.generator.HybridGen;
import com.github.intellectualsites.plotsquared.plot.generator.HybridUtils;
import com.github.intellectualsites.plotsquared.plot.generator.IndependentPlotGenerator;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotId;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.object.SetupObject;
import com.github.intellectualsites.plotsquared.plot.object.worlds.PlotAreaManager;
import com.github.intellectualsites.plotsquared.plot.object.worlds.SinglePlotArea;
import com.github.intellectualsites.plotsquared.plot.object.worlds.SinglePlotAreaManager;
import com.github.intellectualsites.plotsquared.plot.object.worlds.SingleWorldGenerator;
import com.github.intellectualsites.plotsquared.plot.util.*;
import com.github.intellectualsites.plotsquared.plot.util.block.QueueProvider;
import com.github.intellectualsites.plotsquared.plot.uuid.UUIDWrapper;
import com.github.intellectualsites.plotsquared.sponge.generator.SpongePlotGenerator;
import com.github.intellectualsites.plotsquared.sponge.listener.ChunkProcessor;
import com.github.intellectualsites.plotsquared.sponge.listener.MainListener;
import com.github.intellectualsites.plotsquared.sponge.listener.WorldEvents;
import com.github.intellectualsites.plotsquared.sponge.util.*;
import com.github.intellectualsites.plotsquared.sponge.util.block.SpongeLocalQueue;
import com.github.intellectualsites.plotsquared.sponge.uuid.SpongeLowerOfflineUUIDWrapper;
import com.github.intellectualsites.plotsquared.sponge.uuid.SpongeOnlineUUIDWrapper;
import com.github.intellectualsites.plotsquared.sponge.uuid.SpongeUUIDHandler;
import com.google.inject.Inject;
import net.minecrell.mcstats.SpongeStatsLite;
import org.slf4j.Logger;
import org.spongepowered.api.Game;
import org.spongepowered.api.Server;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.config.ConfigDir;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.game.state.GameAboutToStartServerEvent;
import org.spongepowered.api.event.game.state.GamePreInitializationEvent;
import org.spongepowered.api.plugin.Plugin;
import org.spongepowered.api.plugin.PluginContainer;
import org.spongepowered.api.profile.GameProfileManager;
import org.spongepowered.api.world.Chunk;
import org.spongepowered.api.world.World;
import org.spongepowered.api.world.gen.GenerationPopulator;
import org.spongepowered.api.world.gen.WorldGenerator;
import org.spongepowered.api.world.gen.WorldGeneratorModifier;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
@Plugin(id = "plotsquared", name = "PlotSquared", description = "Easy, yet powerful Plot World generation and management.", url = "https://github.com/IntellectualSites/PlotSquared", version = "3.5.0-SNAPSHOT")
public class SpongeMain implements IPlotMain {
public static SpongeMain THIS;
@Inject public PluginContainer plugin;
@Inject public SpongeStatsLite stats;
@Inject private Logger logger;
@Inject private Game game;
private Server server;
@Inject @ConfigDir(sharedRoot = false) private Path privateConfigDir;
private GameProfileManager resolver;
private Logger getLogger() {
return this.logger;
}
public Game getGame() {
return this.game;
}
public Server getServer() {
return this.server;
}
public GameProfileManager getResolver() {
if (this.resolver == null) {
this.resolver = this.game.getServer().getGameProfileManager();
}
return this.resolver;
}
public SpongeMain getPlugin() {
return THIS;
}
@Listener public void onPreInitialize(GamePreInitializationEvent event) {
getLogger().info(
"The metrics section in PlotSquared is ignored in favor of the actual metrics reporter configurations.");
this.stats.start();
}
@Listener public void onServerAboutToStart(GameAboutToStartServerEvent event) {
THIS = this;
new PS(this, "Sponge");
this.server = this.game.getServer();
this.game.getRegistry().register(WorldGeneratorModifier.class,
(WorldGeneratorModifier) PS.get().IMP.getDefaultGenerator().specify(null));
this.game.getRegistry().register(WorldGeneratorModifier.class,
(WorldGeneratorModifier) new SingleWorldGenerator().specify(null));
if (Settings.Enabled_Components.WORLDS) {
TaskManager.IMP.taskRepeat(new Runnable() {
@Override public void run() {
unload();
}
}, 20);
}
}
public void unload() {
PlotAreaManager manager = PS.get().getPlotAreaManager();
if (manager instanceof SinglePlotAreaManager) {
SinglePlotArea area = ((SinglePlotAreaManager) manager).getArea();
for (World world : Sponge.getServer().getWorlds()) {
String name = world.getName();
PlotId id = PlotId.fromString(name);
if (id != null) {
Plot plot = area.getOwnedPlot(id);
if (plot != null) {
List<PlotPlayer> players = plot.getPlayersInPlot();
if (players.isEmpty() && PlotPlayer.wrap(plot.owner) == null) {
try {
world.save();
} catch (IOException e) {
e.printStackTrace();
return;
}
long start = System.currentTimeMillis();
for (Chunk chunk : world.getLoadedChunks()) {
chunk.unloadChunk();
if (System.currentTimeMillis() - start > 10) {
return;
}
}
Sponge.getServer().unloadWorld(world);
return;
}
}
}
}
}
}
@Override public void log(String message) {
message = C.format(message, C.replacements);
if (!Settings.Chat.CONSOLE_COLOR) {
message = message.replaceAll('\u00a7' + "[a-z|0-9]", "");
}
if (this.server == null) {
this.logger.info(message);
return;
}
this.server.getConsole().sendMessage(SpongeUtil.getText(message));
}
@Override public File getDirectory() {
return privateConfigDir.toFile();
}
@Override public File getWorldContainer() {
return new File(game.getSavesDirectory().toFile(), "world");
}
@Override public void disable() {
PS.get().disable();
THIS = null;
}
@Override public int[] getPluginVersion() {
String ver = this.plugin.getVersion().orElse("");
String[] split = ver.split("[\\.|-]");
return new int[] {Integer.parseInt(split[0]), Integer.parseInt(split[1]),
Integer.parseInt(split[2])};
}
@Override public String getPluginVersionString() {
return this.plugin.getVersion().orElse("");
}
@Override public String getPluginName() {
return "PlotSquared";
}
@Override public int[] getServerVersion() {
PS.log("Checking minecraft version: Sponge: ");
String version = this.game.getPlatform().getMinecraftVersion().getName();
String[] split = version.split("\\.");
return new int[] {Integer.parseInt(split[0]), Integer.parseInt(split[1]),
split.length == 3 ? Integer.parseInt(split[2]) : 0};
}
@Override public InventoryUtil initInventoryUtil() {
return new SpongeInventoryUtil();
}
@Override public EconHandler getEconomyHandler() {
SpongeEconHandler econ = new SpongeEconHandler();
Sponge.getEventManager().registerListeners(this, econ);
return econ;
}
@Override public EventUtil initEventUtil() {
return new SpongeEventUtil();
}
@Override public ChunkManager initChunkManager() {
return new SpongeChunkManager();
}
@Override public SetupUtils initSetupUtils() {
return new SpongeSetupUtils();
}
@Override public HybridUtils initHybridUtils() {
return new SpongeHybridUtils();
}
@Override public SchematicHandler initSchematicHandler() {
return new SpongeSchematicHandler();
}
@Override public TaskManager getTaskManager() {
return new SpongeTaskManager(this);
}
@Override public void runEntityTask() {
new KillRoadMobs().run();
}
@Override public void registerCommands() {
getGame().getCommandManager()
.register(THIS, new SpongeCommand(), "plots", "p", "plot", "ps", "plotsquared", "p2",
"2");
}
@Override public void registerPlayerEvents() {
Sponge.getEventManager().registerListeners(this, new MainListener());
}
@Override public void registerInventoryEvents() {
// Part of PlayerEvents - can be moved if necessary
}
@Override public void registerPlotPlusEvents() {
PS.log("registerPlotPlusEvents is not implemented!");
}
@Override public void registerForceFieldEvents() {
}
@Override public boolean initWorldEdit() {
try {
Class.forName("com.sk89q.worldedit.WorldEdit");
} catch (ClassNotFoundException ignored) {
return false;
}
return true;
}
@Override public UUIDHandlerImplementation initUUIDHandler() {
UUIDWrapper wrapper;
if (Settings.UUID.OFFLINE) {
wrapper = new SpongeLowerOfflineUUIDWrapper();
} else {
wrapper = new SpongeOnlineUUIDWrapper();
}
return new SpongeUUIDHandler(wrapper);
}
@Override public boolean initPlotMeConverter() {
return false;
}
@Override public void unregister(PlotPlayer player) {
SpongeUtil.removePlayer(player.getName());
}
@Override public void registerChunkProcessor() {
Sponge.getEventManager().registerListeners(this, new ChunkProcessor());
}
@Override public void registerWorldEvents() {
Sponge.getEventManager().registerListeners(this, new WorldEvents());
}
@Override public void startMetrics() {
}
@Override public void setGenerator(String worldName) {
World world = SpongeUtil.getWorld(worldName);
if (world == null) {
// create world
ConfigurationSection worldConfig =
PS.get().worlds.getConfigurationSection("worlds." + worldName);
String manager = worldConfig.getString("generator.plugin", "PlotSquared");
String generator = worldConfig.getString("generator.init", manager);
int type = worldConfig.getInt("generator.type");
int terrain = worldConfig.getInt("generator.terrain");
SetupObject setup = new SetupObject();
setup.plotManager = manager;
setup.setupGenerator = generator;
setup.type = type;
setup.terrain = terrain;
setup.step = new ConfigurationNode[0];
setup.world = worldName;
SetupUtils.manager.setupWorld(setup);
world = SpongeUtil.getWorld(worldName);
} else {
throw new IllegalArgumentException("World already loaded: " + worldName + "???");
}
WorldGenerator wg = world.getWorldGenerator();
GenerationPopulator gen = wg.getBaseGenerationPopulator();
if (gen instanceof GeneratorWrapper) {
PS.get().loadWorld(worldName, (GeneratorWrapper) gen);
} else {
throw new UnsupportedOperationException(
"NOT IMPLEMENTED YET2! " + worldName + " | " + gen);
}
}
@Override public AbstractTitle initTitleManager() {
return new SpongeTitleManager();
}
@Override public PlotPlayer wrapPlayer(Object player) {
if (player instanceof Player) {
return SpongeUtil.getPlayer((Player) player);
} else if (UUIDHandler.implementation == null) {
return null;
} else if (player instanceof String) {
return UUIDHandler.getPlayer((String) player);
} else if (player instanceof UUID) {
return UUIDHandler.getPlayer((UUID) player);
}
// TODO FIXME offline player
return null;
}
@Override public String getNMSPackage() {
return "";//TODO FIXME
}
@Override public ChatManager<?> initChatManager() {
return new SpongeChatManager();
}
@Override public QueueProvider initBlockQueue() {
MainUtil.canSendChunk = true;
return QueueProvider.of(SpongeLocalQueue.class, null);
}
@Override public WorldUtil initWorldUtil() {
return new SpongeUtil();
}
@Override public GeneratorWrapper<?> getGenerator(String world, String name) {
if (name == null) {
return null;
}
Collection<WorldGeneratorModifier> wgms =
this.game.getRegistry().getAllOf(WorldGeneratorModifier.class);
for (WorldGeneratorModifier wgm : wgms) {
if (StringMan.isEqualIgnoreCaseToAny(name, wgm.getName(), wgm.getId())) {
if (wgm instanceof GeneratorWrapper<?>) {
return (GeneratorWrapper<?>) wgm;
}
return new SpongePlotGenerator(wgm);
}
}
return new SpongePlotGenerator(PS.get().IMP.getDefaultGenerator());
}
@Override
public GeneratorWrapper<?> wrapPlotGenerator(String world, IndependentPlotGenerator generator) {
return new SpongePlotGenerator(generator);
}
@Override public List<String> getPluginIds() {
return this.game.getPluginManager().getPlugins().stream()
.map(plugin1 -> plugin1.getName() + ';' + plugin1.getVersion() + ':' + true)
.collect(Collectors.toCollection(ArrayList::new));
}
@Override public IndependentPlotGenerator getDefaultGenerator() {
return new HybridGen();
}
}

View File

@ -0,0 +1,49 @@
package com.github.intellectualsites.plotsquared.sponge.events;
import com.github.intellectualsites.plotsquared.plot.flag.Flag;
import com.github.intellectualsites.plotsquared.plot.object.PlotCluster;
import org.spongepowered.api.event.Cancellable;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.impl.AbstractEvent;
public class ClusterFlagRemoveEvent extends AbstractEvent implements Cancellable {
private final PlotCluster cluster;
private final Flag flag;
private boolean cancelled;
public ClusterFlagRemoveEvent(final Flag flag, final PlotCluster cluster) {
this.cluster = cluster;
this.flag = flag;
}
/**
* Get the cluster involved
*
* @return PlotCluster
*/
public PlotCluster getCluster() {
return cluster;
}
/**
* Get the flag involved
*
* @return Flag
*/
public Flag getFlag() {
return flag;
}
@Override public boolean isCancelled() {
return cancelled;
}
@Override public void setCancelled(final boolean cancel) {
cancelled = cancel;
}
@Override public Cause getCause() {
return null;
}
}

View File

@ -0,0 +1,53 @@
package com.github.intellectualsites.plotsquared.sponge.events;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.event.Cancellable;
import org.spongepowered.api.event.cause.Cause;
public class PlayerClaimPlotEvent extends PlayerEvent implements Cancellable {
private final Plot plot;
private final boolean auto;
private boolean cancelled;
/**
* PlayerClaimPlotEvent: Called when a plot is claimed
*
* @param player Player that claimed the plot
* @param plot Plot that was claimed
*/
public PlayerClaimPlotEvent(final Player player, final Plot plot, final boolean auto) {
super(player);
this.plot = plot;
this.auto = auto;
}
/**
* Get the plot involved
*
* @return Plot
*/
public Plot getPlot() {
return plot;
}
/**
* @return true if it was an automated claim, else false
*/
public boolean wasAuto() {
return auto;
}
@Override public boolean isCancelled() {
return cancelled;
}
@Override public void setCancelled(final boolean cancel) {
cancelled = cancel;
}
@Override public Cause getCause() {
return null;
}
}

View File

@ -0,0 +1,34 @@
package com.github.intellectualsites.plotsquared.sponge.events;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.event.cause.Cause;
public class PlayerEnterPlotEvent extends PlayerEvent {
private final Plot plot;
/**
* PlayerEnterPlotEvent: Called when a player leaves a plot
*
* @param player Player that entered the plot
* @param plot Plot that was entered
*/
public PlayerEnterPlotEvent(final Player player, final Plot plot) {
super(player);
this.plot = plot;
}
/**
* Get the plot involved
*
* @return Plot
*/
public Plot getPlot() {
return plot;
}
@Override public Cause getCause() {
return null;
}
}

View File

@ -0,0 +1,23 @@
package com.github.intellectualsites.plotsquared.sponge.events;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.impl.AbstractEvent;
public abstract class PlayerEvent extends AbstractEvent {
public final Player player;
public PlayerEvent(final Player player) {
this.player = player;
}
public Player getPlayer() {
return player;
}
@Override public Cause getCause() {
return null;
}
}

View File

@ -0,0 +1,29 @@
package com.github.intellectualsites.plotsquared.sponge.events;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import org.spongepowered.api.entity.living.player.Player;
public class PlayerLeavePlotEvent extends PlayerEvent {
private final Plot plot;
/**
* PlayerLeavePlotEvent: Called when a player leaves a plot
*
* @param player Player that left the plot
* @param plot Plot that was left
*/
public PlayerLeavePlotEvent(final Player player, final Plot plot) {
super(player);
this.plot = plot;
}
/**
* Get the plot involved
*
* @return Plot
*/
public Plot getPlot() {
return plot;
}
}

View File

@ -0,0 +1,56 @@
package com.github.intellectualsites.plotsquared.sponge.events;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import org.spongepowered.api.entity.living.player.Player;
import java.util.UUID;
public class PlayerPlotDeniedEvent extends PlotEvent {
private final Player initiator;
private final boolean added;
private final UUID player;
/**
* PlayerPlotDeniedEvent: Called when the denied UUID list is modified for a plot
*
* @param initiator Player that initiated the event
* @param plot Plot in which the event occurred
* @param player Player that was denied/un-denied
* @param added true of add to deny list, false if removed
*/
public PlayerPlotDeniedEvent(final Player initiator, final Plot plot, final UUID player,
final boolean added) {
super(plot);
this.initiator = initiator;
this.added = added;
this.player = player;
}
/**
* If a user was added
*
* @return boolean
*/
public boolean wasAdded() {
return added;
}
/**
* The player added/removed
*
* @return UUID
*/
public UUID getPlayer() {
return player;
}
/**
* The player initiating the action
*
* @return Player
*/
public Player getInitiator() {
return initiator;
}
}

View File

@ -0,0 +1,56 @@
package com.github.intellectualsites.plotsquared.sponge.events;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import org.spongepowered.api.entity.living.player.Player;
import java.util.UUID;
public class PlayerPlotHelperEvent extends PlotEvent {
private final Player initiator;
private final boolean added;
private final UUID player;
/**
* PlayerPlotHelperEvent: Called when a plot helper is added/removed
*
* @param initiator Player that initiated the event
* @param plot Plot in which the event occurred
* @param player Player that was added/removed from the helper list
* @param added true of the player was added, false if the player was removed
*/
public PlayerPlotHelperEvent(final Player initiator, final Plot plot, final UUID player,
final boolean added) {
super(plot);
this.initiator = initiator;
this.added = added;
this.player = player;
}
/**
* If a user was added
*
* @return boolean
*/
public boolean wasAdded() {
return added;
}
/**
* The player added/removed
*
* @return UUID
*/
public UUID getPlayer() {
return player;
}
/**
* The player initiating the action
*
* @return Player
*/
public Player getInitiator() {
return initiator;
}
}

View File

@ -0,0 +1,56 @@
package com.github.intellectualsites.plotsquared.sponge.events;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import org.spongepowered.api.entity.living.player.Player;
import java.util.UUID;
public class PlayerPlotTrustedEvent extends PlotEvent {
private final Player initiator;
private final boolean added;
private final UUID player;
/**
* PlayerPlotTrustedEvent: Called when a plot trusted user is added/removed
*
* @param initiator Player that initiated the event
* @param plot Plot in which the event occurred
* @param player Player that was added/removed from the trusted list
* @param added true of the player was added, false if the player was removed
*/
public PlayerPlotTrustedEvent(final Player initiator, final Plot plot, final UUID player,
final boolean added) {
super(plot);
this.initiator = initiator;
this.added = added;
this.player = player;
}
/**
* If a user was added
*
* @return boolean
*/
public boolean wasAdded() {
return added;
}
/**
* The player added/removed
*
* @return UUID
*/
public UUID getPlayer() {
return player;
}
/**
* The player initiating the action
*
* @return Player
*/
public Player getInitiator() {
return initiator;
}
}

View File

@ -0,0 +1,52 @@
package com.github.intellectualsites.plotsquared.sponge.events;
import com.github.intellectualsites.plotsquared.plot.object.Location;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.event.Cancellable;
public class PlayerTeleportToPlotEvent extends PlayerEvent implements Cancellable {
private final Location from;
private final Plot plot;
private boolean cancelled;
/**
* PlayerTeleportToPlotEvent: Called when a player teleports to a plot.
*
* @param player That was teleported
* @param from Start location
* @param plot Plot to which the player was teleported
*/
public PlayerTeleportToPlotEvent(Player player, Location from, Plot plot) {
super(player);
this.from = from;
this.plot = plot;
}
/**
* Get the from location.
*
* @return Location
*/
public Location getFrom() {
return this.from;
}
/**
* Get the plot involved.
*
* @return Plot
*/
public Plot getPlot() {
return this.plot;
}
@Override public boolean isCancelled() {
return this.cancelled;
}
@Override public void setCancelled(boolean cancel) {
this.cancelled = cancel;
}
}

View File

@ -0,0 +1,53 @@
package com.github.intellectualsites.plotsquared.sponge.events;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotId;
import org.spongepowered.api.event.Cancellable;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.impl.AbstractEvent;
public class PlotClearEvent extends AbstractEvent implements Cancellable {
private final Plot plot;
private boolean cancelled;
/**
* PlotDeleteEvent: Called when a plot is cleared
*
* @param plot The plot that was cleared
*/
public PlotClearEvent(Plot plot) {
this.plot = plot;
}
/**
* Get the PlotId.
*
* @return PlotId
*/
public PlotId getPlotId() {
return this.plot.getId();
}
/**
* Get the world name.
*
* @return String
*/
public String getWorld() {
return this.plot.getWorldName();
}
@Override public boolean isCancelled() {
return this.cancelled;
}
@Override public void setCancelled(boolean cancel) {
this.cancelled = cancel;
}
@Override public Cause getCause() {
return null;
}
}

View File

@ -0,0 +1,53 @@
package com.github.intellectualsites.plotsquared.sponge.events;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotId;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.impl.AbstractEvent;
public class PlotComponentSetEvent extends AbstractEvent {
private final Plot plot;
private final String component;
/**
* PlotDeleteEvent: Called when a plot component is set
*
* @param plot The plot
* @param component The component which was set
*/
public PlotComponentSetEvent(Plot plot, String component) {
this.plot = plot;
this.component = component;
}
/**
* Get the PlotId
*
* @return PlotId
*/
public PlotId getPlotId() {
return this.plot.getId();
}
/**
* Get the world name
*
* @return String
*/
public String getWorld() {
return this.plot.getWorldName();
}
/**
* Get the component which was set
*
* @return Component name
*/
public String getComponent() {
return this.component;
}
@Override public Cause getCause() {
return null;
}
}

View File

@ -0,0 +1,41 @@
package com.github.intellectualsites.plotsquared.sponge.events;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotId;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.impl.AbstractEvent;
public class PlotDeleteEvent extends AbstractEvent {
private final Plot plot;
/**
* PlotDeleteEvent: Called when a plot is deleted
*
* @param plot The plot that was deleted
*/
public PlotDeleteEvent(Plot plot) {
this.plot = plot;
}
/**
* Get the PlotId
*
* @return PlotId
*/
public PlotId getPlotId() {
return plot.getId();
}
/**
* Get the world name
*
* @return String
*/
public String getWorld() {
return plot.getWorldName();
}
@Override public Cause getCause() {
return null;
}
}

View File

@ -0,0 +1,23 @@
package com.github.intellectualsites.plotsquared.sponge.events;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.impl.AbstractEvent;
public abstract class PlotEvent extends AbstractEvent {
private final Plot plot;
public PlotEvent(final Plot plot) {
this.plot = plot;
}
public final Plot getPlot() {
return plot;
}
@Override public Cause getCause() {
return null;
}
}

View File

@ -0,0 +1,38 @@
package com.github.intellectualsites.plotsquared.sponge.events;
import com.github.intellectualsites.plotsquared.plot.flag.Flag;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import org.spongepowered.api.event.Cancellable;
public class PlotFlagAddEvent extends PlotEvent implements Cancellable {
private final Flag flag;
private boolean cancelled;
/**
* PlotFlagAddEvent: Called when a Flag is added to a plot
*
* @param flag Flag that was added
* @param plot Plot to which the flag was added
*/
public PlotFlagAddEvent(final Flag flag, final Plot plot) {
super(plot);
this.flag = flag;
}
/**
* Get the flag involved
*
* @return Flag
*/
public Flag getFlag() {
return flag;
}
@Override public boolean isCancelled() {
return cancelled;
}
@Override public void setCancelled(final boolean cancel) {
cancelled = cancel;
}
}

View File

@ -0,0 +1,38 @@
package com.github.intellectualsites.plotsquared.sponge.events;
import com.github.intellectualsites.plotsquared.plot.flag.Flag;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import org.spongepowered.api.event.Cancellable;
public class PlotFlagRemoveEvent extends PlotEvent implements Cancellable {
private final Flag flag;
private boolean cancelled;
/**
* PlotFlagRemoveEvent: Called when a flag is removed from a plot
*
* @param flag Flag that was removed
* @param plot Plot from which the flag was removed
*/
public PlotFlagRemoveEvent(final Flag flag, final Plot plot) {
super(plot);
this.flag = flag;
}
/**
* Get the flag involved
*
* @return Flag
*/
public Flag getFlag() {
return flag;
}
@Override public boolean isCancelled() {
return cancelled;
}
@Override public void setCancelled(final boolean cancel) {
cancelled = cancel;
}
}

View File

@ -0,0 +1,62 @@
package com.github.intellectualsites.plotsquared.sponge.events;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotId;
import org.spongepowered.api.event.Cancellable;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.impl.AbstractEvent;
import org.spongepowered.api.world.World;
import java.util.ArrayList;
public class PlotMergeEvent extends AbstractEvent implements Cancellable {
private final ArrayList<PlotId> plots;
private boolean cancelled;
private Plot plot;
private World world;
/**
* PlotMergeEvent: Called when plots are merged
*
* @param world World in which the event occurred
* @param plot Plot that was merged
* @param plots A list of plots involved in the event
*/
public PlotMergeEvent(final World world, final Plot plot, final ArrayList<PlotId> plots) {
this.plots = plots;
}
/**
* Get the plots being added;
*
* @return Plot
*/
public ArrayList<PlotId> getPlots() {
return plots;
}
/**
* Get the main plot
*
* @return Plot
*/
public Plot getPlot() {
return plot;
}
public World getWorld() {
return world;
}
@Override public boolean isCancelled() {
return cancelled;
}
@Override public void setCancelled(final boolean cancel) {
cancelled = cancel;
}
@Override public Cause getCause() {
return null;
}
}

View File

@ -0,0 +1,28 @@
package com.github.intellectualsites.plotsquared.sponge.events;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.object.Rating;
public class PlotRateEvent extends PlotEvent {
private final PlotPlayer rater;
private Rating rating;
public PlotRateEvent(final PlotPlayer rater, final Rating rating, final Plot plot) {
super(plot);
this.rater = rater;
this.rating = rating;
}
public PlotPlayer getRater() {
return rater;
}
public Rating getRating() {
return rating;
}
public void setRating(final Rating rating) {
this.rating = rating;
}
}

View File

@ -0,0 +1,51 @@
package com.github.intellectualsites.plotsquared.sponge.events;
import com.github.intellectualsites.plotsquared.plot.object.PlotId;
import org.spongepowered.api.event.Cancellable;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.impl.AbstractEvent;
import org.spongepowered.api.world.World;
import java.util.ArrayList;
public class PlotUnlinkEvent extends AbstractEvent implements Cancellable {
private final ArrayList<PlotId> plots;
private final World world;
private boolean cancelled;
/**
* Called when a mega-plot is unlinked.
*
* @param world World in which the event occurred
* @param plots Plots that are involved in the event
*/
public PlotUnlinkEvent(final World world, final ArrayList<PlotId> plots) {
this.plots = plots;
this.world = world;
}
/**
* Get the plots involved
*
* @return PlotId
*/
public ArrayList<PlotId> getPlots() {
return plots;
}
public World getWorld() {
return world;
}
@Override public boolean isCancelled() {
return cancelled;
}
@Override public void setCancelled(final boolean cancel) {
cancelled = cancel;
}
@Override public Cause getCause() {
return null;
}
}

View File

@ -0,0 +1,66 @@
package com.github.intellectualsites.plotsquared.sponge.generator;
import com.flowpowered.math.vector.Vector3i;
import com.github.intellectualsites.plotsquared.plot.generator.AugmentedUtils;
import com.github.intellectualsites.plotsquared.plot.object.PlotBlock;
import com.github.intellectualsites.plotsquared.plot.util.block.DelegateLocalBlockQueue;
import com.github.intellectualsites.plotsquared.sponge.util.SpongeUtil;
import org.spongepowered.api.block.BlockState;
import org.spongepowered.api.world.World;
import org.spongepowered.api.world.extent.ImmutableBiomeVolume;
import org.spongepowered.api.world.extent.MutableBlockVolume;
import org.spongepowered.api.world.gen.GenerationPopulator;
import org.spongepowered.api.world.gen.WorldGenerator;
import java.util.List;
public class SpongeAugmentedGenerator implements GenerationPopulator {
private static SpongeAugmentedGenerator generator;
private SpongeAugmentedGenerator() {
}
public static SpongeAugmentedGenerator get(World world) {
WorldGenerator wg = world.getWorldGenerator();
List<GenerationPopulator> populators = wg.getGenerationPopulators();
for (GenerationPopulator populator : populators) {
if (populator instanceof SpongeAugmentedGenerator) {
return (SpongeAugmentedGenerator) populator;
}
}
if (generator == null) {
generator = new SpongeAugmentedGenerator();
}
populators.add(generator);
return generator;
}
@Override
public void populate(World world, MutableBlockVolume terrain, ImmutableBiomeVolume biome) {
Vector3i min = terrain.getBlockMin();
int bx = min.getX();
int bz = min.getZ();
int cx = bx >> 4;
int cz = bz >> 4;
AugmentedUtils.generate(world.getName(), cx, cz, new DelegateLocalBlockQueue(null) {
@Override public boolean setBlock(int x, int y, int z, int id, int data) {
terrain.setBlock(bx + x, y, bz + z, SpongeUtil.getBlockState(id, data));
return true;
}
@Override public PlotBlock getBlock(int x, int y, int z) {
BlockState block = terrain.getBlock(bx + x, y, bz + z);
return SpongeUtil.getPlotBlock(block);
}
@Override public boolean setBiome(int x, int z, String biome) {
return false; // TODO ?
}
@Override public String getWorld() {
return world.getName();
}
});
}
}

View File

@ -0,0 +1,116 @@
package com.github.intellectualsites.plotsquared.sponge.generator;
import com.flowpowered.math.vector.Vector3i;
import com.github.intellectualsites.plotsquared.plot.PS;
import com.github.intellectualsites.plotsquared.plot.generator.GeneratorWrapper;
import com.github.intellectualsites.plotsquared.plot.generator.IndependentPlotGenerator;
import com.github.intellectualsites.plotsquared.plot.object.PlotArea;
import com.github.intellectualsites.plotsquared.plot.object.PlotManager;
import com.github.intellectualsites.plotsquared.plot.util.MainUtil;
import com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils;
import com.github.intellectualsites.plotsquared.sponge.util.SpongeUtil;
import org.spongepowered.api.data.DataContainer;
import org.spongepowered.api.world.biome.BiomeGenerationSettings;
import org.spongepowered.api.world.biome.BiomeType;
import org.spongepowered.api.world.biome.BiomeTypes;
import org.spongepowered.api.world.extent.MutableBiomeVolume;
import org.spongepowered.api.world.gen.BiomeGenerator;
import org.spongepowered.api.world.gen.GenerationPopulator;
import org.spongepowered.api.world.gen.WorldGenerator;
import org.spongepowered.api.world.gen.WorldGeneratorModifier;
import org.spongepowered.api.world.storage.WorldProperties;
import java.util.ArrayList;
import java.util.List;
public class SpongePlotGenerator
implements WorldGeneratorModifier, GeneratorWrapper<WorldGeneratorModifier> {
private final IndependentPlotGenerator plotGenerator;
private final List<GenerationPopulator> populators = new ArrayList<>();
private final boolean loaded = false;
private final WorldGeneratorModifier platformGenerator;
private final boolean full;
private PlotManager manager;
public SpongePlotGenerator(IndependentPlotGenerator generator) {
this.plotGenerator = generator;
this.platformGenerator = this;
this.full = true;
MainUtil.initCache();
}
public SpongePlotGenerator(WorldGeneratorModifier wgm) {
this.plotGenerator = null;
this.platformGenerator = wgm;
this.full = false;
MainUtil.initCache();
}
@Override public String getId() {
if (this.plotGenerator == null) {
if (this.platformGenerator != this) {
return this.platformGenerator.getId();
}
return "null";
}
return this.plotGenerator.getName();
}
@Override public String getName() {
if (this.plotGenerator == null) {
if (this.platformGenerator != this) {
return this.platformGenerator.getName();
}
return "null";
}
return this.plotGenerator.getName();
}
@Override public void modifyWorldGenerator(WorldProperties world, DataContainer settings,
WorldGenerator worldGenerator) {
String worldName = world.getWorldName();
worldGenerator.setBaseGenerationPopulator(new SpongeTerrainGen(this.plotGenerator));
worldGenerator.setBiomeGenerator(new BiomeGenerator() {
@Override public void generateBiomes(MutableBiomeVolume buffer) {
PlotArea area = PS.get().getPlotArea(worldName, null);
if (area != null) {
BiomeType biome = SpongeUtil.getBiome(area.PLOT_BIOME);
Vector3i min = buffer.getBiomeMin();
Vector3i max = buffer.getBiomeMax();
for (int x = min.getX(); x <= max.getX(); x++) {
for (int z = min.getZ(); z <= max.getZ(); z++) {
buffer.setBiome(x, 0, z, biome);
}
}
}
}
});
for (BiomeType type : ReflectionUtils.<BiomeType>getStaticFields(BiomeTypes.class)) {
BiomeGenerationSettings biomeSettings = worldGenerator.getBiomeSettings(type);
biomeSettings.getGenerationPopulators().clear();
biomeSettings.getPopulators().clear();
biomeSettings.getGroundCoverLayers().clear();
}
worldGenerator.getGenerationPopulators().clear();
worldGenerator.getPopulators().clear();
PS.get().loadWorld(worldName, this);
}
@Override public IndependentPlotGenerator getPlotGenerator() {
return this.plotGenerator;
}
@Override public WorldGeneratorModifier getPlatformGenerator() {
return this.platformGenerator;
}
@Override public void augment(PlotArea area) {
SpongeAugmentedGenerator.get(SpongeUtil.getWorld(area.worldname));
}
@Override public boolean isFull() {
return this.full;
}
}

View File

@ -0,0 +1,94 @@
package com.github.intellectualsites.plotsquared.sponge.generator;
import com.flowpowered.math.vector.Vector3i;
import com.github.intellectualsites.plotsquared.plot.PS;
import com.github.intellectualsites.plotsquared.plot.generator.GeneratorWrapper;
import com.github.intellectualsites.plotsquared.plot.generator.IndependentPlotGenerator;
import com.github.intellectualsites.plotsquared.plot.object.ChunkWrapper;
import com.github.intellectualsites.plotsquared.plot.object.PlotArea;
import com.github.intellectualsites.plotsquared.plot.object.PseudoRandom;
import com.github.intellectualsites.plotsquared.plot.util.ChunkManager;
import com.github.intellectualsites.plotsquared.plot.util.MainUtil;
import com.github.intellectualsites.plotsquared.sponge.util.SpongeUtil;
import com.github.intellectualsites.plotsquared.sponge.util.block.GenChunk;
import org.spongepowered.api.world.World;
import org.spongepowered.api.world.extent.ImmutableBiomeVolume;
import org.spongepowered.api.world.extent.MutableBlockVolume;
import org.spongepowered.api.world.gen.GenerationPopulator;
public class SpongeTerrainGen
implements GenerationPopulator, GeneratorWrapper<GenerationPopulator> {
public final IndependentPlotGenerator child;
private final boolean full;
private final GenerationPopulator platformGenerator;
private final PseudoRandom random = new PseudoRandom();
public SpongeTerrainGen(IndependentPlotGenerator ipg) {
this.child = ipg;
this.full = true;
this.platformGenerator = this;
MainUtil.initCache();
}
public SpongeTerrainGen(GenerationPopulator populator) {
this.child = null;
this.platformGenerator = populator;
this.full = false;
MainUtil.initCache();
}
@Override
public void populate(World world, MutableBlockVolume terrain, ImmutableBiomeVolume biomes) {
if (platformGenerator != this) {
platformGenerator.populate(world, terrain, biomes);
return;
}
Vector3i size = terrain.getBlockSize();
if (size.getX() != 16 || size.getZ() != 16) {
throw new UnsupportedOperationException("NON CHUNK POPULATION NOT SUPPORTED");
}
String worldname = world.getName();
Vector3i min = terrain.getBlockMin();
int cx = min.getX() >> 4;
int cz = min.getZ() >> 4;
ChunkWrapper wrap = new ChunkWrapper(worldname, cx, cz);
// Create the result object
GenChunk result = new GenChunk(terrain, null, wrap);
// Catch any exceptions
try {
// Set random seed
random.state = (cx << 16) | (cz & 0xFFFF);
// Process the chunk
result.modified = false;
ChunkManager.preProcessChunk(result);
if (result.modified) {
return;
}
// Fill the result data
PlotArea area = PS.get().getPlotArea(world.getName(), null);
child.generateChunk(result, area, random);
child.populateChunk(result, area, random);
ChunkManager.postProcessChunk(result);
return;
} catch (Throwable e) {
e.printStackTrace();
}
}
@Override public IndependentPlotGenerator getPlotGenerator() {
return child;
}
@Override public GenerationPopulator getPlatformGenerator() {
return platformGenerator;
}
@Override public void augment(PlotArea area) {
SpongeAugmentedGenerator.get(SpongeUtil.getWorld(area.worldname));
}
@Override public boolean isFull() {
return this.full;
}
}

View File

@ -0,0 +1,5 @@
package com.github.intellectualsites.plotsquared.sponge.listener;
public class ChunkProcessor {
// TODO FIXME
}

View File

@ -0,0 +1,102 @@
package com.github.intellectualsites.plotsquared.sponge.listener;
import com.flowpowered.math.vector.Vector3d;
import com.github.intellectualsites.plotsquared.plot.flag.Flags;
import com.github.intellectualsites.plotsquared.plot.object.Location;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.sponge.object.SpongePlayer;
import com.github.intellectualsites.plotsquared.sponge.util.SpongeUtil;
import org.spongepowered.api.entity.Entity;
import org.spongepowered.api.entity.EntityTypes;
import org.spongepowered.api.entity.living.player.Player;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
public class ForceFieldListener {
private static Set<PlotPlayer> getNearbyPlayers(Player player, Plot plot) {
Set<PlotPlayer> players = new HashSet<>();
for (Entity nearbyEntity : player
.getNearbyEntities(entity -> entity.getType().equals(EntityTypes.PLAYER))) {
Player nearbyPlayer = (Player) nearbyEntity;
PlotPlayer plotPlayer;
if ((plotPlayer = SpongeUtil.getPlayer(nearbyPlayer)) == null || !plot
.equals(plotPlayer.getCurrentPlot())) {
continue;
}
if (!plot.isAdded(plotPlayer.getUUID())) {
players.add(plotPlayer);
}
}
return players;
}
private static PlotPlayer hasNearbyPermitted(Player player, Plot plot) {
for (Entity nearbyEntity : player
.getNearbyEntities(entity -> entity.getType().equals(EntityTypes.PLAYER))) {
Player nearbyPlayer = (Player) nearbyEntity;
PlotPlayer plotPlayer;
if ((plotPlayer = SpongeUtil.getPlayer(nearbyPlayer)) == null || !plot
.equals(plotPlayer.getCurrentPlot())) {
continue;
}
if (plot.isAdded(plotPlayer.getUUID())) {
return plotPlayer;
}
}
return null;
}
private static Vector3d calculateVelocity(PlotPlayer player, PlotPlayer e) {
Location playerLocation = player.getLocationFull();
Location oPlayerLocation = e.getLocation();
double playerX = playerLocation.getX();
double playerY = playerLocation.getY();
double playerZ = playerLocation.getZ();
double oPlayerX = oPlayerLocation.getX();
double oPlayerY = oPlayerLocation.getY();
double oPlayerZ = oPlayerLocation.getZ();
double x = 0d;
if (playerX < oPlayerX) {
x = 1.0d;
} else if (playerX > oPlayerX) {
x = -1.0d;
}
double y = 0d;
if (playerY < oPlayerY) {
y = 0.5d;
} else if (playerY > oPlayerY) {
y = -0.5d;
}
double z = 0d;
if (playerZ < oPlayerZ) {
z = 1.0d;
} else if (playerZ > oPlayerZ) {
z = -1.0d;
}
return new Vector3d(x, y, z);
}
public static void handleForcefield(Player player, PlotPlayer plotPlayer, Plot plot) {
if (Flags.FORCEFIELD.isTrue(plot)) {
UUID uuid = plotPlayer.getUUID();
if (plot.isAdded(uuid)) {
Set<PlotPlayer> players = getNearbyPlayers(player, plot);
for (PlotPlayer oPlayer : players) {
((SpongePlayer) oPlayer).player
.setVelocity(calculateVelocity(plotPlayer, oPlayer));
}
} else {
PlotPlayer oPlayer = hasNearbyPermitted(player, plot);
if (oPlayer == null) {
return;
}
player.setVelocity(calculateVelocity(oPlayer, plotPlayer));
}
}
}
}

View File

@ -0,0 +1,755 @@
package com.github.intellectualsites.plotsquared.sponge.listener;
import com.github.intellectualsites.plotsquared.plot.PS;
import com.github.intellectualsites.plotsquared.plot.config.C;
import com.github.intellectualsites.plotsquared.plot.flag.Flags;
import com.github.intellectualsites.plotsquared.plot.listener.PlotListener;
import com.github.intellectualsites.plotsquared.plot.object.*;
import com.github.intellectualsites.plotsquared.plot.util.*;
import com.github.intellectualsites.plotsquared.sponge.SpongeMain;
import com.github.intellectualsites.plotsquared.sponge.object.SpongePlayer;
import com.github.intellectualsites.plotsquared.sponge.util.SpongeUtil;
import org.spongepowered.api.block.BlockSnapshot;
import org.spongepowered.api.block.BlockState;
import org.spongepowered.api.data.Transaction;
import org.spongepowered.api.entity.EntityTypes;
import org.spongepowered.api.entity.explosive.Explosive;
import org.spongepowered.api.entity.living.Ambient;
import org.spongepowered.api.entity.living.Living;
import org.spongepowered.api.entity.living.animal.Animal;
import org.spongepowered.api.entity.living.monster.Monster;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.entity.vehicle.Boat;
import org.spongepowered.api.entity.vehicle.minecart.Minecart;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.block.ChangeBlockEvent;
import org.spongepowered.api.event.block.InteractBlockEvent;
import org.spongepowered.api.event.block.NotifyNeighborBlockEvent;
import org.spongepowered.api.event.entity.BreedEntityEvent;
import org.spongepowered.api.event.entity.MoveEntityEvent;
import org.spongepowered.api.event.entity.SpawnEntityEvent;
import org.spongepowered.api.event.message.MessageEvent;
import org.spongepowered.api.event.network.ClientConnectionEvent;
import org.spongepowered.api.event.world.ExplosionEvent;
import org.spongepowered.api.event.world.ExplosionEvent.Detonate;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.world.World;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Predicate;
@SuppressWarnings("Guava") public class MainListener {
/*
* TODO:
* - Anything marked with a TODO below
* - BlockPhysicsEvent
* - BlockFormEvent
* - BlockFadeEvent
* - BlockFromToEvent
* - BlockDamageEvent
* - Structure (tree etc)
* - ChunkPreGenerateEvent
* - PlayerIgniteBlockEvent
* - PlayerBucketEmptyEvent
* - PlayerBucketFillEvent
* - VehicleCreateEvent
* - HangingPlaceEvent
* - HangingBreakEvent
* - EntityChangeBlockEvent
* - PVP
* - block dispense
* - PVE
* - VehicleDestroy
* - Projectile
* - enderman harvest
*/
@Listener public void onChat(MessageEvent event) {
// TODO
Player player = SpongeUtil.getCause(event.getCause(), Player.class);
if (player == null) {
return;
}
String world = player.getWorld().getName();
if (!PS.get().hasPlotArea(world)) {
return;
}
PlotArea plotworld = PS.get().getPlotAreaByString(world);
PlotPlayer plr = SpongeUtil.getPlayer(player);
if (!plotworld.PLOT_CHAT && (plr.getMeta("chat") == null || !(Boolean) plr
.getMeta("chat"))) {
return;
}
Location loc = SpongeUtil.getLocation(player);
Plot plot = loc.getPlot();
if (plot == null) {
return;
}
Text message = event.getMessage();
// TODO use display name rather than username
// - Getting displayname currently causes NPE, so wait until sponge fixes that
String sender = player.getName();
PlotId id = plot.getId();
String newMessage = StringMan
.replaceAll(C.PLOT_CHAT_FORMAT.s(), "%plot_id%", id.x + ";" + id.y, "%sender%", sender);
// String forcedMessage = StringMan.replaceAll(C.PLOT_CHAT_FORCED.s(), "%plot_id%", id.x + ";" + id.y, "%sender%", sender);
for (Entry<String, PlotPlayer> entry : UUIDHandler.getPlayers().entrySet()) {
PlotPlayer user = entry.getValue();
String toSend;
if (plot.equals(user.getLocation().getPlot())) {
toSend = newMessage;
} else if (Permissions.hasPermission(user, C.PERMISSION_COMMANDS_CHAT)) {
((SpongePlayer) user).player.sendMessage(message);
continue;
} else {
continue;
}
String[] split = (toSend + " ").split("%msg%");
List<Text> components = new ArrayList<>();
Text prefix = null;
for (String part : split) {
if (prefix != null) {
components.add(prefix);
} else {
prefix = message;
}
components.add(SpongeUtil.getText(part));
}
((SpongePlayer) user).player.sendMessage(Text.join(components));
}
//event.setMessage(null);
}
@Listener public void onBreedEntity(BreedEntityEvent.Breed event) {
Location loc = SpongeUtil.getLocation(event.getTargetEntity());
String world = loc.getWorld();
PlotArea plotworld = PS.get().getPlotAreaByString(world);
if (plotworld == null) {
return;
}
Plot plot = loc.getPlot();
if (plot == null) {
if (loc.isPlotRoad()) {
event.setCancelled(true);
}
return;
}
if (!plotworld.SPAWN_BREEDING) {
event.setCancelled(true);
}
}
@Listener public void onSpawnEntity(SpawnEntityEvent event) {
event.filterEntities(entity -> {
if (entity instanceof Player) {
return true;
}
Location loc = SpongeUtil.getLocation(entity);
Plot plot = loc.getPlot();
if (plot == null) {
return !loc.isPlotRoad();
}
// Player player = this.<Player> getCause(event.getCause());
// TODO selectively cancel depending on spawn reason
// - Not sure if possible to get spawn reason (since there are no callbacks)
// if (player != null && !plotworld.SPAWN_EGGS) {
// return false;
// return true;
// }
if (entity.getType() == EntityTypes.ITEM) {
return plot.getFlag(Flags.ITEM_DROP).or(true);
}
int[] mobs = null;
if (entity instanceof Living) {
if (!loc.getPlotArea().MOB_SPAWNING) {
return false;
}
com.google.common.base.Optional<Integer> mobCap = plot.getFlag(Flags.MOB_CAP);
if (mobCap.isPresent()) {
Integer cap = mobCap.get();
if (cap == 0) {
return false;
}
mobs = plot.countEntities();
if (mobs[3] >= cap) {
return false;
}
}
if (entity instanceof Ambient || entity instanceof Animal) {
com.google.common.base.Optional<Integer> animalFlag =
plot.getFlag(Flags.ANIMAL_CAP);
if (animalFlag.isPresent()) {
int cap = animalFlag.get();
if (cap == 0) {
return false;
}
if (mobs == null) {
mobs = plot.countEntities();
}
if (mobs[1] >= cap) {
return false;
}
}
} else if (entity instanceof Monster) {
com.google.common.base.Optional<Integer> monsterFlag =
plot.getFlag(Flags.HOSTILE_CAP);
if (monsterFlag.isPresent()) {
int cap = monsterFlag.get();
if (cap == 0) {
return false;
}
if (mobs == null) {
mobs = plot.countEntities();
}
if (mobs[2] >= cap) {
return false;
}
}
}
return true;
} else if (entity instanceof Minecart || entity instanceof Boat) {
com.google.common.base.Optional<Integer> vehicleFlag =
plot.getFlag(Flags.VEHICLE_CAP);
if (vehicleFlag.isPresent()) {
int cap = vehicleFlag.get();
if (cap == 0) {
return false;
}
mobs = plot.countEntities();
if (mobs[4] >= cap) {
return false;
}
}
}
com.google.common.base.Optional<Integer> entityCap = plot.getFlag(Flags.ENTITY_CAP);
if (entityCap.isPresent()) {
Integer cap = entityCap.get();
if (cap == 0) {
return false;
}
if (mobs == null) {
mobs = plot.countEntities();
}
if (mobs[0] >= cap) {
return false;
}
}
if (entity instanceof Explosive) {
entity.setCreator(plot.owner);
}
return true;
});
}
public void onNotifyNeighborBlock(NotifyNeighborBlockEvent event) {
AtomicBoolean cancelled = new AtomicBoolean(false);
// SpongeUtil.printCause("physics", event.getCause());
// PlotArea area = plotloc.getPlotArea();
// event.filterDirections(new Predicate<Direction>() {
//
// @Override
// public boolean test(Direction dir) {
// if (cancelled.get()) {
// return true;
// }
// org.spongepowered.api.world.Location<World> loc = relatives.get(dir);
// Location plotloc = SpongeUtil.getLocation(loc.getExtent().getPluginName(), loc);
// if (area == null) {
// return true;
// }
// plot = area.get
// Plot plot = plotloc.getPlot();
// if (plot == null) {
// if (MainUtil.isPlotAreaAbs(plotloc)) {
// cancelled.set(true);
// return false;
// }
// cancelled.set(true);
// return true;
// }
// org.spongepowered.api.world.Location<World> relative = loc.getRelative(dir);
// Location relLoc = SpongeUtil.getLocation(relative.getExtent().getPluginName(), relative);
// if (plot.equals(MainUtil.getPlot(relLoc))) {
// return true;
// }
// return false;
// }
// });
}
@Listener public void onInteract(InteractBlockEvent event) {
Player player = SpongeUtil.getCause(event.getCause(), Player.class);
if (player == null) {
event.setCancelled(true);
return;
}
BlockSnapshot block = event.getTargetBlock();
if (block == null) {
return;
}
Optional<org.spongepowered.api.world.Location<World>> bloc = block.getLocation();
if (!bloc.isPresent()) {
return;
}
Location loc = SpongeUtil.getLocation(player.getWorld().getName(), bloc.get());
PlotArea area = loc.getPlotArea();
if (area == null) {
return;
}
Plot plot = area.getPlot(loc);
PlotPlayer pp = SpongeUtil.getPlayer(player);
if (plot == null) {
if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD, true)) {
event.setCancelled(true);
return;
}
return;
}
if (!plot.hasOwner()) {
if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED)) {
return;
}
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_INTERACT_UNOWNED);
event.setCancelled(true);
return;
}
if (plot.isAdded(pp.getUUID()) || Permissions
.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER)) {
return;
} else {
com.google.common.base.Optional<HashSet<PlotBlock>> flag = plot.getFlag(Flags.USE);
org.spongepowered.api.world.Location l = SpongeUtil.getLocation(loc);
if (flag.isPresent() && flag.get().contains(SpongeUtil.getPlotBlock(l.getBlock()))) {
return;
}
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_INTERACT_OTHER);
event.setCancelled(true);
return;
}
}
@Listener public void onExplosion(ExplosionEvent e) {
if (e instanceof ExplosionEvent.Detonate) {
ExplosionEvent.Detonate event = (Detonate) e;
World world = event.getTargetWorld();
String worldName = world.getName();
if (!PS.get().hasPlotArea(worldName)) {
return;
}
Optional<Explosive> source = event.getExplosion().getSourceExplosive();
if (!source.isPresent()) {
event.setCancelled(true);
return;
}
Explosive tnt = source.get();
UUID creator = tnt.getCreator().orElse(null);
Location current = SpongeUtil.getLocation(tnt);
Plot currentPlot = current.getPlot();
if (currentPlot == null) {
if (current.isPlotArea()) {
event.setCancelled(true);
}
return;
}
if (creator != null) {
if (!currentPlot.isAdded(creator)) {
event.setCancelled(true);
return;
}
}
if (!currentPlot.getFlag(Flags.EXPLOSION).or(false)) {
event.setCancelled(true);
return;
}
event.getAffectedLocations().removeIf(worldLocation -> currentPlot.equals(
SpongeUtil.getLocation(worldLocation.getExtent().getName(), worldLocation)
.getPlot()));
event.filterEntities(
entity -> currentPlot.equals(SpongeUtil.getLocation(entity).getPlot()));
}
}
public void onChangeBlock(ChangeBlockEvent event) {
List<Transaction<BlockSnapshot>> transactions = event.getTransactions();
Transaction<BlockSnapshot> first = transactions.get(0);
BlockSnapshot original = first.getOriginal();
Optional<World> world = SpongeMain.THIS.getServer().getWorld(original.getWorldUniqueId());
String worldName = world.get().getName();
Location loc = SpongeUtil.getLocation(worldName, original.getPosition());
PlotArea area = loc.getPlotArea();
if (area == null) {
return;
}
Plot plot = area.getPlot(loc);
if (plot == null) {
if (!loc.isPlotArea()) {
return;
}
event.setCancelled(true);
return;
}
event.filter(loc1 -> !SpongeUtil.getLocation(worldName, loc1).isPlotRoad());
}
@Listener public void onBlockBreak(ChangeBlockEvent.Decay event) {
onChangeBlock(event);
}
@Listener public void onBlockBreak(ChangeBlockEvent.Grow event) {
onChangeBlock(event);
}
@Listener public void onBlockBreak(ChangeBlockEvent.Modify event) {
onChangeBlock(event);
}
@Listener public void onBlockBreak(ChangeBlockEvent.Break event) {
Player player = SpongeUtil.getCause(event.getCause(), Player.class);
if (player == null) {
//SpongeUtil.printCause("break", event.getCause());
return;
}
PlotPlayer pp = SpongeUtil.getPlayer(player);
List<Transaction<BlockSnapshot>> transactions = event.getTransactions();
Transaction<BlockSnapshot> first = transactions.get(0);
BlockSnapshot original = first.getOriginal();
Optional<World> world = SpongeMain.THIS.getServer().getWorld(original.getWorldUniqueId());
String worldName = world.get().getName();
Location loc = SpongeUtil.getLocation(worldName, original.getPosition());
Plot plot = loc.getPlot();
if (plot == null) {
if (!loc.isPlotArea()) {
return;
}
if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_ROAD)) {
MainUtil.sendMessage(pp, C.PERMISSION_ADMIN_DESTROY_ROAD);
event.setCancelled(true);
return;
}
} else if (transactions.size() == 1) {
if (!plot.hasOwner()) {
if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_UNOWNED)) {
return;
}
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_UNOWNED);
event.setCancelled(true);
return;
}
if (plot.isAdded(pp.getUUID()) || Permissions
.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_OTHER)) {
return;
} else {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_OTHER);
com.google.common.base.Optional<HashSet<PlotBlock>> destroy =
plot.getFlag(Flags.BREAK);
BlockState state = original.getState();
if (!destroy.isPresent() || !destroy.get()
.contains(SpongeUtil.getPlotBlock(state))) {
event.setCancelled(true);
return;
}
}
}
event.filter(l -> {
Location loc1 = SpongeUtil.getLocation(worldName, l);
PlotArea area = loc1.getPlotArea();
if (area == null) {
return true;
}
Plot plot1 = area.getPlot(loc1);
if (plot1 == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_ROAD, true);
}
if (!plot1.hasOwner()) {
if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_UNOWNED, true)) {
return false;
}
return true;
}
if (!plot1.isAdded(pp.getUUID()) && !Permissions
.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_OTHER, true)) {
com.google.common.base.Optional<HashSet<PlotBlock>> destroy =
plot1.getFlag(Flags.BREAK);
BlockState state = l.getBlock();
if (destroy.isPresent() && destroy.get().contains(SpongeUtil.getPlotBlock(state))) {
return true;
}
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_OTHER);
return false;
}
return true;
});
}
@Listener public void onBlockPlace(ChangeBlockEvent.Pre event) {
Player player = SpongeUtil.getCause(event.getCause(), Player.class);
if (player == null) {
return;
}
PlotPlayer pp = SpongeUtil.getPlayer(player);
List<org.spongepowered.api.world.Location<World>> locs = event.getLocations();
org.spongepowered.api.world.Location<World> first = locs.get(0);
String worldName = first.getExtent().getName();
Location loc = SpongeUtil.getLocation(worldName, first.getPosition());
PlotArea area = loc.getPlotArea();
if (area == null) {
return;
}
Plot plot = area.getPlot(loc);
if (plot == null) {
if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_ROAD, true)) {
event.setCancelled(true);
}
return;
}
if (plot.hasOwner()) {
if (plot.isAdded(pp.getUUID()) || Permissions
.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) {
return;
} else {
com.google.common.base.Optional<HashSet<PlotBlock>> place =
plot.getFlag(Flags.PLACE);
BlockState state = first.getBlock();
if (!place.isPresent() || !place.get().contains(SpongeUtil.getPlotBlock(state))) {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER);
event.setCancelled(true);
return;
}
}
} else {
if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_UNOWNED)) {
return;
}
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED);
event.setCancelled(true);
return;
}
}
@Listener public void onBlockPlace(ChangeBlockEvent.Place event) {
Player player = SpongeUtil.getCause(event.getCause(), Player.class);
if (player == null) {
return;
}
PlotPlayer pp = SpongeUtil.getPlayer(player);
List<Transaction<BlockSnapshot>> transactions = event.getTransactions();
Transaction<BlockSnapshot> first = transactions.get(0);
BlockSnapshot pos = first.getOriginal();
Optional<World> world = SpongeMain.THIS.getServer().getWorld(pos.getWorldUniqueId());
String worldName = world.get().getName();
Location loc = SpongeUtil.getLocation(worldName, pos.getPosition());
PlotArea area = loc.getPlotArea();
if (area == null) {
return;
}
Plot plot = area.getPlot(loc);
if (plot == null) {
if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_ROAD, true)) {
event.setCancelled(true);
return;
}
} else if (transactions.size() == 1) {
if (plot.hasOwner()) {
if (plot.isAdded(pp.getUUID()) || Permissions
.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) {
return;
} else {
com.google.common.base.Optional<HashSet<PlotBlock>> place =
plot.getFlag(Flags.PLACE);
BlockState state = pos.getState();
if (!place.isPresent() || !place.get()
.contains(SpongeUtil.getPlotBlock(state))) {
MainUtil
.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER);
event.setCancelled(true);
return;
}
}
} else {
if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_UNOWNED)) {
return;
}
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED);
event.setCancelled(true);
return;
}
} else {
event.filter(new Predicate<org.spongepowered.api.world.Location<World>>() {
@Override public boolean test(org.spongepowered.api.world.Location<World> l) {
Location loc = SpongeUtil.getLocation(worldName, l);
Plot plot = loc.getPlot();
if (plot == null) {
return loc.getPlotArea() == null || Permissions
.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_ROAD, true);
}
if (!plot.hasOwner()) {
if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_UNOWNED, true)) {
return true;
}
return false;
}
if (plot.isAdded(pp.getUUID()) || Permissions
.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER, true)) {
return true;
} else {
com.google.common.base.Optional<HashSet<PlotBlock>> place =
plot.getFlag(Flags.PLACE);
BlockState state = l.getBlock();
if (place.isPresent() && place.get()
.contains(SpongeUtil.getPlotBlock(state))) {
return true;
}
MainUtil
.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER);
return false;
}
}
});
}
}
@Listener public void onJoin(ClientConnectionEvent.Join event) {
Player player = event.getTargetEntity();
SpongeUtil.getPlayer(player).unregister();
PlotPlayer pp = SpongeUtil.getPlayer(player);
// Now
String name = pp.getName();
StringWrapper sw = new StringWrapper(name);
UUID uuid = pp.getUUID();
UUIDHandler.add(sw, uuid);
Location loc = pp.getLocation();
PlotArea area = loc.getPlotArea();
Plot plot;
if (area != null) {
plot = area.getPlot(loc);
if (plot != null) {
PlotListener.plotEntry(pp, plot);
}
} else {
plot = null;
}
// Delayed
// Async
TaskManager.runTaskLaterAsync(() -> EventUtil.manager.doJoinTask(pp), 20);
}
@Listener public void onQuit(ClientConnectionEvent.Disconnect event) {
Player player = event.getTargetEntity();
PlotPlayer pp = SpongeUtil.getPlayer(player);
pp.unregister();
}
@Listener public void onMove(MoveEntityEvent event) {
if (!(event.getTargetEntity() instanceof Player)) {
return;
}
org.spongepowered.api.world.Location<World> from = event.getFromTransform().getLocation();
org.spongepowered.api.world.Location<World> to = event.getToTransform().getLocation();
int x2;
if (MathMan.roundInt(from.getX()) != (x2 = MathMan.roundInt(to.getX()))) {
Player player = (Player) event.getTargetEntity();
PlotPlayer pp = SpongeUtil.getPlayer(player);
// Cancel teleport
TaskManager.TELEPORT_QUEUE.remove(pp.getName());
// Set last location
Location loc = SpongeUtil.getLocation(to);
pp.setMeta("location", loc);
PlotArea area = loc.getPlotArea();
if (area == null) {
pp.deleteMeta("lastplot");
return;
}
Plot now = area.getPlotAbs(loc);
Plot lastPlot = pp.getMeta("lastplot");
if (now == null) {
if (lastPlot != null && !PlotListener.plotExit(pp, lastPlot)) {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_EXIT_DENIED);
if (lastPlot.equals(SpongeUtil.getLocation(from).getPlot())) {
player.setLocation(from);
} else {
player.setLocation(player.getWorld().getSpawnLocation());
}
event.setCancelled(true);
return;
}
} else if (now.equals(lastPlot)) {
ForceFieldListener.handleForcefield(player, pp, now);
return;
} else if (!PlotListener.plotEntry(pp, now)) {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_ENTRY_DENIED);
player.setLocation(from);
event.setCancelled(true);
return;
}
Integer border = area.getBorder();
if (x2 > border) {
to.sub(x2 - border + 4, 0, 0);
player.setLocation(to);
MainUtil.sendMessage(pp, C.BORDER);
return;
} else if (x2 < -border) {
to.add(border - x2 + 4, 0, 0);
player.setLocation(to);
MainUtil.sendMessage(pp, C.BORDER);
return;
}
return;
}
int z2;
if (MathMan.roundInt(from.getZ()) != (z2 = MathMan.roundInt(to.getZ()))) {
Player player = (Player) event.getTargetEntity();
PlotPlayer pp = SpongeUtil.getPlayer(player);
// Cancel teleport
TaskManager.TELEPORT_QUEUE.remove(pp.getName());
// Set last location
Location loc = SpongeUtil.getLocation(to);
pp.setMeta("location", loc);
PlotArea area = loc.getPlotArea();
if (area == null) {
pp.deleteMeta("lastplot");
return;
}
Plot now = area.getPlotAbs(loc);
Plot lastPlot = pp.getMeta("lastplot");
if (now == null) {
if (lastPlot != null && !PlotListener.plotExit(pp, lastPlot)) {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_EXIT_DENIED);
if (lastPlot.equals(SpongeUtil.getLocation(from).getPlot())) {
player.setLocation(from);
} else {
player.setLocation(player.getWorld().getSpawnLocation());
}
event.setCancelled(true);
return;
}
} else if (now.equals(lastPlot)) {
ForceFieldListener.handleForcefield(player, pp, now);
return;
} else if (!PlotListener.plotEntry(pp, now)) {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_ENTRY_DENIED);
player.setLocation(from);
event.setCancelled(true);
return;
}
Integer border = area.getBorder();
if (z2 > border) {
to.add(0, 0, z2 - border - 4);
player.setLocation(to);
MainUtil.sendMessage(pp, C.BORDER);
} else if (z2 < -border) {
to.add(0, 0, border - z2 + 4);
player.setLocation(to);
MainUtil.sendMessage(pp, C.BORDER);
}
}
}
}

View File

@ -0,0 +1,25 @@
package com.github.intellectualsites.plotsquared.sponge.listener;
import com.github.intellectualsites.plotsquared.plot.PS;
import com.github.intellectualsites.plotsquared.plot.generator.GeneratorWrapper;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.world.LoadWorldEvent;
import org.spongepowered.api.world.World;
import org.spongepowered.api.world.gen.GenerationPopulator;
import org.spongepowered.api.world.gen.WorldGenerator;
public class WorldEvents {
@Listener public void onLoadWorld(LoadWorldEvent event) {
final World world = event.getTargetWorld();
final String name = world.getName();
WorldGenerator generator = world.getWorldGenerator();
GenerationPopulator terrain = generator.getBaseGenerationPopulator();
if (terrain instanceof GeneratorWrapper) {
GeneratorWrapper stg = (GeneratorWrapper) terrain;
PS.get().loadWorld(name, stg);
} else {
PS.get().loadWorld(name, null);
}
}
}

View File

@ -0,0 +1,31 @@
package com.github.intellectualsites.plotsquared.sponge.object;
import com.github.intellectualsites.plotsquared.plot.object.OfflinePlotPlayer;
import org.spongepowered.api.entity.living.player.User;
import java.util.UUID;
public class SpongeOfflinePlayer implements OfflinePlotPlayer {
private User user;
public SpongeOfflinePlayer(User user) {
this.user = user;
}
@Override public UUID getUUID() {
return user.getUniqueId();
}
@Override public long getLastPlayed() {
return 0; //todo
}
@Override public boolean isOnline() {
return user.isOnline();
}
@Override public String getName() {
return user.getName();
}
}

View File

@ -0,0 +1,250 @@
package com.github.intellectualsites.plotsquared.sponge.object;
import com.flowpowered.math.vector.Vector3d;
import com.github.intellectualsites.plotsquared.plot.PS;
import com.github.intellectualsites.plotsquared.plot.commands.RequiredType;
import com.github.intellectualsites.plotsquared.plot.object.Location;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.util.PlotGameMode;
import com.github.intellectualsites.plotsquared.plot.util.PlotWeather;
import com.github.intellectualsites.plotsquared.plot.util.StringMan;
import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler;
import com.github.intellectualsites.plotsquared.sponge.util.SpongeUtil;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.data.key.Keys;
import org.spongepowered.api.data.manipulator.mutable.TargetedLocationData;
import org.spongepowered.api.effect.sound.SoundTypes;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.entity.living.player.gamemode.GameMode;
import org.spongepowered.api.entity.living.player.gamemode.GameModes;
import org.spongepowered.api.service.ban.BanService;
import org.spongepowered.api.text.chat.ChatTypes;
import org.spongepowered.api.text.serializer.TextSerializers;
import org.spongepowered.api.util.Tristate;
import org.spongepowered.api.world.World;
import java.util.Optional;
import java.util.UUID;
public class SpongePlayer extends PlotPlayer {
public final Player player;
private UUID uuid;
private String name;
public SpongePlayer(Player player) {
this.player = player;
super.populatePersistentMetaMap();
}
@Override public RequiredType getSuperCaller() {
return RequiredType.PLAYER;
}
@Override public Location getLocation() {
Location location = super.getLocation();
if (location == null) {
return SpongeUtil.getLocation(this.player);
} else {
return location;
}
}
@Override public Location getLocationFull() {
return SpongeUtil.getLocationFull(this.player);
}
@Override public UUID getUUID() {
if (this.uuid == null) {
this.uuid = UUIDHandler.getUUID(this);
}
return this.uuid;
}
@Override public long getLastPlayed() {
return this.player.lastPlayed().get().toEpochMilli();
}
@Override public boolean hasPermission(String permission) {
return this.player.hasPermission(permission);
}
@Override public boolean isPermissionSet(String permission) {
Tristate state =
this.player.getPermissionValue(this.player.getActiveContexts(), permission);
return state != Tristate.UNDEFINED;
}
@Override public void sendMessage(String message) {
if (!StringMan.isEqual(this.getMeta("lastMessage"), message) || (
System.currentTimeMillis() - this.<Long>getMeta("lastMessageTime") > 5000)) {
setMeta("lastMessage", message);
setMeta("lastMessageTime", System.currentTimeMillis());
this.player.sendMessage(ChatTypes.CHAT,
TextSerializers.LEGACY_FORMATTING_CODE.deserialize(message));
}
}
@Override public void teleport(Location location) {
if ((Math.abs(location.getX()) >= 30000000) || (Math.abs(location.getZ()) >= 30000000)) {
return;
}
String world = this.player.getWorld().getName();
if (!world.equals(location.getWorld())) {
this.player.transferToWorld(location.getWorld(),
new Vector3d(location.getX(), location.getY(), location.getZ()));
} else {
org.spongepowered.api.world.Location<World> current = this.player.getLocation();
current = current
.setPosition(new Vector3d(location.getX(), location.getY(), location.getZ()));
this.player.setLocation(current);
}
}
@Override public boolean isOnline() {
return this.player.isOnline();
}
@Override public String getName() {
if (this.name == null) {
this.name = this.player.getName();
}
return this.name;
}
@Override public void setCompassTarget(Location location) {
Optional<TargetedLocationData> target = this.player.getOrCreate(TargetedLocationData.class);
if (target.isPresent()) {
target.get()
.set(Keys.TARGETED_LOCATION, SpongeUtil.getLocation(location).getPosition());
} else {
PS.debug("Failed to set compass target.");
}
}
@Override public void setWeather(PlotWeather weather) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
}
@Override public PlotGameMode getGameMode() {
GameMode gamemode = this.player.getGameModeData().type().get();
if (gamemode == GameModes.ADVENTURE) {
return PlotGameMode.ADVENTURE;
} else if (gamemode == GameModes.CREATIVE) {
return PlotGameMode.CREATIVE;
} else if (gamemode == GameModes.SPECTATOR) {
return PlotGameMode.SPECTATOR;
} else if (gamemode == GameModes.SURVIVAL) {
return PlotGameMode.SURVIVAL;
} else {
return PlotGameMode.NOT_SET;
}
}
@Override public void setGameMode(PlotGameMode gameMode) {
switch (gameMode) {
case ADVENTURE:
this.player.offer(Keys.GAME_MODE, GameModes.ADVENTURE);
return;
case CREATIVE:
this.player.offer(Keys.GAME_MODE, GameModes.CREATIVE);
return;
case SPECTATOR:
this.player.offer(Keys.GAME_MODE, GameModes.SPECTATOR);
return;
case SURVIVAL:
this.player.offer(Keys.GAME_MODE, GameModes.SURVIVAL);
return;
case NOT_SET:
this.player.offer(Keys.GAME_MODE, GameModes.NOT_SET);
}
}
@Override public void setTime(long time) {
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
}
@Override public boolean getFlight() {
Optional<Boolean> flying = player.get(Keys.CAN_FLY);
return flying.isPresent() && flying.get();
}
@Override public void setFlight(boolean fly) {
this.player.offer(Keys.IS_FLYING, fly);
this.player.offer(Keys.CAN_FLY, fly);
}
@Override public void playMusic(Location location, int id) {
switch (id) {
case 0:
//Placeholder because Sponge doesn't have a stopSound() implemented yet.
this.player.playSound(SoundTypes.BLOCK_CLOTH_PLACE,
SpongeUtil.getLocation(location).getPosition(), 0);
break;
case 2256:
this.player
.playSound(SoundTypes.RECORD_11, SpongeUtil.getLocation(location).getPosition(),
1);
break;
case 2257:
this.player
.playSound(SoundTypes.RECORD_13, SpongeUtil.getLocation(location).getPosition(),
1);
break;
case 2258:
this.player.playSound(SoundTypes.RECORD_BLOCKS,
SpongeUtil.getLocation(location).getPosition(), 1);
break;
case 2259:
this.player.playSound(SoundTypes.RECORD_CAT,
SpongeUtil.getLocation(location).getPosition(), 1);
break;
case 2260:
this.player.playSound(SoundTypes.RECORD_CHIRP,
SpongeUtil.getLocation(location).getPosition(), 1);
break;
case 2261:
this.player.playSound(SoundTypes.RECORD_FAR,
SpongeUtil.getLocation(location).getPosition(), 1);
break;
case 2262:
this.player.playSound(SoundTypes.RECORD_MALL,
SpongeUtil.getLocation(location).getPosition(), 1);
break;
case 2263:
this.player.playSound(SoundTypes.RECORD_MELLOHI,
SpongeUtil.getLocation(location).getPosition(), 1);
break;
case 2264:
this.player.playSound(SoundTypes.RECORD_STAL,
SpongeUtil.getLocation(location).getPosition(), 1);
break;
case 2265:
this.player.playSound(SoundTypes.RECORD_STRAD,
SpongeUtil.getLocation(location).getPosition(), 1);
break;
case 2266:
this.player.playSound(SoundTypes.RECORD_WAIT,
SpongeUtil.getLocation(location).getPosition(), 1);
break;
case 2267:
this.player.playSound(SoundTypes.RECORD_WARD,
SpongeUtil.getLocation(location).getPosition(), 1);
break;
}
}
@Override public void kick(String message) {
this.player.kick(SpongeUtil.getText(message));
}
@Override public void stopSpectating() {
//Not Implemented
}
@Override public boolean isBanned() {
Optional<BanService> service = Sponge.getServiceManager().provide(BanService.class);
return service.isPresent() && service.get().isBanned(this.player.getProfile());
}
}

View File

@ -0,0 +1,8 @@
package com.github.intellectualsites.plotsquared.sponge.util;
public class KillRoadMobs {
public void run() {
// TODO kill road mobs
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
}
}

View File

@ -0,0 +1,147 @@
package com.github.intellectualsites.plotsquared.sponge.util;
import com.github.intellectualsites.plotsquared.plot.config.Settings;
import com.github.intellectualsites.plotsquared.plot.object.ConsolePlayer;
import com.github.intellectualsites.plotsquared.plot.object.PlotMessage;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.util.ChatManager;
import com.github.intellectualsites.plotsquared.sponge.object.SpongePlayer;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.action.TextActions;
import org.spongepowered.api.text.format.TextColor;
import org.spongepowered.api.text.format.TextColors;
import org.spongepowered.api.text.format.TextStyle;
import org.spongepowered.api.text.format.TextStyles;
import java.util.List;
public class SpongeChatManager extends ChatManager<Text.Builder> {
@Override public Text.Builder builder() {
return Text.builder();
}
@Override public void color(PlotMessage message, String color) {
TextColor tc = null;
TextStyle ts = null;
switch (color.charAt(1)) {
case 'a':
tc = TextColors.GREEN;
break;
case 'b':
tc = TextColors.AQUA;
break;
case 'c':
tc = TextColors.RED;
break;
case 'd':
tc = TextColors.LIGHT_PURPLE;
break;
case 'e':
tc = TextColors.YELLOW;
break;
case 'f':
tc = TextColors.WHITE;
break;
case '1':
tc = TextColors.DARK_BLUE;
break;
case '2':
tc = TextColors.DARK_GREEN;
break;
case '3':
tc = TextColors.DARK_AQUA;
break;
case '4':
tc = TextColors.DARK_RED;
break;
case '5':
tc = TextColors.DARK_PURPLE;
break;
case '6':
tc = TextColors.GOLD;
break;
case '7':
tc = TextColors.GRAY;
break;
case '8':
tc = TextColors.DARK_GRAY;
break;
case '9':
tc = TextColors.BLUE;
break;
case '0':
tc = TextColors.BLACK;
break;
case 'k':
ts = TextStyles.OBFUSCATED;
break;
case 'l':
ts = TextStyles.BOLD;
break;
case 'm':
ts = TextStyles.UNDERLINE;
break;
case 'n':
ts = TextStyles.STRIKETHROUGH;
break;
case 'o':
ts = TextStyles.ITALIC;
break;
case 'r':
tc = TextColors.RESET;
break;
}
if (tc != null) {
apply(message, getChild(message).color(tc));
}
if (ts != null) {
apply(message, getChild(message).style(ts));
}
}
public Text.Builder getChild(PlotMessage m) {
Text.Builder builder = m.$(this);
List<Text> children = builder.getChildren();
Text last = children.get(children.size() - 1);
builder.remove(last);
return Text.builder().append(last);
}
public void apply(PlotMessage m, Text.Builder builder) {
m.$(this).append(builder.build());
}
@Override public void tooltip(PlotMessage message, PlotMessage... tooltips) {
Text.Builder builder = Text.builder();
boolean lb = false;
for (PlotMessage tooltip : tooltips) {
if (lb) {
builder.append(Text.of("\n"));
}
builder.append(tooltip.$(this).build());
lb = true;
}
apply(message, getChild(message).onHover(TextActions.showText(builder.toText())));
}
@Override public void command(PlotMessage message, String command) {
apply(message, getChild(message).onClick(TextActions.runCommand(command)));
}
@Override public void text(PlotMessage message, String text) {
message.$(this).append(SpongeUtil.getText(text));
}
@Override public void send(PlotMessage plotMessage, PlotPlayer player) {
if (player instanceof ConsolePlayer || !Settings.Chat.INTERACTIVE) {
player.sendMessage(plotMessage.$(this).build().toPlain());
} else {
((SpongePlayer) player).player.sendMessage(plotMessage.$(this).build());
}
}
@Override public void suggest(PlotMessage plotMessage, String command) {
apply(plotMessage, getChild(plotMessage).onClick(TextActions.suggestCommand(command)));
}
}

View File

@ -0,0 +1,117 @@
package com.github.intellectualsites.plotsquared.sponge.util;
import com.github.intellectualsites.plotsquared.plot.object.ChunkLoc;
import com.github.intellectualsites.plotsquared.plot.object.Location;
import com.github.intellectualsites.plotsquared.plot.object.Plot;
import com.github.intellectualsites.plotsquared.plot.util.ChunkManager;
import com.github.intellectualsites.plotsquared.plot.util.TaskManager;
import org.spongepowered.api.entity.Entity;
import org.spongepowered.api.entity.living.Living;
import org.spongepowered.api.entity.living.animal.Animal;
import org.spongepowered.api.entity.living.monster.Monster;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.world.Chunk;
import org.spongepowered.api.world.World;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
public class SpongeChunkManager extends ChunkManager {
@Override public int[] countEntities(Plot plot) {
Location pos1 = plot.getBottomAbs();
Location pos2 = plot.getTopAbs();
World world = SpongeUtil.getWorld(pos1.getWorld());
int bx = pos1.getX();
int bz = pos1.getZ();
int tx = pos2.getX();
int tz = pos2.getZ();
int[] count = new int[6];
world.getEntities(entity -> {
org.spongepowered.api.world.Location loc = entity.getLocation();
int x = loc.getBlockX();
if ((x >= bx) && (x <= tx)) {
int z = loc.getBlockZ();
if ((z >= bz) && (z <= tz)) {
count[0]++;
if (entity instanceof Living) {
count[3]++;
if (entity instanceof Animal) {
count[1]++;
} else if (entity instanceof Monster) {
count[2]++;
}
} else {
count[4]++;
}
}
}
return false;
});
return count;
}
@Override public boolean loadChunk(String world, ChunkLoc loc, boolean force) {
World worldObj = SpongeUtil.getWorld(world);
return worldObj.loadChunk(loc.x << 4, 0, loc.z << 4, force).isPresent();
}
@Override public Set<ChunkLoc> getChunkChunks(String world) {
// TODO save world;
return super.getChunkChunks(world);
}
@Override
public boolean copyRegion(Location pos1, Location pos2, Location newPos, Runnable whenDone) {
// TODO copy a region
TaskManager.runTask(whenDone);
return false;
}
@Override public void clearAllEntities(Location pos1, Location pos2) {
String worldName = pos1.getWorld();
World world = SpongeUtil.getWorld(worldName);
int bx = pos1.getX();
int bz = pos1.getZ();
int tx = pos2.getX();
int tz = pos2.getZ();
world.getEntities(new Predicate<Entity>() {
@Override public boolean test(Entity entity) {
org.spongepowered.api.world.Location loc = entity.getLocation();
int x = loc.getBlockX();
if ((x >= bx) && (x <= tx)) {
int z = loc.getBlockZ();
if ((z >= bz) && (z <= tz)) {
if (!(entity instanceof Player)) {
entity.remove();
}
}
}
return false;
}
});
}
@Override public void swap(Location bot1, Location top1, Location bot2, Location top2,
Runnable whenDone) {
// TODO swap region
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
}
@Override public void unloadChunk(String world, ChunkLoc loc, boolean save, boolean safe) {
World worldObj = SpongeUtil.getWorld(world);
Optional<Chunk> chunk = worldObj.getChunk(loc.x << 4, 0, loc.z << 4);
if (chunk.isPresent()) {
worldObj.unloadChunk(chunk.get());
}
}
@Override public boolean regenerateRegion(Location pos1, Location pos2, boolean ignoreAugment,
Runnable whenDone) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
}
}

View File

@ -0,0 +1,89 @@
package com.github.intellectualsites.plotsquared.sponge.util;
import com.github.intellectualsites.plotsquared.plot.commands.MainCommand;
import com.github.intellectualsites.plotsquared.plot.object.ConsolePlayer;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.util.TaskManager;
import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler;
import com.github.intellectualsites.plotsquared.sponge.SpongeMain;
import com.google.common.collect.ImmutableList;
import org.spongepowered.api.command.CommandCallable;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.world.Location;
import org.spongepowered.api.world.World;
import java.util.*;
public class SpongeCommand implements CommandCallable {
@Override public CommandResult process(CommandSource source, String arguments)
throws CommandException {
TaskManager.runTask(() -> {
String id = source.getIdentifier();
PlotPlayer plotPlayer = null;
try {
UUID uuid = UUID.fromString(id);
Optional<Player> player = SpongeMain.THIS.getServer().getPlayer(uuid);
if (player.isPresent()) {
plotPlayer = SpongeUtil.getPlayer(player.get());
}
} catch (Exception ignored) {
plotPlayer = ConsolePlayer.getConsole();
}
MainCommand.onCommand(plotPlayer,
arguments.isEmpty() ? new String[] {} : arguments.split(" "));
});
return CommandResult.success();
}
@Override public List<String> getSuggestions(CommandSource source, String arguments,
Location<World> targetPosition) throws CommandException {
if (!(source instanceof Player)) {
return ImmutableList.of();
}
PlotPlayer player = SpongeUtil.getPlayer((Player) source);
String[] args = arguments.split(" ");
if (args.length == 0) {
return Collections.singletonList(MainCommand.getInstance().toString());
}
Collection objects = MainCommand.getInstance().tab(player, args, arguments.endsWith(" "));
if (objects != null && !objects.isEmpty()) {
List<String> result = new ArrayList<>();
for (Object o : objects) {
result.add(o.toString());
}
return result;
}
List<String> names = new ArrayList<>();
String startsWith = arguments.endsWith(" ") ? "" : args[args.length - 1];
for (Map.Entry<String, PlotPlayer> entry : UUIDHandler.getPlayers().entrySet()) {
String name = entry.getKey();
if (name.startsWith(startsWith)) {
names.add(name);
}
}
return names;
}
@Override public boolean testPermission(CommandSource source) {
return true;
}
@Override public Optional<Text> getShortDescription(CommandSource source) {
return Optional.of(Text.of("Shows plot help"));
}
@Override public Optional<Text> getHelp(CommandSource source) {
return Optional.of(Text.of("/plot"));
}
@Override public Text getUsage(CommandSource source) {
return Text.of("/plot <command>");
}
}

View File

@ -0,0 +1,84 @@
package com.github.intellectualsites.plotsquared.sponge.util;
import com.github.intellectualsites.plotsquared.plot.object.OfflinePlotPlayer;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.util.EconHandler;
import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler;
import com.github.intellectualsites.plotsquared.sponge.object.SpongePlayer;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.service.ChangeServiceProviderEvent;
import org.spongepowered.api.service.economy.EconomyService;
import org.spongepowered.api.service.economy.account.UniqueAccount;
import java.math.BigDecimal;
import java.util.Optional;
public class SpongeEconHandler extends EconHandler {
private EconomyService econ;
public SpongeEconHandler() {
if (Sponge.getServiceManager().isRegistered(EconomyService.class)) {
econ = Sponge.getServiceManager().provide(EconomyService.class).get();
}
}
@Listener public void onChangeServiceProvider(ChangeServiceProviderEvent event) {
if (event.getService().equals(EconomyService.class)) {
econ = (EconomyService) event.getNewProviderRegistration().getProvider();
}
}
@Override public void withdrawMoney(PlotPlayer player, double amount) {
if (econ != null) {
Optional<UniqueAccount> accOpt = econ.getOrCreateAccount(player.getUUID());
if (accOpt.isPresent()) {
UniqueAccount acc = accOpt.get();
acc.withdraw(econ.getDefaultCurrency(), new BigDecimal(amount), SpongeUtil.CAUSE);
}
}
}
@Override public void depositMoney(PlotPlayer player, double amount) {
if (econ != null) {
Optional<UniqueAccount> accOpt = econ.getOrCreateAccount(player.getUUID());
if (accOpt.isPresent()) {
UniqueAccount acc = accOpt.get();
acc.deposit(econ.getDefaultCurrency(), new BigDecimal(amount), SpongeUtil.CAUSE);
}
}
}
@Override public void depositMoney(OfflinePlotPlayer player, double amount) {
if (econ != null) {
Optional<UniqueAccount> accOpt = econ.getOrCreateAccount(player.getUUID());
if (accOpt.isPresent()) {
UniqueAccount acc = accOpt.get();
acc.deposit(econ.getDefaultCurrency(), new BigDecimal(amount), SpongeUtil.CAUSE);
}
}
}
@Override public boolean hasPermission(String world, String player, String perm) {
SpongePlayer obj = (SpongePlayer) UUIDHandler.getPlayer(player);
if (obj != null) {
return obj.player.hasPermission(perm);
}
// TODO offline
return false;
}
@Override public double getBalance(PlotPlayer player) {
if (econ != null) {
Optional<UniqueAccount> accOpt = econ.getOrCreateAccount(player.getUUID());
if (accOpt.isPresent()) {
UniqueAccount acc = accOpt.get();
BigDecimal balance = acc.getBalance(econ.getDefaultCurrency());
return balance.doubleValue();
}
}
return 0;
}
}

View File

@ -0,0 +1,92 @@
package com.github.intellectualsites.plotsquared.sponge.util;
import com.github.intellectualsites.plotsquared.plot.flag.Flag;
import com.github.intellectualsites.plotsquared.plot.object.*;
import com.github.intellectualsites.plotsquared.plot.util.EventUtil;
import com.github.intellectualsites.plotsquared.sponge.SpongeMain;
import com.github.intellectualsites.plotsquared.sponge.events.*;
import org.spongepowered.api.event.Event;
import org.spongepowered.api.event.EventManager;
import java.util.ArrayList;
import java.util.UUID;
public class SpongeEventUtil extends EventUtil {
public EventManager events;
public SpongeEventUtil() {
this.events = SpongeMain.THIS.getGame().getEventManager();
}
public boolean callEvent(Event event) {
return !this.events.post(event);
}
@Override public boolean callClaim(PlotPlayer player, Plot plot, boolean auto) {
return callEvent(new PlayerClaimPlotEvent(SpongeUtil.getPlayer(player), plot, auto));
}
@Override public boolean callTeleport(PlotPlayer player, Location from, Plot plot) {
return callEvent(new PlayerTeleportToPlotEvent(SpongeUtil.getPlayer(player), from, plot));
}
@Override public boolean callComponentSet(Plot plot, String component) {
return callEvent(new PlotComponentSetEvent(plot, component));
}
@Override public boolean callClear(Plot plot) {
return callEvent(new PlotClearEvent(plot));
}
@Override public void callDelete(Plot plot) {
callEvent(new PlotDeleteEvent(plot));
}
@Override public boolean callFlagAdd(Flag flag, Plot plot) {
return callEvent(new PlotFlagAddEvent(flag, plot));
}
@Override public boolean callFlagRemove(Flag<?> flag, Plot plot, Object value) {
return callEvent(new PlotFlagRemoveEvent(flag, plot));
}
@Override public boolean callMerge(Plot plot, ArrayList<PlotId> plots) {
return callEvent(new PlotMergeEvent(SpongeUtil.getWorld(plot.getWorldName()), plot, plots));
}
@Override public boolean callUnlink(PlotArea area, ArrayList<PlotId> plots) {
return callEvent(new PlotUnlinkEvent(SpongeUtil.getWorld(area.worldname), plots));
}
@Override public void callEntry(PlotPlayer player, Plot plot) {
callEvent(new PlayerEnterPlotEvent(SpongeUtil.getPlayer(player), plot));
}
@Override public void callLeave(PlotPlayer player, Plot plot) {
callEvent(new PlayerLeavePlotEvent(SpongeUtil.getPlayer(player), plot));
}
@Override public void callDenied(PlotPlayer initiator, Plot plot, UUID player, boolean added) {
callEvent(new PlayerPlotDeniedEvent(SpongeUtil.getPlayer(initiator), plot, player, added));
}
@Override public void callTrusted(PlotPlayer initiator, Plot plot, UUID player, boolean added) {
callEvent(new PlayerPlotTrustedEvent(SpongeUtil.getPlayer(initiator), plot, player, added));
}
@Override public void callMember(PlotPlayer initiator, Plot plot, UUID player, boolean added) {
callEvent(new PlayerPlotHelperEvent(SpongeUtil.getPlayer(initiator), plot, player, added));
}
@Override public boolean callFlagRemove(Flag flag, Object object, PlotCluster cluster) {
return callEvent(new ClusterFlagRemoveEvent(flag, cluster));
}
@Override public Rating callRating(PlotPlayer player, Plot plot, Rating rating) {
PlotRateEvent event = new PlotRateEvent(player, rating, plot);
this.events.post(event);
return event.getRating();
}
}

View File

@ -0,0 +1,15 @@
package com.github.intellectualsites.plotsquared.sponge.util;
import com.github.intellectualsites.plotsquared.plot.generator.HybridUtils;
import com.github.intellectualsites.plotsquared.plot.object.RegionWrapper;
import com.github.intellectualsites.plotsquared.plot.object.RunnableVal;
import com.github.intellectualsites.plotsquared.plot.util.expiry.PlotAnalysis;
public class SpongeHybridUtils extends HybridUtils {
@Override public void analyzeRegion(String world, RegionWrapper region,
RunnableVal<PlotAnalysis> whenDone) {
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
}
}

View File

@ -0,0 +1,111 @@
package com.github.intellectualsites.plotsquared.sponge.util;
import com.github.intellectualsites.plotsquared.plot.object.PlotInventory;
import com.github.intellectualsites.plotsquared.plot.object.PlotItemStack;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.util.InventoryUtil;
import com.github.intellectualsites.plotsquared.sponge.SpongeMain;
import com.github.intellectualsites.plotsquared.sponge.object.SpongePlayer;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.item.ItemType;
import org.spongepowered.api.item.ItemTypes;
import org.spongepowered.api.item.inventory.Carrier;
import org.spongepowered.api.item.inventory.ItemStack;
import org.spongepowered.api.item.inventory.type.CarriedInventory;
import java.util.ArrayList;
public class SpongeInventoryUtil extends InventoryUtil {
public ItemStack.Builder builder;
public SpongeInventoryUtil() {
builder = SpongeMain.THIS.getGame().getRegistry().createBuilder(ItemStack.Builder.class);
}
@Override public void open(final PlotInventory inv) {
/*
// TODO Auto-generated method stub
final SpongePlayer sp = (SpongePlayer) inv.player;
final Player player = sp.player;
final CustomInventory inventory = Inventory.builder().of(InventoryArchetypes.MENU_ROW)property("test",
InventoryTitle.of(org.spongepowered.api.text.Text.of(inv.getTitle())))
.property("size",org.spongepowered.api.item.inventory.property.InventoryDimension.)
//name(SpongeUtil.getTranslation(inv.getTitle())).size(inv.size).build();
final PlotItemStack[] items = inv.getItems();
for (int i = 0; i < (inv.size * 9); i++) {
final PlotItemStack item = items[i];
if (item != null) {
inventory.set(new SlotIndex(i), getItem(item));
}
}
inv.player.setMeta("inventory", inv);
player.openInventory(inventory, SpongeUtil.CAUSE);
*/
throw new UnsupportedOperationException("Broken as of 1.11");
}
public ItemStack getItem(final PlotItemStack item) {
// FIXME item type, item data, item name, item lore
return builder.itemType(ItemTypes.SPONGE).quantity(item.amount).build();
}
@Override public void close(final PlotInventory inv) {
if (!inv.isOpen()) {
return;
}
inv.player.deleteMeta("inventory");
final SpongePlayer sp = (SpongePlayer) inv.player;
sp.player.closeInventory();
}
@Override
public void setItem(final PlotInventory inv, final int index, final PlotItemStack item) {
if (!inv.isOpen()) {
return;
}
final SpongePlayer sp = (SpongePlayer) inv.player;
final Player player = sp.player;
player.getOpenInventory().get();
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
}
public PlotItemStack getItem(final ItemStack item) {
if (item == null) {
return null;
}
final ItemType type = item.getItem();
final String id = type.getId();
final int amount = item.getQuantity();
// TODO name / lore
return new PlotItemStack(id, amount, null);
}
@Override public PlotItemStack[] getItems(final PlotPlayer player) {
final SpongePlayer sp = (SpongePlayer) player;
sp.player.getInventory();
new ArrayList<PlotItemStack>();
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
// return list.toArray();
}
@Override public boolean isOpen(final PlotInventory inv) {
if (!inv.isOpen()) {
return false;
}
final SpongePlayer sp = (SpongePlayer) inv.player;
final Player player = sp.player;
if (player.isViewingInventory()) {
final CarriedInventory<? extends Carrier> inventory = player.getInventory();
return inv.getTitle().equals(inventory.getName().getId()); // TODO getId()
}
return false;
}
}

View File

@ -0,0 +1,513 @@
package com.github.intellectualsites.plotsquared.sponge.util;
/*
* Copyright 2011-2013 Tyler Blair. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and contributors and should not be interpreted as representing official policies,
* either expressed or implied, of anybody else.
*/
import com.github.intellectualsites.plotsquared.plot.PS;
import com.google.inject.Inject;
import ninja.leaping.configurate.commented.CommentedConfigurationNode;
import ninja.leaping.configurate.hocon.HoconConfigurationLoader;
import ninja.leaping.configurate.loader.ConfigurationLoader;
import org.spongepowered.api.Game;
import org.spongepowered.api.plugin.PluginContainer;
import org.spongepowered.api.scheduler.Task;
import java.io.*;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.zip.GZIPOutputStream;
public class SpongeMetrics {
/**
* The current revision number
*/
private final static int REVISION = 7;
/**
* The base url of the metrics domain
*/
private static final String BASE_URL = "http://report.mcstats.org";
/**
* The url used to report a server's status
*/
private static final String REPORT_URL = "/plugin/%s";
/**
* Interval of time to ping (in minutes)
*/
private static final int PING_INTERVAL = 15;
/**
* The game data is being sent for
*/
private final Game game;
/**
* The plugin this metrics submits for
*/
private final PluginContainer plugin;
/**
* Lock for synchronization
*/
private final Object optOutLock = new Object();
/**
* The plugin configuration file
*/
private CommentedConfigurationNode config;
/**
* The configuration loader
*/
private ConfigurationLoader<CommentedConfigurationNode> configurationLoader;
/**
* The plugin configuration file
*/
private File configurationFile;
/**
* Unique server id
*/
private String guid;
/**
* Debug mode
*/
private boolean debug;
/**
* The scheduled task
*/
private volatile Task task = null;
@Inject public SpongeMetrics(final Game game, final PluginContainer plugin) {
if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null");
}
this.game = game;
this.plugin = plugin;
loadConfiguration();
}
/**
* GZip compress a string of bytes
*
* @param input
* @return
*/
public static byte[] gzip(final String input) {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = null;
try {
gzos = new GZIPOutputStream(baos);
gzos.write(input.getBytes("UTF-8"));
} catch (final IOException e) {
e.printStackTrace();
} finally {
if (gzos != null) {
try {
gzos.close();
} catch (final IOException ignore) {
}
}
}
return baos.toByteArray();
}
/**
* Appends a json encoded key/value pair to the given string builder.
*
* @param json
* @param key
* @param value
* @throws UnsupportedEncodingException
*/
private static void appendJSONPair(final StringBuilder json, final String key,
final String value) {
boolean isValueNumeric = false;
try {
if (value.equals("0") || !value.endsWith("0")) {
Double.parseDouble(value);
isValueNumeric = true;
}
} catch (final NumberFormatException ignored) {
isValueNumeric = false;
}
if (json.charAt(json.length() - 1) != '{') {
json.append(',');
}
json.append(escapeJSON(key));
json.append(':');
if (isValueNumeric) {
json.append(value);
} else {
json.append(escapeJSON(value));
}
}
/**
* Escape a string to create a valid JSON string
*
* @param text
* @return
*/
private static String escapeJSON(final String text) {
final StringBuilder builder = new StringBuilder();
builder.append('"');
for (int index = 0; index < text.length(); index++) {
final char chr = text.charAt(index);
switch (chr) {
case '"':
case '\\':
builder.append('\\');
builder.append(chr);
break;
case '\b':
builder.append("\\b");
break;
case '\t':
builder.append("\\t");
break;
case '\n':
builder.append("\\n");
break;
case '\r':
builder.append("\\r");
break;
default:
if (chr < ' ') {
final String t = "000" + Integer.toHexString(chr);
builder.append("\\u" + t.substring(t.length() - 4));
} else {
builder.append(chr);
}
break;
}
}
builder.append('"');
return builder.toString();
}
/**
* Encode text as UTF-8
*
* @param text the text to encode
* @return the encoded text, as UTF-8
*/
private static String urlEncode(final String text) throws UnsupportedEncodingException {
return URLEncoder.encode(text, "UTF-8");
}
/**
* Loads the configuration
*/
private void loadConfiguration() {
configurationFile = getConfigFile();
configurationLoader = HoconConfigurationLoader.builder().setFile(configurationFile).build();
try {
if (!configurationFile.exists()) {
configurationFile.createNewFile();
config = configurationLoader.load();
config.setComment("This contains settings for MCStats: http://mcstats.org");
config.getNode("mcstats.guid").setValue(UUID.randomUUID().toString());
config.getNode("mcstats.opt-out").setValue(false);
config.getNode("mcstats.debug").setValue(false);
configurationLoader.save(config);
} else {
config = configurationLoader.load();
}
guid = config.getNode("mcstats.guid").getString();
debug = config.getNode("mcstats.debug").getBoolean();
} catch (final IOException e) {
e.printStackTrace();
}
}
/**
* Start measuring statistics. This will immediately create an async repeating task as the plugin and send the
* initial data to the metrics backend, and then after that it will post in increments of PING_INTERVAL * 1200
* ticks.
*
* @return True if statistics measuring is running, otherwise false.
*/
public boolean start() {
synchronized (optOutLock) {
// Did we opt out?
if (isOptOut()) {
return false;
}
// Is metrics already running?
if (task != null) {
return true;
}
// Begin hitting the server with glorious data
final Task.Builder builder = game.getScheduler().createTaskBuilder();
builder.async().interval(PING_INTERVAL, TimeUnit.MINUTES).execute(new Runnable() {
private boolean firstPost = true;
@Override public void run() {
try {
// This has to be synchronized or it can collide with the disable method.
synchronized (optOutLock) {
// Disable Task, if it is running and the server owner decided to opt-out
if (isOptOut() && (task != null)) {
task.cancel();
task = null;
}
}
// We use the inverse of firstPost because if it is the first time we are posting,
// it is not a interval ping, so it evaluates to FALSE
// Each time thereafter it will evaluate to TRUE, i.e PING!
postPlugin(!firstPost);
// After the first post we set firstPost to false
// Each post thereafter will be a ping
firstPost = false;
} catch (final IOException e) {
if (debug) {
PS.debug("[Metrics] " + e.getMessage());
}
}
}
});
return true;
}
}
/**
* Has the server owner denied plugin metrics?
*
* @return true if metrics should be opted out of it
*/
public boolean isOptOut() {
synchronized (optOutLock) {
loadConfiguration();
return config.getNode("mcstats.opt-out").getBoolean();
}
}
/**
* Enables metrics for the server by setting "opt-out" to false in the config file and starting the metrics task.
*
* @throws IOException
*/
public void enable() throws IOException {
// This has to be synchronized or it can collide with the check in the task.
synchronized (optOutLock) {
// Check if the server owner has already set opt-out, if not, set it.
if (isOptOut()) {
config.getNode("mcstats.opt-out").setValue(false);
configurationLoader.save(config);
}
// Enable Task, if it is not running
if (task == null) {
start();
}
}
}
/**
* Disables metrics for the server by setting "opt-out" to true in the config file and canceling the metrics task.
*
* @throws IOException
*/
public void disable() throws IOException {
// This has to be synchronized or it can collide with the check in the task.
synchronized (optOutLock) {
// Check if the server owner has already set opt-out, if not, set it.
if (!isOptOut()) {
config.getNode("mcstats.opt-out").setValue(true);
configurationLoader.save(config);
}
// Disable Task, if it is running
if (task != null) {
task.cancel();
task = null;
}
}
}
/**
* Gets the File object of the config file that should be used to store data such as the GUID and opt-out status
*
* @return the File object for the config file
*/
public File getConfigFile() {
// TODO configDir
final File configFolder = new File("config");
return new File(configFolder, "PluginMetrics.conf");
}
/**
* Generic method that posts a plugin to the metrics website
*/
private void postPlugin(final boolean isPing) throws IOException {
// Server software specific section
final String pluginName = plugin.getName();
final boolean onlineMode =
game.getServer().getOnlineMode(); // TRUE if online mode is enabled
final String pluginVersion = plugin.getVersion().orElse("unknown");
final String serverVersion =
String.format("%s %s", "Sponge", game.getPlatform().getMinecraftVersion());
final int playersOnline = game.getServer().getOnlinePlayers().size();
// END server software specific section -- all code below does not use any code outside of this class / Java
// Construct the post data
final StringBuilder json = new StringBuilder(1024);
json.append('{');
// The plugin's description file containg all of the plugin data such as name, version, author, etc
appendJSONPair(json, "guid", guid);
appendJSONPair(json, "plugin_version", pluginVersion);
appendJSONPair(json, "server_version", serverVersion);
appendJSONPair(json, "players_online", Integer.toString(playersOnline));
// New data as of R6
final String osname = System.getProperty("os.name");
String osarch = System.getProperty("os.arch");
final String osversion = System.getProperty("os.version");
final String java_version = System.getProperty("java.version");
final int coreCount = Runtime.getRuntime().availableProcessors();
// normalize os arch .. amd64 -> x86_64
if (osarch.equals("amd64")) {
osarch = "x86_64";
}
appendJSONPair(json, "osname", osname);
appendJSONPair(json, "osarch", osarch);
appendJSONPair(json, "osversion", osversion);
appendJSONPair(json, "cores", Integer.toString(coreCount));
appendJSONPair(json, "auth_mode", onlineMode ? "1" : "0");
appendJSONPair(json, "java_version", java_version);
// If we're pinging, append it
if (isPing) {
appendJSONPair(json, "ping", "1");
}
// close json
json.append('}');
// Create the url
final URL url = new URL(BASE_URL + String.format(REPORT_URL, urlEncode(pluginName)));
// Connect to the website
URLConnection connection;
// Mineshafter creates a socks proxy, so we can safely bypass it
// It does not reroute POST requests so we need to go around it
if (isMineshafterPresent()) {
connection = url.openConnection(Proxy.NO_PROXY);
} else {
connection = url.openConnection();
}
final byte[] uncompressed = json.toString().getBytes();
final byte[] compressed = gzip(json.toString());
// Headers
connection.addRequestProperty("User-Agent", "MCStats/" + REVISION);
connection.addRequestProperty("Content-Type", "application/json");
connection.addRequestProperty("Content-Encoding", "gzip");
connection.addRequestProperty("Content-Length", Integer.toString(compressed.length));
connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close");
connection.setDoOutput(true);
if (debug) {
PS.debug("[Metrics] Prepared request for " + pluginName + " uncompressed="
+ uncompressed.length + " compressed=" + compressed.length);
}
// Write the data
final OutputStream os = connection.getOutputStream();
os.write(compressed);
os.flush();
// Now read the response
final BufferedReader reader =
new BufferedReader(new InputStreamReader(connection.getInputStream()));
String response = reader.readLine();
// close resources
os.close();
reader.close();
if ((response == null) || response.startsWith("ERR") || response.startsWith("7")) {
if (response == null) {
response = "null";
} else if (response.startsWith("7")) {
response = response.substring(response.startsWith("7,") ? 2 : 1);
}
throw new IOException(response);
}
}
/**
* Check if mineshafter is present. If it is, we need to bypass it to send POST requests
*
* @return true if mineshafter is installed on the server
*/
private boolean isMineshafterPresent() {
try {
Class.forName("mineshafter.MineServer");
return true;
} catch (final Exception ignored) {
return false;
}
}
}

View File

@ -0,0 +1,299 @@
package com.github.intellectualsites.plotsquared.sponge.util;
import com.github.intellectualsites.plotsquared.jnbt.*;
import com.github.intellectualsites.plotsquared.plot.object.*;
import com.github.intellectualsites.plotsquared.plot.util.MainUtil;
import com.github.intellectualsites.plotsquared.plot.util.SchematicHandler;
import com.github.intellectualsites.plotsquared.plot.util.TaskManager;
import com.github.intellectualsites.plotsquared.plot.util.block.LocalBlockQueue;
import org.spongepowered.api.block.BlockState;
import org.spongepowered.api.item.inventory.Carrier;
import org.spongepowered.api.item.inventory.type.CarriedInventory;
import org.spongepowered.api.world.World;
import java.util.*;
import java.util.Map.Entry;
public class SpongeSchematicHandler extends SchematicHandler {
@Override
public boolean restoreTile(LocalBlockQueue queue, CompoundTag tag, int x, int y, int z) {
// TODO Auto-generated method stub
// This method should place the compound tag at a location e.g. chest contents
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
}
@Override public void getCompoundTag(String world, Set<RegionWrapper> regions,
RunnableVal<CompoundTag> whenDone) {
// async
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
// Main positions
Location[] corners = MainUtil.getCorners(world, regions);
Location bot = corners[0];
Location top = corners[1];
int width = top.getX() - bot.getX() + 1;
int height = top.getY() - bot.getY() + 1;
int length = top.getZ() - bot.getZ() + 1;
// Main Schematic tag
HashMap<String, Tag> schematic = new HashMap<>();
schematic.put("Width", new ShortTag("Width", (short) width));
schematic.put("Length", new ShortTag("Length", (short) length));
schematic.put("Height", new ShortTag("Height", (short) height));
schematic.put("Materials", new StringTag("Materials", "Alpha"));
schematic.put("WEOriginX", new IntTag("WEOriginX", 0));
schematic.put("WEOriginY", new IntTag("WEOriginY", 0));
schematic.put("WEOriginZ", new IntTag("WEOriginZ", 0));
schematic.put("WEOffsetX", new IntTag("WEOffsetX", 0));
schematic.put("WEOffsetY", new IntTag("WEOffsetY", 0));
schematic.put("WEOffsetZ", new IntTag("WEOffsetZ", 0));
// Arrays of data types
List<Tag> tileEntities = new ArrayList<>();
byte[] blocks = new byte[width * height * length];
byte[] blockData = new byte[width * height * length];
// Queue
ArrayDeque<RegionWrapper> queue = new ArrayDeque<>(regions);
TaskManager.runTask(new Runnable() {
@Override public void run() {
if (queue.isEmpty()) {
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
schematic.put("Blocks", new ByteArrayTag("Blocks", blocks));
schematic.put("Data", new ByteArrayTag("Data", blockData));
schematic.put("Entities",
new ListTag("Entities", CompoundTag.class,
new ArrayList<>()));
schematic.put("TileEntities",
new ListTag("TileEntities", CompoundTag.class,
tileEntities));
whenDone.value = new CompoundTag("Schematic", schematic);
TaskManager.runTask(whenDone);
System.gc();
System.gc();
}
});
return;
}
Runnable regionTask = this;
RegionWrapper region = queue.poll();
Location pos1 = new Location(world, region.minX, region.minY, region.minZ);
Location pos2 = new Location(world, region.maxX, region.maxY, region.maxZ);
int bx = bot.getX();
int bz = bot.getZ();
int p1x = pos1.getX();
int p1z = pos1.getZ();
int p2x = pos2.getX();
int p2z = pos2.getZ();
int bcx = p1x >> 4;
int bcz = p1z >> 4;
int tcx = p2x >> 4;
int tcz = p2z >> 4;
int sy = pos1.getY();
int ey = pos2.getY();
// Generate list of chunks
ArrayList<ChunkLoc> chunks = new ArrayList<>();
for (int x = bcx; x <= tcx; x++) {
for (int z = bcz; z <= tcz; z++) {
chunks.add(new ChunkLoc(x, z));
}
}
World worldObj = SpongeUtil.getWorld(world);
// Main thread
TaskManager.runTask(new Runnable() {
@Override public void run() {
long start = System.currentTimeMillis();
while (!chunks.isEmpty()
&& System.currentTimeMillis() - start < 20) {
// save schematics
ChunkLoc chunk = chunks.remove(0);
int X = chunk.x;
int Z = chunk.z;
int xxb = X << 4;
int zzb = Z << 4;
if (!worldObj.getChunk(xxb, 1, zzb).isPresent() && !worldObj
.loadChunk(xxb, 1, zzb, false).isPresent()) {
continue;
}
int xxt = xxb + 15;
int zzt = zzb + 15;
if (X == bcx) {
xxb = p1x;
}
if (X == tcx) {
xxt = p2x;
}
if (Z == bcz) {
zzb = p1z;
}
if (Z == tcz) {
zzt = p2z;
}
for (int y = sy; y <= Math.min(255, ey); y++) {
int ry = y - sy;
int i1 = ry * width * length;
for (int z = zzb; z <= zzt; z++) {
int rz = z - p1z;
int i2 = i1 + rz * width;
for (int x = xxb; x <= xxt; x++) {
int rx = x - p1x;
int index = i2 + rx;
BlockState state = worldObj.getBlock(x, y, z);
PlotBlock block = SpongeUtil.getPlotBlock(state);
int id = block.id;
switch (id) {
case 0:
case 2:
case 4:
case 13:
case 14:
case 15:
case 20:
case 21:
case 22:
case 24:
case 30:
case 32:
case 37:
case 39:
case 40:
case 41:
case 42:
case 45:
case 46:
case 47:
case 48:
case 49:
case 51:
case 55:
case 56:
case 57:
case 58:
case 60:
case 7:
case 8:
case 9:
case 10:
case 11:
case 73:
case 74:
case 78:
case 79:
case 80:
case 81:
case 82:
case 83:
case 85:
case 87:
case 88:
case 101:
case 102:
case 103:
case 110:
case 112:
case 113:
case 121:
case 122:
case 129:
case 133:
case 165:
case 166:
case 169:
case 170:
case 172:
case 173:
case 174:
case 181:
case 182:
case 188:
case 189:
case 190:
case 191:
case 192:
break;
case 54:
case 130:
case 142:
case 27:
case 137:
case 52:
case 154:
case 84:
case 25:
case 144:
case 138:
case 176:
case 177:
case 63:
case 68:
case 323:
case 117:
case 116:
case 28:
case 66:
case 157:
case 61:
case 62:
case 140:
case 146:
case 149:
case 150:
case 158:
case 23:
case 123:
case 124:
case 29:
case 33:
case 151:
case 178:
CompoundTag rawTag;
if (state instanceof Carrier) {
Carrier chest = (Carrier) state;
CarriedInventory<? extends Carrier>
inv = chest.getInventory();
// TODO serialize inventory
rawTag = null;
} else {
rawTag = null;
}
if (rawTag != null) {
Map<String, Tag> values =
new HashMap<>();
for (Entry<String, Tag> entry : rawTag
.getValue().entrySet()) {
values.put(entry.getKey(),
entry.getValue());
}
values.put("id",
new StringTag("id", "Chest"));
values.put("x", new IntTag("x", x));
values.put("y", new IntTag("y", y));
values.put("z", new IntTag("z", z));
CompoundTag tileEntityTag =
new CompoundTag(values);
tileEntities.add(tileEntityTag);
}
default:
blockData[index] = block.data;
}
blocks[index] = (byte) id;
}
}
}
}
if (!chunks.isEmpty()) {
TaskManager.runTaskLater(this, 1);
} else {
regionTask.run();
}
}
});
}
});
}
});
}
}

View File

@ -0,0 +1,203 @@
package com.github.intellectualsites.plotsquared.sponge.util;
import com.github.intellectualsites.plotsquared.configuration.ConfigurationSection;
import com.github.intellectualsites.plotsquared.plot.PS;
import com.github.intellectualsites.plotsquared.plot.config.ConfigurationNode;
import com.github.intellectualsites.plotsquared.plot.generator.GeneratorWrapper;
import com.github.intellectualsites.plotsquared.plot.object.PlotArea;
import com.github.intellectualsites.plotsquared.plot.object.SetupObject;
import com.github.intellectualsites.plotsquared.plot.object.worlds.SingleWorldGenerator;
import com.github.intellectualsites.plotsquared.plot.util.SetupUtils;
import com.github.intellectualsites.plotsquared.sponge.generator.SpongePlotGenerator;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.world.DimensionTypes;
import org.spongepowered.api.world.GeneratorTypes;
import org.spongepowered.api.world.World;
import org.spongepowered.api.world.WorldArchetype;
import org.spongepowered.api.world.gen.WorldGenerator;
import org.spongepowered.api.world.gen.WorldGeneratorModifier;
import org.spongepowered.api.world.storage.WorldProperties;
import java.io.IOException;
import java.util.*;
import java.util.Map.Entry;
public class SpongeSetupUtils extends SetupUtils {
@Override public void updateGenerators() {
if (!SetupUtils.generators.isEmpty()) {
return;
}
SetupUtils.generators.put(PS.imp().getPluginName(),
new SpongePlotGenerator(PS.get().IMP.getDefaultGenerator()));
SetupUtils.generators.put(PS.imp().getPluginName() + ":single",
new SpongePlotGenerator(new SingleWorldGenerator()));
// TODO get external world generators
Collection<WorldGeneratorModifier> wgms =
Sponge.getRegistry().getAllOf(WorldGeneratorModifier.class);
for (WorldGeneratorModifier wgm : wgms) {
String id = wgm.getId();
String name = wgm.getName();
if (wgm instanceof GeneratorWrapper<?>) {
SetupUtils.generators.put(id, (GeneratorWrapper<?>) wgm);
SetupUtils.generators.put(name, (GeneratorWrapper<?>) wgm);
} else {
SpongePlotGenerator wrap = new SpongePlotGenerator(wgm);
SetupUtils.generators.put(id, wrap);
SetupUtils.generators.put(name, wrap);
}
}
}
@Override public void unload(String worldName, boolean safe) {
Optional<World> world = Sponge.getServer().getWorld(worldName);
if (world.isPresent()) {
Sponge.getServer().unloadWorld(world.get());
}
}
@Override public String getGenerator(PlotArea plotArea) {
if (SetupUtils.generators.isEmpty()) {
updateGenerators();
}
World world = SpongeUtil.getWorld(plotArea.worldname);
if (world == null) {
return null;
}
WorldGenerator generator = world.getWorldGenerator();
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
}
@Override public String setupWorld(SetupObject object) {
SetupUtils.manager.updateGenerators();
ConfigurationNode[] steps = object.step == null ? new ConfigurationNode[0] : object.step;
String world = object.world;
int type = object.type;
String worldPath = "worlds." + object.world;
switch (type) {
case 2: {
if (!PS.get().worlds.contains(worldPath)) {
PS.get().worlds.createSection(worldPath);
}
ConfigurationSection worldSection =
PS.get().worlds.getConfigurationSection(worldPath);
if (object.id != null) {
String areaName = object.id + "-" + object.min + "-" + object.max;
String areaPath = "areas." + areaName;
if (!worldSection.contains(areaPath)) {
worldSection.createSection(areaPath);
}
ConfigurationSection areaSection =
worldSection.getConfigurationSection(areaPath);
HashMap<String, Object> options = new HashMap<>();
for (ConfigurationNode step : steps) {
options.put(step.getConstant(), step.getValue());
}
options.put("generator.type", object.type);
options.put("generator.terrain", object.terrain);
options.put("generator.plugin", object.plotManager);
if (object.setupGenerator != null && !object.setupGenerator
.equals(object.plotManager)) {
options.put("generator.init", object.setupGenerator);
}
for (Entry<String, Object> entry : options.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (worldSection.contains(key)) {
Object current = worldSection.get(key);
if (!Objects.equals(value, current)) {
areaSection.set(key, value);
}
} else {
worldSection.set(key, value);
}
}
}
GeneratorWrapper<?> gen = SetupUtils.generators.get(object.setupGenerator);
if (gen != null && gen.isFull()) {
object.setupGenerator = null;
}
break;
}
case 1: {
if (!PS.get().worlds.contains(worldPath)) {
PS.get().worlds.createSection(worldPath);
}
ConfigurationSection worldSection =
PS.get().worlds.getConfigurationSection(worldPath);
for (ConfigurationNode step : steps) {
worldSection.set(step.getConstant(), step.getValue());
}
PS.get().worlds.set("worlds." + world + ".generator.type", object.type);
PS.get().worlds.set("worlds." + world + ".generator.terrain", object.terrain);
PS.get().worlds.set("worlds." + world + ".generator.plugin", object.plotManager);
if (object.setupGenerator != null && !object.setupGenerator
.equals(object.plotManager)) {
PS.get().worlds
.set("worlds." + world + ".generator.init", object.setupGenerator);
}
GeneratorWrapper<?> gen = SetupUtils.generators.get(object.setupGenerator);
if (gen != null && gen.isFull()) {
object.setupGenerator = null;
}
break;
}
case 0: {
if (steps.length != 0) {
if (!PS.get().worlds.contains(worldPath)) {
PS.get().worlds.createSection(worldPath);
}
ConfigurationSection worldSection =
PS.get().worlds.getConfigurationSection(worldPath);
for (ConfigurationNode step : steps) {
worldSection.set(step.getConstant(), step.getValue());
}
}
break;
}
}
try {
PS.get().worlds.save(PS.get().worldsFile);
} catch (IOException e) {
e.printStackTrace();
}
if (object.setupGenerator != null) {
// create world with generator
GeneratorWrapper<?> gw = SetupUtils.generators.get(object.setupGenerator);
WorldGeneratorModifier wgm = (WorldGeneratorModifier) gw.getPlatformGenerator();
WorldArchetype settings =
WorldArchetype.builder().loadsOnStartup(true).keepsSpawnLoaded(true)
.dimension(DimensionTypes.OVERWORLD).generator(GeneratorTypes.FLAT)
.usesMapFeatures(false).enabled(true).generatorModifiers(wgm)
.build("PS-" + UUID.randomUUID(), object.world);
WorldProperties properties = null;
try {
properties = Sponge.getServer().createWorldProperties(object.world, settings);
} catch (IOException e) {
e.printStackTrace();
}
World worldObj;
Optional<World> world1 = Sponge.getServer().loadWorld(properties);
if (world1.isPresent()) {
worldObj = world1.get();
}
System.out.println("Create normal world");
} else {
System.out.println("Create vanilla world");
// create vanilla world
WorldArchetype settings =
WorldArchetype.builder().loadsOnStartup(true).keepsSpawnLoaded(true)
.dimension(DimensionTypes.OVERWORLD).generator(GeneratorTypes.OVERWORLD)
.usesMapFeatures(true).enabled(true)
.build("PS-" + UUID.randomUUID(), object.world);
WorldProperties properties = null;
try {
properties = Sponge.getServer().createWorldProperties(object.world, settings);
} catch (IOException e) {
e.printStackTrace();
}
World worldObj = Sponge.getServer().loadWorld(properties).get();
}
return object.world;
}
}

View File

@ -0,0 +1,67 @@
package com.github.intellectualsites.plotsquared.sponge.util;
import com.github.intellectualsites.plotsquared.plot.util.TaskManager;
import com.github.intellectualsites.plotsquared.sponge.SpongeMain;
import org.spongepowered.api.scheduler.Task;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicInteger;
public class SpongeTaskManager extends TaskManager {
private final AtomicInteger i = new AtomicInteger();
private final HashMap<Integer, Task> tasks = new HashMap<>();
private final SpongeMain spongeMain;
public SpongeTaskManager(SpongeMain spongeMain) {
this.spongeMain = spongeMain;
}
@Override public int taskRepeat(Runnable runnable, int interval) {
int val = this.i.incrementAndGet();
Task.Builder builder = this.spongeMain.getGame().getScheduler().createTaskBuilder();
Task.Builder built = builder.delayTicks(interval).intervalTicks(interval).execute(runnable);
Task task = built.submit(this.spongeMain.getPlugin());
this.tasks.put(val, task);
return val;
}
@Override public int taskRepeatAsync(Runnable runnable, int interval) {
int val = this.i.incrementAndGet();
Task.Builder builder = this.spongeMain.getGame().getScheduler().createTaskBuilder();
Task.Builder built =
builder.delayTicks(interval).async().intervalTicks(interval).execute(runnable);
Task task = built.submit(this.spongeMain.getPlugin());
this.tasks.put(val, task);
return val;
}
@Override public void taskAsync(Runnable runnable) {
Task.Builder builder = this.spongeMain.getGame().getScheduler().createTaskBuilder();
builder.async().execute(runnable).submit(this.spongeMain.getPlugin());
}
@Override public void task(Runnable runnable) {
Task.Builder builder = this.spongeMain.getGame().getScheduler().createTaskBuilder();
builder.execute(runnable).submit(this.spongeMain.getPlugin());
}
@Override public void taskLater(Runnable runnable, int delay) {
Task.Builder builder = this.spongeMain.getGame().getScheduler().createTaskBuilder();
builder.delayTicks(delay).execute(runnable).submit(this.spongeMain.getPlugin());
}
@Override public void taskLaterAsync(Runnable runnable, int delay) {
Task.Builder builder = this.spongeMain.getGame().getScheduler().createTaskBuilder();
builder.async().delayTicks(delay).execute(runnable).submit(this.spongeMain.getPlugin());
}
@Override public void cancelTask(int i) {
Task task = this.tasks.remove(i);
if (task != null) {
task.cancel();
}
}
}

View File

@ -0,0 +1,17 @@
package com.github.intellectualsites.plotsquared.sponge.util;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.util.AbstractTitle;
import com.github.intellectualsites.plotsquared.sponge.object.SpongePlayer;
import org.spongepowered.api.text.title.Title;
public class SpongeTitleManager extends AbstractTitle {
@Override
public void sendTitle(PlotPlayer player, String head, String sub, int in, int delay, int out) {
Title title =
Title.builder().title(SpongeUtil.getText(head)).subtitle(SpongeUtil.getText(sub))
.fadeIn(in * 20).stay(delay * 20).fadeOut(out * 20).build();
((SpongePlayer) player).player.sendTitle(title);
}
}

View File

@ -0,0 +1,416 @@
package com.github.intellectualsites.plotsquared.sponge.util;
import com.flowpowered.math.vector.Vector3d;
import com.flowpowered.math.vector.Vector3i;
import com.github.intellectualsites.plotsquared.plot.PS;
import com.github.intellectualsites.plotsquared.plot.config.C;
import com.github.intellectualsites.plotsquared.plot.object.Location;
import com.github.intellectualsites.plotsquared.plot.object.PlotBlock;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.object.RegionWrapper;
import com.github.intellectualsites.plotsquared.plot.object.schematic.PlotItem;
import com.github.intellectualsites.plotsquared.plot.util.*;
import com.github.intellectualsites.plotsquared.sponge.SpongeMain;
import com.github.intellectualsites.plotsquared.sponge.object.SpongePlayer;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.world.biome.Biome;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.block.BlockState;
import org.spongepowered.api.block.BlockType;
import org.spongepowered.api.block.BlockTypes;
import org.spongepowered.api.block.tileentity.Sign;
import org.spongepowered.api.block.tileentity.TileEntity;
import org.spongepowered.api.data.key.Keys;
import org.spongepowered.api.data.manipulator.mutable.tileentity.SignData;
import org.spongepowered.api.data.property.block.SolidCubeProperty;
import org.spongepowered.api.data.value.mutable.ListValue;
import org.spongepowered.api.entity.Entity;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.cause.EventContext;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.serializer.TextSerializers;
import org.spongepowered.api.text.translation.Translation;
import org.spongepowered.api.world.World;
import org.spongepowered.api.world.biome.BiomeType;
import org.spongepowered.api.world.biome.BiomeTypes;
import org.spongepowered.api.world.extent.Extent;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;
public class SpongeUtil extends WorldUtil {
public static Cause CAUSE =
Cause.builder().append(Sponge.getPluginManager().fromInstance(SpongeMain.THIS).get())
.build(EventContext.empty());
private static BiomeType[] biomes;
private static HashMap<String, Integer> biomeMap;
private static Player lastPlayer = null;
private static PlotPlayer lastPlotPlayer = null;
private static World lastWorld;
private static String last;
public static Location getLocation(Entity player) {
String world = player.getWorld().getName();
org.spongepowered.api.world.Location loc = player.getLocation();
Vector3i pos = loc.getBlockPosition();
return new Location(world, pos.getX(), pos.getY(), pos.getZ());
}
public static BiomeType getBiome(String biome) {
if (biomes == null) {
initBiomeCache();
}
return biomes[biomeMap.get(biome.toUpperCase())];
}
public static <T> T getCause(Cause cause, Class<T> clazz) {
Optional<?> root = Optional.of(cause.root());
if (root.isPresent()) {
Object source = root.get();
if (clazz.isInstance(source)) {
return (T) source;
}
}
return null;
}
public static void printCause(String method, Cause cause) {
System.out.println(method + ": " + cause.toString());
System.out.println(method + ": " + cause.getClass());
System.out.println(method + ": " + StringMan.getString(cause.all()));
System.out.println(method + ": " + cause.root());
}
public static void initBiomeCache() {
try {
Field[] fields = BiomeTypes.class.getFields();
biomes = new BiomeType[fields.length];
biomeMap = new HashMap<>();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
String name = field.getName();
biomeMap.put(name, i);
biomes[i] = (BiomeType) field.get(null);
}
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
}
public static BiomeType getBiome(int index) {
return (BiomeType) Biome.getBiome(index);
}
public static Text getText(String m) {
return TextSerializers.LEGACY_FORMATTING_CODE.deserialize(C.color(m));
}
public static Translation getTranslation(String m) {
return new Translation() {
@Override public String getId() {
return m;
}
@Override public String get(Locale l, Object... args) {
return m;
}
@Override public String get(Locale l) {
return m;
}
};
}
public static BlockState getBlockState(int id, int data) {
return (BlockState) Block.getBlockById(id).getStateFromMeta(data);
}
public static PlotBlock getPlotBlock(BlockState state) {
if (state == null) {
return PlotBlock.get(0, 0);
}
IBlockState ibs = ((IBlockState) state);
Block block = ibs.getBlock();
int id = Block.getIdFromBlock(block);
int data = block.getMetaFromState(ibs);
return PlotBlock.get(id, data);
}
public static Location getLocation(org.spongepowered.api.world.Location<World> block) {
return getLocation(block.getExtent().getName(), block);
}
public static Location getLocationFull(Entity player) {
String world = player.getWorld().getName();
Vector3d rot = player.getRotation();
float[] pitchYaw =
MathMan.getPitchAndYaw((float) rot.getX(), (float) rot.getY(), (float) rot.getZ());
org.spongepowered.api.world.Location loc = player.getLocation();
Vector3i pos = loc.getBlockPosition();
return new Location(world, pos.getX(), pos.getY(), pos.getZ(), pitchYaw[1], pitchYaw[0]);
}
public static PlotPlayer getPlayer(Player player) {
if (player == lastPlayer) {
return lastPlotPlayer;
}
String name = player.getName();
PlotPlayer pp = UUIDHandler.getPlayer(name);
if (pp != null) {
return pp;
}
lastPlotPlayer = new SpongePlayer(player);
UUIDHandler.getPlayers().put(name, lastPlotPlayer);
lastPlayer = player;
return lastPlotPlayer;
}
public static Player getPlayer(PlotPlayer player) {
if (player instanceof SpongePlayer) {
return ((SpongePlayer) player).player;
}
return null;
}
public static World getWorld(String world) {
if (StringMan.isEqual(world, last)) {
return lastWorld;
}
Optional<World> optional = Sponge.getServer().getWorld(world);
if (!optional.isPresent()) {
last = null;
return lastWorld = null;
}
last = world;
return lastWorld = optional.get();
}
public static void removePlayer(String player) {
lastPlayer = null;
lastPlotPlayer = null;
}
public static Location getLocation(String world, org.spongepowered.api.world.Location spawn) {
return new Location(world, spawn.getBlockX(), spawn.getBlockY(), spawn.getBlockZ());
}
public static String getWorldName(org.spongepowered.api.world.Location origin) {
Extent extent = origin.getExtent();
if (extent == lastWorld) {
return lastWorld.getName();
}
if (extent instanceof World) {
lastWorld = (World) extent;
return lastWorld.getName();
}
return null;
}
public static org.spongepowered.api.world.Location<World> getLocation(Location location) {
Collection<World> worlds = Sponge.getServer().getWorlds();
World world = Sponge.getServer().getWorld(location.getWorld())
.orElse(worlds.toArray(new World[worlds.size()])[0]);
return new org.spongepowered.api.world.Location<>(world, location.getX(), location.getY(),
location.getZ());
}
public static Location getLocation(String world, Vector3i position) {
return new Location(world, position.getX(), position.getY(), position.getZ());
}
public static Location getLocation(String world, Vector3d position) {
return new Location(world, MathMan.roundInt(position.getX()),
MathMan.roundInt(position.getY()), MathMan.roundInt(position.getZ()));
}
@Override public boolean isBlockSolid(PlotBlock block) {
BlockState state = SpongeUtil.getBlockState(block.id, block.data);
Optional<SolidCubeProperty> property = state.getType().getProperty(SolidCubeProperty.class);
if (property.isPresent()) {
return property.get().getValue();
} else {
return false;
}
}
@Override public StringComparison<PlotBlock>.ComparisonResult getClosestBlock(String name) {
try {
byte data;
String[] split = name.split(":");
if (split.length == 2) {
data = Byte.parseByte(split[1]);
name = split[0];
} else {
data = 0;
}
short id;
double match;
if (MathMan.isInteger(split[0])) {
id = Short.parseShort(split[0]);
match = 0;
} else {
List<BlockType> types = ReflectionUtils.getStaticFields(BlockTypes.class);
StringComparison<BlockType>.ComparisonResult comparison =
new StringComparison<BlockType>(name,
types.toArray(new BlockType[types.size()])) {
@Override public String getString(BlockType type) {
return type.getId();
}
}.getBestMatchAdvanced();
match = comparison.match;
id = SpongeUtil.getPlotBlock(comparison.best.getDefaultState()).id;
}
PlotBlock block = PlotBlock.get(id, data);
StringComparison<PlotBlock> outer = new StringComparison<PlotBlock>();
return outer.new ComparisonResult(match, block);
} catch (NumberFormatException ignored) {
}
return null;
}
@Override public String getClosestMatchingName(PlotBlock block) {
// TODO Auto-generated method stub
return null;
}
@Override public String[] getBiomeList() {
if (biomes == null) {
initBiomeCache();
}
return biomeMap.keySet().toArray(new String[biomeMap.size()]);
}
@Override public boolean addItems(String world, PlotItem items) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
}
@Override public int getBiomeFromString(String biome) {
if (biomes == null) {
initBiomeCache();
}
return biomeMap.get(biome.toUpperCase());
}
@Override public String getBiome(String world, int x, int z) {
return SpongeUtil.getWorld(world).getBiome(x, 0, z).getName().toUpperCase();
}
@Override public PlotBlock getBlock(Location location) {
BlockState state = SpongeUtil.getWorld(location.getWorld())
.getBlock(location.getX(), location.getY(), location.getZ());
return SpongeUtil.getPlotBlock(state);
}
@Override public Location getSpawn(PlotPlayer plotPlayer) {
World world = getWorld(plotPlayer.getLocation().getWorld());
return SpongeUtil.getLocation(world.getSpawnLocation());
}
@Override public Location getSpawn(String world) {
Location result =
SpongeUtil.getLocation(world, SpongeUtil.getWorld(world).getSpawnLocation());
result.setY(1 + getHighestBlock(world, result.getX(), result.getZ()));
return result;
}
@Override public void setSpawn(Location location) {
World world = getWorld(location.getWorld());
if (world != null) {
world.getProperties()
.setSpawnPosition(new Vector3i(location.getX(), location.getY(), location.getZ()));
}
}
@Override public void saveWorld(String worldName) {
try {
SpongeUtil.getWorld(worldName).save();
} catch (IOException e) {
e.printStackTrace();
PS.debug("Failed to save world.");
}
}
@Override public String[] getSign(Location location) {
World world = SpongeUtil.getWorld(location.getWorld());
Optional<TileEntity> block =
world.getTileEntity(location.getX(), location.getY(), location.getZ());
if (!block.isPresent()) {
return null;
}
TileEntity tile = block.get();
if (!(tile instanceof Sign)) {
return null;
}
Sign sign = (Sign) tile;
Optional<SignData> optional = sign.get(SignData.class);
if (!optional.isPresent()) {
return null;
}
String[] result = new String[4];
ListValue<Text> lines = optional.get().lines();
for (int i = 0; i < 4; i++) {
result[i] = lines.get(i).toString();
}
return result;
}
@Override public boolean isWorld(String worldName) {
return SpongeUtil.getWorld(worldName) != null;
}
@Override public String getMainWorld() {
return Sponge.getServer().getWorlds().iterator().next().getName();
}
@Override public int getHighestBlock(String worldName, int x, int z) {
World world = SpongeUtil.getWorld(worldName);
if (world == null) {
return 63;
}
for (int y = 255; y > 0; y--) {
BlockState block = world.getBlock(x, y, z);
if (block.getType() != BlockTypes.AIR) {
return y;
}
}
return 63;
}
@Override public void setSign(String worldName, int x, int y, int z, String[] lines) {
World world = SpongeUtil.getWorld(worldName);
world.setBlock(x, y, z, BlockTypes.WALL_SIGN.getDefaultState());
Optional<TileEntity> block = world.getTileEntity(x, y, z);
if (!block.isPresent()) {
return;
}
TileEntity tile = block.get();
if (!(tile instanceof Sign)) {
return;
}
Sign sign = (Sign) tile;
List<Text> text = new ArrayList<>(4);
for (int i = 0; i < 4; i++) {
text.add(SpongeUtil.getText(lines[i]));
}
sign.offer(Keys.SIGN_LINES, text);
}
@Override public void setBiomes(String worldName, RegionWrapper region, String biomename) {
World world = SpongeUtil.getWorld(worldName);
BiomeType biome = SpongeUtil.getBiome(biomename);
for (int x = region.minX; x <= region.maxX; x++) {
for (int z = region.minZ; z <= region.maxZ; z++) {
world.setBiome(x, 0, z, biome);
}
}
}
}

View File

@ -0,0 +1,81 @@
package com.github.intellectualsites.plotsquared.sponge.util.block;
import com.github.intellectualsites.plotsquared.plot.object.ChunkWrapper;
import com.github.intellectualsites.plotsquared.plot.object.Location;
import com.github.intellectualsites.plotsquared.plot.object.PlotBlock;
import com.github.intellectualsites.plotsquared.plot.util.block.ScopedLocalBlockQueue;
import com.github.intellectualsites.plotsquared.sponge.util.SpongeUtil;
import org.spongepowered.api.world.biome.BiomeType;
import org.spongepowered.api.world.extent.MutableBiomeVolume;
import org.spongepowered.api.world.extent.MutableBlockVolume;
public class GenChunk extends ScopedLocalBlockQueue {
private final MutableBlockVolume terrain;
private final MutableBiomeVolume biome;
private final int bz;
private final int bx;
private final String world;
public boolean modified = false;
public GenChunk(MutableBlockVolume terrain, MutableBiomeVolume biome, ChunkWrapper wrap) {
super(null, new Location(null, 0, 0, 0), new Location(null, 15, 255, 15));
this.bx = wrap.x << 4;
this.bz = wrap.z << 4;
this.terrain = terrain;
this.biome = biome;
this.world = wrap.world;
}
@Override public void fillBiome(String biomeName) {
if (this.biome == null) {
return;
}
BiomeType biome = SpongeUtil.getBiome(biomeName.toUpperCase());
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
this.biome.setBiome(this.bx + x, 0, this.bz + z, biome);
}
}
}
@Override public boolean setBiome(int x, int z, String biomeName) {
modified = true;
BiomeType biome = SpongeUtil.getBiome(biomeName.toUpperCase());
this.biome.setBiome(this.bx + x, 0, this.bz + z, biome);
return true;
}
@Override public boolean setBlock(int x, int y, int z, int id, int data) {
modified = true;
this.terrain.setBlock(this.bx + x, y, this.bz + z, SpongeUtil.getBlockState(id, data));
return true;
}
@Override public PlotBlock getBlock(int x, int y, int z) {
return SpongeUtil.getPlotBlock(this.terrain.getBlock(this.bx + x, y, this.bz + z));
}
@Override public String getWorld() {
return this.world;
}
@Override public Location getMax() {
return new Location(getWorld(), 15 + bx, 255, 15 + bz);
}
@Override public Location getMin() {
return new Location(getWorld(), bx, 0, bz);
}
public GenChunk clone() {
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
}
public GenChunk shallowClone() {
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
}
}

View File

@ -0,0 +1,499 @@
package com.github.intellectualsites.plotsquared.sponge.util.block;
import com.github.intellectualsites.plotsquared.plot.object.PlotBlock;
import com.github.intellectualsites.plotsquared.plot.object.PseudoRandom;
import com.github.intellectualsites.plotsquared.plot.util.MainUtil;
import com.github.intellectualsites.plotsquared.plot.util.StringMan;
import com.github.intellectualsites.plotsquared.plot.util.TaskManager;
import com.github.intellectualsites.plotsquared.plot.util.block.BasicLocalBlockQueue;
import com.github.intellectualsites.plotsquared.sponge.util.SpongeUtil;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityTracker;
import net.minecraft.entity.EntityTrackerEntry;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Blocks;
import net.minecraft.network.play.server.SPacketChunkData;
import net.minecraft.network.play.server.SPacketDestroyEntities;
import net.minecraft.server.management.PlayerChunkMap;
import net.minecraft.util.ClassInheritanceMultiMap;
import net.minecraft.util.IntHashMap;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.world.WorldServer;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.storage.ExtendedBlockStorage;
import org.spongepowered.api.block.BlockState;
import org.spongepowered.api.block.BlockTypes;
import org.spongepowered.api.world.World;
import org.spongepowered.api.world.biome.BiomeType;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashSet;
public class SpongeLocalQueue extends BasicLocalBlockQueue<char[]> {
private BlockState AIR = BlockTypes.AIR.getDefaultState();
public SpongeLocalQueue(String world) {
super(world);
}
@Override public LocalChunk<char[]> getLocalChunk(int x, int z) {
return new CharLocalChunk_Sponge(this, x, z) {
// Custom stuff?
};
}
@Override public void optimize() {
}
public World getSpongeWorld() {
return SpongeUtil.getWorld(getWorld());
}
@Override public PlotBlock getBlock(int x, int y, int z) {
World worldObj = getSpongeWorld();
BlockState block = worldObj.getBlock(x, y, z);
return SpongeUtil.getPlotBlock(block);
}
@Override public void refreshChunk(int x, int z) {
World world = getSpongeWorld();
Chunk nmsChunk = ((net.minecraft.world.World) world).getChunkProvider().provideChunk(x, z);
if (nmsChunk == null || !nmsChunk.isLoaded()) {
return;
}
try {
ChunkPos pos = nmsChunk.getPos();
WorldServer w = (WorldServer) nmsChunk.getWorld();
PlayerChunkMap chunkMap = w.getPlayerChunkMap();
if (!chunkMap.contains(x, z)) {
return;
}
EntityTracker tracker = w.getEntityTracker();
HashSet<EntityPlayerMP> players = new HashSet<>();
for (EntityPlayer player : w.playerEntities) {
if (player instanceof EntityPlayerMP) {
if (chunkMap.isPlayerWatchingChunk((EntityPlayerMP) player, x, z)) {
players.add((EntityPlayerMP) player);
}
}
}
if (players.isEmpty()) {
return;
}
HashSet<EntityTrackerEntry> entities = new HashSet<>();
ClassInheritanceMultiMap<Entity>[] entitieSlices = nmsChunk.getEntityLists();
IntHashMap<EntityTrackerEntry> entries = null;
for (Field field : tracker.getClass().getDeclaredFields()) {
if (field.getType() == IntHashMap.class) {
field.setAccessible(true);
entries = (IntHashMap<EntityTrackerEntry>) field.get(tracker);
}
}
for (ClassInheritanceMultiMap<Entity> slice : entitieSlices) {
if (slice == null) {
continue;
}
for (Entity ent : slice) {
EntityTrackerEntry entry =
entries != null ? entries.lookup(ent.getEntityId()) : null;
if (entry == null) {
continue;
}
entities.add(entry);
SPacketDestroyEntities packet = new SPacketDestroyEntities(ent.getEntityId());
for (EntityPlayerMP player : players) {
player.connection.sendPacket(packet);
}
}
}
// Send chunks
SPacketChunkData packet = new SPacketChunkData(nmsChunk, 65535);
for (EntityPlayerMP player : players) {
player.connection.sendPacket(packet);
}
// send ents
for (EntityTrackerEntry entry : entities) {
try {
TaskManager.IMP.taskLater(new Runnable() {
@Override public void run() {
for (EntityPlayerMP player : players) {
if (entry.isVisibleTo(player)) {
entry.removeFromTrackedPlayers(player);
if (entry.getTrackedEntity() != player) {
entry.updatePlayerEntity(player);
}
}
}
}
}, 2);
} catch (Throwable e) {
e.printStackTrace();
}
}
} catch (Throwable e) {
e.printStackTrace();
}
}
@Override public void fixChunkLighting(int x, int z) {
Chunk nmsChunk = getChunk(getSpongeWorld(), x, z);
nmsChunk.generateSkylightMap();
}
public boolean isSurrounded(char[][] sections, int x, int y, int z) {
return isSolid(getId(sections, x, y + 1, z)) && isSolid(getId(sections, x + 1, y - 1, z))
&& isSolid(getId(sections, x - 1, y, z)) && isSolid(getId(sections, x, y, z + 1))
&& isSolid(getId(sections, x, y, z - 1));
}
public boolean isSolid(int i) {
return i != 0 && Block.getBlockById(i)
.isOpaqueCube(Block.getBlockById(i).getDefaultState());
}
public int getId(char[][] sections, int x, int y, int z) {
if (x < 0 || x > 15 || z < 0 || z > 15) {
return 1;
}
if (y < 0 || y > 255) {
return 1;
}
int i = MainUtil.CACHE_I[y][x][z];
char[] section = sections[i];
if (section == null) {
return 0;
}
int j = MainUtil.CACHE_I[y][x][z];
int combined = section[j];
return combined >> 4;
}
public boolean fixLighting(CharLocalChunk_Sponge bc, Chunk nmsChunk) {
try {
if (!nmsChunk.isLoaded()) {
return false;
}
ExtendedBlockStorage[] sections = nmsChunk.getBlockStorageArray();
nmsChunk.generateSkylightMap();
net.minecraft.world.World nmsWorld = nmsChunk.getWorld();
int X = bc.getX() << 4;
int Z = bc.getZ() << 4;
BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos(0, 0, 0);
for (int j = 0; j < sections.length; j++) {
ExtendedBlockStorage section = sections[j];
if (section == null) {
continue;
}
if ((bc.getCount(j) == 0) || ((bc.getCount(j) >= 4096) && (bc.getAir(j) == 0))
|| bc.getAir(j) == 4096) {
continue;
}
char[] array = bc.getIdArray(j);
if (array != null) {
int l = PseudoRandom.random.random(2);
for (int k = 0; k < array.length; k++) {
int i = array[k];
if (i < 16) {
continue;
}
short id = (short) (i >> 4);
switch (id) { // Lighting
default:
if ((k & 1) == l) {
l = 1 - l;
continue;
}
case 10:
case 11:
case 39:
case 40:
case 50:
case 51:
case 62:
case 74:
case 76:
case 89:
case 122:
case 124:
case 130:
case 138:
case 169:
int x = MainUtil.x_loc[j][k];
int y = MainUtil.y_loc[j][k];
int z = MainUtil.z_loc[j][k];
if (isSurrounded(bc.blocks, x, y, z)) {
continue;
}
pos.setPos(X + x, y, Z + z);
nmsWorld.checkLight(pos);
}
}
}
}
return true;
} catch (Throwable e) {
e.printStackTrace();
}
return false;
}
@Override public final void regenChunk(int x, int z) {
World worldObj = getSpongeWorld();
throw new UnsupportedOperationException("NOT SUPPORTED");
}
@Override public final void setComponents(LocalChunk<char[]> lc) {
setBlocks(lc);
setBiomes(lc);
}
public Chunk getChunk(World world, int x, int z) {
net.minecraft.world.chunk.Chunk chunk =
((net.minecraft.world.World) world).getChunkProvider().provideChunk(x, z);
if (chunk != null && !chunk.isLoaded()) {
chunk.onLoad();
}
return chunk;
}
public void setBlocks(LocalChunk<char[]> lc) {
World worldObj = getSpongeWorld();
org.spongepowered.api.world.Chunk spongeChunk =
(org.spongepowered.api.world.Chunk) getChunk(worldObj, lc.getX(), lc.getZ());
Chunk nmsChunk = (Chunk) spongeChunk;
char[][] ids = ((CharLocalChunk) lc).blocks;
for (int layer = 0; layer < 16; layer++) {
char[] array = ids[layer];
if (array == null) {
continue;
}
ExtendedBlockStorage section = nmsChunk.getBlockStorageArray()[layer];
short[] cacheX = MainUtil.x_loc[0];
short[] cacheY = MainUtil.y_loc[0];
short[] cacheZ = MainUtil.z_loc[0];
for (int j = 0; j < array.length; j++) {
int combinedId = array[j];
switch (combinedId) {
case 0:
continue;
case 1:
int x = cacheX[j];
int y = cacheY[j];
int z = cacheZ[j];
section.set(x, y, z, Blocks.AIR.getDefaultState());
continue;
default:
int id = combinedId >> 4;
Block block = Block.getBlockById(id);
int data = combinedId & 0xf;
IBlockState ibd;
if (data != 0) {
ibd = block.getStateFromMeta(data);
} else {
ibd = block.getDefaultState();
}
x = cacheX[j];
y = cacheY[j];
z = cacheZ[j];
section.set(x, y, z, ibd);
continue;
}
}
}
refreshChunk(nmsChunk.x, nmsChunk.z);
}
public void setBiomes(LocalChunk<char[]> lc) {
if (lc.biomes != null) {
World worldObj = getSpongeWorld();
int bx = lc.getX() << 4;
int bz = lc.getX() << 4;
String last = null;
BiomeType biome = null;
for (int x = 0; x < lc.biomes.length; x++) {
String[] biomes2 = lc.biomes[x];
if (biomes2 != null) {
for (int y = 0; y < biomes2.length; y++) {
String biomeStr = biomes2[y];
if (biomeStr != null) {
if (last == null || !StringMan.isEqual(last, biomeStr)) {
biome = SpongeUtil.getBiome(biomeStr.toUpperCase());
}
worldObj.setBiome(bx, 0, bz, biome);
}
}
}
}
}
}
public class CharLocalChunk_Sponge extends CharLocalChunk {
public short[] count;
public short[] air;
public short[] relight;
public CharLocalChunk_Sponge(BasicLocalBlockQueue parent, int x, int z) {
super(parent, x, z);
this.count = new short[16];
this.air = new short[16];
this.relight = new short[16];
}
@Override public void setBlock(int x, int y, int z, int id, int data) {
int i = MainUtil.CACHE_I[y][x][z];
int j = MainUtil.CACHE_J[y][x][z];
char[] vs = this.blocks[i];
if (vs == null) {
vs = this.blocks[i] = new char[4096];
this.count[i]++;
} else if (vs[j] == 0) {
this.count[i]++;
}
switch (id) {
case 0:
this.air[i]++;
vs[j] = (char) 1;
return;
case 10:
case 11:
case 39:
case 40:
case 51:
case 74:
case 89:
case 122:
case 124:
case 138:
case 169:
this.relight[i]++;
case 2:
case 4:
case 13:
case 14:
case 15:
case 20:
case 21:
case 22:
case 30:
case 32:
case 37:
case 41:
case 42:
case 45:
case 46:
case 47:
case 48:
case 49:
case 55:
case 56:
case 57:
case 58:
case 60:
case 7:
case 8:
case 9:
case 73:
case 78:
case 79:
case 80:
case 81:
case 82:
case 83:
case 85:
case 87:
case 88:
case 101:
case 102:
case 103:
case 110:
case 112:
case 113:
case 121:
case 129:
case 133:
case 165:
case 166:
case 170:
case 172:
case 173:
case 174:
case 181:
case 182:
case 188:
case 189:
case 190:
case 191:
case 192:
vs[j] = (char) (id << 4);
return;
case 130:
case 76:
case 62:
this.relight[i]++;
case 54:
case 146:
case 61:
case 65:
case 68:
case 50:
if (data < 2) {
data = 2;
}
default:
vs[j] = (char) ((id << 4) + data);
return;
}
}
public char[] getIdArray(int i) {
return this.blocks[i];
}
public int getCount(int i) {
return this.count[i];
}
public int getAir(int i) {
return this.air[i];
}
public void setCount(int i, short value) {
this.count[i] = value;
}
public int getRelight(int i) {
return this.relight[i];
}
public int getTotalCount() {
int total = 0;
for (int i = 0; i < 16; i++) {
total += this.count[i];
}
return total;
}
public int getTotalRelight() {
if (getTotalCount() == 0) {
Arrays.fill(this.count, (short) 1);
Arrays.fill(this.relight, Short.MAX_VALUE);
return Short.MAX_VALUE;
}
int total = 0;
for (int i = 0; i < 16; i++) {
total += this.relight[i];
}
return total;
}
}
}

View File

@ -0,0 +1,91 @@
package com.github.intellectualsites.plotsquared.sponge.uuid;
import com.github.intellectualsites.plotsquared.plot.object.OfflinePlotPlayer;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler;
import com.github.intellectualsites.plotsquared.plot.uuid.UUIDWrapper;
import com.github.intellectualsites.plotsquared.sponge.SpongeMain;
import com.google.common.base.Charsets;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.profile.GameProfile;
import java.util.Collection;
import java.util.UUID;
public class SpongeLowerOfflineUUIDWrapper extends UUIDWrapper {
public SpongeLowerOfflineUUIDWrapper() {
// Anything?
}
@Override public UUID getUUID(PlotPlayer player) {
return getUUID(player.getName());
}
@Override public UUID getUUID(OfflinePlotPlayer player) {
return getUUID(player.getName());
}
@Override public OfflinePlotPlayer getOfflinePlayer(UUID uuid) {
String name = UUIDHandler.getName(uuid);
if (name == null) {
try {
GameProfile profile = SpongeMain.THIS.getResolver().get(uuid).get();
if (profile != null) {
name = profile.getName().orElse(null);
}
} catch (Exception e) {
e.printStackTrace();
}
}
if (name == null) {
for (GameProfile profile : SpongeMain.THIS.getResolver().getCache().getProfiles()) {
String tmp = profile.getName().orElse(null);
if (tmp != null) {
if (getUUID(name).equals(uuid)) {
name = tmp;
break;
}
}
}
}
String username = name;
return new OfflinePlotPlayer() {
@Override public boolean isOnline() {
return UUIDHandler.getPlayer(uuid) != null;
}
@Override public UUID getUUID() {
return uuid;
}
@Override public String getName() {
return username;
}
@Override public long getLastPlayed() {
// TODO FIXME
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
}
};
}
public Player[] getOnlinePlayers() {
Collection<Player> onlinePlayers = SpongeMain.THIS.getServer().getOnlinePlayers();
return onlinePlayers.toArray(new Player[onlinePlayers.size()]);
}
@Override public UUID getUUID(String name) {
return UUID
.nameUUIDFromBytes(("OfflinePlayer:" + name.toLowerCase()).getBytes(Charsets.UTF_8));
}
@Override public OfflinePlotPlayer[] getOfflinePlayers() {
// TODO FIXME
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
}
@Override public OfflinePlotPlayer getOfflinePlayer(String name) {
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
}
}

View File

@ -0,0 +1,67 @@
package com.github.intellectualsites.plotsquared.sponge.uuid;
import com.github.intellectualsites.plotsquared.plot.object.OfflinePlotPlayer;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.uuid.UUIDWrapper;
import com.github.intellectualsites.plotsquared.sponge.object.SpongeOfflinePlayer;
import com.github.intellectualsites.plotsquared.sponge.object.SpongePlayer;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.entity.living.player.User;
import org.spongepowered.api.service.user.UserStorageService;
import org.spongepowered.api.util.Identifiable;
import java.util.Optional;
import java.util.UUID;
public class SpongeOnlineUUIDWrapper extends UUIDWrapper {
private UserStorageService userStorageService;
public SpongeOnlineUUIDWrapper() {
Optional<UserStorageService> userStorage =
Sponge.getServiceManager().provide(UserStorageService.class);
userStorage.ifPresent(userStorageService -> this.userStorageService = userStorageService);
}
@Override public UUID getUUID(PlotPlayer player) {
return ((SpongePlayer) player).player.getUniqueId();
}
@Override public UUID getUUID(OfflinePlotPlayer player) {
return player.getUUID();
}
@Override public UUID getUUID(String name) {
Optional<Player> player = Sponge.getServer().getPlayer(name);
if (player.isPresent()) {
return player.get().getUniqueId();
}
Optional<User> user = userStorageService.get(name);
return user.map(Identifiable::getUniqueId).orElse(null);
}
@Override public OfflinePlotPlayer getOfflinePlayer(UUID uuid) {
Optional<Player> player = Sponge.getServer().getPlayer(uuid);
if (player.isPresent()) {
return new SpongeOfflinePlayer(player.get());
}
Optional<User> user = userStorageService.get(uuid);
return user.map(SpongeOfflinePlayer::new).orElse(null);
}
@Override public OfflinePlotPlayer[] getOfflinePlayers() {
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
}
@Override public OfflinePlotPlayer getOfflinePlayer(String name) {
Optional<Player> player = Sponge.getServer().getPlayer(name);
if (player.isPresent()) {
return new SpongeOfflinePlayer(player.get());
}
Optional<User> user = userStorageService.get(name);
return user.map(SpongeOfflinePlayer::new).orElse(null);
}
}

View File

@ -0,0 +1,46 @@
package com.github.intellectualsites.plotsquared.sponge.uuid;
import com.github.intellectualsites.plotsquared.plot.object.RunnableVal;
import com.github.intellectualsites.plotsquared.plot.object.StringWrapper;
import com.github.intellectualsites.plotsquared.plot.util.TaskManager;
import com.github.intellectualsites.plotsquared.plot.util.UUIDHandlerImplementation;
import com.github.intellectualsites.plotsquared.plot.uuid.UUIDWrapper;
import com.github.intellectualsites.plotsquared.sponge.SpongeMain;
import org.spongepowered.api.profile.GameProfile;
import java.util.UUID;
public class SpongeUUIDHandler extends UUIDHandlerImplementation {
public SpongeUUIDHandler(UUIDWrapper wrapper) {
super(wrapper);
}
@Override public boolean startCaching(Runnable whenDone) {
if (!super.startCaching(whenDone)) {
return false;
}
return cache(whenDone);
}
public boolean cache(Runnable whenDone) {
for (GameProfile profile : SpongeMain.THIS.getServer().getGameProfileManager().getCache()
.getProfiles()) {
String name = profile.getName().orElse(null);
if (name != null) {
add(new StringWrapper(name), profile.getUniqueId());
}
}
return true;
}
@Override public void fetchUUID(String name, RunnableVal<UUID> ifFetch) {
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
ifFetch.value = SpongeUUIDHandler.this.uuidWrapper.getUUID(name);
TaskManager.runTask(ifFetch);
}
});
}
}