diff options
author | nea <romangraef@gmail.com> | 2022-04-27 01:07:45 +0200 |
---|---|---|
committer | nea <romangraef@gmail.com> | 2022-04-27 01:07:45 +0200 |
commit | 09a7b56f97e90fd7241a259e39079d56f377c392 (patch) | |
tree | bc8911807d487cdb258c662e8267a308b134db1f | |
parent | acd66175bccf2ba6e9059405edddcd760956cf47 (diff) | |
download | NotEnoughUpdates-09a7b56f97e90fd7241a259e39079d56f377c392.tar.gz NotEnoughUpdates-09a7b56f97e90fd7241a259e39079d56f377c392.tar.bz2 NotEnoughUpdates-09a7b56f97e90fd7241a259e39079d56f377c392.zip |
add teleporter navigation because i can
7 files changed, 316 insertions, 202 deletions
diff --git a/src/main/java/io/github/moulberry/notenoughupdates/NEUManager.java b/src/main/java/io/github/moulberry/notenoughupdates/NEUManager.java index 733a34ec..b11379a6 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/NEUManager.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/NEUManager.java @@ -1,14 +1,24 @@ package io.github.moulberry.notenoughupdates; -import com.google.gson.*; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; import io.github.moulberry.notenoughupdates.auction.APIManager; +import io.github.moulberry.notenoughupdates.events.RepositoryReloadEvent; import io.github.moulberry.notenoughupdates.miscgui.GuiItemRecipe; import io.github.moulberry.notenoughupdates.miscgui.KatSitterOverlay; import io.github.moulberry.notenoughupdates.recipes.CraftingOverlay; import io.github.moulberry.notenoughupdates.recipes.CraftingRecipe; import io.github.moulberry.notenoughupdates.recipes.Ingredient; import io.github.moulberry.notenoughupdates.recipes.NeuRecipe; -import io.github.moulberry.notenoughupdates.util.*; +import io.github.moulberry.notenoughupdates.util.Constants; +import io.github.moulberry.notenoughupdates.util.HotmInformation; +import io.github.moulberry.notenoughupdates.util.HypixelApi; +import io.github.moulberry.notenoughupdates.util.SBInfo; +import io.github.moulberry.notenoughupdates.util.Utils; import net.minecraft.client.Minecraft; import net.minecraft.client.settings.KeyBinding; import net.minecraft.init.Blocks; @@ -16,24 +26,49 @@ import net.minecraft.init.Items; import net.minecraft.inventory.ContainerChest; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import net.minecraft.nbt.*; +import net.minecraft.nbt.CompressedStreamTools; +import net.minecraft.nbt.JsonToNBT; +import net.minecraft.nbt.NBTException; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.nbt.NBTTagString; import net.minecraft.util.ResourceLocation; -import net.minecraftforge.fml.common.ProgressManager; import org.apache.commons.io.FileUtils; import org.lwjgl.input.Keyboard; import org.lwjgl.opengl.Display; import javax.net.ssl.HttpsURLConnection; -import javax.swing.JDialog; -import javax.swing.JOptionPane; -import java.io.*; +import javax.swing.*; +import java.io.BufferedInputStream; +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.Reader; import java.net.URL; import java.net.URLConnection; import java.nio.charset.StandardCharsets; -import java.util.*; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.NavigableMap; +import java.util.Optional; +import java.util.Set; +import java.util.TreeMap; +import java.util.TreeSet; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; import java.util.stream.Collectors; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; @@ -73,8 +108,6 @@ public class NEUManager { private final Map<String, ItemStack> itemstackCache = new HashMap<>(); - private final ExecutorService repoLoaderES = Executors.newSingleThreadExecutor(); - private static String GIT_COMMITS_URL; // TODO: private final Map<String, NeuItem> @@ -160,187 +193,102 @@ public class NEUManager { } } - /** - * Called when the game is first loaded. Compares the local repository to the github repository and handles the - * downloading of new/updated files. This then calls the "loadItem" method for every item in the local repository. - */ - public void loadItemInformation() { - /*File repoFile = new File(configLocation, "repo2"); - repoFile.mkdirs(); - - try(Git git = Git.init().setDirectory(repoFile).call()) { - StoredConfig config = git.getRepository().getConfig(); - config.setString("branch", "master", "merge", "refs/heads/master"); - config.setString("branch", "master", "remote", "origin"); - config.setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*"); - config.setString("remote", "origin", "url", "https://github.com/Moulberry/NotEnoughUpdates-REPO.git"); - config.save(); - - git.remoteAdd().setName("origin").setUri(new URIish("https://github.com/Moulberry/NotEnoughUpdates-REPO.git")).call(); - PullResult result = git.pull().setRemote("origin").setTimeout(30000).call(); - System.out.println("successful pull: " + result.isSuccessful()); - } catch(Exception e) { - e.printStackTrace(); - }*/ - - /*if(repoFile.mkdirs()) { - try { - Git.cloneRepository() - .setURI("https://github.com/Moulberry/NotEnoughUpdates-REPO.git") - .setDirectory(repoFile) - .call(); - } catch(Exception e) { - e.printStackTrace(); - } - } else { - - }*/ - - repoLoaderES.submit(() -> { + public CompletableFuture<Boolean> fetchRepository() { + if (!NotEnoughUpdates.INSTANCE.config.hidden.autoupdate) { + return CompletableFuture.completedFuture(false); + } + return CompletableFuture.<Boolean>supplyAsync(() -> { JDialog dialog = null; try { - if (NotEnoughUpdates.INSTANCE.config.hidden.autoupdate) { - JOptionPane pane = new JOptionPane("Getting items to download from remote repository."); - dialog = pane.createDialog("NotEnoughUpdates Remote Sync"); - dialog.setModal(false); - if (NotEnoughUpdates.INSTANCE.config.hidden.dev) dialog.setVisible(true); - - if (Display.isActive()) dialog.toFront(); - - JsonObject currentCommitJSON = getJsonFromFile(new File(configLocation, "currentCommit.json")); - - latestRepoCommit = null; - try (Reader inReader = new InputStreamReader(new URL(GIT_COMMITS_URL).openStream())) { - JsonObject commits = gson.fromJson(inReader, JsonObject.class); - latestRepoCommit = commits.get("sha").getAsString(); - } catch (Exception e) { - e.printStackTrace(); - } - if (latestRepoCommit == null || latestRepoCommit.isEmpty()) return; + JOptionPane pane = new JOptionPane("Getting items to download from remote repository."); + dialog = pane.createDialog("NotEnoughUpdates Remote Sync"); + dialog.setModal(false); + if (NotEnoughUpdates.INSTANCE.config.hidden.dev) dialog.setVisible(true); - if (new File(configLocation, "repo").exists() && new File(configLocation, "repo/items").exists()) { - if (currentCommitJSON != null && currentCommitJSON.get("sha").getAsString().equals(latestRepoCommit)) { - dialog.setVisible(false); - return; - } + if (Display.isActive()) dialog.toFront(); + + JsonObject currentCommitJSON = getJsonFromFile(new File(configLocation, "currentCommit.json")); + + latestRepoCommit = null; + try (Reader inReader = new InputStreamReader(new URL(GIT_COMMITS_URL).openStream())) { + JsonObject commits = gson.fromJson(inReader, JsonObject.class); + latestRepoCommit = commits.get("sha").getAsString(); + } catch (Exception e) { + e.printStackTrace(); + } + if (latestRepoCommit == null || latestRepoCommit.isEmpty()) return false; + + if (new File(configLocation, "repo").exists() && new File(configLocation, "repo/items").exists()) { + if (currentCommitJSON != null && currentCommitJSON.get("sha").getAsString().equals(latestRepoCommit)) { + return false; } + } - if (Display.isActive()) dialog.toFront(); + if (Display.isActive()) dialog.toFront(); - Utils.recursiveDelete(repoLocation); - repoLocation.mkdirs(); + Utils.recursiveDelete(repoLocation); + repoLocation.mkdirs(); - String dlUrl = neu.config.hidden.repoURL; + String dlUrl = neu.config.hidden.repoURL; - pane.setMessage("Downloading NEU Master Archive. (DL# >20)"); - dialog.pack(); - if (NotEnoughUpdates.INSTANCE.config.hidden.dev) dialog.setVisible(true); - if (Display.isActive()) dialog.toFront(); + pane.setMessage("Downloading NEU Master Archive. (DL# >20)"); + dialog.pack(); + if (NotEnoughUpdates.INSTANCE.config.hidden.dev) dialog.setVisible(true); + if (Display.isActive()) dialog.toFront(); - File itemsZip = new File(repoLocation, "neu-items-master.zip"); - try { - itemsZip.createNewFile(); - } catch (IOException e) { - return; - } + File itemsZip = new File(repoLocation, "neu-items-master.zip"); + try { + itemsZip.createNewFile(); + } catch (IOException e) { + return false; + } - URL url = new URL(dlUrl); - URLConnection urlConnection = url.openConnection(); - urlConnection.setConnectTimeout(15000); - urlConnection.setReadTimeout(30000); - - try (InputStream is = urlConnection.getInputStream()) { - FileUtils.copyInputStreamToFile(is, itemsZip); - } catch (IOException e) { - dialog.dispose(); - e.printStackTrace(); - System.err.println("Failed to download NEU Repo! Please report this issue to the mod creator"); - return; - } - /*try ( - BufferedInputStream inStream = new BufferedInputStream(urlConnection.getInputStream()); - FileOutputStream fileOutputStream = new FileOutputStream(itemsZip) - ) { - byte dataBuffer[] = new byte[1024]; - int bytesRead; - while ((bytesRead = inStream.read(dataBuffer, 0, 1024)) != -1) { - fileOutputStream.write(dataBuffer, 0, bytesRead); - } - } catch (IOException e) { - dialog.dispose(); - return; - }*/ - - pane.setMessage("Unzipping NEU Master Archive."); - dialog.pack(); - //dialog.setVisible(true); - if (Display.isActive()) dialog.toFront(); - - unzipIgnoreFirstFolder(itemsZip.getAbsolutePath(), repoLocation.getAbsolutePath()); - - if (currentCommitJSON == null || !currentCommitJSON.get("sha").getAsString().equals(latestRepoCommit)) { - JsonObject newCurrentCommitJSON = new JsonObject(); - newCurrentCommitJSON.addProperty("sha", latestRepoCommit); - try { - writeJson(newCurrentCommitJSON, new File(configLocation, "currentCommit.json")); - } catch (IOException ignored) { - } - } + URL url = new URL(dlUrl); + URLConnection urlConnection = url.openConnection(); + urlConnection.setConnectTimeout(15000); + urlConnection.setReadTimeout(30000); + + try (InputStream is = urlConnection.getInputStream()) { + FileUtils.copyInputStreamToFile(is, itemsZip); + } catch (IOException e) { + dialog.dispose(); + e.printStackTrace(); + System.err.println("Failed to download NEU Repo! Please report this issue to the mod creator"); + return false; } - } catch (Exception e) { - e.printStackTrace(); - } finally { - if (dialog != null) dialog.dispose(); - } - File items = new File(repoLocation, "items"); - if (items.exists()) { - File[] itemFiles = new File(repoLocation, "items").listFiles(); - if (itemFiles != null) { - ProgressManager.ProgressBar bar = ProgressManager.push("Loading recipes", itemFiles.length); - for (File f : itemFiles) { - String internalname = f.getName().substring(0, f.getName().length() - 5); - bar.step(internalname); - synchronized (itemMap) { - if (!itemMap.containsKey(internalname)) { - loadItem(internalname); - } - } + pane.setMessage("Unzipping NEU Master Archive."); + dialog.pack(); + //dialog.setVisible(true); + if (Display.isActive()) dialog.toFront(); + + unzipIgnoreFirstFolder(itemsZip.getAbsolutePath(), repoLocation.getAbsolutePath()); + + if (currentCommitJSON == null || !currentCommitJSON.get("sha").getAsString().equals(latestRepoCommit)) { + JsonObject newCurrentCommitJSON = new JsonObject(); + newCurrentCommitJSON.addProperty("sha", latestRepoCommit); + try { + writeJson(newCurrentCommitJSON, new File(configLocation, "currentCommit.json")); + } catch (IOException ignored) { } - ProgressManager.pop(bar); } - } - - try { - Constants.reload(); } catch (Exception e) { e.printStackTrace(); + } finally { + if (dialog != null) dialog.dispose(); } + return true; }); + } - File items = new File(repoLocation, "items"); - if (items.exists()) { - File[] itemFiles = new File(repoLocation, "items").listFiles(); - if (itemFiles != null) { - ProgressManager.ProgressBar bar = ProgressManager.push("Loading items", itemFiles.length); - for (File f : itemFiles) { - String internalname = f.getName().substring(0, f.getName().length() - 5); - bar.step(internalname); - synchronized (itemMap) { - if (!itemMap.containsKey(internalname)) { - loadItem(internalname); - } - } - } - ProgressManager.pop(bar); - } - } - - try { - Constants.reload(); - } catch (Exception e) { - e.printStackTrace(); - } + /** + * Called when the game is first loaded. Compares the local repository to the github repository and handles the + * downloading of new/updated files. This then calls the "loadItem" method for every item in the local repository. + */ + public void loadItemInformation() { + fetchRepository().thenAccept(i -> { + reloadRepository(); + }); } /** @@ -1559,20 +1507,24 @@ public class NEUManager { } public void reloadRepository() { - File items = new File(repoLocation, "items"); - if (items.exists()) { - recipes.clear(); - recipesMap.clear(); - usagesMap.clear(); - - File[] itemFiles = new File(repoLocation, "items").listFiles(); - if (itemFiles != null) { - for (File f : itemFiles) { - String internalname = f.getName().substring(0, f.getName().length() - 5); - loadItem(internalname); + Minecraft.getMinecraft().addScheduledTask(() -> { + File items = new File(repoLocation, "items"); + if (items.exists()) { + recipes.clear(); + recipesMap.clear(); + usagesMap.clear(); + + File[] itemFiles = new File(repoLocation, "items").listFiles(); + if (itemFiles != null) { + for (File f : itemFiles) { + String internalname = f.getName().substring(0, f.getName().length() - 5); + loadItem(internalname); + } } } - } + + new RepositoryReloadEvent(repoLocation).post(); + }); } public ItemStack createItem(String internalname) { diff --git a/src/main/java/io/github/moulberry/notenoughupdates/commands/repo/ReloadRepoCommand.java b/src/main/java/io/github/moulberry/notenoughupdates/commands/repo/ReloadRepoCommand.java index e363b59f..33efcb52 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/commands/repo/ReloadRepoCommand.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/commands/repo/ReloadRepoCommand.java @@ -21,7 +21,6 @@ public class ReloadRepoCommand extends ClientCommandBase { @Override public void processCommand(ICommandSender sender, String[] args) throws CommandException { NotEnoughUpdates.INSTANCE.manager.reloadRepository(); - Constants.reload(); NotEnoughUpdates.INSTANCE.newConfigFile(); if (NotEnoughUpdates.INSTANCE.getConfigFile().exists()) { diff --git a/src/main/java/io/github/moulberry/notenoughupdates/events/RepositoryReloadEvent.java b/src/main/java/io/github/moulberry/notenoughupdates/events/RepositoryReloadEvent.java new file mode 100644 index 00000000..cc0f8c0c --- /dev/null +++ b/src/main/java/io/github/moulberry/notenoughupdates/events/RepositoryReloadEvent.java @@ -0,0 +1,15 @@ +package io.github.moulberry.notenoughupdates.events; + +import java.io.File; + +public class RepositoryReloadEvent extends NEUEvent { + private final File baseFile; + + public RepositoryReloadEvent(File baseFile) { + this.baseFile = baseFile; + } + + public File getRepositoryRoot() { + return baseFile; + } +} diff --git a/src/main/java/io/github/moulberry/notenoughupdates/miscfeatures/Navigation.java b/src/main/java/io/github/moulberry/notenoughupdates/miscfeatures/Navigation.java index 86b129c7..a8f3ea9f 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/miscfeatures/Navigation.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/miscfeatures/Navigation.java @@ -1,17 +1,46 @@ package io.github.moulberry.notenoughupdates.miscfeatures; +import com.google.gson.JsonElement; import com.google.gson.JsonObject; import io.github.moulberry.notenoughupdates.NotEnoughUpdates; import io.github.moulberry.notenoughupdates.core.util.render.RenderUtils; +import io.github.moulberry.notenoughupdates.events.RepositoryReloadEvent; +import io.github.moulberry.notenoughupdates.miscfeatures.customblockzones.LocationChangeEvent; +import io.github.moulberry.notenoughupdates.util.JsonUtils; import io.github.moulberry.notenoughupdates.util.SBInfo; +import io.github.moulberry.notenoughupdates.util.Utils; import net.minecraft.client.Minecraft; +import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumChatFormatting; import net.minecraftforge.client.event.RenderWorldLastEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + public class Navigation { + private List<Teleporter> teleporters = new ArrayList<>(); + private Map<String, String> areaNames = new HashMap<>(); + + public static class Teleporter { + public final double x, y, z; + public final String from, to; + + public Teleporter(double x, double y, double z, String from, String to) { + this.x = x; + this.y = y; + this.z = z; + this.from = from; + this.to = to; + } + } + private NotEnoughUpdates neu; public Navigation(NotEnoughUpdates notEnoughUpdates) { @@ -24,6 +53,8 @@ public class Navigation { private String island = null; private String displayName = null; + private Teleporter nextTeleporter = null; + public void trackWaypoint(JsonObject trackNow) { if (trackNow != null && ( !trackNow.has("x") @@ -38,6 +69,36 @@ public class Navigation { updateData(); } + @SubscribeEvent + public void onRepositoryReload(RepositoryReloadEvent event) { + JsonObject obj = Utils.getConstant("islands", neu.manager.gson); + List<Teleporter> teleporters = JsonUtils.getJsonArrayOrEmpty(obj, "teleporters", jsonElement -> { + JsonObject teleporterObj = jsonElement.getAsJsonObject(); + return new Teleporter( + teleporterObj.get("x").getAsDouble(), + teleporterObj.get("y").getAsDouble(), + teleporterObj.get("z").getAsDouble(), + teleporterObj.get("from").getAsString(), + teleporterObj.get("to").getAsString() + ); + }); + for (Teleporter teleporter : teleporters) { + if (teleporter.from.equals(teleporter.to)) { + showError("Found self referencing teleporter: " + teleporter.from); + } + } + this.teleporters = teleporters; + this.areaNames = JsonUtils.transformJsonObjectToMap(obj.getAsJsonObject("area_names"), JsonElement::getAsString); + } + + public String getNameForAreaMode(String mode) { + return areaNames.get(mode); + } + + public String getNameForAreaModeOrUnknown(String mode) { + return areaNames.getOrDefault(mode, "Unknown"); + } + public void untrackWaypoint() { trackWaypoint(null); } @@ -63,6 +124,7 @@ public class Navigation { position = null; island = null; displayName = null; + nextTeleporter = null; } position = new BlockPos( currentlyTrackedWaypoint.get("x").getAsDouble(), @@ -71,18 +133,72 @@ public class Navigation { ); island = currentlyTrackedWaypoint.get("island").getAsString(); displayName = currentlyTrackedWaypoint.get("displayname").getAsString(); + recalculateNextTeleporter(); + } + + @SubscribeEvent + public void onLocationChange(LocationChangeEvent event) { + recalculateNextTeleporter(); + } + + public Teleporter recalculateNextTeleporter() { + String from = SBInfo.getInstance().mode; + String to = island; + if (from == null || to == null) return null; + List<Teleporter> nextTeleporter = findNextTeleporter0(from, to, new HashSet<>()); + if (nextTeleporter == null || nextTeleporter.isEmpty()) { + this.nextTeleporter = null; + } else { + this.nextTeleporter = nextTeleporter.get(0); + } + return this.nextTeleporter; + } + + private List<Teleporter> findNextTeleporter0(String from, String to, Set<String> visited) { + if (from.equals(to)) return new ArrayList<>(); + if (visited.contains(from)) return null; + visited.add(from); + int minPathLength = 0; + List<Teleporter> minPath = null; + for (Teleporter teleporter : teleporters) { + if (!teleporter.from.equals(from)) continue; + List<Teleporter> nextTeleporter0 = findNextTeleporter0(teleporter.to, to, visited); + if (nextTeleporter0 == null) continue; + if (minPath == null || nextTeleporter0.size() < minPathLength) { + minPathLength = nextTeleporter0.size(); + nextTeleporter0.add(teleporter); + minPath = nextTeleporter0; + } + } + visited.remove(from); + return minPath; } private void showError(String message) { - Minecraft.getMinecraft().thePlayer.sendChatMessage(EnumChatFormatting.DARK_RED + - "[NEU-Waypoint] " + message); + EntityPlayerSP player = Minecraft.getMinecraft().thePlayer; + if (player != null) + player.sendChatMessage(EnumChatFormatting.DARK_RED + + "[NEU-Waypoint] " + message); new RuntimeException("[NEU-Waypoint] " + message).printStackTrace(); } @SubscribeEvent public void onRenderLast(RenderWorldLastEvent event) { - if (currentlyTrackedWaypoint != null && island.equals(SBInfo.getInstance().mode)) { - RenderUtils.renderWayPoint(displayName, position, event.partialTicks); + if (currentlyTrackedWaypoint != null) { + if (island.equals(SBInfo.getInstance().mode)) { + RenderUtils.renderWayPoint(displayName, position, event.partialTicks); + } else if (nextTeleporter != null) { + String to = nextTeleporter.to; + String toName = getNameForAreaModeOrUnknown(to); + RenderUtils.renderWayPoint( + "Teleporter to " + toName + " (towards " + displayName + "§r)", + new BlockPos( + nextTeleporter.x, + nextTeleporter.y, + nextTeleporter.z + ), event.partialTicks + ); + } } } } diff --git a/src/main/java/io/github/moulberry/notenoughupdates/profileviewer/GuiProfileViewer.java b/src/main/java/io/github/moulberry/notenoughupdates/profileviewer/GuiProfileViewer.java index 691ccaae..95a293df 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/profileviewer/GuiProfileViewer.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/profileviewer/GuiProfileViewer.java @@ -4816,12 +4816,7 @@ public class GuiProfileViewer extends GuiScreen { if (profile.getUuid().equals("20934ef9488c465180a78f861586b4cf")) { locationStr = "Ignoring DMs"; } else { - if (location != null) { - JsonObject misc = Constants.MISC; - if (misc != null) { - locationStr = Utils.getElementAsString(Utils.getElement(misc, "area_names." + location), "Unknown"); - } - } + locationStr = NotEnoughUpdates.INSTANCE.navigation.getNameForAreaModeOrUnknown(location); } if (locationStr != null) { statusStr += EnumChatFormatting.GRAY + " - " + EnumChatFormatting.GREEN + locationStr; diff --git a/src/main/java/io/github/moulberry/notenoughupdates/util/Constants.java b/src/main/java/io/github/moulberry/notenoughupdates/util/Constants.java index dab4844d..4c421f3e 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/util/Constants.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/util/Constants.java @@ -1,6 +1,17 @@ package io.github.moulberry.notenoughupdates.util; -import com.google.gson.*; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import io.github.moulberry.notenoughupdates.events.RepositoryReloadEvent; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import java.lang.reflect.Type; import java.util.concurrent.locks.ReentrantLock; @@ -42,7 +53,8 @@ public class Constants { private static final ReentrantLock lock = new ReentrantLock(); - public static void reload() { + @SubscribeEvent + public void reload(RepositoryReloadEvent event) { try { lock.lock(); @@ -57,6 +69,8 @@ public class Constants { ESSENCECOSTS = Utils.getConstant("essencecosts", gson); FAIRYSOULS = Utils.getConstant("fairy_souls", gson); REFORGESTONES = Utils.getConstant("reforgestones", gson); + } catch (Exception ex) { + ex.printStackTrace(); } finally { lock.unlock(); } diff --git a/src/main/java/io/github/moulberry/notenoughupdates/util/JsonUtils.java b/src/main/java/io/github/moulberry/notenoughupdates/util/JsonUtils.java index 916631b7..b4193c88 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/util/JsonUtils.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/util/JsonUtils.java @@ -5,7 +5,9 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import java.util.Collections; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -16,11 +18,18 @@ public class JsonUtils { return StreamSupport.stream(array.spliterator(), false); } - public static <T> List<T> transformJsonArrayToList(JsonArray array, Function<? super JsonElement, ? extends T> mapper) { + public static <T> List<T> transformJsonArrayToList( + JsonArray array, + Function<? super JsonElement, ? extends T> mapper + ) { return getJsonArrayAsStream(array).map(mapper).collect(Collectors.toList()); } - public static <T> List<T> getJsonArrayOrEmpty(JsonObject rootObject, String name, Function<? super JsonElement, ? extends T> mapper) { + public static <T> List<T> getJsonArrayOrEmpty( + JsonObject rootObject, + String name, + Function<? super JsonElement, ? extends T> mapper + ) { if (!rootObject.has(name)) { return Collections.emptyList(); } @@ -31,7 +40,10 @@ public class JsonUtils { return Collections.emptyList(); } - public static <T> JsonArray transformListToJsonArray(List<T> things, Function<? super T, ? extends JsonElement> mapper) { + public static <T> JsonArray transformListToJsonArray( + List<T> things, + Function<? super T, ? extends JsonElement> mapper + ) { JsonArray array = new JsonArray(); for (T t : things) { array.add(mapper.apply(t)); @@ -39,4 +51,15 @@ public class JsonUtils { return array; } + public static <T> Map<String, T> transformJsonObjectToMap( + JsonObject object, + Function<? super JsonElement, ? extends T> mapper + ) { + Map<String, T> map = new HashMap<>(); + for (Map.Entry<String, JsonElement> entry : object.entrySet()) { + map.put(entry.getKey(), mapper.apply(entry.getValue())); + } + return map; + } + } |