Search in sources :

Example 16 with ResourceLocation

use of net.minecraft.resources.ResourceLocation in project MinecraftForge by MinecraftForge.

the class LootModifierManager method apply.

@Override
protected void apply(Map<ResourceLocation, JsonElement> resourceList, ResourceManager resourceManagerIn, ProfilerFiller profilerIn) {
    Builder<ResourceLocation, IGlobalLootModifier> builder = ImmutableMap.builder();
    // old way (for reference)
    /*Map<IGlobalLootModifier, ResourceLocation> toLocation = new HashMap<IGlobalLootModifier, ResourceLocation>();
        resourceList.forEach((location, object) -> {
            try {
                IGlobalLootModifier modifier = deserializeModifier(location, object);
                builder.put(location, modifier);
                toLocation.put(modifier, location);
            } catch (Exception exception) {
                LOGGER.error("Couldn't parse loot modifier {}", location, exception);
            }
        });
        builder.orderEntriesByValue((x,y) -> {
            return toLocation.get(x).compareTo(toLocation.get(y));
        });*/
    // new way
    ArrayList<ResourceLocation> finalLocations = new ArrayList<ResourceLocation>();
    ResourceLocation resourcelocation = new ResourceLocation("forge", "loot_modifiers/global_loot_modifiers.json");
    try {
        // read in all data files from forge:loot_modifiers/global_loot_modifiers in order to do layering
        for (Resource iresource : resourceManagerIn.getResources(resourcelocation)) {
            try (InputStream inputstream = iresource.getInputStream();
                Reader reader = new BufferedReader(new InputStreamReader(inputstream, StandardCharsets.UTF_8))) {
                JsonObject jsonobject = GsonHelper.fromJson(GSON_INSTANCE, reader, JsonObject.class);
                boolean replace = jsonobject.get("replace").getAsBoolean();
                if (replace)
                    finalLocations.clear();
                JsonArray entryList = jsonobject.get("entries").getAsJsonArray();
                for (JsonElement entry : entryList) {
                    String loc = entry.getAsString();
                    ResourceLocation res = new ResourceLocation(loc);
                    if (finalLocations.contains(res))
                        finalLocations.remove(res);
                    finalLocations.add(res);
                }
            } catch (RuntimeException | IOException ioexception) {
                LOGGER.error("Couldn't read global loot modifier list {} in data pack {}", resourcelocation, iresource.getSourceName(), ioexception);
            } finally {
                IOUtils.closeQuietly((Closeable) iresource);
            }
        }
    } catch (IOException ioexception1) {
        LOGGER.error("Couldn't read global loot modifier list from {}", resourcelocation, ioexception1);
    }
    // use layered config to fetch modifier data files (modifiers missing from config are disabled)
    finalLocations.forEach(location -> {
        try {
            IGlobalLootModifier modifier = deserializeModifier(location, resourceList.get(location));
            if (modifier != null)
                builder.put(location, modifier);
        } catch (Exception exception) {
            LOGGER.error("Couldn't parse loot modifier {}", location, exception);
        }
    });
    ImmutableMap<ResourceLocation, IGlobalLootModifier> immutablemap = builder.build();
    this.registeredLootModifiers = immutablemap;
}
Also used : InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) Resource(net.minecraft.server.packs.resources.Resource) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) JsonObject(com.google.gson.JsonObject) IOException(java.io.IOException) IOException(java.io.IOException) JsonArray(com.google.gson.JsonArray) JsonElement(com.google.gson.JsonElement) ResourceLocation(net.minecraft.resources.ResourceLocation) BufferedReader(java.io.BufferedReader)

Example 17 with ResourceLocation

use of net.minecraft.resources.ResourceLocation in project MinecraftForge by MinecraftForge.

the class LootModifierManager method deserializeModifier.

private IGlobalLootModifier deserializeModifier(ResourceLocation location, JsonElement element) {
    if (!element.isJsonObject())
        return null;
    JsonObject object = element.getAsJsonObject();
    LootItemCondition[] lootConditions = GSON_INSTANCE.fromJson(object.get("conditions"), LootItemCondition[].class);
    ResourceLocation serializer = new ResourceLocation(GsonHelper.getAsString(object, "type"));
    return ForgeRegistries.LOOT_MODIFIER_SERIALIZERS.getValue(serializer).read(location, object, lootConditions);
}
Also used : LootItemCondition(net.minecraft.world.level.storage.loot.predicates.LootItemCondition) ResourceLocation(net.minecraft.resources.ResourceLocation) JsonObject(com.google.gson.JsonObject)

Example 18 with ResourceLocation

use of net.minecraft.resources.ResourceLocation in project MinecraftForge by MinecraftForge.

the class ForgeHooksClient method processForgeListPingData.

public static void processForgeListPingData(ServerStatus packet, ServerData target) {
    if (packet.getForgeData() != null) {
        final Map<String, String> mods = packet.getForgeData().getRemoteModData();
        final Map<ResourceLocation, Pair<String, Boolean>> remoteChannels = packet.getForgeData().getRemoteChannels();
        final int fmlver = packet.getForgeData().getFMLNetworkVersion();
        boolean fmlNetMatches = fmlver == NetworkConstants.FMLNETVERSION;
        boolean channelsMatch = NetworkRegistry.checkListPingCompatibilityForClient(remoteChannels);
        AtomicBoolean result = new AtomicBoolean(true);
        final List<String> extraClientMods = new ArrayList<>();
        ModList.get().forEachModContainer((modid, mc) -> mc.getCustomExtension(IExtensionPoint.DisplayTest.class).ifPresent(ext -> {
            boolean foundModOnServer = ext.remoteVersionTest().test(mods.get(modid), true);
            result.compareAndSet(true, foundModOnServer);
            if (!foundModOnServer) {
                extraClientMods.add(modid);
            }
        }));
        boolean modsMatch = result.get();
        final Map<String, String> extraServerMods = mods.entrySet().stream().filter(e -> !Objects.equals(NetworkConstants.IGNORESERVERONLY, e.getValue())).filter(e -> !ModList.get().isLoaded(e.getKey())).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        LOGGER.debug(CLIENTHOOKS, "Received FML ping data from server at {}: FMLNETVER={}, mod list is compatible : {}, channel list is compatible: {}, extra server mods: {}", target.ip, fmlver, modsMatch, channelsMatch, extraServerMods);
        String extraReason = null;
        if (!extraServerMods.isEmpty()) {
            extraReason = "fml.menu.multiplayer.extraservermods";
            LOGGER.info(CLIENTHOOKS, ForgeI18n.parseMessage(extraReason) + ": {}", extraServerMods.entrySet().stream().map(e -> e.getKey() + "@" + e.getValue()).collect(Collectors.joining(", ")));
        }
        if (!modsMatch) {
            extraReason = "fml.menu.multiplayer.modsincompatible";
            LOGGER.info(CLIENTHOOKS, "Client has mods that are missing on server: {}", extraClientMods);
        }
        if (!channelsMatch) {
            extraReason = "fml.menu.multiplayer.networkincompatible";
        }
        if (fmlver < NetworkConstants.FMLNETVERSION) {
            extraReason = "fml.menu.multiplayer.serveroutdated";
        }
        if (fmlver > NetworkConstants.FMLNETVERSION) {
            extraReason = "fml.menu.multiplayer.clientoutdated";
        }
        target.forgeData = new ExtendedServerListData("FML", extraServerMods.isEmpty() && fmlNetMatches && channelsMatch && modsMatch, mods.size(), extraReason, packet.getForgeData().isTruncated());
    } else {
        target.forgeData = new ExtendedServerListData("VANILLA", NetworkRegistry.canConnectToVanillaServer(), 0, null);
    }
}
Also used : Camera(net.minecraft.client.Camera) Font(net.minecraft.client.gui.Font) Arrays(java.util.Arrays) Connection(net.minecraft.network.Connection) ForgeMod(net.minecraftforge.common.ForgeMod) Dist(net.minecraftforge.api.distmarker.Dist) net.minecraftforge.fml(net.minecraftforge.fml) Pair(org.apache.commons.lang3.tuple.Pair) MultiPlayerGameMode(net.minecraft.client.multiplayer.MultiPlayerGameMode) Map(java.util.Map) AbstractClientPlayer(net.minecraft.client.player.AbstractClientPlayer) SubscribeEvent(net.minecraftforge.eventbus.api.SubscribeEvent) TooltipComponent(net.minecraft.world.inventory.tooltip.TooltipComponent) WorldPreset(net.minecraft.client.gui.screens.worldselection.WorldPreset) TranslatableComponent(net.minecraft.network.chat.TranslatableComponent) Window(com.mojang.blaze3d.platform.Window) ForgeVersion(net.minecraftforge.versions.forge.ForgeVersion) SoundInstance(net.minecraft.client.resources.sounds.SoundInstance) Screen(net.minecraft.client.gui.screens.Screen) ResourceManager(net.minecraft.server.packs.resources.ResourceManager) Set(java.util.Set) Language(net.minecraft.locale.Language) NetworkRegistry(net.minecraftforge.network.NetworkRegistry) TextComponent(net.minecraft.network.chat.TextComponent) Logger(org.apache.logging.log4j.Logger) Stream(java.util.stream.Stream) FormattedText(net.minecraft.network.chat.FormattedText) FluidState(net.minecraft.world.level.material.FluidState) ForgeI18n(net.minecraftforge.common.ForgeI18n) ItemStack(net.minecraft.world.item.ItemStack) GameType(net.minecraft.world.level.GameType) ForgeRegistries(net.minecraftforge.registries.ForgeRegistries) BETA(net.minecraftforge.fml.VersionChecker.Status.BETA) Resource(net.minecraft.server.packs.resources.Resource) WorldGenSettings(net.minecraft.world.level.levelgen.WorldGenSettings) com.mojang.blaze3d.vertex(com.mojang.blaze3d.vertex) HumanoidArm(net.minecraft.world.entity.HumanoidArm) BlockState(net.minecraft.world.level.block.state.BlockState) ClientLevel(net.minecraft.client.multiplayer.ClientLevel) Supplier(java.util.function.Supplier) Vector3f(com.mojang.math.Vector3f) ArrayList(java.util.ArrayList) I18n(net.minecraft.client.resources.language.I18n) MouseHandler(net.minecraft.client.MouseHandler) AttributeInstance(net.minecraft.world.entity.ai.attributes.AttributeInstance) ModelManager(net.minecraft.client.resources.model.ModelManager) TitleScreen(net.minecraft.client.gui.screens.TitleScreen) Marker(org.apache.logging.log4j.Marker) Nullable(javax.annotation.Nullable) TextureAtlasSprite(net.minecraft.client.renderer.texture.TextureAtlasSprite) BlockAndTintGetter(net.minecraft.world.level.BlockAndTintGetter) ServerData(net.minecraft.client.multiplayer.ServerData) BakedModel(net.minecraft.client.resources.model.BakedModel) Transformation(com.mojang.math.Transformation) ItemTransforms(net.minecraft.client.renderer.block.model.ItemTransforms) Component(net.minecraft.network.chat.Component) MobEffectInstance(net.minecraft.world.effect.MobEffectInstance) TransformationHelper(net.minecraftforge.common.model.TransformationHelper) IOException(java.io.IOException) NarratorChatListener(net.minecraft.client.gui.chat.NarratorChatListener) File(java.io.File) ItemRenderer(net.minecraft.client.renderer.entity.ItemRenderer) LerpingBossEvent(net.minecraft.client.gui.components.LerpingBossEvent) MinecraftForge(net.minecraftforge.common.MinecraftForge) EquipmentSlot(net.minecraft.world.entity.EquipmentSlot) RenderSystem(com.mojang.blaze3d.systems.RenderSystem) ClientTooltipComponent(net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent) InteractionHand(net.minecraft.world.InteractionHand) Material(net.minecraft.client.resources.model.Material) net.minecraftforge.client.event(net.minecraftforge.client.event) ResourceLocation(net.minecraft.resources.ResourceLocation) Either(com.mojang.datafixers.util.Either) LivingEntity(net.minecraft.world.entity.LivingEntity) TextureAtlas(net.minecraft.client.renderer.texture.TextureAtlas) Direction(net.minecraft.core.Direction) Matrix4f(com.mojang.math.Matrix4f) Random(java.util.Random) ServerStatus(net.minecraft.network.protocol.status.ServerStatus) ForgeTextureMetadata(net.minecraftforge.client.textures.ForgeTextureMetadata) GameData(net.minecraftforge.registries.GameData) ChatFormatting(net.minecraft.ChatFormatting) BETA_OUTDATED(net.minecraftforge.fml.VersionChecker.Status.BETA_OUTDATED) FogMode(net.minecraft.client.renderer.FogRenderer.FogMode) Event(net.minecraftforge.eventbus.api.Event) Input(net.minecraft.client.player.Input) ImmutableMap(com.google.common.collect.ImmutableMap) BlockHitResult(net.minecraft.world.phys.BlockHitResult) Matrix3f(com.mojang.math.Matrix3f) Collectors(java.util.stream.Collectors) Player(net.minecraft.world.entity.player.Player) Objects(java.util.Objects) MarkerManager(org.apache.logging.log4j.MarkerManager) List(java.util.List) RecipeManager(net.minecraft.world.item.crafting.RecipeManager) BlockPos(net.minecraft.core.BlockPos) Optional(java.util.Optional) BOSSINFO(net.minecraftforge.client.event.RenderGameOverlayEvent.ElementType.BOSSINFO) Level(net.minecraft.world.level.Level) net.minecraft.client.renderer(net.minecraft.client.renderer) PlayerInfo(net.minecraft.client.multiplayer.PlayerInfo) GuiComponent(net.minecraft.client.gui.GuiComponent) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) SoundEngine(net.minecraft.client.sounds.SoundEngine) PlaySoundEvent(net.minecraftforge.client.event.sound.PlaySoundEvent) Function(java.util.function.Function) Stack(java.util.Stack) ItemColors(net.minecraft.client.color.item.ItemColors) BlockRenderDispatcher(net.minecraft.client.renderer.block.BlockRenderDispatcher) ParticleRenderType(net.minecraft.client.particle.ParticleRenderType) Minecraft(net.minecraft.client.Minecraft) JoinMultiplayerScreen(net.minecraft.client.gui.screens.multiplayer.JoinMultiplayerScreen) Fluid(net.minecraft.world.level.material.Fluid) Mod(net.minecraftforge.fml.common.Mod) HumanoidModel(net.minecraft.client.model.HumanoidModel) NativeImage(com.mojang.blaze3d.platform.NativeImage) Nonnull(javax.annotation.Nonnull) EntityHitResult(net.minecraft.world.phys.EntityHitResult) NetworkConstants(net.minecraftforge.network.NetworkConstants) LayerDefinition(net.minecraft.client.model.geom.builders.LayerDefinition) LocalPlayer(net.minecraft.client.player.LocalPlayer) ModelLayerLocation(net.minecraft.client.model.geom.ModelLayerLocation) HitResult(net.minecraft.world.phys.HitResult) Entity(net.minecraft.world.entity.Entity) Model(net.minecraft.client.model.Model) BlockColors(net.minecraft.client.color.block.BlockColors) KeyMapping(net.minecraft.client.KeyMapping) Comparator(java.util.Comparator) LogManager(org.apache.logging.log4j.LogManager) ForgeModelBakery(net.minecraftforge.client.model.ForgeModelBakery) ArrayList(java.util.ArrayList) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ResourceLocation(net.minecraft.resources.ResourceLocation) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) HashMap(java.util.HashMap) Pair(org.apache.commons.lang3.tuple.Pair)

Example 19 with ResourceLocation

use of net.minecraft.resources.ResourceLocation in project MinecraftForge by MinecraftForge.

the class GameTestTest method generateTests.

/**
 * An example game test generator.
 * <p>
 * A <b>game test generator</b> generates a collection of test functions.
 * It is called immediately when registered to GameTestRegistry.
 * <p><ul>
 * <li>Must return {@code Collection<TestFunction>} (or a subclass)</li>
 * <li>Must take no parameters</li>
 * <li>Can be {@code static} or non-static</li>
 * <p>
 * WARNING: If made non-static, then it will create an instance of the class every time it is run.</li>
 * </ul>
 */
@GameTestGenerator
public static List<TestFunction> generateTests() {
    // An example test function, run in the default batch, with the test name "teststone", and the structure name "gametesttest.teststone" under the "gametest_test" namespace.
    // No rotation, 100 ticks until the test times out if it does not fail or succeed, 0 ticks for setup time, and the actual code to run.
    TestFunction testStone = new TestFunction("defaultBatch", "teststone", new ResourceLocation(MODID, "gametesttest.teststone").toString(), Rotation.NONE, 100, 0, true, helper -> {
        BlockPos stonePos = new BlockPos(1, 1, 1);
        // This should always assert to true, since we set it then directly check it
        helper.setBlock(stonePos, Blocks.STONE);
        helper.assertBlockState(stonePos, b -> b.is(Blocks.STONE), () -> "Block was not stone");
        helper.succeed();
    });
    return List.of(testStone);
}
Also used : TestFunction(net.minecraft.gametest.framework.TestFunction) ResourceLocation(net.minecraft.resources.ResourceLocation) BlockPos(net.minecraft.core.BlockPos) GameTestGenerator(net.minecraft.gametest.framework.GameTestGenerator)

Example 20 with ResourceLocation

use of net.minecraft.resources.ResourceLocation in project MinecraftForge by MinecraftForge.

the class BiomeLoadingEventTest method onBiomeLoading.

public void onBiomeLoading(BiomeLoadingEvent event) {
    ResourceLocation biome = event.getName();
    LOGGER.info("Biome loaded: {}", biome);
}
Also used : ResourceLocation(net.minecraft.resources.ResourceLocation)

Aggregations

ResourceLocation (net.minecraft.resources.ResourceLocation)86 ArrayList (java.util.ArrayList)7 Map (java.util.Map)7 LogManager (org.apache.logging.log4j.LogManager)7 Logger (org.apache.logging.log4j.Logger)7 List (java.util.List)6 FriendlyByteBuf (net.minecraft.network.FriendlyByteBuf)6 JsonObject (com.google.gson.JsonObject)5 CommandSyntaxException (com.mojang.brigadier.exceptions.CommandSyntaxException)5 IOException (java.io.IOException)5 Collectors (java.util.stream.Collectors)5 StringReader (com.mojang.brigadier.StringReader)4 CompoundTag (net.minecraft.nbt.CompoundTag)4 CraftServer (org.bukkit.craftbukkit.v1_17_R1.CraftServer)4 ItemStack (org.bukkit.inventory.ItemStack)4 InputStream (java.io.InputStream)3 Collections (java.util.Collections)3 Set (java.util.Set)3 Function (java.util.function.Function)3 Nullable (javax.annotation.Nullable)3