From 23b741cb5bf4e5d257fb2722f081581facf2a0ad Mon Sep 17 00:00:00 2001 From: Owen Stubbs Date: Tue, 21 Feb 2023 13:28:24 +0000 Subject: [PATCH 01/19] Update build.gradle --- build.gradle | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/build.gradle b/build.gradle index d8b5c08..0991254 100644 --- a/build.gradle +++ b/build.gradle @@ -9,16 +9,16 @@ version = "${project.mod_version}-${project.minecraft_version}+" group = project.maven_group repositories { + mavenLocal() mavenCentral() - maven { - url "https://maven.shedaniel.me/" - } - maven { - url "https://maven.terraformersmc.com/releases/" - } + + maven { url "https://maven.shedaniel.me/" } + maven { url "https://maven.terraformersmc.com/releases/" } } dependencies { + implementation "net.emc.emcw:EMCWrapper:0.0.1" + minecraft "com.mojang:minecraft:${project.minecraft_version}" mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2" From 310ad6e8f0dc36e20770860cb092cb63d05de860 Mon Sep 17 00:00:00 2001 From: Owen Stubbs Date: Tue, 28 Mar 2023 21:26:19 +0100 Subject: [PATCH 02/19] begin using wrapper --- README.md | 2 +- build.gradle | 4 +- gradle.properties | 1 + .../java/net/emc/emce/EarthMCEssentials.java | 29 ++-- .../net/emc/emce/caches/NationDataCache.java | 44 ------ .../net/emc/emce/caches/TownDataCache.java | 43 ------ .../java/net/emc/emce/config/ModConfig.java | 2 +- .../emce/events/commands/InfoCommands.java | 71 +++++---- .../emce/events/commands/TownlessCommand.java | 6 +- .../mixins/ClientPlayNetworkHandlerMixin.java | 2 +- .../net/emc/emce/modules/OverlayRenderer.java | 31 +--- .../net/emc/emce/modules/TaskScheduler.java | 38 +---- .../net/emc/emce/objects/API/APIData.java | 18 --- .../net/emc/emce/objects/API/APIRoute.java | 8 +- .../java/net/emc/emce/objects/Resident.java | 40 ------ .../java/net/emc/emce/utils/EarthMCAPI.java | 135 ++++++------------ .../java/net/emc/emce/utils/Messaging.java | 2 - .../java/net/emc/emce/utils/ModUtils.java | 9 +- .../java/net/emc/emce/utils/Translation.java | 13 +- src/main/resources/api.json | 6 - 20 files changed, 128 insertions(+), 376 deletions(-) delete mode 100644 src/main/java/net/emc/emce/caches/NationDataCache.java delete mode 100644 src/main/java/net/emc/emce/caches/TownDataCache.java delete mode 100644 src/main/java/net/emc/emce/objects/Resident.java diff --git a/README.md b/README.md index ca2cd07..6890906 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ A fabric mod designed for EarthMC that provides info on people, places and more. >*I recommend you use the [latest](https://github.com/EarthMC-Toolkit/EarthMCEssentials/releases/latest) EMCE version, with `Fabric API 0.72.0` and `Fabric Loader 0.14.12`, delete the file `emc-essentials.json` in your config folder and reboot MC. It is also worth checking the output log since some mods may conflict with EMCE.* **How is data obtained?** ->*All data is acquired from our [API](https://emc-toolkit.vercel.app/api) in conjuction with info from the Minecraft client.* +>*Most data comes from the purpose-made [EMC-Wrapper](https://github.com/EarthMC-Toolkit/EarthMC-Wrapper) library, while custom data is acquired from the [API](https://emc-toolkit.vercel.app/api).* **Is there a Forge version?** >*Not right now. There may be a re-write using the Architectuary API, but this won't be any time soon.* diff --git a/build.gradle b/build.gradle index 0991254..bbe3105 100644 --- a/build.gradle +++ b/build.gradle @@ -17,8 +17,6 @@ repositories { } dependencies { - implementation "net.emc.emcw:EMCWrapper:0.0.1" - minecraft "com.mojang:minecraft:${project.minecraft_version}" mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2" @@ -34,6 +32,8 @@ dependencies { // Libraries to include in remapJar include "me.shedaniel.cloth:cloth-config-fabric:${project.cloth_config_version}" + + implementation "io.github.emcw:emc-wrapper:${project.wrapper_version}" } processResources { diff --git a/gradle.properties b/gradle.properties index d637047..9965851 100644 --- a/gradle.properties +++ b/gradle.properties @@ -8,6 +8,7 @@ minecraft_version=1.19.3 yarn_mappings=1.19.3+build.5 loader_version=0.14.12 fabric_version=0.72.0+1.19.3 +wrapper_version=0.8.5 # Mod Properties name = EarthMCEssentials diff --git a/src/main/java/net/emc/emce/EarthMCEssentials.java b/src/main/java/net/emc/emce/EarthMCEssentials.java index 9e3dc6b..6cea1fd 100644 --- a/src/main/java/net/emc/emce/EarthMCEssentials.java +++ b/src/main/java/net/emc/emce/EarthMCEssentials.java @@ -1,14 +1,17 @@ package net.emc.emce; import com.google.gson.JsonArray; -import com.google.gson.JsonElement; + +import io.github.emcw.entities.BaseEntity; +import io.github.emcw.entities.Player; +import io.github.emcw.entities.Resident; +import io.github.emcw.utils.GsonUtil; import me.shedaniel.autoconfig.AutoConfig; import me.shedaniel.autoconfig.serializer.GsonConfigSerializer; import net.emc.emce.config.ModConfig; import net.emc.emce.modules.EventRegistry; import net.emc.emce.modules.OverlayRenderer; import net.emc.emce.modules.TaskScheduler; -import net.emc.emce.objects.Resident; import net.fabricmc.api.ModInitializer; import net.fabricmc.fabric.api.client.command.v2.ClientCommandRegistrationCallback; import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper; @@ -21,7 +24,9 @@ import org.lwjgl.glfw.GLFW; import java.util.List; +import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; +import java.util.stream.Collectors; public class EarthMCEssentials implements ModInitializer { private static EarthMCEssentials instance; @@ -33,9 +38,8 @@ public class EarthMCEssentials implements ModInitializer { private boolean shouldRender = false; private boolean debugModeEnabled = false; - private final List townlessResidents = new CopyOnWriteArrayList<>(); + private List townlessNames = new CopyOnWriteArrayList<>(); private JsonArray nearbyPlayers = new JsonArray(); - //private NewsData newsData = new NewsData(null); public static KeyBinding configKeybinding; @@ -103,7 +107,7 @@ public boolean debugEnabled() { } public List getTownless() { - return townlessResidents; + return townlessNames; } public JsonArray getNearbyPlayers() { @@ -119,21 +123,14 @@ public void setShouldRender(boolean shouldRender) { this.shouldRender = shouldRender; } -// public void trySendNews(NewsData nd) { -// OverlayRenderer.sendNews(config.news.position, nd); -// } - - public void setTownlessResidents(@NotNull JsonArray array) { + public void setTownless(@NotNull Map array) { // Make sure there is data to add. if (array.size() < 1) return; - townlessResidents.clear(); - - for (JsonElement res : array) { - townlessResidents.add(res.getAsJsonObject().get("name").getAsString()); - } + townlessNames.clear(); + townlessNames = GsonUtil.streamValues(array).map(BaseEntity::getName).collect(Collectors.toList()); - OverlayRenderer.SetTownless(townlessResidents); + OverlayRenderer.SetTownless(townlessNames); OverlayRenderer.UpdateStates(true, false); } } \ No newline at end of file diff --git a/src/main/java/net/emc/emce/caches/NationDataCache.java b/src/main/java/net/emc/emce/caches/NationDataCache.java deleted file mode 100644 index fbb9be2..0000000 --- a/src/main/java/net/emc/emce/caches/NationDataCache.java +++ /dev/null @@ -1,44 +0,0 @@ -package net.emc.emce.caches; - -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import net.emc.emce.utils.EarthMCAPI; -import net.emc.emce.utils.Messaging; -import org.jetbrains.annotations.NotNull; - -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; -import java.util.concurrent.CompletableFuture; - -public class NationDataCache extends Cache> { - public static final NationDataCache INSTANCE = new NationDataCache(); - - @Override - public CompletableFuture<@NotNull Map> getCache() { - return CompletableFuture.supplyAsync(() -> { - if (this.cachedData == null || this.needsUpdate()) { - this.updating = true; - this.cachedData = new HashMap<>(); - - JsonArray nations = EarthMCAPI.getNations().join(); - for (JsonElement nation : nations) { - JsonObject object = nation.getAsJsonObject(); - this.cachedData.put(object.get("name").getAsString().toLowerCase(Locale.ROOT), object); - } - - Messaging.sendDebugMessage("Updated nations, array size: " + this.cachedData.size()); - this.update(); - } - - return this.cachedData; - }); - } - - @Override - public void clear() { - this.cachedData.clear(); - super.clear(); - } -} diff --git a/src/main/java/net/emc/emce/caches/TownDataCache.java b/src/main/java/net/emc/emce/caches/TownDataCache.java deleted file mode 100644 index 1549651..0000000 --- a/src/main/java/net/emc/emce/caches/TownDataCache.java +++ /dev/null @@ -1,43 +0,0 @@ -package net.emc.emce.caches; - -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import net.emc.emce.utils.EarthMCAPI; -import net.emc.emce.utils.Messaging; - -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; -import java.util.concurrent.CompletableFuture; - -public class TownDataCache extends Cache> { - public static final TownDataCache INSTANCE = new TownDataCache(); - - @Override - public CompletableFuture> getCache() { - return CompletableFuture.supplyAsync(() -> { - if (this.cachedData == null || this.needsUpdate()) { - this.updating = true; - this.cachedData = new HashMap<>(); - - JsonArray towns = EarthMCAPI.getTowns().join(); - for (JsonElement town : towns) { - JsonObject object = town.getAsJsonObject(); - this.cachedData.put(object.get("name").getAsString().toLowerCase(Locale.ROOT), object); - } - - Messaging.sendDebugMessage("Updated towns, array size: " + this.cachedData.size()); - this.update(); - } - - return this.cachedData; - }); - } - - @Override - public void clear() { - this.cachedData.clear(); - super.clear(); - } -} diff --git a/src/main/java/net/emc/emce/config/ModConfig.java b/src/main/java/net/emc/emce/config/ModConfig.java index 32733ba..8700244 100644 --- a/src/main/java/net/emc/emce/config/ModConfig.java +++ b/src/main/java/net/emc/emce/config/ModConfig.java @@ -96,7 +96,7 @@ public static class Nearby { @Comment("The colour of nearby players' names.") public Colors playerTextColour = Colors.GOLD; - // Independent scaling - each axis can be same or different. + // Independent scaling - either axis can be the same or different. @Comment("The amount of blocks to check on the X axis.") @BoundedDiscrete(min = 50, max = 10000) public int xBlocks = 500; diff --git a/src/main/java/net/emc/emce/events/commands/InfoCommands.java b/src/main/java/net/emc/emce/events/commands/InfoCommands.java index 4c656a9..ef10046 100644 --- a/src/main/java/net/emc/emce/events/commands/InfoCommands.java +++ b/src/main/java/net/emc/emce/events/commands/InfoCommands.java @@ -1,21 +1,22 @@ package net.emc.emce.events.commands; -import com.google.gson.JsonObject; import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.arguments.StringArgumentType; +import io.github.emcw.entities.Location; +import io.github.emcw.entities.Nation; +import io.github.emcw.entities.Resident; +import io.github.emcw.entities.Town; import net.emc.emce.EarthMCEssentials; -import net.emc.emce.caches.NationDataCache; -import net.emc.emce.caches.TownDataCache; -import net.emc.emce.objects.Resident; -import net.emc.emce.utils.Translation; +import net.emc.emce.utils.EarthMCAPI; import net.emc.emce.utils.Messaging; +import net.emc.emce.utils.Translation; import net.fabricmc.fabric.api.client.command.v2.ClientCommandManager; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; import net.kyori.adventure.audience.Audience; import net.kyori.adventure.platform.fabric.FabricClientAudiences; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; -import net.minecraft.client.MinecraftClient; +import org.jetbrains.annotations.NotNull; import java.util.Locale; @@ -82,28 +83,24 @@ private boolean residentExists(Resident res) { private void trySendTown(String townName) { NamedTextColor townTextColour = instance.getConfig().commands.townInfoTextColour.named(); - TownDataCache.INSTANCE.getCache().thenAccept(towns -> { - JsonObject townObject = towns.get(townName.toLowerCase(Locale.ROOT)); + Town town = EarthMCAPI.getTown(townName.toLowerCase(Locale.ROOT)); - if (townObject == null) { - Component townArg = Component.text(townName).color(townTextColour); - Messaging.sendPrefixed(Messaging.create("text_towninfo_err", NamedTextColor.RED, townArg)); - } - else sendTownInfo(townObject, townTextColour); - }); + if (town == null) { + Component townArg = Component.text(townName).color(townTextColour); + Messaging.sendPrefixed(Messaging.create("text_towninfo_err", NamedTextColor.RED, townArg)); + } + else sendTownInfo(town, townTextColour); } - private void trySendNation(String nationName) { + private void trySendNation(@NotNull String nationName) { NamedTextColor nationTextColour = instance.getConfig().commands.nationInfoTextColour.named(); - NationDataCache.INSTANCE.getCache().thenAccept(nations -> { - JsonObject nationObject = nations.get(nationName.toLowerCase(Locale.ROOT)); + Nation nation = EarthMCAPI.getNation(nationName.toLowerCase(Locale.ROOT)); - if (nationObject == null) { - Component nationArg = Component.text(nationName).color(nationTextColour); - Messaging.sendPrefixed(Messaging.create("text_nationinfo_err", NamedTextColor.RED, nationArg)); - } - else sendNationInfo(nationObject, nationTextColour); - }); + if (nation == null) { + Component nationArg = Component.text(nationName).color(nationTextColour); + Messaging.sendPrefixed(Messaging.create("text_nationinfo_err", NamedTextColor.RED, nationArg)); + } + else sendNationInfo(nation, nationTextColour); } static Audience audience = null; @@ -112,20 +109,22 @@ private void sendMsg(NamedTextColor colour, String key, Object... args) { audience.sendMessage(Translation.of(key, args).color(colour)); } - private void sendTownInfo(JsonObject townObject, NamedTextColor colour) { - sendMsg(colour, "text_towninfo_header", townObject.get("name").getAsString()); - sendMsg(colour, "text_towninfo_mayor", townObject.get("mayor").getAsString()); - sendMsg(colour, "text_shared_area", townObject.get("area").getAsString()); - sendMsg(colour, "text_shared_residents", townObject.get("residents").getAsJsonArray().size()); - sendMsg(colour, "text_towninfo_location", townObject.get("x").getAsString(), townObject.get("z").getAsString()); + private void sendTownInfo(@NotNull Town town, NamedTextColor colour) { + sendMsg(colour, "text_towninfo_header", town.getName()); + sendMsg(colour, "text_towninfo_mayor", town.getMayor()); + sendMsg(colour, "text_shared_area", town.getArea()); + sendMsg(colour, "text_shared_residents", town.getResidents().size()); + + Location loc = town.getLocation(); + sendMsg(colour, "text_towninfo_location", loc.getX(), loc.getZ()); } - private void sendNationInfo(JsonObject nationObject, NamedTextColor colour) { - sendMsg(colour, "text_nationinfo_header", nationObject.get("name").getAsString()); - sendMsg(colour, "text_nationinfo_king", nationObject.get("king").getAsString()); - sendMsg(colour, "text_nationinfo_capital", nationObject.get("capitalName").getAsString()); - sendMsg(colour, "text_shared_area", nationObject.get("area").getAsString()); - sendMsg(colour, "text_shared_residents", nationObject.get("residents").getAsJsonArray().size()); - sendMsg(colour, "text_nationinfo_towns", nationObject.get("towns").getAsJsonArray().size()); + private void sendNationInfo(@NotNull Nation nation, NamedTextColor colour) { + sendMsg(colour, "text_nationinfo_header", nation.getName()); + sendMsg(colour, "text_nationinfo_king", nation.getLeader()); + sendMsg(colour, "text_nationinfo_capital", nation.getCapital().getName()); + sendMsg(colour, "text_shared_area", nation.getArea()); + sendMsg(colour, "text_shared_residents", nation.getResidents().size()); + sendMsg(colour, "text_nationinfo_towns", nation.getTowns().size()); } } \ No newline at end of file diff --git a/src/main/java/net/emc/emce/events/commands/TownlessCommand.java b/src/main/java/net/emc/emce/events/commands/TownlessCommand.java index b1673d8..5da68f4 100644 --- a/src/main/java/net/emc/emce/events/commands/TownlessCommand.java +++ b/src/main/java/net/emc/emce/events/commands/TownlessCommand.java @@ -1,6 +1,5 @@ package net.emc.emce.events.commands; -import com.google.gson.JsonArray; import com.mojang.brigadier.CommandDispatcher; import net.emc.emce.EarthMCEssentials; import net.emc.emce.utils.EarthMCAPI; @@ -13,6 +12,7 @@ import net.minecraft.client.MinecraftClient; import java.util.List; +import java.util.Map; public record TownlessCommand(EarthMCEssentials instance) { static NamedTextColor townlessTextColour; @@ -74,12 +74,12 @@ public void register(CommandDispatcher dispatcher) { return 1; })).then(ClientCommandManager.literal("refresh").executes(c -> { - EarthMCAPI.getTownless().thenAccept(instance::setTownlessResidents); + instance.setTownless(EarthMCAPI.getTownless()); Messaging.sendPrefixed("msg_townless_refresh"); return 1; })).then(ClientCommandManager.literal("clear").executes(c -> { - instance.setTownlessResidents(new JsonArray()); + instance.setTownless(Map.of()); Messaging.sendPrefixed("msg_townless_clear"); return 1; diff --git a/src/main/java/net/emc/emce/mixins/ClientPlayNetworkHandlerMixin.java b/src/main/java/net/emc/emce/mixins/ClientPlayNetworkHandlerMixin.java index f15fe72..ccb5dce 100644 --- a/src/main/java/net/emc/emce/mixins/ClientPlayNetworkHandlerMixin.java +++ b/src/main/java/net/emc/emce/mixins/ClientPlayNetworkHandlerMixin.java @@ -28,7 +28,7 @@ public abstract class ClientPlayNetworkHandlerMixin { @Inject(at = @At("TAIL"), method="") private void onInit(MinecraftClient client, Screen screen, ClientConnection connection, ServerInfo serverInfo, GameProfile profile, WorldSession worldSession, CallbackInfo ci) { - EarthMCAPI.getResident(profile.getName()).thenAccept(res -> instance().setClientResident(res)); + instance().setClientResident(EarthMCAPI.getResident(profile.getName())); } @Inject(at = @At("TAIL"), method="onDisconnect") diff --git a/src/main/java/net/emc/emce/modules/OverlayRenderer.java b/src/main/java/net/emc/emce/modules/OverlayRenderer.java index 9d5c865..40475cd 100644 --- a/src/main/java/net/emc/emce/modules/OverlayRenderer.java +++ b/src/main/java/net/emc/emce/modules/OverlayRenderer.java @@ -18,7 +18,6 @@ import net.minecraft.text.*; import net.minecraft.util.Formatting; -import java.util.Iterator; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; @@ -33,7 +32,6 @@ public class OverlayRenderer { private static State townlessState, nearbyState; private static List townless = new CopyOnWriteArrayList<>(); - private static final int currentNewsID = 0; private static final int color = 16777215; public static void Init() { @@ -77,17 +75,6 @@ public static void Render(MatrixStack ms) { if (config.nearby.enabled) RenderNearby(config.nearby.presetPositions); } -// public static void sendNews(NewsState pos, NewsData news) { -// if (news.getID() == currentNewsID) return; -// currentNewsID = news.getID(); -// -// TextComponent text = Component.text(news.getMsg(), NamedTextColor.AQUA); -// switch(pos) { -// case CHAT -> Messaging.send(text); -// case ACTION_BAR -> Messaging.sendActionBar(text); -// } -// } - private static void RenderTownless(boolean usingPreset) { int townlessSize = townless.size(); int maxLen = config.townless.maxLength; @@ -104,19 +91,16 @@ private static void RenderTownless(boolean usingPreset) { renderer.drawWithShadow(matrixStack, townlessText, x, y - 10, color); int index = 0; - Iterator it = townless.iterator(); - - while (it.hasNext()) { - String townlessName = it.next(); + for (String townlessName : townless) { if (maxLen > 0 && index >= maxLen) { MutableText remainingText = Text.translatable("text_townless_remaining", townlessSize - index).formatted(playerTextFormatting); - renderer.drawWithShadow(matrixStack, remainingText, x, y + index*10, color); + renderer.drawWithShadow(matrixStack, remainingText, x, y + index * 10, color); break; } MutableText playerName = Text.translatable(townlessName).formatted(playerTextFormatting); - renderer.drawWithShadow(matrixStack, playerName, x, y + index++*10, color); + renderer.drawWithShadow(matrixStack, playerName, x, y + index++ * 10, color); } } else { @@ -129,14 +113,11 @@ private static void RenderTownless(boolean usingPreset) { if (townlessSize > 0) { int index = 0; - Iterator it = townless.iterator(); - - while (it.hasNext()) { - String name = it.next(); + for (String name : townless) { if (maxLen >= 1) { if (index >= maxLen) { - MutableText remainingText = Text.translatable("text_townless_remaining", townlessSize-index).formatted(playerTextFormatting); + MutableText remainingText = Text.translatable("text_townless_remaining", townlessSize - index).formatted(playerTextFormatting); renderer.drawWithShadow(matrixStack, remainingText, xOffset, playerOffset, color); break; } @@ -260,6 +241,7 @@ private static void UpdateTownlessState() { } case TOP_RIGHT -> { townlessState.setX(widthOffset); + assert client.player != null; townlessState.setY(ModUtils.getStatusEffectOffset(client.player.getStatusEffects())); } case LEFT -> { @@ -317,6 +299,7 @@ private static void UpdateNearbyState() { if (townlessState.equals(State.TOP_RIGHT)) nearbyState.setX(xRightOffset); else nearbyState.setX(windowWidth - nearbyLongest - 5); + assert client.player != null; nearbyState.setY(ModUtils.getStatusEffectOffset(client.player.getStatusEffects())); } case LEFT -> { diff --git a/src/main/java/net/emc/emce/modules/TaskScheduler.java b/src/main/java/net/emc/emce/modules/TaskScheduler.java index 335e12b..31c114e 100644 --- a/src/main/java/net/emc/emce/modules/TaskScheduler.java +++ b/src/main/java/net/emc/emce/modules/TaskScheduler.java @@ -1,23 +1,20 @@ package net.emc.emce.modules; -import net.emc.emce.EarthMCEssentials; import net.emc.emce.caches.AllianceDataCache; import net.emc.emce.caches.Cache; -import net.emc.emce.caches.NationDataCache; -import net.emc.emce.caches.TownDataCache; import net.emc.emce.config.ModConfig; import net.emc.emce.utils.EarthMCAPI; import net.emc.emce.utils.Messaging; import net.emc.emce.utils.ModUtils; import net.minecraft.client.MinecraftClient; -import java.util.Arrays; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import static net.emc.emce.EarthMCEssentials.instance; +import static net.emc.emce.utils.EarthMCAPI.getTownless; import static net.emc.emce.utils.EarthMCAPI.playerOnline; public class TaskScheduler { @@ -25,24 +22,19 @@ public class TaskScheduler { public boolean townlessRunning, nearbyRunning, cacheCheckRunning, newsRunning; public boolean hasMap = false; - private static final List> CACHES = Arrays.asList( - NationDataCache.INSTANCE, - TownDataCache.INSTANCE, - AllianceDataCache.INSTANCE - ); + private static final List> CACHES = List.of(AllianceDataCache.INSTANCE); public void start() { ModConfig config = ModConfig.instance(); // Pre-fill data. if (config.general.enableMod) { - if (config.townless.enabled) EarthMCAPI.getTownless().thenAccept(instance()::setTownlessResidents); + if (config.townless.enabled) instance().setTownless(getTownless()); if (config.nearby.enabled) EarthMCAPI.getNearby().thenAccept(instance()::setNearbyPlayers); } startTownless(); startNearby(); - //startNews(); startCacheCheck(); } @@ -89,10 +81,9 @@ private void startTownless() { service.scheduleAtFixedRate(() -> { if (townlessRunning && config.townless.enabled && shouldRun()) { Messaging.sendDebugMessage("Starting townless task."); - EarthMCAPI.getTownless().thenAccept(townless -> { - instance().setTownlessResidents(townless); - Messaging.sendDebugMessage("Finished townless task."); - }); + + instance().setTownless(getTownless()); + Messaging.sendDebugMessage("Finished townless task."); } }, 30, Math.max(config.api.intervals.townless, 30), TimeUnit.SECONDS); } @@ -112,21 +103,6 @@ private void startNearby() { }, 10, Math.max(config.api.intervals.nearby, 10), TimeUnit.SECONDS); } -// private void startNews() { -// newsRunning = true; -// final ModConfig config = ModConfig.instance(); -// -// service.scheduleAtFixedRate(() -> { -// if (newsRunning && config.news.enabled && shouldRun()) { -// Messaging.sendDebugMessage("Starting news task."); -// EarthMCAPI.getNews().thenAccept(news -> { -// instance().trySendNews(news); -// Messaging.sendDebugMessage("Finished news task."); -// }); -// } -// }, 10, Math.max(config.api.intervals.news, 10), TimeUnit.SECONDS); -// } - private void startCacheCheck() { cacheCheckRunning = true; @@ -142,7 +118,7 @@ private void startCacheCheck() { private boolean shouldRun() { ModConfig config = ModConfig.instance(); boolean focused = MinecraftClient.getInstance().isWindowFocused(); - boolean playingEMC = config.general.enableMod && ModUtils.isConnectedToEMC(); + boolean playingEMC = config.general.enableMod; return playingEMC && focused; } diff --git a/src/main/java/net/emc/emce/objects/API/APIData.java b/src/main/java/net/emc/emce/objects/API/APIData.java index cb6843d..aec6d31 100644 --- a/src/main/java/net/emc/emce/objects/API/APIData.java +++ b/src/main/java/net/emc/emce/objects/API/APIData.java @@ -8,12 +8,7 @@ public class APIData { public Routes routes = new Routes(); public static class Routes { - public String townless; - public String nations; - public String towns; - public String residents; public String allPlayers; - public String onlinePlayers; public String nearby; public String news; public String alliances; @@ -23,16 +18,8 @@ public APIData(JsonObject object) { domain = object.get("domain").getAsString(); JsonObject routesObj = object.get("routes").getAsJsonObject(); - routes.towns = routesObj.get("towns").getAsString(); - routes.nations = routesObj.get("nations").getAsString(); - routes.residents = routesObj.get("residents").getAsString(); - - routes.onlinePlayers = routesObj.get("onlineplayers").getAsString(); routes.allPlayers = routesObj.get("allplayers").getAsString(); - - routes.townless = routesObj.get("townless").getAsString(); routes.nearby = routesObj.get("nearby").getAsString(); - routes.alliances = routesObj.get("alliances").getAsString(); //routes.news = routesObj.get("news").getAsString(); } @@ -40,12 +27,7 @@ public APIData(JsonObject object) { public APIData() { domain = ""; - routes.townless = ""; - routes.nations = ""; - routes.towns = ""; - routes.residents = ""; routes.allPlayers = ""; - routes.onlinePlayers = ""; routes.nearby = ""; routes.news = ""; routes.alliances = ""; diff --git a/src/main/java/net/emc/emce/objects/API/APIRoute.java b/src/main/java/net/emc/emce/objects/API/APIRoute.java index e6de2a8..1759800 100644 --- a/src/main/java/net/emc/emce/objects/API/APIRoute.java +++ b/src/main/java/net/emc/emce/objects/API/APIRoute.java @@ -1,13 +1,7 @@ package net.emc.emce.objects.API; public enum APIRoute { - TOWNLESS, NEARBY, - RESIDENTS, ALL_PLAYERS, - ONLINE_PLAYERS, - TOWNS, - NATIONS, - ALLIANCES, - NEWS + ALLIANCES } \ No newline at end of file diff --git a/src/main/java/net/emc/emce/objects/Resident.java b/src/main/java/net/emc/emce/objects/Resident.java deleted file mode 100644 index 75e4410..0000000 --- a/src/main/java/net/emc/emce/objects/Resident.java +++ /dev/null @@ -1,40 +0,0 @@ -package net.emc.emce.objects; - -import com.google.gson.JsonObject; - -public class Resident { - private final String name; - private final String town; - private final String nation; - private final String rank; - - public Resident(JsonObject object) { - this.name = object.get("name").getAsString(); - this.town = object.get("town").getAsString(); - this.nation = object.get("nation").getAsString(); - this.rank = object.get("rank").getAsString(); - } - - public Resident(String name) { - this.name = name; - this.town = ""; - this.nation = ""; - this.rank = ""; - } - - public String getName() { - return name; - } - - public String getTown() { - return town; - } - - public String getNation() { - return nation; - } - - public String getRank() { - return rank; - } -} diff --git a/src/main/java/net/emc/emce/utils/EarthMCAPI.java b/src/main/java/net/emc/emce/utils/EarthMCAPI.java index cb9c152..6c48ce4 100644 --- a/src/main/java/net/emc/emce/utils/EarthMCAPI.java +++ b/src/main/java/net/emc/emce/utils/EarthMCAPI.java @@ -1,16 +1,24 @@ package net.emc.emce.utils; import com.google.gson.JsonArray; -import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; +import io.github.emcw.core.EMCMap; +import io.github.emcw.core.EMCWrapper; +import io.github.emcw.entities.Nation; +import io.github.emcw.entities.Player; +import io.github.emcw.entities.Resident; +import io.github.emcw.entities.Town; +import io.github.emcw.exceptions.MissingEntryException; import net.emc.emce.config.ModConfig; import net.emc.emce.objects.API.APIData; import net.emc.emce.objects.API.APIRoute; -import net.emc.emce.objects.Resident; import net.emc.emce.objects.exception.APIException; import net.minecraft.client.MinecraftClient; import net.minecraft.client.network.ClientPlayerEntity; +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.net.URI; import java.net.http.HttpClient; @@ -20,37 +28,57 @@ import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.concurrent.CompletableFuture; -import java.util.regex.Pattern; import static net.emc.emce.EarthMCEssentials.instance; public class EarthMCAPI { private static final HttpClient client = HttpClient.newHttpClient(); private static final ModConfig config = ModConfig.instance(); - public static final Pattern urlSchemePattern = Pattern.compile("^[a-z][a-z0-9+\\-.]*://"); public static APIData apiData = new APIData(); public static JsonObject player = new JsonObject(); + public static EMCWrapper wrapper = new EMCWrapper(true, true); - public static CompletableFuture getTownless() { - return CompletableFuture.supplyAsync(() -> { - try { - return (JsonArray) JsonParser.parseString(getURL(getRoute(APIRoute.TOWNLESS))); - } catch (APIException e) { - Messaging.sendDebugMessage(e.getMessage(), e); - return new JsonArray(); - } - }); + private static EMCMap currentMap() { + return Objects.equals(instance().mapName, "aurora") ? wrapper.getAurora() : wrapper.getNova(); } - public static CompletableFuture getNearby() { + public static @Nullable Town getTown(String name) { + try { return currentMap().Towns.single(name); } + catch (MissingEntryException e) { return null; } + } + + public static @Nullable Nation getNation(String name) { + try { return currentMap().Nations.single(name); } + catch (MissingEntryException e) { return null; } + } + + public static Map getTownless() { + return currentMap().Players.townless(); + } + + public static Map onlinePlayers() { return currentMap().Players.online(); } + + public static Map getResidents() { + return currentMap().Residents.all(); + } + + public static @Nullable Resident getResident(String name) { + try { return currentMap().Residents.single(name); } + catch (MissingEntryException e) { return null; } + } + + @Contract(" -> new") + public static @NotNull CompletableFuture getNearby() { return getNearby(config.nearby.xBlocks, config.nearby.zBlocks); } - public static CompletableFuture getNearby(int xBlocks, int zBlocks) { + @Contract("_, _ -> new") + public static @NotNull CompletableFuture getNearby(int xBlocks, int zBlocks) { return CompletableFuture.supplyAsync(() -> { try { MinecraftClient client = MinecraftClient.getInstance(); @@ -81,74 +109,6 @@ public static CompletableFuture getNearby(int xBlocks, int zBlocks) { }); } - public static CompletableFuture getResident(String residentName) { - return CompletableFuture.supplyAsync(() -> { - try { return new Resident((JsonObject) JsonParser.parseString(getURL(getRoute(APIRoute.RESIDENTS) + "/" + residentName))); } - catch (APIException e) { - Messaging.sendDebugMessage(e.getMessage(), e); - return new Resident(residentName); - } - }); - } - - public static CompletableFuture getOnlinePlayers() { - return CompletableFuture.supplyAsync(() -> { - try { return (JsonArray) JsonParser.parseString(getURL(getRoute(APIRoute.ONLINE_PLAYERS))); } - catch (APIException e) { - Messaging.sendDebugMessage(e.getMessage(), e); - return new JsonArray(); - } - }); - } - - public static JsonObject getOnlinePlayer(String name) { - JsonArray ops = getOnlinePlayers().join().getAsJsonArray(); - JsonObject pl = new JsonObject(); - - if (!ops.isEmpty()) { - for (JsonElement op : ops) { - JsonObject cur = op.getAsJsonObject(); - - if (Objects.equals(cur.get("name").getAsString(), name)) { - pl = cur; - break; - } - } - } - - return pl; - } - - public static CompletableFuture getTowns() { - return CompletableFuture.supplyAsync(() -> { - try { return (JsonArray) JsonParser.parseString(getURL(getRoute(APIRoute.TOWNS))); } catch (APIException e) { - Messaging.sendDebugMessage(e.getMessage(), e); - return new JsonArray(); - } - }); - } - - public static CompletableFuture getNations() { - return CompletableFuture.supplyAsync(() -> { - try { return (JsonArray) JsonParser.parseString(getURL(getRoute(APIRoute.NATIONS))); } - catch (APIException e) { - Messaging.sendDebugMessage(e.getMessage(), e); - return new JsonArray(); - } - }); - } - -// public static CompletableFuture getNews() { -// return CompletableFuture.supplyAsync(() -> { -// try { -// return new NewsData((JsonObject) JsonParser.parseString(getURL(getRoute(APIRoute.NEWS)))); -// } catch (APIException e) { -// Messaging.sendDebugMessage(e.getMessage(), e); -// return new NewsData(null); -// } -// }); -// } - public static CompletableFuture getAlliances() { return CompletableFuture.supplyAsync(() -> { try { @@ -189,12 +149,7 @@ public static String getRoute(APIRoute routeType) { String route; switch(routeType) { - case TOWNLESS -> route = apiData.routes.townless; - case NATIONS -> route = apiData.routes.nations; - case RESIDENTS -> route = apiData.routes.residents; case ALL_PLAYERS -> route = apiData.routes.allPlayers; - case ONLINE_PLAYERS -> route = apiData.routes.onlinePlayers; - case TOWNS -> route = apiData.routes.towns; case ALLIANCES -> route = apiData.routes.alliances; case NEARBY -> route = apiData.routes.nearby; case NEWS -> route = apiData.routes.news; @@ -213,9 +168,7 @@ public static String clientName() { public static boolean playerOnline(String map) { instance().mapName = map; // getOnlinePlayer uses mapName. - - JsonObject player = getOnlinePlayer(clientName()); - return player.has("name"); + return onlinePlayers().containsKey(clientName()); } private static String getURL(String urlString) throws APIException { diff --git a/src/main/java/net/emc/emce/utils/Messaging.java b/src/main/java/net/emc/emce/utils/Messaging.java index 76ec7fb..c7baa01 100644 --- a/src/main/java/net/emc/emce/utils/Messaging.java +++ b/src/main/java/net/emc/emce/utils/Messaging.java @@ -1,9 +1,7 @@ package net.emc.emce.utils; -import net.emc.emce.EarthMCEssentials; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; -import net.minecraft.client.MinecraftClient; import java.util.Collections; import java.util.List; diff --git a/src/main/java/net/emc/emce/utils/ModUtils.java b/src/main/java/net/emc/emce/utils/ModUtils.java index c735fec..5b86609 100644 --- a/src/main/java/net/emc/emce/utils/ModUtils.java +++ b/src/main/java/net/emc/emce/utils/ModUtils.java @@ -3,16 +3,14 @@ import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; -import net.emc.emce.objects.Resident; +import io.github.emcw.entities.Resident; import net.minecraft.client.MinecraftClient; import net.minecraft.client.network.ClientPlayNetworkHandler; import net.minecraft.client.network.ClientPlayerEntity; import net.minecraft.client.network.ServerInfo; import net.minecraft.entity.effect.StatusEffectInstance; import net.minecraft.text.MutableText; -import net.minecraft.text.StringVisitable; import net.minecraft.text.Text; -import net.minecraft.text.TranslatableTextContent; import org.jetbrains.annotations.NotNull; import java.net.InetSocketAddress; @@ -26,6 +24,7 @@ public class ModUtils { private static @NotNull String serverName = ""; + @SuppressWarnings("unused") public enum ScaleMethod { Independent, Proportionate @@ -65,6 +64,7 @@ public void setY(int y) { } } + @SuppressWarnings("unused") public static int getStringWidth(String string) { return getInstance().textRenderer.getWidth(string); } public static int getTextWidth(MutableText text) { return getInstance().textRenderer.getWidth(text); } public static int getStringHeight(String string) { return getInstance().textRenderer.getWrappedLinesHeight(string, 1000); } @@ -76,7 +76,8 @@ public static String elementAsString(@NotNull JsonElement el, String name) { return el.getAsJsonObject().get(name).getAsString(); } - public static int getLongestElement(JsonArray array) { + @SuppressWarnings("unused") + public static int getLongestElement(@NotNull JsonArray array) { int length = array.size(); if (array == null || length < 1) return 0; diff --git a/src/main/java/net/emc/emce/utils/Translation.java b/src/main/java/net/emc/emce/utils/Translation.java index a44d9b6..48bef06 100644 --- a/src/main/java/net/emc/emce/utils/Translation.java +++ b/src/main/java/net/emc/emce/utils/Translation.java @@ -3,17 +3,18 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.TextComponent; -import java.util.Arrays; -import java.util.List; +import static net.kyori.adventure.text.Component.text; +import static net.kyori.adventure.text.Component.translatable; + +import java.util.stream.Stream; public class Translation { public static Component of(String key) { - return Component.translatable(key); + return translatable(key); } public static Component of(String key, Object... args) { - List components = Arrays.stream(args).map(arg -> Component.text(String.valueOf(arg))).toList(); - - return Component.translatable(key, components); + Stream components = Stream.of(args).parallel().map(arg -> text(String.valueOf(arg))); + return translatable(key, components.toList()); } } diff --git a/src/main/resources/api.json b/src/main/resources/api.json index 3bab766..9a04d01 100644 --- a/src/main/resources/api.json +++ b/src/main/resources/api.json @@ -1,14 +1,8 @@ { "domain": "https://emctoolkit.vercel.app/api/", "routes": { - "townless": "/townlessplayers", "allplayers": "/allplayers", - "onlineplayers": "/onlineplayers", - "residents": "/residents", - "towns": "/towns", - "nations": "/nations", "alliances": "/alliances", - "news": "/news", "nearby": "/nearby/players" } } From f7135638a56f5e82beb8126f5ff3b13c49c8226a Mon Sep 17 00:00:00 2001 From: Owen Stubbs Date: Tue, 28 Mar 2023 21:35:23 +0100 Subject: [PATCH 03/19] vbb --- gradle.properties | 6 ++++-- src/main/java/net/emc/emce/EarthMCEssentials.java | 1 - 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/gradle.properties b/gradle.properties index 9965851..c94ce28 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,4 +1,4 @@ -org.gradle.jvmargs=-Xmx1G +org.gradle.jvmargs=-Xms256m -Xmx1G -Dfile.encoding=UTF-8 -XX:+UseG1GC org.gradle.caching=true org.gradle.parallel=true org.gradle.workers.max=4 @@ -18,4 +18,6 @@ maven_group = net.emc.emce # Library versions cloth_config_version = 9.0.94 mod_menu_version = 5.0.2 -adventure_fabric_version = 5.6.1 \ No newline at end of file +adventure_fabric_version = 5.6.1 + +gpr.user = "Owen3H" \ No newline at end of file diff --git a/src/main/java/net/emc/emce/EarthMCEssentials.java b/src/main/java/net/emc/emce/EarthMCEssentials.java index 6cea1fd..b42e332 100644 --- a/src/main/java/net/emc/emce/EarthMCEssentials.java +++ b/src/main/java/net/emc/emce/EarthMCEssentials.java @@ -24,7 +24,6 @@ import org.lwjgl.glfw.GLFW; import java.util.List; -import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; import java.util.stream.Collectors; From 7e40c9b83604ecfd5eb0a5f5496274fbd0c0e82b Mon Sep 17 00:00:00 2001 From: Owen Stubbs Date: Tue, 28 Mar 2023 21:35:38 +0100 Subject: [PATCH 04/19] Update EarthMCAPI.java --- src/main/java/net/emc/emce/utils/EarthMCAPI.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/net/emc/emce/utils/EarthMCAPI.java b/src/main/java/net/emc/emce/utils/EarthMCAPI.java index 6c48ce4..79782b0 100644 --- a/src/main/java/net/emc/emce/utils/EarthMCAPI.java +++ b/src/main/java/net/emc/emce/utils/EarthMCAPI.java @@ -152,7 +152,6 @@ public static String getRoute(APIRoute routeType) { case ALL_PLAYERS -> route = apiData.routes.allPlayers; case ALLIANCES -> route = apiData.routes.alliances; case NEARBY -> route = apiData.routes.nearby; - case NEWS -> route = apiData.routes.news; default -> throw new IllegalStateException("Unexpected value: " + routeType); } From 310430025d0ce6ac347363a3db60332f1bf595dc Mon Sep 17 00:00:00 2001 From: Owen Stubbs Date: Tue, 28 Mar 2023 21:45:46 +0100 Subject: [PATCH 05/19] brub --- build.gradle | 24 ++++++++++++------- gradle.properties | 3 ++- .../java/net/emc/emce/EarthMCEssentials.java | 1 + 3 files changed, 19 insertions(+), 9 deletions(-) diff --git a/build.gradle b/build.gradle index bbe3105..ec8c4a8 100644 --- a/build.gradle +++ b/build.gradle @@ -2,16 +2,21 @@ plugins { id 'fabric-loom' version '1.0-SNAPSHOT' } -sourceCompatibility = JavaVersion.VERSION_17 -targetCompatibility = JavaVersion.VERSION_17 - -version = "${project.mod_version}-${project.minecraft_version}+" +version = "${project.mod_version}-${project.minecraft_version}+" as Object group = project.maven_group repositories { - mavenLocal() mavenCentral() + maven { + name = "GitHubPackages" + url = uri("https://maven.pkg.github.com/earthmc-toolkit/earthmc-wrapper") + credentials { + username = project.findProperty("gpr.user") + password = System.getenv("GITHUB_TOKEN") + } + } + maven { url "https://maven.shedaniel.me/" } maven { url "https://maven.terraformersmc.com/releases/" } } @@ -37,18 +42,21 @@ dependencies { } processResources { - inputs.property "version", project.version + inputs.property "version", version filesMatching("fabric.mod.json") { - expand "version": project.version + expand "version": version } } tasks.withType(JavaCompile).configureEach { it.options.encoding = "UTF-8" - it.options.release = 17 } java { + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } + withSourcesJar() } \ No newline at end of file diff --git a/gradle.properties b/gradle.properties index c94ce28..a38b477 100644 --- a/gradle.properties +++ b/gradle.properties @@ -8,7 +8,7 @@ minecraft_version=1.19.3 yarn_mappings=1.19.3+build.5 loader_version=0.14.12 fabric_version=0.72.0+1.19.3 -wrapper_version=0.8.5 + # Mod Properties name = EarthMCEssentials @@ -19,5 +19,6 @@ maven_group = net.emc.emce cloth_config_version = 9.0.94 mod_menu_version = 5.0.2 adventure_fabric_version = 5.6.1 +wrapper_version=0.8.5 gpr.user = "Owen3H" \ No newline at end of file diff --git a/src/main/java/net/emc/emce/EarthMCEssentials.java b/src/main/java/net/emc/emce/EarthMCEssentials.java index b42e332..6cea1fd 100644 --- a/src/main/java/net/emc/emce/EarthMCEssentials.java +++ b/src/main/java/net/emc/emce/EarthMCEssentials.java @@ -24,6 +24,7 @@ import org.lwjgl.glfw.GLFW; import java.util.List; +import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; import java.util.stream.Collectors; From 2cd94039064d210763a2854db10a8ddefd412483 Mon Sep 17 00:00:00 2001 From: Owen Stubbs Date: Wed, 29 Mar 2023 19:34:36 +0100 Subject: [PATCH 06/19] stop using api for nearby --- .../java/net/emc/emce/EarthMCEssentials.java | 9 +- src/main/java/net/emc/emce/caches/Cache.java | 2 +- .../java/net/emc/emce/config/ModConfig.java | 109 ++++++++---------- .../emce/events/commands/AllianceCommand.java | 6 +- .../emce/events/commands/InfoCommands.java | 2 +- .../emce/events/commands/NearbyCommand.java | 37 +++--- .../events/commands/ToggleDebugCommand.java | 1 - .../emc/emce/events/screen/ScreenInit.java | 1 - .../mixins/ClientPlayNetworkHandlerMixin.java | 5 - .../mixins/SessionEventListenerMixin.java | 1 - .../net/emc/emce/modules/OverlayRenderer.java | 100 ++++++++-------- .../net/emc/emce/modules/TaskScheduler.java | 70 ++++++----- .../net/emc/emce/objects/API/APIData.java | 39 ++++--- .../net/emc/emce/objects/API/APIRoute.java | 1 - .../java/net/emc/emce/utils/EarthMCAPI.java | 45 +++----- .../java/net/emc/emce/utils/Messaging.java | 4 +- .../java/net/emc/emce/utils/ModUtils.java | 65 +++++------ 17 files changed, 231 insertions(+), 266 deletions(-) diff --git a/src/main/java/net/emc/emce/EarthMCEssentials.java b/src/main/java/net/emc/emce/EarthMCEssentials.java index 6cea1fd..e75fa5a 100644 --- a/src/main/java/net/emc/emce/EarthMCEssentials.java +++ b/src/main/java/net/emc/emce/EarthMCEssentials.java @@ -1,7 +1,5 @@ package net.emc.emce; -import com.google.gson.JsonArray; - import io.github.emcw.entities.BaseEntity; import io.github.emcw.entities.Player; import io.github.emcw.entities.Resident; @@ -25,6 +23,7 @@ import java.util.List; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.stream.Collectors; @@ -39,7 +38,7 @@ public class EarthMCEssentials implements ModInitializer { private boolean debugModeEnabled = false; private List townlessNames = new CopyOnWriteArrayList<>(); - private JsonArray nearbyPlayers = new JsonArray(); + private Map nearbyPlayers = new ConcurrentHashMap<>(); public static KeyBinding configKeybinding; @@ -110,11 +109,11 @@ public List getTownless() { return townlessNames; } - public JsonArray getNearbyPlayers() { + public Map getNearbyPlayers() { return nearbyPlayers; } - public void setNearbyPlayers(JsonArray nearbyPlayers) { + public void setNearbyPlayers(Map nearbyPlayers) { this.nearbyPlayers = nearbyPlayers; OverlayRenderer.UpdateStates(false, true); } diff --git a/src/main/java/net/emc/emce/caches/Cache.java b/src/main/java/net/emc/emce/caches/Cache.java index 93ab1d5..57cd13c 100644 --- a/src/main/java/net/emc/emce/caches/Cache.java +++ b/src/main/java/net/emc/emce/caches/Cache.java @@ -6,7 +6,7 @@ import java.util.concurrent.CompletableFuture; public abstract class Cache { - int CACHE_SECONDS = 600; + final int CACHE_SECONDS = 600; private Instant lastUpdate = Instant.now(); public boolean updating = false; public T cachedData; diff --git a/src/main/java/net/emc/emce/config/ModConfig.java b/src/main/java/net/emc/emce/config/ModConfig.java index 8700244..feffa97 100644 --- a/src/main/java/net/emc/emce/config/ModConfig.java +++ b/src/main/java/net/emc/emce/config/ModConfig.java @@ -3,7 +3,6 @@ import me.shedaniel.autoconfig.ConfigData; import me.shedaniel.autoconfig.annotation.Config; import me.shedaniel.autoconfig.annotation.Config.Gui.Background; -import me.shedaniel.autoconfig.annotation.ConfigEntry; import me.shedaniel.autoconfig.annotation.ConfigEntry.BoundedDiscrete; import me.shedaniel.autoconfig.annotation.ConfigEntry.Category; import me.shedaniel.autoconfig.annotation.ConfigEntry.Gui.EnumHandler; @@ -11,7 +10,6 @@ import me.shedaniel.cloth.clothconfig.shadowed.blue.endless.jankson.Comment; import net.emc.emce.EarthMCEssentials; import net.emc.emce.objects.Colors; -import net.emc.emce.objects.News.NewsState; import net.emc.emce.utils.ModUtils.State; import static me.shedaniel.autoconfig.annotation.ConfigEntry.Gui.EnumHandler.EnumDisplayOption.BUTTON; @@ -21,136 +19,119 @@ public class ModConfig implements ConfigData { @Category("General") @TransitiveObject() - public General general = new General(); + public final General general = new General(); @Category("Townless") @TransitiveObject() - public Townless townless = new Townless(); + public final Townless townless = new Townless(); @Category("Nearby") @TransitiveObject() - public Nearby nearby = new Nearby(); - - @Category("News") - @TransitiveObject() - public News news = new News(); + public final Nearby nearby = new Nearby(); @Category("Commands") @TransitiveObject() - public Commands commands = new Commands(); + public final Commands commands = new Commands(); - @Category("API") - @TransitiveObject() - public API api = new API(); +// @Category("API") +// @TransitiveObject() +// public API api = new API(); public static class General { @Comment("Toggles the mod on or off.") - public boolean enableMod = true; + public final boolean enableMod = true; } public static class Townless { @Comment("Toggles townless players on or off.") - public boolean enabled = true; + public final boolean enabled = true; @Comment("The maximum length the townless list can be. < 1 for no limit.") - public int maxLength = 0; // < 1 = No limit + public final int maxLength = 0; // < 1 = No limit @Comment("Toggles the use of preset positions, uses sliders if off.") - public boolean presetPositions = true; + public final boolean presetPositions = true; @EnumHandler(option = BUTTON) @Comment("The position of the Townless info.") - public State positionState = State.TOP_LEFT; + public final State positionState = State.TOP_LEFT; @Comment("Note: Only used if Use Preset Positions is off.") - public int xPos = 1; + public final int xPos = 1; @Comment("Note: Only used if Use Preset Positions is off.") - public int yPos = 16; + public final int yPos = 16; @EnumHandler(option = BUTTON) @Comment("The colour of the 'Townless Players' text.") - public Colors headingTextColour = Colors.BLUE; + public final Colors headingTextColour = Colors.BLUE; @EnumHandler(option = BUTTON) @Comment("The colour of the townless player names.") - public Colors playerTextColour = Colors.BLUE; + public final Colors playerTextColour = Colors.BLUE; } public static class Nearby { @Comment("Toggle nearby overlay on or off.") - public boolean enabled = true; + public final boolean enabled = true; @Comment("Toggle if players' ranks should show before their name.") - public boolean showRank = false; + public final boolean showRank = false; @Comment("Toggle between a preset or custom position.") - public boolean presetPositions = true; + public final boolean presetPositions = true; @EnumHandler(option = BUTTON) - public State positionState = State.TOP_RIGHT; + public final State positionState = State.TOP_RIGHT; @Comment("The horizontal position on the HUD.") - public int xPos = 100; + public final int xPos = 100; @Comment("The vertical position on the HUD.") - public int yPos = 16; + public final int yPos = 16; @EnumHandler(option = BUTTON) @Comment("The colour of the 'Nearby Players' text.") - public Colors headingTextColour = Colors.GOLD; + public final Colors headingTextColour = Colors.GOLD; @EnumHandler(option = BUTTON) @Comment("The colour of nearby players' names.") - public Colors playerTextColour = Colors.GOLD; + public final Colors playerTextColour = Colors.GOLD; // Independent scaling - either axis can be the same or different. @Comment("The amount of blocks to check on the X axis.") @BoundedDiscrete(min = 50, max = 10000) - public int xBlocks = 500; + public final int xBlocks = 500; @BoundedDiscrete(min = 50, max = 10000) @Comment("The amount of blocks to check on the Z axis.") - public int zBlocks = 500; - } - - public static class News { - @Comment("Toggle news on or off.") - public boolean enabled = true; - - @EnumHandler(option = BUTTON) - @Comment("The position of where news will be shown.") - public NewsState position = NewsState.ACTION_BAR; + public final int zBlocks = 500; } public static class Commands { @EnumHandler(option = BUTTON) @Comment("The colour of the townless players text.") - public Colors townlessTextColour = Colors.LIGHT_PURPLE; + public final Colors townlessTextColour = Colors.LIGHT_PURPLE; @EnumHandler(option = BUTTON) @Comment("The colour of the town info text.") - public Colors townInfoTextColour = Colors.GREEN; + public final Colors townInfoTextColour = Colors.GREEN; @EnumHandler(option = BUTTON) @Comment("The colour of the nation info text.") - public Colors nationInfoTextColour = Colors.AQUA; + public final Colors nationInfoTextColour = Colors.AQUA; @EnumHandler(option = BUTTON) @Comment("The colour of the alliance info text.") - public Colors allianceInfoTextColour = Colors.GOLD; + public final Colors allianceInfoTextColour = Colors.GOLD; } - public static class API { - @ConfigEntry.Gui.CollapsibleObject - @Comment("Configure the rate (in seconds) at which different data will be updated.") - public Intervals intervals = new Intervals(); - - public static class Intervals { - @Comment("Fairly harmless on performance, can be lowered without much overhead.") - @BoundedDiscrete(min = 30, max = 300) - public int townless = 60; - - @Comment("Small but frequent payload, if you don't rely on it much, turn it up.") - @BoundedDiscrete(min = 10, max = 120) - public int nearby = 20; - - @Comment("Very small payload and you won't need to turn this up in most situations.") - @BoundedDiscrete(min = 10, max = 180) - public int news = 60; - } - } +// public static class API { +// @ConfigEntry.Gui.CollapsibleObject +// @Comment("Configure the rate (in seconds) at which different data will be updated.") +// public Intervals intervals = new Intervals(); +// +// public static class Intervals { +// @Comment("Fairly harmless on performance, can be lowered without much overhead.") +// @BoundedDiscrete(min = 10, max = 600) +// public int townless = 60; +// +// @Comment("Small but frequent payload, if you don't rely on it much, turn it up.") +// @BoundedDiscrete(min = 5, max = 60) +// public int nearby = 30; +// } +// } public static ModConfig instance() { return EarthMCEssentials.instance().getConfig(); diff --git a/src/main/java/net/emc/emce/events/commands/AllianceCommand.java b/src/main/java/net/emc/emce/events/commands/AllianceCommand.java index e54cbaf..b6de90b 100644 --- a/src/main/java/net/emc/emce/events/commands/AllianceCommand.java +++ b/src/main/java/net/emc/emce/events/commands/AllianceCommand.java @@ -18,7 +18,6 @@ import net.kyori.adventure.text.format.TextColor; import net.kyori.adventure.text.format.TextDecoration; -import java.util.Iterator; import java.util.Locale; public record AllianceCommand(EarthMCEssentials instance) { @@ -79,10 +78,9 @@ private static String formatElement(JsonElement element) { if (!element.isJsonArray()) return element.getAsString(); StringBuilder sb = new StringBuilder(); - Iterator iter = element.getAsJsonArray().iterator(); - while (iter.hasNext()) { - sb.append(iter.next().getAsString()); + for (JsonElement jsonElement : element.getAsJsonArray()) { + sb.append(jsonElement.getAsString()); sb.append(", "); } diff --git a/src/main/java/net/emc/emce/events/commands/InfoCommands.java b/src/main/java/net/emc/emce/events/commands/InfoCommands.java index ef10046..ac9b0bf 100644 --- a/src/main/java/net/emc/emce/events/commands/InfoCommands.java +++ b/src/main/java/net/emc/emce/events/commands/InfoCommands.java @@ -81,7 +81,7 @@ private boolean residentExists(Resident res) { return true; } - private void trySendTown(String townName) { + private void trySendTown(@NotNull String townName) { NamedTextColor townTextColour = instance.getConfig().commands.townInfoTextColour.named(); Town town = EarthMCAPI.getTown(townName.toLowerCase(Locale.ROOT)); diff --git a/src/main/java/net/emc/emce/events/commands/NearbyCommand.java b/src/main/java/net/emc/emce/events/commands/NearbyCommand.java index 7ef20f0..fe7aa2d 100644 --- a/src/main/java/net/emc/emce/events/commands/NearbyCommand.java +++ b/src/main/java/net/emc/emce/events/commands/NearbyCommand.java @@ -1,9 +1,8 @@ package net.emc.emce.events.commands; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; import com.mojang.brigadier.CommandDispatcher; +import io.github.emcw.entities.Player; +import io.github.emcw.entities.Resident; import net.emc.emce.EarthMCEssentials; import net.emc.emce.config.ModConfig; import net.emc.emce.utils.Translation; @@ -15,6 +14,8 @@ import net.kyori.adventure.text.format.NamedTextColor; import net.minecraft.client.MinecraftClient; +import java.util.Map; + public record NearbyCommand(EarthMCEssentials instance) { public void register(CommandDispatcher dispatcher) { @@ -29,38 +30,38 @@ public void register(CommandDispatcher dispatcher) { Messaging.send(Component.text("text_nearby_header", headingColour)); - JsonArray nearby = instance.getNearbyPlayers(); - int size = nearby.size(); - - for (int i = 0; i < size; i++) { - JsonObject currentPlayer = nearby.get(i).getAsJsonObject(); + Map nearby = instance.getNearbyPlayers(); - JsonElement xElement = currentPlayer.get("x"); - JsonElement zElement = currentPlayer.get("z"); - if (xElement == null || zElement == null) continue; + for (Player curPlayer : nearby.values()) { + Integer x = curPlayer.getLocation().getX(); + Integer z = curPlayer.getLocation().getZ(); + if (x == null || z == null) continue; - int distance = Math.abs(xElement.getAsInt() - (int) client.player.getX()) + - Math.abs(zElement.getAsInt() - (int) client.player.getZ()); + int distance = Math.abs(x - (int) client.player.getX()) + + Math.abs(z - (int) client.player.getZ()); Component prefix = Component.empty(); if (nearbyConfig.showRank) { - if (!currentPlayer.has("town")) prefix = Translation.of("text_nearby_rank_townless"); - else prefix = Component.text("(" + currentPlayer.get("rank").getAsString() + ") "); + if (!curPlayer.isResident()) prefix = Translation.of("text_nearby_rank_townless"); + else { + Resident res = (Resident) curPlayer; + prefix = Component.text("(" + res.getRank() + ") "); + } } - String str = currentPlayer.get("name").getAsString() + ": " + distance + "m"; + String str = curPlayer.getName() + ": " + distance + "m"; Component comp = Component.empty().append(prefix.append(Component.text(str))); Messaging.send(comp.color(textColour)); } - + return 1; }).then(ClientCommandManager.literal("refresh").executes(c -> { EarthMCAPI.getNearby().thenAccept(instance::setNearbyPlayers); Messaging.sendPrefixed("msg_nearby_refresh"); return 1; })).then(ClientCommandManager.literal("clear").executes(c -> { - instance.setNearbyPlayers(new JsonArray()); + instance.setNearbyPlayers(Map.of()); Messaging.send("msg_nearby_clear"); return 1; }))); diff --git a/src/main/java/net/emc/emce/events/commands/ToggleDebugCommand.java b/src/main/java/net/emc/emce/events/commands/ToggleDebugCommand.java index 4933513..6af5109 100644 --- a/src/main/java/net/emc/emce/events/commands/ToggleDebugCommand.java +++ b/src/main/java/net/emc/emce/events/commands/ToggleDebugCommand.java @@ -2,7 +2,6 @@ package net.emc.emce.events.commands; import com.mojang.brigadier.CommandDispatcher; -import net.emc.emce.utils.Translation; import net.emc.emce.utils.Messaging; import net.fabricmc.fabric.api.client.command.v2.ClientCommandManager; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; diff --git a/src/main/java/net/emc/emce/events/screen/ScreenInit.java b/src/main/java/net/emc/emce/events/screen/ScreenInit.java index 1c72683..9478953 100644 --- a/src/main/java/net/emc/emce/events/screen/ScreenInit.java +++ b/src/main/java/net/emc/emce/events/screen/ScreenInit.java @@ -2,7 +2,6 @@ import me.shedaniel.clothconfig2.gui.ClothConfigScreen; import net.emc.emce.modules.OverlayRenderer; -import net.fabricmc.fabric.api.client.screen.v1.ScreenEvents; import net.fabricmc.fabric.impl.client.screen.ScreenExtensions; import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.screen.Screen; diff --git a/src/main/java/net/emc/emce/mixins/ClientPlayNetworkHandlerMixin.java b/src/main/java/net/emc/emce/mixins/ClientPlayNetworkHandlerMixin.java index ccb5dce..b4c48a7 100644 --- a/src/main/java/net/emc/emce/mixins/ClientPlayNetworkHandlerMixin.java +++ b/src/main/java/net/emc/emce/mixins/ClientPlayNetworkHandlerMixin.java @@ -1,8 +1,6 @@ package net.emc.emce.mixins; import com.mojang.authlib.GameProfile; -import net.emc.emce.EarthMCEssentials; -import net.emc.emce.modules.EventRegistry; import net.emc.emce.modules.OverlayRenderer; import net.emc.emce.utils.EarthMCAPI; import net.emc.emce.utils.ModUtils; @@ -10,12 +8,9 @@ import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.network.ClientPlayNetworkHandler; import net.minecraft.client.network.ServerInfo; -import net.minecraft.client.util.telemetry.TelemetrySender; import net.minecraft.client.util.telemetry.WorldSession; import net.minecraft.network.ClientConnection; import net.minecraft.network.packet.s2c.play.DisconnectS2CPacket; -import net.minecraft.network.packet.s2c.play.GameJoinS2CPacket; -import net.minecraft.text.Text; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; diff --git a/src/main/java/net/emc/emce/mixins/SessionEventListenerMixin.java b/src/main/java/net/emc/emce/mixins/SessionEventListenerMixin.java index cacb5da..17c95c2 100644 --- a/src/main/java/net/emc/emce/mixins/SessionEventListenerMixin.java +++ b/src/main/java/net/emc/emce/mixins/SessionEventListenerMixin.java @@ -16,7 +16,6 @@ import static net.emc.emce.modules.EventRegistry.RegisterScreen; import static net.emc.emce.modules.EventRegistry.RegisterHud; -import static net.emc.emce.utils.ModUtils.updateServerName; @Mixin(MinecraftClientGame.class) public abstract class SessionEventListenerMixin { diff --git a/src/main/java/net/emc/emce/modules/OverlayRenderer.java b/src/main/java/net/emc/emce/modules/OverlayRenderer.java index 40475cd..bfe9b58 100644 --- a/src/main/java/net/emc/emce/modules/OverlayRenderer.java +++ b/src/main/java/net/emc/emce/modules/OverlayRenderer.java @@ -1,17 +1,10 @@ package net.emc.emce.modules; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; +import io.github.emcw.entities.Player; +import io.github.emcw.entities.Resident; import net.emc.emce.config.ModConfig; -import net.emc.emce.objects.News.NewsData; -import net.emc.emce.objects.News.NewsState; -import net.emc.emce.utils.Messaging; import net.emc.emce.utils.ModUtils; import net.emc.emce.utils.ModUtils.State; -import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.TextComponent; -import net.kyori.adventure.text.format.NamedTextColor; import net.minecraft.client.MinecraftClient; import net.minecraft.client.font.TextRenderer; import net.minecraft.client.util.math.MatrixStack; @@ -19,9 +12,12 @@ import net.minecraft.util.Formatting; import java.util.List; +import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; import static net.emc.emce.EarthMCEssentials.instance; +import static net.emc.emce.utils.ModUtils.getTextWidth; +import static net.minecraft.text.Text.translatable; public class OverlayRenderer { private static MinecraftClient client; @@ -46,11 +42,11 @@ public static void Init() { } public static void Clear() { - instance().setNearbyPlayers(new JsonArray()); + instance().setNearbyPlayers(Map.of()); townless = new CopyOnWriteArrayList<>(); } - public static JsonArray nearby() { + public static Map nearby() { return instance().getNearbyPlayers(); } @@ -84,7 +80,7 @@ private static void RenderTownless(boolean usingPreset) { Formatting playerTextFormatting = Formatting.byName(config.townless.playerTextColour.name()); Formatting townlessTextFormatting = Formatting.byName(config.townless.headingTextColour.name()); - MutableText townlessText = Text.translatable("text_townless_header", townlessSize).formatted(townlessTextFormatting); + MutableText townlessText = translatable("text_townless_header", townlessSize).formatted(townlessTextFormatting); if (usingPreset) { // Draw heading. @@ -94,12 +90,12 @@ private static void RenderTownless(boolean usingPreset) { for (String townlessName : townless) { if (maxLen > 0 && index >= maxLen) { - MutableText remainingText = Text.translatable("text_townless_remaining", townlessSize - index).formatted(playerTextFormatting); + MutableText remainingText = translatable("text_townless_remaining", townlessSize - index).formatted(playerTextFormatting); renderer.drawWithShadow(matrixStack, remainingText, x, y + index * 10, color); break; } - MutableText playerName = Text.translatable(townlessName).formatted(playerTextFormatting); + MutableText playerName = translatable(townlessName).formatted(playerTextFormatting); renderer.drawWithShadow(matrixStack, playerName, x, y + index++ * 10, color); } } @@ -117,7 +113,7 @@ private static void RenderTownless(boolean usingPreset) { for (String name : townless) { if (maxLen >= 1) { if (index >= maxLen) { - MutableText remainingText = Text.translatable("text_townless_remaining", townlessSize - index).formatted(playerTextFormatting); + MutableText remainingText = translatable("text_townless_remaining", townlessSize - index).formatted(playerTextFormatting); renderer.drawWithShadow(matrixStack, remainingText, xOffset, playerOffset, color); break; } @@ -125,7 +121,7 @@ private static void RenderTownless(boolean usingPreset) { index++; } - MutableText playerName = Text.translatable(name).formatted(playerTextFormatting); + MutableText playerName = translatable(name).formatted(playerTextFormatting); renderer.drawWithShadow(matrixStack, playerName, xOffset, playerOffset, color); // Add offset for the next player. @@ -136,40 +132,45 @@ private static void RenderTownless(boolean usingPreset) { } private static void RenderNearby(boolean usingPreset) { - int nearbySize = nearby().size(); + Map nearby = nearby(); Formatting playerTextFormatting = Formatting.byName(config.nearby.playerTextColour.name()); Formatting nearbyTextFormatting = Formatting.byName(config.nearby.headingTextColour.name()); - MutableText nearbyText = Text.translatable("text_nearby_header", nearbySize).formatted(nearbyTextFormatting); + MutableText nearbyText = translatable("text_nearby_header", nearby.size()).formatted(nearbyTextFormatting); if (usingPreset) { // Draw heading. renderer.drawWithShadow(matrixStack, nearbyText, nearbyState.getX(), nearbyState.getY() - 10, color); if (client.player == null) return; - if (nearbySize >= 1) { - for (int i = 0; i < nearbySize; i++) { - JsonObject currentPlayer = nearby().get(i).getAsJsonObject(); + if (nearby.size() >= 1) { + int i = 0; - JsonElement xElement = currentPlayer.get("x"); - JsonElement zElement = currentPlayer.get("z"); - if (xElement == null || zElement == null) continue; + for (Player curPlayer : nearby.values()) { + Integer x = curPlayer.getLocation().getX(); + Integer z = curPlayer.getLocation().getZ(); + if (x == null || z == null) continue; - String currentPlayerName = currentPlayer.get("name").getAsString(); - if (currentPlayerName.equals(client.player.getName().getString())) continue; + String name = curPlayer.getName(); + if (name.equals(client.player.getName().getString())) continue; - int distance = Math.abs(xElement.getAsInt() - (int) client.player.getX()) + - Math.abs(zElement.getAsInt() - (int) client.player.getZ()); + int distance = Math.abs(x - (int) client.player.getX()) + + Math.abs(z - (int) client.player.getZ()); String prefix = ""; if (config.nearby.showRank) { - if (!currentPlayer.has("town")) prefix = "(Townless) "; - else prefix = "(" + currentPlayer.get("rank").getAsString() + ") "; + if (!curPlayer.isResident()) prefix = "(Townless) "; + else { + Resident res = (Resident) curPlayer; + prefix = "(" + res.getRank() + ") "; + } } - MutableText playerText = Text.translatable(prefix + currentPlayerName + ": " + distance + "m").formatted(playerTextFormatting); + MutableText playerText = translatable(prefix + name + ": " + distance + "m").formatted(playerTextFormatting); renderer.drawWithShadow(matrixStack, playerText, nearbyState.getX(), nearbyState.getY() + 10 * i, color); + + ++i; } } } @@ -182,27 +183,28 @@ private static void RenderNearby(boolean usingPreset) { renderer.drawWithShadow(matrixStack, nearbyText, xOffset, playerOffset - 15, color); if (client.player == null) return; - if (nearbySize >= 1) { - for (int i = 0; i < nearbySize; i++) { - JsonObject currentPlayer = nearby().get(i).getAsJsonObject(); + if (nearby.size() >= 1) { + for (Player curPlayer : nearby.values()) { + Integer x = curPlayer.getLocation().getX(); + Integer z = curPlayer.getLocation().getZ(); + if (x == null || z == null) continue; - JsonElement xElement = currentPlayer.get("x"); - JsonElement zElement = currentPlayer.get("z"); - if (xElement == null || zElement == null) continue; - - String currentPlayerName = currentPlayer.get("name").getAsString(); + String currentPlayerName = curPlayer.getName(); if (currentPlayerName.equals(client.player.getName().getString())) continue; - int distance = Math.abs(xElement.getAsInt() - (int) client.player.getX()) + - Math.abs(zElement.getAsInt() - (int) client.player.getZ()); + int distance = Math.abs(x - (int) client.player.getX()) + + Math.abs(z - (int) client.player.getZ()); String prefix = ""; if (config.nearby.showRank) { - if (!currentPlayer.has("town")) prefix = "(Townless) "; - else prefix = "(" + currentPlayer.get("rank").getAsString() + ") "; + if (!curPlayer.isResident()) prefix = "(Townless) "; + else { + Resident res = (Resident) curPlayer; + prefix = "(" + res.getRank() + ") "; + } } - MutableText playerText = Text.translatable(prefix + currentPlayerName + ": " + distance + "m").formatted(playerTextFormatting); + MutableText playerText = translatable(prefix + currentPlayerName + ": " + distance + "m").formatted(playerTextFormatting); renderer.drawWithShadow(matrixStack, playerText, xOffset, playerOffset, color); // Add 10 pixels to offset. (Where the next player will be rendered) @@ -217,10 +219,10 @@ private static void UpdateTownlessState() { int townlessLongest, nearbyLongest; townlessLongest = Math.max(ModUtils.getLongestElement(townless), - ModUtils.getTextWidth(Text.translatable("text_townless_header", townless.size()))); + getTextWidth(translatable("text_townless_header", townless.size()))); nearbyLongest = Math.max(ModUtils.getNearbyLongestElement(instance().getNearbyPlayers()), - ModUtils.getTextWidth(Text.translatable("text_nearby_header", nearby().size()))); + getTextWidth(translatable("text_nearby_header", nearby().size()))); int windowHeight = ModUtils.getWindowHeight(); int windowWidth = ModUtils.getWindowWidth(); @@ -271,17 +273,17 @@ private static void UpdateNearbyState() { int nearbyLongest, townlessLongest; nearbyLongest = Math.max(ModUtils.getNearbyLongestElement(instance().getNearbyPlayers()), - ModUtils.getTextWidth(Text.translatable("text_nearby_header", nearby().size()))); + getTextWidth(translatable("text_nearby_header", nearby().size()))); townlessLongest = Math.max(ModUtils.getLongestElement(townless), - ModUtils.getTextWidth(Text.translatable("text_townless_header", townless.size()))); + getTextWidth(translatable("text_townless_header", townless.size()))); int windowHeight = ModUtils.getWindowHeight(); int windowWidth = ModUtils.getWindowWidth(); int nearbyArrayHeight = ModUtils.getArrayHeight(nearby()); int windowHeightOffset = windowHeight - nearbyArrayHeight - 10; - int windowHeightHalfOffset = windowHeight/2 - nearbyArrayHeight/2; + int windowHeightHalfOffset = windowHeight / 2 - nearbyArrayHeight / 2; int xRightOffset = windowWidth - townlessLongest - nearbyLongest - 15; diff --git a/src/main/java/net/emc/emce/modules/TaskScheduler.java b/src/main/java/net/emc/emce/modules/TaskScheduler.java index 31c114e..4fe56ff 100644 --- a/src/main/java/net/emc/emce/modules/TaskScheduler.java +++ b/src/main/java/net/emc/emce/modules/TaskScheduler.java @@ -5,7 +5,6 @@ import net.emc.emce.config.ModConfig; import net.emc.emce.utils.EarthMCAPI; import net.emc.emce.utils.Messaging; -import net.emc.emce.utils.ModUtils; import net.minecraft.client.MinecraftClient; import java.util.List; @@ -33,9 +32,9 @@ public void start() { if (config.nearby.enabled) EarthMCAPI.getNearby().thenAccept(instance()::setNearbyPlayers); } - startTownless(); - startNearby(); - startCacheCheck(); + //startTownless(); + //startNearby(); + //startCacheCheck(); } public void stop() { @@ -74,34 +73,34 @@ public void setHasMap(String map) { } } - private void startTownless() { - townlessRunning = true; - ModConfig config = ModConfig.instance(); - - service.scheduleAtFixedRate(() -> { - if (townlessRunning && config.townless.enabled && shouldRun()) { - Messaging.sendDebugMessage("Starting townless task."); - - instance().setTownless(getTownless()); - Messaging.sendDebugMessage("Finished townless task."); - } - }, 30, Math.max(config.api.intervals.townless, 30), TimeUnit.SECONDS); - } - - private void startNearby() { - nearbyRunning = true; - final ModConfig config = ModConfig.instance(); - - service.scheduleAtFixedRate(() -> { - if (nearbyRunning && config.nearby.enabled && shouldRun()) { - Messaging.sendDebugMessage("Starting nearby task."); - EarthMCAPI.getNearby().thenAccept(nearby -> { - instance().setNearbyPlayers(nearby); - Messaging.sendDebugMessage("Finished nearby task."); - }); - } - }, 10, Math.max(config.api.intervals.nearby, 10), TimeUnit.SECONDS); - } +// private void startTownless() { +// townlessRunning = true; +// ModConfig config = ModConfig.instance(); +// +// service.scheduleAtFixedRate(() -> { +// if (townlessRunning && config.townless.enabled && shouldRun()) { +// Messaging.sendDebugMessage("Starting townless task."); +// +// instance().setTownless(getTownless()); +// Messaging.sendDebugMessage("Finished townless task."); +// } +// }, 30, Math.max(config.api.intervals.townless, 30), TimeUnit.SECONDS); +// } +// +// private void startNearby() { +// nearbyRunning = true; +// final ModConfig config = ModConfig.instance(); +// +// service.scheduleAtFixedRate(() -> { +// if (nearbyRunning && config.nearby.enabled && shouldRun()) { +// Messaging.sendDebugMessage("Starting nearby task."); +// EarthMCAPI.getNearby().thenAccept(nearby -> { +// instance().setNearbyPlayers(nearby); +// Messaging.sendDebugMessage("Finished nearby task."); +// }); +// } +// }, 10, Math.max(config.api.intervals.nearby, 10), TimeUnit.SECONDS); +// } private void startCacheCheck() { cacheCheckRunning = true; @@ -116,10 +115,7 @@ private void startCacheCheck() { } private boolean shouldRun() { - ModConfig config = ModConfig.instance(); - boolean focused = MinecraftClient.getInstance().isWindowFocused(); - boolean playingEMC = config.general.enableMod; - - return playingEMC && focused; + return ModConfig.instance().general.enableMod && + MinecraftClient.getInstance().isWindowFocused(); } } diff --git a/src/main/java/net/emc/emce/objects/API/APIData.java b/src/main/java/net/emc/emce/objects/API/APIData.java index aec6d31..8408633 100644 --- a/src/main/java/net/emc/emce/objects/API/APIData.java +++ b/src/main/java/net/emc/emce/objects/API/APIData.java @@ -1,36 +1,39 @@ package net.emc.emce.objects.API; import com.google.gson.JsonObject; -import net.emc.emce.config.ModConfig; +import org.jetbrains.annotations.NotNull; + +import static io.github.emcw.utils.GsonUtil.keyAsStr; public class APIData { private final String domain; - public Routes routes = new Routes(); + public final Routes routes; public static class Routes { - public String allPlayers; - public String nearby; - public String news; - public String alliances; + public final String allPlayers; + public final String alliances; + + public Routes() { + allPlayers = ""; + alliances = ""; + } + + public Routes(String allPlayers, String alliances) { + this.allPlayers = allPlayers; + this.alliances = alliances; + } } - public APIData(JsonObject object) { - domain = object.get("domain").getAsString(); - JsonObject routesObj = object.get("routes").getAsJsonObject(); + public APIData(@NotNull JsonObject object) { + domain = keyAsStr(object, "domain"); + JsonObject obj = object.get("routes").getAsJsonObject(); - routes.allPlayers = routesObj.get("allplayers").getAsString(); - routes.nearby = routesObj.get("nearby").getAsString(); - routes.alliances = routesObj.get("alliances").getAsString(); - //routes.news = routesObj.get("news").getAsString(); + routes = new Routes(keyAsStr(obj, "allplayers"), keyAsStr(obj, "alliances")); } public APIData() { domain = ""; - - routes.allPlayers = ""; - routes.nearby = ""; - routes.news = ""; - routes.alliances = ""; + routes = new Routes(); } public String getDomain() { return domain; } diff --git a/src/main/java/net/emc/emce/objects/API/APIRoute.java b/src/main/java/net/emc/emce/objects/API/APIRoute.java index 1759800..5cf5222 100644 --- a/src/main/java/net/emc/emce/objects/API/APIRoute.java +++ b/src/main/java/net/emc/emce/objects/API/APIRoute.java @@ -1,7 +1,6 @@ package net.emc.emce.objects.API; public enum APIRoute { - NEARBY, ALL_PLAYERS, ALLIANCES } \ No newline at end of file diff --git a/src/main/java/net/emc/emce/utils/EarthMCAPI.java b/src/main/java/net/emc/emce/utils/EarthMCAPI.java index 79782b0..62b6c6b 100644 --- a/src/main/java/net/emc/emce/utils/EarthMCAPI.java +++ b/src/main/java/net/emc/emce/utils/EarthMCAPI.java @@ -5,10 +5,7 @@ import com.google.gson.JsonParser; import io.github.emcw.core.EMCMap; import io.github.emcw.core.EMCWrapper; -import io.github.emcw.entities.Nation; -import io.github.emcw.entities.Player; -import io.github.emcw.entities.Resident; -import io.github.emcw.entities.Town; +import io.github.emcw.entities.*; import io.github.emcw.exceptions.MissingEntryException; import net.emc.emce.config.ModConfig; import net.emc.emce.objects.API.APIData; @@ -41,7 +38,7 @@ public class EarthMCAPI { public static APIData apiData = new APIData(); public static JsonObject player = new JsonObject(); - public static EMCWrapper wrapper = new EMCWrapper(true, true); + public static final EMCWrapper wrapper = new EMCWrapper(true, true); private static EMCMap currentMap() { return Objects.equals(instance().mapName, "aurora") ? wrapper.getAurora() : wrapper.getNova(); @@ -73,38 +70,33 @@ public static Map getResidents() { } @Contract(" -> new") - public static @NotNull CompletableFuture getNearby() { + public static @NotNull CompletableFuture> getNearby() { return getNearby(config.nearby.xBlocks, config.nearby.zBlocks); } @Contract("_, _ -> new") - public static @NotNull CompletableFuture getNearby(int xBlocks, int zBlocks) { + public static @NotNull CompletableFuture> getNearby(int xBlocks, int zBlocks) { return CompletableFuture.supplyAsync(() -> { + Map result = Map.of(); + try { MinecraftClient client = MinecraftClient.getInstance(); ClientPlayerEntity player = client.player; - if (player != null) { - if (!player.getEntityWorld().getDimension().bedWorks()) - return new JsonArray(); + if (player == null) return result; + if (!player.getEntityWorld().getDimension().bedWorks()) return result; - JsonArray array = (JsonArray) JsonParser.parseString(getURL(getRoute(APIRoute.NEARBY) + "/" + - (int) player.getX() + "/" + - (int) player.getZ() + "/" + - xBlocks + "/" + zBlocks)); + EMCMap curMap = currentMap(); + Integer x = (int) player.getX(), + y = (int) player.getY(); - int size = array.size(); - for (int i = 0; i < size; i++) { - JsonObject currentObj = (JsonObject) array.get(i); - if (currentObj.get("name").getAsString().equals(clientName())) - array.remove(i); - } + Map nearby = curMap.Players.getNearby(curMap.Players.all(), x, y, xBlocks, zBlocks); + nearby.remove(clientName()); - return array; - } else return instance().getNearbyPlayers(); - } catch (APIException e) { + return nearby; + } catch (Exception e) { Messaging.sendDebugMessage("Error fetching nearby!", e); - return instance().getNearbyPlayers(); + return result; } }); } @@ -151,7 +143,6 @@ public static String getRoute(APIRoute routeType) { switch(routeType) { case ALL_PLAYERS -> route = apiData.routes.allPlayers; case ALLIANCES -> route = apiData.routes.alliances; - case NEARBY -> route = apiData.routes.nearby; default -> throw new IllegalStateException("Unexpected value: " + routeType); } @@ -161,8 +152,10 @@ public static String getRoute(APIRoute routeType) { return apiData.getDomain() + endpoint; } + @Nullable public static String clientName() { - return MinecraftClient.getInstance().player.getName().getString(); + ClientPlayerEntity pl = MinecraftClient.getInstance().player; + return pl == null ? null : pl.getName().getString(); } public static boolean playerOnline(String map) { diff --git a/src/main/java/net/emc/emce/utils/Messaging.java b/src/main/java/net/emc/emce/utils/Messaging.java index c7baa01..f7db001 100644 --- a/src/main/java/net/emc/emce/utils/Messaging.java +++ b/src/main/java/net/emc/emce/utils/Messaging.java @@ -2,6 +2,7 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; +import net.minecraft.client.network.ClientPlayerEntity; import java.util.Collections; import java.util.List; @@ -58,7 +59,8 @@ public static void sendPrefixedActionBar(Component text) { //#region Send Command public static void performCommand(String cmd) { - getInstance().player.networkHandler.sendCommand(cmd); + ClientPlayerEntity pl = getInstance().player; + if (pl != null) getInstance().player.networkHandler.sendCommand(cmd); } //endregion diff --git a/src/main/java/net/emc/emce/utils/ModUtils.java b/src/main/java/net/emc/emce/utils/ModUtils.java index 5b86609..af87f7a 100644 --- a/src/main/java/net/emc/emce/utils/ModUtils.java +++ b/src/main/java/net/emc/emce/utils/ModUtils.java @@ -1,8 +1,6 @@ package net.emc.emce.utils; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; +import io.github.emcw.entities.Player; import io.github.emcw.entities.Resident; import net.minecraft.client.MinecraftClient; import net.minecraft.client.network.ClientPlayNetworkHandler; @@ -14,9 +12,7 @@ import org.jetbrains.annotations.NotNull; import java.net.InetSocketAddress; -import java.util.Collection; -import java.util.List; -import java.util.Objects; +import java.util.*; import static net.emc.emce.EarthMCEssentials.instance; import static net.minecraft.client.MinecraftClient.getInstance; @@ -72,18 +68,16 @@ public void setY(int y) { public static int getWindowWidth() { return getInstance().getWindow().getScaledWidth(); } public static int getWindowHeight() { return getInstance().getWindow().getScaledHeight(); } - public static String elementAsString(@NotNull JsonElement el, String name) { - return el.getAsJsonObject().get(name).getAsString(); - } - @SuppressWarnings("unused") - public static int getLongestElement(@NotNull JsonArray array) { - int length = array.size(); - if (array == null || length < 1) return 0; + public static int getLongestElement(Map map) { + int length = map == null ? 0 : map.size(); + if (length < 1) return 0; + + List keys = new ArrayList<>(map.keySet()); int longestElement = 0, i = 0; for (; i < length; i++) { - int currentWidth = getStringWidth(elementAsString(array.get(i), "name")); + int currentWidth = getStringWidth(keys.get(i)); longestElement = Math.max(currentWidth, longestElement); } @@ -99,13 +93,16 @@ public static int getLongestElement(@NotNull Collection collection) { return longestElement; } - public static int getArrayHeight(JsonArray array) { - int length = array.size(); + public static int getArrayHeight(Map map) { + int length = map.size(); if (length < 1) return 0; + List keys = new ArrayList<>(map.keySet()); + int totalLength = 0, i = 0; - for (; i < length; i++) - totalLength += getStringHeight(elementAsString(array.get(i), "name")); + for (; i < length; i++) { + totalLength += getStringHeight(keys.get(i)); + } return totalLength; } @@ -128,34 +125,36 @@ public static int getTownlessArrayHeight(List townless, int maxLength) { return totalLength; } - public static int getNearbyLongestElement(JsonArray nearbyResidents) { - int length = nearbyResidents.size(); + public static int getNearbyLongestElement(@NotNull Map nearby) { + int length = nearby.size(); if (length < 1) return 0; - int longestElement = 0, i = 0; - for (; i < length; i++) { - JsonObject currentObj = nearbyResidents.get(i).getAsJsonObject(); + int longestElement = 0; + for (Player curPlayer : nearby.values()) { Resident clientRes = instance().getClientResident(); - JsonElement name = currentObj.get("name"); - JsonElement xElem = currentObj.get("x"); - JsonElement zElem = currentObj.get("z"); + String name = curPlayer.getName(); + Integer x = curPlayer.getLocation().getX(); + Integer z = curPlayer.getLocation().getZ(); - if (zElem == null || xElem == null || name == null) continue; - if (clientRes != null && name.getAsString().equals(clientRes.getName())) continue; + if (z == null || x == null || name == null) continue; + if (clientRes != null && name.equals(clientRes.getName())) continue; ClientPlayerEntity player = Objects.requireNonNull(getInstance().player); - int distance = Math.abs(xElem.getAsInt() - player.getBlockX()) + - Math.abs(zElem.getAsInt() - player.getBlockZ()); + int distance = Math.abs(x - player.getBlockX()) + + Math.abs(z - player.getBlockZ()); String prefix = ""; if (instance().getConfig().nearby.showRank) { - if (!currentObj.has("town")) prefix = "(Townless) "; - else prefix = "(" + currentObj.get("rank").getAsString() + ") "; + if (!curPlayer.isResident()) prefix = "(Townless) "; + else { + Resident curRes = (Resident) curPlayer; + prefix = "(" + curRes.getRank() + ") "; + } } - MutableText nearbyText = Text.translatable(prefix + name.getAsString() + ": " + distance + "m"); + MutableText nearbyText = Text.translatable(prefix + name + ": " + distance + "m"); longestElement = Math.max(getTextWidth(nearbyText), longestElement); } From 0553a7112e361c2eee03ef373b16bca1f3bf1188 Mon Sep 17 00:00:00 2001 From: Owen Stubbs Date: Wed, 29 Mar 2023 21:17:57 +0100 Subject: [PATCH 07/19] e --- src/main/java/net/emc/emce/utils/ModUtils.java | 11 +++++------ src/main/resources/api.json | 3 +-- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/src/main/java/net/emc/emce/utils/ModUtils.java b/src/main/java/net/emc/emce/utils/ModUtils.java index af87f7a..5ba51e1 100644 --- a/src/main/java/net/emc/emce/utils/ModUtils.java +++ b/src/main/java/net/emc/emce/utils/ModUtils.java @@ -161,14 +161,13 @@ public static int getNearbyLongestElement(@NotNull Map nearby) { return longestElement; } - public static int getStatusEffectOffset(Collection statusEffectInstances) { - if (statusEffectInstances.isEmpty()) return 16; + public static int getStatusEffectOffset(Collection statusEffects) { + if (statusEffects.isEmpty()) return 16; int offset = 0; - for (StatusEffectInstance statusEffectInstance : statusEffectInstances) { - if (statusEffectInstance.shouldShowIcon()) { - if (statusEffectInstance.getEffectType().isBeneficial()) offset = Math.max(offset, 36); - else offset = 64; + for (StatusEffectInstance effect : statusEffects) { + if (effect.shouldShowIcon()) { + offset = effect.getEffectType().isBeneficial() ? Math.max(offset, 36) : 64; } } diff --git a/src/main/resources/api.json b/src/main/resources/api.json index 9a04d01..7b09cb3 100644 --- a/src/main/resources/api.json +++ b/src/main/resources/api.json @@ -2,7 +2,6 @@ "domain": "https://emctoolkit.vercel.app/api/", "routes": { "allplayers": "/allplayers", - "alliances": "/alliances", - "nearby": "/nearby/players" + "alliances": "/alliances" } } From 27f61088bbec09c1d84c279626b68363a9dd85df Mon Sep 17 00:00:00 2001 From: Owen Stubbs Date: Wed, 29 Mar 2023 21:20:23 +0100 Subject: [PATCH 08/19] Update SessionEventListenerMixin.java --- .../emc/emce/mixins/SessionEventListenerMixin.java | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/src/main/java/net/emc/emce/mixins/SessionEventListenerMixin.java b/src/main/java/net/emc/emce/mixins/SessionEventListenerMixin.java index 17c95c2..8e2b1a4 100644 --- a/src/main/java/net/emc/emce/mixins/SessionEventListenerMixin.java +++ b/src/main/java/net/emc/emce/mixins/SessionEventListenerMixin.java @@ -29,14 +29,11 @@ public void onStartGameSession(CallbackInfo ci) { RegisterScreen(); RegisterHud(); - if (!isConnectedToEMC()) { - instance().setShouldRender(false); - return; + instance().setShouldRender(instance().getConfig().general.enableMod); + if (isConnectedToEMC()) { + updateSessionCounter('+'); + fetchEndpoints(); } - - instance().setShouldRender(true); - updateSessionCounter('+'); - fetchEndpoints(); } @Inject(at = @At("TAIL"), method="onLeaveGameSession") From 6c8e8f43ec2c8443721d0316dd3793bb011e1463 Mon Sep 17 00:00:00 2001 From: Owen Stubbs Date: Wed, 29 Mar 2023 21:26:41 +0100 Subject: [PATCH 09/19] delete more news stuff --- README.md | 3 +- gradle.properties | 1 - .../net/emc/emce/modules/TaskScheduler.java | 3 +- .../net/emc/emce/objects/News/NewsData.java | 28 ------------------- .../net/emc/emce/objects/News/NewsState.java | 6 ---- .../resources/assets/emce/lang/en_us.json | 8 +----- 6 files changed, 3 insertions(+), 46 deletions(-) delete mode 100644 src/main/java/net/emc/emce/objects/News/NewsData.java delete mode 100644 src/main/java/net/emc/emce/objects/News/NewsState.java diff --git a/README.md b/README.md index 6890906..51fbf8c 100644 --- a/README.md +++ b/README.md @@ -12,9 +12,8 @@ A fabric mod designed for EarthMC that provides info on people, places and more. - `/townless inviteAll/revokeAll` - Automatically invite/revoke all townless players to/from your town! - `/nether ` - Quickly convert overworld coordinates into their nether counterpart. #### On-Screen Info - - Townless - All online townless players are shown on your screen. + - Townless - Show a list of online townless players and their (optional) coords. - Nearby - See anyone whose close to you without checking the dynmap! Configurable options include: radius, rank and distance. - - News - Sometimes it's hard to keep up with the news. EMCE sends news to your action bar (or chat) as soon as it is reported. #### Config screen (F4) - API Intervals - Set the rate at which you want data to be updated. - Data - Toggle on/off, screen x/y position, text colors, radius and more. diff --git a/gradle.properties b/gradle.properties index a38b477..e0687b5 100644 --- a/gradle.properties +++ b/gradle.properties @@ -9,7 +9,6 @@ yarn_mappings=1.19.3+build.5 loader_version=0.14.12 fabric_version=0.72.0+1.19.3 - # Mod Properties name = EarthMCEssentials mod_version = 3.6.0 diff --git a/src/main/java/net/emc/emce/modules/TaskScheduler.java b/src/main/java/net/emc/emce/modules/TaskScheduler.java index 4fe56ff..dc95e0e 100644 --- a/src/main/java/net/emc/emce/modules/TaskScheduler.java +++ b/src/main/java/net/emc/emce/modules/TaskScheduler.java @@ -18,7 +18,7 @@ public class TaskScheduler { public ScheduledExecutorService service; - public boolean townlessRunning, nearbyRunning, cacheCheckRunning, newsRunning; + public boolean townlessRunning, nearbyRunning, cacheCheckRunning; public boolean hasMap = false; private static final List> CACHES = List.of(AllianceDataCache.INSTANCE); @@ -40,7 +40,6 @@ public void start() { public void stop() { townlessRunning = false; nearbyRunning = false; - newsRunning = false; cacheCheckRunning = false; Messaging.sendDebugMessage("Stopping scheduled tasks..."); diff --git a/src/main/java/net/emc/emce/objects/News/NewsData.java b/src/main/java/net/emc/emce/objects/News/NewsData.java deleted file mode 100644 index 3753eb0..0000000 --- a/src/main/java/net/emc/emce/objects/News/NewsData.java +++ /dev/null @@ -1,28 +0,0 @@ -package net.emc.emce.objects.News; - -import com.google.gson.JsonObject; - -public class NewsData { - private final String message; - private final int id, timestamp; - - public NewsData(JsonObject object) { - JsonObject elem = object != null ? object.get("latest").getAsJsonObject() : null; - - this.message = elem == null ? "" : elem.get("message").getAsString(); - this.id = elem == null ? 0 : elem.get("id").getAsInt(); - this.timestamp = elem == null ? 0 : elem.get("timestamp").getAsInt(); - } - - public String getMsg() { - return message; - } - - public int getID() { - return id; - } - - public int getTimestamp() { - return timestamp; - } -} \ No newline at end of file diff --git a/src/main/java/net/emc/emce/objects/News/NewsState.java b/src/main/java/net/emc/emce/objects/News/NewsState.java deleted file mode 100644 index e760f97..0000000 --- a/src/main/java/net/emc/emce/objects/News/NewsState.java +++ /dev/null @@ -1,6 +0,0 @@ -package net.emc.emce.objects.News; - -public enum NewsState { - CHAT, - ACTION_BAR -} diff --git a/src/main/resources/assets/emce/lang/en_us.json b/src/main/resources/assets/emce/lang/en_us.json index 4425e3a..d3345d0 100644 --- a/src/main/resources/assets/emce/lang/en_us.json +++ b/src/main/resources/assets/emce/lang/en_us.json @@ -82,10 +82,6 @@ "text.autoconfig.emc-essentials.option.nearby.xBlocks": "X Blocks", "text.autoconfig.emc-essentials.option.nearby.zBlocks": "Z Blocks", - "text.autoconfig.emc-essentials.category.News": "News", - "text.autoconfig.emc-essentials.option.news.enabled": "Enabled", - "text.autoconfig.emc-essentials.option.news.position": "Position", - "text.autoconfig.emc-essentials.category.Commands": "Commands", "text.autoconfig.emc-essentials.option.commands.townlessTextColour": "Townless Text Colour", "text.autoconfig.emc-essentials.option.commands.townInfoTextColour": "Town Text Colour", @@ -94,7 +90,5 @@ "text.autoconfig.emc-essentials.category.API": "API", "text.autoconfig.emc-essentials.option.api.intervals": "Intervals", - "text.autoconfig.emc-essentials.option.api.intervals.townless": "Townless", - "text.autoconfig.emc-essentials.option.api.intervals.nearby": "Nearby", - "text.autoconfig.emc-essentials.option.api.intervals.news": "News" + "text.autoconfig.emc-essentials.option.api.intervals.townless": "Townless" } \ No newline at end of file From e598b6bc83bed76f3cd33a05824f36dfc2dbc4ec Mon Sep 17 00:00:00 2001 From: Owen Stubbs Date: Thu, 30 Mar 2023 20:07:23 +0100 Subject: [PATCH 10/19] gradle changes --- gradle/wrapper/gradle-wrapper.jar | Bin 59536 -> 60756 bytes gradle/wrapper/gradle-wrapper.properties | 2 +- gradlew | 16 +++++++++++----- gradlew.bat | 14 ++++++++------ 4 files changed, 20 insertions(+), 12 deletions(-) diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 7454180f2ae8848c63b8b4dea2cb829da983f2fa..249e5832f090a2944b7473328c07c9755baa3196 100644 GIT binary patch delta 10158 zcmaKSbyOWsmn~e}-QC?axCPf>!2<-jxI0|j{UX8L-QC?axDz};a7}ppGBe+Nv*x{5 zy?WI?=j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Ff0@yjS@nbPB0)6D`lA;e%61nh`-qhydO!uS7jXGQd%i7opEnOL;| zDn!3EUm(V796;f?fA+RDF<@%qKlo)`0VtL74`!~516_aogYP%QfG#<2kQ!pijthz2 zpaFX3|D$%C7!bL242U?-e@2QZ`q$~lgZbvgfLLyVfT1OC5<8@6lLi=A{stK#zJmWd zlx+(HbgX)l$RGwH|2rV@P3o@xCrxch0$*z1ASpy(n+d4d2XWd~2AYjQm`xZU3af8F p+x$Nxf1895@0bJirXkdpJh+N7@Nb7x007(DEB&^Lm}dWn{T~m64-^0Z diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 41dfb87..ae04661 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index c53aefa..a69d9cb 100755 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ #!/bin/sh # -# Copyright © 2015-2021 the original authors. +# Copyright © 2015-2021 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -32,10 +32,10 @@ # Busybox and similar reduced shells will NOT work, because this script # requires all of these POSIX shell features: # * functions; -# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», -# «${var#prefix}», «${var%suffix}», and «$( cmd )»; -# * compound commands having a testable exit status, especially «case»; -# * various built-in commands including «command», «set», and «ulimit». +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». # # Important for patching: # @@ -205,6 +205,12 @@ set -- \ org.gradle.wrapper.GradleWrapperMain \ "$@" +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + # Use "xargs" to parse quoted args. # # With -n1 it outputs one arg per line, with the quotes and backslashes removed. diff --git a/gradlew.bat b/gradlew.bat index ac1b06f..53a6b23 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -14,7 +14,7 @@ @rem limitations under the License. @rem -@if "%DEBUG%" == "" @echo off +@if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @@ -25,7 +25,7 @@ if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. +if "%DIRNAME%"=="" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @@ -40,7 +40,7 @@ if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute +if %ERRORLEVEL% equ 0 goto execute echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. @@ -75,13 +75,15 @@ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar :end @rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd +if %ERRORLEVEL% equ 0 goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% :mainEnd if "%OS%"=="Windows_NT" endlocal From f6d4e8a4c532905fff698586f8df1caaab8368fd Mon Sep 17 00:00:00 2001 From: Owen Stubbs Date: Sun, 2 Apr 2023 06:20:03 +0100 Subject: [PATCH 11/19] some fixes --- build.gradle | 27 +++++-- gradle.properties | 11 +-- .../java/net/emc/emce/EarthMCEssentials.java | 16 ++-- .../java/net/emc/emce/config/ModConfig.java | 30 +++---- .../emce/events/commands/InfoCommands.java | 21 +++-- .../mixins/ClientPlayNetworkHandlerMixin.java | 2 +- .../mixins/SessionEventListenerMixin.java | 4 + .../net/emc/emce/modules/OverlayRenderer.java | 36 +++++---- .../net/emc/emce/modules/TaskScheduler.java | 80 ++++++++++--------- .../java/net/emc/emce/utils/EarthMCAPI.java | 52 +++++++----- .../java/net/emc/emce/utils/Messaging.java | 4 +- .../java/net/emc/emce/utils/ModUtils.java | 10 +-- .../resources/assets/emce/lang/en_us.json | 6 +- src/main/resources/fabric.mod.json | 6 +- 14 files changed, 175 insertions(+), 130 deletions(-) diff --git a/build.gradle b/build.gradle index ec8c4a8..8881ad2 100644 --- a/build.gradle +++ b/build.gradle @@ -2,6 +2,9 @@ plugins { id 'fabric-loom' version '1.0-SNAPSHOT' } +sourceCompatibility = JavaVersion.VERSION_17 +targetCompatibility = JavaVersion.VERSION_17 + version = "${project.mod_version}-${project.minecraft_version}+" as Object group = project.maven_group @@ -13,7 +16,7 @@ repositories { url = uri("https://maven.pkg.github.com/earthmc-toolkit/earthmc-wrapper") credentials { username = project.findProperty("gpr.user") - password = System.getenv("GITHUB_TOKEN") + password = project.findProperty("GITHUB_TOKEN") } } @@ -32,20 +35,32 @@ dependencies { modImplementation include("net.kyori:adventure-platform-fabric:${project.adventure_fabric_version}") modApi("me.shedaniel.cloth:cloth-config-fabric:${project.cloth_config_version}") { + exclude(group: "com.google.code.gson") exclude(group: "net.fabricmc.fabric-api") } // Libraries to include in remapJar include "me.shedaniel.cloth:cloth-config-fabric:${project.cloth_config_version}" - implementation "io.github.emcw:emc-wrapper:${project.wrapper_version}" + api include("io.github.emcw:emc-wrapper:${project.wrapper_version}") { + exclude(group: "org.jetbrains") + exclude(group: "com.google.code.gson") + } + + include 'com.google.code.gson:gson:2.10.1' + + compileOnly 'org.jetbrains:annotations:24.0.1' + annotationProcessor 'org.jetbrains:annotations:24.0.1' + + compileOnly 'org.projectlombok:lombok:1.18.26' + annotationProcessor 'org.projectlombok:lombok:1.18.26' } processResources { - inputs.property "version", version + inputs.property "version", project.version filesMatching("fabric.mod.json") { - expand "version": version + expand "version": project.version } } @@ -54,9 +69,5 @@ tasks.withType(JavaCompile).configureEach { } java { - toolchain { - languageVersion = JavaLanguageVersion.of(17) - } - withSourcesJar() } \ No newline at end of file diff --git a/gradle.properties b/gradle.properties index e0687b5..b653a8c 100644 --- a/gradle.properties +++ b/gradle.properties @@ -15,9 +15,10 @@ mod_version = 3.6.0 maven_group = net.emc.emce # Library versions -cloth_config_version = 9.0.94 -mod_menu_version = 5.0.2 -adventure_fabric_version = 5.6.1 -wrapper_version=0.8.5 +cloth_config_version=9.0.94 +mod_menu_version=5.0.2 +adventure_fabric_version=5.6.1 +wrapper_version=0.8.8 -gpr.user = "Owen3H" \ No newline at end of file +gpr.user=Owen3H +GITHUB_TOKEN=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 \ No newline at end of file diff --git a/src/main/java/net/emc/emce/EarthMCEssentials.java b/src/main/java/net/emc/emce/EarthMCEssentials.java index e75fa5a..d20c2ab 100644 --- a/src/main/java/net/emc/emce/EarthMCEssentials.java +++ b/src/main/java/net/emc/emce/EarthMCEssentials.java @@ -1,8 +1,8 @@ package net.emc.emce; +import io.github.emcw.core.EMCWrapper; import io.github.emcw.entities.BaseEntity; import io.github.emcw.entities.Player; -import io.github.emcw.entities.Resident; import io.github.emcw.utils.GsonUtil; import me.shedaniel.autoconfig.AutoConfig; import me.shedaniel.autoconfig.serializer.GsonConfigSerializer; @@ -32,7 +32,7 @@ public class EarthMCEssentials implements ModInitializer { private final Logger logger = LogManager.getLogger(EarthMCEssentials.class); - private Resident clientResident = null; + private Player clientPlayer = null; private ModConfig config = null; private boolean shouldRender = false; private boolean debugModeEnabled = false; @@ -47,10 +47,14 @@ public class EarthMCEssentials implements ModInitializer { public int sessionCounter = 0; + public EMCWrapper wrapper; + @Override public void onInitialize() { instance = this; + this.wrapper = new EMCWrapper(); + AutoConfig.register(ModConfig.class, GsonConfigSerializer::new); initConfig(); @@ -75,12 +79,12 @@ public TaskScheduler scheduler() { return scheduler; } - public Resident getClientResident() { - return clientResident; + public Player getClientPlayer() { + return clientPlayer; } - public void setClientResident(Resident res) { - clientResident = res; + public void setClientPlayer(Player res) { + clientPlayer = res; } private void initConfig() { config = AutoConfig.getConfigHolder(ModConfig.class).getConfig(); } diff --git a/src/main/java/net/emc/emce/config/ModConfig.java b/src/main/java/net/emc/emce/config/ModConfig.java index feffa97..172d5c4 100644 --- a/src/main/java/net/emc/emce/config/ModConfig.java +++ b/src/main/java/net/emc/emce/config/ModConfig.java @@ -33,9 +33,9 @@ public class ModConfig implements ConfigData { @TransitiveObject() public final Commands commands = new Commands(); -// @Category("API") -// @TransitiveObject() -// public API api = new API(); + @Category("Intervals") + @TransitiveObject() + public Intervals intervals = new Intervals(); public static class General { @Comment("Toggles the mod on or off.") @@ -117,21 +117,15 @@ public static class Commands { public final Colors allianceInfoTextColour = Colors.GOLD; } -// public static class API { -// @ConfigEntry.Gui.CollapsibleObject -// @Comment("Configure the rate (in seconds) at which different data will be updated.") -// public Intervals intervals = new Intervals(); -// -// public static class Intervals { -// @Comment("Fairly harmless on performance, can be lowered without much overhead.") -// @BoundedDiscrete(min = 10, max = 600) -// public int townless = 60; -// -// @Comment("Small but frequent payload, if you don't rely on it much, turn it up.") -// @BoundedDiscrete(min = 5, max = 60) -// public int nearby = 30; -// } -// } + public static class Intervals { + @Comment("Fairly harmless on performance, can be lowered without much overhead.") + @BoundedDiscrete(min = 10, max = 200) + public int townless = 60; + + @Comment("Small but frequent payload, if you don't rely on it much, turn it up.") + @BoundedDiscrete(min = 5, max = 30) + public int nearby = 10; + } public static ModConfig instance() { return EarthMCEssentials.instance().getConfig(); diff --git a/src/main/java/net/emc/emce/events/commands/InfoCommands.java b/src/main/java/net/emc/emce/events/commands/InfoCommands.java index ac9b0bf..37c5b92 100644 --- a/src/main/java/net/emc/emce/events/commands/InfoCommands.java +++ b/src/main/java/net/emc/emce/events/commands/InfoCommands.java @@ -2,10 +2,7 @@ import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.arguments.StringArgumentType; -import io.github.emcw.entities.Location; -import io.github.emcw.entities.Nation; -import io.github.emcw.entities.Resident; -import io.github.emcw.entities.Town; +import io.github.emcw.entities.*; import net.emc.emce.EarthMCEssentials; import net.emc.emce.utils.EarthMCAPI; import net.emc.emce.utils.Messaging; @@ -36,10 +33,10 @@ public void registerTownInfoCommand(CommandDispatcher return 1; })).executes(c -> { - Resident clientResident = instance.getClientResident(); + Player clientPlayer = instance.getClientPlayer(); - if (residentExists(clientResident)) { - String townName = clientResident.getTown(); + if (residentExists(clientPlayer.getName())) { + String townName = ((Resident) clientPlayer).getTown(); if (townName.equals("") || townName.equals("No Town")) Messaging.sendPrefixed("text_towninfo_not_registered"); @@ -58,10 +55,10 @@ public void registerNationInfoCommand(CommandDispatcher { - Resident clientResident = instance.getClientResident(); + Player clientPlayer = instance.getClientPlayer(); - if (residentExists(clientResident)) { - String nationName = clientResident.getNation(); + if (residentExists(clientPlayer.getName())) { + String nationName = ((Resident) clientPlayer).getNation(); if (nationName.equals("") || nationName.equals("No Nation")) Messaging.sendPrefixed("text_nationinfo_not_registered"); @@ -72,7 +69,9 @@ public void registerNationInfoCommand(CommandDispatcher 1) + instance().scheduler().initMap(); } } diff --git a/src/main/java/net/emc/emce/modules/OverlayRenderer.java b/src/main/java/net/emc/emce/modules/OverlayRenderer.java index bfe9b58..2ff2393 100644 --- a/src/main/java/net/emc/emce/modules/OverlayRenderer.java +++ b/src/main/java/net/emc/emce/modules/OverlayRenderer.java @@ -16,7 +16,7 @@ import java.util.concurrent.CopyOnWriteArrayList; import static net.emc.emce.EarthMCEssentials.instance; -import static net.emc.emce.utils.ModUtils.getTextWidth; +import static net.emc.emce.utils.ModUtils.*; import static net.minecraft.text.Text.translatable; public class OverlayRenderer { @@ -90,8 +90,11 @@ private static void RenderTownless(boolean usingPreset) { for (String townlessName : townless) { if (maxLen > 0 && index >= maxLen) { - MutableText remainingText = translatable("text_townless_remaining", townlessSize - index).formatted(playerTextFormatting); + MutableText remainingText = translatable("text_townless_remaining", townlessSize - index); + + remainingText = remainingText.formatted(playerTextFormatting); renderer.drawWithShadow(matrixStack, remainingText, x, y + index * 10, color); + break; } @@ -113,8 +116,11 @@ private static void RenderTownless(boolean usingPreset) { for (String name : townless) { if (maxLen >= 1) { if (index >= maxLen) { - MutableText remainingText = translatable("text_townless_remaining", townlessSize - index).formatted(playerTextFormatting); + MutableText remainingText = translatable("text_townless_remaining", townlessSize - index); + + remainingText = remainingText.formatted(playerTextFormatting); renderer.drawWithShadow(matrixStack, remainingText, xOffset, playerOffset, color); + break; } @@ -218,17 +224,17 @@ private static void UpdateTownlessState() { // No advanced positioning, use preset states. int townlessLongest, nearbyLongest; - townlessLongest = Math.max(ModUtils.getLongestElement(townless), + townlessLongest = Math.max(getLongestElement(townless), getTextWidth(translatable("text_townless_header", townless.size()))); - nearbyLongest = Math.max(ModUtils.getNearbyLongestElement(instance().getNearbyPlayers()), + nearbyLongest = Math.max(getNearbyLongestElement(instance().getNearbyPlayers()), getTextWidth(translatable("text_nearby_header", nearby().size()))); - int windowHeight = ModUtils.getWindowHeight(); - int windowWidth = ModUtils.getWindowWidth(); + int windowHeight = getWindowHeight(); + int windowWidth = getWindowWidth(); - int heightOffset = windowHeight - ModUtils.getTownlessArrayHeight(townless, config.townless.maxLength) - 22; - int heightHalfOffset = windowHeight / 2 - ModUtils.getTownlessArrayHeight(townless, config.townless.maxLength) / 2; + int heightOffset = windowHeight - getTownlessArrayHeight(townless, config.townless.maxLength) - 22; + int heightHalfOffset = windowHeight / 2 - getTownlessArrayHeight(townless, config.townless.maxLength) / 2; int widthOffset = windowWidth - townlessLongest - 5; @@ -244,7 +250,7 @@ private static void UpdateTownlessState() { case TOP_RIGHT -> { townlessState.setX(widthOffset); assert client.player != null; - townlessState.setY(ModUtils.getStatusEffectOffset(client.player.getStatusEffects())); + townlessState.setY(getStatusEffectOffset(client.player.getStatusEffects())); } case LEFT -> { townlessState.setX(5); @@ -272,14 +278,14 @@ private static void UpdateTownlessState() { private static void UpdateNearbyState() { int nearbyLongest, townlessLongest; - nearbyLongest = Math.max(ModUtils.getNearbyLongestElement(instance().getNearbyPlayers()), + nearbyLongest = Math.max(getNearbyLongestElement(instance().getNearbyPlayers()), getTextWidth(translatable("text_nearby_header", nearby().size()))); - townlessLongest = Math.max(ModUtils.getLongestElement(townless), + townlessLongest = Math.max(getLongestElement(townless), getTextWidth(translatable("text_townless_header", townless.size()))); - int windowHeight = ModUtils.getWindowHeight(); - int windowWidth = ModUtils.getWindowWidth(); + int windowHeight = getWindowHeight(); + int windowWidth = getWindowWidth(); int nearbyArrayHeight = ModUtils.getArrayHeight(nearby()); int windowHeightOffset = windowHeight - nearbyArrayHeight - 10; @@ -302,7 +308,7 @@ private static void UpdateNearbyState() { else nearbyState.setX(windowWidth - nearbyLongest - 5); assert client.player != null; - nearbyState.setY(ModUtils.getStatusEffectOffset(client.player.getStatusEffects())); + nearbyState.setY(getStatusEffectOffset(client.player.getStatusEffects())); } case LEFT -> { if (townlessState.equals(State.LEFT)) { diff --git a/src/main/java/net/emc/emce/modules/TaskScheduler.java b/src/main/java/net/emc/emce/modules/TaskScheduler.java index dc95e0e..e94dfde 100644 --- a/src/main/java/net/emc/emce/modules/TaskScheduler.java +++ b/src/main/java/net/emc/emce/modules/TaskScheduler.java @@ -32,9 +32,9 @@ public void start() { if (config.nearby.enabled) EarthMCAPI.getNearby().thenAccept(instance()::setNearbyPlayers); } - //startTownless(); - //startNearby(); - //startCacheCheck(); + startCacheCheck(); + startTownless(); + startNearby(); } public void stop() { @@ -46,12 +46,20 @@ public void stop() { } public void initMap() { + initMap(false); + } + + public void initMap(Boolean singleplayer) { service = Executors.newScheduledThreadPool(1); service.scheduleAtFixedRate(() -> { if (hasMap) return; - if (playerOnline("aurora")) setHasMap("aurora"); - else if (playerOnline("nova")) setHasMap("nova"); + if (singleplayer || playerOnline("aurora")) { + setHasMap("aurora"); + return; + } + + if (playerOnline("nova")) setHasMap("nova"); else setHasMap(null); }, 15, 10, TimeUnit.SECONDS); // Give enough time for Dynmap & Vercel to update. } @@ -72,34 +80,34 @@ public void setHasMap(String map) { } } -// private void startTownless() { -// townlessRunning = true; -// ModConfig config = ModConfig.instance(); -// -// service.scheduleAtFixedRate(() -> { -// if (townlessRunning && config.townless.enabled && shouldRun()) { -// Messaging.sendDebugMessage("Starting townless task."); -// -// instance().setTownless(getTownless()); -// Messaging.sendDebugMessage("Finished townless task."); -// } -// }, 30, Math.max(config.api.intervals.townless, 30), TimeUnit.SECONDS); -// } -// -// private void startNearby() { -// nearbyRunning = true; -// final ModConfig config = ModConfig.instance(); -// -// service.scheduleAtFixedRate(() -> { -// if (nearbyRunning && config.nearby.enabled && shouldRun()) { -// Messaging.sendDebugMessage("Starting nearby task."); -// EarthMCAPI.getNearby().thenAccept(nearby -> { -// instance().setNearbyPlayers(nearby); -// Messaging.sendDebugMessage("Finished nearby task."); -// }); -// } -// }, 10, Math.max(config.api.intervals.nearby, 10), TimeUnit.SECONDS); -// } + private void startTownless() { + townlessRunning = true; + ModConfig config = ModConfig.instance(); + + service.scheduleAtFixedRate(() -> { + if (townlessRunning && config.townless.enabled && shouldRun()) { + Messaging.sendDebugMessage("Starting townless task."); + + instance().setTownless(getTownless()); + Messaging.sendDebugMessage("Finished townless task."); + } + }, 5, Math.max(config.intervals.townless, 200), TimeUnit.SECONDS); + } + + private void startNearby() { + nearbyRunning = true; + final ModConfig config = ModConfig.instance(); + + service.scheduleAtFixedRate(() -> { + if (nearbyRunning && config.nearby.enabled && shouldRun()) { + Messaging.sendDebugMessage("Starting nearby task."); + EarthMCAPI.getNearby().thenAccept(nearby -> { + instance().setNearbyPlayers(nearby); + Messaging.sendDebugMessage("Finished nearby task."); + }); + } + }, 5, Math.max(config.intervals.nearby, 30), TimeUnit.SECONDS); + } private void startCacheCheck() { cacheCheckRunning = true; @@ -113,8 +121,8 @@ private void startCacheCheck() { }, 0, 5, TimeUnit.MINUTES); } - private boolean shouldRun() { - return ModConfig.instance().general.enableMod && - MinecraftClient.getInstance().isWindowFocused(); + boolean shouldRun() { + return ModConfig.instance().general.enableMod && MinecraftClient.getInstance().isWindowFocused(); } + } diff --git a/src/main/java/net/emc/emce/utils/EarthMCAPI.java b/src/main/java/net/emc/emce/utils/EarthMCAPI.java index 62b6c6b..e877bec 100644 --- a/src/main/java/net/emc/emce/utils/EarthMCAPI.java +++ b/src/main/java/net/emc/emce/utils/EarthMCAPI.java @@ -37,21 +37,34 @@ public class EarthMCAPI { public static APIData apiData = new APIData(); - public static JsonObject player = new JsonObject(); - public static final EMCWrapper wrapper = new EMCWrapper(true, true); - private static EMCMap currentMap() { - return Objects.equals(instance().mapName, "aurora") ? wrapper.getAurora() : wrapper.getNova(); + boolean isNova = Objects.equals(instance().mapName, "nova"); + + if (isNova) { + try { return instance().wrapper.getNova(); } + catch (Exception e) { System.out.println(e.getMessage()); } + } else { + try { return instance().wrapper.getAurora(); } + catch (Exception e) { System.out.println(e.getMessage()); } + } + + return new EMCMap(instance().mapName); } public static @Nullable Town getTown(String name) { try { return currentMap().Towns.single(name); } - catch (MissingEntryException e) { return null; } + catch (MissingEntryException e) { + System.out.println(e.getMessage()); + return null; + } } public static @Nullable Nation getNation(String name) { try { return currentMap().Nations.single(name); } - catch (MissingEntryException e) { return null; } + catch (MissingEntryException e) { + System.out.println(e.getMessage()); + return null; + } } public static Map getTownless() { @@ -60,13 +73,21 @@ public static Map getTownless() { public static Map onlinePlayers() { return currentMap().Players.online(); } + @SuppressWarnings("unused") public static Map getResidents() { return currentMap().Residents.all(); } public static @Nullable Resident getResident(String name) { try { return currentMap().Residents.single(name); } - catch (MissingEntryException e) { return null; } + catch (MissingEntryException e) { + System.out.println(e.getMessage()); + return null; + } + } + + public static @Nullable Player getPlayer(String name) { + return currentMap().Players.all().getOrDefault(name, null); } @Contract(" -> new") @@ -101,7 +122,8 @@ public static Map getResidents() { }); } - public static CompletableFuture getAlliances() { + @Contract(" -> new") + public static @NotNull CompletableFuture getAlliances() { return CompletableFuture.supplyAsync(() -> { try { return (JsonArray) JsonParser.parseString(getURL(getRoute(APIRoute.ALLIANCES))); @@ -112,7 +134,8 @@ public static CompletableFuture getAlliances() { }); } - public static CompletableFuture fetchAPI() { + @Contract(" -> new") + public static @NotNull CompletableFuture fetchAPI() { return CompletableFuture.supplyAsync(() -> { try { return new APIData((JsonObject) JsonParser.parseString( @@ -127,17 +150,10 @@ public static CompletableFuture fetchAPI() { public static void fetchEndpoints() { Messaging.sendDebugMessage("Fetching endpoint URLs"); - - fetchAPI().thenAccept(data -> { - apiData = data; - - // Out of queue, begin map check. - if (instance().sessionCounter > 1) - instance().scheduler().initMap(); - }); + fetchAPI().thenAccept(data -> apiData = data); } - public static String getRoute(APIRoute routeType) { + public static @NotNull String getRoute(@NotNull APIRoute routeType) { String route; switch(routeType) { diff --git a/src/main/java/net/emc/emce/utils/Messaging.java b/src/main/java/net/emc/emce/utils/Messaging.java index f7db001..481bbe6 100644 --- a/src/main/java/net/emc/emce/utils/Messaging.java +++ b/src/main/java/net/emc/emce/utils/Messaging.java @@ -4,7 +4,7 @@ import net.kyori.adventure.text.format.NamedTextColor; import net.minecraft.client.network.ClientPlayerEntity; -import java.util.Collections; +import java.util.ArrayList; import java.util.List; import static net.emc.emce.EarthMCEssentials.instance; @@ -16,7 +16,7 @@ public class Messaging { //#region Helper Methods public static Component create(String key, NamedTextColor keyColour, Object... args) { - List argList = Collections.emptyList(); + List argList = new ArrayList<>(); for (Object obj : args) argList.add(Component.text(obj.toString())); return translatable().key(key).color(keyColour).args(argList).build(); diff --git a/src/main/java/net/emc/emce/utils/ModUtils.java b/src/main/java/net/emc/emce/utils/ModUtils.java index 5ba51e1..61403d6 100644 --- a/src/main/java/net/emc/emce/utils/ModUtils.java +++ b/src/main/java/net/emc/emce/utils/ModUtils.java @@ -93,7 +93,7 @@ public static int getLongestElement(@NotNull Collection collection) { return longestElement; } - public static int getArrayHeight(Map map) { + public static int getArrayHeight(@NotNull Map map) { int length = map.size(); if (length < 1) return 0; @@ -107,7 +107,7 @@ public static int getArrayHeight(Map map) { return totalLength; } - public static int getTownlessArrayHeight(List townless, int maxLength) { + public static int getTownlessArrayHeight(@NotNull List townless, int maxLength) { int length = townless.size(); if (length < 1) return 0; @@ -116,7 +116,7 @@ public static int getTownlessArrayHeight(List townless, int maxLength) { String name = townless.get(i); if (i >= maxLength && maxLength != 0) { - String maxLengthString = "And " + name + " more..."; + String maxLengthString = "And " + (length-i) + " more..."; return totalLength + getStringHeight(maxLengthString) - 10; } else totalLength += getStringHeight(name); @@ -131,14 +131,14 @@ public static int getNearbyLongestElement(@NotNull Map nearby) { int longestElement = 0; for (Player curPlayer : nearby.values()) { - Resident clientRes = instance().getClientResident(); + Player clientPlayer = instance().getClientPlayer(); String name = curPlayer.getName(); Integer x = curPlayer.getLocation().getX(); Integer z = curPlayer.getLocation().getZ(); if (z == null || x == null || name == null) continue; - if (clientRes != null && name.equals(clientRes.getName())) continue; + if (clientPlayer != null && name.equals(clientPlayer.getName())) continue; ClientPlayerEntity player = Objects.requireNonNull(getInstance().player); int distance = Math.abs(x - player.getBlockX()) + diff --git a/src/main/resources/assets/emce/lang/en_us.json b/src/main/resources/assets/emce/lang/en_us.json index d3345d0..8375196 100644 --- a/src/main/resources/assets/emce/lang/en_us.json +++ b/src/main/resources/assets/emce/lang/en_us.json @@ -88,7 +88,7 @@ "text.autoconfig.emc-essentials.option.commands.nationInfoTextColour": "Nation Text Colour", "text.autoconfig.emc-essentials.option.commands.allianceInfoTextColour": "Alliance Text Colour", - "text.autoconfig.emc-essentials.category.API": "API", - "text.autoconfig.emc-essentials.option.api.intervals": "Intervals", - "text.autoconfig.emc-essentials.option.api.intervals.townless": "Townless" + "text.autoconfig.emc-essentials.category.Intervals": "Data Scheduling", + "text.autoconfig.emc-essentials.option.intervals.townless": "Townless Interval (sec)", + "text.autoconfig.emc-essentials.option.intervals.nearby": "Nearby Interval (sec)" } \ No newline at end of file diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json index 9da4dd8..51f0a83 100644 --- a/src/main/resources/fabric.mod.json +++ b/src/main/resources/fabric.mod.json @@ -9,10 +9,12 @@ ], "contact": { "homepage": "https://github.com/EarthMC-Toolkit/EarthMCEssentials", - "issues": "https://github.com/EarthMC-Toolkit/EarthMCEssentials/issues" + "issues": "https://github.com/EarthMC-Toolkit/EarthMCEssentials/issues", + "discord": "https://discord.gg/AVtgkcRgFs" }, + "license": "CC BY-NC 4.0", "icon": "assets/emce/icon.png", - "environment": "*", + "environment": "client", "entrypoints": { "main": [ "net.emc.emce.EarthMCEssentials" From b385ac2f79ce5b96b362ca5d5d69bc3902092a72 Mon Sep 17 00:00:00 2001 From: Owen Stubbs Date: Sun, 2 Apr 2023 20:52:17 +0100 Subject: [PATCH 12/19] use local props to store github token --- .gitignore | 4 +++- build.gradle | 7 +++++-- gradle.properties | 5 +---- 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/.gitignore b/.gitignore index 6639326..6175f78 100644 --- a/.gitignore +++ b/.gitignore @@ -19,4 +19,6 @@ out/ run/ # Extra -/remappedSrc \ No newline at end of file +/remappedSrc + +local.properties \ No newline at end of file diff --git a/build.gradle b/build.gradle index 8881ad2..271c43b 100644 --- a/build.gradle +++ b/build.gradle @@ -8,6 +8,9 @@ targetCompatibility = JavaVersion.VERSION_17 version = "${project.mod_version}-${project.minecraft_version}+" as Object group = project.maven_group +def localProps = new Properties() +localProps.load(new FileInputStream(rootProject.file("local.properties"))) + repositories { mavenCentral() @@ -15,8 +18,8 @@ repositories { name = "GitHubPackages" url = uri("https://maven.pkg.github.com/earthmc-toolkit/earthmc-wrapper") credentials { - username = project.findProperty("gpr.user") - password = project.findProperty("GITHUB_TOKEN") + username = localProps.getProperty("USERNAME") + password = localProps.getProperty("GITHUB_TOKEN") } } diff --git a/gradle.properties b/gradle.properties index b653a8c..db04825 100644 --- a/gradle.properties +++ b/gradle.properties @@ -18,7 +18,4 @@ maven_group = net.emc.emce cloth_config_version=9.0.94 mod_menu_version=5.0.2 adventure_fabric_version=5.6.1 -wrapper_version=0.8.8 - -gpr.user=Owen3H -GITHUB_TOKEN=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 \ No newline at end of file +wrapper_version=0.8.8 \ No newline at end of file From 3f44e704341309a90942eed2ef9fb4cbf65a0539 Mon Sep 17 00:00:00 2001 From: Owen Stubbs Date: Mon, 3 Apr 2023 04:18:24 +0100 Subject: [PATCH 13/19] working --- build.gradle | 15 +++++++++++---- gradle.properties | 2 +- .../java/net/emc/emce/modules/TaskScheduler.java | 12 ++---------- src/main/java/net/emc/emce/utils/EarthMCAPI.java | 15 +++------------ 4 files changed, 17 insertions(+), 27 deletions(-) diff --git a/build.gradle b/build.gradle index 271c43b..bef828a 100644 --- a/build.gradle +++ b/build.gradle @@ -31,11 +31,8 @@ dependencies { minecraft "com.mojang:minecraft:${project.minecraft_version}" mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2" - modImplementation "net.fabricmc:fabric-loader:${project.loader_version}" - modImplementation "com.terraformersmc:modmenu:${project.mod_menu_version}" modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}" - - modImplementation include("net.kyori:adventure-platform-fabric:${project.adventure_fabric_version}") + modImplementation "net.fabricmc:fabric-loader:${project.loader_version}" modApi("me.shedaniel.cloth:cloth-config-fabric:${project.cloth_config_version}") { exclude(group: "com.google.code.gson") @@ -45,11 +42,21 @@ dependencies { // Libraries to include in remapJar include "me.shedaniel.cloth:cloth-config-fabric:${project.cloth_config_version}" + modImplementation("com.terraformersmc:modmenu:${project.mod_menu_version}") { + exclude(group: "net.fabricmc", module: "fabric-loader") + } + + modImplementation include("net.kyori:adventure-platform-fabric:${project.adventure_fabric_version}") { + exclude(group: "net.fabricmc", module: "fabric-loader") + } + api include("io.github.emcw:emc-wrapper:${project.wrapper_version}") { exclude(group: "org.jetbrains") exclude(group: "com.google.code.gson") + exclude(group: "org.apache.commons", module: "commons-lang3") } + include 'org.apache.commons:commons-lang3:3.12.0' include 'com.google.code.gson:gson:2.10.1' compileOnly 'org.jetbrains:annotations:24.0.1' diff --git a/gradle.properties b/gradle.properties index db04825..3e42515 100644 --- a/gradle.properties +++ b/gradle.properties @@ -18,4 +18,4 @@ maven_group = net.emc.emce cloth_config_version=9.0.94 mod_menu_version=5.0.2 adventure_fabric_version=5.6.1 -wrapper_version=0.8.8 \ No newline at end of file +wrapper_version=0.9.0 \ No newline at end of file diff --git a/src/main/java/net/emc/emce/modules/TaskScheduler.java b/src/main/java/net/emc/emce/modules/TaskScheduler.java index e94dfde..4662bdb 100644 --- a/src/main/java/net/emc/emce/modules/TaskScheduler.java +++ b/src/main/java/net/emc/emce/modules/TaskScheduler.java @@ -46,20 +46,12 @@ public void stop() { } public void initMap() { - initMap(false); - } - - public void initMap(Boolean singleplayer) { service = Executors.newScheduledThreadPool(1); service.scheduleAtFixedRate(() -> { if (hasMap) return; - if (singleplayer || playerOnline("aurora")) { - setHasMap("aurora"); - return; - } - - if (playerOnline("nova")) setHasMap("nova"); + if (playerOnline("aurora")) setHasMap("aurora"); + else if (playerOnline("nova")) setHasMap("nova"); else setHasMap(null); }, 15, 10, TimeUnit.SECONDS); // Give enough time for Dynmap & Vercel to update. } diff --git a/src/main/java/net/emc/emce/utils/EarthMCAPI.java b/src/main/java/net/emc/emce/utils/EarthMCAPI.java index e877bec..56830ed 100644 --- a/src/main/java/net/emc/emce/utils/EarthMCAPI.java +++ b/src/main/java/net/emc/emce/utils/EarthMCAPI.java @@ -4,7 +4,6 @@ import com.google.gson.JsonObject; import com.google.gson.JsonParser; import io.github.emcw.core.EMCMap; -import io.github.emcw.core.EMCWrapper; import io.github.emcw.entities.*; import io.github.emcw.exceptions.MissingEntryException; import net.emc.emce.config.ModConfig; @@ -38,17 +37,9 @@ public class EarthMCAPI { public static APIData apiData = new APIData(); private static EMCMap currentMap() { - boolean isNova = Objects.equals(instance().mapName, "nova"); - - if (isNova) { - try { return instance().wrapper.getNova(); } - catch (Exception e) { System.out.println(e.getMessage()); } - } else { - try { return instance().wrapper.getAurora(); } - catch (Exception e) { System.out.println(e.getMessage()); } - } - - return new EMCMap(instance().mapName); + return Objects.equals(instance().mapName, "nova") + ? instance().wrapper.getNova() + : instance().wrapper.getAurora(); } public static @Nullable Town getTown(String name) { From 37fa756e281ffd86921610b891ca9e69af188212 Mon Sep 17 00:00:00 2001 From: Owen Stubbs Date: Mon, 3 Apr 2023 17:21:38 +0100 Subject: [PATCH 14/19] stuff --- .../java/net/emc/emce/config/ModConfig.java | 16 +++--- .../mixins/ClientPlayNetworkHandlerMixin.java | 13 ----- .../emc/emce/mixins/MinecraftClientMixin.java | 27 ++++++++++ .../mixins/SessionEventListenerMixin.java | 4 +- .../emce/objects/exception/APIException.java | 16 ------ .../java/net/emc/emce/utils/EarthMCAPI.java | 51 +++++-------------- src/main/resources/emce.mixins.json | 1 + 7 files changed, 50 insertions(+), 78 deletions(-) create mode 100644 src/main/java/net/emc/emce/mixins/MinecraftClientMixin.java delete mode 100644 src/main/java/net/emc/emce/objects/exception/APIException.java diff --git a/src/main/java/net/emc/emce/config/ModConfig.java b/src/main/java/net/emc/emce/config/ModConfig.java index 172d5c4..83fcf02 100644 --- a/src/main/java/net/emc/emce/config/ModConfig.java +++ b/src/main/java/net/emc/emce/config/ModConfig.java @@ -46,13 +46,13 @@ public static class Townless { @Comment("Toggles townless players on or off.") public final boolean enabled = true; @Comment("The maximum length the townless list can be. < 1 for no limit.") - public final int maxLength = 0; // < 1 = No limit + public final int maxLength = 10; // < 1 = No limit @Comment("Toggles the use of preset positions, uses sliders if off.") public final boolean presetPositions = true; @EnumHandler(option = BUTTON) @Comment("The position of the Townless info.") - public final State positionState = State.TOP_LEFT; + public final State positionState = State.RIGHT; @Comment("Note: Only used if Use Preset Positions is off.") public final int xPos = 1; @@ -61,10 +61,10 @@ public static class Townless { @EnumHandler(option = BUTTON) @Comment("The colour of the 'Townless Players' text.") - public final Colors headingTextColour = Colors.BLUE; + public final Colors headingTextColour = Colors.DARK_PURPLE; @EnumHandler(option = BUTTON) @Comment("The colour of the townless player names.") - public final Colors playerTextColour = Colors.BLUE; + public final Colors playerTextColour = Colors.DARK_PURPLE; } public static class Nearby { @@ -92,9 +92,9 @@ public static class Nearby { // Independent scaling - either axis can be the same or different. @Comment("The amount of blocks to check on the X axis.") - @BoundedDiscrete(min = 50, max = 10000) + @BoundedDiscrete(min = 32, max = 10240) public final int xBlocks = 500; - @BoundedDiscrete(min = 50, max = 10000) + @BoundedDiscrete(min = 32, max = 10240) @Comment("The amount of blocks to check on the Z axis.") public final int zBlocks = 500; } @@ -123,8 +123,8 @@ public static class Intervals { public int townless = 60; @Comment("Small but frequent payload, if you don't rely on it much, turn it up.") - @BoundedDiscrete(min = 5, max = 30) - public int nearby = 10; + @BoundedDiscrete(min = 3, max = 15) + public int nearby = 5; } public static ModConfig instance() { diff --git a/src/main/java/net/emc/emce/mixins/ClientPlayNetworkHandlerMixin.java b/src/main/java/net/emc/emce/mixins/ClientPlayNetworkHandlerMixin.java index 740c47a..9c523ea 100644 --- a/src/main/java/net/emc/emce/mixins/ClientPlayNetworkHandlerMixin.java +++ b/src/main/java/net/emc/emce/mixins/ClientPlayNetworkHandlerMixin.java @@ -1,15 +1,8 @@ package net.emc.emce.mixins; -import com.mojang.authlib.GameProfile; import net.emc.emce.modules.OverlayRenderer; -import net.emc.emce.utils.EarthMCAPI; import net.emc.emce.utils.ModUtils; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.network.ClientPlayNetworkHandler; -import net.minecraft.client.network.ServerInfo; -import net.minecraft.client.util.telemetry.WorldSession; -import net.minecraft.network.ClientConnection; import net.minecraft.network.packet.s2c.play.DisconnectS2CPacket; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; @@ -20,12 +13,6 @@ @Mixin(ClientPlayNetworkHandler.class) public abstract class ClientPlayNetworkHandlerMixin { - @Inject(at = @At("TAIL"), method="") - private void onInit(MinecraftClient client, Screen screen, ClientConnection connection, - ServerInfo serverInfo, GameProfile profile, WorldSession worldSession, CallbackInfo ci) { - instance().setClientPlayer(EarthMCAPI.getPlayer(profile.getName())); - } - @Inject(at = @At("TAIL"), method="onDisconnect") private void onDisconnect(DisconnectS2CPacket packet, CallbackInfo ci) { System.out.println("EMCE > Disconnected."); diff --git a/src/main/java/net/emc/emce/mixins/MinecraftClientMixin.java b/src/main/java/net/emc/emce/mixins/MinecraftClientMixin.java new file mode 100644 index 0000000..ebdcd04 --- /dev/null +++ b/src/main/java/net/emc/emce/mixins/MinecraftClientMixin.java @@ -0,0 +1,27 @@ +package net.emc.emce.mixins; + +import io.github.emcw.entities.Player; +import net.emc.emce.utils.EarthMCAPI; +import net.minecraft.client.MinecraftClient; +import net.minecraft.client.RunArgs; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import static net.emc.emce.EarthMCEssentials.instance; + +@Mixin(MinecraftClient.class) +public class MinecraftClientMixin { + @Inject(at = @At("TAIL"), method="") + private void onInit(RunArgs args, CallbackInfo ci) { + String clientName = args.network.session.getUsername(); + Player clientPlayer = EarthMCAPI.getPlayer(clientName); + + if (clientPlayer == null) System.out.println("Could not find player by client name: " + clientName); + else { + instance().setClientPlayer(clientPlayer); + System.out.println(clientPlayer.asString()); + } + } +} diff --git a/src/main/java/net/emc/emce/mixins/SessionEventListenerMixin.java b/src/main/java/net/emc/emce/mixins/SessionEventListenerMixin.java index c0947e1..7eed9e3 100644 --- a/src/main/java/net/emc/emce/mixins/SessionEventListenerMixin.java +++ b/src/main/java/net/emc/emce/mixins/SessionEventListenerMixin.java @@ -21,7 +21,7 @@ public abstract class SessionEventListenerMixin { @Inject(at = @At("TAIL"), method="onStartGameSession") public void onStartGameSession(CallbackInfo ci) { - System.out.println("EMCE > Joined game."); + System.out.println("EMCE > New game session detected."); ModUtils.updateServerName(); OverlayRenderer.Init(); @@ -32,7 +32,7 @@ public void onStartGameSession(CallbackInfo ci) { instance().setShouldRender(instance().getConfig().general.enableMod); if (isConnectedToEMC()) { updateSessionCounter('+'); - fetchEndpoints(); + //fetchEndpoints(); // Out of queue, begin map check. if (instance().sessionCounter > 1) diff --git a/src/main/java/net/emc/emce/objects/exception/APIException.java b/src/main/java/net/emc/emce/objects/exception/APIException.java deleted file mode 100644 index e82a704..0000000 --- a/src/main/java/net/emc/emce/objects/exception/APIException.java +++ /dev/null @@ -1,16 +0,0 @@ -package net.emc.emce.objects.exception; - -import java.io.Serial; - -public class APIException extends Exception { - @Serial - private static final long serialVersionUID = -3129573277546383741L; - - public APIException() { - super("An unknown API exception has occurred."); - } - - public APIException(String message) { - super(message); - } -} diff --git a/src/main/java/net/emc/emce/utils/EarthMCAPI.java b/src/main/java/net/emc/emce/utils/EarthMCAPI.java index 56830ed..3e6ad3e 100644 --- a/src/main/java/net/emc/emce/utils/EarthMCAPI.java +++ b/src/main/java/net/emc/emce/utils/EarthMCAPI.java @@ -1,29 +1,20 @@ package net.emc.emce.utils; import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; import io.github.emcw.core.EMCMap; import io.github.emcw.entities.*; +import io.github.emcw.exceptions.APIException; import io.github.emcw.exceptions.MissingEntryException; +import io.github.emcw.utils.Request; import net.emc.emce.config.ModConfig; import net.emc.emce.objects.API.APIData; import net.emc.emce.objects.API.APIRoute; -import net.emc.emce.objects.exception.APIException; import net.minecraft.client.MinecraftClient; import net.minecraft.client.network.ClientPlayerEntity; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.net.http.HttpTimeoutException; -import java.nio.charset.StandardCharsets; -import java.time.Duration; -import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.CompletableFuture; @@ -31,10 +22,10 @@ import static net.emc.emce.EarthMCEssentials.instance; public class EarthMCAPI { - private static final HttpClient client = HttpClient.newHttpClient(); private static final ModConfig config = ModConfig.instance(); - public static APIData apiData = new APIData(); + private static final String endpoints = + "https://raw.githubusercontent.com/EarthMC-Toolkit/EarthMCEssentials/main/src/main/resources/api.json"; private static EMCMap currentMap() { return Objects.equals(instance().mapName, "nova") @@ -77,8 +68,12 @@ public static Map getResidents() { } } + public static Map allPlayers() { + return currentMap().Players.all(); + } + public static @Nullable Player getPlayer(String name) { - return currentMap().Players.all().getOrDefault(name, null); + return allPlayers().getOrDefault(name, null); } @Contract(" -> new") @@ -102,7 +97,7 @@ public static Map getResidents() { Integer x = (int) player.getX(), y = (int) player.getY(); - Map nearby = curMap.Players.getNearby(curMap.Players.all(), x, y, xBlocks, zBlocks); + Map nearby = curMap.Players.getNearby(allPlayers(), x, y, xBlocks, zBlocks); nearby.remove(clientName()); return nearby; @@ -117,7 +112,7 @@ public static Map getResidents() { public static @NotNull CompletableFuture getAlliances() { return CompletableFuture.supplyAsync(() -> { try { - return (JsonArray) JsonParser.parseString(getURL(getRoute(APIRoute.ALLIANCES))); + return Request.send(getRoute(APIRoute.ALLIANCES)); } catch (APIException e) { Messaging.sendDebugMessage(e.getMessage(), e); return new JsonArray(); @@ -129,9 +124,7 @@ public static Map getResidents() { public static @NotNull CompletableFuture fetchAPI() { return CompletableFuture.supplyAsync(() -> { try { - return new APIData((JsonObject) JsonParser.parseString( - getURL("https://raw.githubusercontent.com/EarthMC-Toolkit/EarthMCEssentials" + - "/main/src/main/resources/api.json"))); + return new APIData(Request.send(endpoints)); } catch (APIException e) { Messaging.sendDebugMessage(e.getMessage(), e); return new APIData(); @@ -169,24 +162,4 @@ public static boolean playerOnline(String map) { instance().mapName = map; // getOnlinePlayer uses mapName. return onlinePlayers().containsKey(clientName()); } - - private static String getURL(String urlString) throws APIException { - try { - HttpRequest.Builder builder = HttpRequest.newBuilder() - .uri(URI.create(urlString)).header("Accept", "application/json"); - - Duration timeout = Duration.ofSeconds(5); - final HttpRequest req = builder.timeout(timeout).GET().build(); - final HttpResponse response; - - try { response = client.send(req, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)); } - catch (HttpTimeoutException e) { throw new APIException("Request timed out after 5 seconds.\nEndpoint: " + urlString); } - - List codes = List.of(new Integer[]{ 200, 203, 304 }); - if (!codes.contains(response.statusCode())) - throw new APIException("API Error! Response code: " + response.statusCode() + "\nEndpoint: " + urlString); - - return response.body(); - } catch (Exception e) { throw new APIException(e.getMessage()); } - } } \ No newline at end of file diff --git a/src/main/resources/emce.mixins.json b/src/main/resources/emce.mixins.json index 9966012..0697193 100644 --- a/src/main/resources/emce.mixins.json +++ b/src/main/resources/emce.mixins.json @@ -4,6 +4,7 @@ "compatibilityLevel": "JAVA_17", "client": [ "ClientPlayNetworkHandlerMixin", + "MinecraftClientMixin", "SessionEventListenerMixin" ], "injectors": { From a58735cfd569279c8465acad19fb6426b2ae9a74 Mon Sep 17 00:00:00 2001 From: Owen Stubbs Date: Tue, 4 Apr 2023 05:03:25 +0100 Subject: [PATCH 15/19] remove debug command and other qol --- .../java/net/emc/emce/EarthMCEssentials.java | 31 +++++----- .../java/net/emc/emce/config/ModConfig.java | 59 ++++++++++--------- .../emce/events/commands/AllianceCommand.java | 11 +++- .../emce/events/commands/InfoCommands.java | 4 +- .../emce/events/commands/NearbyCommand.java | 2 +- .../events/commands/ToggleDebugCommand.java | 27 --------- .../emce/events/commands/TownlessCommand.java | 2 +- .../emc/emce/events/screen/ScreenInit.java | 5 +- .../mixins/SessionEventListenerMixin.java | 22 ++++--- .../net/emc/emce/modules/EventRegistry.java | 2 - .../net/emc/emce/modules/OverlayRenderer.java | 3 +- .../net/emc/emce/modules/TaskScheduler.java | 26 ++++---- .../java/net/emc/emce/objects/Colors.java | 1 + .../java/net/emc/emce/utils/EarthMCAPI.java | 15 +++-- .../java/net/emc/emce/utils/ModUtils.java | 9 ++- .../resources/assets/emce/lang/en_us.json | 1 + 16 files changed, 103 insertions(+), 117 deletions(-) delete mode 100644 src/main/java/net/emc/emce/events/commands/ToggleDebugCommand.java diff --git a/src/main/java/net/emc/emce/EarthMCEssentials.java b/src/main/java/net/emc/emce/EarthMCEssentials.java index d20c2ab..e2fca82 100644 --- a/src/main/java/net/emc/emce/EarthMCEssentials.java +++ b/src/main/java/net/emc/emce/EarthMCEssentials.java @@ -10,6 +10,7 @@ import net.emc.emce.modules.EventRegistry; import net.emc.emce.modules.OverlayRenderer; import net.emc.emce.modules.TaskScheduler; +import net.emc.emce.utils.Messaging; import net.fabricmc.api.ModInitializer; import net.fabricmc.fabric.api.client.command.v2.ClientCommandRegistrationCallback; import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper; @@ -29,31 +30,29 @@ public class EarthMCEssentials implements ModInitializer { private static EarthMCEssentials instance; + public EMCWrapper wrapper; private final Logger logger = LogManager.getLogger(EarthMCEssentials.class); private Player clientPlayer = null; - private ModConfig config = null; private boolean shouldRender = false; - private boolean debugModeEnabled = false; private List townlessNames = new CopyOnWriteArrayList<>(); private Map nearbyPlayers = new ConcurrentHashMap<>(); - public static KeyBinding configKeybinding; - private final TaskScheduler scheduler = new TaskScheduler(); - public String mapName = "aurora"; + public String mapName = "aurora"; public int sessionCounter = 0; - public EMCWrapper wrapper; + public static KeyBinding configKeybinding; + private ModConfig config = null; + private boolean debugModeEnabled = false; @Override public void onInitialize() { instance = this; - - this.wrapper = new EMCWrapper(); + wrapper = new EMCWrapper(); AutoConfig.register(ModConfig.class, GsonConfigSerializer::new); initConfig(); @@ -87,11 +86,8 @@ public void setClientPlayer(Player res) { clientPlayer = res; } - private void initConfig() { config = AutoConfig.getConfigHolder(ModConfig.class).getConfig(); } - public ModConfig getConfig() { - if (config == null) initConfig(); - return config; - } + public ModConfig config() { return config; } + public void initConfig() { config = AutoConfig.getConfigHolder(ModConfig.class).getConfig(); } public boolean shouldRender() { MinecraftClient client = MinecraftClient.getInstance(); @@ -101,12 +97,15 @@ public boolean shouldRender() { return shouldRender; } - public void setDebugEnabled(boolean debugModeEnabled) { - this.debugModeEnabled = debugModeEnabled; + public void setDebugEnabled(boolean enabled) { + this.debugModeEnabled = enabled; + + if (enabled) Messaging.sendPrefixed("msg_debug_enabled"); + else Messaging.sendPrefixed("msg_debug_enabled"); } public boolean debugEnabled() { - return debugModeEnabled; + return this.debugModeEnabled; } public List getTownless() { diff --git a/src/main/java/net/emc/emce/config/ModConfig.java b/src/main/java/net/emc/emce/config/ModConfig.java index 83fcf02..b3a3425 100644 --- a/src/main/java/net/emc/emce/config/ModConfig.java +++ b/src/main/java/net/emc/emce/config/ModConfig.java @@ -19,19 +19,19 @@ public class ModConfig implements ConfigData { @Category("General") @TransitiveObject() - public final General general = new General(); + public General general = new General(); @Category("Townless") @TransitiveObject() - public final Townless townless = new Townless(); + public Townless townless = new Townless(); @Category("Nearby") @TransitiveObject() - public final Nearby nearby = new Nearby(); + public Nearby nearby = new Nearby(); @Category("Commands") @TransitiveObject() - public final Commands commands = new Commands(); + public Commands commands = new Commands(); @Category("Intervals") @TransitiveObject() @@ -39,82 +39,85 @@ public class ModConfig implements ConfigData { public static class General { @Comment("Toggles the mod on or off.") - public final boolean enableMod = true; + public boolean enableMod = true; + + @Comment("Toggles logging debug messages in chat.") + public boolean debugLog = false; } public static class Townless { @Comment("Toggles townless players on or off.") - public final boolean enabled = true; + public boolean enabled = true; @Comment("The maximum length the townless list can be. < 1 for no limit.") - public final int maxLength = 10; // < 1 = No limit + public int maxLength = 10; // < 1 = No limit @Comment("Toggles the use of preset positions, uses sliders if off.") - public final boolean presetPositions = true; + public boolean presetPositions = true; @EnumHandler(option = BUTTON) @Comment("The position of the Townless info.") - public final State positionState = State.RIGHT; + public State positionState = State.RIGHT; @Comment("Note: Only used if Use Preset Positions is off.") - public final int xPos = 1; + public int xPos = 1; @Comment("Note: Only used if Use Preset Positions is off.") - public final int yPos = 16; + public int yPos = 16; @EnumHandler(option = BUTTON) @Comment("The colour of the 'Townless Players' text.") - public final Colors headingTextColour = Colors.DARK_PURPLE; + public Colors headingTextColour = Colors.DARK_PURPLE; @EnumHandler(option = BUTTON) @Comment("The colour of the townless player names.") - public final Colors playerTextColour = Colors.DARK_PURPLE; + public Colors playerTextColour = Colors.DARK_PURPLE; } public static class Nearby { @Comment("Toggle nearby overlay on or off.") - public final boolean enabled = true; + public boolean enabled = true; @Comment("Toggle if players' ranks should show before their name.") - public final boolean showRank = false; + public boolean showRank = false; @Comment("Toggle between a preset or custom position.") - public final boolean presetPositions = true; + public boolean presetPositions = true; @EnumHandler(option = BUTTON) - public final State positionState = State.TOP_RIGHT; + public State positionState = State.TOP_RIGHT; @Comment("The horizontal position on the HUD.") - public final int xPos = 100; + public int xPos = 100; @Comment("The vertical position on the HUD.") - public final int yPos = 16; + public int yPos = 16; @EnumHandler(option = BUTTON) @Comment("The colour of the 'Nearby Players' text.") - public final Colors headingTextColour = Colors.GOLD; + public Colors headingTextColour = Colors.GOLD; @EnumHandler(option = BUTTON) @Comment("The colour of nearby players' names.") - public final Colors playerTextColour = Colors.GOLD; + public Colors playerTextColour = Colors.GOLD; // Independent scaling - either axis can be the same or different. @Comment("The amount of blocks to check on the X axis.") @BoundedDiscrete(min = 32, max = 10240) - public final int xBlocks = 500; + public int xBlocks = 500; @BoundedDiscrete(min = 32, max = 10240) @Comment("The amount of blocks to check on the Z axis.") - public final int zBlocks = 500; + public int zBlocks = 500; } public static class Commands { @EnumHandler(option = BUTTON) @Comment("The colour of the townless players text.") - public final Colors townlessTextColour = Colors.LIGHT_PURPLE; + public Colors townlessTextColour = Colors.LIGHT_PURPLE; @EnumHandler(option = BUTTON) @Comment("The colour of the town info text.") - public final Colors townInfoTextColour = Colors.GREEN; + public Colors townInfoTextColour = Colors.GREEN; @EnumHandler(option = BUTTON) @Comment("The colour of the nation info text.") - public final Colors nationInfoTextColour = Colors.AQUA; + public Colors nationInfoTextColour = Colors.AQUA; @EnumHandler(option = BUTTON) @Comment("The colour of the alliance info text.") - public final Colors allianceInfoTextColour = Colors.GOLD; + public Colors allianceInfoTextColour = Colors.GOLD; } public static class Intervals { @@ -128,6 +131,6 @@ public static class Intervals { } public static ModConfig instance() { - return EarthMCEssentials.instance().getConfig(); + return EarthMCEssentials.instance().config(); } } \ No newline at end of file diff --git a/src/main/java/net/emc/emce/events/commands/AllianceCommand.java b/src/main/java/net/emc/emce/events/commands/AllianceCommand.java index b6de90b..59ac3a9 100644 --- a/src/main/java/net/emc/emce/events/commands/AllianceCommand.java +++ b/src/main/java/net/emc/emce/events/commands/AllianceCommand.java @@ -12,6 +12,9 @@ import net.kyori.adventure.audience.Audience; import net.kyori.adventure.platform.fabric.FabricClientAudiences; import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.ComponentBuilder; +import net.kyori.adventure.text.TextComponent; +import net.kyori.adventure.text.TranslatableComponent; import net.kyori.adventure.text.event.ClickEvent; import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.format.Style; @@ -26,7 +29,7 @@ public void register(CommandDispatcher dispatcher) { dispatcher.register(ClientCommandManager.literal("alliance").then( ClientCommandManager.argument("allianceName", StringArgumentType.string()).executes(c -> { String allianceName = StringArgumentType.getString(c, "allianceName"); - NamedTextColor colour = instance.getConfig().commands.allianceInfoTextColour.named(); + NamedTextColor colour = instance.config().commands.allianceInfoTextColour.named(); // Implement data cache AllianceDataCache.INSTANCE.getCache().thenAccept(alliances -> { @@ -67,11 +70,13 @@ private Component createText(String langKey, JsonObject obj, String key, TextCol } private Component createText(String langKey, JsonObject obj, String key, TextColor color, boolean isLink) { + if (!isLink) return createText(langKey, obj, key, color); + String text = formatElement(obj.get(key)); Style linkStyle = Style.style(ClickEvent.openUrl(text), NamedTextColor.AQUA, TextDecoration.UNDERLINED); - return Component.translatable().key(langKey).color(color) - .append(Component.text(text).style(linkStyle)).build(); + Component comp = Component.translatable(langKey).color(color); + return comp.append(Component.text(text).style(linkStyle)); } private static String formatElement(JsonElement element) { diff --git a/src/main/java/net/emc/emce/events/commands/InfoCommands.java b/src/main/java/net/emc/emce/events/commands/InfoCommands.java index 37c5b92..b29b7fa 100644 --- a/src/main/java/net/emc/emce/events/commands/InfoCommands.java +++ b/src/main/java/net/emc/emce/events/commands/InfoCommands.java @@ -81,7 +81,7 @@ private boolean residentExists(String name) { } private void trySendTown(@NotNull String townName) { - NamedTextColor townTextColour = instance.getConfig().commands.townInfoTextColour.named(); + NamedTextColor townTextColour = instance.config().commands.townInfoTextColour.named(); Town town = EarthMCAPI.getTown(townName.toLowerCase(Locale.ROOT)); if (town == null) { @@ -92,7 +92,7 @@ private void trySendTown(@NotNull String townName) { } private void trySendNation(@NotNull String nationName) { - NamedTextColor nationTextColour = instance.getConfig().commands.nationInfoTextColour.named(); + NamedTextColor nationTextColour = instance.config().commands.nationInfoTextColour.named(); Nation nation = EarthMCAPI.getNation(nationName.toLowerCase(Locale.ROOT)); if (nation == null) { diff --git a/src/main/java/net/emc/emce/events/commands/NearbyCommand.java b/src/main/java/net/emc/emce/events/commands/NearbyCommand.java index fe7aa2d..2b84b46 100644 --- a/src/main/java/net/emc/emce/events/commands/NearbyCommand.java +++ b/src/main/java/net/emc/emce/events/commands/NearbyCommand.java @@ -23,7 +23,7 @@ public void register(CommandDispatcher dispatcher) { MinecraftClient client = MinecraftClient.getInstance(); if (client.player == null) return -1; - ModConfig.Nearby nearbyConfig = instance.getConfig().nearby; + ModConfig.Nearby nearbyConfig = instance.config().nearby; NamedTextColor headingColour = nearbyConfig.headingTextColour.named(); NamedTextColor textColour = nearbyConfig.playerTextColour.named(); diff --git a/src/main/java/net/emc/emce/events/commands/ToggleDebugCommand.java b/src/main/java/net/emc/emce/events/commands/ToggleDebugCommand.java deleted file mode 100644 index 6af5109..0000000 --- a/src/main/java/net/emc/emce/events/commands/ToggleDebugCommand.java +++ /dev/null @@ -1,27 +0,0 @@ - -package net.emc.emce.events.commands; - -import com.mojang.brigadier.CommandDispatcher; -import net.emc.emce.utils.Messaging; -import net.fabricmc.fabric.api.client.command.v2.ClientCommandManager; -import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; - -import static net.emc.emce.EarthMCEssentials.instance; - -public class ToggleDebugCommand { - public void register(CommandDispatcher dispatcher) { - dispatcher.register( - ClientCommandManager.literal("toggledebug").executes(c -> { - if (instance().debugEnabled()) { - Messaging.sendPrefixed("msg_debug_disabled"); - instance().setDebugEnabled(false); - } else { - Messaging.sendPrefixed("msg_debug_enabled"); - instance().setDebugEnabled(true); - } - - return 1; - }) - ); - } -} \ No newline at end of file diff --git a/src/main/java/net/emc/emce/events/commands/TownlessCommand.java b/src/main/java/net/emc/emce/events/commands/TownlessCommand.java index 5da68f4..4046868 100644 --- a/src/main/java/net/emc/emce/events/commands/TownlessCommand.java +++ b/src/main/java/net/emc/emce/events/commands/TownlessCommand.java @@ -27,7 +27,7 @@ String inviteStr(Object str, boolean revoking) { return "towny:town invite" + (revoking ? " -" : " ") + str.toString() + " "; } - NamedTextColor getTextColour() { return instance.getConfig().commands.townlessTextColour.named(); } + NamedTextColor getTextColour() { return instance.config().commands.townlessTextColour.named(); } Component createMsg(String key, int size) { return Messaging.create(key, getTextColour(), whiteText(size)); } Component whiteText(int size) { return Component.text(size).color(NamedTextColor.WHITE); } diff --git a/src/main/java/net/emc/emce/events/screen/ScreenInit.java b/src/main/java/net/emc/emce/events/screen/ScreenInit.java index 9478953..e018038 100644 --- a/src/main/java/net/emc/emce/events/screen/ScreenInit.java +++ b/src/main/java/net/emc/emce/events/screen/ScreenInit.java @@ -2,7 +2,7 @@ import me.shedaniel.clothconfig2.gui.ClothConfigScreen; import net.emc.emce.modules.OverlayRenderer; -import net.fabricmc.fabric.impl.client.screen.ScreenExtensions; +import net.fabricmc.fabric.api.client.screen.v1.ScreenEvents; import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.screen.Screen; @@ -28,8 +28,7 @@ public static void before(MinecraftClient client, Screen newScreen, int scaledWi public static void after(MinecraftClient client, Screen newScreen, int scaledWidth, int scaledHeight) { if (newScreen instanceof ClothConfigScreen) { - ScreenExtensions configSE = ScreenExtensions.getExtensions(newScreen); - configSE.fabric_getRemoveEvent().register(ScreenInit::Refresh); + ScreenEvents.remove(newScreen).register(ScreenInit::Refresh); } } } diff --git a/src/main/java/net/emc/emce/mixins/SessionEventListenerMixin.java b/src/main/java/net/emc/emce/mixins/SessionEventListenerMixin.java index 7eed9e3..d1fe079 100644 --- a/src/main/java/net/emc/emce/mixins/SessionEventListenerMixin.java +++ b/src/main/java/net/emc/emce/mixins/SessionEventListenerMixin.java @@ -1,5 +1,6 @@ package net.emc.emce.mixins; +import net.emc.emce.config.ModConfig; import net.emc.emce.modules.OverlayRenderer; import net.emc.emce.utils.Messaging; import net.emc.emce.utils.ModUtils; @@ -26,13 +27,20 @@ public void onStartGameSession(CallbackInfo ci) { ModUtils.updateServerName(); OverlayRenderer.Init(); - RegisterScreen(); - RegisterHud(); + ModConfig.General gen = instance().config().general; + instance().setShouldRender(gen.enableMod); + instance().setDebugEnabled(gen.debugLog); + + System.out.println("EMCE > Debug mode: " + gen.debugLog); + + if (instance().sessionCounter == 1) { + RegisterScreen(); + RegisterHud(); + } - instance().setShouldRender(instance().getConfig().general.enableMod); if (isConnectedToEMC()) { updateSessionCounter('+'); - //fetchEndpoints(); + fetchEndpoints(); // Out of queue, begin map check. if (instance().sessionCounter > 1) @@ -42,11 +50,11 @@ public void onStartGameSession(CallbackInfo ci) { @Inject(at = @At("TAIL"), method="onLeaveGameSession") public void onLeaveGameSession(CallbackInfo ci) { + if(isConnectedToEMC()) + updateSessionCounter('-'); + ModUtils.setServerName(""); OverlayRenderer.Clear(); - - if (isConnectedToEMC()) - updateSessionCounter('-'); } void updateSessionCounter(char type) { diff --git a/src/main/java/net/emc/emce/modules/EventRegistry.java b/src/main/java/net/emc/emce/modules/EventRegistry.java index a8832e3..9ed7f63 100644 --- a/src/main/java/net/emc/emce/modules/EventRegistry.java +++ b/src/main/java/net/emc/emce/modules/EventRegistry.java @@ -20,9 +20,7 @@ public static void RegisterCommands(EarthMCEssentials instance, CommandDispatche new NearbyCommand(instance).register(dispatcher); new TownlessCommand(instance).register(dispatcher); new AllianceCommand(instance).register(dispatcher); - new NetherCommand().register(dispatcher); - new ToggleDebugCommand().register(dispatcher); } public static void RegisterClientTick() { diff --git a/src/main/java/net/emc/emce/modules/OverlayRenderer.java b/src/main/java/net/emc/emce/modules/OverlayRenderer.java index 2ff2393..1ee2f03 100644 --- a/src/main/java/net/emc/emce/modules/OverlayRenderer.java +++ b/src/main/java/net/emc/emce/modules/OverlayRenderer.java @@ -16,6 +16,7 @@ import java.util.concurrent.CopyOnWriteArrayList; import static net.emc.emce.EarthMCEssentials.instance; +import static net.emc.emce.utils.EarthMCAPI.clientName; import static net.emc.emce.utils.ModUtils.*; import static net.minecraft.text.Text.translatable; @@ -158,7 +159,7 @@ private static void RenderNearby(boolean usingPreset) { if (x == null || z == null) continue; String name = curPlayer.getName(); - if (name.equals(client.player.getName().getString())) continue; + if (name.equals(clientName())) continue; int distance = Math.abs(x - (int) client.player.getX()) + Math.abs(z - (int) client.player.getZ()); diff --git a/src/main/java/net/emc/emce/modules/TaskScheduler.java b/src/main/java/net/emc/emce/modules/TaskScheduler.java index 4662bdb..516c093 100644 --- a/src/main/java/net/emc/emce/modules/TaskScheduler.java +++ b/src/main/java/net/emc/emce/modules/TaskScheduler.java @@ -14,10 +14,10 @@ import static net.emc.emce.EarthMCEssentials.instance; import static net.emc.emce.utils.EarthMCAPI.getTownless; -import static net.emc.emce.utils.EarthMCAPI.playerOnline; +import static net.emc.emce.utils.EarthMCAPI.clientOnline; public class TaskScheduler { - public ScheduledExecutorService service; + public ScheduledExecutorService service = Executors.newScheduledThreadPool(1); public boolean townlessRunning, nearbyRunning, cacheCheckRunning; public boolean hasMap = false; @@ -46,29 +46,24 @@ public void stop() { } public void initMap() { - service = Executors.newScheduledThreadPool(1); service.scheduleAtFixedRate(() -> { if (hasMap) return; - if (playerOnline("aurora")) setHasMap("aurora"); - else if (playerOnline("nova")) setHasMap("nova"); + if (clientOnline("aurora")) setHasMap("aurora"); + if (clientOnline("nova")) setHasMap("nova"); else setHasMap(null); - }, 15, 10, TimeUnit.SECONDS); // Give enough time for Dynmap & Vercel to update. + }, 15, 10, TimeUnit.SECONDS); } public void setHasMap(String map) { + hasMap = map != null; + if (map == null) { - Messaging.sendDebugMessage("Player not found on any map."); stop(); - - instance().mapName = "aurora"; - hasMap = false; - } - else { - Messaging.sendDebugMessage("Player found on: " + map); - - hasMap = true; + Messaging.sendDebugMessage("Player not found on any map!"); + } else { start(); + Messaging.sendDebugMessage("Player found on: " + map); } } @@ -116,5 +111,4 @@ private void startCacheCheck() { boolean shouldRun() { return ModConfig.instance().general.enableMod && MinecraftClient.getInstance().isWindowFocused(); } - } diff --git a/src/main/java/net/emc/emce/objects/Colors.java b/src/main/java/net/emc/emce/objects/Colors.java index f1d6359..59741fd 100644 --- a/src/main/java/net/emc/emce/objects/Colors.java +++ b/src/main/java/net/emc/emce/objects/Colors.java @@ -3,6 +3,7 @@ import net.kyori.adventure.text.format.NamedTextColor; import org.jetbrains.annotations.NotNull; +@SuppressWarnings("unused") public enum Colors { BLUE(NamedTextColor.BLUE), DARK_BLUE(NamedTextColor.DARK_BLUE), diff --git a/src/main/java/net/emc/emce/utils/EarthMCAPI.java b/src/main/java/net/emc/emce/utils/EarthMCAPI.java index 3e6ad3e..c6a54ba 100644 --- a/src/main/java/net/emc/emce/utils/EarthMCAPI.java +++ b/src/main/java/net/emc/emce/utils/EarthMCAPI.java @@ -55,6 +55,16 @@ public static Map getTownless() { public static Map onlinePlayers() { return currentMap().Players.online(); } + @Nullable + public static Player getOnlinePlayer(String playerName) { + return currentMap().Players.getOnline(playerName); + } + + public static boolean clientOnline(String map) { + instance().mapName = map; // getOnlinePlayer uses mapName. + return onlinePlayers().containsKey(clientName()); + } + @SuppressWarnings("unused") public static Map getResidents() { return currentMap().Residents.all(); @@ -157,9 +167,4 @@ public static String clientName() { ClientPlayerEntity pl = MinecraftClient.getInstance().player; return pl == null ? null : pl.getName().getString(); } - - public static boolean playerOnline(String map) { - instance().mapName = map; // getOnlinePlayer uses mapName. - return onlinePlayers().containsKey(clientName()); - } } \ No newline at end of file diff --git a/src/main/java/net/emc/emce/utils/ModUtils.java b/src/main/java/net/emc/emce/utils/ModUtils.java index 61403d6..4e9cd45 100644 --- a/src/main/java/net/emc/emce/utils/ModUtils.java +++ b/src/main/java/net/emc/emce/utils/ModUtils.java @@ -2,6 +2,7 @@ import io.github.emcw.entities.Player; import io.github.emcw.entities.Resident; +import net.emc.emce.config.ModConfig; import net.minecraft.client.MinecraftClient; import net.minecraft.client.network.ClientPlayNetworkHandler; import net.minecraft.client.network.ClientPlayerEntity; @@ -14,7 +15,7 @@ import java.net.InetSocketAddress; import java.util.*; -import static net.emc.emce.EarthMCEssentials.instance; +import static net.emc.emce.utils.EarthMCAPI.clientName; import static net.minecraft.client.MinecraftClient.getInstance; public class ModUtils { @@ -131,14 +132,12 @@ public static int getNearbyLongestElement(@NotNull Map nearby) { int longestElement = 0; for (Player curPlayer : nearby.values()) { - Player clientPlayer = instance().getClientPlayer(); - String name = curPlayer.getName(); Integer x = curPlayer.getLocation().getX(); Integer z = curPlayer.getLocation().getZ(); if (z == null || x == null || name == null) continue; - if (clientPlayer != null && name.equals(clientPlayer.getName())) continue; + if (name.equals(clientName())) continue; ClientPlayerEntity player = Objects.requireNonNull(getInstance().player); int distance = Math.abs(x - player.getBlockX()) + @@ -146,7 +145,7 @@ public static int getNearbyLongestElement(@NotNull Map nearby) { String prefix = ""; - if (instance().getConfig().nearby.showRank) { + if (ModConfig.instance().nearby.showRank) { if (!curPlayer.isResident()) prefix = "(Townless) "; else { Resident curRes = (Resident) curPlayer; diff --git a/src/main/resources/assets/emce/lang/en_us.json b/src/main/resources/assets/emce/lang/en_us.json index 8375196..bf8e0d4 100644 --- a/src/main/resources/assets/emce/lang/en_us.json +++ b/src/main/resources/assets/emce/lang/en_us.json @@ -59,6 +59,7 @@ "text.autoconfig.emc-essentials.category.General": "General", "text.autoconfig.emc-essentials.option.general.enableMod": "Enable Mod", + "text.autoconfig.emc-essentials.option.general.debugLog": "Log debug messages", "text.autoconfig.emc-essentials.category.Townless": "Townless", "text.autoconfig.emc-essentials.option.townless.enabled": "Enabled", From 7d623e29f04be6cc27e77e5ee74aba5d5f0fa121 Mon Sep 17 00:00:00 2001 From: Owen Stubbs Date: Tue, 4 Apr 2023 19:30:48 +0100 Subject: [PATCH 16/19] remove use of CompletableFuture getting nearby --- .../net/emc/emce/modules/TaskScheduler.java | 22 ++++------ .../java/net/emc/emce/utils/EarthMCAPI.java | 42 ++++++++++--------- 2 files changed, 31 insertions(+), 33 deletions(-) diff --git a/src/main/java/net/emc/emce/modules/TaskScheduler.java b/src/main/java/net/emc/emce/modules/TaskScheduler.java index 516c093..bd5a568 100644 --- a/src/main/java/net/emc/emce/modules/TaskScheduler.java +++ b/src/main/java/net/emc/emce/modules/TaskScheduler.java @@ -13,8 +13,7 @@ import java.util.concurrent.TimeUnit; import static net.emc.emce.EarthMCEssentials.instance; -import static net.emc.emce.utils.EarthMCAPI.getTownless; -import static net.emc.emce.utils.EarthMCAPI.clientOnline; +import static net.emc.emce.utils.EarthMCAPI.*; public class TaskScheduler { public ScheduledExecutorService service = Executors.newScheduledThreadPool(1); @@ -29,7 +28,7 @@ public void start() { // Pre-fill data. if (config.general.enableMod) { if (config.townless.enabled) instance().setTownless(getTownless()); - if (config.nearby.enabled) EarthMCAPI.getNearby().thenAccept(instance()::setNearbyPlayers); + if (config.nearby.enabled) instance().setNearbyPlayers(getNearby()); } startCacheCheck(); @@ -52,7 +51,7 @@ public void initMap() { if (clientOnline("aurora")) setHasMap("aurora"); if (clientOnline("nova")) setHasMap("nova"); else setHasMap(null); - }, 15, 10, TimeUnit.SECONDS); + }, 10, 5, TimeUnit.SECONDS); } public void setHasMap(String map) { @@ -69,31 +68,28 @@ public void setHasMap(String map) { private void startTownless() { townlessRunning = true; - ModConfig config = ModConfig.instance(); service.scheduleAtFixedRate(() -> { + var config = instance().config(); if (townlessRunning && config.townless.enabled && shouldRun()) { Messaging.sendDebugMessage("Starting townless task."); - instance().setTownless(getTownless()); Messaging.sendDebugMessage("Finished townless task."); } - }, 5, Math.max(config.intervals.townless, 200), TimeUnit.SECONDS); + }, 5, Math.max(instance().config().intervals.townless, 200), TimeUnit.SECONDS); } private void startNearby() { nearbyRunning = true; - final ModConfig config = ModConfig.instance(); service.scheduleAtFixedRate(() -> { + var config = instance().config(); if (nearbyRunning && config.nearby.enabled && shouldRun()) { Messaging.sendDebugMessage("Starting nearby task."); - EarthMCAPI.getNearby().thenAccept(nearby -> { - instance().setNearbyPlayers(nearby); - Messaging.sendDebugMessage("Finished nearby task."); - }); + instance().setNearbyPlayers(EarthMCAPI.getNearby()); + Messaging.sendDebugMessage("Finished nearby task."); } - }, 5, Math.max(config.intervals.nearby, 30), TimeUnit.SECONDS); + }, 5, Math.max(instance().config().intervals.nearby, 30), TimeUnit.SECONDS); } private void startCacheCheck() { diff --git a/src/main/java/net/emc/emce/utils/EarthMCAPI.java b/src/main/java/net/emc/emce/utils/EarthMCAPI.java index c6a54ba..2da098e 100644 --- a/src/main/java/net/emc/emce/utils/EarthMCAPI.java +++ b/src/main/java/net/emc/emce/utils/EarthMCAPI.java @@ -18,7 +18,9 @@ import java.util.Map; import java.util.Objects; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import static io.github.emcw.utils.GsonUtil.serialize; import static net.emc.emce.EarthMCEssentials.instance; public class EarthMCAPI { @@ -62,6 +64,8 @@ public static Player getOnlinePlayer(String playerName) { public static boolean clientOnline(String map) { instance().mapName = map; // getOnlinePlayer uses mapName. + + System.out.println(serialize(onlinePlayers().values())); return onlinePlayers().containsKey(clientName()); } @@ -87,35 +91,33 @@ public static Map allPlayers() { } @Contract(" -> new") - public static @NotNull CompletableFuture> getNearby() { + public static @NotNull Map getNearby() { return getNearby(config.nearby.xBlocks, config.nearby.zBlocks); } @Contract("_, _ -> new") - public static @NotNull CompletableFuture> getNearby(int xBlocks, int zBlocks) { - return CompletableFuture.supplyAsync(() -> { - Map result = Map.of(); + public static @NotNull Map getNearby(int xBlocks, int zBlocks) { + Map result = new ConcurrentHashMap<>(); - try { - MinecraftClient client = MinecraftClient.getInstance(); - ClientPlayerEntity player = client.player; + try { + MinecraftClient client = MinecraftClient.getInstance(); + ClientPlayerEntity player = client.player; - if (player == null) return result; - if (!player.getEntityWorld().getDimension().bedWorks()) return result; + if (player == null) return result; + if (!player.getEntityWorld().getDimension().bedWorks()) return result; - EMCMap curMap = currentMap(); - Integer x = (int) player.getX(), - y = (int) player.getY(); + EMCMap curMap = currentMap(); + Integer x = (int) player.getX(), + y = (int) player.getY(); - Map nearby = curMap.Players.getNearby(allPlayers(), x, y, xBlocks, zBlocks); - nearby.remove(clientName()); + Map nearby = curMap.Players.getNearby(allPlayers(), x, y, xBlocks, zBlocks); + nearby.remove(clientName()); - return nearby; - } catch (Exception e) { - Messaging.sendDebugMessage("Error fetching nearby!", e); - return result; - } - }); + return nearby; + } catch (Exception e) { + Messaging.sendDebugMessage("Error fetching nearby!", e); + return result; + } } @Contract(" -> new") From 78d5840753213b78e5156b5d3ce6d57372184d46 Mon Sep 17 00:00:00 2001 From: Owen Stubbs Date: Tue, 4 Apr 2023 19:40:12 +0100 Subject: [PATCH 17/19] fix problems --- src/main/java/net/emc/emce/config/ModConfig.java | 1 + .../java/net/emc/emce/events/commands/AllianceCommand.java | 3 --- .../java/net/emc/emce/events/commands/NearbyCommand.java | 5 +++-- src/main/java/net/emc/emce/modules/OverlayRenderer.java | 1 - src/main/java/net/emc/emce/modules/TaskScheduler.java | 2 +- 5 files changed, 5 insertions(+), 7 deletions(-) diff --git a/src/main/java/net/emc/emce/config/ModConfig.java b/src/main/java/net/emc/emce/config/ModConfig.java index b3a3425..7b61789 100644 --- a/src/main/java/net/emc/emce/config/ModConfig.java +++ b/src/main/java/net/emc/emce/config/ModConfig.java @@ -14,6 +14,7 @@ import static me.shedaniel.autoconfig.annotation.ConfigEntry.Gui.EnumHandler.EnumDisplayOption.BUTTON; +@SuppressWarnings("CanBeFinal") @Config(name = "emc-essentials") @Background(value = "cloth-config2:transparent") public class ModConfig implements ConfigData { diff --git a/src/main/java/net/emc/emce/events/commands/AllianceCommand.java b/src/main/java/net/emc/emce/events/commands/AllianceCommand.java index 59ac3a9..73ab819 100644 --- a/src/main/java/net/emc/emce/events/commands/AllianceCommand.java +++ b/src/main/java/net/emc/emce/events/commands/AllianceCommand.java @@ -12,9 +12,6 @@ import net.kyori.adventure.audience.Audience; import net.kyori.adventure.platform.fabric.FabricClientAudiences; import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.ComponentBuilder; -import net.kyori.adventure.text.TextComponent; -import net.kyori.adventure.text.TranslatableComponent; import net.kyori.adventure.text.event.ClickEvent; import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.format.Style; diff --git a/src/main/java/net/emc/emce/events/commands/NearbyCommand.java b/src/main/java/net/emc/emce/events/commands/NearbyCommand.java index 2b84b46..db8f7d9 100644 --- a/src/main/java/net/emc/emce/events/commands/NearbyCommand.java +++ b/src/main/java/net/emc/emce/events/commands/NearbyCommand.java @@ -13,12 +13,13 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; import net.minecraft.client.MinecraftClient; +import org.jetbrains.annotations.NotNull; import java.util.Map; public record NearbyCommand(EarthMCEssentials instance) { - public void register(CommandDispatcher dispatcher) { + public void register(@NotNull CommandDispatcher dispatcher) { dispatcher.register(ClientCommandManager.literal("nearby").executes(c -> { MinecraftClient client = MinecraftClient.getInstance(); if (client.player == null) return -1; @@ -57,7 +58,7 @@ public void register(CommandDispatcher dispatcher) { return 1; }).then(ClientCommandManager.literal("refresh").executes(c -> { - EarthMCAPI.getNearby().thenAccept(instance::setNearbyPlayers); + instance.setNearbyPlayers(EarthMCAPI.getNearby()); Messaging.sendPrefixed("msg_nearby_refresh"); return 1; })).then(ClientCommandManager.literal("clear").executes(c -> { diff --git a/src/main/java/net/emc/emce/modules/OverlayRenderer.java b/src/main/java/net/emc/emce/modules/OverlayRenderer.java index 1ee2f03..2b81b9d 100644 --- a/src/main/java/net/emc/emce/modules/OverlayRenderer.java +++ b/src/main/java/net/emc/emce/modules/OverlayRenderer.java @@ -4,7 +4,6 @@ import io.github.emcw.entities.Resident; import net.emc.emce.config.ModConfig; import net.emc.emce.utils.ModUtils; -import net.emc.emce.utils.ModUtils.State; import net.minecraft.client.MinecraftClient; import net.minecraft.client.font.TextRenderer; import net.minecraft.client.util.math.MatrixStack; diff --git a/src/main/java/net/emc/emce/modules/TaskScheduler.java b/src/main/java/net/emc/emce/modules/TaskScheduler.java index bd5a568..07f030f 100644 --- a/src/main/java/net/emc/emce/modules/TaskScheduler.java +++ b/src/main/java/net/emc/emce/modules/TaskScheduler.java @@ -16,7 +16,7 @@ import static net.emc.emce.utils.EarthMCAPI.*; public class TaskScheduler { - public ScheduledExecutorService service = Executors.newScheduledThreadPool(1); + public final ScheduledExecutorService service = Executors.newScheduledThreadPool(1); public boolean townlessRunning, nearbyRunning, cacheCheckRunning; public boolean hasMap = false; From 7710686200d4d9db7324cc8775834729349dcb85 Mon Sep 17 00:00:00 2001 From: Owen Stubbs Date: Mon, 10 Apr 2023 15:17:42 +0100 Subject: [PATCH 18/19] fix nearby & add 'Sort Order' config option --- build.gradle | 4 +- gradle.properties | 4 +- settings.gradle | 2 +- .../java/net/emc/emce/EarthMCEssentials.java | 8 +- .../java/net/emc/emce/config/ModConfig.java | 27 ++-- .../emce/events/commands/InfoCommands.java | 30 ++-- .../emce/events/commands/NearbyCommand.java | 23 ++- .../emce/events/commands/TownlessCommand.java | 14 +- .../emc/emce/events/screen/ScreenInit.java | 13 +- .../mixins/SessionEventListenerMixin.java | 17 +-- .../net/emc/emce/modules/EventRegistry.java | 5 +- .../net/emc/emce/modules/OverlayRenderer.java | 131 ++++++++++++------ .../net/emc/emce/modules/TaskScheduler.java | 39 +++--- .../java/net/emc/emce/utils/EarthMCAPI.java | 46 +++--- .../java/net/emc/emce/utils/Messaging.java | 18 ++- .../java/net/emc/emce/utils/ModUtils.java | 63 +++++---- .../resources/assets/emce/lang/en_us.json | 7 +- 17 files changed, 269 insertions(+), 182 deletions(-) diff --git a/build.gradle b/build.gradle index bef828a..7174f19 100644 --- a/build.gradle +++ b/build.gradle @@ -5,7 +5,7 @@ plugins { sourceCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17 -version = "${project.mod_version}-${project.minecraft_version}+" as Object +version = "v${project.mod_version}-${project.minecraft_version}" as Object group = project.maven_group def localProps = new Properties() @@ -70,7 +70,7 @@ processResources { inputs.property "version", project.version filesMatching("fabric.mod.json") { - expand "version": project.version + expand("version": project.version) } } diff --git a/gradle.properties b/gradle.properties index 3e42515..08d1c88 100644 --- a/gradle.properties +++ b/gradle.properties @@ -11,11 +11,11 @@ fabric_version=0.72.0+1.19.3 # Mod Properties name = EarthMCEssentials -mod_version = 3.6.0 +mod_version = 4.0.0 maven_group = net.emc.emce # Library versions cloth_config_version=9.0.94 mod_menu_version=5.0.2 adventure_fabric_version=5.6.1 -wrapper_version=0.9.0 \ No newline at end of file +wrapper_version=0.10.2 \ No newline at end of file diff --git a/settings.gradle b/settings.gradle index b4ba4a7..1c63b75 100644 --- a/settings.gradle +++ b/settings.gradle @@ -8,4 +8,4 @@ pluginManagement { } } -rootProject.name = 'EarthMCEssentials' \ No newline at end of file +rootProject.name = 'EMCEssentials' \ No newline at end of file diff --git a/src/main/java/net/emc/emce/EarthMCEssentials.java b/src/main/java/net/emc/emce/EarthMCEssentials.java index e2fca82..3806c40 100644 --- a/src/main/java/net/emc/emce/EarthMCEssentials.java +++ b/src/main/java/net/emc/emce/EarthMCEssentials.java @@ -101,7 +101,7 @@ public void setDebugEnabled(boolean enabled) { this.debugModeEnabled = enabled; if (enabled) Messaging.sendPrefixed("msg_debug_enabled"); - else Messaging.sendPrefixed("msg_debug_enabled"); + else Messaging.sendPrefixed("msg_debug_disabled"); } public boolean debugEnabled() { @@ -125,12 +125,12 @@ public void setShouldRender(boolean shouldRender) { this.shouldRender = shouldRender; } - public void setTownless(@NotNull Map array) { + public void setTownless(@NotNull Map map) { // Make sure there is data to add. - if (array.size() < 1) return; + if (map.size() < 1) return; townlessNames.clear(); - townlessNames = GsonUtil.streamValues(array).map(BaseEntity::getName).collect(Collectors.toList()); + townlessNames = GsonUtil.streamValues(map).map(BaseEntity::getName).collect(Collectors.toList()); OverlayRenderer.SetTownless(townlessNames); OverlayRenderer.UpdateStates(true, false); diff --git a/src/main/java/net/emc/emce/config/ModConfig.java b/src/main/java/net/emc/emce/config/ModConfig.java index 7b61789..45c5b19 100644 --- a/src/main/java/net/emc/emce/config/ModConfig.java +++ b/src/main/java/net/emc/emce/config/ModConfig.java @@ -10,9 +10,12 @@ import me.shedaniel.cloth.clothconfig.shadowed.blue.endless.jankson.Comment; import net.emc.emce.EarthMCEssentials; import net.emc.emce.objects.Colors; + +import net.emc.emce.utils.ModUtils.NearbySort; import net.emc.emce.utils.ModUtils.State; import static me.shedaniel.autoconfig.annotation.ConfigEntry.Gui.EnumHandler.EnumDisplayOption.BUTTON; +import static me.shedaniel.autoconfig.annotation.ConfigEntry.Gui.EnumHandler.EnumDisplayOption.DROPDOWN; @SuppressWarnings("CanBeFinal") @Config(name = "emc-essentials") @@ -63,10 +66,10 @@ public static class Townless { @Comment("Note: Only used if Use Preset Positions is off.") public int yPos = 16; - @EnumHandler(option = BUTTON) + @EnumHandler(option = DROPDOWN) @Comment("The colour of the 'Townless Players' text.") public Colors headingTextColour = Colors.DARK_PURPLE; - @EnumHandler(option = BUTTON) + @EnumHandler(option = DROPDOWN) @Comment("The colour of the townless player names.") public Colors playerTextColour = Colors.DARK_PURPLE; } @@ -82,15 +85,19 @@ public static class Nearby { @EnumHandler(option = BUTTON) public State positionState = State.TOP_RIGHT; + @EnumHandler(option = BUTTON) + @Comment("Determines order of the nearby players list before rendering.") + public NearbySort nearbySort = NearbySort.NEAREST; + @Comment("The horizontal position on the HUD.") public int xPos = 100; @Comment("The vertical position on the HUD.") public int yPos = 16; - @EnumHandler(option = BUTTON) + @EnumHandler(option = DROPDOWN) @Comment("The colour of the 'Nearby Players' text.") public Colors headingTextColour = Colors.GOLD; - @EnumHandler(option = BUTTON) + @EnumHandler(option = DROPDOWN) @Comment("The colour of nearby players' names.") public Colors playerTextColour = Colors.GOLD; @@ -104,19 +111,19 @@ public static class Nearby { } public static class Commands { - @EnumHandler(option = BUTTON) + @EnumHandler(option = DROPDOWN) @Comment("The colour of the townless players text.") public Colors townlessTextColour = Colors.LIGHT_PURPLE; - @EnumHandler(option = BUTTON) + @EnumHandler(option = DROPDOWN) @Comment("The colour of the town info text.") public Colors townInfoTextColour = Colors.GREEN; - @EnumHandler(option = BUTTON) + @EnumHandler(option = DROPDOWN) @Comment("The colour of the nation info text.") public Colors nationInfoTextColour = Colors.AQUA; - @EnumHandler(option = BUTTON) + @EnumHandler(option = DROPDOWN) @Comment("The colour of the alliance info text.") public Colors allianceInfoTextColour = Colors.GOLD; } @@ -124,10 +131,10 @@ public static class Commands { public static class Intervals { @Comment("Fairly harmless on performance, can be lowered without much overhead.") @BoundedDiscrete(min = 10, max = 200) - public int townless = 60; + public int townless = 30; @Comment("Small but frequent payload, if you don't rely on it much, turn it up.") - @BoundedDiscrete(min = 3, max = 15) + @BoundedDiscrete(min = 2, max = 30) public int nearby = 5; } diff --git a/src/main/java/net/emc/emce/events/commands/InfoCommands.java b/src/main/java/net/emc/emce/events/commands/InfoCommands.java index b29b7fa..dce6066 100644 --- a/src/main/java/net/emc/emce/events/commands/InfoCommands.java +++ b/src/main/java/net/emc/emce/events/commands/InfoCommands.java @@ -33,12 +33,18 @@ public void registerTownInfoCommand(CommandDispatcher return 1; })).executes(c -> { - Player clientPlayer = instance.getClientPlayer(); + if (residentExists(clientName())) { + String townName; - if (residentExists(clientPlayer.getName())) { - String townName = ((Resident) clientPlayer).getTown(); + try { + Player clientPlayer = instance.getClientPlayer(); + townName = clientPlayer.asResident(instance.mapName).getTown(); + } catch (Exception e) { + Messaging.sendPrefixed("text_towninfo_not_registered"); + return 1; + } - if (townName.equals("") || townName.equals("No Town")) + if (townName.equals("") && townName.equals("No Town")) Messaging.sendPrefixed("text_towninfo_not_registered"); else trySendTown(townName); } @@ -55,12 +61,18 @@ public void registerNationInfoCommand(CommandDispatcher { - Player clientPlayer = instance.getClientPlayer(); + if (residentExists(clientName())) { + String nationName; - if (residentExists(clientPlayer.getName())) { - String nationName = ((Resident) clientPlayer).getNation(); + try { + Player clientPlayer = instance.getClientPlayer(); + nationName = clientPlayer.asResident(instance.mapName).getNation(); + } catch (Exception e) { + Messaging.sendPrefixed("text_towninfo_not_registered"); + return 1; + } - if (nationName.equals("") || nationName.equals("No Nation")) + if (nationName == null || nationName.equals("No Nation")) Messaging.sendPrefixed("text_nationinfo_not_registered"); else trySendNation(nationName); } @@ -73,7 +85,7 @@ private boolean residentExists(String name) { Resident res = EarthMCAPI.getResident(name); if (res == null) { - Messaging.send(Translation.of("text_shared_notregistered", clientName())); + Messaging.send(Translation.of("text_shared_notregistered", name)); return false; } diff --git a/src/main/java/net/emc/emce/events/commands/NearbyCommand.java b/src/main/java/net/emc/emce/events/commands/NearbyCommand.java index db8f7d9..4afb14f 100644 --- a/src/main/java/net/emc/emce/events/commands/NearbyCommand.java +++ b/src/main/java/net/emc/emce/events/commands/NearbyCommand.java @@ -3,6 +3,7 @@ import com.mojang.brigadier.CommandDispatcher; import io.github.emcw.entities.Player; import io.github.emcw.entities.Resident; +import io.github.emcw.exceptions.MissingEntryException; import net.emc.emce.EarthMCEssentials; import net.emc.emce.config.ModConfig; import net.emc.emce.utils.Translation; @@ -13,16 +14,19 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; import net.minecraft.client.MinecraftClient; +import net.minecraft.client.network.ClientPlayerEntity; import org.jetbrains.annotations.NotNull; import java.util.Map; +import static net.emc.emce.modules.OverlayRenderer.dist; + public record NearbyCommand(EarthMCEssentials instance) { public void register(@NotNull CommandDispatcher dispatcher) { dispatcher.register(ClientCommandManager.literal("nearby").executes(c -> { - MinecraftClient client = MinecraftClient.getInstance(); - if (client.player == null) return -1; + ClientPlayerEntity player = MinecraftClient.getInstance().player; + if (player == null) return -1; ModConfig.Nearby nearbyConfig = instance.config().nearby; @@ -38,14 +42,19 @@ public void register(@NotNull CommandDispatcher dispa Integer z = curPlayer.getLocation().getZ(); if (x == null || z == null) continue; - int distance = Math.abs(x - (int) client.player.getX()) + - Math.abs(z - (int) client.player.getZ()); - + int distance = dist(x, z); Component prefix = Component.empty(); + if (nearbyConfig.showRank) { if (!curPlayer.isResident()) prefix = Translation.of("text_nearby_rank_townless"); else { - Resident res = (Resident) curPlayer; + Resident res; + try { + res = curPlayer.asResident(instance.mapName); + } catch (MissingEntryException e) { + continue; + } + prefix = Component.text("(" + res.getRank() + ") "); } } @@ -67,4 +76,4 @@ public void register(@NotNull CommandDispatcher dispa return 1; }))); } -} +} \ No newline at end of file diff --git a/src/main/java/net/emc/emce/events/commands/TownlessCommand.java b/src/main/java/net/emc/emce/events/commands/TownlessCommand.java index 4046868..4c5f6ed 100644 --- a/src/main/java/net/emc/emce/events/commands/TownlessCommand.java +++ b/src/main/java/net/emc/emce/events/commands/TownlessCommand.java @@ -2,17 +2,18 @@ import com.mojang.brigadier.CommandDispatcher; import net.emc.emce.EarthMCEssentials; +import net.emc.emce.modules.OverlayRenderer; import net.emc.emce.utils.EarthMCAPI; import net.emc.emce.utils.Messaging; import net.emc.emce.utils.ModUtils; import net.fabricmc.fabric.api.client.command.v2.ClientCommandManager; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.TextComponent; import net.kyori.adventure.text.format.NamedTextColor; import net.minecraft.client.MinecraftClient; import java.util.List; -import java.util.Map; public record TownlessCommand(EarthMCEssentials instance) { static NamedTextColor townlessTextColour; @@ -28,8 +29,11 @@ String inviteStr(Object str, boolean revoking) { } NamedTextColor getTextColour() { return instance.config().commands.townlessTextColour.named(); } - Component createMsg(String key, int size) { return Messaging.create(key, getTextColour(), whiteText(size)); } - Component whiteText(int size) { return Component.text(size).color(NamedTextColor.WHITE); } + TextComponent whiteText(int size) { return Component.text(size).color(NamedTextColor.WHITE); } + + Component createMsg(String key, int size) { + return Messaging.create(key, getTextColour(), whiteText(size)); + } public void register(CommandDispatcher dispatcher) { dispatcher.register(ClientCommandManager.literal("townless").executes(c -> { @@ -79,7 +83,9 @@ public void register(CommandDispatcher dispatcher) { return 1; })).then(ClientCommandManager.literal("clear").executes(c -> { - instance.setTownless(Map.of()); + OverlayRenderer.SetTownless(List.of()); + OverlayRenderer.UpdateStates(true, false); + Messaging.sendPrefixed("msg_townless_clear"); return 1; diff --git a/src/main/java/net/emc/emce/events/screen/ScreenInit.java b/src/main/java/net/emc/emce/events/screen/ScreenInit.java index e018038..cb8c071 100644 --- a/src/main/java/net/emc/emce/events/screen/ScreenInit.java +++ b/src/main/java/net/emc/emce/events/screen/ScreenInit.java @@ -7,19 +7,8 @@ import net.minecraft.client.gui.screen.Screen; public class ScreenInit { - private static boolean configOpen = false; - - public static boolean configOpen() { - return configOpen; - } - - public static void setConfigOpen(boolean value) { - configOpen = value; - } - private static void Refresh(Screen screen) { OverlayRenderer.Init(); - setConfigOpen(false); } public static void before(MinecraftClient client, Screen newScreen, int scaledWidth, int scaledHeight) { @@ -31,4 +20,4 @@ public static void after(MinecraftClient client, Screen newScreen, int scaledWid ScreenEvents.remove(newScreen).register(ScreenInit::Refresh); } } -} +} \ No newline at end of file diff --git a/src/main/java/net/emc/emce/mixins/SessionEventListenerMixin.java b/src/main/java/net/emc/emce/mixins/SessionEventListenerMixin.java index d1fe079..258dc87 100644 --- a/src/main/java/net/emc/emce/mixins/SessionEventListenerMixin.java +++ b/src/main/java/net/emc/emce/mixins/SessionEventListenerMixin.java @@ -1,9 +1,7 @@ package net.emc.emce.mixins; -import net.emc.emce.config.ModConfig; import net.emc.emce.modules.OverlayRenderer; import net.emc.emce.utils.Messaging; -import net.emc.emce.utils.ModUtils; import net.minecraft.client.MinecraftClientGame; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; @@ -11,12 +9,12 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import static net.emc.emce.EarthMCEssentials.instance; - import static net.emc.emce.utils.EarthMCAPI.fetchEndpoints; -import static net.emc.emce.utils.ModUtils.isConnectedToEMC; import static net.emc.emce.modules.EventRegistry.RegisterScreen; import static net.emc.emce.modules.EventRegistry.RegisterHud; +import static net.emc.emce.utils.ModUtils.isConnectedToEMC; +import static net.emc.emce.utils.ModUtils.updateServerName; @Mixin(MinecraftClientGame.class) public abstract class SessionEventListenerMixin { @@ -24,14 +22,11 @@ public abstract class SessionEventListenerMixin { public void onStartGameSession(CallbackInfo ci) { System.out.println("EMCE > New game session detected."); - ModUtils.updateServerName(); + updateServerName(); OverlayRenderer.Init(); - ModConfig.General gen = instance().config().general; - instance().setShouldRender(gen.enableMod); - instance().setDebugEnabled(gen.debugLog); - - System.out.println("EMCE > Debug mode: " + gen.debugLog); + instance().setShouldRender(instance().config().general.enableMod); + instance().setDebugEnabled(instance().config().general.debugLog); if (instance().sessionCounter == 1) { RegisterScreen(); @@ -53,7 +48,7 @@ public void onLeaveGameSession(CallbackInfo ci) { if(isConnectedToEMC()) updateSessionCounter('-'); - ModUtils.setServerName(""); + updateServerName(); OverlayRenderer.Clear(); } diff --git a/src/main/java/net/emc/emce/modules/EventRegistry.java b/src/main/java/net/emc/emce/modules/EventRegistry.java index 9ed7f63..183249b 100644 --- a/src/main/java/net/emc/emce/modules/EventRegistry.java +++ b/src/main/java/net/emc/emce/modules/EventRegistry.java @@ -7,6 +7,7 @@ import net.emc.emce.events.commands.*; import net.emc.emce.events.screen.ScreenInit; import net.emc.emce.utils.Messaging; +import net.emc.emce.utils.ModUtils; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents; import net.fabricmc.fabric.api.client.rendering.v1.HudRenderCallback; @@ -27,10 +28,8 @@ public static void RegisterClientTick() { // Every tick, see if we are pressing F4. ClientTickEvents.END_CLIENT_TICK.register(client -> { if (EarthMCEssentials.configKeybinding.wasPressed()) { - if (!ScreenInit.configOpen()) { + if (!ModUtils.configOpen()) { try { - ScreenInit.setConfigOpen(true); - Screen configScreen = AutoConfig.getConfigScreen(ModConfig.class, client.currentScreen).get(); client.setScreen(configScreen); } catch (Exception e) { diff --git a/src/main/java/net/emc/emce/modules/OverlayRenderer.java b/src/main/java/net/emc/emce/modules/OverlayRenderer.java index 2b81b9d..13ed0dc 100644 --- a/src/main/java/net/emc/emce/modules/OverlayRenderer.java +++ b/src/main/java/net/emc/emce/modules/OverlayRenderer.java @@ -1,7 +1,8 @@ package net.emc.emce.modules; +import io.github.emcw.entities.Location; import io.github.emcw.entities.Player; -import io.github.emcw.entities.Resident; +import io.github.emcw.exceptions.MissingEntryException; import net.emc.emce.config.ModConfig; import net.emc.emce.utils.ModUtils; import net.minecraft.client.MinecraftClient; @@ -9,11 +10,17 @@ import net.minecraft.client.util.math.MatrixStack; import net.minecraft.text.*; import net.minecraft.util.Formatting; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.concurrent.CopyOnWriteArrayList; +import static io.github.emcw.utils.GsonUtil.streamEntries; +import static java.util.stream.Collectors.toMap; import static net.emc.emce.EarthMCEssentials.instance; import static net.emc.emce.utils.EarthMCAPI.clientName; import static net.emc.emce.utils.ModUtils.*; @@ -71,6 +78,66 @@ public static void Render(MatrixStack ms) { if (config.nearby.enabled) RenderNearby(config.nearby.presetPositions); } + public static String getRankPrefix(Player player) throws MissingEntryException { + String prefix = "(Townless) "; + + if (config.nearby.showRank) { + if (player.isResident()) { + String rank = player.asResident(instance().mapName).getRank(); + prefix = "(" + rank + ") "; + } + } + + return prefix; + } + + public static int dist(int x, int z) { + assert client.player != null; + return Math.abs(x - (int) client.player.getX()) + + Math.abs(z - (int) client.player.getZ()); + } + + public static @Nullable MutableText prefixedPlayerDistance(@NotNull Player player) throws MissingEntryException { + Formatting playerTextFormatting = Formatting.byName(config.nearby.playerTextColour.name()); + + Integer x = player.getLocation().getX(); + Integer z = player.getLocation().getZ(); + if (x == null || z == null) return null; + + String name = player.getName(); + if (name.equals(clientName())) return null; + + int distance = dist(x, z); + String prefix = getRankPrefix(player); + + return translatable(prefix + name + ": " + distance + "m").formatted(playerTextFormatting); + } + + static LinkedHashMap sortByDistance(Map players, boolean acsending) { + return streamEntries(players).sorted((o1, o2) -> { + Location loc1 = o1.getValue().getLocation(); + Integer dist1 = dist(loc1.getX(), loc1.getZ()); + + Location loc2 = o2.getValue().getLocation(); + Integer dist2 = dist(loc2.getX(), loc2.getZ()); + + return acsending ? dist1.compareTo(dist2) : dist2.compareTo(dist1); + }).collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (k1, k2) -> k1, LinkedHashMap::new)); + } + + static LinkedHashMap sortByRank(Map players, String rank) { + return streamEntries(players).sorted((o1, o2) -> { + if (Objects.equals(rank, "townless")) { + Boolean cur = !o1.getValue().isResident(); + Boolean next = !o2.getValue().isResident(); + + return cur.compareTo(next); + } + + return 0; + }).collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (k1, k2) -> k1, LinkedHashMap::new)); + } + private static void RenderTownless(boolean usingPreset) { int townlessSize = townless.size(); int maxLen = config.townless.maxLength; @@ -140,7 +207,12 @@ private static void RenderTownless(boolean usingPreset) { private static void RenderNearby(boolean usingPreset) { Map nearby = nearby(); - Formatting playerTextFormatting = Formatting.byName(config.nearby.playerTextColour.name()); + switch (config.nearby.nearbySort) { + case NEAREST -> nearby = sortByDistance(nearby, true); + case FURTHEST -> nearby = sortByDistance(nearby, false); + case TOWNLESS -> nearby = sortByRank(nearby, "townless"); + } + Formatting nearbyTextFormatting = Formatting.byName(config.nearby.headingTextColour.name()); MutableText nearbyText = translatable("text_nearby_header", nearby.size()).formatted(nearbyTextFormatting); @@ -150,32 +222,19 @@ private static void RenderNearby(boolean usingPreset) { if (client.player == null) return; if (nearby.size() >= 1) { + MutableText playerText; int i = 0; for (Player curPlayer : nearby.values()) { - Integer x = curPlayer.getLocation().getX(); - Integer z = curPlayer.getLocation().getZ(); - if (x == null || z == null) continue; - - String name = curPlayer.getName(); - if (name.equals(clientName())) continue; - - int distance = Math.abs(x - (int) client.player.getX()) + - Math.abs(z - (int) client.player.getZ()); - - String prefix = ""; - - if (config.nearby.showRank) { - if (!curPlayer.isResident()) prefix = "(Townless) "; - else { - Resident res = (Resident) curPlayer; - prefix = "(" + res.getRank() + ") "; - } + try { + playerText = prefixedPlayerDistance(curPlayer); + if (playerText == null) continue; + } + catch (MissingEntryException e) { + continue; } - MutableText playerText = translatable(prefix + name + ": " + distance + "m").formatted(playerTextFormatting); renderer.drawWithShadow(matrixStack, playerText, nearbyState.getX(), nearbyState.getY() + 10 * i, color); - ++i; } } @@ -190,27 +249,17 @@ private static void RenderNearby(boolean usingPreset) { if (client.player == null) return; if (nearby.size() >= 1) { + MutableText playerText; + for (Player curPlayer : nearby.values()) { - Integer x = curPlayer.getLocation().getX(); - Integer z = curPlayer.getLocation().getZ(); - if (x == null || z == null) continue; - - String currentPlayerName = curPlayer.getName(); - if (currentPlayerName.equals(client.player.getName().getString())) continue; - - int distance = Math.abs(x - (int) client.player.getX()) + - Math.abs(z - (int) client.player.getZ()); - - String prefix = ""; - if (config.nearby.showRank) { - if (!curPlayer.isResident()) prefix = "(Townless) "; - else { - Resident res = (Resident) curPlayer; - prefix = "(" + res.getRank() + ") "; - } + try { + playerText = prefixedPlayerDistance(curPlayer); + if (playerText == null) continue; + } + catch (MissingEntryException e) { + continue; } - MutableText playerText = translatable(prefix + currentPlayerName + ": " + distance + "m").formatted(playerTextFormatting); renderer.drawWithShadow(matrixStack, playerText, xOffset, playerOffset, color); // Add 10 pixels to offset. (Where the next player will be rendered) @@ -354,4 +403,4 @@ private static void UpdateNearbyState() { } } } -} +} \ No newline at end of file diff --git a/src/main/java/net/emc/emce/modules/TaskScheduler.java b/src/main/java/net/emc/emce/modules/TaskScheduler.java index 07f030f..eced20d 100644 --- a/src/main/java/net/emc/emce/modules/TaskScheduler.java +++ b/src/main/java/net/emc/emce/modules/TaskScheduler.java @@ -12,23 +12,24 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; +import static io.github.emcw.utils.GsonUtil.serialize; import static net.emc.emce.EarthMCEssentials.instance; -import static net.emc.emce.utils.EarthMCAPI.*; +import static net.emc.emce.utils.EarthMCAPI.clientOnline; public class TaskScheduler { - public final ScheduledExecutorService service = Executors.newScheduledThreadPool(1); public boolean townlessRunning, nearbyRunning, cacheCheckRunning; public boolean hasMap = false; private static final List> CACHES = List.of(AllianceDataCache.INSTANCE); + private ScheduledExecutorService service; public void start() { ModConfig config = ModConfig.instance(); // Pre-fill data. if (config.general.enableMod) { - if (config.townless.enabled) instance().setTownless(getTownless()); - if (config.nearby.enabled) instance().setNearbyPlayers(getNearby()); + if (config.townless.enabled) instance().setTownless(EarthMCAPI.getTownless()); + if (config.nearby.enabled) instance().setNearbyPlayers(EarthMCAPI.getNearby()); } startCacheCheck(); @@ -45,22 +46,26 @@ public void stop() { } public void initMap() { + service = Executors.newScheduledThreadPool(4); service.scheduleAtFixedRate(() -> { if (hasMap) return; if (clientOnline("aurora")) setHasMap("aurora"); - if (clientOnline("nova")) setHasMap("nova"); + else if (clientOnline("nova")) setHasMap("nova"); else setHasMap(null); - }, 10, 5, TimeUnit.SECONDS); + }, 5, 15, TimeUnit.SECONDS); } public void setHasMap(String map) { - hasMap = map != null; - if (map == null) { + hasMap = false; + instance().mapName = "aurora"; + stop(); Messaging.sendDebugMessage("Player not found on any map!"); } else { + hasMap = true; + start(); Messaging.sendDebugMessage("Player found on: " + map); } @@ -68,28 +73,26 @@ public void setHasMap(String map) { private void startTownless() { townlessRunning = true; + ModConfig config = ModConfig.instance(); service.scheduleAtFixedRate(() -> { - var config = instance().config(); if (townlessRunning && config.townless.enabled && shouldRun()) { - Messaging.sendDebugMessage("Starting townless task."); - instance().setTownless(getTownless()); - Messaging.sendDebugMessage("Finished townless task."); + instance().setTownless(EarthMCAPI.getTownless()); + Messaging.sendDebugMessage("Updating townless..."); } - }, 5, Math.max(instance().config().intervals.townless, 200), TimeUnit.SECONDS); + }, 5, Math.min(config.intervals.townless, 200), TimeUnit.SECONDS); } private void startNearby() { nearbyRunning = true; + ModConfig config = ModConfig.instance(); service.scheduleAtFixedRate(() -> { - var config = instance().config(); if (nearbyRunning && config.nearby.enabled && shouldRun()) { - Messaging.sendDebugMessage("Starting nearby task."); instance().setNearbyPlayers(EarthMCAPI.getNearby()); - Messaging.sendDebugMessage("Finished nearby task."); + Messaging.sendDebugMessage("Updating nearby..."); } - }, 5, Math.max(instance().config().intervals.nearby, 30), TimeUnit.SECONDS); + }, 5, Math.min(config.intervals.nearby, 30), TimeUnit.SECONDS); } private void startCacheCheck() { @@ -107,4 +110,4 @@ private void startCacheCheck() { boolean shouldRun() { return ModConfig.instance().general.enableMod && MinecraftClient.getInstance().isWindowFocused(); } -} +} \ No newline at end of file diff --git a/src/main/java/net/emc/emce/utils/EarthMCAPI.java b/src/main/java/net/emc/emce/utils/EarthMCAPI.java index 2da098e..6006103 100644 --- a/src/main/java/net/emc/emce/utils/EarthMCAPI.java +++ b/src/main/java/net/emc/emce/utils/EarthMCAPI.java @@ -20,16 +20,14 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; -import static io.github.emcw.utils.GsonUtil.serialize; import static net.emc.emce.EarthMCEssentials.instance; public class EarthMCAPI { - private static final ModConfig config = ModConfig.instance(); public static APIData apiData = new APIData(); private static final String endpoints = "https://raw.githubusercontent.com/EarthMC-Toolkit/EarthMCEssentials/main/src/main/resources/api.json"; - private static EMCMap currentMap() { + public static EMCMap currentMap() { return Objects.equals(instance().mapName, "nova") ? instance().wrapper.getNova() : instance().wrapper.getAurora(); @@ -51,11 +49,28 @@ private static EMCMap currentMap() { } } + private static void refresh() { + currentMap().Players.updateCache(true); + } + + private static void clear() { + currentMap().Players.clear(); + } + + public static Map allPlayers() { + refresh(); + return currentMap().Players.all(); + } + public static Map getTownless() { + refresh(); return currentMap().Players.townless(); } - public static Map onlinePlayers() { return currentMap().Players.online(); } + public static Map onlinePlayers() { + refresh(); + return currentMap().Players.online(); + } @Nullable public static Player getOnlinePlayer(String playerName) { @@ -64,8 +79,6 @@ public static Player getOnlinePlayer(String playerName) { public static boolean clientOnline(String map) { instance().mapName = map; // getOnlinePlayer uses mapName. - - System.out.println(serialize(onlinePlayers().values())); return onlinePlayers().containsKey(clientName()); } @@ -82,16 +95,13 @@ public static Map getResidents() { } } - public static Map allPlayers() { - return currentMap().Players.all(); - } - public static @Nullable Player getPlayer(String name) { return allPlayers().getOrDefault(name, null); } @Contract(" -> new") public static @NotNull Map getNearby() { + ModConfig config = ModConfig.instance(); return getNearby(config.nearby.xBlocks, config.nearby.zBlocks); } @@ -100,24 +110,22 @@ public static Map allPlayers() { Map result = new ConcurrentHashMap<>(); try { - MinecraftClient client = MinecraftClient.getInstance(); - ClientPlayerEntity player = client.player; + ClientPlayerEntity player = MinecraftClient.getInstance().player; + // Check if client's player is valid, and we can sleep in a bed in this world. if (player == null) return result; if (!player.getEntityWorld().getDimension().bedWorks()) return result; - EMCMap curMap = currentMap(); Integer x = (int) player.getX(), - y = (int) player.getY(); + z = (int) player.getZ(); - Map nearby = curMap.Players.getNearby(allPlayers(), x, y, xBlocks, zBlocks); - nearby.remove(clientName()); - - return nearby; + result = currentMap().Players.getNearby(onlinePlayers(), x, z, xBlocks, zBlocks); + result.remove(clientName()); } catch (Exception e) { Messaging.sendDebugMessage("Error fetching nearby!", e); - return result; } + + return result; } @Contract(" -> new") diff --git a/src/main/java/net/emc/emce/utils/Messaging.java b/src/main/java/net/emc/emce/utils/Messaging.java index 481bbe6..9ccf5d4 100644 --- a/src/main/java/net/emc/emce/utils/Messaging.java +++ b/src/main/java/net/emc/emce/utils/Messaging.java @@ -3,9 +3,8 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; import net.minecraft.client.network.ClientPlayerEntity; - -import java.util.ArrayList; -import java.util.List; +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; import static net.emc.emce.EarthMCEssentials.instance; import static net.kyori.adventure.platform.fabric.FabricClientAudiences.of; @@ -15,15 +14,14 @@ public class Messaging { //#region Helper Methods - public static Component create(String key, NamedTextColor keyColour, Object... args) { - List argList = new ArrayList<>(); - for (Object obj : args) argList.add(Component.text(obj.toString())); - - return translatable().key(key).color(keyColour).args(argList).build(); + @Contract("_, _, _ -> new") + public static @NotNull Component create(String key, NamedTextColor keyColour, Component... args) { + return translatable().key(key).color(keyColour).args(args).build(); } //#endregion - private static Component prefix() { + @Contract(value = " -> new", pure = true) + private static @NotNull Component prefix() { return translatable("mod_prefix"); } @@ -60,7 +58,7 @@ public static void sendPrefixedActionBar(Component text) { //#region Send Command public static void performCommand(String cmd) { ClientPlayerEntity pl = getInstance().player; - if (pl != null) getInstance().player.networkHandler.sendCommand(cmd); + if (pl != null) pl.networkHandler.sendCommand(cmd); } //endregion diff --git a/src/main/java/net/emc/emce/utils/ModUtils.java b/src/main/java/net/emc/emce/utils/ModUtils.java index 4e9cd45..1a2f4a6 100644 --- a/src/main/java/net/emc/emce/utils/ModUtils.java +++ b/src/main/java/net/emc/emce/utils/ModUtils.java @@ -1,9 +1,11 @@ package net.emc.emce.utils; import io.github.emcw.entities.Player; -import io.github.emcw.entities.Resident; -import net.emc.emce.config.ModConfig; +import io.github.emcw.exceptions.MissingEntryException; +import lombok.Setter; +import me.shedaniel.clothconfig2.gui.ClothConfigScreen; import net.minecraft.client.MinecraftClient; +import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.network.ClientPlayNetworkHandler; import net.minecraft.client.network.ClientPlayerEntity; import net.minecraft.client.network.ServerInfo; @@ -13,13 +15,16 @@ import org.jetbrains.annotations.NotNull; import java.net.InetSocketAddress; +import java.net.SocketAddress; import java.util.*; +import static net.emc.emce.modules.OverlayRenderer.dist; +import static net.emc.emce.modules.OverlayRenderer.getRankPrefix; import static net.emc.emce.utils.EarthMCAPI.clientName; import static net.minecraft.client.MinecraftClient.getInstance; public class ModUtils { - private static @NotNull String serverName = ""; + @Setter private static @NotNull String serverName = ""; @SuppressWarnings("unused") public enum ScaleMethod { @@ -27,6 +32,14 @@ public enum ScaleMethod { Proportionate } + public enum NearbySort { + NEAREST, + FURTHEST, + TOWNLESS, + MAYOR, + NATION_LEADER + } + public enum State { BOTTOM_LEFT(0, 0), BOTTOM_RIGHT(0, 0), @@ -140,17 +153,13 @@ public static int getNearbyLongestElement(@NotNull Map nearby) { if (name.equals(clientName())) continue; ClientPlayerEntity player = Objects.requireNonNull(getInstance().player); - int distance = Math.abs(x - player.getBlockX()) + - Math.abs(z - player.getBlockZ()); + int distance = dist(x, z); - String prefix = ""; - - if (ModConfig.instance().nearby.showRank) { - if (!curPlayer.isResident()) prefix = "(Townless) "; - else { - Resident curRes = (Resident) curPlayer; - prefix = "(" + curRes.getRank() + ") "; - } + String prefix; + try { + prefix = getRankPrefix(curPlayer); + } catch (MissingEntryException e) { + continue; } MutableText nearbyText = Text.translatable(prefix + name + ": " + distance + "m"); @@ -173,11 +182,20 @@ public static int getStatusEffectOffset(Collection statusE return offset; } + public static boolean configOpen() { + Screen screen = MinecraftClient.getInstance().currentScreen; + return screen instanceof ClothConfigScreen; + } + public static boolean isConnectedToEMC() { return serverName.toLowerCase().contains("earthmc.net"); } - public static @NotNull String getServerName() { + public static void updateServerName() { + setServerName(currentServer()); + } + + public static @NotNull String currentServer() { String serverName = ""; try { @@ -191,10 +209,11 @@ public static boolean isConnectedToEMC() { else if (instance.isConnectedToRealms()) serverName = "Realms"; else if (instance.isInSingleplayer()) serverName = "Singleplayer"; else { - ClientPlayNetworkHandler clientPlayNetworkHandler = instance.getNetworkHandler(); + ClientPlayNetworkHandler networkHandler = instance.getNetworkHandler(); - if (clientPlayNetworkHandler != null) { - return ((InetSocketAddress) clientPlayNetworkHandler.getConnection().getAddress()).getHostName(); + if (networkHandler != null) { + SocketAddress address = networkHandler.getConnection().getAddress(); + return ((InetSocketAddress) address).getHostName(); } } } catch (Exception e) { @@ -203,12 +222,4 @@ public static boolean isConnectedToEMC() { return serverName; } - - public static void updateServerName() { - serverName = getServerName().toLowerCase(); - } - - public static void setServerName(@NotNull String serverName) { - ModUtils.serverName = serverName; - } -} +} \ No newline at end of file diff --git a/src/main/resources/assets/emce/lang/en_us.json b/src/main/resources/assets/emce/lang/en_us.json index bf8e0d4..bf5386d 100644 --- a/src/main/resources/assets/emce/lang/en_us.json +++ b/src/main/resources/assets/emce/lang/en_us.json @@ -40,7 +40,7 @@ "text_nationinfo_capital": "Capital: %s", "text_nationinfo_area": "Area: %s", "text_nationinfo_towns": "Towns: %s", - "text_nationinfo_err": "§cNation %s is not registered.", + "text_nationinfo_err": "§cNation %s §cis not registered.", "text_nationinfo_not_registered": "§cYour nation is not registered.", "text_alliance_header": "Alliance Information - %s - #%s", @@ -53,9 +53,9 @@ "text_shared_area": "Area: %s", "text_shared_residents": "Residents: %d", - "text_shared_notregistered": "§cResident %s is not registered.", + "text_shared_notregistered": "§cPlayer %s §cis not a resident!", - "text.autoconfig.emc-essentials.title": "EarthMC Essentials Config", + "text.autoconfig.emc-essentials.title": "§n§aEarthMC Essentials Config", "text.autoconfig.emc-essentials.category.General": "General", "text.autoconfig.emc-essentials.option.general.enableMod": "Enable Mod", @@ -76,6 +76,7 @@ "text.autoconfig.emc-essentials.option.nearby.showRank": "Show Rank", "text.autoconfig.emc-essentials.option.nearby.presetPositions": "Use Preset Positions", "text.autoconfig.emc-essentials.option.nearby.positionState": "Preset Position", + "text.autoconfig.emc-essentials.option.nearby.nearbySort": "Sort Order", "text.autoconfig.emc-essentials.option.nearby.xPos": "Horizontal Position (X)", "text.autoconfig.emc-essentials.option.nearby.yPos": "Vertical Position (Y)", "text.autoconfig.emc-essentials.option.nearby.headingTextColour": "Heading Colour", From a0c60ff5bd1f83182105bdb664e50c911a263d02 Mon Sep 17 00:00:00 2001 From: Owen Stubbs Date: Mon, 10 Apr 2023 21:59:22 +0100 Subject: [PATCH 19/19] 1.19.3 ready --- build.gradle | 2 +- .../java/net/emc/emce/config/ModConfig.java | 13 ++--- .../mixins/SessionEventListenerMixin.java | 17 ++----- .../net/emc/emce/modules/OverlayRenderer.java | 50 +++++++++++-------- .../java/net/emc/emce/utils/ModUtils.java | 6 +-- 5 files changed, 44 insertions(+), 44 deletions(-) diff --git a/build.gradle b/build.gradle index 7174f19..705a83a 100644 --- a/build.gradle +++ b/build.gradle @@ -1,5 +1,5 @@ plugins { - id 'fabric-loom' version '1.0-SNAPSHOT' + id 'fabric-loom' version '1.1-SNAPSHOT' } sourceCompatibility = JavaVersion.VERSION_17 diff --git a/src/main/java/net/emc/emce/config/ModConfig.java b/src/main/java/net/emc/emce/config/ModConfig.java index 45c5b19..436b250 100644 --- a/src/main/java/net/emc/emce/config/ModConfig.java +++ b/src/main/java/net/emc/emce/config/ModConfig.java @@ -52,8 +52,9 @@ public static class General { public static class Townless { @Comment("Toggles townless players on or off.") public boolean enabled = true; - @Comment("The maximum length the townless list can be. < 1 for no limit.") - public int maxLength = 10; // < 1 = No limit + @Comment("The maximum amount of players shown before wrapping.") + @BoundedDiscrete(min = 3, max = 24) + public int maxLength = 12; // < 1 = No limit @Comment("Toggles the use of preset positions, uses sliders if off.") public boolean presetPositions = true; @@ -61,9 +62,9 @@ public static class Townless { @Comment("The position of the Townless info.") public State positionState = State.RIGHT; - @Comment("Note: Only used if Use Preset Positions is off.") + @Comment("Note: No effect when 'Use Preset Positions' is on.") public int xPos = 1; - @Comment("Note: Only used if Use Preset Positions is off.") + @Comment("Note: No effect when 'Use Preset Positions' is on.") public int yPos = 16; @EnumHandler(option = DROPDOWN) @@ -83,10 +84,10 @@ public static class Nearby { public boolean presetPositions = true; @EnumHandler(option = BUTTON) - public State positionState = State.TOP_RIGHT; + public State positionState = State.LEFT; @EnumHandler(option = BUTTON) - @Comment("Determines order of the nearby players list before rendering.") + @Comment("Determines order of importance when sorting Nearby Players. Only affects the HUD.") public NearbySort nearbySort = NearbySort.NEAREST; @Comment("The horizontal position on the HUD.") diff --git a/src/main/java/net/emc/emce/mixins/SessionEventListenerMixin.java b/src/main/java/net/emc/emce/mixins/SessionEventListenerMixin.java index 258dc87..8cd0892 100644 --- a/src/main/java/net/emc/emce/mixins/SessionEventListenerMixin.java +++ b/src/main/java/net/emc/emce/mixins/SessionEventListenerMixin.java @@ -2,7 +2,7 @@ import net.emc.emce.modules.OverlayRenderer; import net.emc.emce.utils.Messaging; -import net.minecraft.client.MinecraftClientGame; +import net.minecraft.client.ClientGameSession; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -16,10 +16,10 @@ import static net.emc.emce.utils.ModUtils.isConnectedToEMC; import static net.emc.emce.utils.ModUtils.updateServerName; -@Mixin(MinecraftClientGame.class) +@Mixin(ClientGameSession.class) public abstract class SessionEventListenerMixin { - @Inject(at = @At("TAIL"), method="onStartGameSession") - public void onStartGameSession(CallbackInfo ci) { + @Inject(at = @At("TAIL"), method="") + public void onInit(CallbackInfo ci) { System.out.println("EMCE > New game session detected."); updateServerName(); @@ -43,15 +43,6 @@ public void onStartGameSession(CallbackInfo ci) { } } - @Inject(at = @At("TAIL"), method="onLeaveGameSession") - public void onLeaveGameSession(CallbackInfo ci) { - if(isConnectedToEMC()) - updateSessionCounter('-'); - - updateServerName(); - OverlayRenderer.Clear(); - } - void updateSessionCounter(char type) { int oldCount = instance().sessionCounter; diff --git a/src/main/java/net/emc/emce/modules/OverlayRenderer.java b/src/main/java/net/emc/emce/modules/OverlayRenderer.java index 13ed0dc..a9987a6 100644 --- a/src/main/java/net/emc/emce/modules/OverlayRenderer.java +++ b/src/main/java/net/emc/emce/modules/OverlayRenderer.java @@ -16,8 +16,8 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import java.util.Objects; import java.util.concurrent.CopyOnWriteArrayList; +import java.util.stream.Stream; import static io.github.emcw.utils.GsonUtil.streamEntries; import static java.util.stream.Collectors.toMap; @@ -97,6 +97,20 @@ public static int dist(int x, int z) { Math.abs(z - (int) client.player.getZ()); } + public static int closest(Player p1, Player p2) { + Location loc1 = p1.getLocation(); + Integer dist1 = dist(loc1.getX(), loc1.getZ()); + + Location loc2 = p2.getLocation(); + Integer dist2 = dist(loc2.getX(), loc2.getZ()); + + return dist1.compareTo(dist2); + } + + public static Map collectSorted(Stream> entries) { + return entries.collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (k1, k2) -> k1, LinkedHashMap::new)); + } + public static @Nullable MutableText prefixedPlayerDistance(@NotNull Player player) throws MissingEntryException { Formatting playerTextFormatting = Formatting.byName(config.nearby.playerTextColour.name()); @@ -113,29 +127,23 @@ public static int dist(int x, int z) { return translatable(prefix + name + ": " + distance + "m").formatted(playerTextFormatting); } - static LinkedHashMap sortByDistance(Map players, boolean acsending) { - return streamEntries(players).sorted((o1, o2) -> { - Location loc1 = o1.getValue().getLocation(); - Integer dist1 = dist(loc1.getX(), loc1.getZ()); - - Location loc2 = o2.getValue().getLocation(); - Integer dist2 = dist(loc2.getX(), loc2.getZ()); - - return acsending ? dist1.compareTo(dist2) : dist2.compareTo(dist1); - }).collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (k1, k2) -> k1, LinkedHashMap::new)); + static Map sortByDistance(Map players, boolean acsending) { + return collectSorted(streamEntries(players).sorted((o1, o2) -> + closest(o1.getValue(), o2.getValue()) + )); } - static LinkedHashMap sortByRank(Map players, String rank) { - return streamEntries(players).sorted((o1, o2) -> { - if (Objects.equals(rank, "townless")) { - Boolean cur = !o1.getValue().isResident(); - Boolean next = !o2.getValue().isResident(); + static Map sortByTownless(Map players) { + return collectSorted(streamEntries(players).sorted((o1, o2) -> { + Player p1 = o1.getValue(), p2 = o2.getValue(); + boolean res1 = p1.isResident(), res2 = p2.isResident(); - return cur.compareTo(next); - } + if (res1 && res2) return -1; // Both residents, ignore. + if (!res1 && !res2) return closest(p1, p2); // Both townless, sort by closest. - return 0; - }).collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (k1, k2) -> k1, LinkedHashMap::new)); + // Different results, sort by whoever is townless. + return Boolean.compare(res1, res2); + })); } private static void RenderTownless(boolean usingPreset) { @@ -210,7 +218,7 @@ private static void RenderNearby(boolean usingPreset) { switch (config.nearby.nearbySort) { case NEAREST -> nearby = sortByDistance(nearby, true); case FURTHEST -> nearby = sortByDistance(nearby, false); - case TOWNLESS -> nearby = sortByRank(nearby, "townless"); + case TOWNLESS -> nearby = sortByTownless(nearby); } Formatting nearbyTextFormatting = Formatting.byName(config.nearby.headingTextColour.name()); diff --git a/src/main/java/net/emc/emce/utils/ModUtils.java b/src/main/java/net/emc/emce/utils/ModUtils.java index 1a2f4a6..19094f8 100644 --- a/src/main/java/net/emc/emce/utils/ModUtils.java +++ b/src/main/java/net/emc/emce/utils/ModUtils.java @@ -35,9 +35,9 @@ public enum ScaleMethod { public enum NearbySort { NEAREST, FURTHEST, - TOWNLESS, - MAYOR, - NATION_LEADER + TOWNLESS +// MAYOR, +// NATION_LEADER } public enum State {