Skip to content

Commit

Permalink
Migrate JsonUtils methods to mantle's JsonHelper
Browse files Browse the repository at this point in the history
  • Loading branch information
KnightMiner committed Jun 4, 2022
1 parent f82ea56 commit cd13f7b
Show file tree
Hide file tree
Showing 8 changed files with 32 additions and 124 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@
import net.minecraftforge.fml.ModLoader;
import net.minecraftforge.fml.event.IModBusEvent;
import slimeknights.mantle.data.IEarlySafeManagerReloadListener;
import slimeknights.mantle.util.JsonHelper;
import slimeknights.tconstruct.common.config.Config;
import slimeknights.tconstruct.library.client.model.tools.MaterialModel;
import slimeknights.tconstruct.library.modifiers.ModifierId;
import slimeknights.tconstruct.library.utils.JsonUtils;

import javax.annotation.Nullable;
import java.util.Collection;
Expand Down Expand Up @@ -94,7 +94,7 @@ public void onReloadSafe(ResourceManager manager) {
Map<ModifierId,IUnbakedModifierModel> models = new HashMap<>();

// get a list of files from all namespaces
List<JsonObject> jsonFiles = JsonUtils.getFileInAllDomainsAndPacks(manager, VISIBLE_MODIFIERS);
List<JsonObject> jsonFiles = JsonHelper.getFileInAllDomainsAndPacks(manager, VISIBLE_MODIFIERS, null);
// first object is bottom most pack, so upper resource packs will replace it
for (int i = jsonFiles.size() - 1; i >= 0; i--) {
JsonObject json = jsonFiles.get(i);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import net.minecraft.world.item.TooltipFlag;
import net.minecraftforge.registries.ForgeRegistries;
import slimeknights.mantle.data.GenericLoaderRegistry.IGenericLoader;
import slimeknights.mantle.util.JsonHelper;
import slimeknights.tconstruct.library.json.predicate.IJsonPredicate;
import slimeknights.tconstruct.library.json.predicate.entity.LivingEntityPredicate;
import slimeknights.tconstruct.library.modifiers.Modifier;
Expand Down Expand Up @@ -88,7 +89,7 @@ public ConditionalDamageModifier deserialize(JsonObject json) {
int level = 0;
if (json.has("effect")) {
JsonObject effectJson = GsonHelper.getAsJsonObject(json, "effect");
effect = JsonUtils.getAsEntry(ForgeRegistries.MOB_EFFECTS, effectJson, "name");
effect = JsonHelper.getAsEntry(ForgeRegistries.MOB_EFFECTS, effectJson, "name");
level = JsonUtils.getIntMin(effectJson, "level", 1);
}
return new ConditionalDamageModifier(predicate, damage, effect, level);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@
import net.minecraft.world.item.enchantment.Enchantment;
import net.minecraftforge.registries.ForgeRegistries;
import slimeknights.mantle.data.GenericLoaderRegistry.IGenericLoader;
import slimeknights.mantle.util.JsonHelper;
import slimeknights.tconstruct.library.modifiers.Modifier;
import slimeknights.tconstruct.library.modifiers.hooks.IArmorLootModifier;
import slimeknights.tconstruct.library.modifiers.util.ModifierLevelDisplay;
import slimeknights.tconstruct.library.tools.context.ToolHarvestContext;
import slimeknights.tconstruct.library.tools.nbt.IToolStackView;
import slimeknights.tconstruct.library.utils.JsonUtils;

import javax.annotation.Nullable;
import java.util.Objects;
Expand Down Expand Up @@ -75,7 +75,7 @@ public LootModifier deserialize(JsonObject json) {
int enchantmentLevel = 0;
if (json.has("enchantment")) {
JsonObject enchantmentJson = GsonHelper.getAsJsonObject(json, "enchantment");
enchantment = JsonUtils.getAsEntry(ForgeRegistries.ENCHANTMENTS, enchantmentJson, "name");
enchantment = JsonHelper.getAsEntry(ForgeRegistries.ENCHANTMENTS, enchantmentJson, "name");
enchantmentLevel = GsonHelper.getAsInt(enchantmentJson, "level");
}
int looting = GsonHelper.getAsInt(json, "looting", 0);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@
import net.minecraft.world.entity.EquipmentSlot.Type;
import net.minecraftforge.registries.ForgeRegistries;
import slimeknights.mantle.data.GenericLoaderRegistry.IGenericLoader;
import slimeknights.mantle.util.JsonHelper;
import slimeknights.tconstruct.TConstruct;
import slimeknights.tconstruct.library.modifiers.Modifier;
import slimeknights.tconstruct.library.modifiers.impl.NoLevelsModifier;
import slimeknights.tconstruct.library.tools.capability.TinkerDataCapability.TinkerDataKey;
import slimeknights.tconstruct.library.tools.context.EquipmentChangeContext;
import slimeknights.tconstruct.library.tools.nbt.IToolStackView;
import slimeknights.tconstruct.library.utils.JsonUtils;

import java.util.Objects;

Expand All @@ -26,7 +26,7 @@ public class MobDisguiseModifier extends NoLevelsModifier {
public static final IGenericLoader<MobDisguiseModifier> LOADER = new IGenericLoader<MobDisguiseModifier>() {
@Override
public MobDisguiseModifier deserialize(JsonObject json) {
return new MobDisguiseModifier(JsonUtils.getAsEntry(ForgeRegistries.ENTITIES, json, "entity"));
return new MobDisguiseModifier(JsonHelper.getAsEntry(ForgeRegistries.ENTITIES, json, "entity"));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@
import slimeknights.tconstruct.library.tools.stat.INumericToolStat;
import slimeknights.tconstruct.library.tools.stat.IToolStat;
import slimeknights.tconstruct.library.tools.stat.ModifierStatsBuilder;
import slimeknights.tconstruct.library.utils.JsonUtils;

import javax.annotation.Nullable;
import java.util.Collections;
Expand Down Expand Up @@ -106,7 +105,7 @@ public IGenericLoader<? extends Modifier> getLoader() {
public StatBoostModifier deserialize(JsonObject json) {
Rarity rarity = null;
if (json.has("rarity")) {
rarity = JsonUtils.getAsEnum(json, "rarity", Rarity.class);
rarity = JsonHelper.getAsEnum(json, "rarity", Rarity.class);
}
List<ModifierStatBoost> stats = Collections.emptyList();
if (json.has("stats")) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import net.minecraft.world.entity.LivingEntity;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.registries.ForgeRegistries;
import slimeknights.mantle.util.JsonHelper;
import slimeknights.tconstruct.TConstruct;
import slimeknights.tconstruct.library.modifiers.spilling.ISpillingEffect;
import slimeknights.tconstruct.library.tools.context.ToolAttackContext;
Expand Down Expand Up @@ -36,5 +37,5 @@ public JsonObject serialize(JsonSerializationContext context) {

/** Loader instance */
public static final JsonDeserializer<RemoveEffectSpillingEffect> LOADER = (json, typeOfT, context) ->
new RemoveEffectSpillingEffect(JsonUtils.getAsEntry(ForgeRegistries.MOB_EFFECTS, json.getAsJsonObject(), "effect"));
new RemoveEffectSpillingEffect(JsonHelper.getAsEntry(ForgeRegistries.MOB_EFFECTS, json.getAsJsonObject(), "effect"));
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
import net.minecraftforge.registries.ForgeRegistries;
import slimeknights.mantle.util.JsonHelper;
import slimeknights.tconstruct.library.tools.nbt.IToolStackView;
import slimeknights.tconstruct.library.utils.JsonUtils;

import java.util.List;
import java.util.Locale;
Expand Down Expand Up @@ -87,8 +86,8 @@ public JsonObject toJson() {
/** Parses the modifier attribute from JSON */
public static ModifierAttribute fromJson(JsonObject json) {
String unique = GsonHelper.getAsString(json, "unique");
Attribute attribute = JsonUtils.getAsEntry(ForgeRegistries.ATTRIBUTES, json, "attribute");
Operation op = JsonUtils.getAsEnum(json, "operation", Operation.class);
Attribute attribute = JsonHelper.getAsEntry(ForgeRegistries.ATTRIBUTES, json, "attribute");
Operation op = JsonHelper.getAsEnum(json, "operation", Operation.class);
float amount = GsonHelper.getAsFloat(json, "amount");
List<EquipmentSlot> slots = JsonHelper.parseList(json, "slots", (element, string) -> EquipmentSlot.byName(GsonHelper.convertToString(element, string)));
return new ModifierAttribute(unique, attribute, op, amount, slots);
Expand Down
130 changes: 19 additions & 111 deletions src/main/java/slimeknights/tconstruct/library/utils/JsonUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,20 @@

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSyntaxException;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.packs.resources.Resource;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.util.GsonHelper;
import net.minecraftforge.event.OnDatapackSyncEvent;
import net.minecraftforge.network.PacketDistributor;
import net.minecraftforge.network.PacketDistributor.PacketTarget;
import net.minecraftforge.registries.IForgeRegistry;
import net.minecraftforge.registries.IForgeRegistryEntry;
import slimeknights.mantle.network.packet.ISimplePacket;
import slimeknights.mantle.util.JsonHelper;
import slimeknights.tconstruct.TConstruct;
import slimeknights.tconstruct.common.network.TinkerNetwork;

import javax.annotation.Nullable;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.stream.Stream;

/** Helpers for a few JSON related tasks */
public class JsonUtils {
Expand Down Expand Up @@ -66,125 +53,46 @@ public static int getIntMin(JsonElement json, String key, int min) {
return value;
}

/**
* Parses a registry entry from JSON
* @param registry Registry
* @param element Element to deserialize
* @param key Json key
* @param <T> Object type
* @return Registry value
* @throws JsonSyntaxException If something failed to parse
*/
/** @deprecated use {@link JsonHelper#convertToEntry(IForgeRegistry, JsonElement, String)} */
@Deprecated
public static <T extends IForgeRegistryEntry<T>> T convertToEntry(IForgeRegistry<T> registry, JsonElement element, String key) {
ResourceLocation name = JsonHelper.convertToResourceLocation(element, key);
if (registry.containsKey(name)) {
T value = registry.getValue(name);
if (value != null) {
return value;
}
}
throw new JsonSyntaxException("Unknown " + registry.getRegistryName() + " " + name);
return JsonHelper.convertToEntry(registry, element, key);
}

/**
* Parses a registry entry from JSON
* @param registry Registry
* @param parent Parent JSON object
* @param key Json key
* @param <T> Object type
* @return Registry value
* @throws JsonSyntaxException If something failed to parse
*/
/** @deprecated use {@link JsonHelper#getAsEntry(IForgeRegistry, JsonObject, String)} */
@Deprecated
public static <T extends IForgeRegistryEntry<T>> T getAsEntry(IForgeRegistry<T> registry, JsonObject parent, String key) {
return convertToEntry(registry, JsonHelper.getElement(parent, key), key);
return JsonHelper.getAsEntry(registry, parent, key);
}

/**
* Converts the resource into a JSON file
* @param resource Resource to read. Closed when done
* @return JSON object, or null if failed to parse
*/
/** @deprecated use {@link JsonHelper#getJson(Resource)} */
@Deprecated
@Nullable
public static JsonObject getJson(Resource resource) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8))) {
return GsonHelper.parse(reader);
} catch (JsonParseException | IOException e) {
TConstruct.LOG.error("Failed to load JSON from resource " + resource.getLocation(), e);
return null;
}
return JsonHelper.getJson(resource);
}

/** Parses an enum from its name */
private static <T extends Enum<T>> T enumByName(String name, Class<T> enumClass) {
for (T value : enumClass.getEnumConstants()) {
if (value.name().toLowerCase(Locale.ROOT).equals(name)) {
return value;
}
}
throw new JsonSyntaxException("Invalid " + enumClass.getSimpleName() + " " + name);
}

/** Gets an enum value from its string name */
/** @deprecated use {@link JsonHelper#convertToEnum(JsonElement, String, Class)} */
@Deprecated
public static <T extends Enum<T>> T convertToEnum(JsonElement element, String key, Class<T> enumClass) {
String name = GsonHelper.convertToString(element, key);
return enumByName(name, enumClass);
return JsonHelper.convertToEnum(element, key, enumClass);
}

/** Gets an enum value from its string name */
/** @deprecated use {@link JsonHelper#getAsEnum(JsonObject, String, Class)} */
@Deprecated
public static <T extends Enum<T>> T getAsEnum(JsonObject json, String key, Class<T> enumClass) {
String name = GsonHelper.getAsString(json, key);
return enumByName(name, enumClass);
return JsonHelper.getAsEnum(json, key, enumClass);
}

/** Gets a list of JSON objects for a single path in all domains and packs, for a language file like loader */
/** @deprecated use {@link JsonHelper#getFileInAllDomainsAndPacks(ResourceManager, String, String)} */
@Deprecated
public static List<JsonObject> getFileInAllDomainsAndPacks(ResourceManager manager, String path) {
return manager
.getNamespaces().stream()
.filter(ResourceLocation::isValidNamespace)
.flatMap(namespace -> {
ResourceLocation location = new ResourceLocation(namespace, path);
try {
return manager.getResources(location).stream();
} catch (FileNotFoundException e) {
// suppress, the above method throws instead of returning empty
} catch (IOException e) {
TConstruct.LOG.error("Failed to load JSON files from {}", location, e);
}
return Stream.empty();
})
.map(JsonUtils::getJson)
.filter(Objects::nonNull).toList();
}

/** Sends the packet to the given player */
private static void sendPackets(ServerPlayer player, ISimplePacket[] packets) {
// on an integrated server, the modifier registries have a single instance on both the client and the server thread
// this means syncing is unneeded, and has the side-effect of recreating all the modifier instances (which can lead to unexpected behavior)
// as a result, integrated servers just mark fullyLoaded as true without syncing anything, side-effect is listeners may run twice on single player

// on a dedicated server, the client is running a separate game instance, this is where we send packets, plus fully loaded should already be true
// this event is not fired when connecting to a server
if (!player.connection.getConnection().isMemoryConnection()) {
TinkerNetwork network = TinkerNetwork.getInstance();
PacketTarget target = PacketDistributor.PLAYER.with(() -> player);
for (ISimplePacket packet : packets) {
network.send(target, packet);
}
}
return JsonHelper.getFileInAllDomainsAndPacks(manager, path, null);
}

/** Called when the player logs in to send packets */
public static void syncPackets(OnDatapackSyncEvent event, ISimplePacket... packets) {
// send to single player
ServerPlayer targetedPlayer = event.getPlayer();
if (targetedPlayer != null) {
sendPackets(targetedPlayer, packets);
} else {
// send to all players
for (ServerPlayer player : event.getPlayerList().getPlayers()) {
sendPackets(player, packets);
}
}
JsonHelper.syncPackets(event, TinkerNetwork.getInstance(), packets);
}

/** Creates a JSON object with the given key set to a resource location */
Expand Down

0 comments on commit cd13f7b

Please sign in to comment.