Merge pull request 'Add LegacyBauSystem with adaptions to current SpigotCore' (#20) from legacy-bau-system into main
All checks were successful
SteamWarCI Build successful

Reviewed-on: #20
Reviewed-by: YoyoNow <yoyonow@noreply.localhost>
This commit is contained in:
2025-02-20 06:46:06 +01:00
86 changed files with 8253 additions and 0 deletions

View File

@ -0,0 +1,29 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2024 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
plugins {
steamwar.java
}
dependencies {
compileOnly(project(":SpigotCore", "default"))
compileOnly(libs.nms12)
compileOnly(libs.worldedit12)
}

View File

@ -0,0 +1,197 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem;
import de.steamwar.bausystem.commands.*;
import de.steamwar.bausystem.world.*;
import de.steamwar.bausystem.world.regions.Region;
import de.steamwar.core.Core;
import de.steamwar.providers.BauServerInfo;
import de.steamwar.scoreboard.SWScoreboard;
import de.steamwar.sql.SteamwarUser;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitTask;
import java.util.UUID;
import java.util.logging.Level;
public class BauSystem extends JavaPlugin implements Listener {
private static BauSystem plugin;
private static Integer owner;
public static final String PREFIX = "§eBauSystem§8» §7";
private BukkitTask autoShutdown;
@Override
public void onEnable() {
plugin = this;
Mapper.init();
new CommandTrace();
new CommandTPSLimiter();
new CommandNV();
new CommandReset();
new CommandSpeed();
new CommandTNT();
new CommandGamemode();
new CommandClear();
new CommandTime();
new CommandTeleport();
new CommandFire();
new CommandFreeze();
new CommandTestblock();
new CommandInfo();
new CommandProtect();
new CommandSkull();
new CommandLoader();
new CommandLockschem();
new CommandDebugStick();
new CommandGills();
new CommandDetonator();
new CommandScript();
new CommandScriptVars();
new CommandRedstoneTester();
new CommandGUI();
new CommandWorldSpawn();
new CommandRegion();
new CommandSelect();
new CommandKillAll();
if (Core.getVersion() > 14 && Region.buildAreaEnabled()) {
new CommandColor();
}
Bukkit.getPluginManager().registerEvents(this, this);
Bukkit.getPluginManager().registerEvents(new RegionListener(), this);
Bukkit.getPluginManager().registerEvents(new ScriptListener(), this);
Bukkit.getPluginManager().registerEvents(new BauScoreboard(), this);
Bukkit.getPluginManager().registerEvents(new ClipboardListener(), this);
Bukkit.getPluginManager().registerEvents(new CommandGUI(), this);
Bukkit.getPluginManager().registerEvents(new DetonatorListener(), this);
Bukkit.getPluginManager().registerEvents(new ItemFrameListener(), this);
new AFKStopper();
autoShutdown = Bukkit.getScheduler().runTaskLater(this, Bukkit::shutdown, 1200);
TPSUtils.init();
}
@Override
public void onDisable() {
Region.save();
}
public static BauSystem getPlugin() {
return plugin;
}
public static UUID getOwner() {
return SteamwarUser.get(getOwnerID()).getUUID();
}
public static int getOwnerID() {
//Lazy loading to improve startup time of the server in 1.15
if (owner == null) {
owner = BauServerInfo.getOwnerId();
}
return owner;
}
@EventHandler
public void onDeath(PlayerDeathEvent e) {
e.setDeathMessage(null);
}
@EventHandler
public void onJoin(PlayerLoginEvent e) {
if (autoShutdown != null) {
autoShutdown.cancel();
autoShutdown = null;
}
Player p = e.getPlayer();
p.setOp(true);
}
@EventHandler
public void onLeave(PlayerQuitEvent e) {
Player p = e.getPlayer();
SWScoreboard.impl.removeScoreboard(p);
if (Bukkit.getOnlinePlayers().isEmpty() || (Bukkit.getOnlinePlayers().size() == 1 && Bukkit.getOnlinePlayers().contains(p))) {
if (autoShutdown != null) {
autoShutdown.cancel();
}
CommandTPSLimiter.setTPS(20.0);
autoShutdown = Bukkit.getScheduler().runTaskTimer(this, new Runnable() {
int count = 0;
@Override
public void run() {
if (count >= 300) {
Bukkit.shutdown();
return;
}
count++;
try {
if (RamUsage.getUsage() > 0.8) {
Bukkit.shutdown();
}
} catch (Throwable throwable) {
Bukkit.getLogger().log(Level.WARNING, throwable.getMessage(), throwable);
Bukkit.shutdown();
}
}
}, 20, 20);
}
}
@EventHandler
public void onInventoryClick(InventoryClickEvent e) {
ItemStack stack = e.getCursor();
if (stack == null || !stack.hasItemMeta())
return;
assert stack.getItemMeta() != null;
if (stack.getItemMeta().hasEnchants()) {
for (Enchantment en : Enchantment.values()) {
if (stack.getEnchantmentLevel(en) > en.getMaxLevel())
stack.removeEnchantment(en);
}
}
Material material = stack.getType();
if (material == Material.POTION || material == Material.SPLASH_POTION || material == Material.LINGERING_POTION) {
stack.setType(Material.MILK_BUCKET);
}
e.setCurrentItem(stack);
}
}

View File

@ -0,0 +1,43 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2021 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem;
import de.steamwar.bausystem.tracer.AbstractTraceEntity;
import de.steamwar.core.VersionDependent;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
public class CraftbukkitWrapper {
private CraftbukkitWrapper() {}
public static final ICraftbukkitWrapper impl = VersionDependent.getVersionImpl(BauSystem.getPlugin());
public interface ICraftbukkitWrapper {
void initTPS();
void createTickCache(World world);
void sendTickPackets();
void openSignEditor(Player player, Location location);
AbstractTraceEntity create(World world, Vector tntPosition, boolean tnt);
}
}

View File

@ -0,0 +1,80 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2021 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem;
import de.steamwar.bausystem.tracer.AbstractTraceEntity;
import de.steamwar.bausystem.world.TPSUtils;
import net.minecraft.server.v1_12_R1.*;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.craftbukkit.v1_12_R1.entity.CraftEntity;
import org.bukkit.craftbukkit.v1_12_R1.entity.CraftPlayer;
import org.bukkit.entity.Player;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.util.Vector;
import java.util.ArrayList;
import java.util.List;
public class CraftbukkitWrapper12 implements CraftbukkitWrapper.ICraftbukkitWrapper {
private final List<Packet<?>> packets = new ArrayList<>();
@Override
public void initTPS() {
TPSUtils.disableWarp();
}
@Override
public void createTickCache(World world) {
packets.clear();
world.getEntities().stream().filter(entity -> !(entity instanceof Player)).forEach(entity -> {
packets.add(new PacketPlayOutEntityVelocity(entity.getEntityId(), 0, 0, 0));
packets.add(new PacketPlayOutEntityTeleport(((CraftEntity) entity).getHandle()));
if (entity instanceof TNTPrimed) {
net.minecraft.server.v1_12_R1.Entity serverEntity = ((CraftEntity) entity).getHandle();
packets.add(new PacketPlayOutEntityMetadata(serverEntity.getId(), serverEntity.getDataWatcher(), true));
}
});
}
@Override
public void sendTickPackets() {
Bukkit.getOnlinePlayers().forEach(player -> {
PlayerConnection connection = ((CraftPlayer) player).getHandle().playerConnection;
for (Packet<?> p : packets) {
connection.sendPacket(p);
}
});
}
@Override
public void openSignEditor(Player player, Location location) {
PacketPlayOutOpenSignEditor packet = new PacketPlayOutOpenSignEditor(new BlockPosition(location.getBlockX(), location.getBlockY(), location.getBlockZ()));
((CraftPlayer) player).getHandle().playerConnection.sendPacket(packet);
}
@Override
public AbstractTraceEntity create(World world, Vector tntPosition, boolean tnt) {
return new TraceEntity12(world, tntPosition, tnt);
}
}

View File

@ -0,0 +1,53 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2021 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem;
import de.steamwar.bausystem.world.Detoloader;
import de.steamwar.core.VersionDependent;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.Vector;
public class FlatteningWrapper {
private FlatteningWrapper(){}
public static final IFlatteningWrapper impl = VersionDependent.getVersionImpl(BauSystem.getPlugin());
public interface IFlatteningWrapper {
boolean tntPlaceActionPerform(Location location);
boolean setRedstone(Location location, boolean active);
Detoloader onPlayerInteractLoader(PlayerInteractEvent event);
boolean getLever(Block block);
boolean isNoBook(ItemStack item);
boolean inWater(World world, Vector tntPosition);
Material getTraceShowMaterial();
Material getTraceHideMaterial();
Material getTraceXZMaterial();
void giveStick(Player player);
}
}

View File

@ -0,0 +1,148 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2021 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem;
import de.steamwar.bausystem.world.Detoloader;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.Vector;
import java.util.List;
import java.util.stream.Collectors;
public class FlatteningWrapper12 implements FlatteningWrapper.IFlatteningWrapper {
@Override
public boolean tntPlaceActionPerform(Location location) {
Material m = location.getBlock().getType();
if (m != Material.AIR && m != Material.STATIONARY_WATER && m != Material.WATER)
return false;
location.getBlock().setType(Material.TNT);
return true;
}
@Override
@SuppressWarnings("deprecation")
public boolean setRedstone(Location location, boolean active) {
Block block = location.getBlock();
Material material = block.getType();
if (material == Material.LEVER || material == Material.STONE_BUTTON || material == Material.WOOD_BUTTON) {
if (active)
block.setData((byte) (block.getData() | 8));
else
block.setData((byte) (block.getData() & -9));
} else if (material == Material.STONE_PLATE || material == Material.WOOD_PLATE) {
if (active)
block.setData((byte) 1);
else
block.setData((byte) 0);
} else if (material == Material.TRIPWIRE) {
if (active) {
ArmorStand armorStand = (ArmorStand) Bukkit.getWorlds().get(0).spawnEntity(location, EntityType.ARMOR_STAND);
armorStand.setVisible(false);
armorStand.setBasePlate(false);
armorStand.addScoreboardTag("detonator-" + location.getBlockX() + location.getBlockY() + location.getBlockZ());
} else {
List<Entity> entityList = Bukkit.getWorlds().get(0).getEntitiesByClasses(ArmorStand.class).stream().filter(entity ->
entity.getScoreboardTags().contains("detonator-" + location.getBlockX() + location.getBlockY() + location.getBlockZ()))
.limit(1)
.collect(Collectors.toList());
if (entityList.isEmpty()) return false;
entityList.get(0).remove();
}
} else {
return false;
}
block.getState().update(true);
return true;
}
@Override
@SuppressWarnings("deprecation")
public Detoloader onPlayerInteractLoader(PlayerInteractEvent event) {
Block block = event.getClickedBlock();
Material material = block.getType();
if (material == Material.LEVER) {
if ((block.getData() & 8) == 8) {
return new Detoloader("Hebel", 0).setActive(false);
} else {
return new Detoloader("Hebel", 0).setActive(true);
}
} else if (material == Material.STONE_BUTTON) {
return new Detoloader("Knopf", Detoloader.STONE_BUTTON);
} else if (material == Material.WOOD_BUTTON) {
return new Detoloader("Knopf", Detoloader.WOODEN_BUTTON);
} else if (material == Material.NOTE_BLOCK) {
return new Detoloader("Noteblock", Detoloader.NOTE_BLOCK);
} else if (material == Material.STONE_PLATE || material == Material.WOOD_PLATE) {
return new Detoloader("Druckplatte", Detoloader.PRESSURE_PLATE);
} else if (material == Material.TRIPWIRE) {
return new Detoloader("Tripwire", Detoloader.TRIPWIRE);
}
return new Detoloader("§eUnbekannter Block betätigt (nicht aufgenommen)", -1).setAddBack(false);
}
@Override
@SuppressWarnings("deprecation")
public boolean getLever(Block block) {
return (block.getData() & 8) == 8;
}
@Override
public boolean isNoBook(ItemStack item) {
return item.getType() != Material.BOOK_AND_QUILL && item.getType() != Material.WRITTEN_BOOK;
}
@Override
public boolean inWater(World world, Vector tntPosition) {
Material material = world.getBlockAt(tntPosition.getBlockX(), tntPosition.getBlockY(), tntPosition.getBlockZ()).getType();
return material == Material.WATER || material == Material.STATIONARY_WATER;
}
@Override
public Material getTraceShowMaterial() {
return Material.CONCRETE;
}
@Override
public Material getTraceHideMaterial() {
return Material.CONCRETE;
}
@Override
public Material getTraceXZMaterial() {
return Material.STEP;
}
@Override
public void giveStick(Player player) {
player.sendMessage(BauSystem.PREFIX + "§cDen Debugstick gibt es nicht in der 1.12.");
}
}

View File

@ -0,0 +1,87 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem;
import de.steamwar.bausystem.tracer.show.ShowModeParameterType;
import de.steamwar.command.SWCommandUtils;
import de.steamwar.command.TypeMapper;
import de.steamwar.sql.BauweltMember;
import de.steamwar.sql.SteamwarUser;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Mapper {
private Mapper() {
throw new IllegalStateException("Utility Class");
}
public static void init() {
SWCommandUtils.addMapper(ShowModeParameterType.class, showModeParameterTypesTypeMapper());
SWCommandUtils.addMapper(BauweltMember.class, bauweltMemberTypeMapper());
}
private static TypeMapper<ShowModeParameterType> showModeParameterTypesTypeMapper() {
Map<String, ShowModeParameterType> showModeParameterTypesMap = new HashMap<>();
showModeParameterTypesMap.put("-water", ShowModeParameterType.WATER);
showModeParameterTypesMap.put("-interpolatey", ShowModeParameterType.INTERPOLATE_Y);
showModeParameterTypesMap.put("-interpolate-y", ShowModeParameterType.INTERPOLATE_Y);
showModeParameterTypesMap.put("-interpolate_y", ShowModeParameterType.INTERPOLATE_Y);
showModeParameterTypesMap.put("-y", ShowModeParameterType.INTERPOLATE_Y);
showModeParameterTypesMap.put("-interpolatex", ShowModeParameterType.INTERPOLATE_XZ);
showModeParameterTypesMap.put("-interpolate-x", ShowModeParameterType.INTERPOLATE_XZ);
showModeParameterTypesMap.put("-interpolate_x", ShowModeParameterType.INTERPOLATE_XZ);
showModeParameterTypesMap.put("-x", ShowModeParameterType.INTERPOLATE_XZ);
showModeParameterTypesMap.put("-interpolatez", ShowModeParameterType.INTERPOLATE_XZ);
showModeParameterTypesMap.put("-interpolate-z", ShowModeParameterType.INTERPOLATE_XZ);
showModeParameterTypesMap.put("-interpolate_z", ShowModeParameterType.INTERPOLATE_XZ);
showModeParameterTypesMap.put("-z", ShowModeParameterType.INTERPOLATE_XZ);
showModeParameterTypesMap.put("-interpolatexz", ShowModeParameterType.INTERPOLATE_XZ);
showModeParameterTypesMap.put("-interpolate-xz", ShowModeParameterType.INTERPOLATE_XZ);
showModeParameterTypesMap.put("-interpolate_xz", ShowModeParameterType.INTERPOLATE_XZ);
showModeParameterTypesMap.put("-xz", ShowModeParameterType.INTERPOLATE_XZ);
showModeParameterTypesMap.put("-advanced", ShowModeParameterType.ADVANCED);
showModeParameterTypesMap.put("-a", ShowModeParameterType.ADVANCED);
showModeParameterTypesMap.put("advanced", ShowModeParameterType.ADVANCED);
showModeParameterTypesMap.put("a", ShowModeParameterType.ADVANCED);
List<String> tabCompletes = new ArrayList<>(showModeParameterTypesMap.keySet());
return SWCommandUtils.createMapper(s -> showModeParameterTypesMap.getOrDefault(s, null), s -> tabCompletes);
}
private static TypeMapper<BauweltMember> bauweltMemberTypeMapper() {
return SWCommandUtils.createMapper(s -> BauweltMember.getMembers(BauSystem.getOwnerID())
.stream()
.filter(m -> SteamwarUser.get(m.getMemberID()).getUserName().equals(s)).findFirst().orElse(null),
s -> BauweltMember.getMembers(BauSystem.getOwnerID())
.stream()
.map(m -> SteamwarUser.get(m.getMemberID()).getUserName())
.collect(Collectors.toList()));
}
}

View File

@ -0,0 +1,26 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem;
public enum Permission {
WORLD,
WORLDEDIT,
MEMBER
}

View File

@ -0,0 +1,44 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem;
import org.bukkit.Bukkit;
import java.lang.management.ManagementFactory;
import java.util.logging.Level;
public class RamUsage {
private RamUsage() {
throw new IllegalStateException("Utility Class");
}
public static double getUsage() {
try {
long memorySize = ((com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean()).getTotalPhysicalMemorySize();
long freeMemory = ((com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean()).getFreePhysicalMemorySize();
return (memorySize - freeMemory) / (double) memorySize;
} catch (Throwable throwable) {
Bukkit.getLogger().log(Level.WARNING, throwable.getMessage(), throwable);
return 1D;
}
}
}

View File

@ -0,0 +1,64 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.List;
public class SWUtils {
public static void giveItemToPlayer(Player player, ItemStack itemStack) {
if (itemStack == null || itemStack.getType() == Material.AIR) {
return;
}
for (int i = 0; i < player.getInventory().getSize(); i++) {
ItemStack current = player.getInventory().getItem(i);
if (current != null && current.isSimilar(itemStack)) {
player.getInventory().setItem(i, null);
itemStack = current;
break;
}
}
ItemStack current = player.getInventory().getItemInMainHand();
player.getInventory().setItemInMainHand(itemStack);
if (current.getType() != Material.AIR) {
player.getInventory().addItem(current);
}
}
public static List<String> manageList(List<String> strings, String[] args, int index) {
strings = new ArrayList<>(strings);
for (int i = strings.size() - 1; i >= 0; i--) {
if (!strings.get(i).startsWith(args[index])) {
strings.remove(i);
}
}
return strings;
}
public static List<String> manageList(List<String> strings, String[] args) {
return manageList(strings, args, args.length - 1);
}
}

View File

@ -0,0 +1,77 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2021 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem;
import de.steamwar.bausystem.tracer.AbstractTraceEntity;
import net.minecraft.server.v1_12_R1.*;
import org.bukkit.World;
import org.bukkit.craftbukkit.v1_12_R1.CraftWorld;
import org.bukkit.craftbukkit.v1_12_R1.entity.CraftPlayer;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
class TraceEntity12 extends EntityFallingBlock implements AbstractTraceEntity {
private boolean exploded;
private int references;
public TraceEntity12(World world, Vector position, boolean tnt) {
super(((CraftWorld) world).getHandle(), position.getX(), position.getY(), position.getZ(), tnt ? Blocks.TNT.getBlockData() : Blocks.STAINED_GLASS.getBlockData());
this.setNoGravity(true);
this.ticksLived = -12000;
}
@Override
public void display(Player player, boolean exploded) {
if (!this.exploded && exploded) {
this.setCustomNameVisible(true);
this.setCustomName("Bumm");
this.exploded = true;
if (references++ > 0)
sendDestroy(player);
} else if (references++ > 0)
return;
PacketPlayOutSpawnEntity packetPlayOutSpawnEntity = new PacketPlayOutSpawnEntity(this, 70, Block.getCombinedId(getBlock()));
PlayerConnection playerConnection = ((CraftPlayer) player).getHandle().playerConnection;
playerConnection.sendPacket(packetPlayOutSpawnEntity);
PacketPlayOutEntityMetadata packetPlayOutEntityMetadata = new PacketPlayOutEntityMetadata(getId(), datawatcher, true);
playerConnection.sendPacket(packetPlayOutEntityMetadata);
}
@Override
public boolean hide(Player player, boolean force) {
if (!force && --references > 0)
return false;
sendDestroy(player);
die();
return true;
}
private void sendDestroy(Player player) {
PacketPlayOutEntityDestroy packetPlayOutEntityDestroy = new PacketPlayOutEntityDestroy(getId());
((CraftPlayer) player).getHandle().playerConnection.sendPacket(packetPlayOutEntityDestroy);
}
}

View File

@ -0,0 +1,44 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2021 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.extent.clipboard.Clipboard;
import de.steamwar.bausystem.world.regions.PasteOptions;
import de.steamwar.bausystem.world.regions.Point;
import de.steamwar.core.VersionDependent;
import org.bukkit.entity.Player;
import java.io.File;
public class WorldeditWrapper {
private WorldeditWrapper() {}
public static final IWorldeditWrapper impl = VersionDependent.getVersionImpl(BauSystem.getPlugin());
public interface IWorldeditWrapper {
void setSelection(Player p, Point minPoint, Point maxPoint);
EditSession paste(File file, int x, int y, int z, PasteOptions pasteOptions);
EditSession paste(Clipboard clipboard, int x, int y, int z, PasteOptions pasteOptions);
boolean isWorldEditCommand(String command);
}
}

View File

@ -0,0 +1,114 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2021 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.MaxChangedBlocksException;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.bukkit.BukkitWorld;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldedit.extent.clipboard.Clipboard;
import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat;
import com.sk89q.worldedit.function.operation.Operations;
import com.sk89q.worldedit.math.transform.AffineTransform;
import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.regions.selector.CuboidRegionSelector;
import com.sk89q.worldedit.session.ClipboardHolder;
import com.sk89q.worldedit.world.World;
import de.steamwar.bausystem.world.regions.PasteOptions;
import de.steamwar.bausystem.world.regions.Point;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Objects;
public class WorldeditWrapper12 implements WorldeditWrapper.IWorldeditWrapper {
private final WorldEditPlugin WORLDEDIT_PLUGIN = ((WorldEditPlugin) Bukkit.getPluginManager().getPlugin("WorldEdit"));
private final World BUKKITWORLD = new BukkitWorld(Bukkit.getWorlds().get(0));
@Override
public void setSelection(Player p, Point minPoint, Point maxPoint) {
WORLDEDIT_PLUGIN.getSession(p).setRegionSelector(BUKKITWORLD, new CuboidRegionSelector(BUKKITWORLD, toVector(minPoint), toVector(maxPoint)));
}
@Override
public EditSession paste(File file, int x, int y, int z, PasteOptions pasteOptions) {
World w = new BukkitWorld(Bukkit.getWorlds().get(0));
Clipboard clipboard;
try {
clipboard = Objects.requireNonNull(ClipboardFormat.findByFile(file)).getReader(new FileInputStream(file)).read(w.getWorldData());
} catch (NullPointerException | IOException e) {
throw new SecurityException("Bausystem schematic not found", e);
}
return paste(clipboard, x, y, z, pasteOptions);
}
@Override
public EditSession paste(Clipboard clipboard, int x, int y, int z, PasteOptions pasteOptions) {
World w = new BukkitWorld(Bukkit.getWorlds().get(0));
Vector dimensions = clipboard.getDimensions();
Vector v = new Vector(x, y, z);
Vector offset = clipboard.getRegion().getMinimumPoint().subtract(clipboard.getOrigin());
AffineTransform aT = new AffineTransform();
if (pasteOptions.isRotate()) {
aT = aT.rotateY(180);
v = v.add(dimensions.getX() / 2 + dimensions.getX() % 2, 0, dimensions.getZ() / 2 + dimensions.getZ() % 2).subtract(offset.multiply(-1, 1, -1)).subtract(1, 0, 1);
} else {
v = v.subtract(dimensions.getX() / 2 - dimensions.getX() % 2, 0, dimensions.getZ() / 2 - dimensions.getZ() % 2).subtract(offset);
}
EditSession e = WorldEdit.getInstance().getEditSessionFactory().getEditSession(w, -1);
ClipboardHolder ch = new ClipboardHolder(clipboard, w.getWorldData());
ch.setTransform(aT);
if (pasteOptions.isReset()) {
try {
e.setBlocks(new CuboidRegion(toVector(pasteOptions.getMinPoint()), toVector(pasteOptions.getMaxPoint())), new BaseBlock(BlockID.AIR));
} catch (MaxChangedBlocksException ex) {
throw new SecurityException("Max blocks changed?", ex);
}
}
Operations.completeBlindly(ch.createPaste(e, w.getWorldData()).to(v).ignoreAirBlocks(pasteOptions.isIgnoreAir()).build());
return e;
}
@Override
public boolean isWorldEditCommand(String command) {
if (command.startsWith("/")) {
command = command.replaceFirst("/", "");
}
command = command.toLowerCase();
return ((WorldEditPlugin) Bukkit.getPluginManager().getPlugin("WorldEdit")).getWorldEdit().getPlatformManager()
.getCommandManager().getDispatcher().get(command) != null;
}
private Vector toVector(Point point) {
return Vector.toBlockPoint(point.getX(), point.getY(), point.getZ());
}
}

View File

@ -0,0 +1,71 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.commands;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.Permission;
import de.steamwar.bausystem.world.Welt;
import de.steamwar.command.SWCommand;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public class CommandClear extends SWCommand {
public CommandClear() {
super("clear");
}
@Register(help = true)
public void genericHelp(Player p, String... args) {
p.sendMessage("§8/§eclear §8- §7Leere dein Inventar");
p.sendMessage("§8/§ebau clear §8[§7Player§8] §8- §7Leere ein Spieler Inventar");
}
@Register
public void genericClearCommand(Player p) {
clear(p);
p.sendMessage(BauSystem.PREFIX + "Dein Inventar wurde geleert.");
}
@Register
public void clearPlayerCommand(Player p, Player target) {
if (!permissionCheck(p)) return;
clear(target);
target.sendMessage(BauSystem.PREFIX + "Dein Inventar wurde von " + p.getDisplayName() + " §7geleert.");
p.sendMessage(BauSystem.PREFIX + "Das Inventar von " + target.getDisplayName() + " §7wurde geleert.");
}
private boolean permissionCheck(Player player) {
if (Welt.noPermission(player, Permission.WORLD)) {
player.sendMessage(BauSystem.PREFIX + "§cDu darfst hier keine fremden Inventare leeren.");
return false;
}
return true;
}
private void clear(Player player) {
player.getInventory().clear();
player.getInventory().setHelmet(new ItemStack(Material.AIR));
player.getInventory().setChestplate(new ItemStack(Material.AIR));
player.getInventory().setLeggings(new ItemStack(Material.AIR));
player.getInventory().setBoots(new ItemStack(Material.AIR));
}
}

View File

@ -0,0 +1,73 @@
package de.steamwar.bausystem.commands;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.world.Color;
import de.steamwar.bausystem.world.regions.GlobalRegion;
import de.steamwar.bausystem.world.regions.Region;
import de.steamwar.command.SWCommand;
import org.bukkit.entity.Player;
public class CommandColor extends SWCommand {
private static CommandColor instance = null;
public CommandColor() {
super("color");
instance = this;
}
public static CommandColor getInstance() {
return instance;
}
@Register(help = true)
public void genericHelp(Player p, String... args) {
p.sendMessage("§8/§ecolor §8[§7Color§8] §8- §7Setze die Farbe der Region");
p.sendMessage("§8/§ecolor §8[§7Color§8] §8[§7Type§8] §8- §7Setze die Farbe der Region oder Global");
}
@Register
public void genericColor(Player p, Color color) {
genericColorSet(p, color, ColorizationType.LOCAL);
}
@Register
public void genericColorSet(Player p, Color color, ColorizationType colorizationType) {
if (!permissionCheck(p)) {
return;
}
if (colorizationType == ColorizationType.GLOBAL) {
Region.setGlobalColor(color);
p.sendMessage(BauSystem.PREFIX + "Alle Regions farben auf §e" + color.name().toLowerCase() + "§7 gesetzt");
return;
}
Region region = Region.getRegion(p.getLocation());
if (GlobalRegion.isGlobalRegion(region)) {
p.sendMessage(BauSystem.PREFIX + "§cDu befindest dich derzeit in keiner Region");
return;
}
region.setColor(color);
p.sendMessage(BauSystem.PREFIX + "Regions farben auf §e" + color.name().toLowerCase() + "§7 gesetzt");
}
@Register
public void genericColorSet(Player p, ColorizationType colorizationType, Color color) {
genericColorSet(p, color, colorizationType);
}
private boolean permissionCheck(Player p) {
if (!BauSystem.getOwner().equals(p.getUniqueId())) {
p.sendMessage(BauSystem.PREFIX + "§cDies ist nicht deine Welt!");
return false;
} else {
return true;
}
}
public enum ColorizationType {
LOCAL,
GLOBAL
}
}

View File

@ -0,0 +1,41 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.commands;
import de.steamwar.bausystem.FlatteningWrapper;
import de.steamwar.command.SWCommand;
import org.bukkit.entity.Player;
public class CommandDebugStick extends SWCommand {
public CommandDebugStick() {
super("debugstick");
}
@Register(help = true)
public void genericHelp(Player p, String... args) {
p.sendMessage("§8/§edebugstick §8- §7Erhalte einen DebugStick");
}
@Register
public void genericCommand(Player p) {
FlatteningWrapper.impl.giveStick(p);
}
}

View File

@ -0,0 +1,114 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.commands;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.Permission;
import de.steamwar.bausystem.SWUtils;
import de.steamwar.bausystem.world.Detonator;
import de.steamwar.bausystem.world.Welt;
import de.steamwar.command.SWCommand;
import org.bukkit.entity.Player;
public class CommandDetonator extends SWCommand {
public CommandDetonator() {
super ("detonator", "dt");
}
@Register(help = true)
public void genericHelp(Player p, String... args) {
p.sendMessage("§8/§edetonator wand §8- §7Legt den Fernzünder ins Inventar");
p.sendMessage("§8/§edetonator detonate §8- §7Benutzt den nächst besten Fernzünder");
p.sendMessage("§8/§edetonator reset §8- §7Löscht alle markierten Positionen");
p.sendMessage("§8/§edetonator remove §8- §7Entfernt den Fernzünder");
}
@Register("wand")
public void wandCommand(Player p) {
if (!permissionCheck(p)) return;
SWUtils.giveItemToPlayer(p, Detonator.WAND);
}
@Register("detonator")
public void detonatorCommand(Player p) {
if (!permissionCheck(p)) return;
SWUtils.giveItemToPlayer(p, Detonator.WAND);
}
@Register("item")
public void itemCommand(Player p) {
if (!permissionCheck(p)) return;
SWUtils.giveItemToPlayer(p, Detonator.WAND);
}
@Register("remove")
public void removeCommand(Player p) {
if (!permissionCheck(p)) return;
p.getInventory().removeItem(Detonator.WAND);
}
@Register("detonate")
public void detonateCommand(Player p) {
if (!permissionCheck(p)) return;
Detonator.execute(p);
}
@Register("click")
public void clickCommand(Player p) {
if (!permissionCheck(p)) return;
Detonator.execute(p);
}
@Register("use")
public void useCommand(Player p) {
if (!permissionCheck(p)) return;
Detonator.execute(p);
}
@Register("clear")
public void clearCommand(Player p) {
if (!permissionCheck(p)) return;
Detonator.clear(p);
}
@Register("delete")
public void deleteCommand(Player p) {
if (!permissionCheck(p)) return;
Detonator.clear(p);
}
@Register("reset")
public void resetCommand(Player p) {
if (!permissionCheck(p)) return;
Detonator.clear(p);
}
private boolean permissionCheck(Player player) {
if (Welt.noPermission(player, Permission.WORLD)) {
player.sendMessage(BauSystem.PREFIX + "§cDu darfst hier nicht den Detonator nutzen");
return false;
}
return true;
}
}

View File

@ -0,0 +1,92 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.commands;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.Permission;
import de.steamwar.bausystem.world.regions.Region;
import de.steamwar.bausystem.world.Welt;
import de.steamwar.command.SWCommand;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockSpreadEvent;
public class CommandFire extends SWCommand implements Listener {
public CommandFire() {
super("fire");
Bukkit.getPluginManager().registerEvents(this, BauSystem.getPlugin());
}
@Register(help = true)
public void genericHelp(Player p, String... args) {
p.sendMessage("§8/§efire §8- §7Toggle Feuerschaden");
}
@Register
public void toggleCommand(Player p) {
if (!permissionCheck(p)) return;
Region region = Region.getRegion(p.getLocation());
if (toggle(region)) {
RegionUtils.actionBar(region, getEnableMessage());
} else {
RegionUtils.actionBar(region, getDisableMessage());
}
}
private String getNoPermMessage() {
return "§cDu darfst hier nicht Feuerschaden (de-)aktivieren";
}
private String getEnableMessage() {
return "§cRegions Feuerschaden deaktiviert";
}
private String getDisableMessage() {
return "§aRegions Feuerschaden aktiviert";
}
private boolean toggle(Region region) {
region.setFire(!region.isFire());
return region.isFire();
}
private boolean permissionCheck(Player player) {
if (Welt.noPermission(player, Permission.WORLD)) {
player.sendMessage(BauSystem.PREFIX + getNoPermMessage());
return false;
}
return true;
}
@EventHandler
public void onFireDamage(BlockBurnEvent e) {
if (Region.getRegion(e.getBlock().getLocation()).isFire()) e.setCancelled(true);
}
@EventHandler
public void onFireSpread(BlockSpreadEvent e) {
if (Region.getRegion(e.getBlock().getLocation()).isFire()) e.setCancelled(true);
}
}

View File

@ -0,0 +1,148 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.commands;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.Permission;
import de.steamwar.bausystem.world.regions.Region;
import de.steamwar.bausystem.world.Welt;
import de.steamwar.command.SWCommand;
import de.steamwar.core.Core;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.*;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.event.entity.EntitySpawnEvent;
import org.bukkit.event.inventory.InventoryMoveItemEvent;
public class CommandFreeze extends SWCommand implements Listener {
public CommandFreeze() {
super("freeze", "stoplag");
Bukkit.getPluginManager().registerEvents(this, BauSystem.getPlugin());
}
@Register(help = true)
public void genericHelp(Player p, String... args) {
p.sendMessage("§8/§efreeze §8- §7Toggle Freeze");
}
@Register
public void toggleCommand(Player p) {
if (!permissionCheck(p)) return;
Region region = Region.getRegion(p.getLocation());
if (toggle(region)) {
RegionUtils.actionBar(region, getEnableMessage());
} else {
RegionUtils.actionBar(region, getDisableMessage());
}
}
private String getNoPermMessage() {
return "§cDu darfst diese Welt nicht einfrieren";
}
private String getEnableMessage(){
return "§cRegion eingefroren";
}
private String getDisableMessage(){
return "§aRegion aufgetaut";
}
private boolean toggle(Region region) {
region.setFreeze(!region.isFreeze());
return region.isFreeze();
}
private boolean permissionCheck(Player player) {
if (Welt.noPermission(player, Permission.WORLD)) {
player.sendMessage(BauSystem.PREFIX + getNoPermMessage());
return false;
}
return true;
}
@EventHandler
public void onEntitySpawn(EntitySpawnEvent e) {
if (!Region.getRegion(e.getLocation()).isFreeze()) return;
e.setCancelled(true);
if (e.getEntityType() == EntityType.PRIMED_TNT) {
Bukkit.getScheduler().runTaskLater(BauSystem.getPlugin(), () -> {
e.getLocation().getBlock().setType(Material.TNT, false);
}, 1L);
}
}
@EventHandler
public void onBlockCanBuild(BlockCanBuildEvent e) {
if (Core.getVersion() == 12) return;
if (!e.isBuildable()) return;
if (!Region.getRegion(e.getBlock().getLocation()).isFreeze()) return;
if (e.getMaterial() == Material.TNT) {
e.setBuildable(false);
e.getBlock().setType(Material.TNT, false);
}
}
@EventHandler
public void onEntityChangeBlock(EntityChangeBlockEvent e) {
if (Region.getRegion(e.getBlock().getLocation()).isFreeze()) e.setCancelled(true);
}
@EventHandler
public void onPhysicsEvent(BlockPhysicsEvent e){
if (Region.getRegion(e.getBlock().getLocation()).isFreeze()) e.setCancelled(true);
}
@EventHandler
public void onPistonExtend(BlockPistonExtendEvent e){
if (Region.getRegion(e.getBlock().getLocation()).isFreeze()) e.setCancelled(true);
}
@EventHandler
public void onPistonRetract(BlockPistonRetractEvent e){
if (Region.getRegion(e.getBlock().getLocation()).isFreeze()) e.setCancelled(true);
}
@EventHandler
public void onBlockGrow(BlockGrowEvent e){
if (Region.getRegion(e.getBlock().getLocation()).isFreeze()) e.setCancelled(true);
}
@EventHandler
public void onRedstoneEvent(BlockRedstoneEvent e) {
if (Region.getRegion(e.getBlock().getLocation()).isFreeze()) e.setNewCurrent(e.getOldCurrent());
}
@EventHandler
public void onBlockDispense(BlockDispenseEvent e) {
if (Region.getRegion(e.getBlock().getLocation()).isFreeze()) e.setCancelled(true);
}
@EventHandler
public void onInventoryMoveEvent(InventoryMoveItemEvent e){
if (Region.getRegion(e.getDestination().getLocation()).isFreeze()) e.setCancelled(true);
}
}

View File

@ -0,0 +1,530 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.commands;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.Permission;
import de.steamwar.bausystem.SWUtils;
import de.steamwar.bausystem.tracer.record.RecordStateMachine;
import de.steamwar.bausystem.tracer.show.TraceShowManager;
import de.steamwar.bausystem.world.*;
import de.steamwar.bausystem.world.regions.GlobalRegion;
import de.steamwar.bausystem.world.regions.Region;
import de.steamwar.command.SWCommand;
import de.steamwar.core.Core;
import de.steamwar.inventory.SWAnvilInv;
import de.steamwar.inventory.SWInventory;
import de.steamwar.inventory.SWItem;
import de.steamwar.inventory.SWListInv;
import de.steamwar.sql.BauweltMember;
import de.steamwar.sql.SteamwarUser;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerSwapHandItemsEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.potion.PotionEffectType;
import java.util.*;
public class CommandGUI extends SWCommand implements Listener {
private static final Set<Player> OPEN_INVS = new HashSet<>();
private static final Set<Player> OPEN_TRACER_INVS = new HashSet<>();
private static final Set<Player> LAST_F_PLAYER = new HashSet<>();
private static boolean isRefreshing = false;
public CommandGUI() {
super("gui");
Bukkit.getScheduler().runTaskTimerAsynchronously(BauSystem.getPlugin(), LAST_F_PLAYER::clear, 0, 20);
}
@Register(help = true)
public void genericHelp(Player p, String... args) {
p.sendMessage("§8/§egui §8- §7Öffne die GUI");
p.sendMessage("§8/§egui item §8- §7Gebe das GUI item");
}
@Register
public void genericCommand(Player p) {
openBauGui(p);
OPEN_INVS.add(p);
}
@Register({"item"})
public void itemCommand(Player p) {
SWUtils.giveItemToPlayer(p, new ItemStack(Material.NETHER_STAR));
}
public static void openBauGui(Player player) {
Region region = Region.getRegion(player.getLocation());
SWInventory inv = new SWInventory(player, 5 * 9, SteamwarUser.get(BauSystem.getOwner()).getUserName() + "s Bau");
inv.setCallback(-1, clickType -> {
if (!isRefreshing)
OPEN_INVS.remove(player);
});
inv.setItem(43, getMaterial("GLASS_PANE", "THIN_GLASS"), "§7Platzhalter", clickType -> {
});
inv.setItem(42, Material.NETHER_STAR, "§7Bau GUI Item", Arrays.asList("§7Du kannst dieses Item zum Öffnen der BauGUI nutzen", "§7oder Doppel F (Swap hands) drücken."), false, clickType -> {
player.closeInventory();
player.performCommand("gui item");
});
ItemStack dtWand = wand(player, Detonator.WAND, "§8/§7dt wand", Permission.WORLD, "§cDu hast keine Worldrechte");
inv.setItem(39, dtWand, clickType -> {
if (Welt.noPermission(player, Permission.WORLD))
return;
player.closeInventory();
player.performCommand("dt wand");
});
ItemStack redstoneWand = wand(player, CommandRedstoneTester.WAND, "§8/§7redstonetester", null, "");
inv.setItem(37, redstoneWand, clickType -> {
player.closeInventory();
player.performCommand("redstonetester");
});
inv.setItem(40, getMaterial("WOODEN_AXE", "WOOD_AXE"), "§eWorldedit Axt", getNoPermsLore(Arrays.asList("§8//§7wand"), player, "§cDu hast keine Worldeditrechte", Permission.WORLDEDIT), false, clickType -> {
if (Welt.noPermission(player, Permission.WORLD))
return;
player.closeInventory();
player.performCommand("/wand");
});
inv.setItem(41, getMaterial("DEBUG_STICK", "STICK"), "§eDebugstick", getNoPermsLore(Arrays.asList("§8/§7debugstick"), player, "§cDu hast keine Worldrechte", Permission.WORLD), Core.getVersion() < 13, clickType -> {
if (Welt.noPermission(player, Permission.WORLD))
return;
player.closeInventory();
player.performCommand("debugstick");
});
inv.setItem(20, Material.COMPASS, "§7TPS Limitieren", getNoPermsLore(Arrays.asList("§7Aktuell: §e" + CommandTPSLimiter.getCurrentTPSLimit(), "§8/§7tpslimit §8[§e0,5 - " + (TPSUtils.isWarpAllowed() ? 40 : 20) + "§8]"), player, "§cDu hast keine Worldrechte", Permission.WORLD), false, clickType -> {
if (Welt.noPermission(player, Permission.WORLD))
return;
SWAnvilInv anvilInv = new SWAnvilInv(player, "TPS Limitieren");
anvilInv.setItem(Material.COMPASS);
anvilInv.setCallback(s -> player.performCommand("tpslimit " + s));
anvilInv.open();
});
inv.setItem(5, Material.FEATHER, "§7Geschwindigkeit", Arrays.asList("§7Aktuell: §e" + player.getFlySpeed() * 10, "§8/§7speed §8[§e1 - 10§8]"), false, clickType -> {
SWAnvilInv anvilInv = new SWAnvilInv(player, "Geschwindigkeit");
anvilInv.setItem(Material.FEATHER);
anvilInv.setCallback(s -> player.performCommand("speed " + s));
anvilInv.open();
});
if (player.getUniqueId().equals(BauSystem.getOwner())) {
SWItem skull = SWItem.getPlayerSkull(player.getName());
skull.setName("§7Bau verwalten");
List<String> skullLore = new ArrayList<>();
skullLore.add("§7TNT: §e" + region.getTntMode().getName());
skullLore.add("§7StopLag: §e" + (region.isFreeze() ? "Eingeschaltet" : "Ausgeschaltet"));
skullLore.add("§7Fire: §e" + (region.isFire() ? "Ausgeschaltet" : "Eingeschaltet"));
skullLore.add("§7Members: §e" + (BauweltMember.getMembers(BauSystem.getOwnerID()).size() - 1));
skull.setLore(skullLore);
inv.setItem(4, skull);
}
inv.setItem(6, Material.BOOK, "§7Script Bücher", Arrays.asList("§7Aktuell §e" + PredefinedBook.getBookCount() + " §7Bücher"), true, clickType -> {
player.closeInventory();
scriptBooksGUI(player);
});
inv.setItem(21, Material.OBSERVER, "§7Tracer", getNoPermsLore(Arrays.asList("§7Status: §e" + RecordStateMachine.getRecordStatus().getName()), player, "§cDu hast keine Worldrechte", Permission.WORLD), false, clickType -> {
if (Welt.noPermission(player, Permission.WORLD))
return;
player.closeInventory();
OPEN_TRACER_INVS.add(player);
traceGUI(player);
});
inv.setItem(22, Material.DISPENSER, "§7Auto-Loader", getNoPermsLore(Arrays.asList("§7Status: " + (AutoLoader.hasLoader(player) ? "§aan" : "§caus")), player, "§cDu hast keine Worldrechte", Permission.WORLD), false, clickType -> {
if (Welt.noPermission(player, Permission.WORLD))
return;
player.closeInventory();
autoLoaderGUI(player);
});
inv.setItem(17, getMaterial("PLAYER_HEAD", "SKULL_ITEM"), (byte) 3, "§7Spielerkopf geben", Arrays.asList("§8/§7skull §8[§eSpieler§8]"), false, clickType -> {
SWAnvilInv anvilInv = new SWAnvilInv(player, "Spielerköpfe");
anvilInv.setItem(Material.NAME_TAG);
anvilInv.setCallback(s -> player.performCommand("skull " + s));
anvilInv.open();
});
if (GlobalRegion.isGlobalRegion(region)) {
inv.setItem(9, Material.BARRIER, "§eKeine Region", clickType -> {
});
inv.setItem(18, Material.BARRIER, "§eKeine Region", clickType -> {
});
inv.setItem(27, Material.BARRIER, "§eKeine Region", clickType -> {
});
} else {
inv.setItem(27, getMaterial("HEAVY_WEIGHTED_PRESSURE_PLATE", "IRON_PLATE"), "§eRegion Reseten", getNoPermsLore(Arrays.asList("§8/§7reset"), player, "§cDu hast keine Worldrechte", Permission.WORLD), false, clickType -> {
if (Welt.noPermission(player, Permission.WORLD))
return;
confirmationInventory(player, "Region Reseten?", () -> player.performCommand("reset"), () -> openBauGui(player));
});
if (region.hasProtection()) {
inv.setItem(18, Material.OBSIDIAN, "§eRegion Protecten", getNoPermsLore(Arrays.asList("§8/§7protect"), player, "§cDu hast keine Worldrechte", Permission.WORLD), false, clickType -> {
if (Welt.noPermission(player, Permission.WORLD))
return;
confirmationInventory(player, "Region Protecten", () -> player.performCommand("protect"), () -> openBauGui(player));
});
} else {
inv.setItem(18, Material.BARRIER, "§eRegion nicht Protect bar", clickType -> {
});
}
if (region.hasTestblock()) {
inv.setItem(9, getMaterial("END_STONE", "ENDER_STONE"), "§eTestblock erneuern", getNoPermsLore(Arrays.asList("§8/§7testblock"), player, "§cDu hast keine Worldrechte", Permission.WORLD), false, clickType -> {
if (Welt.noPermission(player, Permission.WORLD))
return;
confirmationInventory(player, "Testblock erneuern", () -> player.performCommand("testblock"), () -> openBauGui(player));
});
} else {
inv.setItem(9, Material.BARRIER, "§eDie Region hat keinen Testblock", clickType -> {
});
}
}
if (player.hasPotionEffect(PotionEffectType.NIGHT_VISION)) {
inv.setItem(26, Material.POTION, "§7Nightvision: §eEingeschaltet", Collections.singletonList("§8/§7nv"), false, clickType -> {
CommandNV.toggleNightvision(player);
openBauGui(player);
});
} else {
inv.setItem(26, Material.GLASS_BOTTLE, "§7Nightvision: §eAusgeschaltet", Collections.singletonList("§8/§7nv"), false, clickType -> {
CommandNV.toggleNightvision(player);
openBauGui(player);
});
}
if (player.hasPotionEffect(PotionEffectType.WATER_BREATHING)) {
inv.setItem(35, Material.WATER_BUCKET, "§7Waterbreathing: §eEingeschaltet", Collections.singletonList("§8/§7wv"), false, clickType -> {
CommandGills.toggleGills(player);
openBauGui(player);
});
} else {
inv.setItem(35, Material.BUCKET, "§7Waterbreathing: §eAusgeschaltet", Collections.singletonList("§8/§7wv"), false, clickType -> {
CommandGills.toggleGills(player);
openBauGui(player);
});
}
boolean isBuildArea = region.hasBuildRegion();
List<String> tntLore = getNoPermsLore(Arrays.asList("§8/§7tnt §8[" + (isBuildArea ? "§eTB§7, " : "") + "§eOff §7oder §eOn§7]"), player, "§cDu hast keine Worldrechte", Permission.WORLD);
switch (region.getTntMode()) {
case OFF:
inv.setItem(23, Material.MINECART, "§7TNT: §eAusgeschaltet", tntLore, false, clickType -> {
if (Welt.noPermission(player, Permission.WORLD))
return;
player.performCommand("tnt " + (isBuildArea ? "tb" : "on"));
updateInventories();
});
break;
case ONLY_TB:
inv.setItem(23, getMaterial("TNT_MINECART", "EXPLOSIVE_MINECART"), "§7TNT: §enur Testblock", tntLore, false, clickType -> {
if (Welt.noPermission(player, Permission.WORLD))
return;
player.performCommand("tnt on");
updateInventories();
});
break;
default:
inv.setItem(23, Material.TNT, "§7TNT: §eEingeschaltet", tntLore, false, clickType -> {
if (Welt.noPermission(player, Permission.WORLD))
return;
player.performCommand("tnt off");
updateInventories();
});
}
if (region.isFreeze()) {
inv.setItem(24, getMaterial("GUNPOWDER", "SULPHUR"), "§7Freeze: §eEingeschaltet", getNoPermsLore(Arrays.asList("§8/§7freeze"), player, "§cDu hast keine Worldrechte", Permission.WORLD), false, clickType -> {
if (Welt.noPermission(player, Permission.WORLD))
return;
player.performCommand("freeze");
updateInventories();
});
} else {
inv.setItem(24, Material.REDSTONE, "§7Freeze: §eAusgeschaltet", getNoPermsLore(Arrays.asList("§8/§7freeze"), player, "§cDu hast keine Worldrechte", Permission.WORLD), false, clickType -> {
if (Welt.noPermission(player, Permission.WORLD))
return;
player.performCommand("freeze");
updateInventories();
});
}
if (region.isFire()) {
inv.setItem(3, getMaterial("FIREWORK_STAR", "FIREWORK_CHARGE"), "§7Fire: §eAusgeschaltet", getNoPermsLore(Arrays.asList("§8/§7fire"), player, "§cDu hast keine Worldrechte", Permission.WORLD), false, clickType -> {
if (Welt.noPermission(player, Permission.WORLD))
return;
player.performCommand("fire");
updateInventories();
});
} else {
inv.setItem(3, getMaterial("FIRE_CHARGE", "FIREBALL"), "§7Fire: §eEingeschaltet", getNoPermsLore(Arrays.asList("§8/§7fire"), player, "§cDu hast keine Worldrechte", Permission.WORLD), false, clickType -> {
if (Welt.noPermission(player, Permission.WORLD))
return;
player.performCommand("fire");
updateInventories();
});
}
inv.setItem(2, Material.ENDER_PEARL, "§7Teleporter", getNoPermsLore(Arrays.asList("§8/§7tp §8[§eSpieler§8]"), player, "", null), false, clickType -> {
List<SWListInv.SWListEntry<String>> playerSWListEntry = new ArrayList<>();
Bukkit.getOnlinePlayers().forEach(player1 -> {
if (player1.equals(player))
return;
playerSWListEntry.add(new SWListInv.SWListEntry<>(SWItem.getPlayerSkull(player1.getName()), player1.getName()));
});
SWListInv<String> playerSWListInv = new SWListInv<>(player, "Teleporter", playerSWListEntry, (clickType1, player1) -> {
player.closeInventory();
player.performCommand("tp " + player1);
});
playerSWListInv.open();
});
inv.open();
}
private static void traceGUI(Player player) {
SWInventory inv = new SWInventory(player, 9, "Tracer");
inv.setCallback(-1, clickType -> {
if (!isRefreshing)
OPEN_TRACER_INVS.remove(player);
});
List<String> stateLore = Arrays.asList("§7Aktuell: §e" + RecordStateMachine.getRecordStatus().getName(), "§8/§7trace §8[§estart§8, stop §8oder §eauto§8]");
switch (RecordStateMachine.getRecordStatus()) {
case IDLE:
inv.setItem(0, getMaterial("SNOWBALL", "SNOW_BALL"), "§7Tracerstatus", stateLore, false, clickType -> {
RecordStateMachine.commandAuto();
updateInventories();
});
break;
case IDLE_AUTO:
inv.setItem(0, Material.ENDER_PEARL, "§7Tracerstatus", stateLore, false, clickType -> {
RecordStateMachine.commandStart();
updateInventories();
});
break;
case RECORD:
case RECORD_AUTO:
inv.setItem(0, getMaterial("ENDER_EYE", "EYE_OF_ENDER"), "§7Tracerstatus", stateLore, false, clickType -> {
RecordStateMachine.commandStop();
updateInventories();
});
}
if (TraceShowManager.hasActiveShow(player)) {
inv.setItem(2, Material.TNT, "§7Showstatus", Arrays.asList("§7Aktuell: §eGezeigt", "§8/§7trace §8[§eshow§8/§ehide§8]"), false, clickType -> {
player.performCommand("trace hide");
traceGUI(player);
});
} else {
inv.setItem(2, Material.GLASS, "§7Showstatus", Arrays.asList("§7Aktuell: §eVersteckt", "§8/§7trace §8[§eshow§8/§ehide§8]"), false, clickType -> {
player.performCommand("trace show");
traceGUI(player);
});
}
inv.setItem(4, getMaterial("TNT_MINECART", "EXPLOSIVE_MINECART"), "§7Trace GUI", Collections.singletonList("§8/§7trace show gui"), false, clickType -> {
player.closeInventory();
player.performCommand("trace show gui");
});
inv.setItem(6, Material.BARRIER, "§7Trace löschen", Arrays.asList("§8/§7trace delete"), false, clickType -> confirmationInventory(player, "Trace löschen", () -> player.performCommand("trace delete"), () -> {
}));
inv.setItem(8, Material.ARROW, "§7Zurück", clickType -> {
player.closeInventory();
openBauGui(player);
OPEN_INVS.add(player);
});
inv.open();
}
private static void scriptBooksGUI(Player player) {
List<SWListInv.SWListEntry<PredefinedBook>> entries = new ArrayList<>();
List<PredefinedBook> books = PredefinedBook.getBooks();
books.forEach(predefinedBook -> entries.add(new SWListInv.SWListEntry<>(new SWItem(predefinedBook.getBookMat(), predefinedBook.getName(), predefinedBook.getLore(), false, clickType -> {
}), predefinedBook)));
SWListInv<PredefinedBook> inv = new SWListInv<>(player, "Script Bücher", entries, (clickType, predefinedBook) -> {
player.closeInventory();
player.getInventory().addItem(predefinedBook.toItemStack());
});
inv.open();
}
private static void autoLoaderGUI(Player player) {
SWInventory inv = new SWInventory(player, 9, "Autoloader");
boolean hasLoader = AutoLoader.hasLoader(player);
if (hasLoader) {
AutoLoader loader = AutoLoader.getLoader(player);
if (loader.isSetup()) {
inv.setItem(0, Material.DROPPER, "§7Loader Starten", Collections.singletonList("§8/§7loader start"), false, clickType -> {
loader.start();
autoLoaderGUI(player);
});
inv.setItem(2, Material.ARROW, "§7Letzte Aktion entfernen", Collections.singletonList("§8/§7loader undo"), false, clickType -> {
});
} else {
inv.setItem(0, Material.BLAZE_ROD, "§7Loader Bearbeiten", Collections.singletonList("§8/§7loader setup"), false, clickType -> {
loader.setup();
autoLoaderGUI(player);
});
}
inv.setItem(4, Material.COMPASS, "§7Schuss Delay", Arrays.asList("§7Aktuell: §e" + loader.getTicksBetweenShots(), "§8/§7loader wait §8[§eTicks§8]"), false, clickType -> {
SWAnvilInv anvilInv = new SWAnvilInv(player, "Schuss Delay", loader.getTicksBetweenShots() + "");
anvilInv.setItem(Material.STONE);
anvilInv.setCallback(s -> {
player.performCommand("loader wait " + s);
autoLoaderGUI(player);
});
anvilInv.open();
});
inv.setItem(6, getMaterial("CLOCK", "WATCH"), "§7Block platzier Geschwindigkeit", Arrays.asList("§7Aktuell: §e" + loader.getTicksBetweenBlocks(), "§8/§7loader speed §8[§eTicks§8]"), false, clickType -> {
SWAnvilInv anvilInv = new SWAnvilInv(player, "Platzier Geschwindigkeit", loader.getTicksBetweenBlocks() + "");
anvilInv.setItem(Material.STONE);
anvilInv.setCallback(s -> {
player.performCommand("loader speed " + s);
autoLoaderGUI(player);
});
anvilInv.open();
});
inv.setItem(8, Material.BARRIER, "§7Loader löschen", Collections.singletonList("§8/§7loader stop"), false, clickType -> confirmationInventory(player, "Loader löschen?", () -> {
loader.stop();
autoLoaderGUI(player);
}, () -> autoLoaderGUI(player)));
} else {
inv.setItem(4, Material.GOLD_NUGGET, "§eNeuer Autoloader", clickType -> {
AutoLoader.getLoader(player);
player.closeInventory();
});
inv.setItem(8, Material.ARROW, "§7Zurück", clickType -> {
player.closeInventory();
openBauGui(player);
OPEN_INVS.add(player);
});
}
inv.open();
}
private static void confirmChatMessage(Player player, String command) {
player.sendMessage(BauSystem.PREFIX + "§7Klicke auf die Nachricht zum bestätigen");
TextComponent t = new TextComponent();
t.setText("[Hier]");
t.setColor(ChatColor.YELLOW);
t.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, command));
t.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, TextComponent.fromLegacyText("§7" + command)));
player.spigot().sendMessage(t);
}
private static List<String> getNoPermsLore(List<String> lore, Player player, String noPerms, Permission perm) {
if (perm != null && Welt.noPermission(player, perm)) {
lore = new ArrayList<>(lore);
lore.add(noPerms);
}
return lore;
}
private static void updateInventories() {
isRefreshing = true;
OPEN_INVS.forEach(CommandGUI::openBauGui);
OPEN_TRACER_INVS.forEach(CommandGUI::traceGUI);
isRefreshing = false;
}
private static void confirmationInventory(Player player, String title, Runnable confirm, Runnable decline) {
SWInventory inv = new SWInventory(player, 9, title);
inv.setItem(0, SWItem.getDye(1), (byte) 1, "§cAbbrechen", clickType -> {
player.closeInventory();
decline.run();
});
inv.setItem(8, SWItem.getDye(10), (byte) 10, "§aBestätigen", clickType -> {
player.closeInventory();
confirm.run();
});
inv.open();
}
private static Material getMaterial(String... names) {
for (String name : names) {
try {
return Material.valueOf(name);
} catch (IllegalArgumentException ignored) {
//Ignored /\
}
}
return null;
}
private static ItemStack wand(Player player, ItemStack base, String command, Permission permission, String noPermissionMessage) {
base = base.clone();
ItemMeta meta = base.getItemMeta();
List<String> lore = meta.getLore();
lore.add(command);
if (permission != null && Welt.noPermission(player, permission))
lore.add(noPermissionMessage);
meta.setLore(lore);
base.setItemMeta(meta);
return base;
}
@EventHandler
public void onPlayerInteract(PlayerInteractEvent event) {
if (event.getAction() != Action.RIGHT_CLICK_AIR && event.getAction() != Action.RIGHT_CLICK_BLOCK)
return;
if (event.getItem() == null || event.getItem().getType() != Material.NETHER_STAR)
return;
openBauGui(event.getPlayer());
OPEN_INVS.add(event.getPlayer());
}
@EventHandler
public void onPlayerSwapHandItems(PlayerSwapHandItemsEvent event) {
if (LAST_F_PLAYER.contains(event.getPlayer())) {
openBauGui(event.getPlayer());
OPEN_INVS.add(event.getPlayer());
} else {
LAST_F_PLAYER.add(event.getPlayer());
}
}
}

View File

@ -0,0 +1,50 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.commands;
import de.steamwar.command.SWCommand;
import org.bukkit.GameMode;
import org.bukkit.entity.Player;
public class CommandGamemode extends SWCommand {
public CommandGamemode() {
super("gamemode", "gm", "g");
}
@Register(help = true)
public void gamemodeHelp(Player p, String... args) {
p.sendMessage("§cUnbekannter Spielmodus");
}
@Register
public void genericCommand(Player p) {
if (p.getGameMode() == GameMode.CREATIVE) {
p.setGameMode(GameMode.SPECTATOR);
} else {
p.setGameMode(GameMode.CREATIVE);
}
}
@Register
public void gamemodeCommand(Player p, GameMode gameMode) {
p.setGameMode(gameMode);
}
}

View File

@ -0,0 +1,53 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.commands;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.command.SWCommand;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
public class CommandGills extends SWCommand {
public CommandGills() {
super("watervision", "wv");
}
@Register(help = true)
public void genericHelp(Player p, String... args) {
p.sendMessage("§8/§ewatervision §8- §7Toggle WaterBreathing");
}
@Register
public void genericCommand(Player p) {
toggleGills(p);
}
public static void toggleGills(Player player) {
if (player.hasPotionEffect(PotionEffectType.WATER_BREATHING)) {
player.sendMessage(BauSystem.PREFIX + "Wassersicht deaktiviert");
player.removePotionEffect(PotionEffectType.WATER_BREATHING);
return;
}
player.addPotionEffect(new PotionEffect(PotionEffectType.WATER_BREATHING, 1000000, 255, false, false));
player.sendMessage(BauSystem.PREFIX + "Wassersicht aktiviert");
}
}

View File

@ -0,0 +1,80 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.commands;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.world.TPSUtils;
import de.steamwar.bausystem.world.regions.Region;
import de.steamwar.command.SWCommand;
import de.steamwar.core.TPSWatcher;
import de.steamwar.sql.BauweltMember;
import de.steamwar.sql.SteamwarUser;
import org.bukkit.entity.Player;
import java.util.List;
import static de.steamwar.bausystem.world.TPSUtils.getTps;
public class CommandInfo extends SWCommand {
public CommandInfo() {
super("bauinfo");
}
@Register(help = true)
public void genericHelp(Player p, String... args) {
p.sendMessage("§8/§ebauinfo §8- §7Gibt Informationen über den Bau");
}
@Register
public void genericCommand(Player p) {
CommandInfo.sendBauInfo(p);
}
public static void sendBauInfo(Player p) {
p.sendMessage(BauSystem.PREFIX + "Besitzer: §e" + SteamwarUser.get(BauSystem.getOwnerID()).getUserName());
Region region = Region.getRegion(p.getLocation());
p.sendMessage(BauSystem.PREFIX + "§eTNT§8: " + region.getTntMode().getName() + " §eFire§8: " + (region.isFire() ? "§aAUS" : "§cAN") + " §eFreeze§8: " + (region.isFreeze() ? "§aAN" : "§cAUS"));
if (region.hasProtection()) {
p.sendMessage(BauSystem.PREFIX + "§eProtect§8: " + (region.isProtect() ? "§aAN" : "§cAUS"));
}
List<BauweltMember> members = BauweltMember.getMembers(BauSystem.getOwnerID());
StringBuilder membermessage = new StringBuilder().append(BauSystem.PREFIX).append("Mitglieder: ");
for (BauweltMember member : members) {
membermessage.append("§e").append(SteamwarUser.get(member.getMemberID()).getUserName()).append("§8[");
membermessage.append(member.isWorldEdit() ? "§a" : "§c").append("WE").append("§8,");
membermessage.append(member.isWorld() ? "§a" : "§c").append("W").append("§8]").append(" ");
}
p.sendMessage(membermessage.toString());
StringBuilder tpsMessage = new StringBuilder();
tpsMessage.append(BauSystem.PREFIX).append("TPS:§e");
tpsMessage.append(" ").append(getTps(TPSWatcher.TPSType.ONE_SECOND));
tpsMessage.append(" ").append(getTps(TPSWatcher.TPSType.TEN_SECONDS));
if (!TPSUtils.isWarping()) {
tpsMessage.append(" ").append(TPSWatcher.getTPS(TPSWatcher.TPSType.ONE_MINUTE));
tpsMessage.append(" ").append(TPSWatcher.getTPS(TPSWatcher.TPSType.FIVE_MINUTES));
tpsMessage.append(" ").append(TPSWatcher.getTPS(TPSWatcher.TPSType.TEN_MINUTES));
}
p.sendMessage(tpsMessage.toString());
}
}

View File

@ -0,0 +1,74 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.commands;
import de.steamwar.bausystem.world.regions.*;
import de.steamwar.command.SWCommand;
import java.util.concurrent.atomic.AtomicLong;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.entity.Player;
public class CommandKillAll extends SWCommand {
private static final World WORLD = Bukkit.getWorlds().get(0);
public CommandKillAll() {
super("killall", "removeall");
}
@Register(help = true)
public void genericHelp(Player player, String... args) {
player.sendMessage("§8/§ekillall §8- §7Entferne alle Entities aus deiner Region");
player.sendMessage("§8/§ekillall §8[§7Global§8/Local§7] §8- §7Entferne alle Entities aus deiner Region oder global");
}
@Register
public void genericCommand(Player player) {
genericCommand(player, RegionSelectionType.LOCAL);
}
@Register
public void genericCommand(Player player, RegionSelectionType regionSelectionType) {
Region region = Region.getRegion(player.getLocation());
AtomicLong removedEntities = new AtomicLong();
if (regionSelectionType == RegionSelectionType.GLOBAL || GlobalRegion.isGlobalRegion(region)) {
WORLD.getEntities()
.stream()
.filter(e -> !(e instanceof Player))
.forEach(entity -> {
entity.remove();
removedEntities.getAndIncrement();
});
RegionUtils.actionBar(GlobalRegion.getInstance(), "§a" + removedEntities.get() + " Entities aus der Welt entfernt");
} else {
WORLD.getEntities()
.stream()
.filter(e -> !(e instanceof Player))
.filter(e -> region.inRegion(e.getLocation(), RegionType.NORMAL, RegionExtensionType.NORMAL))
.forEach(entity -> {
entity.remove();
removedEntities.getAndIncrement();
});
RegionUtils.actionBar(region, "§a" + removedEntities.get() + " Entities aus der Region entfernt");
}
}
}

View File

@ -0,0 +1,134 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.commands;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.Permission;
import de.steamwar.bausystem.world.AutoLoader;
import de.steamwar.bausystem.world.Welt;
import de.steamwar.command.SWCommand;
import org.bukkit.entity.Player;
public class CommandLoader extends SWCommand {
public CommandLoader() {
super("loader");
}
@Register(help = true)
public void genericHelp(Player p, String... args) {
p.sendMessage("§8/§eloader setup §8- §7Startet die Aufnahme der Aktionen");
p.sendMessage("§8/§7loader undo §8- §7Entfernt die zuletzt aufgenommene Aktion");
p.sendMessage("§8/§eloader start §8- §7Spielt die zuvor aufgenommenen Aktionen ab");
p.sendMessage("§8/§7loader wait §8[§7Ticks§8] - §7Setzt die Wartezeit zwischen Schüssen");
p.sendMessage("§8/§7loader speed §8[§7Ticks§8] - §7Setzt die Wartezeit zwischen Aktionen");
p.sendMessage("§8/§eloader stop §8- §7Stoppt die Aufnahme bzw. das Abspielen");
p.sendMessage("§7Der AutoLader arbeitet mit §eIngame§8-§eTicks §8(20 Ticks pro Sekunde)");
}
@Register({"setup"})
public void setupCommand(Player p) {
setup(p);
}
@Register({"undo"})
public void undoCommand(Player p) {
undo(p);
}
@Register({"start"})
public void startCommand(Player p) {
start(p);
}
@Register({"stop"})
public void stopCommand(Player p) {
stop(p);
}
@Register({"wait"})
public void waitCommand(Player p, int time) {
wait(p, time);
}
@Register({"speed"})
public void speedCommand(Player p, int time) {
speed(p, time);
}
private void setup(Player player) {
AutoLoader.getLoader(player).setup();
}
private void undo(Player player) {
AutoLoader loader = loader(player);
if (loader == null)
return;
if (!loader.isSetup()) {
player.sendMessage("§cDer AutoLader wird in den Setup-Zustand versetzt");
setup(player);
}
loader.undo();
}
private void start(Player player) {
AutoLoader loader = loader(player);
if (loader == null)
return;
loader.start();
}
private void stop(Player player) {
if (!AutoLoader.hasLoader(player)) {
player.sendMessage(BauSystem.PREFIX + "§cDu hast keinen aktiven AutoLader");
return;
}
AutoLoader.getLoader(player).stop();
}
private void wait(Player player, int time) {
AutoLoader loader = loader(player);
if (loader == null) {
loader = AutoLoader.getLoader(player);
}
loader.wait(time);
}
private void speed(Player player, int time) {
AutoLoader loader = loader(player);
if (loader == null) {
loader = AutoLoader.getLoader(player);
}
loader.blockWait(time);
}
private AutoLoader loader(Player player) {
if (AutoLoader.hasLoader(player)) {
return AutoLoader.getLoader(player);
}
player.sendMessage(BauSystem.PREFIX + "§cDu hast keinen aktiven AutoLader");
player.sendMessage(BauSystem.PREFIX + "§7Es wird ein neuer AutoLader gestartet");
setup(player);
return null;
}
}

View File

@ -0,0 +1,67 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.commands;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.command.SWCommand;
import de.steamwar.sql.*;
import org.bukkit.entity.Player;
public class CommandLockschem extends SWCommand {
public CommandLockschem() {
super("lockschem");
}
@Register(help = true)
public void genericHelp(Player p, String... args) {
if (!SteamwarUser.get(p.getUniqueId()).hasPerm(UserPerm.CHECK)) {
return;
}
sendHelp(p);
}
@Register
public void genericCommand(Player p, String owner, String schematicName) {
if (!SteamwarUser.get(p.getUniqueId()).hasPerm(UserPerm.CHECK)) {
return;
}
SteamwarUser schemOwner = SteamwarUser.get(owner);
if (schemOwner == null) {
p.sendMessage(BauSystem.PREFIX + "Dieser Spieler existiert nicht!");
return;
}
SchematicNode node = SchematicNode.getNodeFromPath(schemOwner, schematicName);
if (node == null) {
p.sendMessage(BauSystem.PREFIX + "Dieser Spieler besitzt keine Schematic mit diesem Namen!");
return;
}
p.sendMessage(BauSystem.PREFIX + "Schematic " + node .getName() + " von " +
SteamwarUser.get(node.getOwner()).getUserName() + " von " + node.getSchemtype().toString() +
" auf NORMAL zurückgesetzt!");
node.setSchemtype(SchematicType.Normal);
}
private void sendHelp(Player player) {
player.sendMessage("§8/§eschemlock §8[§7Owner§8] §8[§7Schematic§8] §8- §7 Sperre eine Schematic");
}
}

View File

@ -0,0 +1,54 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.commands;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.command.SWCommand;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
public class CommandNV extends SWCommand {
public CommandNV() {
super("nightvision", "nv");
}
@Register(help = true)
public void genericHelp(Player p, String... args) {
p.sendMessage("§8/§enightvision §8- §7Toggle NightVision");
}
@Register
public void genericCommand(Player p) {
toggleNightvision(p);
}
public static void toggleNightvision(Player player) {
if (player.hasPotionEffect(PotionEffectType.NIGHT_VISION)) {
player.sendMessage(BauSystem.PREFIX + "Nachtsicht deaktiviert");
player.removePotionEffect(PotionEffectType.NIGHT_VISION);
return;
}
player.addPotionEffect(new PotionEffect(PotionEffectType.NIGHT_VISION, 1000000, 255, false, false));
player.sendMessage(BauSystem.PREFIX + "Nachtsicht aktiviert");
}
}

View File

@ -0,0 +1,127 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.commands;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.Permission;
import de.steamwar.bausystem.world.Welt;
import de.steamwar.bausystem.world.regions.Region;
import de.steamwar.command.SWCommand;
import de.steamwar.sql.SchematicNode;
import de.steamwar.sql.SteamwarUser;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityExplodeEvent;
import java.io.IOException;
import java.util.logging.Level;
public class CommandProtect extends SWCommand implements Listener {
public CommandProtect() {
super("protect");
if (Region.buildAreaEnabled()) {
Bukkit.getPluginManager().registerEvents(this, BauSystem.getPlugin());
}
}
@Register(help = true)
public void genericHelp(Player p, String... args) {
p.sendMessage("§8/§eprotect §8- §7Schütze die Region");
p.sendMessage("§8/§eprotect §8[§7Schematic§8] §8- §7Schütze die Region mit einer Schematic");
}
@Register
public void genericProtectCommand(Player p) {
if (!permissionCheck(p)) return;
Region region = regionCheck(p);
if (region == null) return;
if (Region.buildAreaEnabled()) {
region.setProtect(!region.isProtect());
if (region.isProtect()) {
RegionUtils.actionBar(region, "§aBoden geschützt");
} else {
RegionUtils.actionBar(region, "§cBoden Schutz aufgehoben");
}
return;
}
try {
region.protect(null);
p.sendMessage(BauSystem.PREFIX + "§7Boden geschützt");
} catch (IOException e) {
p.sendMessage(BauSystem.PREFIX + "§cFehler beim Schützen der Region");
Bukkit.getLogger().log(Level.WARNING, "Failed protect", e);
}
}
@Register
public void schematicProtectCommand(Player p, String s) {
if (!permissionCheck(p)) return;
if (Region.buildAreaEnabled()) {
genericHelp(p);
return;
}
Region region = regionCheck(p);
if (region == null) return;
SteamwarUser owner = SteamwarUser.get(p.getUniqueId());
SchematicNode schem = SchematicNode.getNodeFromPath(owner, s);
if (schem == null) {
p.sendMessage(BauSystem.PREFIX + "§cSchematic nicht gefunden");
return;
}
try {
region.protect(schem);
p.sendMessage(BauSystem.PREFIX + "§7Boden geschützt");
} catch (IOException e) {
p.sendMessage(BauSystem.PREFIX + "§cFehler beim Schützen der Region");
Bukkit.getLogger().log(Level.WARNING, "Failed protect", e);
}
}
private boolean permissionCheck(Player player) {
if (Welt.noPermission(player, Permission.WORLDEDIT)) {
player.sendMessage(BauSystem.PREFIX + "§cDu darfst hier nicht den Boden schützen");
return false;
}
return true;
}
private Region regionCheck(Player player) {
Region region = Region.getRegion(player.getLocation());
if (!region.hasProtection()) {
player.sendMessage(BauSystem.PREFIX + "§cDu befindest dich derzeit in keiner (M)WG-Region");
return null;
}
return region;
}
@EventHandler
public void onExplode(EntityExplodeEvent event) {
Region region = Region.getRegion(event.getLocation());
if (!region.isProtect() || !region.hasProtection()) {
return;
}
event.blockList().removeIf(block -> {
return block.getY() < region.getProtectYLevel();
});
}
}

View File

@ -0,0 +1,52 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.commands;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.SWUtils;
import de.steamwar.command.SWCommand;
import de.steamwar.inventory.SWItem;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.util.Arrays;
public class CommandRedstoneTester extends SWCommand {
public static final ItemStack WAND = new SWItem(Material.BLAZE_ROD, "§eRedstonetester", Arrays.asList("§eLinksklick Block §8- §7Setzt die 1. Position", "§eRechtsklick Block §8- §7Setzt die 2. Position", "§eShift-Rechtsklick Luft §8- §7Zurücksetzten"), false, null).getItemStack();
public CommandRedstoneTester() {
super("redstonetester", "rt");
}
@Register(help = true)
public void genericHelp(Player p, String... args) {
p.sendMessage("§8/§eredstonetester §8- §7Gibt den RedstoneTester");
}
@Register
public void genericCommand(Player p) {
p.sendMessage(BauSystem.PREFIX + "Messe die Zeit zwischen der Aktivierung zweier Redstone Komponenten");
SWUtils.giveItemToPlayer(p, WAND);
}
}

View File

@ -0,0 +1,132 @@
package de.steamwar.bausystem.commands;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.Permission;
import de.steamwar.bausystem.world.Color;
import de.steamwar.bausystem.world.Welt;
import de.steamwar.bausystem.world.regions.GlobalRegion;
import de.steamwar.bausystem.world.regions.Region;
import de.steamwar.bausystem.world.regions.RegionExtensionType;
import de.steamwar.bausystem.world.regions.RegionType;
import de.steamwar.command.SWCommand;
import de.steamwar.sql.SchematicNode;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.io.IOException;
import java.util.logging.Level;
public class CommandRegion extends SWCommand {
public CommandRegion() {
super("region", "rg");
}
@Register
public void genericCommand(Player player) {
genericHelp(player);
}
@Register(help = true)
public void genericHelp(Player player, String... args) {
player.sendMessage("§8/§eregion undo §8- §7Mache die letzten 20 /testblock oder /reset rückgängig");
player.sendMessage("§8/§eregion redo §8- §7Wiederhole die letzten 20 §8/§7rg undo");
player.sendMessage("§8/§eregion restore §8- §7Setzte die Region zurück, ohne das Gebaute zu löschen");
player.sendMessage("§8/§eregion §8[§7RegionsTyp§8] §8- §7Wähle einen RegionsTyp aus");
player.sendMessage("§8/§eregion §8[§7RegionsTyp§8] §8[§7Extension§8] §8- §7Wähle einen RegionsTyp aus mit oder ohne Extension");
player.sendMessage("§8/§eregion color §8[§7Color§8] §8- §7Ändere die Regions Farbe");
}
@Register("undo")
public void undoCommand(Player p) {
if(!permissionCheck(p)) return;
Region region = Region.getRegion(p.getLocation());
if(checkGlobalRegion(region, p)) return;
if (region.undo()) {
p.sendMessage(BauSystem.PREFIX + "Letzte Aktion rückgangig gemacht");
} else {
p.sendMessage(BauSystem.PREFIX + "§cNichts zum rückgängig machen");
}
}
@Register("redo")
public void redoCommand(Player p) {
if (!permissionCheck(p)) {
return;
}
Region region = Region.getRegion(p.getLocation());
if (checkGlobalRegion(region, p)) {
return;
}
if (region.redo()) {
p.sendMessage(BauSystem.PREFIX + "Letzte Aktion wiederhohlt");
} else {
p.sendMessage(BauSystem.PREFIX + "§cNichts zum wiederhohlen");
}
}
@Register
public void baurahmenCommand(Player p, RegionType regionType) {
CommandSelect.getInstance().baurahmenCommand(p, regionType, RegionExtensionType.NORMAL);
}
@Register
public void baurahmenCommand(Player p, RegionType regionType, RegionExtensionType regionExtensionType) {
CommandSelect.getInstance().baurahmenCommand(p, regionType, regionExtensionType);
}
@Register("restore")
public void genericRestoreCommand(Player p) {
if (!permissionCheck(p)) return;
Region region = Region.getRegion(p.getLocation());
if(checkGlobalRegion(region, p)) return;
if (region == null) return;
try {
region.reset(null, true);
p.sendMessage(BauSystem.PREFIX + "§7Region zurückgesetzt");
} catch (IOException e) {
p.sendMessage(BauSystem.PREFIX + "§cFehler beim Zurücksetzen der Region");
Bukkit.getLogger().log(Level.WARNING, "Failed testblock", e);
}
}
@Register("restore")
public void schematicRestoreCommand(Player p, SchematicNode schem) {
if (!permissionCheck(p)) return;
Region region = Region.getRegion(p.getLocation());
if(checkGlobalRegion(region, p)) return;
if (region == null) return;
try {
region.reset(schem, true);
p.sendMessage(BauSystem.PREFIX + "§7Region zurückgesetzt");
} catch (IOException e) {
p.sendMessage(BauSystem.PREFIX + "§cFehler beim Zurücksetzen der Region");
Bukkit.getLogger().log(Level.WARNING, "Failed reset", e);
}
}
@Register("color")
public void colorCommand(Player p, Color color) {
CommandColor.getInstance().genericColor(p, color);
}
static boolean checkGlobalRegion(Region region, Player p) {
if (GlobalRegion.isGlobalRegion(region)) {
p.sendMessage(BauSystem.PREFIX + "§cDu bist in keiner Region");
return true;
}
return false;
}
private boolean permissionCheck(Player player) {
if (Welt.noPermission(player, Permission.WORLDEDIT)) {
player.sendMessage(BauSystem.PREFIX + "§cDu darfst hier nicht die Region verändern");
return false;
}
return true;
}
}

View File

@ -0,0 +1,91 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.commands;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.Permission;
import de.steamwar.bausystem.world.Welt;
import de.steamwar.bausystem.world.regions.GlobalRegion;
import de.steamwar.bausystem.world.regions.Region;
import de.steamwar.command.SWCommand;
import de.steamwar.sql.SchematicNode;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.io.IOException;
import java.util.logging.Level;
public class CommandReset extends SWCommand {
public CommandReset() {
super("reset");
}
@Register(help = true)
public void genericHelp(Player p, String... args) {
p.sendMessage("§8/§ereset §8- §7Setzte die Region zurück");
p.sendMessage("§8/§ereset §8[§7Schematic§8] §8- §7Setzte die Region mit einer Schematic zurück");
}
@Register
public void genericResetCommand(Player p) {
if (!permissionCheck(p)) return;
Region region = regionCheck(p);
if (region == null) return;
try {
region.reset(null, false);
p.sendMessage(BauSystem.PREFIX + "§7Region zurückgesetzt");
} catch (IOException e) {
p.sendMessage(BauSystem.PREFIX + "§cFehler beim Zurücksetzen der Region");
Bukkit.getLogger().log(Level.WARNING, "Failed testblock", e);
}
}
@Register
public void schematicResetCommand(Player p, SchematicNode schem) {
if (!permissionCheck(p)) return;
Region region = regionCheck(p);
if (region == null) return;
try {
region.reset(schem, false);
p.sendMessage(BauSystem.PREFIX + "§7Region zurückgesetzt");
} catch (IOException e) {
p.sendMessage(BauSystem.PREFIX + "§cFehler beim Zurücksetzen der Region");
Bukkit.getLogger().log(Level.WARNING, "Failed reset", e);
}
}
private boolean permissionCheck(Player player) {
if (Welt.noPermission(player, Permission.WORLD)) {
player.sendMessage(BauSystem.PREFIX + "§cDu darfst hier nicht die Region zurücksetzen");
return false;
}
return true;
}
private Region regionCheck(Player player) {
Region region = Region.getRegion(player.getLocation());
if (region == GlobalRegion.getInstance()) {
player.sendMessage(BauSystem.PREFIX + "§cDu befindest dich derzeit in keiner Region");
return null;
}
return region;
}
}

View File

@ -0,0 +1,94 @@
/*
*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
* /
*/
package de.steamwar.bausystem.commands;
import de.steamwar.bausystem.SWUtils;
import de.steamwar.command.SWCommand;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta;
import java.util.ArrayList;
import java.util.List;
public class CommandScript extends SWCommand {
public CommandScript() {
super("script");
}
public static final ItemStack BOOK = new ItemStack(Material.WRITTEN_BOOK, 1);
static {
List<String> pages = new ArrayList<>();
pages.add("§6Script System§8\n\n- Commands\n- Kommentare\n- Scriptausführung\n- Sleep\n- Variablen\n- Konstanten\n- Abfragen\n- Schleifen\n- \"echo\"\n- \"input\"\n- Arithmetik\n- Logik");
pages.add("§6Commands§8\n\nEin minecraft Befehl wird im Scriptbuch so hingeschrieben. Dabei kann man ein '/' weglassen. Um Befehle zu trennen kommen diese in neue Zeilen.\n\nStatt\n/tnt -> tnt\n//pos1 -> /pos1");
pages.add("§6Kommentare§8\n\nFür ein Kommentar fängt die Zeile mit einem '#' an. Diese Zeilen werden bei dem Ausführen dann ignoriert.\n\nBeispiel:\n§9# TNT an/aus\ntnt");
pages.add("§6Scriptausführung§8\n\nWenn du mit dem Buch in der Hand links klickst wird dieses ausgeführt.");
pages.add("§6Sleep§8\n\nUm Sachen langsamer zu machen kann man ein 'sleep' in sein Script schreiben. Danach kommt eine Zahl mit der Anzahl der GameTicks die zu schlafen sind.\n\nBeispiel:\n§9# 1 Sekunde schlafen\nsleep 20");
pages.add("§6Variablen§8\n\nMit Variablen kann man sich Zahlen speichern. Man definiert diese mit 'var <NAME> <VALUE>'.\n\nBeispiel:\n§9# Setze i zu 0\nvar i 0§8\n\nEs gibt einige spezial values. Dazu zählen");
pages.add("§8'true', 'yes', 'false' und 'no', welche für 1, 1, 0 und 0 stehen.\n\nMan kann eine Variable auch um einen erhöhen oder verkleinern. Hierfür schreibt man statt einer Zahl '++', 'inc' oder '--', 'dec'.\n\nBeispiel:\n§9var i ++");
pages.add("§8Variablen kann man referenzieren\ndurch '<' vor dem Variablennamen und '>' nach diesem. Diese kann man in jedem Befehl verwenden.\n\nBeispiel:\n§9# Stacked um 10\nvar stacks 10\n/stack <stacks>");
pages.add("§8Man kann auch explizit eine globale, locale, oder konstante variable referenzieren, indem 'global.', 'local.' oder 'const.' vor den Namen in die Klammern zu schreiben.");
pages.add("§8Um Variablen über das Script ausführen zu speichern gibt es 'global' und 'unglobal' als Befehle. Der erste speichert eine locale Variable global und das zweite löscht eine globale wieder.");
pages.add("§8Des weiteren kann man Lokale Variablen mit 'unvar' löschen. Nach dem verlassen einer Welt werden alle Globalen Variablen gelöscht. Globale Variablen kann man mit '/scriptvars' einsehen.");
pages.add("§6Konstanten§8\n\nNeben den variablen gibt es noch 5 Konstante Werte, welche nicht mit dem 'var' Befehl verändert werden können.\n\nDiese sind:\n- trace/autotrace\n- tnt\n- freeze\n- fire");
pages.add("§8Des weiteren gibt es 3 weitere Variablen, welche explizit Spieler gebunden sind\n\nDiese sind:\n- x\n- y\n- z");
pages.add("§6Abfragen§8\n\nMit Abfragen kann man nur Gleichheit von 2 Werten überprüft werden. Hierfür verwendet man\n'if <VAL> <VAL>'.\nNach den zwei Werten kann man ein oder 2 Jump-Points schreiben\n'if [...] <JP> (JP)'.");
pages.add("§8Des weiteren kann man überprüfen, ob eine Variable existiert mit 'if <VAL> exists' wonach dann wieder 1 oder 2 Jump-Points sein müssen.");
pages.add("§8Ein Jump-Point ist eine Zeile Script, wohin man springen kann. Dieser wird mit einem '.' am Anfang der Zeile beschrieben und direkt danach der Jump-Point Namen ohne Leerzeichen.\n\nBeispiel:\n§9# Jump-Point X\n.X§8");
pages.add("§8Um zu einem Jump-Point ohne Abfrage zu springen kann man den\n'jump <JP>' Befehl verwenden.");
pages.add("§6Schleifen§8\n\nSchleifen werden mit Jump-Points, if Abfragen und Jumps gebaut.\n\nBeispiel:\n§9var i 0\n.JUMP\nvar i ++\nif i 10 END JUMP\n.END§8");
pages.add("§6\"echo\"§8\n\nDer echo Befehl ist da um Ausgaben zu tätigen. Hier drin kann man sowohl Variablen ausgeben, als auch Farbcodes verwenden. Es wird alles nach dem Befehl ausgegeben.\n\nBeispiel:\n§9echo &eSteam&8war &7war hier!");
pages.add("§6\"input\"§8\n\nDer input Befehl ist eine Aufforderung einer Eingabe des Users. Die Argumente sind eine Variable und ein Text als Nachricht.\n\nBeispiel:\n§9input age &eDein Alter?");
pages.add("§6Arithmetik§8\n\nEs gibt 4 Arithmetische Befehle:\n- add\n- sub\n- mul\n- div\n\nDer erste Parameter ist die Variable welche den ausgerechneten Wert halten soll. Hiernach muss ein");
pages.add("§8Wert oder Variable kommen welcher verrechnet wird. Hierbei wird das erste Argument als ersten Operand genommen.\n\nBeispiel:\n§9var i 2\nvar j 3\nadd i j\necho $i");
pages.add("§8Man kann auch 3 Argumente angeben. Dann wird die arithmetische Operation zwischen den letzten beiden Argumenten berechnet und als Variable des ersten Arguments abgespeichert. \n\nBeispiel auf der nächsten Seite -->");
pages.add("§8Beispiel:\n§9var i 2\nvar j 2\nadd k i j\necho $k");
pages.add("§6Logik§8\n\nEs gibt 3 Vergleichs Befehle:\n- equal\n- less\n- greater\n\nUnd 3 Logik Befehle:\n- and\n- or\n- not");
pages.add("§8Der erste Parameter ist die Variable welche den ausgerechneten Wert halten soll. Hiernach muss ein Wert oder Variable kommen welcher verrechnet wird. Hierbei wird das erste Argument als ersten Operand genommen. Dies gilt nicht für den 'not' Befehl, welcher");
pages.add("§8nur 2 Parameter nimmt. Der erste die Variable und der zweite eine optionale Variable oder ein Wert. Equal vergleicht 2 Werte, less gibt zurück ob der erste kleiner als der zweite Wert ist, greater gibt zurück ob der erste größer als der zweite Wert ist.");
pages.add("§8And vergleicht ob 2 Werte true (1) sind. Or vergleicht ob 1 Wert oder 2 Werte true (1) ist/sind. Not invertiert den Wert von true (1) auf false und anders rum.");
pages.add("§8Beispiel:\n§9var i 1\nvar j 1\n#Ist i und j gleich\nequal k i j\nvar j 0\n#Ist i kleiner j\nless k i j\n#Ist i größer j\ngreater k i j\n#Ist i und j true\nand k i j\n#Beispiel weiter auf nächster Seite");
pages.add("§9#Ist i oder j true\nor k i j\n#Invertiere i\nnot k i");
BookMeta bookMeta = (BookMeta) BOOK.getItemMeta();
bookMeta.setGeneration(BookMeta.Generation.ORIGINAL);
bookMeta.setAuthor("§eSteam§8war");
bookMeta.setTitle("§7Script Buch");
bookMeta.setDisplayName("§7Script Buch");
bookMeta.setPages(pages);
BOOK.setItemMeta(bookMeta);
}
@Register(help = true)
public void genericHelp(Player p, String... args) {
p.sendMessage("§8/§escript §8- §7Gibt das Script Buch");
}
@Register
public void giveCommand(Player p) {
SWUtils.giveItemToPlayer(p, BOOK);
}
}

View File

@ -0,0 +1,120 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.commands;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.world.ScriptListener;
import de.steamwar.command.SWCommand;
import de.steamwar.command.SWCommandUtils;
import de.steamwar.command.TypeMapper;
import org.bukkit.entity.Player;
import java.util.*;
public class CommandScriptVars extends SWCommand {
public CommandScriptVars() {
super("scripvars");
}
@Register(help = true)
public void genericHelp(Player p, String... args) {
p.sendMessage("§8/§escriptvars §8- §7Zähle alle globalen Variablen auf");
p.sendMessage("§8/§escriptvars §8[§7Variable§8] §8- §7Gebe den Wert der Variable zurück");
p.sendMessage("§8/§escriptvars §8[§7Variable§8] §8[§7Value§8] §8- §7Setzte eine Variable auf einen Wert");
p.sendMessage("§8/§escriptvars §8[§7Variable§8] §8<§7remove§8|§7delete§8|§7clear§8> §8- §7Lösche eine Variable");
}
@Register
public void genericCommand(Player p) {
Map<String, Integer> globalVariables = ScriptListener.GLOBAL_VARIABLES.get(p);
if (globalVariables == null) {
p.sendMessage(BauSystem.PREFIX + "§cKeine globalen Variablen definiert");
return;
}
int i = 0;
p.sendMessage(BauSystem.PREFIX + globalVariables.size() + " Variable(n)");
for (Map.Entry<String, Integer> var : globalVariables.entrySet()) {
if (i++ >= 40) break;
p.sendMessage("- " + var.getKey() + "=" + var.getValue());
}
}
@Register
public void removeCommand(Player p, String varName) {
Map<String, Integer> globalVariables = ScriptListener.GLOBAL_VARIABLES.get(p);
if (globalVariables == null) {
p.sendMessage(BauSystem.PREFIX + "§cKeine globalen Variablen definiert");
return;
}
if (!globalVariables.containsKey(varName)) {
p.sendMessage(BauSystem.PREFIX + "§cUnbekannte Variable");
return;
}
p.sendMessage(BauSystem.PREFIX + varName + "=" + globalVariables.get(varName));
}
@Register
public void booleanValueCommand(Player p, String varName, int value) {
ScriptListener.GLOBAL_VARIABLES.computeIfAbsent(p, player -> new HashMap<>()).put(varName, value);
p.sendMessage(BauSystem.PREFIX + varName + " auf " + value + " gesetzt");
}
@Register
public void removeCommand(Player p, String varName, @Mapper(value = "Delete") String remove) {
if (!ScriptListener.GLOBAL_VARIABLES.containsKey(p)) {
p.sendMessage(BauSystem.PREFIX + "§cKeine globalen Variablen definiert");
return;
}
ScriptListener.GLOBAL_VARIABLES.get(p).remove(varName);
p.sendMessage(BauSystem.PREFIX + "Variable " + varName + " gelöscht");
}
@ClassMapper(value = String.class, local = true)
public TypeMapper<String> stringTypeMapper() {
return SWCommandUtils.createMapper(s -> s, (commandSender, s) -> {
if (commandSender instanceof Player) {
Player player = (Player) commandSender;
return new ArrayList<>(ScriptListener.GLOBAL_VARIABLES.getOrDefault(player, new HashMap<>()).keySet());
}
return null;
});
}
@Mapper(value = "Delete", local = true)
public TypeMapper<String> clearStringTypeMapper() {
List<String> tabCompletes = Arrays.asList("delete", "clear", "remove");
return SWCommandUtils.createMapper(s -> {
if (s.equalsIgnoreCase("delete") || s.equalsIgnoreCase("clear") || s.equalsIgnoreCase("remove")) {
return s;
}
return null;
}, s -> tabCompletes);
}
@ClassMapper(value = int.class, local = true)
public TypeMapper<Integer> integerTypeMapper() {
List<String> tabCompletes = Arrays.asList("true", "false", "yes", "no");
return SWCommandUtils.createMapper(s -> {
if (s.equalsIgnoreCase("remove") || s.equalsIgnoreCase("clear") || s.equalsIgnoreCase("delete")) return null;
return ScriptListener.parseValue(s);
}, s -> tabCompletes);
}
}

View File

@ -0,0 +1,124 @@
package de.steamwar.bausystem.commands;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.Permission;
import de.steamwar.bausystem.WorldeditWrapper;
import de.steamwar.bausystem.world.Welt;
import de.steamwar.bausystem.world.regions.*;
import de.steamwar.command.SWCommand;
import lombok.Getter;
import org.bukkit.entity.Player;
public class CommandSelect extends SWCommand {
@Getter
private static CommandSelect instance = null;
public CommandSelect() {
super("select");
}
{
instance = this;
}
@Register(help = true)
public void genericHelp(Player p, String... args) {
p.sendMessage("§8/§eselect §8[§7RegionsTyp§8] §8- §7Wähle einen RegionsTyp aus");
p.sendMessage("§8/§eselect §8[§7RegionsTyp§8] §8[§7Extension§8] §8- §7Wähle einen RegionsTyp aus mit oder ohne Extension");
}
@Register
public void baurahmenCommand(Player p, RegionType regionType) {
if (!permissionCheck(p)) {
return;
}
Region region = Region.getRegion(p.getLocation());
if (GlobalRegion.isGlobalRegion(region)) {
p.sendMessage(BauSystem.PREFIX + "§cDie globale Region kannst du nicht auswählen");
return;
}
if (regionType == RegionType.TESTBLOCK) {
if (!region.hasTestblock()) {
p.sendMessage(BauSystem.PREFIX + "§cDiese Region hat keinen Testblock");
return;
}
setSelection(regionType, RegionExtensionType.NORMAL, region, p);
return;
}
if (regionType == RegionType.BUILD) {
if (!region.hasBuildRegion()) {
p.sendMessage(BauSystem.PREFIX + "§cDiese Region hat keinen BuildArea");
return;
}
setSelection(regionType, RegionExtensionType.NORMAL, region, p);
return;
}
setSelection(regionType, RegionExtensionType.NORMAL, region, p);
}
@Register
public void baurahmenCommand(Player p, RegionType regionType, RegionExtensionType regionExtensionType) {
if (!permissionCheck(p)) {
return;
}
Region region = Region.getRegion(p.getLocation());
if (GlobalRegion.isGlobalRegion(region)) {
p.sendMessage(BauSystem.PREFIX + "§cDie globale Region kannst du nicht auswählen");
return;
}
if (regionType == RegionType.TESTBLOCK) {
if (!region.hasTestblock()) {
p.sendMessage(BauSystem.PREFIX + "§cDiese Region hat keinen Testblock");
return;
}
if (regionExtensionType == RegionExtensionType.EXTENSION && !region.hasExtensionArea(regionType)) {
p.sendMessage(BauSystem.PREFIX + "§cDiese Region hat keine Ausfahrmaße");
return;
}
setSelection(regionType, regionExtensionType, region, p);
return;
}
if (regionType == RegionType.BUILD) {
if (!region.hasBuildRegion()) {
p.sendMessage(BauSystem.PREFIX + "§cDiese Region hat keinen BuildArea");
return;
}
if (regionExtensionType == RegionExtensionType.EXTENSION && !region.hasExtensionArea(regionType)) {
p.sendMessage(BauSystem.PREFIX + "§cDiese Region hat keine Ausfahrmaße");
return;
}
setSelection(regionType, regionExtensionType, region, p);
return;
}
setSelection(regionType, regionExtensionType, region, p);
}
private boolean permissionCheck(Player player) {
if (Welt.noPermission(player, Permission.WORLDEDIT)) {
player.sendMessage(BauSystem.PREFIX + "§cDu darfst hier nicht den Select verwenden");
return false;
}
return true;
}
private void setSelection(RegionType regionType, RegionExtensionType regionExtensionType, Region region, Player p) {
Point minPoint = region.getMinPoint(regionType, regionExtensionType);
Point maxPoint = region.getMaxPoint(regionType, regionExtensionType);
WorldeditWrapper.impl.setSelection(p, minPoint, maxPoint);
p.sendMessage(BauSystem.PREFIX + "WorldEdit auswahl auf " + minPoint.getX() + ", " + minPoint.getY() + ", " + minPoint.getZ() + " und " + maxPoint.getX() + ", " + maxPoint.getY() + ", " + maxPoint.getZ() + " gesetzt");
}
}

View File

@ -0,0 +1,49 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.commands;
import de.steamwar.bausystem.SWUtils;
import de.steamwar.command.SWCommand;
import de.steamwar.inventory.SWItem;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.SkullMeta;
public class CommandSkull extends SWCommand {
public CommandSkull() {
super("skull");
}
@Register(help = true)
public void genericHelp(Player p, String... args) {
p.sendMessage("§8/§eskull §8[§eSpieler§8] §8- §7Gibt einen SpielerKopf");
}
@Register
public void giveCommand(Player p, String skull) {
ItemStack is = SWItem.getPlayerSkull(skull).getItemStack();
SkullMeta sm = (SkullMeta) is.getItemMeta();
assert sm != null;
sm.setDisplayName("§e" + skull + "§8s Kopf");
is.setItemMeta(sm);
SWUtils.giveItemToPlayer(p, is);
}
}

View File

@ -0,0 +1,70 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.commands;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.command.SWCommand;
import de.steamwar.command.SWCommandUtils;
import de.steamwar.command.TypeMapper;
import org.bukkit.entity.Player;
import java.util.Arrays;
import java.util.List;
public class CommandSpeed extends SWCommand {
public CommandSpeed() {
super("speed");
}
@Register(help = true)
public void genericHelp(Player p, String... args) {
p.sendMessage("§8/§espeed §8[§7Geschwindigkeit§8] §8- §7Setzte deine Flug- und Gehgeschwindigkeit");
}
@Register({"default"})
public void defaultCommand(Player p) {
speedCommand(p, 1);
}
@Register
public void speedCommand(Player p, float speed) {
if (speed < 0 || speed > 10) {
p.sendMessage(BauSystem.PREFIX + "§cBitte gib eine Zahl zwischen 0 und 10 an");
return;
}
p.sendMessage("§aGeschwindigkeit wurde auf §6" + speed + " §agesetzt");
p.setFlySpeed(speed / 10);
p.setWalkSpeed((speed >= 9 ? speed : speed + 1) / 10);
}
@ClassMapper(value = float.class, local = true)
public TypeMapper<Float> doubleTypeMapper() {
List<String> tabCompletes = Arrays.asList("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10");
return SWCommandUtils.createMapper(s -> {
try {
return Float.parseFloat(s.replace(',', '.'));
} catch (NumberFormatException e) {
return null;
}
}, s -> tabCompletes);
}
}

View File

@ -0,0 +1,173 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.commands;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.Permission;
import de.steamwar.bausystem.world.regions.Region;
import de.steamwar.bausystem.world.Welt;
import de.steamwar.bausystem.world.regions.RegionExtensionType;
import de.steamwar.bausystem.world.regions.RegionType;
import de.steamwar.command.SWCommand;
import de.steamwar.command.SWCommandUtils;
import de.steamwar.command.TypeMapper;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityExplodeEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CommandTNT extends SWCommand implements Listener {
public enum TNTMode {
ON("§aan"),
ONLY_TB("§7Kein §eBaurahmen"),
OFF("§caus");
private String name;
TNTMode(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public CommandTNT() {
super("tnt");
Bukkit.getPluginManager().registerEvents(this, BauSystem.getPlugin());
}
@Register(help = true)
public void genericHelp(Player p, String... args) {
p.sendMessage("§8/§etnt §8- §7Ändere das TNT verhalten");
p.sendMessage("§8/§etnt §8[§7Mode§8] §8- §7Setzte das TNT verhalten auf einen Modus");
}
@Register
public void toggleCommand(Player p) {
if (!permissionCheck(p)) return;
Region region = Region.getRegion(p.getLocation());
tntToggle(region, null, null);
}
@Register
public void setCommand(Player p, TNTMode tntMode) {
if (!permissionCheck(p)) return;
Region region = Region.getRegion(p.getLocation());
String requestedMessage = null;
switch (tntMode) {
case ON:
requestedMessage = getEnableMessage();
break;
case OFF:
requestedMessage = getDisableMessage();
break;
case ONLY_TB:
requestedMessage = getTestblockEnableMessage();
break;
}
tntToggle(region, tntMode, requestedMessage);
}
private boolean permissionCheck(Player p) {
if (Welt.noPermission(p, Permission.WORLD)) {
p.sendMessage(BauSystem.PREFIX + "§cDu darfst hier nicht TNT-Schaden (de-)aktivieren");
return false;
}
return true;
}
@ClassMapper(value = TNTMode.class, local = true)
public TypeMapper<TNTMode> tntModeTypeMapper() {
Map<String, TNTMode> tntModeMap = new HashMap<>();
tntModeMap.put("an", TNTMode.ON);
tntModeMap.put("on", TNTMode.ON);
tntModeMap.put("aus", TNTMode.OFF);
tntModeMap.put("off", TNTMode.OFF);
if (Region.buildAreaEnabled()) {
tntModeMap.put("testblock", TNTMode.ONLY_TB);
tntModeMap.put("tb", TNTMode.ONLY_TB);
}
List<String> tabCompletes = new ArrayList<>(tntModeMap.keySet());
return SWCommandUtils.createMapper(s -> tntModeMap.getOrDefault(s, null), s -> tabCompletes);
}
private String getEnableMessage() {
return "§aTNT-Schaden aktiviert";
}
private String getDisableMessage() {
return "§cTNT-Schaden deaktiviert";
}
private String getTestblockEnableMessage() {
return "§aTNT-Schaden außerhalb Baurahmen aktiviert";
}
private void tntToggle(Region region, TNTMode requestedMode, String requestedMessage) {
if (requestedMode != null && region.hasTestblock()) {
region.setTntMode(requestedMode);
RegionUtils.actionBar(region, requestedMessage);
return;
}
switch (region.getTntMode()) {
case ON:
case ONLY_TB:
region.setTntMode(TNTMode.OFF);
RegionUtils.actionBar(region, getDisableMessage());
break;
case OFF:
if (Region.buildAreaEnabled() && region.hasTestblock()) {
region.setTntMode(TNTMode.ONLY_TB);
RegionUtils.actionBar(region, getTestblockEnableMessage());
} else {
region.setTntMode(TNTMode.ON);
RegionUtils.actionBar(region, getEnableMessage());
}
break;
}
}
@EventHandler
public void onExplode(EntityExplodeEvent event) {
event.blockList().removeIf(block -> {
Region region = Region.getRegion(block.getLocation());
if (region.getTntMode() == TNTMode.ON) return false;
if (region.hasBuildRegion() && region.inRegion(block.getLocation(), RegionType.BUILD, RegionExtensionType.NORMAL)) {
RegionUtils.actionBar(region, "§cEine Explosion hätte Blöcke im Baubereich zerstört");
return true;
}
if (region.hasBuildRegion() && region.inRegion(block.getLocation(), RegionType.BUILD, RegionExtensionType.EXTENSION)) {
RegionUtils.actionBar(region, "§cEine Explosion hätte Blöcke im Ausfahrbereich zerstört");
return true;
}
return region.getTntMode() == TNTMode.OFF;
});
}
}

View File

@ -0,0 +1,176 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.commands;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.CraftbukkitWrapper;
import de.steamwar.bausystem.Permission;
import de.steamwar.bausystem.world.TPSUtils;
import de.steamwar.bausystem.world.Welt;
import de.steamwar.command.SWCommand;
import de.steamwar.command.SWCommandUtils;
import de.steamwar.command.TypeMapper;
import net.md_5.bungee.api.ChatMessageType;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitTask;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CommandTPSLimiter extends SWCommand {
private static CommandTPSLimiter instance = null;
{
instance = this;
}
private static final World WORLD = Bukkit.getWorlds().get(0);
private static double currentTPSLimit = 20;
private long lastTime = System.nanoTime();
private long currentTime = System.nanoTime();
private double delay = 0;
private int loops = 0;
private long sleepDelay = 0;
private BukkitTask tpsLimiter = null;
private List<String> tabCompletions = new ArrayList<>(Arrays.asList("0,5", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20"));
public CommandTPSLimiter() {
super("tpslimit");
if (TPSUtils.isWarpAllowed()) {
for (int i = 20; i <= 60; i += 5) {
tabCompletions.add(i + "");
}
}
}
@Register(help = true)
public void genericHelp(Player p, String... args) {
p.sendMessage(BauSystem.PREFIX + "Jetziges TPS limit: " + currentTPSLimit);
p.sendMessage("§8/§etpslimit §8[§7TPS§8|§edefault§8] §8- §7Setzte die TPS auf dem Bau");
}
@Register({"default"})
public void defaultCommand(Player p) {
if (!permissionCheck(p)) return;
currentTPSLimit = 20;
sendNewTPSLimitMessage();
tpsLimiter();
}
@Register
public void valueCommand(Player p, double tpsLimitDouble) {
if (!permissionCheck(p)) return;
if (tpsLimitDouble < 0.5 || tpsLimitDouble > (TPSUtils.isWarpAllowed() ? 60 : 20)) {
sendInvalidArgumentMessage(p);
return;
}
currentTPSLimit = tpsLimitDouble;
sendNewTPSLimitMessage();
tpsLimiter();
}
@ClassMapper(value = double.class, local = true)
public TypeMapper<Double> doubleTypeMapper() {
return SWCommandUtils.createMapper(s -> {
try {
return Double.parseDouble(s.replace(',', '.'));
} catch (NumberFormatException e) {
return 0D;
}
}, s -> tabCompletions);
}
private boolean permissionCheck(Player player) {
if (Welt.noPermission(player, Permission.WORLD)) {
player.sendMessage(BauSystem.PREFIX + "§cDu darfst hier nicht den TPS-Limiter nutzen");
return false;
}
return true;
}
private void sendNewTPSLimitMessage() {
Bukkit.getOnlinePlayers().forEach(p -> p.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText("§eTPS limit auf " + currentTPSLimit + " gesetzt.")));
}
private void sendInvalidArgumentMessage(Player player) {
player.sendMessage(BauSystem.PREFIX + "§cNur Zahlen zwischen 0,5 und " + (TPSUtils.isWarpAllowed() ? 60 : 20) + ", und 'default' erlaubt.");
}
private void tpsLimiter() {
delay = 20 / currentTPSLimit;
loops = (int) Math.ceil(delay);
sleepDelay = (long) (50 * delay) / loops;
TPSUtils.setTPS(currentTPSLimit);
if (currentTPSLimit >= 20) {
if (tpsLimiter == null) return;
tpsLimiter.cancel();
tpsLimiter = null;
} else {
if (tpsLimiter != null) return;
tpsLimiter = Bukkit.getScheduler().runTaskTimer(BauSystem.getPlugin(), () -> {
CraftbukkitWrapper.impl.createTickCache(WORLD);
for (int i = 0; i < loops; i++) {
sleepUntilNextTick(sleepDelay);
CraftbukkitWrapper.impl.sendTickPackets();
}
}, 0, 1);
}
}
private void sleepUntilNextTick(long neededDelta) {
lastTime = currentTime;
currentTime = System.nanoTime();
long timeDelta = (currentTime - lastTime) / 1000000;
if (neededDelta - timeDelta < 0) return;
try {
Thread.sleep(neededDelta - timeDelta);
currentTime = System.nanoTime();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static double getCurrentTPSLimit() {
return (double) Math.round(currentTPSLimit * 10.0D) / 10.0D;
}
public static void setTPS(double d) {
if (d < 0.5) d = 0.5;
if (d > (TPSUtils.isWarpAllowed() ? 60 : 20)) d = (TPSUtils.isWarpAllowed() ? 60 : 20);
if (instance != null) {
currentTPSLimit = d;
instance.tpsLimiter();
}
}
}

View File

@ -0,0 +1,46 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.commands;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.command.SWCommand;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerTeleportEvent;
public class CommandTeleport extends SWCommand {
public CommandTeleport() {
super("teleport", "tp");
}
@Register(help = true)
public void genericHelp(Player p, String... args) {
p.sendMessage("§8/§etp §8[§7Player§8] §8- §7Teleportiere dich zu einem Spieler");
}
@Register
public void genericCommand(Player p, Player target) {
if (p.getUniqueId().equals(target.getUniqueId())) {
p.sendMessage(BauSystem.PREFIX + "§cSei eins mit dir selbst!");
return;
}
p.teleport(target, PlayerTeleportEvent.TeleportCause.COMMAND);
}
}

View File

@ -0,0 +1,128 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.commands;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.Permission;
import de.steamwar.bausystem.tracer.show.ShowModeParameterType;
import de.steamwar.bausystem.world.regions.Region;
import de.steamwar.bausystem.world.Welt;
import de.steamwar.bausystem.world.regions.RegionExtensionType;
import de.steamwar.command.SWCommand;
import de.steamwar.command.SWCommandUtils;
import de.steamwar.command.TypeMapper;
import de.steamwar.sql.SchematicNode;
import de.steamwar.sql.SteamwarUser;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
public class CommandTestblock extends SWCommand {
public CommandTestblock() {
super("testblock", "tb");
}
@Register(help = true)
public void genericHelp(Player p, String... args) {
p.sendMessage("§8/§etestblock §8- §7Setzte den Testblock zurück");
p.sendMessage("§8/§etestblock §8[§7Schematic§8] §8- §7Setzte den Testblock mit einer Schematic zurück");
}
@Register
public void genericTestblockCommand(Player p) {
genericTestblockCommand(p, RegionExtensionType.NORMAL);
}
@Register
public void genericTestblockCommand(Player p, RegionExtensionType regionExtensionType) {
if (!permissionCheck(p)) return;
Region region = regionCheck(p);
if (region == null) return;
try {
region.resetTestblock(null, regionExtensionType == RegionExtensionType.EXTENSION);
p.sendMessage(BauSystem.PREFIX + "§7Testblock zurückgesetzt");
} catch (IOException e) {
p.sendMessage(BauSystem.PREFIX + "§cFehler beim Zurücksetzen des Testblocks");
Bukkit.getLogger().log(Level.WARNING, "Failed testblock", e);
}
}
@Register
public void schematicTestblockCommand(Player p, SchematicNode schem) {
schematicTestblockCommand(p, schem, RegionExtensionType.NORMAL);
}
@Register
public void schematicTestblockCommand(Player p, RegionExtensionType regionExtensionType, SchematicNode schem) {
schematicTestblockCommand(p, schem, regionExtensionType);
}
@Register
public void schematicTestblockCommand(Player p, SchematicNode schem, RegionExtensionType regionExtensionType) {
if (!permissionCheck(p)) return;
Region region = regionCheck(p);
if (region == null) return;
try {
region.resetTestblock(schem, regionExtensionType == RegionExtensionType.EXTENSION);
p.sendMessage(BauSystem.PREFIX + "§7Testblock zurückgesetzt");
} catch (IOException e) {
p.sendMessage(BauSystem.PREFIX + "§cFehler beim Zurücksetzen des Testblocks");
Bukkit.getLogger().log(Level.WARNING, "Failed testblock", e);
}
}
@ClassMapper(value = RegionExtensionType.class, local = true)
private TypeMapper<RegionExtensionType> regionExtensionTypeTypeMapper() {
Map<String, RegionExtensionType> showModeParameterTypesMap = new HashMap<>();
showModeParameterTypesMap.put("-normal", RegionExtensionType.NORMAL);
showModeParameterTypesMap.put("-n", RegionExtensionType.NORMAL);
showModeParameterTypesMap.put("-extension", RegionExtensionType.EXTENSION);
showModeParameterTypesMap.put("-e", RegionExtensionType.EXTENSION);
List<String> tabCompletes = new ArrayList<>(showModeParameterTypesMap.keySet());
return SWCommandUtils.createMapper(s -> showModeParameterTypesMap.getOrDefault(s, null), s -> tabCompletes);
}
private boolean permissionCheck(Player player) {
if (Welt.noPermission(player, Permission.WORLDEDIT)) {
player.sendMessage(BauSystem.PREFIX + "§cDu darfst hier nicht den Testblock zurücksetzen");
return false;
}
return true;
}
private Region regionCheck(Player player) {
Region region = Region.getRegion(player.getLocation());
if (!region.hasTestblock()) {
player.sendMessage(BauSystem.PREFIX + "§cDu befindest dich derzeit in keiner Region");
return null;
}
return region;
}
}

View File

@ -0,0 +1,99 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.commands;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.Permission;
import de.steamwar.bausystem.world.Welt;
import de.steamwar.command.SWCommand;
import de.steamwar.command.SWCommandUtils;
import de.steamwar.command.TypeMapper;
import java.util.Arrays;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
public class CommandTime extends SWCommand {
private static List<String> tabCompletions = Arrays.asList("0", "6000", "12000", "18000");
public CommandTime() {
super("time");
}
@Register(help = true)
public void genericHelp(Player p, String... args) {
p.sendMessage("§8/§etime §8<§7Zeit 0=Morgen§8, §76000=Mittag§8, §718000=Mitternacht§8> §8- §7Setzt die Zeit auf dem Bau");
}
@Register
public void genericCommand(Player p, int time) {
if (Welt.noPermission(p, Permission.WORLD)) {
p.sendMessage(BauSystem.PREFIX + "§cDu darfst hier nicht die Zeit ändern");
return;
}
if (time < 0 || time > 24000) {
p.sendMessage(BauSystem.PREFIX + "§cBitte gib eine Zahl zwischen 0 und 24000 an");
return;
}
Bukkit.getWorlds().get(0).setTime(time);
}
@Register
public void genericCommand(Player p, Time time) {
if (Welt.noPermission(p, Permission.WORLD)) {
p.sendMessage(BauSystem.PREFIX + "§cDu darfst hier nicht die Zeit ändern");
return;
}
Bukkit.getWorlds().get(0).setTime(time.getValue());
}
@ClassMapper(value = int.class, local = true)
public TypeMapper<Integer> doubleTypeMapper() {
return SWCommandUtils.createMapper(s -> {
try {
return Integer.parseInt(s);
} catch (NumberFormatException e) {
return 0;
}
}, s -> tabCompletions);
}
public enum Time {
NIGHT(18000),
DAY(6000),
DAWN(0),
SUNSET(12000),
NACHT(18000),
TAG(6000),
MORGEN(0),
ABEND(12000);
private int value;
private Time(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
}

View File

@ -0,0 +1,132 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.commands;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.Permission;
import de.steamwar.bausystem.gui.GuiTraceShow;
import de.steamwar.bausystem.tracer.record.RecordStateMachine;
import de.steamwar.bausystem.tracer.show.ShowModeParameter;
import de.steamwar.bausystem.tracer.show.ShowModeParameterType;
import de.steamwar.bausystem.tracer.show.StoredRecords;
import de.steamwar.bausystem.tracer.show.TraceShowManager;
import de.steamwar.bausystem.tracer.show.mode.EntityShowMode;
import de.steamwar.bausystem.world.Welt;
import de.steamwar.command.SWCommand;
import org.bukkit.entity.Player;
public class CommandTrace extends SWCommand {
public CommandTrace() {
super("trace");
}
@Register(help = true)
public void genericHelp(Player p, String... args) {
p.sendMessage("§8/§etrace start §8- §7Startet die Aufnahme aller TNT-Positionen");
p.sendMessage("§8/§etrace stop §8- §7Stoppt den TNT-Tracer");
p.sendMessage("§8/§etrace toggleauto §8- §7Automatischer Aufnahmenstart");
p.sendMessage("§8/§etrace show gui §8- §7Zeigt die Trace show gui");
p.sendMessage("§8/§etrace show §8<§e-water§8|§e-interpolate-xz§8|§e-interpolate-y§8> §8- §7Zeigt alle TNT-Positionen");
p.sendMessage("§8/§etrace hide §8- §7Versteckt alle TNT-Positionen");
p.sendMessage("§8/§etrace delete §8- §7Löscht alle TNT-Positionen");
// p.sendMessage("§8/§etrace list §8<§7FRAME-ID§8> §8- §7Listet alle TNT auf");
// p.sendMessage("§8/§etrace gui §8- §7Zeigt die Trace Oberfläche an");
// p.sendMessage("§7Optionale Parameter mit §8<>§7, Benötigte Parameter mit §8[]");
}
@Register({"start"})
public void startCommand(Player p) {
if (!permissionCheck(p)) return;
RecordStateMachine.commandStart();
p.sendMessage(BauSystem.PREFIX + "§aTNT-Tracer gestartet");
}
@Register({"stop"})
public void stopCommand(Player p) {
if (!permissionCheck(p)) return;
RecordStateMachine.commandStop();
p.sendMessage(BauSystem.PREFIX + "§cTNT-Tracer gestoppt");
}
@Register({"toggleauto"})
public void toggleAutoCommand(Player p) {
autoCommand(p);
}
@Register({"auto"})
public void autoCommand(Player p) {
if (!permissionCheck(p)) return;
RecordStateMachine.commandAuto();
p.sendMessage(BauSystem.PREFIX + RecordStateMachine.getRecordStatus().getAutoMessage());
}
@Register({"clear"})
public void clearCommand(Player p) {
deleteCommand(p);
}
@Register({"delete"})
public void deleteCommand(Player p) {
if (!permissionCheck(p)) return;
StoredRecords.clear();
p.sendMessage(BauSystem.PREFIX + "§cAlle TNT-Positionen gelöscht");
}
@Register({"show"})
public void showCommand(Player p) {
if (!permissionCheck(p)) return;
TraceShowManager.show(p, new EntityShowMode(p, new ShowModeParameter()));
p.sendMessage(BauSystem.PREFIX + "§aAlle TNT-Positionen angezeigt");
}
@Register({"show"})
public void showCommand(Player p, ShowModeParameterType... showModeParameterTypes) {
if (!permissionCheck(p)) return;
ShowModeParameter showModeParameter = new ShowModeParameter();
for (ShowModeParameterType showModeParameterType : showModeParameterTypes) {
showModeParameterType.getShowModeParameterConsumer().accept(showModeParameter);
}
TraceShowManager.show(p, new EntityShowMode(p, showModeParameter));
p.sendMessage(BauSystem.PREFIX + "§aAlle TNT-Positionen angezeigt");
}
@Register({"show", "gui"})
public void showGuiCommand(Player p) {
if (!permissionCheck(p)) return;
GuiTraceShow.openGui(p);
}
@Register({"hide"})
public void hideCommand(Player p) {
if (!permissionCheck(p)) return;
TraceShowManager.hide(p);
p.sendMessage(BauSystem.PREFIX + "§cAlle TNT-Positionen ausgeblendet");
}
private boolean permissionCheck(Player player) {
if (Welt.noPermission(player, Permission.WORLD)) {
player.sendMessage(BauSystem.PREFIX + "§cDu darfst hier nicht den TNT-Tracer nutzen");
return false;
}
return true;
}
}

View File

@ -0,0 +1,45 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.commands;
import de.steamwar.command.SWCommand;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerTeleportEvent;
public class CommandWorldSpawn extends SWCommand {
private World world = Bukkit.getWorlds().get(0);
public CommandWorldSpawn() {
super("worldspawn");
}
@Register(help = true)
public void genericHelp(Player p, String... args) {
p.sendMessage("§8/§eworldspawn §8- §7Teleportiere dich zum Spawn");
}
@Register
public void genericCommand(Player p) {
p.teleport(world.getSpawnLocation(), PlayerTeleportEvent.TeleportCause.COMMAND);
}
}

View File

@ -0,0 +1,42 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.commands;
import de.steamwar.bausystem.world.regions.GlobalRegion;
import de.steamwar.bausystem.world.regions.Region;
import de.steamwar.bausystem.world.regions.RegionExtensionType;
import de.steamwar.bausystem.world.regions.RegionType;
import lombok.experimental.UtilityClass;
import net.md_5.bungee.api.ChatMessageType;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Bukkit;
@UtilityClass
public class RegionUtils {
public static void actionBar(Region region, String s) {
if (GlobalRegion.isGlobalRegion(region)) {
Bukkit.getOnlinePlayers().forEach(player -> player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(s)));
} else {
Bukkit.getOnlinePlayers().stream().filter(player -> region.inRegion(player.getLocation(), RegionType.NORMAL, RegionExtensionType.NORMAL)).forEach(player -> player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(s)));
}
}
}

View File

@ -0,0 +1,133 @@
/*
*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
* /
*/
package de.steamwar.bausystem.gui;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.FlatteningWrapper;
import de.steamwar.bausystem.tracer.show.ShowModeParameter;
import de.steamwar.bausystem.tracer.show.TraceShowManager;
import de.steamwar.bausystem.tracer.show.mode.EntityShowMode;
import de.steamwar.inventory.SWInventory;
import de.steamwar.inventory.SWItem;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class GuiTraceShow {
private static final Map<Player, ShowModeParameter> ShowModeParameterMap = new HashMap<>();
private GuiTraceShow() {
}
public static void openGui(Player player) {
ShowModeParameter playerShowMode = new ShowModeParameter();
playerShowMode.setInterpolate_Y(false);
playerShowMode.setInterpolate_XZ(false);
ShowModeParameterMap.put(player, playerShowMode);
SWInventory swInventory = new SWInventory(player, 9, "Trace Show GUI");
swInventory.addCloseCallback(clickType -> ShowModeParameterMap.remove(player));
setActiveShow(player, swInventory);
SWItem water = new SWItem(Material.TNT, "§eWasser §7Positionen", Arrays.asList("§7Zeigt alles TNT, welches", "§7im Wasser explodiert ist."), false, clickType -> {
});
swInventory.setItem(5, water);
swInventory.setCallback(5, clickType -> toggleHideTNTinWaterExploded(player, swInventory, water));
SWItem interpolateY = new SWItem(Material.QUARTZ_STAIRS, "§eInterpolation §7Y-Achse", Arrays.asList("§7Zeigt die Interpolation", "§7auf der Y-Achse."), false, clickType -> {
});
swInventory.setItem(6, interpolateY);
swInventory.setCallback(6, clickType -> toggleInterpolateYPosition(player, swInventory, interpolateY));
Material xzMaterial = FlatteningWrapper.impl.getTraceXZMaterial();
SWItem interpolateXZ = new SWItem(xzMaterial, (byte) 7, "§eInterpolation §7XZ-Achse", Arrays.asList("§7Zeigt die Interpolation", "§7auf der XZ-Achse."), false, clickType -> {
});
swInventory.setItem(7, interpolateXZ);
swInventory.setCallback(7, clickType -> toggleInterpolateXZPosition(player, swInventory, interpolateXZ));
// Water Bucket (-water)
// TNT (-water-exploded)
// Quartz_Stair (-interpolate-y)
// Quartz_Slab (-interpolate-xz)
swInventory.open();
}
private static void setActiveShow(Player player, SWInventory swInventory) {
if (TraceShowManager.hasActiveShow(player)) {
Material showMaterial = FlatteningWrapper.impl.getTraceShowMaterial();
SWItem shown = new SWItem(showMaterial, (byte) 5, "§aTraces angezeigt", new ArrayList<>(), false, clickType -> {
TraceShowManager.hide(player);
player.sendMessage(BauSystem.PREFIX + "§cAlle TNT-Positionen ausgeblendet");
setActiveShow(player, swInventory);
});
swInventory.setItem(1, shown);
} else {
Material hideMaterial = FlatteningWrapper.impl.getTraceHideMaterial();
SWItem hidden = new SWItem(hideMaterial, (byte) 14, "§cTraces ausgeblendet", new ArrayList<>(), false, clickType -> {
show(player);
player.sendMessage(BauSystem.PREFIX + "§aAlle TNT-Positionen angezeigt");
setActiveShow(player, swInventory);
});
swInventory.setItem(1, hidden);
}
}
private static void toggleHideTNTinWaterExploded(Player player, SWInventory swInventory, SWItem swItem) {
ShowModeParameter showModeParameter = ShowModeParameterMap.get(player);
showModeParameter.setWater(!showModeParameter.isWater());
show(player);
swItem.setEnchanted(showModeParameter.isWater());
swInventory.setItem(5, swItem);
swInventory.setCallback(5, clickType -> toggleHideTNTinWaterExploded(player, swInventory, swItem));
}
private static void toggleInterpolateYPosition(Player player, SWInventory swInventory, SWItem swItem) {
ShowModeParameter showModeParameter = ShowModeParameterMap.get(player);
showModeParameter.setInterpolate_Y(!showModeParameter.isInterpolate_Y());
show(player);
swItem.setEnchanted(showModeParameter.isInterpolate_Y());
swInventory.setItem(6, swItem);
swInventory.setCallback(6, clickType -> toggleInterpolateYPosition(player, swInventory, swItem));
}
private static void toggleInterpolateXZPosition(Player player, SWInventory swInventory, SWItem swItem) {
ShowModeParameter showModeParameter = ShowModeParameterMap.get(player);
showModeParameter.setInterpolate_XZ(!showModeParameter.isInterpolate_XZ());
show(player);
swItem.setEnchanted(showModeParameter.isInterpolate_XZ());
swInventory.setItem(7, swItem);
swInventory.setCallback(7, clickType -> toggleInterpolateXZPosition(player, swInventory, swItem));
}
private static void show(Player player) {
TraceShowManager.show(player, new EntityShowMode(player, ShowModeParameterMap.get(player)));
}
}

View File

@ -0,0 +1,34 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.tracer;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
public interface AbstractTraceEntity {
void display(Player player, boolean exploded);
boolean hide(Player player, boolean always);
int getId();
Entity getBukkitEntity();
}

View File

@ -0,0 +1,65 @@
/*
*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
* /
*/
package de.steamwar.bausystem.tracer;
import org.bukkit.util.Vector;
import java.util.Objects;
public class RoundedTNTPosition {
private static final int factor = 10;
private int x;
private int y;
private int z;
public RoundedTNTPosition(TNTPosition tntPosition) {
this(tntPosition.getLocation().getX(), tntPosition.getLocation().getY(), tntPosition.getLocation().getZ());
}
public RoundedTNTPosition(Vector vector) {
this(vector.getX(), vector.getY(), vector.getZ());
}
public RoundedTNTPosition(double x, double y, double z) {
this.x = (int) (x * factor);
this.y = (int) (y * factor);
this.z = (int) (z * factor);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof RoundedTNTPosition)) return false;
RoundedTNTPosition that = (RoundedTNTPosition) o;
return x == that.x &&
y == that.y &&
z == that.z;
}
@Override
public int hashCode() {
return Objects.hash(x, y, z);
}
}

View File

@ -0,0 +1,63 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.tracer;
import de.steamwar.bausystem.tracer.show.Record;
import org.bukkit.entity.Entity;
import org.bukkit.util.Vector;
public class TNTPosition {
private final Record.TNTRecord record;
private final Vector location;
private final Vector previousLocation;
private final boolean exploded;
public TNTPosition(Record.TNTRecord record, Entity entity, Vector previousLocation, boolean exploded) {
this.location = entity.getLocation().toVector();
this.record = record;
this.previousLocation = previousLocation;
this.exploded = exploded;
}
public Vector getLocation() {
return location;
}
public Vector getPreviousLocation() {
return previousLocation;
}
public boolean isExploded() {
return exploded;
}
public Record.TNTRecord getRecord() {
return record;
}
@Override
public String toString() {
return "Position{" +
"location=" + location +
'}';
}
}

View File

@ -0,0 +1,94 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.tracer.record;
public class RecordStateMachine {
private RecordStateMachine() {
}
private static final TraceAutoHandler autoHandler = new TraceAutoHandler();
private static RecordStatus recordStatus = RecordStatus.IDLE;
private static Recorder recorder = null;
public static void commandStart() {
autoHandler.disable();
recordStart();
recordStatus = RecordStatus.RECORD;
}
public static void commandStop() {
autoHandler.disable();
recordStop();
recordStatus = RecordStatus.IDLE;
}
public static void commandAuto() {
if (recordStatus.isTracing())
return;
if (recordStatus == RecordStatus.IDLE_AUTO) {
recordStatus = RecordStatus.IDLE;
autoHandler.disable();
} else {
recordStatus = RecordStatus.IDLE_AUTO;
autoHandler.enable();
}
}
static void autoRecord() {
recordStart();
recordStatus = RecordStatus.RECORD_AUTO;
}
static void autoIdle() {
recordStop();
recordStatus = RecordStatus.IDLE_AUTO;
}
private static void recordStart() {
if (recordStatus.isTracing()) return;
recorder = new Recorder();
}
private static void recordStop() {
if (!recordStatus.isTracing()) return;
recorder.stopRecording();
}
public static RecordStatus getRecordStatus() {
return recordStatus;
}
public static int size() {
if (recorder == null) return 0;
return recorder.size();
}
public static long getStartTime() {
if (recorder == null) return 0;
return recorder.getStartTime();
}
public static void postClear() {
if (recorder == null) return;
recorder.postClear();
}
}

View File

@ -0,0 +1,55 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.tracer.record;
public enum RecordStatus {
RECORD("§aan", true, "§cTNT-Tracer muss gestoppt werden"),
RECORD_AUTO("§aan", true, "§cTNT-Tracer darf nicht aufnehmen"),
IDLE("§caus", false, "§cAuto-Tracer gestoppt"),
IDLE_AUTO("§eauto", false, "§aAuto-Tracer gestartet");
String name;
boolean tracing;
String autoMessage;
RecordStatus(String value, boolean tracing, String autoMessage) {
this.name = value;
this.tracing = tracing;
this.autoMessage = autoMessage;
}
public String getName() {
return name;
}
public boolean isTracing() {
return tracing;
}
public boolean isAutoTrace() {
return this == RECORD_AUTO || this == IDLE_AUTO;
}
public String getAutoMessage() {
return autoMessage;
}
}

View File

@ -0,0 +1,96 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.tracer.record;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.tracer.show.Record;
import de.steamwar.bausystem.tracer.show.StoredRecords;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.event.EventHandler;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.scheduler.BukkitTask;
import java.util.HashMap;
import java.util.Map;
public class Recorder implements Listener {
private static final World world = Bukkit.getWorlds().get(0);
private final Map<TNTPrimed, Record.TNTRecord> recordMap = new HashMap<>();
private final BukkitTask task;
private final Record record;
Recorder() {
Bukkit.getPluginManager().registerEvents(this, BauSystem.getPlugin());
task = Bukkit.getScheduler().runTaskTimer(BauSystem.getPlugin(), this::run, 1, 1);
record = new Record();
// To trace TNT initial positions with AutoTracer
run();
}
void stopRecording() {
HandlerList.unregisterAll(this);
task.cancel();
}
int size() {
return record.size();
}
long getStartTime() {
return record.getStartTime();
}
void postClear() {
record.clear();
recordMap.clear();
StoredRecords.add(record);
}
private void run() {
world.getEntitiesByClass(TNTPrimed.class).forEach(tntPrimed -> get(tntPrimed).add(tntPrimed));
}
@EventHandler
public void onEntityExplode(EntityExplodeEvent event) {
if (!(event.getEntity() instanceof TNTPrimed))
return;
TNTPrimed tntPrimed = (TNTPrimed) event.getEntity();
get(tntPrimed).explode(tntPrimed);
recordMap.remove(tntPrimed);
}
private Record.TNTRecord get(TNTPrimed tntPrimed) {
Record.TNTRecord tntRecord = recordMap.get(tntPrimed);
if (tntRecord != null)
return tntRecord;
tntRecord = this.record.spawn();
recordMap.put(tntPrimed, tntRecord);
return tntRecord;
}
}

View File

@ -0,0 +1,70 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.tracer.record;
import de.steamwar.bausystem.BauSystem;
import org.bukkit.Bukkit;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.event.EventHandler;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.scheduler.BukkitTask;
public class TraceAutoHandler implements Listener {
/* This listener handles the en- and disabling of the Tracer in AUTO mode */
private BukkitTask task;
private int lastExplosion = 0; // Time since the last explosion in ticks
public void enable() {
Bukkit.getPluginManager().registerEvents(this, BauSystem.getPlugin());
}
public void disable() {
HandlerList.unregisterAll(this);
if (task != null) {
task.cancel();
task = null;
}
}
@EventHandler
public void onEntityExplode(EntityExplodeEvent event) {
if (!(event.getEntity() instanceof TNTPrimed))
return;
lastExplosion = 0;
if (task == null) {
RecordStateMachine.autoRecord();
task = Bukkit.getScheduler().runTaskTimer(BauSystem.getPlugin(), this::run, 1, 1);
}
}
private void run() {
lastExplosion++;
if (lastExplosion > 80) {
RecordStateMachine.autoIdle();
task.cancel();
task = null;
}
}
}

View File

@ -0,0 +1,94 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.tracer.show;
import de.steamwar.bausystem.tracer.TNTPosition;
import org.bukkit.entity.TNTPrimed;
import java.util.ArrayList;
import java.util.List;
public class Record {
private final long startTime;
private final List<TNTRecord> tnt = new ArrayList<>();
public int size() {
return tnt.size();
}
public long getStartTime() {
return startTime;
}
public void showAll(ShowMode mode) {
for (TNTRecord record : tnt)
record.showAll(mode);
}
/* The following methods should only be called by a recorder */
public Record() {
startTime = System.currentTimeMillis();
StoredRecords.add(this);
}
public TNTRecord spawn() {
TNTRecord record = new TNTRecord();
tnt.add(record);
return record;
}
public void clear() {
tnt.clear();
}
public static class TNTRecord {
private final List<TNTPosition> positions = new ArrayList<>(41);
public void showAll(ShowMode mode) {
for (TNTPosition position : positions)
mode.show(position);
}
/* The following methods should only be called by a recorder */
public void add(TNTPrimed tntPrimed) {
add(tntPrimed, false);
}
private void add(TNTPrimed tntPrimed, boolean exploded) {
TNTPosition position;
if (positions.isEmpty()) {
position = new TNTPosition(this, tntPrimed, null, exploded);
} else {
position = new TNTPosition(this, tntPrimed, positions.get(positions.size() - 1).getLocation(), exploded);
}
positions.add(position);
TraceShowManager.show(position);
}
public void explode(TNTPrimed tntPrimed) {
add(tntPrimed, true);
}
public List<TNTPosition> getPositions() {
return positions;
}
}
}

View File

@ -0,0 +1,28 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.tracer.show;
import de.steamwar.bausystem.tracer.TNTPosition;
public interface ShowMode {
void show(TNTPosition position);
void hide();
}

View File

@ -0,0 +1,57 @@
/*
*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
* /
*/
package de.steamwar.bausystem.tracer.show;
public class ShowModeParameter {
private boolean water = false;
private boolean interpolate_Y = false;
private boolean interpolate_XZ = false;
public ShowModeParameter() {
}
public boolean isWater() {
return water;
}
public boolean isInterpolate_Y() {
return interpolate_Y;
}
public boolean isInterpolate_XZ() {
return interpolate_XZ;
}
public void setWater(boolean water) {
this.water = water;
}
public void setInterpolate_Y(boolean interpolate_Y) {
this.interpolate_Y = interpolate_Y;
}
public void setInterpolate_XZ(boolean interpolate_XZ) {
this.interpolate_XZ = interpolate_XZ;
}
}

View File

@ -0,0 +1,44 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.tracer.show;
import java.util.function.Consumer;
public enum ShowModeParameterType {
WATER(showModeParameter -> showModeParameter.setWater(true)),
INTERPOLATE_Y(showModeParameter -> showModeParameter.setInterpolate_Y(true)),
INTERPOLATE_XZ(showModeParameter -> showModeParameter.setInterpolate_XZ(true)),
ADVANCED(showModeParameter -> {
showModeParameter.setInterpolate_Y(true);
showModeParameter.setInterpolate_XZ(true);
});
private final Consumer<ShowModeParameter> showModeParameterConsumer;
public Consumer<ShowModeParameter> getShowModeParameterConsumer() {
return showModeParameterConsumer;
}
ShowModeParameterType(Consumer<ShowModeParameter> showModeParameterConsumer) {
this.showModeParameterConsumer = showModeParameterConsumer;
}
}

View File

@ -0,0 +1,45 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.tracer.show;
import de.steamwar.bausystem.tracer.record.RecordStateMachine;
import java.util.ArrayList;
import java.util.List;
public class StoredRecords {
private static final List<Record> records = new ArrayList<>();
public static void add(Record record) {
records.add(record);
}
public static void showAll(ShowMode mode) {
for (Record record : records) record.showAll(mode);
}
public static void clear() {
records.clear();
TraceShowManager.clear();
RecordStateMachine.postClear();
}
}

View File

@ -0,0 +1,59 @@
package de.steamwar.bausystem.tracer.show;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.tracer.TNTPosition;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerQuitEvent;
import java.util.HashMap;
import java.util.Map;
public class TraceShowManager implements Listener {
private TraceShowManager() {
}
private static final Map<Player, ShowMode> showModes = new HashMap<>();
public static void show(Player player, ShowMode showMode) {
hide(player);
showModes.put(player, showMode);
StoredRecords.showAll(showMode);
}
public static void hide(Player player) {
ShowMode showMode = showModes.remove(player);
if (showMode == null)
return;
showMode.hide();
}
/* Only to be called by record */
static void show(TNTPosition tnt) {
for (ShowMode mode : showModes.values())
mode.show(tnt);
}
/* Only to be called by StoredRecords */
static void clear() {
for (ShowMode mode : showModes.values())
mode.hide();
}
/* Internal if player leaves*/
static {
Bukkit.getPluginManager().registerEvents(new TraceShowManager(), BauSystem.getPlugin());
}
@EventHandler
public void onLeave(PlayerQuitEvent event) {
showModes.remove(event.getPlayer());
}
public static boolean hasActiveShow(Player player) {
return showModes.containsKey(player);
}
}

View File

@ -0,0 +1,120 @@
/*
*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
* /
*/
package de.steamwar.bausystem.tracer.show.mode;
import de.steamwar.bausystem.CraftbukkitWrapper;
import de.steamwar.bausystem.FlatteningWrapper;
import de.steamwar.bausystem.tracer.AbstractTraceEntity;
import de.steamwar.bausystem.tracer.RoundedTNTPosition;
import de.steamwar.bausystem.tracer.TNTPosition;
import de.steamwar.bausystem.tracer.show.ShowMode;
import de.steamwar.bausystem.tracer.show.ShowModeParameter;
import org.bukkit.entity.Player;
import org.bukkit.util.Consumer;
import org.bukkit.util.Vector;
import java.util.HashMap;
import java.util.Map;
public class EntityShowMode implements ShowMode {
protected final Player player;
protected final ShowModeParameter showModeParameter;
private final Map<RoundedTNTPosition, AbstractTraceEntity> tntEntityMap = new HashMap<>();
private final Map<RoundedTNTPosition, AbstractTraceEntity> updateEntityMap = new HashMap<>();
public EntityShowMode(Player player, ShowModeParameter showModeParameter) {
this.player = player;
this.showModeParameter = showModeParameter;
}
@Override
public void show(TNTPosition position) {
if (!showModeParameter.isWater() && position.isExploded() && checkWater(position.getLocation())) {
// Basic
for (TNTPosition pos : position.getRecord().getPositions()) {
RoundedTNTPosition roundedTNTPosition = new RoundedTNTPosition(pos);
tntEntityMap.computeIfPresent(roundedTNTPosition, (p, tnt) -> {
return tnt.hide(player, false) ? null : tnt;
});
}
// Advanced
for (TNTPosition pos : position.getRecord().getPositions()) {
applyOnPosition(pos, updatePointPosition -> {
updateEntityMap.computeIfPresent(new RoundedTNTPosition(updatePointPosition), (p, point) -> {
return point.hide(player, false) ? null : point;
});
});
}
return;
}
RoundedTNTPosition roundedTNTPosition = new RoundedTNTPosition(position);
AbstractTraceEntity entity = tntEntityMap.computeIfAbsent(roundedTNTPosition, pos -> createEntity(player, position.getLocation(), true));
entity.display(player, position.isExploded());
applyOnPosition(position, updatePointPosition -> {
updateEntityMap.computeIfAbsent(new RoundedTNTPosition(updatePointPosition), pos -> {
return createEntity(player, updatePointPosition, false);
}).display(player, position.isExploded());
});
}
private boolean checkWater(Vector position) {
return FlatteningWrapper.impl.inWater(player.getWorld(), position);
}
public static AbstractTraceEntity createEntity(Player player, Vector position, boolean tnt) {
return CraftbukkitWrapper.impl.create(player.getWorld(), position, tnt);
}
private void applyOnPosition(TNTPosition position, Consumer<Vector> function) {
if (position.getPreviousLocation() == null) return;
if (showModeParameter.isInterpolate_Y()) {
Vector updatePointY = position.getPreviousLocation().clone().setY(position.getLocation().getY());
if (!position.getLocation().equals(updatePointY)) {
function.accept(updatePointY);
}
}
if (showModeParameter.isInterpolate_XZ()) {
Vector movement = position.getLocation().clone().subtract(position.getPreviousLocation());
Vector updatePointXZ = Math.abs(movement.getX()) > Math.abs(movement.getZ())
? position.getLocation().clone().setZ(position.getPreviousLocation().getZ())
: position.getLocation().clone().setX(position.getPreviousLocation().getX());
if (!position.getLocation().equals(updatePointXZ)) {
function.accept(updatePointXZ);
}
}
}
@Override
public void hide() {
tntEntityMap.forEach((roundedTNTPosition, abstractTraceEntity) -> abstractTraceEntity.hide(player, true));
tntEntityMap.clear();
updateEntityMap.forEach((roundedTNTPosition, abstractTraceEntity) -> abstractTraceEntity.hide(player, true));
updateEntityMap.clear();
}
}

View File

@ -0,0 +1,56 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.world;
import de.steamwar.bausystem.BauSystem;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerMoveEvent;
public class AFKStopper implements Listener {
private static final String afkWarning = BauSystem.PREFIX + "§cDieser Server wird bei weiterer Inaktivität in einer Minute gestoppt";
private int minutesAfk;
public AFKStopper() {
minutesAfk = 0;
Bukkit.getPluginManager().registerEvents(this, BauSystem.getPlugin());
Bukkit.getScheduler().runTaskTimer(BauSystem.getPlugin(), () -> {
switch (minutesAfk) {
case 5:
for (Player p : Bukkit.getOnlinePlayers())
p.kickPlayer("§cAuf diesem Server ist seit 5 Minuten nichts passiert.");
break;
case 4:
Bukkit.broadcastMessage(afkWarning);
default:
minutesAfk++;
}
}, 1200, 1200); //every minute
}
@EventHandler
public void onPlayerMove(PlayerMoveEvent event) {
minutesAfk = 0;
}
}

View File

@ -0,0 +1,122 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.world;
import net.md_5.bungee.api.ChatMessageType;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import java.util.LinkedList;
abstract class AbstractAutoLoader {
abstract Player getPlayer();
abstract boolean setRedstone(Location location, boolean active);
abstract LinkedList<LoaderAction> getActions();
abstract void resetLastActivation();
abstract int getLastActivation();
void print(String message, boolean withSize){
if(withSize)
getPlayer().spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(message + " §8" + getActions().size()));
else
getPlayer().spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(message));
}
abstract static class LoaderAction {
final Location location;
final AbstractAutoLoader loader;
LoaderAction(AbstractAutoLoader loader, Location location){
this.location = location;
this.loader = loader;
loader.getActions().add(this);
loader.resetLastActivation();
}
abstract boolean perform();
abstract int ticks();
}
static class RedstoneActivation extends LoaderAction{
final boolean active;
final int length;
int status;
RedstoneActivation(AbstractAutoLoader loader, Location location, int ticks, boolean active){
super(loader, location);
this.length = ticks;
this.active = active;
status = 0;
}
@Override
public boolean perform() {
status++;
if(status < length)
return false;
if(!loader.setRedstone(location, active))
return false;
status = 0;
return true;
}
@Override
int ticks() {
return 1;
}
}
static class TemporaryActivation extends LoaderAction{
final int length;
int status;
TemporaryActivation(AbstractAutoLoader loader, Location location, int ticks){
super(loader, location);
this.length = ticks;
status = 0;
}
@Override
public boolean perform() {
if(status == 0){
if(!loader.setRedstone(location, true))
return false;
}else if(status == length){
if(!loader.setRedstone(location, false))
return false;
status = 0;
return true;
}
status++;
return false;
}
@Override
int ticks() {
return 1;
}
}
}

View File

@ -0,0 +1,266 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.world;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.FlatteningWrapper;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.scheduler.BukkitTask;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Map;
public class AutoLoader extends AbstractAutoLoader implements Listener {
private static final Map<Player, AutoLoader> players = new HashMap<>();
public static AutoLoader getLoader(Player player){
if(!players.containsKey(player))
return new AutoLoader(player);
return players.get(player);
}
public static boolean hasLoader(Player player){
return players.containsKey(player);
}
private final Player player;
private final BukkitTask task;
private final LinkedList<LoaderAction> actions = new LinkedList<>();
private int ticksBetweenShots = 80;
private int ticksBetweenBlocks = 1;
private int lastActivation;
private int waitTicks;
private ListIterator<LoaderAction> lastAction;
private boolean setup;
private Location lastLocation;
private AutoLoader(Player player){
this.player = player;
Bukkit.getPluginManager().registerEvents(this, BauSystem.getPlugin());
task = Bukkit.getScheduler().runTaskTimer(BauSystem.getPlugin(), this::run, 1, 1);
players.put(player, this);
player.sendMessage(BauSystem.PREFIX + "§7Schieße bitte einmal die Kanone ab");
player.sendMessage(BauSystem.PREFIX + "§7Und starte anschließend den AutoLader mit §8/§eloader start");
setup();
}
public void setup(){
print("§aAutoLader im Setup-Modus", false);
setup = true;
waitTicks = 0;
lastActivation = 0;
}
public void start(){
if(actions.isEmpty()){
print("§cKeine Aktion vorhanden", false);
return;
}
if(!setup){
print("§cAutoLader läuft bereits", false);
return;
}
setup = false;
waitTicks = 0;
lastActivation = 0;
lastAction = actions.listIterator();
print("§aAutoLader gestartet", false);
}
public void stop(){
print("§cAutoLader gestoppt", false);
players.remove(player);
HandlerList.unregisterAll(this);
if(task != null)
task.cancel();
}
public void undo(){
if(actions.isEmpty()){
print("§cKeine Aktion vorhanden", false);
return;
}
actions.removeLast();
print("§aUndo erfolgreich", true);
}
public void wait(int time){
if(time < 1){
print("§cDie Wartezeit ist zu klein", false);
return;
}
print("§aSchusswartezeit §e" + time + " §aTicks§8, zuvor " + ticksBetweenShots, false);
ticksBetweenShots = time;
}
public void blockWait(int time){
if(time < 1){
print("§cDie Wartezeit ist zu klein", false);
return;
}
print("§aSetzwartezeit §e" + time + " §aTicks§8, zuvor " + ticksBetweenBlocks, false);
ticksBetweenBlocks = time;
}
public int getTicksBetweenShots() {
return ticksBetweenShots;
}
public int getTicksBetweenBlocks() {
return ticksBetweenBlocks;
}
public boolean isSetup() {
return setup;
}
@EventHandler
public void onBlockPlace(BlockPlaceEvent event){
if(!setup || !event.getPlayer().equals(player))
return;
if(event.getBlock().getType() != Material.TNT)
return;
new TNTPlaceAction(this, event.getBlock().getLocation());
print("§eTNT platziert", true);
}
//BlockRedstoneEvent?
@EventHandler
public void onPlayerInteract(PlayerInteractEvent event){
if (event.getAction() != Action.RIGHT_CLICK_BLOCK && event.getAction() != Action.PHYSICAL)
return;
if (event.getClickedBlock().getType() == Material.OBSERVER)
return;
if (event.getPlayer().isSneaking())
return;
if (!setup || !event.getPlayer().equals(player))
return;
Detoloader detoloader = FlatteningWrapper.impl.onPlayerInteractLoader(event);
if (detoloader == null || detoloader.getActivation() < 0) return;
if (lastLocation != null && lastLocation.distance(event.getClickedBlock().getLocation()) <= 1) return;
if (detoloader.useActive) {
new AbstractAutoLoader.RedstoneActivation(this, event.getClickedBlock().getLocation()
, detoloader.getActivation() == 0 ? getLastActivation() : detoloader.getActivation()
, detoloader.isActive());
} else {
new AbstractAutoLoader.TemporaryActivation(this, event.getClickedBlock().getLocation()
, detoloader.getActivation());
}
print(detoloader.addBack ? "§e" + detoloader.getBlock() + " betätigt" :
detoloader.getBlock(), detoloader.addBack);
lastLocation = event.getClickedBlock().getLocation();
}
@EventHandler
public void onLeave(PlayerQuitEvent event){
if(!event.getPlayer().equals(player))
return;
stop();
}
private void run(){
lastActivation++;
if(setup)
return;
while(lastActivation >= waitTicks){
lastActivation = 0;
LoaderAction action = lastAction.next();
if(action.perform()){
waitTicks = action.ticks();
}else{
waitTicks = 1;
lastAction.previous();
}
if(!lastAction.hasNext()){
lastAction = actions.listIterator();
waitTicks = ticksBetweenShots;
}
}
}
@Override
Player getPlayer() {
return player;
}
@Override
boolean setRedstone(Location location, boolean active){
return FlatteningWrapper.impl.setRedstone(location, active);
}
@Override
LinkedList<LoaderAction> getActions() {
return actions;
}
@Override
void resetLastActivation() {
lastActivation = 0;
}
@Override
int getLastActivation() {
return lastActivation;
}
class TNTPlaceAction extends AbstractAutoLoader.LoaderAction {
TNTPlaceAction(AbstractAutoLoader loader, Location location){
super(loader, location);
}
@Override
public boolean perform() {
return FlatteningWrapper.impl.tntPlaceActionPerform(location);
}
@Override
int ticks(){
return ticksBetweenBlocks;
}
}
}

View File

@ -0,0 +1,111 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.world;
import de.steamwar.bausystem.commands.CommandTPSLimiter;
import de.steamwar.bausystem.tracer.record.RecordStateMachine;
import de.steamwar.bausystem.world.regions.Region;
import de.steamwar.core.TPSWatcher;
import de.steamwar.scoreboard.SWScoreboard;
import de.steamwar.scoreboard.ScoreboardCallback;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
public class BauScoreboard implements Listener {
@EventHandler
public void handlePlayerJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
SWScoreboard.impl.createScoreboard(player, new ScoreboardCallback() {
@Override
public HashMap<String, Integer> getData() {
return sidebar(player);
}
@Override
public String getTitle() {
return "§eSteam§8War";
}
});
}
private HashMap<String, Integer> sidebar(Player p) {
List<String> strings = new ArrayList<>();
strings.add("§1");
strings.add("§eUhrzeit§8: §7" + new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime()));
strings.add("§2");
Region region = Region.getRegion(p.getLocation());
strings.add("§eTNT§8: " + region.getTntMode().getName());
strings.add("§eFreeze§8: " + (region.isFreeze() ? "§aan" : "§caus"));
strings.add("§eFire§8: " + (region.isFire() ? "§aaus" : "§can"));
strings.add("§eTrace§8: " + RecordStateMachine.getRecordStatus().getName());
strings.add("§eLoader§8: " + (AutoLoader.hasLoader(p) ? "§aan" : "§caus"));
if (region.hasProtection()) {
strings.add("§eProtect§8: " + (region.isProtect() ? "§aan" : "§caus"));
}
if (RecordStateMachine.getRecordStatus().isTracing()) {
strings.add("§3");
strings.add("§eTicks§8: §7" + traceTicks());
strings.add("§eAnzahl TNT§8: §7" + RecordStateMachine.size());
}
strings.add("§4");
strings.add("§eTPS§8: " + tpsColor() + TPSUtils.getTps(TPSWatcher.TPSType.ONE_SECOND) + tpsLimit());
int i = strings.size();
HashMap<String, Integer> result = new HashMap<>();
for (String s : strings)
result.put(s, i--);
return result;
}
private long traceTicks() {
return (System.currentTimeMillis() - RecordStateMachine.getStartTime()) / 50;
}
private String tpsColor() {
double tps = TPSUtils.getTps(TPSWatcher.TPSType.ONE_SECOND);
if (tps > CommandTPSLimiter.getCurrentTPSLimit() * 0.9) {
return "§a";
}
if (tps > CommandTPSLimiter.getCurrentTPSLimit() * 0.5) {
return "§e";
}
return "§c";
}
private String tpsLimit() {
if (CommandTPSLimiter.getCurrentTPSLimit() == 20) {
return "";
}
return "§8/§7" + CommandTPSLimiter.getCurrentTPSLimit();
}
}

View File

@ -0,0 +1,63 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.world;
import de.steamwar.sql.SchematicData;
import de.steamwar.sql.SchematicNode;
import de.steamwar.sql.SteamwarUser;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
public class ClipboardListener implements Listener {
private static final String CLIPBOARD_SCHEMNAME = "//copy";
@EventHandler
public void onLogin(PlayerJoinEvent e) {
try {
SchematicNode schematic = SchematicNode.getSchematicNode(SteamwarUser.get(e.getPlayer().getUniqueId()).getId(), CLIPBOARD_SCHEMNAME, (Integer) null);
if (schematic != null) {
new SchematicData(schematic).loadToPlayer(e.getPlayer());
}
} catch (Exception ex) {
// ignore cause players do all kind of stuff with schematics.... like massively oversized schems
}
}
@EventHandler
public void onLogout(PlayerQuitEvent e) {
SchematicNode schematic = SchematicNode.getSchematicNode(SteamwarUser.get(e.getPlayer().getUniqueId()).getId(), CLIPBOARD_SCHEMNAME, (Integer) null);
boolean newSchem = false;
if (schematic == null) {
schematic = SchematicNode.createSchematic(SteamwarUser.get(e.getPlayer().getUniqueId()).getId(), CLIPBOARD_SCHEMNAME, null);
newSchem = true;
}
try {
new SchematicData(schematic).saveFromPlayer(e.getPlayer());
} catch (Exception ex) {
if (newSchem) {
schematic.delete();
}
}
}
}

View File

@ -0,0 +1,39 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.world;
public enum Color {
WHITE,
ORANGE,
MAGENTA,
LIGHT_BLUE,
YELLOW,
LIME,
PINK,
GRAY,
LIGHT_GRAY,
CYAN,
PURPLE,
BLUE,
BROWN,
GREEN,
RED,
BLACK;
}

View File

@ -0,0 +1,87 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.world;
import org.bukkit.Location;
public class Detoloader {
String message;
int activation;
boolean active, addBack = true, useActive = false;
public Detoloader(String message, int activation) {
this.message = message;
this.activation = activation;
}
public String getBlock() {
return message;
}
public void setBlock(String message) {
this.message = message;
}
public int getActivation() {
return activation;
}
public boolean isActive() {
return active;
}
public Detoloader setActive(boolean active) {
useActive = true;
this.active = active;
return this;
}
public boolean isAddBack() {
return addBack;
}
public Detoloader setAddBack(boolean addBack) {
this.addBack = addBack;
return this;
}
static class DetonatorActivation {
int activation = -1;
Location location;
public DetonatorActivation(Location location) {
this.location = location;
}
public DetonatorActivation(int activation, Location location) {
this.activation = activation;
this.location = location;
}
}
//Timings
public static final int STONE_BUTTON = 20;
public static final int WOODEN_BUTTON = 30;
public static final int PRESSURE_PLATE = 20;
public static final int NOTE_BLOCK = 1;
public static final int TRIPWIRE = 20;
}

View File

@ -0,0 +1,120 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.world;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.FlatteningWrapper;
import net.md_5.bungee.api.ChatMessageType;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.*;
public class Detonator implements Listener {
public static final ItemStack WAND;
public static final Map<Player, Set<Detoloader.DetonatorActivation>> PLAYER_LOCS = new HashMap<>();
static {
WAND = new ItemStack(Material.BLAZE_ROD, 1);
ItemMeta im = WAND.getItemMeta();
im.setDisplayName("§eFernzünder");
List<String> lorelist = Arrays.asList("§eLinks Klick §8- §7Setzte einen Punkt zum Aktivieren",
"§eLinks Klick + Shift §8- §7Füge einen Punkt hinzu", "§eRechts Klick §8- §7Löse alle Punkte aus");
im.setLore(lorelist);
WAND.setItemMeta(im);
}
public static Detonator getDetonator(Player player, ItemStack item) {
return new Detonator(player, PLAYER_LOCS.get(player));
}
public static ItemStack setLocation(Player player, ItemStack item, Detoloader.DetonatorActivation detoloader) {
PLAYER_LOCS.computeIfAbsent(player, player1 -> new HashSet<>()).clear();
PLAYER_LOCS.get(player).add(detoloader);
return item;
}
public static ItemStack toggleLocation(ItemStack item, Player player, Detoloader detoloader, Location location) {
if (PLAYER_LOCS.computeIfAbsent(player, player1 -> new HashSet<>()).stream().anyMatch(activation -> activation.location.equals(location))) {
DetonatorListener.print(player, detoloader.addBack ? "§e" + detoloader.getBlock() + " entfernt" :
detoloader.getBlock(), Detonator.getDetonator(player, player.getInventory().getItemInMainHand()).getLocs().size() - 1);
PLAYER_LOCS.computeIfAbsent(player, player1 -> new HashSet<>()).removeIf(activation -> activation.location.equals(location));
return item;
} else {
DetonatorListener.print(player, detoloader.addBack ? "§e" + detoloader.getBlock() + " hinzugefügt" :
detoloader.getBlock(), Detonator.getDetonator(player, player.getInventory().getItemInMainHand()).getLocs().size() + 1);
if (detoloader.getActivation() == 0) {
PLAYER_LOCS.computeIfAbsent(player, player1 -> new HashSet<>()).add(new Detoloader.DetonatorActivation(location));
return item;
} else {
PLAYER_LOCS.computeIfAbsent(player, player1 -> new HashSet<>()).add(new Detoloader.DetonatorActivation(detoloader.getActivation(), location));
return item;
}
}
}
public static void execute(Player player) {
execute(player, PLAYER_LOCS.get(player));
}
private static void execute(Player player, Set<Detoloader.DetonatorActivation> locs) {
for (Detoloader.DetonatorActivation activation : locs) {
if (activation.activation == -1) {
FlatteningWrapper.impl.setRedstone(activation.location, !FlatteningWrapper.impl.getLever(activation.location.getBlock()));
} else {
FlatteningWrapper.impl.setRedstone(activation.location, true);
Bukkit.getScheduler().runTaskLater(BauSystem.getPlugin(), () -> FlatteningWrapper.impl.setRedstone(activation.location, false), activation.activation);
}
}
player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText("§e" + locs.size() + " §7Punkt" + (locs.size() > 1 ? "e" : "") + " ausgelöst!"));
}
public static void clear(Player player) {
PLAYER_LOCS.computeIfAbsent(player, player1 -> new HashSet<>()).clear();
}
private final Set<Detoloader.DetonatorActivation> locs;
private final Player player;
private Detonator(Player player, Set<Detoloader.DetonatorActivation> locs) {
this.player = player;
this.locs = locs;
}
public Set<Detoloader.DetonatorActivation> getLocs() {
return locs;
}
public Player getPlayer() {
return player;
}
}

View File

@ -0,0 +1,65 @@
package de.steamwar.bausystem.world;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.FlatteningWrapper;
import de.steamwar.bausystem.Permission;
import net.md_5.bungee.api.ChatMessageType;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
public class DetonatorListener implements Listener {
@EventHandler
public void onPlayerInteract(PlayerInteractEvent event) {
if (event.getItem() == null) return;
if (event.getItem().isSimilar(Detonator.WAND)) {
Player player = event.getPlayer();
if (Welt.noPermission(player, Permission.WORLD)) {
player.sendMessage(BauSystem.PREFIX + "§cDu darfst hier nicht den Detonator nutzen");
return;
}
ItemStack item = event.getItem();
event.setCancelled(true);
switch (event.getAction()) {
case LEFT_CLICK_BLOCK:
Detoloader detoloader = FlatteningWrapper.impl.onPlayerInteractLoader(event);
if (detoloader == null) {
return;
} else if (detoloader.activation == -1) {
print(player, detoloader.getBlock(), detoloader.addBack ? Detonator.getDetonator(player, player.getInventory().getItemInMainHand()).getLocs().size() : 0);
return;
}
if (event.getPlayer().isSneaking()) {
player.getInventory().setItemInMainHand(Detonator.toggleLocation(item, player, detoloader, event.getClickedBlock().getLocation()));
} else {
if (detoloader.getActivation() == 0) {
player.getInventory().setItemInMainHand(Detonator.setLocation(player, item, new Detoloader.DetonatorActivation(event.getClickedBlock().getLocation())));
} else {
player.getInventory().setItemInMainHand(Detonator.setLocation(player, item, new Detoloader.DetonatorActivation(detoloader.activation, event.getClickedBlock().getLocation())));
}
print(player, detoloader.addBack ? "§e" + detoloader.getBlock() + " gesetzt" :
detoloader.getBlock(), detoloader.addBack ? Detonator.getDetonator(player, player.getInventory().getItemInMainHand()).getLocs().size() : 0);
}
break;
case RIGHT_CLICK_AIR:
case RIGHT_CLICK_BLOCK:
Detonator.execute(player);
break;
}
}
}
public static void print(Player player, String message, int size) {
if (size == 0) {
player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(message));
} else {
player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(message + " §8" + size));
}
}
}

View File

@ -0,0 +1,52 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.world;
import de.steamwar.bausystem.SWUtils;
import org.bukkit.Material;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.inventory.ItemStack;
public class ItemFrameListener implements Listener {
@EventHandler
public void onEntityDamageByEntity(EntityDamageByEntityEvent event) {
if (!(event.getDamager() instanceof Player)) {
return;
}
if (!(event.getEntity() instanceof ItemFrame)) {
return;
}
event.setCancelled(true);
ItemFrame itemFrame = (ItemFrame) event.getEntity();
ItemStack itemStack = itemFrame.getItem();
if (itemStack.getType() != Material.AIR) {
SWUtils.giveItemToPlayer((Player) event.getDamager(), itemFrame.getItem());
itemFrame.setItem(null);
} else {
itemFrame.remove();
}
}
}

View File

@ -0,0 +1,124 @@
package de.steamwar.bausystem.world;
import de.steamwar.bausystem.BauSystem;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class PredefinedBook {
private static final FileConfiguration configuration;
private static List<PredefinedBook> bookCache;
static {
configuration = YamlConfiguration.loadConfiguration(new File(BauSystem.getPlugin().getDataFolder(), "books.yml"));
}
public static List<PredefinedBook> getBooks() {
if (bookCache != null)
return bookCache;
List<PredefinedBook> books = new ArrayList<>();
for (String book : configuration.getKeys(false)) {
ConfigurationSection section = Objects.requireNonNull(configuration.getConfigurationSection(book));
books.add(new PredefinedBook(section));
}
bookCache = books;
return books;
}
public static int getBookCount() {
return configuration.getKeys(false).size();
}
private List<String> lines;
private List<String> lore;
private String author;
private String name;
private ItemStack finishedBook;
PredefinedBook(ConfigurationSection section) {
this.lines = section.getStringList("lines");
this.lore = section.getStringList("lore");
this.author = section.getString("author", "§8Steam§eWar");
this.name = section.getName();
}
public ItemStack toItemStack() {
if (finishedBook != null)
return finishedBook;
ItemStack book = new ItemStack(getBookMat());
BookMeta meta = (BookMeta) book.getItemMeta();
meta.setPages(getPages());
meta.setDisplayName(name);
meta.setTitle(name);
meta.setAuthor(author);
meta.setGeneration(BookMeta.Generation.ORIGINAL);
meta.setLore(lore);
book.setItemMeta(meta);
finishedBook = book;
return book;
}
public Material getBookMat() {
return Material.WRITTEN_BOOK;
}
public List<String> getLines() {
return lines;
}
public String getAuthor() {
return author;
}
public String getName() {
return name;
}
public List<String> getLore() {
return lore;
}
private String[] getPages() {
List<StringBuilder> pages = new ArrayList<>();
pages.add(0, new StringBuilder());
int charsPerLine = 19;
int currentLine = 0;
int currentpage = 0;
boolean first = true;
for (String line : lines) {
int linesPlus = (int) Math.ceil((double) line.length() / charsPerLine);
currentLine += linesPlus;
if (currentLine >= 14 || line.equals("!")) {
currentLine = linesPlus;
currentpage++;
if (currentpage > 50)
throw new IllegalStateException("Book " + name + " has more pages than 50");
pages.add(currentpage, new StringBuilder());
first = true;
if (line.equals("!"))
continue;
}
if (!first) {
pages.get(currentpage).append("\n");
} else {
first = false;
}
pages.get(currentpage).append(line);
}
String[] finalPages = new String[pages.size()];
for (int i = 0; i < pages.size(); i++) {
finalPages[i] = pages.get(i).toString();
}
return finalPages;
}
}

View File

@ -0,0 +1,137 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.world;
import de.steamwar.Reflection;
import com.comphenix.tinyprotocol.TinyProtocol;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.CraftbukkitWrapper;
import de.steamwar.bausystem.Permission;
import de.steamwar.bausystem.WorldeditWrapper;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import java.util.ArrayList;
import java.util.List;
public class RegionListener implements Listener {
private final List<Player> signEditing = new ArrayList<>();
private static final Class<?> updateSign = Reflection.getClass("{nms}.PacketPlayInUpdateSign");
private static final Class<?> blockPosition = Reflection.getClass("{nms}.BlockPosition");
private static final Reflection.Field<?> blockPos = Reflection.getField(updateSign, blockPosition, 0);
private static final Reflection.Field<String[]> signText = Reflection.getField(updateSign, String[].class, 0);
private static final Class<?> baseBlockPosition = Reflection.getClass("{nms}.BaseBlockPosition");
private static final Reflection.Field<Integer> blockPosX = Reflection.getField(baseBlockPosition, int.class, 0);
private static final Reflection.Field<Integer> blockPosY = Reflection.getField(baseBlockPosition, int.class, 1);
private static final Reflection.Field<Integer> blockPosZ = Reflection.getField(baseBlockPosition, int.class, 2);
public RegionListener() {
TinyProtocol.instance.addFilter(updateSign, (player, packet) -> {
if(!signEditing.contains(player))
return packet;
String[] lines = signText.get(packet);
Object pos = blockPos.get(packet);
Bukkit.getScheduler().runTask(BauSystem.getPlugin(), () -> {
Block signLoc = new Location(player.getWorld(), blockPosX.get(pos), blockPosY.get(pos), blockPosZ.get(pos)).getBlock();
if (!signLoc.getType().name().contains("SIGN"))
return;
Sign sign = ((Sign) signLoc.getState());
for (int i = 0; i < lines.length; i++) {
sign.setLine(i, ChatColor.translateAlternateColorCodes('&', lines[i]));
}
sign.update();
signEditing.remove(player);
});
return packet;
});
}
@EventHandler(priority = EventPriority.LOWEST)
public void playerCommandHandler(PlayerCommandPreprocessEvent e) {
if (!isWorldEditCommand(e.getMessage().split(" ")[0]))
return;
Player p = e.getPlayer();
if (Welt.noPermission(p, Permission.WORLDEDIT)) {
p.sendMessage(BauSystem.PREFIX + "§cDu darfst hier kein WorldEdit benutzen");
e.setCancelled(true);
}
}
private static final String[] shortcutCommands = {"//1", "//2", "//90", "//-90", "//180", "//p", "//c", "//flopy", "//floppy", "//flopyp", "//floppyp", "//u", "//r"};
private boolean isWorldEditCommand(String command) {
for (String shortcut : shortcutCommands)
if (command.startsWith(shortcut))
return true;
return WorldeditWrapper.impl.isWorldEditCommand(command);
}
@EventHandler
public void onSignChange(SignChangeEvent event) {
for (int i = 0; i <= 3; ++i) {
String line = event.getLine(i);
if (line == null)
continue;
line = ChatColor.translateAlternateColorCodes('&', line);
event.setLine(i, line);
}
}
@EventHandler
public void editSign(PlayerInteractEvent event) {
if (event.getAction() != Action.RIGHT_CLICK_BLOCK ||
!event.getClickedBlock().getType().name().contains("SIGN") ||
!event.getPlayer().isSneaking() ||
(event.getItem() != null && event.getItem().getType() != Material.AIR))
return;
Player player = event.getPlayer();
Sign sign = (Sign) event.getClickedBlock().getState();
String[] lines = sign.getLines();
for (int i = 0; i < lines.length; i++) {
sign.setLine(i, lines[i].replace('\u00A7' /* WINDOWS \u00A7 -> § */, '&'));
}
sign.update();
CraftbukkitWrapper.impl.openSignEditor(player, event.getClickedBlock().getLocation());
signEditing.add(player);
}
}

View File

@ -0,0 +1,542 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.world;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.FlatteningWrapper;
import de.steamwar.bausystem.commands.CommandScript;
import de.steamwar.bausystem.commands.CommandTNT;
import de.steamwar.bausystem.tracer.record.RecordStateMachine;
import de.steamwar.bausystem.world.regions.Region;
import de.steamwar.inventory.SWAnvilInv;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta;
import java.util.*;
import java.util.function.Function;
import java.util.function.IntBinaryOperator;
import java.util.function.IntUnaryOperator;
import java.util.logging.Level;
public class ScriptListener implements Listener {
public static final Map<Player, Map<String, Integer>> GLOBAL_VARIABLES = new HashMap<>();
private static final Map<String, Function<Player, Integer>> CONSTANTS = new HashMap<>();
static {
CONSTANTS.put("trace", player -> RecordStateMachine.getRecordStatus().isTracing() ? 1 : 0);
CONSTANTS.put("autotrace", player -> RecordStateMachine.getRecordStatus().isAutoTrace() ? 1 : 0);
CONSTANTS.put("tnt", player -> Region.getRegion(player.getLocation()).getTntMode() == CommandTNT.TNTMode.OFF ? 0 : 1);
CONSTANTS.put("freeze", player -> Region.getRegion(player.getLocation()).isFreeze() ? 1 : 0);
CONSTANTS.put("fire", player -> Region.getRegion(player.getLocation()).isFire() ? 1 : 0);
CONSTANTS.put("x", player -> player.getLocation().getBlockX());
CONSTANTS.put("y", player -> player.getLocation().getBlockY());
CONSTANTS.put("z", player -> player.getLocation().getBlockZ());
}
private Set<Player> playerSet = new HashSet<>();
public ScriptListener() {
Bukkit.getScheduler().runTaskTimer(BauSystem.getPlugin(), playerSet::clear, 5, 5);
}
@EventHandler(priority = EventPriority.HIGH)
public void onLeftClick(PlayerInteractEvent event) {
ItemStack item = event.getItem();
if (item == null || isNoBook(item) || item.getItemMeta() == null)
return;
if (CommandScript.BOOK.getItemMeta() != null && item.getItemMeta().hasDisplayName() && item.getItemMeta().getDisplayName().equals(CommandScript.BOOK.getItemMeta().getDisplayName())) {
return;
}
if (event.getAction() != Action.LEFT_CLICK_AIR && event.getAction() != Action.LEFT_CLICK_BLOCK) {
if (event.getAction() == Action.RIGHT_CLICK_AIR) {
playerSet.add(event.getPlayer());
}
return;
}
if (playerSet.remove(event.getPlayer())) {
return;
}
event.setCancelled(true);
new ScriptExecutor((BookMeta) item.getItemMeta(), event.getPlayer());
}
@EventHandler
public void onPlayerQuit(PlayerQuitEvent event) {
GLOBAL_VARIABLES.remove(event.getPlayer());
}
private boolean isNoBook(ItemStack item) {
return FlatteningWrapper.impl.isNoBook(item);
}
private static class ScriptExecutor {
private final Player player;
private final List<String> commands = new ArrayList<>();
private final Map<String, Integer> jumpPoints = new HashMap<>();
private Map<String, Integer> variables = new HashMap<>();
private int index = 0;
public ScriptExecutor(BookMeta bookMeta, Player player) {
this.player = player;
for (String page : bookMeta.getPages()) {
for (String command : page.split("\n")) {
command = command.replaceAll(" +", " ");
if (command.startsWith("#") || command.trim().isEmpty()) continue;
if (command.startsWith(".")) {
jumpPoints.put(command.substring(1), commands.size());
continue;
}
commands.add(command);
}
}
if (commands.isEmpty()) return;
resume();
}
private void resume() {
if (!player.isOnline()) {
return;
}
int executionPoints = 0;
while (index < commands.size()) {
String command = commands.get(index++);
if (executionPoints++ > 200) {
player.sendMessage(BauSystem.PREFIX + "§cFüge ein sleep in dein Script ein");
return;
}
String firstArg = command;
if (command.contains(" ")) {
firstArg = command.substring(0, command.indexOf(' '));
}
switch (firstArg.toLowerCase()) {
case "sleep":
ScriptListener.sleepCommand(this, generateArgumentArray("sleep", this, command));
return;
case "exit":
return;
case "jump":
int jumpIndex = ScriptListener.jumpCommand(this, generateArgumentArray("jump", this, command));
if (jumpIndex != -1) {
index = jumpIndex;
} else {
player.sendMessage(BauSystem.PREFIX + "§cUnbekannter Jump Punkt: " + command);
}
continue;
case "echo":
ScriptListener.echoCommand(this, generateArgumentArray("echo", this, command));
continue;
case "input":
ScriptListener.inputCommand(this, generateArgumentArray("input", this, command));
return;
case "var":
ScriptListener.variableCommand(this, generateArgumentArray("var", this, command));
continue;
case "unvar":
ScriptListener.unvariableCommand(this, generateArgumentArray("unvar", this, command));
continue;
case "global":
ScriptListener.globalCommand(this, generateArgumentArray("global", this, command));
continue;
case "unglobal":
ScriptListener.unglobalCommand(this, generateArgumentArray("unglobal", this, command));
continue;
case "add":
ScriptListener.arithmeticCommand(this, generateArgumentArray("add", this, command), (left, right) -> left + right);
continue;
case "sub":
ScriptListener.arithmeticCommand(this, generateArgumentArray("sub", this, command), (left, right) -> left - right);
continue;
case "mul":
ScriptListener.arithmeticCommand(this, generateArgumentArray("mul", this, command), (left, right) -> left * right);
continue;
case "div":
ScriptListener.arithmeticCommand(this, generateArgumentArray("div", this, command), (left, right) -> left / right);
continue;
case "equal":
ScriptListener.arithmeticCommand(this, generateArgumentArray("equal", this, command), (left, right) -> left == right ? 1 : 0);
continue;
case "less":
ScriptListener.arithmeticCommand(this, generateArgumentArray("less", this, command), (left, right) -> left < right ? 1 : 0);
continue;
case "greater":
ScriptListener.arithmeticCommand(this, generateArgumentArray("greater", this, command), (left, right) -> left > right ? 1 : 0);
continue;
case "not":
ScriptListener.arithmeticInfixCommand(this, generateArgumentArray("not", this, command), (left) -> left == 1 ? 0 : 1);
continue;
case "and":
ScriptListener.arithmeticCommand(this, generateArgumentArray("and", this, command), (left, right) -> left == 1 && right == 1 ? 1 : 0);
continue;
case "or":
ScriptListener.arithmeticCommand(this, generateArgumentArray("or", this, command), (left, right) -> left == 1 || right == 1 ? 1 : 0);
continue;
case "if":
int ifJumpIndex = ScriptListener.ifCommand(this, generateArgumentArray("if", this, command));
if (ifJumpIndex != -1) {
index = ifJumpIndex;
}
continue;
default:
break;
}
PlayerCommandPreprocessEvent preprocessEvent = new PlayerCommandPreprocessEvent(player, "/" + command);
Bukkit.getServer().getPluginManager().callEvent(preprocessEvent);
if (preprocessEvent.isCancelled()) {
continue;
}
// Variable Replaces in commands.
command = String.join(" ", generateArgumentArray("", this, command));
Bukkit.getLogger().log(Level.INFO, player.getName() + " dispatched command: " + command);
Bukkit.getServer().dispatchCommand(player, command);
}
}
}
private static String[] generateArgumentArray(String command, ScriptExecutor scriptExecutor, String fullCommand) {
String[] strings;
if (command.isEmpty()) {
strings = fullCommand.split(" ");
} else {
strings = fullCommand.substring(command.length()).trim().split(" ");
}
return replaceVariables(scriptExecutor, strings);
}
private static void sleepCommand(ScriptExecutor scriptExecutor, String[] args) {
int sleepTime = 1;
if (args.length > 0) {
try {
sleepTime = Integer.parseInt(args[0]);
if (sleepTime <= 0) {
scriptExecutor.player.sendMessage(BauSystem.PREFIX + "§cDie Zeit muss eine Zahl großer 0 sein.");
sleepTime = 1;
}
} catch (NumberFormatException e) {
scriptExecutor.player.sendMessage(BauSystem.PREFIX + "§cDie Zeit darf nur aus Zahlen bestehen.");
}
}
Bukkit.getScheduler().runTaskLater(BauSystem.getPlugin(), scriptExecutor::resume, sleepTime);
}
private static int jumpCommand(ScriptExecutor scriptExecutor, String[] args) {
if (args.length < 1) {
scriptExecutor.player.sendMessage(BauSystem.PREFIX + "§cEin Jump Punkt muss angegeben sein.");
return -1;
}
return scriptExecutor.jumpPoints.getOrDefault(args[0], -1);
}
private static String[] replaceVariables(ScriptExecutor scriptExecutor, String[] args) {
// Legacy '$' notation for variable reference, could be removed later on.
for (int i = 0; i < args.length; i++) {
if (args[i].startsWith("$") && isVariable(scriptExecutor, args[i].substring(1))) {
args[i] = getValue(scriptExecutor, args[i].substring(1)) + "";
}
}
String s = String.join(" ", args);
Set<String> variables = new HashSet<>(scriptExecutor.variables.keySet());
variables.addAll(CONSTANTS.keySet());
if (GLOBAL_VARIABLES.containsKey(scriptExecutor.player)) {
variables.addAll(GLOBAL_VARIABLES.get(scriptExecutor.player).keySet());
}
for (String variable : variables) {
s = s.replace("<" + variable + ">", getValue(scriptExecutor, variable) + "");
}
for (String constVariable : CONSTANTS.keySet()) {
s = s.replace("<const." + constVariable + ">", getConstantValue(scriptExecutor, constVariable) + "");
}
for (String localVariable : scriptExecutor.variables.keySet()) {
s = s.replace("<local." + localVariable + ">", getLocalValue(scriptExecutor, localVariable) + "");
}
for (String globalVariable : GLOBAL_VARIABLES.getOrDefault(scriptExecutor.player, new HashMap<>()).keySet()) {
s = s.replace("<global." + globalVariable + ">", getGlobalValue(scriptExecutor, globalVariable) + "");
}
return s.split(" ");
}
private static void echoCommand(ScriptExecutor scriptExecutor, String[] args) {
scriptExecutor.player.sendMessage("§eInfo§8» §7" + ChatColor.translateAlternateColorCodes('&', String.join(" ", replaceVariables(scriptExecutor, args))));
}
private static void variableCommand(ScriptExecutor scriptExecutor, String[] args) {
if (args.length < 1) {
scriptExecutor.player.sendMessage(BauSystem.PREFIX + "§cVariablen Namen und Zahlen/Boolsche Wert fehlt.");
return;
}
if (args.length < 2) {
scriptExecutor.player.sendMessage(BauSystem.PREFIX + "§cZahlen/Boolsche Wert fehlt.");
return;
}
switch (args[1]) {
case "inc":
case "increment":
case "++":
add(scriptExecutor, args[0], 1);
return;
case "dec":
case "decrement":
case "--":
add(scriptExecutor, args[0], -1);
return;
default:
break;
}
setValue(scriptExecutor, args[0], parseValue(args[1]));
}
private static void unvariableCommand(ScriptExecutor scriptExecutor, String[] args) {
if (args.length < 1) {
scriptExecutor.player.sendMessage(BauSystem.PREFIX + "§cVariablen Namen fehlt.");
return;
}
if (!isLocalVariable(scriptExecutor, args[0])) {
scriptExecutor.player.sendMessage(BauSystem.PREFIX + "§cVariable is nicht definiert");
return;
}
scriptExecutor.variables.remove(args[0]);
}
private static void globalCommand(ScriptExecutor scriptExecutor, String[] args) {
if (args.length < 1) {
scriptExecutor.player.sendMessage(BauSystem.PREFIX + "§cVariablen Namen fehlt.");
return;
}
if (!isLocalVariable(scriptExecutor, args[0])) {
scriptExecutor.player.sendMessage(BauSystem.PREFIX + "§cVariable is nicht definiert");
return;
}
GLOBAL_VARIABLES.computeIfAbsent(scriptExecutor.player, player -> new HashMap<>()).put(args[0], scriptExecutor.variables.getOrDefault(args[0], 0));
}
private static void unglobalCommand(ScriptExecutor scriptExecutor, String[] args) {
if (args.length < 1) {
scriptExecutor.player.sendMessage(BauSystem.PREFIX + "§cVariablen Namen fehlt.");
return;
}
if (!isGlobalVariable(scriptExecutor, args[0])) {
scriptExecutor.player.sendMessage(BauSystem.PREFIX + "§cVariable is nicht definiert");
return;
}
if (GLOBAL_VARIABLES.containsKey(scriptExecutor.player)) {
GLOBAL_VARIABLES.get(scriptExecutor.player).remove(args[0]);
}
}
private static int ifCommand(ScriptExecutor scriptExecutor, String[] args) {
if (args.length < 2) {
scriptExecutor.player.sendMessage(BauSystem.PREFIX + "§cDie ersten beiden Argumente sind Zahlen/Boolsche Werte oder Variablen.");
return -1;
}
if (args.length < 3) {
scriptExecutor.player.sendMessage(BauSystem.PREFIX + "§cDas dritte Argument muss ein JumpPoint sein.");
return -1;
}
int jumpTruePoint = scriptExecutor.jumpPoints.getOrDefault(args[2], -1);
int jumpFalsePoint = args.length > 3 ? scriptExecutor.jumpPoints.getOrDefault(args[3], -1) : -1;
if (args[1].equals("exists")) {
if (isVariable(scriptExecutor, args[0])) {
return jumpTruePoint;
} else {
return jumpFalsePoint;
}
}
int firstValue = getValueOrParse(scriptExecutor, args[0]);
int secondValue = getValueOrParse(scriptExecutor, args[1]);
if (firstValue == secondValue) {
return jumpTruePoint;
} else {
return jumpFalsePoint;
}
}
private static void arithmeticCommand(ScriptExecutor scriptExecutor, String[] args, IntBinaryOperator operation) {
if (args.length < 1) {
scriptExecutor.player.sendMessage(BauSystem.PREFIX + "§cAls erstes Argument fehlt eine Variable");
return;
}
if (args.length < 2) {
scriptExecutor.player.sendMessage(BauSystem.PREFIX + "§cAls zweites Argument fehlt eine Zahl oder Variable");
return;
}
int firstValue;
int secondValue;
if (args.length < 3) {
if (!isVariable(scriptExecutor, args[0])) {
scriptExecutor.player.sendMessage(BauSystem.PREFIX + "§cDas erste Argument muss eine Variable sein");
return;
}
firstValue = getValue(scriptExecutor, args[0]);
secondValue = getValueOrParse(scriptExecutor, args[1]);
} else {
firstValue = getValue(scriptExecutor, args[1]);
secondValue = getValueOrParse(scriptExecutor, args[2]);
}
setValue(scriptExecutor, args[0], operation.applyAsInt(firstValue, secondValue));
}
private static void arithmeticInfixCommand(ScriptExecutor scriptExecutor, String[] args, IntUnaryOperator operation) {
if (args.length < 1) {
scriptExecutor.player.sendMessage(BauSystem.PREFIX + "§cAls erstes Argument fehlt eine Variable");
return;
}
int firstValue;
if (args.length < 2) {
if (!isVariable(scriptExecutor, args[0])) {
scriptExecutor.player.sendMessage(BauSystem.PREFIX + "§cDas erste Argument muss eine Variable sein");
return;
}
firstValue = getValue(scriptExecutor, args[0]);
} else {
firstValue = getValue(scriptExecutor, args[1]);
}
setValue(scriptExecutor, args[0], operation.applyAsInt(firstValue));
}
private static void inputCommand(ScriptExecutor scriptExecutor, String[] args) {
if (args.length < 1) {
scriptExecutor.player.sendMessage(BauSystem.PREFIX + "§cAls erstes Argument fehlt eine Variable");
return;
}
String varName = args[0];
StringBuilder st = new StringBuilder();
for (int i = 1; i < args.length; i++) {
if (i != 1) {
st.append(" ");
}
st.append(args[i]);
}
SWAnvilInv swAnvilInv = new SWAnvilInv(scriptExecutor.player, ChatColor.translateAlternateColorCodes('&', st.toString()));
swAnvilInv.setCallback(s -> {
int value = parseValue(s);
setValue(scriptExecutor, varName, value);
scriptExecutor.resume();
});
swAnvilInv.open();
}
private static void setValue(ScriptExecutor scriptExecutor, String key, int value) {
scriptExecutor.variables.put(key, value);
}
private static void add(ScriptExecutor scriptExecutor, String key, int value) {
if (!isVariable(scriptExecutor, key)) {
scriptExecutor.variables.put(key, 0);
}
scriptExecutor.variables.put(key, scriptExecutor.variables.get(key) + value);
}
private static int getValueOrParse(ScriptExecutor scriptExecutor, String key) {
if (isVariable(scriptExecutor, key)) {
return getValue(scriptExecutor, key);
} else {
return parseValue(key);
}
}
private static int getValue(ScriptExecutor scriptExecutor, String key) {
if (CONSTANTS.containsKey(key)) {
return CONSTANTS.get(key).apply(scriptExecutor.player);
}
if (GLOBAL_VARIABLES.containsKey(scriptExecutor.player) && GLOBAL_VARIABLES.get(scriptExecutor.player).containsKey(key)) {
return GLOBAL_VARIABLES.get(scriptExecutor.player).get(key);
}
return scriptExecutor.variables.getOrDefault(key, 0);
}
private static int getConstantValue(ScriptExecutor scriptExecutor, String key) {
return CONSTANTS.getOrDefault(key, player -> 0).apply(scriptExecutor.player);
}
private static int getGlobalValue(ScriptExecutor scriptExecutor, String key) {
if (!GLOBAL_VARIABLES.containsKey(scriptExecutor.player)) {
return 0;
}
return GLOBAL_VARIABLES.get(scriptExecutor.player).getOrDefault(key, 0);
}
private static int getLocalValue(ScriptExecutor scriptExecutor, String key) {
return scriptExecutor.variables.getOrDefault(key, 0);
}
private static boolean isVariable(ScriptExecutor scriptExecutor, String key) {
if (CONSTANTS.containsKey(key)) {
return true;
}
if (GLOBAL_VARIABLES.containsKey(scriptExecutor.player) && GLOBAL_VARIABLES.get(scriptExecutor.player).containsKey(key)) {
return true;
}
return scriptExecutor.variables.containsKey(key);
}
private static boolean isLocalVariable(ScriptExecutor scriptExecutor, String key) {
return isVariable(scriptExecutor, key) && !isGlobalVariable(scriptExecutor, key);
}
private static boolean isGlobalVariable(ScriptExecutor scriptExecutor, String key) {
if (!GLOBAL_VARIABLES.containsKey(scriptExecutor.player)) {
return false;
}
return GLOBAL_VARIABLES.get(scriptExecutor.player).containsKey(key);
}
public static int parseValue(String value) {
if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("yes")) {
return 1;
} else if (value.equalsIgnoreCase("false") || value.equalsIgnoreCase("no")) {
return 0;
}
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
return 0;
}
}
}

View File

@ -0,0 +1,123 @@
package de.steamwar.bausystem.world;
@SuppressWarnings({"unused", "UnusedReturnValue"})
public class SizedStack<T> {
private final int maxSize;
private final T[] data;
private int size;
private int head;
public SizedStack(int size) {
this.maxSize = size;
this.data = (T[]) new Object[this.maxSize];
this.head = 0;
this.size = 0;
}
public T push(final T element) {
this.data[this.head] = element;
this.increaseHead();
this.increaseSize();
return element;
}
public T pop() {
this.decreaseHead();
this.decreaseSize();
final T result = this.data[this.head];
this.data[this.head] = null;
return result;
}
public T peek() {
return this.data[this.head];
}
public boolean empty() {
return this.size == 0;
}
protected boolean canEqual(final Object other) {
return other instanceof SizedStack;
}
private void increaseHead() {
this.head++;
while (this.head > this.maxSize - 1) {
this.head -= this.maxSize;
}
}
private void decreaseHead() {
this.head--;
while (this.head < 0) {
this.head += this.maxSize;
}
}
private void increaseSize() {
if (this.size < this.maxSize) {
this.size++;
}
}
private void decreaseSize() {
if (this.size > 0) {
this.size--;
}
}
@Override
public int hashCode() {
final int PRIME = 59;
int result = 1;
result = result * PRIME + this.maxSize;
result = result * PRIME + this.toString().hashCode();
result = result * PRIME + this.size;
return result;
}
@Override
public boolean equals(final Object o) {
if (o == this) {
return true;
}
if (!(o instanceof SizedStack)) {
return false;
}
final SizedStack<?> other = (SizedStack<?>) o;
if (!other.canEqual(this)) {
return false;
}
if (this.maxSize != other.maxSize) {
return false;
}
if (this.size != other.size) {
return false;
}
if (!this.data.getClass().equals(other.data.getClass())) {
return false;
}
return this.toString().equals(other.toString());
}
public int getMaxSize() {
return maxSize;
}
public int getSize() {
return size;
}
@Override
public String toString() {
final StringBuilder result = new StringBuilder("[");
for (int i = 0; i < this.size - 1; i++) {
result.append(this.data[(this.head - i - 1 < 0) ? (this.head - i - 1 + this.maxSize) : (this.head - i - 1)]).append(",");
}
result.append(this.data[(this.head - this.size < 0) ? (this.head - this.size + this.maxSize) : (this.head - this.size)]);
result.append("]");
return result.toString();
}
}

View File

@ -0,0 +1,77 @@
/*
*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.world;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.CraftbukkitWrapper;
import de.steamwar.bausystem.commands.CommandTPSLimiter;
import de.steamwar.core.TPSWatcher;
import org.bukkit.Bukkit;
import java.util.function.Supplier;
public class TPSUtils {
private TPSUtils() {
throw new IllegalStateException("Utility Class");
}
private static boolean warp = true;
private static long nanoOffset = 0;
private static long nanoDOffset = 0;
public static void disableWarp() {
warp = false;
}
public static long getNanoOffset() {
return nanoOffset;
}
private static long ticksSinceServerStart = 0;
public static final Supplier<Long> currentTick = () -> ticksSinceServerStart;
public static void init() {
CraftbukkitWrapper.impl.initTPS();
Bukkit.getScheduler().runTaskTimer(BauSystem.getPlugin(), () -> nanoOffset += nanoDOffset, 1, 1);
Bukkit.getScheduler().runTaskTimer(BauSystem.getPlugin(), () -> ticksSinceServerStart++, 1, 1);
}
public static void setTPS(double tps) {
double d = 50 - (50 / (tps / 20.0));
nanoDOffset = Math.max(0, Math.min((long) (d * 1000000), 37500000));
}
public static boolean isWarpAllowed() {
return warp;
}
public static boolean isWarping() {
return nanoDOffset > 0;
}
public static double getTps(TPSWatcher.TPSType tpsType) {
if (TPSUtils.isWarping())
return TPSWatcher.getTPS(tpsType, Math.max(CommandTPSLimiter.getCurrentTPSLimit(), 20));
return TPSWatcher.getTPS(tpsType);
}
}

View File

@ -0,0 +1,51 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.world;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.Permission;
import de.steamwar.sql.BauweltMember;
import org.bukkit.entity.Player;
public class Welt {
private Welt() {
}
public static boolean noPermission(Player member, Permission perm) {
if (member.getUniqueId().equals(BauSystem.getOwner()))
return false;
BauweltMember member1 = BauweltMember.getBauMember(BauSystem.getOwner(), member.getUniqueId());
if (member1 == null)
return true;
switch (perm) {
case WORLDEDIT:
return !member1.isWorldEdit();
case WORLD:
return !member1.isWorld();
case MEMBER:
return false;
default:
return true;
}
}
}

View File

@ -0,0 +1,64 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.world.regions;
import org.bukkit.Location;
public class GlobalRegion extends Region {
private static final GlobalRegion GLOBAL_REGION = new GlobalRegion();
public static GlobalRegion getInstance() {
return GLOBAL_REGION;
}
public static boolean isGlobalRegion(Region region) {
return region == GLOBAL_REGION;
}
public GlobalRegion() {
super("Global");
}
@Override
public boolean inRegion(Location l, RegionType regionType, RegionExtensionType regionExtensionType) {
return true;
}
@Override
public boolean hasBuildRegion() {
return false;
}
@Override
public boolean hasTestblock() {
return false;
}
@Override
public boolean hasProtection() {
return false;
}
@Override
public boolean hasExtensionArea(RegionType regionType) {
return false;
}
}

View File

@ -0,0 +1,99 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.world.regions;
import de.steamwar.bausystem.world.Color;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class PasteOptions {
/**
* Used in 1.12 and 1.15
*/
private boolean rotate = false;
/**
* Used in 1.12 and 1.15
*/
private boolean ignoreAir = false;
/**
* Used in 1.15
*/
private Color color = Color.YELLOW;
/**
* Used in 1.15
*/
private boolean reset = false;
/**
* Used in 1.15
*/
private Point minPoint = null;
/**
* Used in 1.15
*/
private Point maxPoint = null;
/**
* Used in 1.15
*/
private int waterLevel = 0;
public PasteOptions(boolean rotate) {
this.rotate = rotate;
}
public PasteOptions(boolean rotate, Color color) {
this.rotate = rotate;
this.color = color;
}
public PasteOptions(boolean rotate, boolean ignoreAir) {
this.rotate = rotate;
this.ignoreAir = ignoreAir;
}
public PasteOptions(boolean rotate, boolean ignoreAir, boolean reset) {
this.rotate = rotate;
this.ignoreAir = ignoreAir;
this.reset = reset;
}
public PasteOptions(boolean rotate, Color color, boolean reset) {
this.rotate = rotate;
this.color = color;
this.reset = reset;
}
public PasteOptions(boolean rotate, boolean ignoreAir, Color color) {
this.rotate = rotate;
this.ignoreAir = ignoreAir;
this.color = color;
}
}

View File

@ -0,0 +1,31 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.world.regions;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public class Point {
final int x;
final int y;
final int z;
}

View File

@ -0,0 +1,204 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.world.regions;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.extent.clipboard.Clipboard;
import de.steamwar.bausystem.WorldeditWrapper;
import de.steamwar.bausystem.world.Color;
import de.steamwar.sql.NoClipboardException;
import de.steamwar.sql.SchematicData;
import de.steamwar.sql.SchematicNode;
import org.bukkit.Location;
import org.bukkit.configuration.ConfigurationSection;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class Prototype {
static final Map<String, Prototype> prototypes = new HashMap<>();
private final int sizeX;
private final int sizeY;
private final int sizeZ;
private final int offsetX;
private final int offsetY;
private final int offsetZ;
private final int extensionPositiveZ;
private final int extensionNegativeZ;
private final int extensionPositiveY;
private final int extensionAxisX;
final boolean extensionPrototypeArea;
private final int waterLevel;
private final String schematic;
private final boolean rotate;
final Prototype testblock; //nullable
final Prototype buildArea; //nullable
private final String protectSchematic; //nullable
Prototype(ConfigurationSection config) {
sizeX = config.getInt("sizeX");
sizeY = config.getInt("sizeY");
sizeZ = config.getInt("sizeZ");
schematic = config.getString("schematic");
offsetX = config.getInt("offsetX", 0);
offsetY = config.getInt("offsetY", 0);
offsetZ = config.getInt("offsetZ", 0);
extensionPositiveZ = config.getInt("extensionPositiveZ", 0);
extensionNegativeZ = config.getInt("extensionNegativeZ", 0);
extensionPositiveY = config.getInt("extensionPositiveY", 0);
extensionAxisX = config.getInt("extensionAxisX", 0);
if (config.contains("extensionPositiveZ") || config.contains("extensionNegativeZ") || config.contains("extensionPositiveY") || config.contains("extensionAxisX")) {
Region.extensionArea = true;
}
extensionPrototypeArea = extensionNegativeZ != 0 || extensionPositiveZ != 0 || extensionPositiveY != 0 || extensionAxisX != 0;
waterLevel = config.getInt("waterLevel", 0);
rotate = config.getBoolean("rotate", false);
ConfigurationSection testblockSection = config.getConfigurationSection("testblock");
testblock = testblockSection != null ? new Prototype(testblockSection) : null;
ConfigurationSection buildAreaSection = config.getConfigurationSection("buildArea");
buildArea = buildAreaSection != null ? new Prototype(buildAreaSection) : null;
if (buildArea != null) {
Region.buildArea = true;
}
protectSchematic = config.getString("protection", null);
if (!config.getName().equals("testblock") && !config.getName().equals("buildArea"))
prototypes.put(config.getName(), this);
}
public Point getMinPoint(Region region, RegionExtensionType regionExtensionType) {
switch (regionExtensionType) {
case EXTENSION:
return new Point(
region.minPoint.getX() + offsetX - extensionAxisX,
region.minPoint.getY() + offsetY,
region.minPoint.getZ() + offsetZ - extensionNegativeZ
);
default:
case NORMAL:
return new Point(
region.minPoint.getX() + offsetX,
region.minPoint.getY() + offsetY,
region.minPoint.getZ() + offsetZ
);
}
}
public Point getMaxPoint(Region region, RegionExtensionType regionExtensionType) {
switch (regionExtensionType) {
case EXTENSION:
return new Point(
region.minPoint.getX() + offsetX - extensionAxisX + (sizeX + extensionAxisX * 2) - 1,
region.minPoint.getY() + offsetY + sizeY + extensionPositiveY - 1,
region.minPoint.getZ() + offsetZ - extensionNegativeZ + (sizeZ + extensionNegativeZ + extensionPositiveZ) - 1
);
default:
case NORMAL:
return new Point(
region.minPoint.getX() + offsetX + sizeX - 1,
region.minPoint.getY() + offsetY + sizeY - 1,
region.minPoint.getZ() + offsetZ + sizeZ - 1
);
}
}
public boolean inRegion(Region region, Location l, RegionExtensionType regionExtensionType) {
switch (regionExtensionType) {
case EXTENSION:
return inRange(l.getX(), region.minPoint.getX() + offsetX - extensionAxisX, sizeX + extensionAxisX * 2) &&
inRange(l.getY(), region.minPoint.getY() + offsetY, sizeY + extensionPositiveY) &&
inRange(l.getZ(), region.minPoint.getZ() + offsetZ - extensionNegativeZ, sizeZ + extensionNegativeZ + extensionPositiveZ);
default:
case NORMAL:
return inRange(l.getX(), region.minPoint.getX() + offsetX, sizeX) &&
inRange(l.getY(), region.minPoint.getY() + offsetY, sizeY) &&
inRange(l.getZ(), region.minPoint.getZ() + offsetZ, sizeZ);
}
}
public EditSession reset(Region region, SchematicNode schem, boolean ignoreAir, Color color) throws IOException, NoClipboardException {
return reset(region, schem, ignoreAir, color, false);
}
public EditSession reset(Region region, SchematicNode schem, boolean ignoreAir, Color color, boolean reset) throws IOException, NoClipboardException {
PasteOptions pasteOptions;
if (reset) {
pasteOptions = new PasteOptions(rotate ^ (schem != null && (schem.getSchemtype().fightType() || schem.getSchemtype().check())), ignoreAir, color, true, getMinPoint(region, RegionExtensionType.EXTENSION), getMaxPoint(region, RegionExtensionType.EXTENSION), waterLevel);
} else {
pasteOptions = new PasteOptions(rotate ^ (schem != null && (schem.getSchemtype().fightType() || schem.getSchemtype().check())), ignoreAir, color);
}
int x = region.minPoint.getX() + offsetX + sizeX / 2;
int y = region.minPoint.getY() + offsetY;
int z = region.minPoint.getZ() + offsetZ + sizeZ / 2;
if (schem == null) {
return paste(new File(schematic), x, y, z, pasteOptions);
} else {
return paste(new SchematicData(schem).load(), x, y, z, pasteOptions);
}
}
public boolean hasProtection() {
return protectSchematic != null;
}
public EditSession protect(Region region, SchematicNode schem) throws IOException, NoClipboardException {
int x = region.minPoint.getX() + offsetX + sizeX / 2;
int y = region.minPoint.getY() + testblock.offsetY - 1;
int z = region.minPoint.getZ() + offsetZ + sizeZ / 2;
if (schem == null) {
return paste(new File(protectSchematic), x, y, z, new PasteOptions(rotate, false, Color.YELLOW));
} else {
return paste(new SchematicData(schem).load(), x, y, z, new PasteOptions(rotate, false, Color.YELLOW));
}
}
public boolean hasTestblock() {
return testblock != null;
}
public EditSession resetTestblock(Region region, SchematicNode schem, Color color, boolean reset) throws IOException, NoClipboardException {
return testblock.reset(region, schem, false, color, reset && waterLevel == 0);
}
private static boolean inRange(double l, int min, int size) {
return min <= l && l < min + size;
}
private static EditSession paste(File file, int x, int y, int z, PasteOptions pasteOptions) { //Type of protect
return WorldeditWrapper.impl.paste(file, x, y, z, pasteOptions);
}
private static EditSession paste(Clipboard clipboard, int x, int y, int z, PasteOptions pasteOptions) {
return WorldeditWrapper.impl.paste(clipboard, x, y, z, pasteOptions);
}
}

View File

@ -0,0 +1,388 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.world.regions;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSyntaxException;
import com.sk89q.worldedit.EditSession;
import de.steamwar.bausystem.commands.CommandTNT.TNTMode;
import de.steamwar.bausystem.world.Color;
import de.steamwar.bausystem.world.SizedStack;
import de.steamwar.sql.NoClipboardException;
import de.steamwar.sql.SchematicNode;
import lombok.Getter;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.logging.Level;
public class Region {
private static final List<Region> regions = new ArrayList<>();
static boolean buildArea = false;
static boolean extensionArea = false;
private static JsonObject regionsObject = new JsonObject();
static {
File regionsFile = new File(Bukkit.getWorlds().get(0).getWorldFolder(), "regions.json");
if (regionsFile.exists()) {
try {
regionsObject = new JsonParser().parse(new FileReader(regionsFile)).getAsJsonObject();
} catch (JsonSyntaxException | IOException e) {
Bukkit.getLogger().log(Level.WARNING, "Item JSON error");
}
}
YamlConfiguration config = new YamlConfiguration();
try {
config.load(new File(Bukkit.getWorlds().get(0).getWorldFolder(), "sections.yml"));
} catch (InvalidConfigurationException | IOException e) {
Bukkit.getLogger().log(Level.SEVERE, "Failed to load sections.yml", e);
}
ConfigurationSection prototypes = config.getConfigurationSection("prototypes");
assert prototypes != null;
for (String prototype : prototypes.getKeys(false)) {
new Prototype(Objects.requireNonNull(prototypes.getConfigurationSection(prototype)));
}
ConfigurationSection regions = config.getConfigurationSection("regions");
assert regions != null;
for (String region : regions.getKeys(false)) {
new Region(Objects.requireNonNull(regions.getConfigurationSection(region)));
}
}
public static boolean buildAreaEnabled() {
return buildArea;
}
public static boolean extensionAreaEnabled() {
return extensionArea;
}
public static Region getRegion(Location location) {
for (Region region : regions) {
if (region.inRegion(location, RegionType.NORMAL, RegionExtensionType.NORMAL)) {
return region;
}
}
return GlobalRegion.getInstance();
}
public static void setGlobalColor(Color color) {
for (Region region : regions) {
region.setColor(color);
}
}
public static void save() {
File colorsFile = new File(Bukkit.getWorlds().get(0).getWorldFolder(), "regions.json");
if (!colorsFile.exists()) {
try {
colorsFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
return;
}
}
try (FileOutputStream fileOutputStream = new FileOutputStream(colorsFile)) {
fileOutputStream.write(regionsObject.toString().getBytes());
} catch (IOException e) {
e.printStackTrace();
// Ignored
}
}
private final String name;
final Point minPoint;
private final Prototype prototype;
private final String optionsLinkedWith; // nullable
private Region linkedRegion = null; // nullable
private SizedStack<EditSession> undosessions;
private SizedStack<EditSession> redosessions;
private JsonObject regionOptions = new JsonObject();
@Getter
private TNTMode tntMode = Region.buildAreaEnabled() ? TNTMode.ONLY_TB : TNTMode.OFF;
@Getter
private boolean freeze = false;
@Getter
private boolean fire = false;
@Getter
private boolean protect = false;
@Getter
private Color color = Color.YELLOW;
private Region(ConfigurationSection config) {
name = config.getName();
minPoint = new Point(config.getInt("minX"), config.getInt("minY"), config.getInt("minZ"));
prototype = Prototype.prototypes.get(config.getString("prototype"));
optionsLinkedWith = config.getString("optionsLinkedWith", null);
if (!hasTestblock()) tntMode = TNTMode.OFF;
regions.add(this);
load();
}
public Region(String name) {
this.name = name;
this.minPoint = new Point(0, 0, 0);
this.prototype = null;
this.optionsLinkedWith = null;
tntMode = TNTMode.OFF;
load();
}
private void load() {
if (regionsObject.has(name)) {
regionOptions = regionsObject.getAsJsonObject(name);
if (regionOptions.has("tnt")) {
String tntName = regionsObject.getAsJsonObject(name).getAsJsonPrimitive("tnt").getAsString();
try {
tntMode = TNTMode.valueOf(tntName);
} catch (Exception e) {
// Ignored
}
}
if (regionOptions.has("fire")) {
fire = regionOptions.getAsJsonPrimitive("fire").getAsBoolean();
}
if (regionOptions.has("freeze")) {
freeze = regionOptions.getAsJsonPrimitive("freeze").getAsBoolean();
}
if (regionOptions.has("protect")) {
protect = regionOptions.getAsJsonPrimitive("protect").getAsBoolean();
}
if (regionOptions.has("color")) {
String colorName = regionOptions.getAsJsonPrimitive("color").getAsString();
try {
color = Color.valueOf(colorName);
} catch (Exception e) {
// Ignored
}
}
} else {
regionsObject.add(name, regionOptions);
}
}
public void setColor(Color color) {
this.color = color;
regionOptions.add("color", new JsonPrimitive(color.name()));
}
private void setLinkedRegion(Consumer<Region> regionConsumer) {
if (optionsLinkedWith == null) {
return;
}
if (linkedRegion != null) {
regionConsumer.accept(linkedRegion);
return;
}
for (Region region : regions) {
if (region.name.equals(name)) {
linkedRegion = region;
regionConsumer.accept(linkedRegion);
return;
}
}
}
public void setTntMode(TNTMode tntMode) {
this.tntMode = tntMode;
setLinkedRegion(region -> {
region.tntMode = tntMode;
region.regionOptions.add("tnt", new JsonPrimitive(tntMode.name()));
});
regionOptions.add("tnt", new JsonPrimitive(tntMode.name()));
}
public void setFreeze(boolean freeze) {
this.freeze = freeze;
setLinkedRegion(region -> {
region.freeze = freeze;
region.regionOptions.add("freeze", new JsonPrimitive(freeze));
});
regionOptions.add("freeze", new JsonPrimitive(freeze));
}
public void setFire(boolean fire) {
this.fire = fire;
setLinkedRegion(region -> {
region.fire = fire;
region.regionOptions.add("fire", new JsonPrimitive(fire));
});
regionOptions.add("fire", new JsonPrimitive(fire));
}
public void setProtect(boolean protect) {
this.protect = protect;
setLinkedRegion(region -> {
region.protect = protect;
region.regionOptions.add("protect", new JsonPrimitive(protect));
});
regionOptions.add("protect", new JsonPrimitive(protect));
}
public Point getMinPoint(RegionType regionType, RegionExtensionType regionExtensionType) {
switch (regionType) {
case BUILD:
return prototype.buildArea.getMinPoint(this, regionExtensionType);
case TESTBLOCK:
return prototype.testblock.getMinPoint(this, regionExtensionType);
default:
case NORMAL:
return prototype.getMinPoint(this, regionExtensionType);
}
}
public Point getMaxPoint(RegionType regionType, RegionExtensionType regionExtensionType) {
switch (regionType) {
case BUILD:
return prototype.buildArea.getMaxPoint(this, regionExtensionType);
case TESTBLOCK:
return prototype.testblock.getMaxPoint(this, regionExtensionType);
default:
case NORMAL:
return prototype.getMaxPoint(this, regionExtensionType);
}
}
public boolean inRegion(Location l, RegionType regionType, RegionExtensionType regionExtensionType) {
switch (regionType) {
case BUILD:
return prototype.buildArea.inRegion(this, l, regionExtensionType);
case TESTBLOCK:
return prototype.testblock.inRegion(this, l, regionExtensionType);
default:
case NORMAL:
return prototype.inRegion(this, l, regionExtensionType);
}
}
public boolean hasBuildRegion() {
return prototype.buildArea != null;
}
public void reset(SchematicNode schem, boolean ignoreAir) throws IOException, NoClipboardException {
initSessions();
undosessions.push(prototype.reset(this, schem, ignoreAir, color));
}
public boolean hasTestblock() {
return prototype.hasTestblock();
}
public void resetTestblock(SchematicNode schem, boolean reset) throws IOException, NoClipboardException {
initSessions();
undosessions.push(prototype.resetTestblock(this, schem, color, reset));
}
public boolean hasProtection() {
return prototype.hasProtection();
}
public void protect(SchematicNode schem) throws IOException, NoClipboardException {
initSessions();
undosessions.push(prototype.protect(this, schem));
}
public int getProtectYLevel() {
return getMinPoint(RegionType.TESTBLOCK, RegionExtensionType.NORMAL).getY();
}
public boolean hasExtensionArea(RegionType regionType) {
switch (regionType) {
case BUILD:
return prototype.buildArea.extensionPrototypeArea;
case TESTBLOCK:
return prototype.testblock.extensionPrototypeArea;
default:
case NORMAL:
return prototype.extensionPrototypeArea;
}
}
private void initSessions() {
if (undosessions == null) {
undosessions = new SizedStack<>(20);
redosessions = new SizedStack<>(20);
}
}
public boolean undo() {
initSessions();
EditSession session = null;
try {
session = undosessions.pop();
if (session == null) {
return false;
}
session.undo(session);
redosessions.push(session);
return true;
} finally {
if (session != null) {
session.flushQueue();
}
}
}
public boolean redo() {
initSessions();
EditSession session = null;
try {
session = redosessions.pop();
if (session == null) {
return false;
}
session.redo(session);
undosessions.push(session);
return true;
} finally {
if (session != null) {
session.flushQueue();
}
}
}
}

View File

@ -0,0 +1,25 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.world.regions;
public enum RegionExtensionType {
NORMAL,
EXTENSION
}

View File

@ -0,0 +1,25 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.world.regions;
public enum RegionSelectionType {
GLOBAL,
LOCAL
}

View File

@ -0,0 +1,26 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bausystem.world.regions;
public enum RegionType {
NORMAL,
BUILD,
TESTBLOCK
}

View File

@ -0,0 +1,9 @@
name: BauSystem
authors: [Lixfel, YoyoNow, Chaoscaot, Zeanon]
version: "1.0"
depend: [WorldEdit, SpigotCore]
load: POSTWORLD
main: de.steamwar.bausystem.BauSystem
api-version: "1.13"
website: "https://steamwar.de"
description: "So unseriös wie wir sind: BauSystem nur besser. Jaja"

View File

@ -207,6 +207,8 @@ include(
include("KotlinCore") include("KotlinCore")
include("LegacyBauSystem")
include("LobbySystem") include("LobbySystem")
include("MissileWars") include("MissileWars")

View File

@ -4,6 +4,7 @@ build:
artifacts: artifacts:
"/jars/BauSystem.jar": "BauSystem/build/libs/BauSystem-all.jar" "/jars/BauSystem.jar": "BauSystem/build/libs/BauSystem-all.jar"
"/jars/BauSystem-1.12.jar": "LegacyBauSystem/build/libs/LegacyBauSystem.jar"
"/jars/FightSystem.jar": "FightSystem/build/libs/FightSystem-all.jar" "/jars/FightSystem.jar": "FightSystem/build/libs/FightSystem-all.jar"
#"/binarys/FightSystem_Standalone.jar": "FightSystem/FightSystem_Standalone/build/libs/FightSystem_Standalone-all.jar" #"/binarys/FightSystem_Standalone.jar": "FightSystem/FightSystem_Standalone/build/libs/FightSystem_Standalone-all.jar"