diff --git a/src/main/java/net/doubledoordev/d3core/D3Core.java b/src/main/java/net/doubledoordev/d3core/D3Core.java index 95a0ced..d784c9e 100644 --- a/src/main/java/net/doubledoordev/d3core/D3Core.java +++ b/src/main/java/net/doubledoordev/d3core/D3Core.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, + * Copyright (c) 2014-2016, Dries007 & DoubleDoorDevelopment * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -12,7 +12,7 @@ * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - * Neither the name of the {organization} nor the names of its + * Neither the name of DoubleDoorDevelopment nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * @@ -27,75 +27,56 @@ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * - * */ package net.doubledoordev.d3core; -import net.minecraftforge.fml.client.config.IConfigElement; +import net.doubledoordev.d3core.util.*; +import net.minecraft.client.resources.I18n; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.common.config.Configuration; +import net.minecraftforge.common.config.Property; import net.minecraftforge.fml.client.event.ConfigChangedEvent; -import net.minecraftforge.fml.common.*; +import net.minecraftforge.fml.common.FMLCommonHandler; +import net.minecraftforge.fml.common.ICrashCallable; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.common.ModMetadata; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.event.FMLServerStartingEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; -import net.minecraftforge.fml.common.gameevent.PlayerEvent; - -import net.minecraft.util.text.ITextComponent; -import net.minecraft.util.text.translation.I18n; -import net.minecraftforge.fml.common.versioning.ArtifactVersion; -import net.minecraftforge.fml.common.versioning.DefaultArtifactVersion; -import net.doubledoordev.d3core.permissions.PermissionsDB; -import net.doubledoordev.d3core.util.*; -import net.doubledoordev.d3core.util.libs.org.mcstats.Metrics; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.common.config.ConfigElement; -import net.minecraftforge.common.config.Configuration; -import net.minecraftforge.common.config.Property; -import org.apache.commons.io.FileUtils; import org.apache.logging.log4j.Logger; -import org.w3c.dom.Document; -import org.w3c.dom.NodeList; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; import java.io.File; import java.io.IOException; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; -import java.util.TreeSet; +import java.util.Calendar; import static net.doubledoordev.d3core.util.CoreConstants.*; -import static net.doubledoordev.d3core.util.FMLEventHandler.FML_EVENT_HANDLER; -import static net.doubledoordev.d3core.util.ForgeEventHandler.FORGE_EVENT_HANDLER; import static net.doubledoordev.d3core.util.VoidRefunds.VOID_REFUNDS; /** * @author Dries007 */ -@Mod(modid = MODID, name = NAME, canBeDeactivated = false, guiFactory = MOD_GUI_FACTORY) -public class D3Core implements ID3Mod +@Mod(modid = MODID, name = NAME, updateJSON = UPDATE_URL, guiFactory = MOD_GUI_FACTORY) +public class D3Core { + @SuppressWarnings("WeakerAccess") @Mod.Instance(MODID) public static D3Core instance; - public static boolean aprilFools = true; - private File folder; @Mod.Metadata private ModMetadata metadata; - private Logger logger; - private DevPerks devPerks; + private Logger logger; + private DevPerks devPerks; private Configuration configuration; + private File folder; - private boolean debug = false; - private boolean sillyness = true; - private boolean updateWarning = true; + private boolean debug = false; + private boolean silliness = true; + private boolean aprilFools = true; - private List d3Mods = new ArrayList<>(); - private List updateDateList = new ArrayList<>(); private boolean pastPost; @Mod.EventHandler @@ -103,198 +84,80 @@ public void preInit(FMLPreInitializationEvent event) { logger = event.getModLog(); - FMLCommonHandler.instance().bus().register(this); - FMLCommonHandler.instance().bus().register(FML_EVENT_HANDLER); - FMLCommonHandler.instance().bus().register(VOID_REFUNDS); - MinecraftForge.EVENT_BUS.register(FORGE_EVENT_HANDLER); + MinecraftForge.EVENT_BUS.register(this); + MinecraftForge.EVENT_BUS.register(EventHandler.I); MinecraftForge.EVENT_BUS.register(VOID_REFUNDS); folder = new File(event.getModConfigurationDirectory(), MODID); + //noinspection ResultOfMethodCallIgnored folder.mkdir(); - File configFile = new File(folder, event.getSuggestedConfigurationFile().getName()); - if (event.getSuggestedConfigurationFile().exists()) - { - try + configuration = new Configuration(new File(folder, event.getSuggestedConfigurationFile().getName())); + updateConfig(); + + FMLCommonHandler.instance().registerCrashCallable(new ICrashCallable() { + @Override + public String getLabel() { - FileUtils.copyFile(event.getSuggestedConfigurationFile(), configFile); - event.getSuggestedConfigurationFile().delete(); + return MODID; } - catch (IOException e) + + @Override + public String call() throws Exception { - e.printStackTrace(); + return "Debug: " + debug + " Silliness: " + silliness + " AprilFools: " + aprilFools + " PastPost:" + pastPost; } - } - configuration = new Configuration(configFile); - syncConfig(); - - PermissionsDB.load(); + }); } @Mod.EventHandler public void init(FMLInitializationEvent event) throws IOException { Materials.load(); - - final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - for (final ModContainer modContainer : Loader.instance().getActiveModList()) - { - if (modContainer instanceof FMLModContainer && modContainer.getMod() instanceof ID3Mod) - { - if (debug()) logger.info(String.format("[%s] Found a D3 Mod!", modContainer.getModId())); - d3Mods.add(modContainer); - if (!updateWarning) continue; - - new Thread(new Runnable() - { - @Override - public void run() - { - try - { - TreeSet availableVersions = new TreeSet<>(); - - String group = modContainer.getMod().getClass().getPackage().getName(); - String artifactId = modContainer.getName(); - if (debug()) logger.info(String.format("[%s] Group: %s ArtifactId: %s", modContainer.getModId(), group, artifactId)); - - URL url = new URL(MAVENURL + group.replace('.', '/') + '/' + artifactId + "/maven-metadata.xml"); - if (debug()) logger.info(String.format("[%s] Maven URL: %s", modContainer.getModId(), url)); - - DocumentBuilder builder = dbf.newDocumentBuilder(); - Document document = builder.parse(url.toURI().toString()); - NodeList list = document.getDocumentElement().getElementsByTagName("version"); - for (int i = 0; i < list.getLength(); i++) - { - String version = list.item(i).getFirstChild().getNodeValue(); - if (version.startsWith(Loader.MC_VERSION + "-")) - { - availableVersions.add(new DefaultArtifactVersion(version.replace(Loader.MC_VERSION + "-", ""))); - } - } - DefaultArtifactVersion current = new DefaultArtifactVersion(modContainer.getVersion().replace(Loader.MC_VERSION + "-", "")); - - if (debug()) logger.info(String.format("[%s] Current: %s Latest: %s All versions for MC %s: %s", modContainer.getModId(), current, availableVersions.last(), Loader.MC_VERSION, availableVersions)); - - if (current.compareTo(availableVersions.last()) < 0) - { - updateDateList.add(new CoreHelper.ModUpdateDate(modContainer.getName(), modContainer.getModId(), current.toString(), availableVersions.last().toString())); - } - } - catch (Exception e) - { - logger.info("D3 Mod " + modContainer.getModId() + " Version check FAILED. Error: " + e.toString()); - } - } - }).start(); - } - } - - try - { - Metrics metrics = new Metrics(MODID, metadata.version); - - Metrics.Graph submods = metrics.createGraph("Submods"); - for (ModContainer modContainer : d3Mods) - { - submods.addPlotter(new Metrics.Plotter(modContainer.getModId()) { - @Override - public int getValue() - { - return 1; - } - }); - } - - for (ModContainer modContainer : d3Mods) - { - metrics.createGraph(modContainer.getModId()).addPlotter(new Metrics.Plotter(modContainer.getDisplayVersion()) { - @Override - public int getValue() - { - return 1; - } - }); - } - - metrics.start(); - } - catch (Exception e) - { - e.printStackTrace(); - } } @Mod.EventHandler public void postInit(FMLPostInitializationEvent event) { - for (CoreHelper.ModUpdateDate updateDate : updateDateList) - { - logger.warn(String.format("Update available for %s (%s)! Current version: %s New version: %s. Please update ASAP!", updateDate.getName(), updateDate.getModId(), updateDate.getCurrentVersion(), updateDate.getLatestVersion())); - } - EndermanGriefing.init(); pastPost = true; - - PermissionsDB.save(); } @Mod.EventHandler public void serverStarting(FMLServerStartingEvent event) { - //event.registerServerCommand(new CommandGroup()); event.registerServerCommand(new CommandSetLoginMessage()); } @SubscribeEvent - public void nameFormatEvent(PlayerEvent.PlayerLoggedInEvent event) + public void onConfigChanged(ConfigChangedEvent.OnConfigChangedEvent event) { - if (!updateWarning || updateDateList.isEmpty()) return; - - event.player.addChatComponentMessage(ITextComponent.Serializer.jsonToComponent("{\"text\":\"\",\"extra\":[{\"text\":\"Updates available for these mods:\",\"color\":\"gold\"}]}")); - for (CoreHelper.ModUpdateDate updateDate : updateDateList) - { - event.player.addChatComponentMessage(ITextComponent.Serializer.jsonToComponent(String.format("{\"text\":\"\",\"extra\":[{\"text\":\"%s: %s -> %s\"}]}", updateDate.getName(), updateDate.getCurrentVersion(), updateDate.getLatestVersion()))); - } - event.player.addChatComponentMessage(ITextComponent.Serializer.jsonToComponent("{\"text\":\"\",\"extra\":[{\"text\":\"Download here!\",\"color\":\"gold\",\"clickEvent\":{\"action\":\"open_url\",\"value\":\"http://doubledoordev.net\"}},{\"text\":\" <- That is a link btw :p\"}]}")); + if (event.getModID().equals(MODID)) updateConfig(); } - @SubscribeEvent - public void onConfigChanged(ConfigChangedEvent.OnConfigChangedEvent eventArgs) + private void updateConfig() { - for (ModContainer modContainer : Loader.instance().getActiveModList()) - { - if (modContainer.getMod() instanceof ID3Mod) - { - ((ID3Mod) modContainer.getMod()).syncConfig(); - } - } - } - - @Override - public void syncConfig() - { - configuration.setCategoryLanguageKey(MODID, "d3.core.config.core").setCategoryComment(MODID, I18n.translateToLocal("d3.core.config.core")); - - debug = configuration.getBoolean("debug", MODID, debug, "Enable debug mode", "d3.core.config.debug"); - sillyness = configuration.getBoolean("sillyness", MODID, sillyness, "Enable sillyness\nBut seriously, you can disable name changes, drops and block helmets with this setting.", "d3.core.config.sillyness"); - updateWarning = configuration.getBoolean("updateWarning", MODID, updateWarning, "Allow update warnings on login", "d3.core.config.updateWarning"); - FML_EVENT_HANDLER.norain = configuration.getBoolean("norain", MODID, FML_EVENT_HANDLER.norain, "No more rain if set to true.", "d3.core.config.norain"); - FML_EVENT_HANDLER.insomnia = configuration.getBoolean("insomnia", MODID, FML_EVENT_HANDLER.insomnia, "No more daytime when players sleep if set to true.", "d3.core.config.insomnia"); - FML_EVENT_HANDLER.lilypad = configuration.getBoolean("lilypad", MODID, FML_EVENT_HANDLER.lilypad, "Spawn the player on a lilypad when in or above water.", "d3.core.config.lilypad"); - FORGE_EVENT_HANDLER.nosleep = configuration.getBoolean("nosleep", MODID, FORGE_EVENT_HANDLER.nosleep, "No sleep at all", "d3.core.config.nosleep"); - FORGE_EVENT_HANDLER.printDeathCoords = configuration.getBoolean("printDeathCoords", MODID, FORGE_EVENT_HANDLER.printDeathCoords, "Print your death coordinates in chat (client side)", "d3.core.config.printDeathCoords"); - FORGE_EVENT_HANDLER.claysTortureMode = configuration.getBoolean("claysTortureMode", MODID, FORGE_EVENT_HANDLER.claysTortureMode, "Deletes all drops on death.", "d3.core.config.claystorturemode"); + configuration.setCategoryLanguageKey(MODID, "d3.core.config.core").setCategoryComment(MODID, I18n.format("d3.core.config.core")); + + debug = configuration.getBoolean("isDebug", MODID, debug, "Enable isDebug mode", "d3.core.config.isDebug"); + silliness = configuration.getBoolean("silliness", MODID, silliness, "Enable silliness\nBut seriously, you can disable name changes, drops and block helmets with this setting.", "d3.core.config.silliness"); + EventHandler.I.norain = configuration.getBoolean("norain", MODID, EventHandler.I.norain, "No more rain if set to true.", "d3.core.config.norain"); + EventHandler.I.insomnia = configuration.getBoolean("insomnia", MODID, EventHandler.I.insomnia, "No more daytime when players sleep if set to true.", "d3.core.config.insomnia"); + EventHandler.I.lilypad = configuration.getBoolean("lilypad", MODID, EventHandler.I.lilypad, "Spawn the player on a lilypad when in or above water.", "d3.core.config.lilypad"); + EventHandler.I.achievementFireworks = configuration.getBoolean("achievementFireworks", MODID, EventHandler.I.achievementFireworks, "Achievement = Fireworks", "d3.core.config.achievementFireworks"); + EventHandler.I.nosleep = configuration.getBoolean("nosleep", MODID, EventHandler.I.nosleep, "No sleep at all", "d3.core.config.nosleep"); + EventHandler.I.printDeathCoords = configuration.getBoolean("printDeathCoords", MODID, EventHandler.I.printDeathCoords, "Print your death coordinates in chat (client side)", "d3.core.config.printDeathCoords"); + EventHandler.I.claysTortureMode = configuration.getBoolean("claysTortureMode", MODID, EventHandler.I.claysTortureMode, "Deletes all drops on death.", "d3.core.config.claystorturemode"); aprilFools = configuration.getBoolean("aprilFools", MODID, aprilFools, "What would this do..."); - getDevPerks().update(sillyness); + getDevPerks().update(silliness); final String catTooltips = MODID + ".tooltips"; - configuration.setCategoryLanguageKey(catTooltips, "d3.core.config.tooltips").addCustomCategoryComment(catTooltips, I18n.translateToLocal("d3.core.config.tooltips")); + configuration.setCategoryLanguageKey(catTooltips, "d3.core.config.tooltips").addCustomCategoryComment(catTooltips, I18n.format("d3.core.config.tooltips")); - FORGE_EVENT_HANDLER.enableStringID = configuration.getBoolean("enableStringID", catTooltips, true, "Example: minecraft:gold_ore", "d3.core.config.tooltips.enableStringID"); - FORGE_EVENT_HANDLER.enableUnlocalizedName = configuration.getBoolean("enableUnlocalizedName", catTooltips, true, "Example: tile.oreGold", "d3.core.config.tooltips.enableUnlocalizedName"); - FORGE_EVENT_HANDLER.enableOreDictionary = configuration.getBoolean("enableOreDictionary", catTooltips, true, "Example: oreGold", "d3.core.config.tooltips.enableOreDictionary"); - FORGE_EVENT_HANDLER.enableBurnTime = configuration.getBoolean("enableBurnTime", catTooltips, true, "Example: 300 ticks", "d3.core.config.tooltips.enableBurnTime"); + EventHandler.I.enableStringID = configuration.getBoolean("enableStringID", catTooltips, true, "Example: minecraft:gold_ore", "d3.core.config.tooltips.enableStringID"); + EventHandler.I.enableUnlocalizedName = configuration.getBoolean("enableUnlocalizedName", catTooltips, true, "Example: tile.oreGold", "d3.core.config.tooltips.enableUnlocalizedName"); + EventHandler.I.enableOreDictionary = configuration.getBoolean("enableOreDictionary", catTooltips, true, "Example: oreGold", "d3.core.config.tooltips.enableOreDictionary"); + EventHandler.I.enableBurnTime = configuration.getBoolean("enableBurnTime", catTooltips, true, "Example: 300 ticks", "d3.core.config.tooltips.enableBurnTime"); { final String catEnderGriefing = MODID + ".EndermanGriefing"; @@ -321,28 +184,28 @@ public void syncConfig() if (configuration.hasChanged()) configuration.save(); } - @Override - public void addConfigElements(List list) - { - list.add(new ConfigElement(configuration.getCategory(MODID.toLowerCase()))); - } - public static Logger getLogger() { return instance.logger; } - public static boolean debug() + public static boolean isDebug() { return instance.debug; } - public static Configuration getConfiguration() + public static boolean isAprilFools() + { + //noinspection MagicConstant + return instance.aprilFools && Calendar.getInstance().get(Calendar.MONTH) == Calendar.APRIL && Calendar.getInstance().get(Calendar.DAY_OF_MONTH) == 1; + } + + public static Configuration getConfig() { return instance.configuration; } - public static DevPerks getDevPerks() + private static DevPerks getDevPerks() { if (instance.devPerks == null) instance.devPerks = new DevPerks(); return instance.devPerks; diff --git a/src/main/java/net/doubledoordev/d3core/client/ModConfigGuiFactory.java b/src/main/java/net/doubledoordev/d3core/client/ModConfigGuiFactory.java index 89c3571..20adfb8 100644 --- a/src/main/java/net/doubledoordev/d3core/client/ModConfigGuiFactory.java +++ b/src/main/java/net/doubledoordev/d3core/client/ModConfigGuiFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, + * Copyright (c) 2014-2016, Dries007 & DoubleDoorDevelopment * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -12,7 +12,7 @@ * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - * Neither the name of the {organization} nor the names of its + * Neither the name of DoubleDoorDevelopment nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * @@ -27,18 +27,17 @@ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * - * */ package net.doubledoordev.d3core.client; +import net.doubledoordev.d3core.D3Core; +import net.minecraftforge.common.config.ConfigElement; +import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.client.IModGuiFactory; import net.minecraftforge.fml.client.config.GuiConfig; import net.minecraftforge.fml.client.config.IConfigElement; -import net.minecraftforge.fml.common.Loader; -import net.minecraftforge.fml.common.ModContainer; import net.doubledoordev.d3core.util.CoreConstants; -import net.doubledoordev.d3core.util.ID3Mod; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.resources.I18n; @@ -52,6 +51,7 @@ */ public class ModConfigGuiFactory implements IModGuiFactory { + @SuppressWarnings("WeakerAccess") public static class D3ConfigGuiScreen extends GuiConfig { public D3ConfigGuiScreen(GuiScreen parentScreen) @@ -61,14 +61,22 @@ public D3ConfigGuiScreen(GuiScreen parentScreen) private static List getConfigElements() { - List list = new ArrayList<>(); - for (ModContainer modContainer : Loader.instance().getActiveModList()) + Configuration c = D3Core.getConfig(); + if (c.getCategoryNames().size() == 1) { - if (modContainer.getMod() instanceof ID3Mod) + //noinspection LoopStatementThatDoesntLoop + for (String k : c.getCategoryNames()) { - ((ID3Mod) modContainer.getMod()).addConfigElements(list); + // Let forge do the work, for loop abused to avoid other strange constructs + return new ConfigElement(c.getCategory(k)).getChildElements(); } } + + List list = new ArrayList<>(); + for (String k : c.getCategoryNames()) + { + list.add(new ConfigElement(c.getCategory(k))); + } return list; } } diff --git a/src/main/java/net/doubledoordev/d3core/permissions/Group.java b/src/main/java/net/doubledoordev/d3core/permissions/Group.java deleted file mode 100644 index 314d1c7..0000000 --- a/src/main/java/net/doubledoordev/d3core/permissions/Group.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright (c) 2014, - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * Neither the name of the {organization} nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * - */ - -package net.doubledoordev.d3core.permissions; - -import java.util.HashSet; - -/** - * Permission system stuff - * - * @author Dries007 - */ -public class Group -{ - private HashSet nodes = new HashSet<>(); - private String name; - private String parent; - - public Group() - { - } - - public Group(String name) - { - this.name = name; - } - - public Group(String name, String parent) - { - this.name = name; - this.parent = parent; - } - - public String getName() - { - return name; - } - - public String getParent() - { - return parent; - } - - public void setParent(String parent) - { - this.parent = parent; - } - - public boolean hasPermissionFor(Node requestNode) - { - if (parent != null && PermissionsDB.INSTANCE.getGroup(parent).hasPermissionFor(requestNode)) return true; - for (Node hadNode : nodes) if (hadNode.matches(requestNode)) return true; - return false; - } - - @Override - public int hashCode() - { - int result = nodes.hashCode(); - result = 31 * result + name.hashCode(); - result = 31 * result + parent.hashCode(); - return result; - } - - @Override - public boolean equals(Object o) - { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - Group group = (Group) o; - - return name.equals(group.name) && nodes.equals(group.nodes) && parent.equals(group.parent); - - } - - public void addNode(String nodeString) - { - nodes.add(new Node(nodeString)); - } - - public boolean removeNode(String nodeString) - { - return nodes.remove(new Node(nodeString)); - } - - public HashSet getNodes() - { - HashSet strings = new HashSet<>(); - for (Node node : nodes) strings.add(node.toString()); - return strings; - } -} diff --git a/src/main/java/net/doubledoordev/d3core/permissions/Node.java b/src/main/java/net/doubledoordev/d3core/permissions/Node.java deleted file mode 100644 index 9b935b7..0000000 --- a/src/main/java/net/doubledoordev/d3core/permissions/Node.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (c) 2014, - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * Neither the name of the {organization} nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * - */ - -package net.doubledoordev.d3core.permissions; - -import com.google.gson.*; -import net.doubledoordev.d3core.util.CoreConstants; -import org.apache.commons.lang3.ArrayUtils; - -import java.lang.reflect.Type; -import java.util.Arrays; - -import static net.doubledoordev.d3core.util.CoreConstants.JOINER_DOT; - -/** - * Permission system stuff - * - * @author Dries007 - */ -public class Node -{ - final String[] parts; - - public Node(String parts) - { - this.parts = parts.toLowerCase().split("\\."); - } - - public Node(String... parts) - { - for (int i = 0; i < parts.length; i++) - { - parts[i] = parts[i].toLowerCase(); - } - this.parts = parts; - } - - public boolean matches(Node requestNode) - { - if (this.equals(requestNode)) return true; - for (int i = 0; i < this.parts.length && i < requestNode.parts.length; i++) - { - if (this.parts[i].equals("*")) return true; - if (!this.parts[i].equals(requestNode.parts[i])) return false; - } - return true; - } - - @Override - public int hashCode() - { - return Arrays.hashCode(parts); - } - - @Override - public boolean equals(Object o) - { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - Node node = (Node) o; - - return Arrays.equals(parts, node.parts); - } - - @Override - public String toString() - { - return JOINER_DOT.join(parts); - } - - public Node append(String... extras) - { - return new Node(ArrayUtils.addAll(parts, extras)); - } - - public static class JsonHelper implements JsonSerializer, JsonDeserializer - { - @Override - public Node deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException - { - return new Node((String) context.deserialize(json, String.class)); - } - - @Override - public JsonElement serialize(Node src, Type typeOfSrc, JsonSerializationContext context) - { - return context.serialize(src.toString()); - } - } -} diff --git a/src/main/java/net/doubledoordev/d3core/permissions/PermConstants.java b/src/main/java/net/doubledoordev/d3core/permissions/PermConstants.java deleted file mode 100644 index cda5fcb..0000000 --- a/src/main/java/net/doubledoordev/d3core/permissions/PermConstants.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2014, - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * Neither the name of the {organization} nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * - */ - -package net.doubledoordev.d3core.permissions; - -/** - * @author Dries007 - */ -public class PermConstants -{ - public static final String COMMAND_PREFIX = "cmd"; - public static final String PERMISSIONS_PREFIX = "permissions"; -} diff --git a/src/main/java/net/doubledoordev/d3core/permissions/PermissionsDB.java b/src/main/java/net/doubledoordev/d3core/permissions/PermissionsDB.java deleted file mode 100644 index c16c3a9..0000000 --- a/src/main/java/net/doubledoordev/d3core/permissions/PermissionsDB.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Copyright (c) 2014, - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * Neither the name of the {organization} nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * - */ - -package net.doubledoordev.d3core.permissions; - -import com.mojang.authlib.GameProfile; -import net.doubledoordev.d3core.D3Core; - -import net.minecraft.client.Minecraft; -import net.minecraft.command.ICommandSender; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.network.rcon.RConConsoleSource; -import net.minecraft.server.MinecraftServer; -import net.minecraft.world.World; - -import org.apache.commons.io.FileUtils; -import sun.security.krb5.internal.crypto.Des3; - -import java.io.File; -import java.io.IOException; -import java.util.Collection; -import java.util.HashMap; -import java.util.UUID; - -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.fml.common.FMLCommonHandler; -import net.minecraftforge.fml.common.network.internal.FMLNetworkHandler; - -import static net.doubledoordev.d3core.util.CoreConstants.GSON; - -/** - * Permission system stuff - * - * @author Dries007 - */ -public class PermissionsDB -{ - public static final PermissionsDB INSTANCE = new PermissionsDB(); - - private HashMap playerDB = new HashMap<>(); - private HashMap groupDB = new HashMap<>(); - - private PermissionsDB() - { - - } - - @SuppressWarnings("unchecked") - public static void load() - { - try - { - INSTANCE.playerDB.clear(); - if (getPlayersFile().exists()) INSTANCE.playerDB.putAll(GSON.fromJson(FileUtils.readFileToString(getPlayersFile()), HashMap.class)); - } - catch (IOException e) - { - e.printStackTrace(); - } - try - { - INSTANCE.groupDB.clear(); - if (getGroupsFile().exists()) INSTANCE.groupDB.putAll(GSON.fromJson(FileUtils.readFileToString(getGroupsFile()), HashMap.class)); - } - catch (IOException e) - { - e.printStackTrace(); - } - } - - public static void save() - { - try - { - FileUtils.writeStringToFile(getPlayersFile(), GSON.toJson(INSTANCE.playerDB)); - } - catch (IOException e) - { - e.printStackTrace(); - } - try - { - FileUtils.writeStringToFile(getGroupsFile(), GSON.toJson(INSTANCE.groupDB)); - } - catch (IOException e) - { - e.printStackTrace(); - } - } - - public static File getGroupsFile() - { - return new File(D3Core.getFolder(), "Groups.json"); - } - - public static File getPlayersFile() - { - return new File(D3Core.getFolder(), "Players.json"); - } - - public Group getGroup(String parent) - { - parent = parent.toLowerCase(); - if (groupDB.containsKey(parent)) groupDB.put(parent, new Group(parent)); - return groupDB.get(parent); - } - - public Player getPlayer(UUID uuid) - { - if (!playerDB.containsKey(uuid)) playerDB.put(uuid, new Player(uuid)); - return playerDB.get(uuid); - } - - public Collection getGroups() - { - return groupDB.values(); - } - - public Collection getPlayers() - { - return playerDB.values(); - } - - public boolean checkPermissions(ICommandSender sender, Node node) - { - if (sender.getName().equals(FMLCommonHandler.instance().getMinecraftServerInstance().getServerOwner())) return true; - else if (sender == FMLCommonHandler.instance().getMinecraftServerInstance()) return true; - else if (sender instanceof RConConsoleSource) return true; - else if (sender instanceof EntityPlayer) return checkPermissions(((EntityPlayer) sender).getGameProfile().getId(), node); - - D3Core.getLogger().warn("checkPermissions: " + sender.getName()); // TODO: when does this happends. - return false; - } - - public boolean checkPermissions(UUID uuid, Node node) - { - Player player = getPlayer(uuid); - for (Node hadNode : player.getNodes()) if (hadNode.matches(node)) return true; - for (String groupName : player.getGroups()) if (getGroup(groupName).hasPermissionFor(node)) return true; - return false; - } -} diff --git a/src/main/java/net/doubledoordev/d3core/permissions/Player.java b/src/main/java/net/doubledoordev/d3core/permissions/Player.java deleted file mode 100644 index 91e4c5c..0000000 --- a/src/main/java/net/doubledoordev/d3core/permissions/Player.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright (c) 2014, - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * Neither the name of the {organization} nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * - */ - -package net.doubledoordev.d3core.permissions; - -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonPrimitive; - -import java.util.HashSet; -import java.util.UUID; - -/** - * Permission system stuff - * - * @author Dries007 - */ -public class Player -{ - private HashSet groups = new HashSet<>(); - private HashSet overrideNodes = new HashSet<>(); - private UUID uuid; - - public Player() - { - - } - - public Player(UUID uuid) - { - this.uuid = uuid; - } - - public UUID getUuid() - { - return uuid; - } - - public Iterable getGroups() - { - return groups; - } - - public boolean removeGroup(String group) - { - return groups.remove(group.toLowerCase()); - } - - public void addGroup(String groupName) - { - groups.add(groupName.toLowerCase()); - } - - @Override - public int hashCode() - { - int result = groups.hashCode(); - result = 31 * result + overrideNodes.hashCode(); - result = 31 * result + uuid.hashCode(); - return result; - } - - @Override - public boolean equals(Object o) - { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - Player player = (Player) o; - - return groups.equals(player.groups) && uuid.equals(player.uuid) && overrideNodes.equals(player.overrideNodes); - - } - - public void addNode(Node node) - { - overrideNodes.add(node); - } - - public boolean removeNode(Node node) - { - return overrideNodes.remove(node); - } - - public HashSet getNodes() - { - return overrideNodes; - } -} diff --git a/src/main/java/net/doubledoordev/d3core/permissions/cmd/CommandGroup.java b/src/main/java/net/doubledoordev/d3core/permissions/cmd/CommandGroup.java deleted file mode 100644 index 3a16c5f..0000000 --- a/src/main/java/net/doubledoordev/d3core/permissions/cmd/CommandGroup.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (c) 2014, - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * Neither the name of the {organization} nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * - */ - -package net.doubledoordev.d3core.permissions.cmd; -import net.doubledoordev.d3core.permissions.Node; -import net.minecraft.command.ICommandSender; -import net.minecraft.command.WrongUsageException; -import net.minecraft.server.MinecraftServer; -import net.minecraft.util.text.TextComponentTranslation; - -import static net.doubledoordev.d3core.permissions.PermConstants.PERMISSIONS_PREFIX; - -/** - * @author Dries007 - */ -public class CommandGroup extends CommandPermissionBase -{ - @Override - public String getCommandName() - { - return "d3group"; - } - - @Override - public String getCommandUsage(ICommandSender p_71518_1_) - { - return "commands.d3group.usage"; - } - - @Override - public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws WrongUsageException - { - if (args.length == 0) throw new WrongUsageException(getCommandUsage(sender)); - - switch(args[0].toLowerCase()) - { - case "help": - sender.addChatMessage(new TextComponentTranslation("commands.d3group.help.new")); - sender.addChatMessage(new TextComponentTranslation("commands.d3group.help.remove")); - sender.addChatMessage(new TextComponentTranslation("commands.d3group.help.node.add")); - sender.addChatMessage(new TextComponentTranslation("commands.d3group.help.node.remove")); - sender.addChatMessage(new TextComponentTranslation("commands.d3group.help.parent.set")); - sender.addChatMessage(new TextComponentTranslation("commands.d3group.help.parent.clear")); - break; - default: - throw new WrongUsageException(getCommandUsage(sender)); - } - - } - - @Override - public Node getBasePermission() - { - return new Node(PERMISSIONS_PREFIX.concat(".group")); - } -} diff --git a/src/main/java/net/doubledoordev/d3core/permissions/cmd/CommandPermissionBase.java b/src/main/java/net/doubledoordev/d3core/permissions/cmd/CommandPermissionBase.java deleted file mode 100644 index 0f63a59..0000000 --- a/src/main/java/net/doubledoordev/d3core/permissions/cmd/CommandPermissionBase.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2014, - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * Neither the name of the {organization} nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * - */ - -package net.doubledoordev.d3core.permissions.cmd; - -import net.doubledoordev.d3core.permissions.Node; -import net.doubledoordev.d3core.permissions.PermConstants; -import net.doubledoordev.d3core.permissions.PermissionsDB; -import net.minecraft.command.CommandBase; -import net.minecraft.command.ICommandSender; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.server.MinecraftServer; - -/** - * @author Dries007 - */ -public abstract class CommandPermissionBase extends CommandBase -{ - @Override - public boolean checkPermission(MinecraftServer server, ICommandSender sender) - { - if (sender instanceof EntityPlayer) return PermissionsDB.INSTANCE.checkPermissions(sender, getBasePermission()); - else return super.checkPermission(sender.getServer(),sender); - } - - public boolean checkPermission(ICommandSender sender) - { - if (sender instanceof EntityPlayer) return PermissionsDB.INSTANCE.checkPermissions(sender, getBasePermission()); - else return super.checkPermission(sender.getServer(),sender); - } - - public Node getBasePermission() - { - return new Node(PermConstants.COMMAND_PREFIX + "." + getCommandName()); - } - - public boolean checkExtraPermission(ICommandSender sender, String... extras) - { - return PermissionsDB.INSTANCE.checkPermissions(sender, getBasePermission().append(extras)); - } -} diff --git a/src/main/java/net/doubledoordev/d3core/permissions/cmd/CommandPermissionWrapper.java b/src/main/java/net/doubledoordev/d3core/permissions/cmd/CommandPermissionWrapper.java deleted file mode 100644 index 0daad1b..0000000 --- a/src/main/java/net/doubledoordev/d3core/permissions/cmd/CommandPermissionWrapper.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright (c) 2014, - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * Neither the name of the {organization} nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * - */ - -package net.doubledoordev.d3core.permissions.cmd; - -import javax.annotation.Nullable; - -import net.doubledoordev.d3core.D3Core; -import net.doubledoordev.d3core.permissions.PermissionsDB; -import net.minecraft.command.CommandBase; -import net.minecraft.command.CommandException; -import net.minecraft.command.ICommand; -import net.minecraft.command.ICommandSender; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.server.MinecraftServer; -import net.minecraft.util.math.BlockPos; - -import java.util.List; - -/** - * @author Dries007 - */ -public class CommandPermissionWrapper extends CommandPermissionBase -{ - CommandBase commandBase; - - public CommandPermissionWrapper(CommandBase commandBase) - { - this.commandBase = commandBase; - } - - @Override - public int getRequiredPermissionLevel() - { - return commandBase.getRequiredPermissionLevel(); - } - - @Override - public String getCommandName() - { - return commandBase.getCommandName(); - } - - @Override - public String getCommandUsage(ICommandSender p_71518_1_) - { - return commandBase.getCommandUsage(p_71518_1_); - } - - @Override - public List getCommandAliases() - { - return commandBase.getCommandAliases(); - } - - @Override - public void execute(MinecraftServer server, ICommandSender sender, String[] args) - { - try { - commandBase.execute(server, sender, args); - } - catch (CommandException e) - { - D3Core.getLogger().error(e); - } - } - - @Override - public boolean checkPermission(MinecraftServer server, ICommandSender sender) - { - if (sender instanceof EntityPlayer) return PermissionsDB.INSTANCE.checkPermissions(sender, getBasePermission()); - else return commandBase.checkPermission(server,sender); - } - - @Override - public List getTabCompletionOptions(MinecraftServer server, ICommandSender sender, String[] args, @Nullable BlockPos pos) - { - return commandBase.getTabCompletionOptions(server,sender,args,null); - - } - - @Override - public boolean isUsernameIndex(String[] p_82358_1_, int p_82358_2_) - { - return commandBase.isUsernameIndex(p_82358_1_, p_82358_2_); - } - - @Override - public int compareTo(ICommand p_compareTo_1_) - { - return commandBase.compareTo(p_compareTo_1_); - } -} diff --git a/src/main/java/net/doubledoordev/d3core/util/CommandSetLoginMessage.java b/src/main/java/net/doubledoordev/d3core/util/CommandSetLoginMessage.java index 7895523..444773b 100644 --- a/src/main/java/net/doubledoordev/d3core/util/CommandSetLoginMessage.java +++ b/src/main/java/net/doubledoordev/d3core/util/CommandSetLoginMessage.java @@ -1,8 +1,40 @@ +/* + * Copyright (c) 2014-2016, Dries007 & DoubleDoorDevelopment + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * Neither the name of DoubleDoorDevelopment nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + package net.doubledoordev.d3core.util; import com.google.gson.JsonParseException; import net.doubledoordev.d3core.D3Core; import net.minecraft.command.CommandBase; +import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; import net.minecraft.server.MinecraftServer; import net.minecraft.util.text.ITextComponent; @@ -17,6 +49,7 @@ /** * @author Dries007 */ +@SuppressWarnings("NullableProblems") public class CommandSetLoginMessage extends CommandBase { @Override @@ -32,12 +65,14 @@ public String getCommandUsage(ICommandSender p_71518_1_) } @Override - public void execute(MinecraftServer server, ICommandSender sender, String[] args) + public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { + File file = new File(D3Core.getFolder(), CoreConstants.LOGIN_MESSAGE_FILE); if (args.length == 0) { - File file = new File(D3Core.getFolder(), "loginmessage.txt"); - if (file.exists()) file.delete(); + + if (file.exists()) //noinspection ResultOfMethodCallIgnored + file.delete(); sender.addChatMessage(new TextComponentTranslation("d3.core.cmd.setloginmessage.removed")); } else @@ -45,11 +80,12 @@ public void execute(MinecraftServer server, ICommandSender sender, String[] args String txt = buildString(args, 0); try { - FileUtils.writeStringToFile(new File(D3Core.getFolder(), "loginmessage.txt"), txt); + FileUtils.writeStringToFile(file, txt); } catch (IOException e) { - throw new RuntimeException(e); + e.printStackTrace(); + throw new CommandException(e.getMessage()); } sender.addChatMessage(new TextComponentTranslation("d3.core.cmd.setloginmessage.success")); try diff --git a/src/main/java/net/doubledoordev/d3core/util/CoreConstants.java b/src/main/java/net/doubledoordev/d3core/util/CoreConstants.java index 4513a31..da8cd2a 100644 --- a/src/main/java/net/doubledoordev/d3core/util/CoreConstants.java +++ b/src/main/java/net/doubledoordev/d3core/util/CoreConstants.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, + * Copyright (c) 2014-2016, Dries007 & DoubleDoorDevelopment * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -12,7 +12,7 @@ * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - * Neither the name of the {organization} nor the names of its + * Neither the name of DoubleDoorDevelopment nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * @@ -27,60 +27,52 @@ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * - * */ package net.doubledoordev.d3core.util; -import com.google.common.base.Joiner; import com.google.gson.Gson; import com.google.gson.GsonBuilder; -import net.doubledoordev.d3core.D3Core; -import net.doubledoordev.d3core.permissions.Node; +import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityFireworkRocket; -import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; -import java.util.Calendar; import java.util.Random; +import java.util.regex.Pattern; /** * @author Dries007 */ +@SuppressWarnings("WeakerAccess") public class CoreConstants { - public static final String MODID = "D3Core"; - public static final String NAME = "D³ Core"; - public static final String BASEURL = "http://doubledoordev.net/"; - public static final String PERKSURL = BASEURL + "perks.json"; - public static final String MAVENURL = BASEURL + "maven/"; - /** - * @see net.doubledoordev.d3core.client.ModConfigGuiFactory - */ + public static final String MODID = "D3Core"; + public static final String NAME = "D³ Core"; + public static final String BASE_URL = "http://doubledoordev.net/"; + public static final String PERKS_URL = BASE_URL + "perks.json"; + public static final String UPDATE_URL = BASE_URL + MODID + ".json"; + + /** @see net.doubledoordev.d3core.client.ModConfigGuiFactory */ public static final String MOD_GUI_FACTORY = "net.doubledoordev.d3core.client.ModConfigGuiFactory"; - public static final Gson GSON = new GsonBuilder().setPrettyPrinting().registerTypeAdapter(Node.class, new Node.JsonHelper()).create(); - public static final Joiner JOINER_DOT = Joiner.on('.'); - public static final Random RANDOM = new Random(); - public static boolean isAprilFools() - { - //noinspection MagicConstant - return D3Core.aprilFools && Calendar.getInstance().get(Calendar.MONTH) == Calendar.APRIL && Calendar.getInstance().get(Calendar.DAY_OF_MONTH) == 1; - } + public static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); + public static final Random RANDOM = new Random(); + public static final String LOGIN_MESSAGE_FILE = "loginmessage.txt"; + public static final Pattern PATTERN_ITEMSTACK = Pattern.compile("^(?:(?.*):)?(?.*?) ?(?\\*|\\d+)? ?(?\\d+)?$"); - public static void spawnRandomFireworks(EntityPlayer target, int rad, int rockets) + public static void spawnRandomFireworks(Entity target, int rad, int rockets) { - while (rockets -- > 0) + while (rockets-- > 0) { ItemStack itemStack = new ItemStack(Items.FIREWORKS); NBTTagCompound fireworks = new NBTTagCompound(); NBTTagList explosions = new NBTTagList(); int charges = 1 + CoreConstants.RANDOM.nextInt(3); - while (charges -- > 0) + while (charges-- > 0) { NBTTagCompound explosion = new NBTTagCompound(); diff --git a/src/main/java/net/doubledoordev/d3core/util/CoreHelper.java b/src/main/java/net/doubledoordev/d3core/util/CoreHelper.java deleted file mode 100644 index 5e8c0e4..0000000 --- a/src/main/java/net/doubledoordev/d3core/util/CoreHelper.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) 2014, - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * Neither the name of the {organization} nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * - */ - -package net.doubledoordev.d3core.util; - -/** - * @author Dries007 - */ -public class CoreHelper -{ - private CoreHelper() - { - } - - public static class ModUpdateDate - { - private final String name; - private final String modId; - private final String currentVersion; - private final String latestVersion; - - public ModUpdateDate(String name, String modId, String currentVersion, String latestVersion) - { - this.name = name; - this.modId = modId; - this.currentVersion = currentVersion; - this.latestVersion = latestVersion; - } - - public String getName() - { - return name; - } - - public String getModId() - { - return modId; - } - - public String getCurrentVersion() - { - return currentVersion; - } - - public String getLatestVersion() - { - return latestVersion; - } - } - - -} diff --git a/src/main/java/net/doubledoordev/d3core/util/DevPerks.java b/src/main/java/net/doubledoordev/d3core/util/DevPerks.java index e3c02d7..17f8b3f 100644 --- a/src/main/java/net/doubledoordev/d3core/util/DevPerks.java +++ b/src/main/java/net/doubledoordev/d3core/util/DevPerks.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, DoubleDoorDevelopment + * Copyright (c) 2014-2016, Dries007 & DoubleDoorDevelopment * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -12,7 +12,7 @@ * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - * Neither the name of the project nor the names of its + * Neither the name of DoubleDoorDevelopment nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * @@ -26,6 +26,7 @@ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * */ package net.doubledoordev.d3core.util; @@ -33,26 +34,27 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; -import net.minecraftforge.fml.common.FMLCommonHandler; -import net.minecraftforge.fml.common.eventhandler.EventPriority; -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; -import net.minecraftforge.fml.common.registry.GameData; import net.doubledoordev.d3core.D3Core; import net.minecraft.entity.item.EntityItem; +import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.NBTTagString; import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.event.entity.player.AchievementEvent; import net.minecraftforge.event.entity.player.PlayerDropsEvent; import net.minecraftforge.event.entity.player.PlayerEvent; +import net.minecraftforge.fml.common.eventhandler.EventPriority; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.registry.GameRegistry; - import org.apache.commons.io.IOUtils; import java.net.URL; import java.nio.charset.Charset; +import static net.minecraftforge.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent; + /** * Something other than capes for once * @@ -60,25 +62,33 @@ */ public class DevPerks { - private JsonObject perks = new JsonObject(); + private JsonObject perks = new JsonObject(); public DevPerks() + { + update(); + } + + private void update() { try { - perks = new JsonParser().parse(IOUtils.toString(new URL(CoreConstants.PERKSURL), Charset.forName("UTF-8"))).getAsJsonObject(); + perks = new JsonParser().parse(IOUtils.toString(new URL(CoreConstants.PERKS_URL), Charset.forName("UTF-8"))).getAsJsonObject(); } catch (Exception e) { - if (D3Core.debug()) e.printStackTrace(); + D3Core.getLogger().warn("There may be an error in devperks, no sillyness for you...", e); + if (D3Core.isDebug()) e.printStackTrace(); } + if (perks == null) perks = new JsonObject(); } - public static ItemStack getItemStackFromJson(JsonObject data, int defaultMeta, int defaultStacksize) + private static ItemStack getItemStackFromJson(JsonObject data, int defaultMeta, int defaultStacksize) { int meta = data.has("meta") ? data.get("meta").getAsInt() : defaultMeta; int size = data.has("size") ? data.get("size").getAsInt() : defaultStacksize; - ItemStack stack = GameRegistry.makeItemStack(data.get("name").getAsString(), size, meta,null); + ItemStack stack = GameRegistry.makeItemStack(data.get("name").getAsString(), size, meta, null); + if (stack == null) return null; if (data.has("display")) stack.setStackDisplayName(data.get("display").getAsString()); if (data.has("color")) { @@ -95,7 +105,8 @@ public static ItemStack getItemStackFromJson(JsonObject data, int defaultMeta, i if (root == null) root = new NBTTagCompound(); NBTTagCompound display = root.getCompoundTag("display"); NBTTagList lore = new NBTTagList(); - for (JsonElement element : data.getAsJsonArray("lore")) lore.appendTag(new NBTTagString(element.getAsString())); + for (JsonElement element : data.getAsJsonArray("lore")) + lore.appendTag(new NBTTagString(element.getAsString())); display.setTag("Lore", lore); root.setTag("display", display); stack.setTagCompound(root); @@ -103,96 +114,144 @@ public static ItemStack getItemStackFromJson(JsonObject data, int defaultMeta, i return stack; } - /** - * Something other than capes for once - */ @SubscribeEvent public void nameFormatEvent(PlayerEvent.NameFormat event) { try { - if (D3Core.debug()) perks = new JsonParser().parse(IOUtils.toString(new URL(CoreConstants.PERKSURL), Charset.forName("UTF-8"))).getAsJsonObject(); + if (D3Core.isDebug()) update(); if (perks.has(event.getUsername())) { JsonObject perk = perks.getAsJsonObject(event.getUsername()); if (perk.has("displayname")) event.setDisplayname(perk.get("displayname").getAsString()); - if (perk.has("hat") && (event.getEntityPlayer().inventory.armorInventory[3] == null || event.getEntityPlayer().inventory.armorInventory[3].stackSize == 0)) - { - ItemStack hat = getItemStackFromJson(perk.getAsJsonObject("hat"), 0, 0); - hat.stackSize = 0; - event.getEntityPlayer().inventory.armorInventory[3] = hat; - } + doHat(perk, event.getEntityPlayer()); } } catch (Exception e) { - if (D3Core.debug()) e.printStackTrace(); + if (D3Core.isDebug()) e.printStackTrace(); } } @SubscribeEvent - public void cloneEvent(PlayerEvent.Clone event) + public void playerLoggedInEvent(PlayerLoggedInEvent event) { try { - if (D3Core.debug()) perks = new JsonParser().parse(IOUtils.toString(new URL(CoreConstants.PERKSURL), Charset.forName("UTF-8"))).getAsJsonObject(); - if (perks.has(event.getOriginal().getCommandSenderEntity().getName())) + if (D3Core.isDebug()) update(); + if (perks.has(event.player.getName())) { - JsonObject perk = perks.getAsJsonObject(event.getOriginal().getCommandSenderEntity().getName()); - if (perk.has("hat") && (event.getEntityPlayer().inventory.armorInventory[3] == null || event.getEntityPlayer().inventory.armorInventory[3].stackSize == 0)) + JsonObject perk = perks.getAsJsonObject(event.player.getName()); + if (perk.has("fireworks")) { - ItemStack hat = getItemStackFromJson(perk.getAsJsonObject("hat"), 0, 0); - hat.stackSize = 0; - event.getEntityPlayer().inventory.armorInventory[3] = hat; + JsonObject fw = perk.getAsJsonObject("fireworks"); + if (fw.has("login")) + { + JsonObject obj = fw.getAsJsonObject("login"); + int rad = obj.has("radius") ? obj.get("radius").getAsInt() : 5; + int rockets = obj.has("rockets") ? obj.get("rockets").getAsInt() : 5; + CoreConstants.spawnRandomFireworks(event.player, rad + CoreConstants.RANDOM.nextInt(rad), rockets + CoreConstants.RANDOM.nextInt(rockets)); + } } } } catch (Exception e) { - if (D3Core.debug()) e.printStackTrace(); + if (D3Core.isDebug()) e.printStackTrace(); } } - @SubscribeEvent(priority = EventPriority.HIGHEST) - public void deathEvent(PlayerDropsEvent event) + @SubscribeEvent + public void achievementEvent(AchievementEvent event) { try { - if (D3Core.debug()) perks = new JsonParser().parse(IOUtils.toString(new URL(CoreConstants.PERKSURL), Charset.forName("UTF-8"))).getAsJsonObject(); - if (perks.has(event.getEntityPlayer().getCommandSenderEntity().getName())) + if (D3Core.isDebug()) update(); + if (perks.has(event.getEntityPlayer().getName())) { - JsonObject perk = perks.getAsJsonObject(event.getEntityPlayer().getCommandSenderEntity().getName()); - if (perk.has("drop")) + JsonObject perk = perks.getAsJsonObject(event.getEntityPlayer().getName()); + if (perk.has("fireworks")) { - event.getDrops().add(new EntityItem(event.getEntityPlayer().getEntityWorld(), event.getEntityPlayer().posX, event.getEntityPlayer().posY, event.getEntityPlayer().posZ, getItemStackFromJson(perk.getAsJsonObject("drop"), 0, 1))); + JsonObject fw = perk.getAsJsonObject("fireworks"); + if (fw.has("achievement")) + { + JsonObject obj = fw.getAsJsonObject("achievement"); + int rad = obj.has("radius") ? obj.get("radius").getAsInt() : 5; + int rockets = obj.has("rockets") ? obj.get("rockets").getAsInt() : 5; + CoreConstants.spawnRandomFireworks(event.getEntityPlayer(), rad + CoreConstants.RANDOM.nextInt(rad), rockets + CoreConstants.RANDOM.nextInt(rockets)); + } } } } catch (Exception e) { - if (D3Core.debug()) e.printStackTrace(); + if (D3Core.isDebug()) e.printStackTrace(); } } - public void update(boolean sillyness) + @SubscribeEvent + public void cloneEvent(PlayerEvent.Clone event) { try { - if (sillyness) MinecraftForge.EVENT_BUS.register(this); - else MinecraftForge.EVENT_BUS.unregister(this); + if (D3Core.isDebug()) update(); + if (perks.has(event.getOriginal().getName())) + { + JsonObject perk = perks.getAsJsonObject(event.getOriginal().getName()); + doHat(perk, event.getEntityPlayer()); + } } catch (Exception e) { - if (D3Core.debug()) e.printStackTrace(); + if (D3Core.isDebug()) e.printStackTrace(); } + } + + private void doHat(JsonObject perk, EntityPlayer player) + { + if (perk.has("hat") && (player.inventory.armorInventory[3] == null || player.inventory.armorInventory[3].stackSize == 0)) + { + ItemStack hat = getItemStackFromJson(perk.getAsJsonObject("hat"), 0, 0); + if (hat == null) return; + hat.stackSize = 0; + player.inventory.armorInventory[3] = hat; + } + } + + @SubscribeEvent(priority = EventPriority.HIGHEST) + public void deathEvent(PlayerDropsEvent event) + { try { - if (sillyness) FMLCommonHandler.instance().bus().register(this); - else FMLCommonHandler.instance().bus().unregister(this); + if (D3Core.isDebug()) + perks = new JsonParser().parse(IOUtils.toString(new URL(CoreConstants.PERKS_URL), Charset.forName("UTF-8"))).getAsJsonObject(); + if (perks.has(event.getEntityPlayer().getName())) + { + JsonObject perk = perks.getAsJsonObject(event.getEntityPlayer().getName()); + if (perk.has("drop")) + { + ItemStack stack = getItemStackFromJson(perk.getAsJsonObject("drop"), 0, 1); + if (stack == null) return; + event.getDrops().add(new EntityItem(event.getEntityPlayer().getEntityWorld(), event.getEntityPlayer().posX, event.getEntityPlayer().posY, event.getEntityPlayer().posZ, stack)); + } + } + } + catch (Exception e) + { + if (D3Core.isDebug()) e.printStackTrace(); + } + } + + public void update(boolean silliness) + { + try + { + if (silliness) MinecraftForge.EVENT_BUS.register(this); + else MinecraftForge.EVENT_BUS.unregister(this); } catch (Exception e) { - if (D3Core.debug()) e.printStackTrace(); + if (D3Core.isDebug()) e.printStackTrace(); } } } diff --git a/src/main/java/net/doubledoordev/d3core/util/EndermanGriefing.java b/src/main/java/net/doubledoordev/d3core/util/EndermanGriefing.java index 7e85566..22c8a2d 100644 --- a/src/main/java/net/doubledoordev/d3core/util/EndermanGriefing.java +++ b/src/main/java/net/doubledoordev/d3core/util/EndermanGriefing.java @@ -1,14 +1,45 @@ +/* + * Copyright (c) 2014-2016, Dries007 & DoubleDoorDevelopment + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * Neither the name of DoubleDoorDevelopment nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + package net.doubledoordev.d3core.util; -import net.minecraftforge.fml.common.registry.FMLControlledNamespacedRegistry; -import net.minecraftforge.fml.common.registry.GameData; import net.doubledoordev.d3core.D3Core; import net.minecraft.block.Block; import net.minecraft.entity.monster.EntityEnderman; -import net.minecraft.init.Blocks; import net.minecraft.util.ResourceLocation; +import net.minecraft.util.registry.RegistryNamespacedDefaultedByKey; -import java.util.*; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Set; import java.util.regex.Pattern; /** @@ -27,10 +58,10 @@ public static void init() { if (disable) { - FMLControlledNamespacedRegistry blockData = GameData.getBlockRegistry(); + RegistryNamespacedDefaultedByKey blockData = Block.REGISTRY; for (ResourceLocation key : blockData.getKeys()) { - Block block = (Block) blockData.getObject(key); + Block block = blockData.getObject(key); reverseMap.put(blockData.getNameForObject(block).toString(), EntityEnderman.getCarriable(block)); EntityEnderman.setCarriable(block, false); } @@ -40,7 +71,7 @@ public static void init() int added = 0, removed = 0; for (String item : addList) { - List blocks = matchBlock(item); + Set blocks = matchBlock(item); if (blocks.isEmpty()) D3Core.getLogger().warn("[EndermanGriefing] '{}' does not match any block...", item); else { @@ -54,7 +85,7 @@ public static void init() } for (String item : blacklist) { - List blocks = matchBlock(item); + Set blocks = matchBlock(item); if (blocks.isEmpty()) D3Core.getLogger().warn("[EndermanGriefing] '{}' does not match any block...", item); else { @@ -66,25 +97,22 @@ public static void init() } } } - D3Core.getLogger().info("[EndermanGriefing] Added {} and removed {} blocks to the Ederman grab list...", added, removed); + D3Core.getLogger().info("[EndermanGriefing] Added {} and removed {} blocks to the Enderman grab list...", added, removed); } } - private static List matchBlock(String item) + private static Set matchBlock(String item) { - boolean ignored = false; - ArrayList blocks = new ArrayList<>(); + Set blocks = new HashSet<>(); Pattern pattern = Pattern.compile(item.replace("*", ".*?")); - FMLControlledNamespacedRegistry blockData = GameData.getBlockRegistry(); - for (Block block : blockData.typeSafeIterable()) + RegistryNamespacedDefaultedByKey blockData = Block.REGISTRY; + for (Block block : blockData) { if (pattern.matcher(blockData.getNameForObject(block).toString()).matches()) { - if (blockData.getId(block) > 255) ignored = true; - else blocks.add(block); + blocks.add(block); } } - if (ignored) D3Core.getLogger().warn("[EndermanGriefing] Blocks with ID > 255 won't work! Some blocks matching {} have been ignored.", item); return blocks; } @@ -92,7 +120,7 @@ public static void undo() { for (String entry : reverseMap.keySet()) { - EntityEnderman.setCarriable(GameData.getBlockRegistry().getObject(new ResourceLocation(entry)), reverseMap.get(entry)); + EntityEnderman.setCarriable(Block.REGISTRY.getObject(new ResourceLocation(entry)), reverseMap.get(entry)); } } } diff --git a/src/main/java/net/doubledoordev/d3core/util/ForgeEventHandler.java b/src/main/java/net/doubledoordev/d3core/util/EventHandler.java similarity index 58% rename from src/main/java/net/doubledoordev/d3core/util/ForgeEventHandler.java rename to src/main/java/net/doubledoordev/d3core/util/EventHandler.java index 0ea1b26..55e14d2 100644 --- a/src/main/java/net/doubledoordev/d3core/util/ForgeEventHandler.java +++ b/src/main/java/net/doubledoordev/d3core/util/EventHandler.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, + * Copyright (c) 2014-2016, Dries007 & DoubleDoorDevelopment * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -12,7 +12,7 @@ * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - * Neither the name of the {organization} nor the names of its + * Neither the name of DoubleDoorDevelopment nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * @@ -27,16 +27,14 @@ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * - * */ package net.doubledoordev.d3core.util; -import net.minecraftforge.fml.common.FMLCommonHandler; -import net.minecraftforge.fml.common.eventhandler.EventPriority; -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; - -import net.minecraft.command.ICommandSender; +import com.google.gson.JsonParseException; +import net.doubledoordev.d3core.D3Core; +import net.minecraft.block.material.Material; +import net.minecraft.block.state.IBlockState; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.monster.EntityEnderman; import net.minecraft.entity.player.EntityPlayer; @@ -44,27 +42,40 @@ import net.minecraft.item.ItemStack; import net.minecraft.server.MinecraftServer; import net.minecraft.tileentity.TileEntityFurnace; +import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; +import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.Style; import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.event.ClickEvent; import net.minecraft.util.text.event.HoverEvent; - +import net.minecraft.world.World; +import net.minecraft.world.storage.WorldInfo; import net.minecraftforge.event.ServerChatEvent; import net.minecraftforge.event.entity.living.LivingDeathEvent; import net.minecraftforge.event.entity.living.LivingDropsEvent; +import net.minecraftforge.event.entity.player.AchievementEvent; import net.minecraftforge.event.entity.player.ItemTooltipEvent; import net.minecraftforge.event.entity.player.PlayerEvent; import net.minecraftforge.event.entity.player.PlayerSleepInBedEvent; +import net.minecraftforge.fml.common.FMLCommonHandler; +import net.minecraftforge.fml.common.eventhandler.EventPriority; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.fml.common.gameevent.TickEvent; +import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.oredict.OreDictionary; +import org.apache.commons.io.FileUtils; + +import java.io.File; +import java.io.IOException; /** * @author Dries007 */ -public class ForgeEventHandler +public class EventHandler { - public static final ForgeEventHandler FORGE_EVENT_HANDLER = new ForgeEventHandler(); + public static final EventHandler I = new EventHandler(); public boolean enableStringID; public boolean enableUnlocalizedName; public boolean enableOreDictionary; @@ -72,8 +83,12 @@ public class ForgeEventHandler public boolean nosleep; public boolean printDeathCoords = true; public boolean claysTortureMode; + public boolean norain; + public boolean insomnia; + public boolean lilypad; + public boolean achievementFireworks; - private ForgeEventHandler() {} + private EventHandler() {} @SubscribeEvent(priority = EventPriority.LOWEST) public void itemTooltipEventHandler(ItemTooltipEvent event) @@ -87,6 +102,12 @@ public void itemTooltipEventHandler(ItemTooltipEvent event) } } + @SubscribeEvent + public void achievementEvent(AchievementEvent event) + { + if (achievementFireworks) CoreConstants.spawnRandomFireworks(event.getEntityPlayer(), 1, 1); + } + @SubscribeEvent() public void entityDeathEvent(LivingDropsEvent event) { @@ -97,9 +118,10 @@ public void entityDeathEvent(LivingDropsEvent event) else if (event.getEntityLiving() instanceof EntityEnderman && EndermanGriefing.dropCarrying) { EntityEnderman entityEnderman = ((EntityEnderman) event.getEntityLiving()); - if (entityEnderman.getHeldBlockState() != Blocks.AIR) + IBlockState state = entityEnderman.getHeldBlockState(); + if (state != null && state.getBlock() != Blocks.AIR) { - ItemStack stack = new ItemStack(entityEnderman.getHeldBlockState().getBlock(), 1, entityEnderman.getHeldBlockState().getBlock().getMetaFromState(entityEnderman.getHeldBlockState())); + ItemStack stack = new ItemStack(state.getBlock(), 1, state.getBlock().getMetaFromState(state)); event.getDrops().add(new EntityItem(entityEnderman.worldObj, entityEnderman.posX, entityEnderman.posY, entityEnderman.posZ, stack)); } } @@ -114,7 +136,7 @@ public void playerDeath(LivingDeathEvent event) try { MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); - if (!server.getCommandManager().getPossibleCommands((ICommandSender) event.getEntityLiving()).contains(server.getCommandManager().getCommands().get("tp"))) + if (!server.getCommandManager().getPossibleCommands(event.getEntityLiving()).contains(server.getCommandManager().getCommands().get("tp"))) { posText.setStyle(new Style().setItalic(true) .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponentString("Click to teleport!"))) @@ -133,7 +155,7 @@ public void playerDeath(LivingDeathEvent event) @SubscribeEvent() public void sleepEvent(PlayerSleepInBedEvent event) { - if (nosleep || CoreConstants.isAprilFools()) + if (nosleep || D3Core.isAprilFools()) { event.setResult(EntityPlayer.SleepResult.OTHER_PROBLEM); } @@ -142,7 +164,7 @@ public void sleepEvent(PlayerSleepInBedEvent event) @SubscribeEvent public void aprilFools(ServerChatEvent event) { - if (CoreConstants.isAprilFools()) + if (D3Core.isAprilFools()) { Style style = event.getComponent().getStyle(); @@ -180,9 +202,105 @@ public void aprilFools(ServerChatEvent event) @SubscribeEvent public void aprilFools(PlayerEvent.NameFormat event) { - if (CoreConstants.isAprilFools()) + if (D3Core.isAprilFools()) { event.setDisplayname("§k" + event.getDisplayname()); } } + + @SubscribeEvent + public void worldTickHandler(TickEvent.WorldTickEvent event) + { + if (event.side != Side.SERVER || event.phase != TickEvent.Phase.START) return; + + if (norain) + { + WorldInfo worldInfo = event.world.getWorldInfo(); + worldInfo.setThundering(false); + worldInfo.setRaining(false); + worldInfo.setRainTime(Integer.MAX_VALUE); + worldInfo.setThunderTime(Integer.MAX_VALUE); + } + } + + private int aprilFoolsDelay = 0; + @SubscribeEvent + public void playerTickHandler(TickEvent.PlayerTickEvent event) + { + if (event.side != Side.SERVER || event.phase != TickEvent.Phase.START) return; + + if (insomnia) + { + if (event.player.sleepTimer > 90) + { + event.player.sleepTimer = 90; + } + } + + + if (D3Core.isAprilFools()) + { + if (aprilFoolsDelay-- <= 0) + { + aprilFoolsDelay = 100 * (5 + CoreConstants.RANDOM.nextInt(FMLCommonHandler.instance().getMinecraftServerInstance().getCurrentPlayerCount())); + CoreConstants.spawnRandomFireworks(event.player, 1 + CoreConstants.RANDOM.nextInt(5), 1 + CoreConstants.RANDOM.nextInt(5)); + } + } + } + + @SubscribeEvent + public void playerLoggedInEvent(net.minecraftforge.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent event) + { + File file = new File(D3Core.getFolder(), "loginmessage.txt"); + if (file.exists()) + { + try + { + String txt = FileUtils.readFileToString(file); + try + { + event.player.addChatMessage(ITextComponent.Serializer.jsonToComponent(txt)); + } + catch (JsonParseException jsonparseexception) + { + event.player.addChatMessage(new TextComponentString(txt)); + } + } + catch (IOException e) + { + e.printStackTrace(); + } + } + + if (lilypad) lilypad(event.player); + if (D3Core.isAprilFools()) CoreConstants.spawnRandomFireworks(event.player, 1 + CoreConstants.RANDOM.nextInt(5), 1 + CoreConstants.RANDOM.nextInt(5)); + } + + @SubscribeEvent + public void playerRespawnEvent(net.minecraftforge.fml.common.gameevent.PlayerEvent.PlayerRespawnEvent event) + { + if (lilypad) lilypad(event.player); + if (D3Core.isAprilFools()) CoreConstants.spawnRandomFireworks(event.player, 1 + CoreConstants.RANDOM.nextInt(5), 1 + CoreConstants.RANDOM.nextInt(5)); + } + + private void lilypad(EntityPlayer player) + { + World world = player.worldObj; + + BlockPos blockPos = new BlockPos((int)(player.posX),(int)(player.posY),(int)(player.posZ)); + + if (blockPos.getX() < 0) blockPos.add(-1,0,0); + if (blockPos.getZ() < 0) blockPos.add(0,0,-1); + + int limiter = world.getActualHeight() * 2; + + while (world.getBlockState(blockPos).getMaterial() == Material.WATER && --limiter != 0) blockPos.add(0,1,0); + while (world.getBlockState(blockPos).getMaterial() == Material.AIR && --limiter != 0) blockPos.add(0,-1,0); + if (limiter == 0) return; + if (world.getBlockState(blockPos).getMaterial() == Material.WATER) + { + world.setBlockState(blockPos.add(0,1,0), Blocks.WATERLILY.getDefaultState()); + player.setPositionAndUpdate(blockPos.getX() + 0.5,blockPos.getY() + 2,blockPos.getZ() + 0.5); + } + } } diff --git a/src/main/java/net/doubledoordev/d3core/util/FMLEventHandler.java b/src/main/java/net/doubledoordev/d3core/util/FMLEventHandler.java deleted file mode 100644 index 838ac59..0000000 --- a/src/main/java/net/doubledoordev/d3core/util/FMLEventHandler.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Copyright (c) 2014, - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * Neither the name of the {organization} nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * - */ - -package net.doubledoordev.d3core.util; - -import com.google.gson.JsonParseException; - -import net.minecraftforge.fml.common.FMLCommonHandler; -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; -import net.minecraftforge.fml.common.gameevent.PlayerEvent; -import net.minecraftforge.fml.common.gameevent.TickEvent; -import net.minecraftforge.fml.relauncher.Side; -import net.doubledoordev.d3core.D3Core; - -import net.minecraft.block.Block; -import net.minecraft.block.material.Material; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.init.Blocks; -import net.minecraft.server.MinecraftServer; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.text.ITextComponent; -import net.minecraft.util.text.TextComponentString; -import net.minecraft.world.World; -import net.minecraft.world.storage.WorldInfo; -import org.apache.commons.io.FileUtils; - -import java.io.File; -import java.io.IOException; - -/** - * @author Dries007 - */ -public class FMLEventHandler -{ - public static final FMLEventHandler FML_EVENT_HANDLER = new FMLEventHandler(); - private FMLEventHandler() - { - } - - public boolean norain; - public boolean insomnia; - public boolean lilypad; - - @SubscribeEvent - public void worldTickHandler(TickEvent.WorldTickEvent event) - { - if (event.side != Side.SERVER || event.phase != TickEvent.Phase.START) return; - - if (norain) - { - WorldInfo worldInfo = event.world.getWorldInfo(); - worldInfo.setThundering(false); - worldInfo.setRaining(false); - worldInfo.setRainTime(Integer.MAX_VALUE); - worldInfo.setThunderTime(Integer.MAX_VALUE); - } - } - - int aprilFoolsDelay = 0; - @SubscribeEvent - public void playerTickHandler(TickEvent.PlayerTickEvent event) - { - if (event.side != Side.SERVER || event.phase != TickEvent.Phase.START) return; - - if (insomnia) - { - if (event.player.sleepTimer > 90) - { - event.player.sleepTimer = 90; - } - } - - - if (CoreConstants.isAprilFools()) - { - if (aprilFoolsDelay-- == 0) - { - aprilFoolsDelay = 100 * (5 + CoreConstants.RANDOM.nextInt(FMLCommonHandler.instance().getMinecraftServerInstance().getCurrentPlayerCount())); - CoreConstants.spawnRandomFireworks(event.player, 1 + CoreConstants.RANDOM.nextInt(5), 1 + CoreConstants.RANDOM.nextInt(5)); - } - } - } - - @SubscribeEvent - public void playerLoggedInEvent(PlayerEvent.PlayerLoggedInEvent event) - { - File file = new File(D3Core.getFolder(), "loginmessage.txt"); - if (file.exists()) - { - try - { - String txt = FileUtils.readFileToString(file); - try - { - event.player.addChatMessage(ITextComponent.Serializer.jsonToComponent(txt)); - } - catch (JsonParseException jsonparseexception) - { - event.player.addChatMessage(new TextComponentString(txt)); - } - } - catch (IOException e) - { - e.printStackTrace(); - } - } - - if (lilypad) lilypad(event.player); - if (CoreConstants.isAprilFools()) CoreConstants.spawnRandomFireworks(event.player, 1 + CoreConstants.RANDOM.nextInt(5), 1 + CoreConstants.RANDOM.nextInt(5)); - } - - @SubscribeEvent - public void playerRespawnEvent(PlayerEvent.PlayerRespawnEvent event) - { - if (lilypad) lilypad(event.player); - if (CoreConstants.isAprilFools()) CoreConstants.spawnRandomFireworks(event.player, 1 + CoreConstants.RANDOM.nextInt(5), 1 + CoreConstants.RANDOM.nextInt(5)); - } - - private void lilypad(EntityPlayer player) - { - World world = player.worldObj; - - BlockPos blockPos = new BlockPos((int)(player.posX),(int)(player.posY),(int)(player.posZ)); - - if (blockPos.getX() < 0) blockPos.add(-1,0,0); - if (blockPos.getZ() < 0) blockPos.add(0,0,-1); - - int limiter = world.getActualHeight() * 2; - - while (world.getBlockState(blockPos).getMaterial() == Material.WATER && --limiter != 0) blockPos.add(0,1,0); - while (world.getBlockState(blockPos).getMaterial() == Material.AIR && --limiter != 0) blockPos.add(0,-1,0); - if (limiter == 0) return; - if (world.getBlockState(blockPos).getMaterial() == Material.WATER) - { - world.setBlockState(blockPos.add(0,1,0), Blocks.WATERLILY.getDefaultState()); - player.setPositionAndUpdate(blockPos.getX() + 0.5,blockPos.getY() + 2,blockPos.getZ() + 0.5); - } - } -} diff --git a/src/main/java/net/doubledoordev/d3core/util/ID3Mod.java b/src/main/java/net/doubledoordev/d3core/util/ID3Mod.java deleted file mode 100644 index 5f8b88a..0000000 --- a/src/main/java/net/doubledoordev/d3core/util/ID3Mod.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2014, - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * Neither the name of the {organization} nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * - */ - -package net.doubledoordev.d3core.util; - -import net.minecraftforge.fml.client.config.IConfigElement; - -import java.util.List; - -/** - * @author Dries007 - */ -public interface ID3Mod -{ - void syncConfig(); - - void addConfigElements(List list); -} diff --git a/src/main/java/net/doubledoordev/d3core/util/Materials.java b/src/main/java/net/doubledoordev/d3core/util/Materials.java index 76c5105..5a8fe5b 100644 --- a/src/main/java/net/doubledoordev/d3core/util/Materials.java +++ b/src/main/java/net/doubledoordev/d3core/util/Materials.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, + * Copyright (c) 2014-2016, Dries007 & DoubleDoorDevelopment * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -12,7 +12,7 @@ * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - * Neither the name of the {organization} nor the names of its + * Neither the name of DoubleDoorDevelopment nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * @@ -27,67 +27,87 @@ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * - * */ package net.doubledoordev.d3core.util; -import net.minecraftforge.fml.common.registry.GameRegistry; +import com.google.common.base.Strings; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; import net.doubledoordev.d3core.D3Core; import net.minecraft.item.Item; import net.minecraft.item.Item.ToolMaterial; +import net.minecraftforge.fml.common.Loader; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; +import java.util.HashMap; import java.util.Map; +import java.util.regex.Matcher; /** * @author Dries007 */ public class Materials { - public static void load() + public static void load() throws IOException { File file = new File(D3Core.getFolder(), "materials.json"); - if (!file.exists()) + if (!file.exists()) return; + + Map stringMap = CoreConstants.GSON.>fromJson(FileUtils.readFileToString(file, "utf-8"), Map.class); + Map itemStackMap = new HashMap<>(stringMap.size()); + + boolean stop = false; + for (Map.Entry entry : stringMap.entrySet()) { - try + Matcher matcher = CoreConstants.PATTERN_ITEMSTACK.matcher(entry.getValue()); + if (!matcher.matches()) { - FileUtils.write(file, "{}", "utf-8"); + D3Core.getLogger().error("Entry in materials.json does not match a valid ItemStack text: {}.", entry); + stop = true; + continue; } - catch (IOException e) + String mod = matcher.group("mod"); + String name = matcher.group("name"); + String metaString = matcher.group("meta"); + String stacksizeString = matcher.group("stacksize"); + if (Strings.isNullOrEmpty(mod)) mod = "minecraft"; + if (!Loader.isModLoaded(mod)) { - e.printStackTrace(); + D3Core.getLogger().warn("Skipped materials.json entry {} because mod {} is not loaded.", entry, mod); + continue; } - } - try - { - Map map = CoreConstants.GSON.>fromJson(FileUtils.readFileToString(file, "utf-8"), Map.class); - for (ToolMaterial material : ToolMaterial.values()) - { - String itemName = map.get(material.name()); - if (itemName != null) - { - String modid = itemName.substring(0, itemName.indexOf(':')); - String name = itemName.substring(itemName.indexOf(':' + 1)); - Item item = GameRegistry.findItem(modid, name); - if (item != null) material.customCraftingMaterial = item; - else - { - D3Core.getLogger().warn("Tried to assign item {} to material {}. That item doesn't exist.", itemName, material.name()); - } - map.remove(material.name()); - } - } - for (Map.Entry entry : map.entrySet()) + int meta = net.minecraftforge.oredict.OreDictionary.WILDCARD_VALUE; + int stacksize = 1; + // should not throw NumberFormatException since the regex does number check + if (!Strings.isNullOrEmpty(metaString) && !metaString.equals("*")) meta = Integer.parseInt(metaString); + if (!Strings.isNullOrEmpty(stacksizeString)) stacksize = Integer.parseInt(stacksizeString); + + Item item = Item.REGISTRY.getObject(new ResourceLocation(mod, name)); + if (item == null) { - D3Core.getLogger().warn("Tried to assign item {} to material {}. That material doesn't exist.", entry.getValue(), entry.getKey()); + D3Core.getLogger().error("Entry in materials.json {} invalid. Item {}:{} does not exist.", entry, mod, name); + stop = true; + continue; } + ItemStack stack = new ItemStack(item, stacksize, meta); + itemStackMap.put(entry.getKey().toLowerCase(), stack); } - catch (IOException e) + if (stop) + { + D3Core.getLogger().error("The proper format for materials.json entries is (in regex): {}", CoreConstants.PATTERN_ITEMSTACK.pattern()); + RuntimeException e = new RuntimeException("You have invalid entries in your materials.json file. Check the log for more info."); + e.setStackTrace(new StackTraceElement[0]); // No need for this + throw e; + } + + for (ToolMaterial material : ToolMaterial.values()) { - e.printStackTrace(); + ItemStack stack = itemStackMap.get(material.name().toLowerCase()); + if (stack == null) continue; + material.setRepairItem(stack); } } } diff --git a/src/main/java/net/doubledoordev/d3core/util/VoidRefunds.java b/src/main/java/net/doubledoordev/d3core/util/VoidRefunds.java index d2a752c..f1456a5 100644 --- a/src/main/java/net/doubledoordev/d3core/util/VoidRefunds.java +++ b/src/main/java/net/doubledoordev/d3core/util/VoidRefunds.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, + * Copyright (c) 2014-2016, Dries007 & DoubleDoorDevelopment * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -12,7 +12,7 @@ * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - * Neither the name of the {organization} nor the names of its + * Neither the name of DoubleDoorDevelopment nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * @@ -27,22 +27,19 @@ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * - * */ package net.doubledoordev.d3core.util; -import net.minecraftforge.fml.common.FMLCommonHandler; -import net.minecraftforge.fml.common.eventhandler.EventPriority; -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; -import net.minecraftforge.fml.common.gameevent.PlayerEvent; import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.item.ItemStack; import net.minecraft.util.DamageSource; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.event.entity.living.LivingDeathEvent; +import net.minecraftforge.fml.common.FMLCommonHandler; +import net.minecraftforge.fml.common.eventhandler.EventPriority; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.fml.common.gameevent.PlayerEvent; import java.util.HashMap; import java.util.UUID; @@ -81,6 +78,7 @@ public void livingDeathEvent(LivingDeathEvent event) if (dim != event.getEntity().dimension) continue; event.setCanceled(true); + //noinspection ConstantConditions InventoryPlayer tempCopy = new InventoryPlayer(null); tempCopy.copyInventory(((EntityPlayer) event.getEntity()).inventory); map.put(event.getEntity().getPersistentID(), tempCopy); diff --git a/src/main/java/net/doubledoordev/d3core/util/libs/org/mcstats/Metrics.java b/src/main/java/net/doubledoordev/d3core/util/libs/org/mcstats/Metrics.java deleted file mode 100644 index 042088b..0000000 --- a/src/main/java/net/doubledoordev/d3core/util/libs/org/mcstats/Metrics.java +++ /dev/null @@ -1,808 +0,0 @@ -package net.doubledoordev.d3core.util.libs.org.mcstats; - - -import net.minecraftforge.fml.common.FMLCommonHandler; -import net.minecraftforge.fml.common.FMLLog; -import net.minecraftforge.fml.common.Loader; -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; -import net.minecraftforge.fml.common.gameevent.TickEvent; - -import net.minecraft.client.multiplayer.ServerData; -import net.minecraft.server.MinecraftServer; -import net.minecraft.world.World; -import net.minecraft.world.WorldServer; - - -import net.minecraftforge.common.config.Configuration; - -import java.io.*; -import java.net.Proxy; -import java.net.URL; -import java.net.URLConnection; -import java.net.URLEncoder; -import java.util.*; -import java.util.zip.GZIPOutputStream; - -public class Metrics -{ - - /** - * The current revision number - */ - private final static int REVISION = 7; - - /** - * The base url of the metrics domain - */ - private static final String BASE_URL = "http://report.mcstats.org"; - - /** - * The url used to report a server's status - */ - private static final String REPORT_URL = "/plugin/%s"; - - /** - * Interval of time to ping (in minutes) - */ - private static final int PING_INTERVAL = 15; - - /** - * The mod this metrics submits for - */ - private final String modname; - - private final String modversion; - - /** - * All of the custom graphs to submit to metrics - */ - private final Set graphs = Collections.synchronizedSet(new HashSet()); - - /** - * The metrics configuration file - */ - private final Configuration configuration; - - /** - * The metrics configuration file - */ - private final File configurationFile; - - /** - * Unique server id - */ - private final String guid; - - /** - * Debug mode - */ - private final boolean debug; - - public Metrics(final String modname, final String modversion) throws IOException - { - if ((modname == null) || (modversion == null)) - { - throw new IllegalArgumentException("modname and modversion cannot be null"); - } - - this.modname = modname; - this.modversion = modversion; - - // load the config - configurationFile = getConfigFile(); - configuration = new Configuration(configurationFile); - - // Get values, and add some defaults, if needed - configuration.get(Configuration.CATEGORY_GENERAL, "opt-out", false, "Set to true to disable all reporting"); - guid = configuration.get(Configuration.CATEGORY_GENERAL, "guid", UUID.randomUUID().toString(), "Server unique ID").getString(); - debug = configuration.get(Configuration.CATEGORY_GENERAL, "debug", false, "Set to true for verbose debug").getBoolean(false); - configuration.save(); - } - - /** - * Construct and create a Graph that can be used to separate specific - * plotters to their own graphs on the metrics website. Plotters can be - * added to the graph object returned. - * - * @param name The name of the graph - * @return Graph object created. Will never return NULL under normal - * circumstances unless bad parameters are given - */ - public Graph createGraph(final String name) - { - if (name == null) - { - throw new IllegalArgumentException("Graph name cannot be null"); - } - - // Construct the graph object - final Graph graph = new Graph(name); - - // Now we can add our graph - graphs.add(graph); - - // and return back - return graph; - } - - /** - * Add a Graph object to Metrics that represents data for the plugin that - * should be sent to the backend - * - * @param graph The name of the graph - */ - public void addGraph(final Graph graph) - { - if (graph == null) - { - throw new IllegalArgumentException("Graph cannot be null"); - } - - graphs.add(graph); - } - - /** - * Start measuring statistics. This will immediately create an async - * repeating task as the plugin and send the initial data to the metrics - * backend, and then after that it will post in increments of PING_INTERVAL - * * 1200 ticks. - * - * @return True if statistics measuring is running, otherwise false. - */ - public boolean start() - { - // Did we opt out? - if (isOptOut()) - { - return false; - } - - FMLCommonHandler.instance().bus().register(this); - - return true; - } - - private Thread thrd = null; - private boolean firstPost = true; - int tickCount; - - @SubscribeEvent - public void tick(TickEvent.ServerTickEvent tick) - { - if (tick.phase != TickEvent.Phase.END) return; - - // Disable Task, if it is running and the server owner decided - // to opt-out - if (isOptOut()) - { - // Tell all plotters to stop gathering information. - for (Graph graph : graphs) - { - graph.onOptOut(); - } - - FMLCommonHandler.instance().bus().unregister(this); - return; - } - - tickCount++; - - if (tickCount % (firstPost ? 100 : PING_INTERVAL * 1200) != 0) return; - - tickCount = 0; - - if (thrd == null) - { - thrd = new Thread(new Runnable() - { - public void run() - { - try - { - // We use the inverse of firstPost because if it - // is the first time we are posting, - // it is not a interval ping, so it evaluates to - // FALSE - // Each time thereafter it will evaluate to - // TRUE, i.e PING! - postPlugin(!firstPost); - // After the first post we set firstPost to - // false - // Each post thereafter will be a ping - firstPost = false; - } - catch (IOException e) - { - if (debug) - { - FMLLog.info("[Metrics] Exception - %s", e.getMessage()); - } - } - finally - { - thrd = null; - } - } - }); - thrd.start(); - } - } - - /** - * Stop processing - */ - public void stop() - { - FMLCommonHandler.instance().bus().unregister(this); - } - - /** - * Has the server owner denied plugin metrics? - * - * @return true if metrics should be opted out of it - */ - public boolean isOptOut() - { - // Reload the metrics file - configuration.load(); - return configuration.get(Configuration.CATEGORY_GENERAL, "opt-out", false).getBoolean(false); - } - - /** - * Enables metrics for the server by setting "opt-out" to false in the - * config file and starting the metrics task. - * - * @throws java.io.IOException - */ - public void enable() throws IOException - { - // Check if the server owner has already set opt-out, if not, set it. - if (isOptOut()) - { - configuration.getCategory(Configuration.CATEGORY_GENERAL).get("opt-out").set("false"); - configuration.save(); - } - FMLCommonHandler.instance().bus().register(this); - } - - /** - * Disables metrics for the server by setting "opt-out" to true in the - * config file and canceling the metrics task. - * - * @throws java.io.IOException - */ - public void disable() throws IOException - { - // Check if the server owner has already set opt-out, if not, set it. - if (!isOptOut()) - { - configuration.getCategory(Configuration.CATEGORY_GENERAL).get("opt-out").set("true"); - configuration.save(); - } - FMLCommonHandler.instance().bus().unregister(this); - } - - /** - * Gets the File object of the config file that should be used to store data - * such as the GUID and opt-out status - * - * @return the File object for the config file - */ - public File getConfigFile() - { - return new File(Loader.instance().getConfigDir(), "PluginMetrics.cfg"); - } - - /** - * Generic method that posts a plugin to the metrics website - */ - private void postPlugin(final boolean isPing) throws IOException - { - // Server software specific section - String pluginName = modname; - MinecraftServer minecraftServer = FMLCommonHandler.instance().getMinecraftServerInstance(); - boolean onlineMode = minecraftServer.isServerInOnlineMode(); - - String pluginVersion = modversion; - String serverVersion; - if (minecraftServer.isDedicatedServer()) - { - serverVersion = "MinecraftForge (MC: " + minecraftServer.getMinecraftVersion() + ")"; - } - else - { - serverVersion = "MinecraftForgeSSP (MC: " + minecraftServer.getMinecraftVersion() + ")"; - } - int playersOnline = minecraftServer.getCurrentPlayerCount(); - - // END server software specific section -- all code below does not use any code outside of this class / Java - - // Construct the post data - StringBuilder json = new StringBuilder(1024); - json.append('{'); - - // The plugin's description file containg all of the plugin data such as name, version, author, etc - appendJSONPair(json, "guid", guid); - appendJSONPair(json, "plugin_version", pluginVersion); - appendJSONPair(json, "server_version", serverVersion); - appendJSONPair(json, "players_online", Integer.toString(playersOnline)); - - // New data as of R6 - String osname = System.getProperty("os.name"); - String osarch = System.getProperty("os.arch"); - String osversion = System.getProperty("os.version"); - String java_version = System.getProperty("java.version"); - int coreCount = Runtime.getRuntime().availableProcessors(); - - // normalize os arch .. amd64 -> x86_64 - if (osarch.equals("amd64")) - { - osarch = "x86_64"; - } - - appendJSONPair(json, "osname", osname); - appendJSONPair(json, "osarch", osarch); - appendJSONPair(json, "osversion", osversion); - appendJSONPair(json, "cores", Integer.toString(coreCount)); - appendJSONPair(json, "auth_mode", onlineMode ? "1" : "0"); - appendJSONPair(json, "java_version", java_version); - - // If we're pinging, append it - if (isPing) - { - appendJSONPair(json, "ping", "1"); - } - - if (graphs.size() > 0) - { - synchronized (graphs) - { - json.append(','); - json.append('"'); - json.append("graphs"); - json.append('"'); - json.append(':'); - json.append('{'); - - boolean firstGraph = true; - - final Iterator iter = graphs.iterator(); - - while (iter.hasNext()) - { - Graph graph = iter.next(); - - StringBuilder graphJson = new StringBuilder(); - graphJson.append('{'); - - for (Plotter plotter : graph.getPlotters()) - { - appendJSONPair(graphJson, plotter.getColumnName(), Integer.toString(plotter.getValue())); - } - - graphJson.append('}'); - - if (!firstGraph) - { - json.append(','); - } - - json.append(escapeJSON(graph.getName())); - json.append(':'); - json.append(graphJson); - - firstGraph = false; - } - - json.append('}'); - } - } - - // close json - json.append('}'); - - // Create the url - URL url = new URL(BASE_URL + String.format(REPORT_URL, urlEncode(pluginName))); - - // Connect to the website - URLConnection connection; - - // Mineshafter creates a socks proxy, so we can safely bypass it - // It does not reroute POST requests so we need to go around it - if (isMineshafterPresent()) - { - connection = url.openConnection(Proxy.NO_PROXY); - } - else - { - connection = url.openConnection(); - } - - - byte[] uncompressed = json.toString().getBytes(); - byte[] compressed = gzip(json.toString()); - - // Headers - connection.addRequestProperty("User-Agent", "MCStats/" + REVISION); - connection.addRequestProperty("Content-Type", "application/json"); - connection.addRequestProperty("Content-Encoding", "gzip"); - connection.addRequestProperty("Content-Length", Integer.toString(compressed.length)); - connection.addRequestProperty("Accept", "application/json"); - connection.addRequestProperty("Connection", "close"); - - connection.setDoOutput(true); - - if (debug) - { - System.out.println("[Metrics] Prepared request for " + pluginName + " uncompressed=" + uncompressed.length + " compressed=" + compressed.length); - } - - // Write the data - OutputStream os = connection.getOutputStream(); - os.write(compressed); - os.flush(); - - // Now read the response - final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); - String response = reader.readLine(); - - // close resources - os.close(); - reader.close(); - - if (response == null || response.startsWith("ERR") || response.startsWith("7")) - { - if (response == null) - { - response = "null"; - } - else if (response.startsWith("7")) - { - response = response.substring(response.startsWith("7,") ? 2 : 1); - } - - throw new IOException(response); - } - else - { - // Is this the first update this hour? - if (response.equals("1") || response.contains("This is your first update this hour")) - { - synchronized (graphs) - { - final Iterator iter = graphs.iterator(); - - while (iter.hasNext()) - { - final Graph graph = iter.next(); - - for (Plotter plotter : graph.getPlotters()) - { - plotter.reset(); - } - } - } - } - } - } - - /** - * GZip compress a string of bytes - * - * @param input - * @return - */ - public static byte[] gzip(String input) - { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - GZIPOutputStream gzos = null; - - try - { - gzos = new GZIPOutputStream(baos); - gzos.write(input.getBytes("UTF-8")); - } - catch (IOException e) - { - e.printStackTrace(); - } - finally - { - if (gzos != null) try - { - gzos.close(); - } - catch (IOException ignore) - { - } - } - - return baos.toByteArray(); - } - - /** - * Check if mineshafter is present. If it is, we need to bypass it to send POST requests - * - * @return true if mineshafter is installed on the server - */ - private boolean isMineshafterPresent() - { - try - { - Class.forName("mineshafter.MineServer"); - return true; - } - catch (Exception e) - { - return false; - } - } - - /** - * Appends a json encoded key/value pair to the given string builder. - * - * @param json - * @param key - * @param value - * @throws java.io.UnsupportedEncodingException - */ - private static void appendJSONPair(StringBuilder json, String key, String value) throws UnsupportedEncodingException - { - boolean isValueNumeric = false; - - try - { - if (value.equals("0") || !value.endsWith("0")) - { - Double.parseDouble(value); - isValueNumeric = true; - } - } - catch (NumberFormatException e) - { - isValueNumeric = false; - } - - if (json.charAt(json.length() - 1) != '{') - { - json.append(','); - } - - json.append(escapeJSON(key)); - json.append(':'); - - if (isValueNumeric) - { - json.append(value); - } - else - { - json.append(escapeJSON(value)); - } - } - - /** - * Escape a string to create a valid JSON string - * - * @param text - * @return - */ - private static String escapeJSON(String text) - { - StringBuilder builder = new StringBuilder(); - - builder.append('"'); - for (int index = 0; index < text.length(); index++) - { - char chr = text.charAt(index); - - switch (chr) - { - case '"': - case '\\': - builder.append('\\'); - builder.append(chr); - break; - case '\b': - builder.append("\\b"); - break; - case '\t': - builder.append("\\t"); - break; - case '\n': - builder.append("\\n"); - break; - case '\r': - builder.append("\\r"); - break; - default: - if (chr < ' ') - { - String t = "000" + Integer.toHexString(chr); - builder.append("\\u" + t.substring(t.length() - 4)); - } - else - { - builder.append(chr); - } - break; - } - } - builder.append('"'); - - return builder.toString(); - } - - /** - * Encode text as UTF-8 - * - * @param text the text to encode - * @return the encoded text, as UTF-8 - */ - private static String urlEncode(final String text) throws UnsupportedEncodingException - { - return URLEncoder.encode(text, "UTF-8"); - } - - /** - * Represents a custom graph on the website - */ - public static class Graph - { - - /** - * The graph's name, alphanumeric and spaces only :) If it does not comply to the above when submitted, it is - * rejected - */ - private final String name; - - /** - * The set of plotters that are contained within this graph - */ - private final Set plotters = new LinkedHashSet(); - - private Graph(final String name) - { - this.name = name; - } - - /** - * Gets the graph's name - * - * @return the Graph's name - */ - public String getName() - { - return name; - } - - /** - * Add a plotter to the graph, which will be used to plot entries - * - * @param plotter the plotter to add to the graph - */ - public void addPlotter(final Plotter plotter) - { - plotters.add(plotter); - } - - /** - * Remove a plotter from the graph - * - * @param plotter the plotter to remove from the graph - */ - public void removePlotter(final Plotter plotter) - { - plotters.remove(plotter); - } - - /** - * Gets an unmodifiable set of the plotter objects in the graph - * - * @return an unmodifiable {@link java.util.Set} of the plotter objects - */ - public Set getPlotters() - { - return Collections.unmodifiableSet(plotters); - } - - @Override - public int hashCode() - { - return name.hashCode(); - } - - @Override - public boolean equals(final Object object) - { - if (!(object instanceof Graph)) - { - return false; - } - - final Graph graph = (Graph) object; - return graph.name.equals(name); - } - - /** - * Called when the server owner decides to opt-out of BukkitMetrics while the server is running. - */ - protected void onOptOut() - { - } - } - - /** - * Interface used to collect custom data for a plugin - */ - public static abstract class Plotter - { - - /** - * The plot's name - */ - private final String name; - - /** - * Construct a plotter with the default plot name - */ - public Plotter() - { - this("Default"); - } - - /** - * Construct a plotter with a specific plot name - * - * @param name the name of the plotter to use, which will show up on the website - */ - public Plotter(final String name) - { - this.name = name; - } - - /** - * Get the current value for the plotted point. Since this function defers to an external function it may or may - * not return immediately thus cannot be guaranteed to be thread friendly or safe. This function can be called - * from any thread so care should be taken when accessing resources that need to be synchronized. - * - * @return the current value for the point to be plotted. - */ - public abstract int getValue(); - - /** - * Get the column name for the plotted point - * - * @return the plotted point's column name - */ - public String getColumnName() - { - return name; - } - - /** - * Called after the website graphs have been updated - */ - public void reset() - { - } - - @Override - public int hashCode() - { - return getColumnName().hashCode(); - } - - @Override - public boolean equals(final Object object) - { - if (!(object instanceof Plotter)) - { - return false; - } - - final Plotter plotter = (Plotter) object; - return plotter.name.equals(name) && plotter.getValue() == getValue(); - } - } -} diff --git a/src/main/resources/assets/D3Core/lang/en_US.lang b/src/main/resources/assets/D3Core/lang/en_US.lang index b520025..dd1d0c5 100644 --- a/src/main/resources/assets/D3Core/lang/en_US.lang +++ b/src/main/resources/assets/D3Core/lang/en_US.lang @@ -9,11 +9,11 @@ d3.core.config.debug.tooltip=Please enable before making a bug report. d3.core.config.printDeathCoords=Print your death coordinates in chat (client side) d3.core.config.printDeathCoords.tooltip=Contains a clickable TP command thing too! -d3.core.config.sillyness=Enable sillyness -d3.core.config.sillyness.tooltip=Please don't disable, unless you want to piss off the D³ crew :p But seriously, you can disable name changes, drops and block helmets with this setting. +d3.core.config.Silliness=Enable silliness +d3.core.config.Silliness.tooltip=Please don't disable, unless you want to piss off the D³ crew :p But seriously, you can disable name changes, drops and block helmets with this setting. -d3.core.config.updateWarning=Update warnings -d3.core.config.updateWarning.tooltip=Please don't disable, unless you are on a modpack. +d3.core.config.achievementFireworks=Achievement is Fireworks! +d3.core.config.achievementFireworks.tooltip=I made this just to annoy Clay & James. Have fun with it! d3.core.config.tooltips=Tooltips d3.core.config.tooltips.tooltip=Item hover options, toggle with F3 + H diff --git a/src/main/resources/assets/D3Core/lang/pl_PL.lang b/src/main/resources/assets/D3Core/lang/pl_PL.lang index 9947cc0..22ce57c 100644 --- a/src/main/resources/assets/D3Core/lang/pl_PL.lang +++ b/src/main/resources/assets/D3Core/lang/pl_PL.lang @@ -6,8 +6,8 @@ d3.core.config.core.tooltip=Działa na wszystkie mody D³ d3.core.config.debug=Tryb debugowania d3.core.config.debug.tooltip=Proszę włączyć przed reportowaniem bugów. -d3.core.config.sillyness=Włącz głupoty -d3.core.config.sillyness.tooltip=Proszę nie wyłączać, chyba, że chcesz wkurzyć ekipę D³ :p Ale poważnie, możesz wyłączyć zmiany nazw, wypadające przedmioty i blokować hełmy tym ustawieniem. +d3.core.config.silliness=Włącz głupoty +d3.core.config.silliness.tooltip=Proszę nie wyłączać, chyba, że chcesz wkurzyć ekipę D³ :p Ale poważnie, możesz wyłączyć zmiany nazw, wypadające przedmioty i blokować hełmy tym ustawieniem. d3.core.config.updateWarning=Ostrzeżenia o uaktualnieniach d3.core.config.updateWarning.tooltip=Proszę nie wyłączać, chyba, że używasz paczki modów. diff --git a/src/main/resources/assets/D3Core/lang/ru_RU.lang b/src/main/resources/assets/D3Core/lang/ru_RU.lang index f544c59..fdd1833 100644 --- a/src/main/resources/assets/D3Core/lang/ru_RU.lang +++ b/src/main/resources/assets/D3Core/lang/ru_RU.lang @@ -6,8 +6,8 @@ d3.core.config.core.tooltip=Применяется для всех модов D d3.core.config.debug=Режим отладки d3.core.config.debug.tooltip=Пожалуйста, включите, прежде чем отправить отчёт об ошибке. -d3.core.config.sillyness=Включение примочек -d3.core.config.sillyness.tooltip=Пожалуйста не отключайте, если Вы не хотите позлить команду D³ :p А если серьезно, Вы можете отключить изменения имени, выпадение предметов и шлемы-блоки этой настройкой. +d3.core.config.silliness=Включение примочек +d3.core.config.silliness.tooltip=Пожалуйста не отключайте, если Вы не хотите позлить команду D³ :p А если серьезно, Вы можете отключить изменения имени, выпадение предметов и шлемы-блоки этой настройкой. d3.core.config.updateWarning=Предупреждения об обновлениях d3.core.config.updateWarning.tooltip=Пожалуйста, не отключайте, если только Вы не используете пакет модов. diff --git a/src/main/resources/assets/D3Core/lang/zh_CN.lang b/src/main/resources/assets/D3Core/lang/zh_CN.lang index 9cc66ee..627d23f 100644 --- a/src/main/resources/assets/D3Core/lang/zh_CN.lang +++ b/src/main/resources/assets/D3Core/lang/zh_CN.lang @@ -9,8 +9,8 @@ d3.core.config.debug.tooltip=请在错误报告生成前开启. d3.core.config.printDeathCoords=显示死亡坐标在聊天窗口(客户端) d3.core.config.printDeathCoords.tooltip=同时也包含可点击的传送指令! -d3.core.config.sillyness=开启意义不明项 -d3.core.config.sillyness.tooltip=请勿禁用此项,除非你讨厌D³团队:p 但严肃地说,你可以用该设定禁用名称变更,掉落以及方块保护等. +d3.core.config.silliness=开启意义不明项 +d3.core.config.silliness.tooltip=请勿禁用此项,除非你讨厌D³团队:p 但严肃地说,你可以用该设定禁用名称变更,掉落以及方块保护等. d3.core.config.updateWarning=更新警告 d3.core.config.updateWarning.tooltip=请勿禁用,除非你使用的整合包. diff --git a/src/main/resources/mcmod.info b/src/main/resources/mcmod.info index 0a3bbba..1602cfa 100644 --- a/src/main/resources/mcmod.info +++ b/src/main/resources/mcmod.info @@ -2,13 +2,13 @@ "modListVersion": 2, "modList": [{ "modid": "D3Core", - "name": "D3Core", + "name": "D³Core", "description": "${description}", "version": "${version}", "mcversion": "${mcversion}", "url": "https://github.com/${githuborg}/${modid}", "updateUrl": "", - "authorList": [ "Dries007", "Doubledoor team" ], + "authorList": [ "Dries007", "DoubleDoor team" ], "credits": "", "logoFile": "", "screenshots": [], diff --git a/template/README.md b/template/README.md deleted file mode 100644 index cc2a2d2..0000000 --- a/template/README.md +++ /dev/null @@ -1 +0,0 @@ -This folder contains files for a correct dependent mod setup. \ No newline at end of file diff --git a/template/resources/mcmod.info b/template/resources/mcmod.info deleted file mode 100644 index cbfa202..0000000 --- a/template/resources/mcmod.info +++ /dev/null @@ -1,21 +0,0 @@ -{ - "modListVersion": 2, - "modList": [{ - "modid": "${modid}", - "name": "${modid}", - "description": "${description}", - "version": "${version}", - "mcversion": "${mcversion}", - "url": "https://github.com/${githuborg}/${modid}", - "updateUrl": "", - "authorList": [ "Dries007", "Doubledoor team" ], - "credits": "", - "logoFile": "", - "screenshots": [], - "parent": "", - "requiredMods": [ "Forge" ], - "dependencies": [ ], - "dependants": [ ], - "useDependencyInformation": true - }] -} \ No newline at end of file diff --git a/template/resources/version.properties b/template/resources/version.properties deleted file mode 100644 index 5918f0e..0000000 --- a/template/resources/version.properties +++ /dev/null @@ -1,3 +0,0 @@ -${modid}.version=${version} -${modid}.group=${group} -${modid}.artifactId=${artifactId}