Search in sources :

Example 6 with JSONParser

use of com.loohp.interactivechat.libs.org.json.simple.parser.JSONParser in project InteractiveChat-DiscordSRV-Addon by LOOHP.

the class InteractiveChatDiscordSrvAddon method cachePlayerSkin.

private void cachePlayerSkin(ICPlayer player) {
    Debug.debug("Caching skin for player " + player.getName() + " (" + player.getUniqueId() + ")");
    if (player.isLocal()) {
        try {
            UUID uuid = player.getUniqueId();
            JSONObject json = (JSONObject) new JSONParser().parse(SkinUtils.getSkinJsonFromProfile(player.getLocalPlayer()));
            String value = (String) ((JSONObject) ((JSONObject) json.get("textures")).get("SKIN")).get("url");
            BufferedImage skin = ImageUtils.downloadImage(value);
            Cache.putCache(uuid + value + ImageGeneration.PLAYER_SKIN_CACHE_KEY, skin, InteractiveChatDiscordSrvAddon.plugin.cacheTimeout);
        } catch (Exception e) {
        }
    } else {
        try {
            UUID uuid = player.getUniqueId();
            String value = SkinUtils.getSkinURLFromUUID(uuid);
            BufferedImage skin = ImageUtils.downloadImage(value);
            Cache.putCache(uuid + "null" + ImageGeneration.PLAYER_SKIN_CACHE_KEY, skin, InteractiveChatDiscordSrvAddon.plugin.cacheTimeout);
        } catch (Exception e) {
        }
    }
}
Also used : JSONObject(com.loohp.interactivechat.libs.org.json.simple.JSONObject) JSONParser(com.loohp.interactivechat.libs.org.json.simple.parser.JSONParser) UUID(java.util.UUID) BufferedImage(java.awt.image.BufferedImage) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException)

Example 7 with JSONParser

use of com.loohp.interactivechat.libs.org.json.simple.parser.JSONParser in project InteractiveChat-DiscordSRV-Addon by LOOHP.

the class ImageGeneration method getTabListImage.

public static BufferedImage getTabListImage(List<Component> header, List<Component> footer, List<ValueTrios<UUID, Component, Integer>> players, boolean showAvatar, boolean showPing) {
    List<ValuePairs<BufferedImage, Integer>> playerImages = new ArrayList<>(players.size());
    int masterOffsetX = 0;
    for (ValueTrios<UUID, Component, Integer> trio : players) {
        UUID uuid = trio.getFirst();
        Component name = trio.getSecond();
        int ping = trio.getThird();
        BufferedImage image = new BufferedImage(2048, TABLIST_INTERNAL_HEIGHT, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = image.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
        int offsetX = 0;
        if (showAvatar) {
            BufferedImage skin;
            try {
                Player onlinePlayer = Bukkit.getPlayer(uuid);
                if (onlinePlayer == null) {
                    Cache<?> cache = Cache.getCache(uuid + "null" + PLAYER_SKIN_CACHE_KEY);
                    if (cache == null) {
                        String value = SkinUtils.getSkinURLFromUUID(uuid);
                        skin = ImageUtils.downloadImage(value);
                        Cache.putCache(uuid + "null" + PLAYER_SKIN_CACHE_KEY, skin, InteractiveChatDiscordSrvAddon.plugin.cacheTimeout);
                        skin = ImageUtils.copyImage(skin);
                    } else {
                        skin = ImageUtils.copyImage((BufferedImage) cache.getObject());
                    }
                } else {
                    try {
                        JSONObject json = (JSONObject) new JSONParser().parse(SkinUtils.getSkinJsonFromProfile(onlinePlayer));
                        String value = (String) ((JSONObject) ((JSONObject) json.get("textures")).get("SKIN")).get("url");
                        Cache<?> cache = Cache.getCache(uuid + value + PLAYER_SKIN_CACHE_KEY);
                        if (cache == null) {
                            skin = ImageUtils.downloadImage(value);
                            Cache.putCache(uuid + value + PLAYER_SKIN_CACHE_KEY, skin, InteractiveChatDiscordSrvAddon.plugin.cacheTimeout);
                        } else {
                            skin = (BufferedImage) cache.getObject();
                        }
                        skin = ImageUtils.copyImage(skin);
                    } catch (Exception e) {
                        String value = SkinUtils.getSkinURLFromUUID(uuid);
                        skin = ImageUtils.downloadImage(value);
                    }
                }
            } catch (Exception e) {
                skin = resourceManager.get().getTextureManager().getTexture(ResourceRegistry.ENTITY_TEXTURE_LOCATION + "steve").getTexture(64, 64);
            }
            BufferedImage avatar = ImageUtils.copyAndGetSubImage(skin, 8, 8, 8, 8);
            BufferedImage avatarOverlay = ImageUtils.copyAndGetSubImage(skin, 40, 8, 8, 8);
            if (ModelUtils.isRenderedUpsideDown(name)) {
                avatar = ImageUtils.rotateImageByDegrees(avatar, 180);
                avatarOverlay = ImageUtils.rotateImageByDegrees(avatarOverlay, 180);
            }
            g.drawImage(avatar, offsetX, (TABLIST_INTERNAL_HEIGHT - 18) / 2, 16, 16, null);
            g.drawImage(avatarOverlay, offsetX, (TABLIST_INTERNAL_HEIGHT - 18) / 2, 16, 16, null);
            offsetX += 18;
        } else {
            offsetX += 2;
        }
        g.dispose();
        ImageUtils.printComponent(resourceManager.get(), image, name, InteractiveChatDiscordSrvAddon.plugin.language, version.get().isLegacyRGB(), offsetX, (TABLIST_INTERNAL_HEIGHT - 18) / 2 - 1, 16);
        int lastX = InteractiveChatDiscordSrvAddon.plugin.playerlistCommandMinWidth;
        for (int x = InteractiveChatDiscordSrvAddon.plugin.playerlistCommandMinWidth; x < image.getWidth(); x++) {
            for (int y = 0; y < image.getHeight(); y++) {
                if (image.getRGB(x, y) != 0) {
                    lastX = x;
                    break;
                }
            }
        }
        if (lastX > masterOffsetX) {
            masterOffsetX = lastX;
        }
        playerImages.add(new ValuePairs<>(image, ping));
    }
    List<BufferedImage> playerRows = new ArrayList<>(playerImages.size());
    if (showPing) {
        masterOffsetX += 26;
    } else {
        masterOffsetX += 2;
    }
    for (ValuePairs<BufferedImage, Integer> pair : playerImages) {
        BufferedImage image = pair.getFirst();
        if (showPing) {
            BufferedImage ping = getPingIcon(pair.getSecond());
            Graphics2D g = image.createGraphics();
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
            g.drawImage(ImageUtils.resizeImageAbs(ping, 20, 14), masterOffsetX - 22, (TABLIST_INTERNAL_HEIGHT - 18) / 2 + 2, null);
            g.dispose();
        }
        BufferedImage cropped = new BufferedImage(masterOffsetX, TABLIST_INTERNAL_HEIGHT, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = cropped.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
        g.setColor(TABLIST_PLAYER_BACKGROUND);
        g.fillRect(0, (TABLIST_INTERNAL_HEIGHT - 18) / 2, cropped.getWidth(), 16);
        g.drawImage(image, 0, 0, null);
        g.dispose();
        playerRows.add(cropped);
    }
    Map<BufferedImage, Integer> headerLines = new LinkedHashMap<>(header.size());
    for (Component line : header) {
        BufferedImage image = new BufferedImage(2048, TABLIST_INTERNAL_HEIGHT, BufferedImage.TYPE_INT_ARGB);
        ImageUtils.printComponent(resourceManager.get(), image, line, InteractiveChatDiscordSrvAddon.plugin.language, version.get().isLegacyRGB(), 0, (TABLIST_INTERNAL_HEIGHT - 18) / 2 - 1, 16);
        int lastX = 0;
        for (int x = 0; x < image.getWidth(); x++) {
            for (int y = 0; y < image.getHeight(); y++) {
                if (image.getRGB(x, y) != 0) {
                    lastX = x;
                    break;
                }
            }
        }
        BufferedImage cropped = new BufferedImage(Math.max(1, lastX), TABLIST_INTERNAL_HEIGHT, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = cropped.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
        g.drawImage(image, 0, 0, null);
        g.dispose();
        headerLines.put(cropped, lastX);
    }
    Map<BufferedImage, Integer> footerLines = new LinkedHashMap<>(footer.size());
    for (Component line : footer) {
        BufferedImage image = new BufferedImage(2048, TABLIST_INTERNAL_HEIGHT, BufferedImage.TYPE_INT_ARGB);
        ImageUtils.printComponent(resourceManager.get(), image, line, InteractiveChatDiscordSrvAddon.plugin.language, version.get().isLegacyRGB(), 0, (TABLIST_INTERNAL_HEIGHT - 18) / 2 - 1, 16);
        int lastX = 0;
        for (int x = 0; x < image.getWidth(); x++) {
            for (int y = 0; y < image.getHeight(); y++) {
                if (image.getRGB(x, y) != 0) {
                    lastX = x;
                    break;
                }
            }
        }
        BufferedImage cropped = new BufferedImage(Math.max(1, lastX), TABLIST_INTERNAL_HEIGHT, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = cropped.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
        g.drawImage(image, 0, 0, null);
        g.dispose();
        footerLines.put(cropped, lastX);
    }
    BufferedImage image;
    if (playerRows.size() <= TABLIST_SINGLE_COLUMN_LIMIT) {
        image = new BufferedImage(masterOffsetX + 4, playerRows.size() * 18 + 2, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = image.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
        g.setColor(TABLIST_BACKGROUND);
        g.fillRect(0, 0, image.getWidth(), image.getHeight());
        int offsetY = -((TABLIST_INTERNAL_HEIGHT - 18) / 2);
        for (BufferedImage each : playerRows) {
            g.drawImage(each, 2, offsetY, null);
            offsetY += 18;
        }
        g.dispose();
    } else {
        image = new BufferedImage(masterOffsetX * 2 + 6, (int) Math.ceil((double) playerRows.size() / 2) * 18 + 2, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = image.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
        g.setColor(TABLIST_BACKGROUND);
        g.fillRect(0, 0, image.getWidth(), image.getHeight());
        int offsetY = -((TABLIST_INTERNAL_HEIGHT - 18) / 2 - 2);
        int half = (int) Math.ceil((double) playerRows.size() / 2);
        for (int i = 0; i < half; i++) {
            g.drawImage(playerRows.get(i), 2, offsetY, null);
            offsetY += 18;
        }
        offsetY = -((TABLIST_INTERNAL_HEIGHT - 18) / 2 - 2);
        for (int i = half; i < playerRows.size(); i++) {
            g.drawImage(playerRows.get(i), masterOffsetX + 4, offsetY, null);
            offsetY += 18;
        }
        if (playerRows.size() % 2 == 1) {
            g.setColor(TABLIST_PLAYER_BACKGROUND);
            g.fillRect(masterOffsetX + 4, offsetY + ((TABLIST_INTERNAL_HEIGHT - 18) / 2), masterOffsetX, 16);
        }
        g.dispose();
    }
    int maxOffsetX = Stream.concat(headerLines.values().stream(), footerLines.values().stream()).mapToInt(each -> each).max().orElse(0);
    if (maxOffsetX <= 0) {
        return image;
    } else {
        BufferedImage decoration = new BufferedImage(Math.max(image.getWidth(), maxOffsetX + 4), (headerLines.isEmpty() ? 0 : headerLines.size() * 18 + 2) + image.getHeight() + (footerLines.isEmpty() ? 2 : footerLines.size() * 18 + 4), BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = decoration.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
        int offsetY = -((TABLIST_INTERNAL_HEIGHT - 18) / 2 - 2);
        for (BufferedImage each : headerLines.keySet()) {
            g.drawImage(each, (decoration.getWidth() / 2) - (each.getWidth() / 2), offsetY, null);
            offsetY += 18;
        }
        g.drawImage(image, (decoration.getWidth() / 2) - (image.getWidth() / 2), offsetY + ((TABLIST_INTERNAL_HEIGHT - 18) / 2), null);
        offsetY += image.getHeight() + 2;
        for (BufferedImage each : footerLines.keySet()) {
            g.drawImage(each, (decoration.getWidth() / 2) - (each.getWidth() / 2), offsetY, null);
            offsetY += 18;
        }
        g.dispose();
        int lastY = offsetY + ((TABLIST_INTERNAL_HEIGHT - 18) / 2 - 2);
        for (int y = offsetY + ((TABLIST_INTERNAL_HEIGHT - 18) / 2 - 2); y < decoration.getHeight(); y++) {
            for (int x = 0; x < decoration.getWidth(); x++) {
                if (decoration.getRGB(x, y) != 0) {
                    lastY = y;
                    break;
                }
            }
        }
        BufferedImage finalDecoration = new BufferedImage(decoration.getWidth(), lastY + 3, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = finalDecoration.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
        g2.setColor(TABLIST_BACKGROUND);
        g2.fillRect(0, 0, finalDecoration.getWidth(), finalDecoration.getHeight());
        g2.drawImage(decoration, 0, 0, null);
        g2.dispose();
        return finalDecoration;
    }
}
Also used : Player(org.bukkit.entity.Player) ICPlayer(com.loohp.interactivechat.objectholders.ICPlayer) OfflineICPlayer(com.loohp.interactivechat.objectholders.OfflineICPlayer) ValuePairs(com.loohp.interactivechat.objectholders.ValuePairs) ArrayList(java.util.ArrayList) BufferedImage(java.awt.image.BufferedImage) IOException(java.io.IOException) Graphics2D(java.awt.Graphics2D) LinkedHashMap(java.util.LinkedHashMap) JSONObject(com.loohp.interactivechat.libs.org.json.simple.JSONObject) JSONParser(com.loohp.interactivechat.libs.org.json.simple.parser.JSONParser) UUID(java.util.UUID) Component(com.loohp.interactivechat.libs.net.kyori.adventure.text.Component)

Example 8 with JSONParser

use of com.loohp.interactivechat.libs.org.json.simple.parser.JSONParser in project InteractiveChat-DiscordSRV-Addon by LOOHP.

the class ImageGeneration method getFullBodyImage.

private static BufferedImage getFullBodyImage(OfflineICPlayer player, ItemStack helmet, ItemStack chestplate, ItemStack leggings, ItemStack boots) throws IOException {
    InteractiveChatDiscordSrvAddon.plugin.imageCounter.incrementAndGet();
    Debug.debug("ImageGeneration creating puppet image of " + player.getName());
    BufferedImage skin = null;
    boolean slim = false;
    BufferedImage cape;
    try {
        JSONObject json;
        ICPlayer icPlayer = player.getPlayer();
        if (icPlayer != null && icPlayer.isLocal()) {
            json = (JSONObject) new JSONParser().parse(SkinUtils.getSkinJsonFromProfile(((ICPlayer) player).getLocalPlayer()));
        } else {
            json = (JSONObject) new JSONParser().parse(new String(Base64.getDecoder().decode(((JSONObject) ((JSONArray) HTTPRequestUtils.getJSONResponse(PLAYER_INFO_URL.replace("%s", player.getUniqueId().toString())).get("properties")).get(0)).get("value").toString())));
        }
        if (json == null) {
            cape = null;
        } else {
            try {
                if (((JSONObject) json.get("textures")).containsKey("CAPE")) {
                    String url = (String) ((JSONObject) ((JSONObject) json.get("textures")).get("CAPE")).get("url");
                    Cache<?> cache = Cache.getCache(player.getUniqueId().toString() + url + PLAYER_CAPE_CACHE_KEY);
                    if (cache == null) {
                        cape = ImageUtils.downloadImage(url);
                        Cache.putCache(player.getUniqueId().toString() + url + PLAYER_CAPE_CACHE_KEY, cape, InteractiveChatDiscordSrvAddon.plugin.cacheTimeout);
                    } else {
                        cape = (BufferedImage) cache.getObject();
                    }
                } else {
                    String url = OPTIFINE_CAPE_URL.replaceAll("%s", CustomStringUtils.escapeReplaceAllMetaCharacters(player.getName()));
                    Cache<?> cache = Cache.getCache(player.getUniqueId().toString() + url + PLAYER_CAPE_CACHE_KEY);
                    if (cache == null) {
                        try {
                            cape = ImageUtils.downloadImage(url);
                            Cache.putCache(player.getUniqueId().toString() + url + PLAYER_CAPE_CACHE_KEY, cape, InteractiveChatDiscordSrvAddon.plugin.cacheTimeout);
                        } catch (Throwable ignore) {
                            cape = null;
                        }
                    } else {
                        cape = (BufferedImage) cache.getObject();
                    }
                }
            } catch (Throwable e) {
                cape = null;
            }
            try {
                String value = (String) ((JSONObject) ((JSONObject) json.get("textures")).get("SKIN")).get("url");
                if (((JSONObject) ((JSONObject) json.get("textures")).get("SKIN")).containsKey("metadata")) {
                    slim = ((JSONObject) ((JSONObject) ((JSONObject) json.get("textures")).get("SKIN")).get("metadata")).get("model").toString().equals("slim");
                }
                Cache<?> cache = Cache.getCache(player.getUniqueId().toString() + value + PLAYER_SKIN_CACHE_KEY);
                if (cache == null) {
                    skin = ImageUtils.downloadImage(value);
                    Cache.putCache(player.getUniqueId().toString() + value + PLAYER_SKIN_CACHE_KEY, skin, InteractiveChatDiscordSrvAddon.plugin.cacheTimeout);
                } else {
                    skin = (BufferedImage) cache.getObject();
                }
                skin = ImageUtils.copyImage(skin);
            } catch (Throwable e1) {
            }
        }
    } catch (Exception e) {
        cape = null;
    }
    if (skin == null) {
        if (slim) {
            skin = resourceManager.get().getTextureManager().getTexture(ResourceRegistry.ENTITY_TEXTURE_LOCATION + "alex").getTexture();
        } else {
            skin = resourceManager.get().getTextureManager().getTexture(ResourceRegistry.ENTITY_TEXTURE_LOCATION + "steve").getTexture();
        }
    }
    BufferedImage elytraImage = null;
    BufferedImage image = new BufferedImage(556, 748, BufferedImage.TYPE_INT_ARGB);
    Map<String, TextureResource> providedTextures = new HashMap<>();
    Map<PlayerModelItemPosition, PlayerModelItem> modelItems = new HashMap<>();
    providedTextures.put(ResourceRegistry.SKIN_FULL_TEXTURE_PLACEHOLDER, new GeneratedTextureResource(ModelUtils.convertToModernSkinTexture(skin)));
    if (ItemStackUtils.isWearable(leggings)) {
        XMaterial type = XMaterialUtils.matchXMaterial(leggings);
        BufferedImage leggingsImage = null;
        switch(type) {
            case LEATHER_LEGGINGS:
                leggingsImage = resourceManager.get().getTextureManager().getTexture(ResourceRegistry.ARMOR_TEXTURE_LOCATION + "leather_layer_2").getTexture();
                LeatherArmorMeta meta = (LeatherArmorMeta) leggings.getItemMeta();
                Color color = new Color(meta.getColor().asRGB());
                BufferedImage armorOverlay = resourceManager.get().getTextureManager().getTexture(ResourceRegistry.ARMOR_TEXTURE_LOCATION + "leather_layer_2_overlay").getTexture();
                BufferedImage colorOverlay = ImageUtils.changeColorTo(ImageUtils.copyImage(leggingsImage), color);
                leggingsImage = ImageUtils.multiply(leggingsImage, colorOverlay);
                Graphics2D g2 = leggingsImage.createGraphics();
                g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
                g2.drawImage(armorOverlay, 0, 0, null);
                g2.dispose();
                break;
            case CHAINMAIL_LEGGINGS:
                leggingsImage = resourceManager.get().getTextureManager().getTexture(ResourceRegistry.ARMOR_TEXTURE_LOCATION + "chainmail_layer_2").getTexture();
                break;
            case GOLDEN_LEGGINGS:
                leggingsImage = resourceManager.get().getTextureManager().getTexture(ResourceRegistry.ARMOR_TEXTURE_LOCATION + "gold_layer_2").getTexture();
                break;
            case IRON_LEGGINGS:
                leggingsImage = resourceManager.get().getTextureManager().getTexture(ResourceRegistry.ARMOR_TEXTURE_LOCATION + "iron_layer_2").getTexture();
                break;
            case DIAMOND_LEGGINGS:
                leggingsImage = resourceManager.get().getTextureManager().getTexture(ResourceRegistry.ARMOR_TEXTURE_LOCATION + "diamond_layer_2").getTexture();
                break;
            case NETHERITE_LEGGINGS:
                leggingsImage = resourceManager.get().getTextureManager().getTexture(ResourceRegistry.ARMOR_TEXTURE_LOCATION + "netherite_layer_2").getTexture();
                break;
            default:
                break;
        }
        if (leggingsImage != null) {
            if (leggings.getEnchantments().size() > 0) {
                leggingsImage = getEnchantedImage(leggingsImage);
            }
            providedTextures.put(ResourceRegistry.LEGGINGS_TEXTURE_PLACEHOLDER, new GeneratedTextureResource(leggingsImage));
        }
    }
    if (ItemStackUtils.isWearable(boots)) {
        XMaterial type = XMaterialUtils.matchXMaterial(boots);
        BufferedImage bootsImage = null;
        switch(type) {
            case LEATHER_BOOTS:
                bootsImage = resourceManager.get().getTextureManager().getTexture(ResourceRegistry.ARMOR_TEXTURE_LOCATION + "leather_layer_1").getTexture();
                LeatherArmorMeta meta = (LeatherArmorMeta) boots.getItemMeta();
                Color color = new Color(meta.getColor().asRGB());
                BufferedImage armorOverlay = resourceManager.get().getTextureManager().getTexture(ResourceRegistry.ARMOR_TEXTURE_LOCATION + "leather_layer_1_overlay").getTexture();
                BufferedImage colorOverlay = ImageUtils.changeColorTo(ImageUtils.copyImage(bootsImage), color);
                bootsImage = ImageUtils.multiply(bootsImage, colorOverlay);
                Graphics2D g2 = bootsImage.createGraphics();
                g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
                g2.drawImage(armorOverlay, 0, 0, null);
                g2.dispose();
                break;
            case CHAINMAIL_BOOTS:
                bootsImage = resourceManager.get().getTextureManager().getTexture(ResourceRegistry.ARMOR_TEXTURE_LOCATION + "chainmail_layer_1").getTexture();
                break;
            case GOLDEN_BOOTS:
                bootsImage = resourceManager.get().getTextureManager().getTexture(ResourceRegistry.ARMOR_TEXTURE_LOCATION + "gold_layer_1").getTexture();
                break;
            case IRON_BOOTS:
                bootsImage = resourceManager.get().getTextureManager().getTexture(ResourceRegistry.ARMOR_TEXTURE_LOCATION + "iron_layer_1").getTexture();
                break;
            case DIAMOND_BOOTS:
                bootsImage = resourceManager.get().getTextureManager().getTexture(ResourceRegistry.ARMOR_TEXTURE_LOCATION + "diamond_layer_1").getTexture();
                break;
            case NETHERITE_BOOTS:
                bootsImage = resourceManager.get().getTextureManager().getTexture(ResourceRegistry.ARMOR_TEXTURE_LOCATION + "netherite_layer_1").getTexture();
                break;
            default:
                break;
        }
        if (bootsImage != null) {
            if (boots.getEnchantments().size() > 0) {
                bootsImage = getEnchantedImage(bootsImage);
            }
            providedTextures.put(ResourceRegistry.BOOTS_TEXTURE_PLACEHOLDER, new GeneratedTextureResource(bootsImage));
        }
    }
    if (ItemStackUtils.isWearable(chestplate)) {
        XMaterial type = XMaterialUtils.matchXMaterial(chestplate);
        BufferedImage chestplateImage = null;
        boolean isArmor = true;
        switch(type) {
            case LEATHER_CHESTPLATE:
                chestplateImage = resourceManager.get().getTextureManager().getTexture(ResourceRegistry.ARMOR_TEXTURE_LOCATION + "leather_layer_1").getTexture();
                LeatherArmorMeta meta = (LeatherArmorMeta) chestplate.getItemMeta();
                Color color = new Color(meta.getColor().asRGB());
                BufferedImage armorOverlay = resourceManager.get().getTextureManager().getTexture(ResourceRegistry.ARMOR_TEXTURE_LOCATION + "leather_layer_1_overlay").getTexture();
                BufferedImage colorOverlay = ImageUtils.changeColorTo(ImageUtils.copyImage(chestplateImage), color);
                chestplateImage = ImageUtils.multiply(chestplateImage, colorOverlay);
                Graphics2D g2 = chestplateImage.createGraphics();
                g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
                g2.drawImage(armorOverlay, 0, 0, null);
                g2.dispose();
                break;
            case CHAINMAIL_CHESTPLATE:
                chestplateImage = resourceManager.get().getTextureManager().getTexture(ResourceRegistry.ARMOR_TEXTURE_LOCATION + "chainmail_layer_1").getTexture();
                break;
            case GOLDEN_CHESTPLATE:
                chestplateImage = resourceManager.get().getTextureManager().getTexture(ResourceRegistry.ARMOR_TEXTURE_LOCATION + "gold_layer_1").getTexture();
                break;
            case IRON_CHESTPLATE:
                chestplateImage = resourceManager.get().getTextureManager().getTexture(ResourceRegistry.ARMOR_TEXTURE_LOCATION + "iron_layer_1").getTexture();
                break;
            case DIAMOND_CHESTPLATE:
                chestplateImage = resourceManager.get().getTextureManager().getTexture(ResourceRegistry.ARMOR_TEXTURE_LOCATION + "diamond_layer_1").getTexture();
                break;
            case NETHERITE_CHESTPLATE:
                chestplateImage = resourceManager.get().getTextureManager().getTexture(ResourceRegistry.ARMOR_TEXTURE_LOCATION + "netherite_layer_1").getTexture();
                break;
            case ELYTRA:
                isArmor = false;
                chestplateImage = new BufferedImage(150, 150, BufferedImage.TYPE_INT_ARGB);
                BufferedImage wing = cape == null ? resourceManager.get().getTextureManager().getTexture(ResourceRegistry.ENTITY_TEXTURE_LOCATION + "elytra").getTexture() : cape;
                if (wing.getWidth() % 64 != 0 || wing.getHeight() % 32 != 0) {
                    int w = 0;
                    int h = 0;
                    while (w < wing.getWidth()) {
                        w += 64;
                        h += 32;
                    }
                    BufferedImage resize = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
                    Graphics2D g3 = resize.createGraphics();
                    g3.drawImage(wing, 0, 0, null);
                    g3.dispose();
                    wing = resize;
                }
                int scale = wing.getWidth() / 64;
                wing = ImageUtils.copyAndGetSubImage(wing, 34 * scale, 2 * scale, 12 * scale, 20 * scale);
                wing = ImageUtils.multiply(ImageUtils.resizeImage(wing, Math.pow(scale, -1) * 3.75), 0.7);
                BufferedImage leftWing = ImageUtils.rotateImageByDegrees(wing, 23.41);
                Graphics2D g3 = chestplateImage.createGraphics();
                g3.drawImage(leftWing, 0, 0, null);
                wing = ImageUtils.flipHorizontal(wing);
                BufferedImage rightWing = ImageUtils.rotateImageByDegrees(wing, 360.0 - 23.41);
                g3.drawImage(rightWing, 26, 0, null);
                g3.dispose();
                if (chestplate.getEnchantments().size() > 0) {
                    chestplateImage = getEnchantedImage(chestplateImage);
                }
                elytraImage = chestplateImage;
            default:
                break;
        }
        if (isArmor && chestplateImage != null) {
            if (chestplate.getEnchantments().size() > 0) {
                chestplateImage = getEnchantedImage(chestplateImage);
            }
            providedTextures.put(ResourceRegistry.CHESTPLATE_TEXTURE_PLACEHOLDER, new GeneratedTextureResource(chestplateImage));
        }
    }
    if (helmet != null && !helmet.getType().equals(Material.AIR)) {
        XMaterial type = XMaterialUtils.matchXMaterial(helmet);
        BufferedImage helmetImage = null;
        boolean isArmor = true;
        switch(type) {
            case LEATHER_HELMET:
                helmetImage = resourceManager.get().getTextureManager().getTexture(ResourceRegistry.ARMOR_TEXTURE_LOCATION + "leather_layer_1").getTexture();
                LeatherArmorMeta meta = (LeatherArmorMeta) helmet.getItemMeta();
                Color color = new Color(meta.getColor().asRGB());
                BufferedImage armorOverlay = resourceManager.get().getTextureManager().getTexture(ResourceRegistry.ARMOR_TEXTURE_LOCATION + "leather_layer_1_overlay").getTexture();
                BufferedImage colorOverlay = ImageUtils.changeColorTo(ImageUtils.copyImage(helmetImage), color);
                helmetImage = ImageUtils.multiply(helmetImage, colorOverlay);
                Graphics2D g2 = helmetImage.createGraphics();
                g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
                g2.drawImage(armorOverlay, 0, 0, null);
                g2.dispose();
                break;
            case CHAINMAIL_HELMET:
                helmetImage = resourceManager.get().getTextureManager().getTexture(ResourceRegistry.ARMOR_TEXTURE_LOCATION + "chainmail_layer_1").getTexture();
                break;
            case GOLDEN_HELMET:
                helmetImage = resourceManager.get().getTextureManager().getTexture(ResourceRegistry.ARMOR_TEXTURE_LOCATION + "gold_layer_1").getTexture();
                break;
            case IRON_HELMET:
                helmetImage = resourceManager.get().getTextureManager().getTexture(ResourceRegistry.ARMOR_TEXTURE_LOCATION + "iron_layer_1").getTexture();
                break;
            case DIAMOND_HELMET:
                helmetImage = resourceManager.get().getTextureManager().getTexture(ResourceRegistry.ARMOR_TEXTURE_LOCATION + "diamond_layer_1").getTexture();
                break;
            case NETHERITE_HELMET:
                helmetImage = resourceManager.get().getTextureManager().getTexture(ResourceRegistry.ARMOR_TEXTURE_LOCATION + "netherite_layer_1").getTexture();
                break;
            case TURTLE_HELMET:
                helmetImage = resourceManager.get().getTextureManager().getTexture(ResourceRegistry.ARMOR_TEXTURE_LOCATION + "turtle_layer_1").getTexture();
                break;
            default:
                isArmor = false;
                String key = ModelUtils.getItemModelKey(type);
                ItemStackProcessResult itemProcessResult = ItemRenderUtils.processItemForRendering(player, helmet);
                boolean enchanted = itemProcessResult.requiresEnchantmentGlint();
                Map<ModelOverrideType, Float> predicate = itemProcessResult.getPredicates();
                String modelKey = itemProcessResult.getDirectLocation() == null ? ResourceRegistry.ITEM_MODEL_LOCATION + key : itemProcessResult.getDirectLocation();
                Map<String, TextureResource> itemProvidedTextures = itemProcessResult.getProvidedTextures();
                TintIndexData tintIndexData = itemProcessResult.getTintIndexData();
                modelItems.put(PlayerModelItemPosition.HELMET, new PlayerModelItem(PlayerModelItemPosition.HELMET, modelKey, predicate, enchanted, itemProvidedTextures, tintIndexData));
                break;
        }
        if (isArmor) {
            if (helmet.getEnchantments().size() > 0) {
                helmetImage = getEnchantedImage(helmetImage);
            }
            providedTextures.put(ResourceRegistry.HELMET_TEXTURE_PLACEHOLDER, new GeneratedTextureResource(helmetImage));
        }
    }
    if (InteractiveChatDiscordSrvAddon.plugin.renderHandHeldItems) {
        ItemStack rightHand = player.isRightHanded() ? player.getMainHandItem() : player.getOffHandItem();
        if (rightHand != null) {
            String key = ModelUtils.getItemModelKey(XMaterialUtils.matchXMaterial(rightHand));
            ItemStackProcessResult itemProcessResult = ItemRenderUtils.processItemForRendering(player, rightHand);
            boolean enchanted = itemProcessResult.requiresEnchantmentGlint();
            Map<ModelOverrideType, Float> predicate = itemProcessResult.getPredicates();
            String modelKey = itemProcessResult.getDirectLocation() == null ? ResourceRegistry.ITEM_MODEL_LOCATION + key : itemProcessResult.getDirectLocation();
            Map<String, TextureResource> itemProvidedTextures = itemProcessResult.getProvidedTextures();
            TintIndexData tintIndexData = itemProcessResult.getTintIndexData();
            modelItems.put(PlayerModelItemPosition.RIGHT_HAND, new PlayerModelItem(PlayerModelItemPosition.RIGHT_HAND, modelKey, predicate, enchanted, itemProvidedTextures, tintIndexData));
        }
        ItemStack leftHand = player.isRightHanded() ? player.getOffHandItem() : player.getMainHandItem();
        if (leftHand != null) {
            String key = ModelUtils.getItemModelKey(XMaterialUtils.matchXMaterial(leftHand));
            ItemStackProcessResult itemProcessResult = ItemRenderUtils.processItemForRendering(player, leftHand);
            boolean enchanted = itemProcessResult.requiresEnchantmentGlint();
            Map<ModelOverrideType, Float> predicate = itemProcessResult.getPredicates();
            String modelKey = itemProcessResult.getDirectLocation() == null ? ResourceRegistry.ITEM_MODEL_LOCATION + key : itemProcessResult.getDirectLocation();
            Map<String, TextureResource> itemProvidedTextures = itemProcessResult.getProvidedTextures();
            TintIndexData tintIndexData = itemProcessResult.getTintIndexData();
            modelItems.put(PlayerModelItemPosition.LEFT_HAND, new PlayerModelItem(PlayerModelItemPosition.LEFT_HAND, modelKey, predicate, enchanted, itemProvidedTextures, tintIndexData));
        }
    }
    boolean upsideDown = ModelUtils.isRenderedUpsideDown(player.getName(), cape != null);
    RenderResult renderResult = InteractiveChatDiscordSrvAddon.plugin.modelRenderer.renderPlayer(image.getWidth(), image.getHeight(), resourceManager.get(), version.get().isOld(), slim, providedTextures, TintIndexData.EMPTY_INSTANCE, modelItems);
    Graphics2D g = image.createGraphics();
    BufferedImage resizedImage = ImageUtils.resizeImageAbs(renderResult.getImage(), 117, 159);
    if (upsideDown) {
        resizedImage = ImageUtils.rotateImageByDegrees(resizedImage, 180);
    }
    g.drawImage(resizedImage, -1, 12, null);
    g.dispose();
    if (elytraImage != null) {
        BufferedImage resizedElytraImage = ImageUtils.resizeImage(elytraImage, 0.9);
        if (upsideDown) {
            resizedElytraImage = ImageUtils.rotateImageByDegrees(resizedElytraImage, 180);
        }
        ImageUtils.drawTransparent(image, resizedElytraImage, 14, 75);
    }
    return image;
}
Also used : TextureResource(com.loohp.interactivechatdiscordsrvaddon.resources.textures.TextureResource) GeneratedTextureResource(com.loohp.interactivechatdiscordsrvaddon.resources.textures.GeneratedTextureResource) ICPlayer(com.loohp.interactivechat.objectholders.ICPlayer) OfflineICPlayer(com.loohp.interactivechat.objectholders.OfflineICPlayer) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ItemStackProcessResult(com.loohp.interactivechatdiscordsrvaddon.utils.ItemRenderUtils.ItemStackProcessResult) RenderResult(com.loohp.interactivechatdiscordsrvaddon.resources.ModelRenderer.RenderResult) BufferedImage(java.awt.image.BufferedImage) PlayerModelItemPosition(com.loohp.interactivechatdiscordsrvaddon.resources.ModelRenderer.PlayerModelItemPosition) PlayerModelItem(com.loohp.interactivechatdiscordsrvaddon.resources.ModelRenderer.PlayerModelItem) ModelOverrideType(com.loohp.interactivechatdiscordsrvaddon.resources.models.ModelOverride.ModelOverrideType) Color(java.awt.Color) TextColor(com.loohp.interactivechat.libs.net.kyori.adventure.text.format.TextColor) NamedTextColor(com.loohp.interactivechat.libs.net.kyori.adventure.text.format.NamedTextColor) GeneratedTextureResource(com.loohp.interactivechatdiscordsrvaddon.resources.textures.GeneratedTextureResource) XMaterial(com.loohp.interactivechat.libs.com.cryptomorin.xseries.XMaterial) IOException(java.io.IOException) TintIndexData(com.loohp.interactivechatdiscordsrvaddon.utils.TintUtils.TintIndexData) Graphics2D(java.awt.Graphics2D) JSONObject(com.loohp.interactivechat.libs.org.json.simple.JSONObject) LeatherArmorMeta(org.bukkit.inventory.meta.LeatherArmorMeta) JSONParser(com.loohp.interactivechat.libs.org.json.simple.parser.JSONParser) ItemStack(org.bukkit.inventory.ItemStack)

Example 9 with JSONParser

use of com.loohp.interactivechat.libs.org.json.simple.parser.JSONParser in project InteractiveChat-DiscordSRV-Addon by LOOHP.

the class AssetsDownloader method loadAssets.

@SuppressWarnings("deprecation")
public static void loadAssets(File rootFolder, boolean force, boolean clean, CommandSender... senders) throws Exception {
    if (!Arrays.asList(senders).contains(Bukkit.getConsoleSender())) {
        List<CommandSender> senderList = new ArrayList<>(Arrays.asList(senders));
        senderList.add(Bukkit.getConsoleSender());
        senders = senderList.toArray(new CommandSender[senderList.size()]);
    }
    if (!LOCK.tryLock(0, TimeUnit.MILLISECONDS)) {
        return;
    }
    try {
        File hashes = new File(rootFolder, "hashes.json");
        if (!hashes.exists()) {
            try (PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(hashes), StandardCharsets.UTF_8))) {
                pw.println("{}");
                pw.flush();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        JSONObject json;
        try (InputStreamReader hashReader = new InputStreamReader(new FileInputStream(hashes), StandardCharsets.UTF_8)) {
            json = (JSONObject) new JSONParser().parse(hashReader);
        } catch (Throwable e) {
            new RuntimeException("Invalid hashes.json! It will be reset.", e).printStackTrace();
            json = new JSONObject();
        }
        String oldHash = InteractiveChatDiscordSrvAddon.plugin.defaultResourceHash = json.containsKey("Default") ? json.get("Default").toString() : "EMPTY";
        String oldVersion = json.containsKey("version") ? json.get("version").toString() : "EMPTY";
        File defaultAssetsFolder = new File(rootFolder + "/built-in", "Default");
        defaultAssetsFolder.mkdirs();
        ResourceDownloadManager downloadManager = new ResourceDownloadManager(InteractiveChat.exactMinecraftVersion, defaultAssetsFolder);
        String hash = downloadManager.getHash();
        if (force || !hash.equals(oldHash) || !InteractiveChatDiscordSrvAddon.plugin.getDescription().getVersion().equals(oldVersion)) {
            if (clean) {
                InteractiveChatDiscordSrvAddon.plugin.sendMessage(ChatColor.AQUA + "[ICDiscordSrvAddon] Cleaning old default resources!", senders);
                FileUtils.removeFolderRecursively(defaultAssetsFolder);
                defaultAssetsFolder.mkdirs();
            }
            if (force) {
                InteractiveChatDiscordSrvAddon.plugin.sendMessage(ChatColor.AQUA + "[ICDiscordSrvAddon] Forcibly re-downloading default resources! Please wait... (" + oldHash + " -> " + hash + ")", senders);
            } else if (!hash.equals(oldHash)) {
                InteractiveChatDiscordSrvAddon.plugin.sendMessage(ChatColor.AQUA + "[ICDiscordSrvAddon] Hash changed! Re-downloading default resources! Please wait... (" + oldHash + " -> " + hash + ")", senders);
            } else {
                InteractiveChatDiscordSrvAddon.plugin.sendMessage(ChatColor.AQUA + "[ICDiscordSrvAddon] Plugin version changed! Re-downloading default resources! Please wait... (" + oldHash + " -> " + hash + ")", senders);
            }
            downloadManager.downloadResources((type, fileName, percentage) -> {
                switch(type) {
                    case CLIENT_DOWNLOAD:
                        if (!InteractiveChatDiscordSrvAddon.plugin.reducedAssetsDownloadInfo) {
                            Bukkit.getConsoleSender().sendMessage(ChatColor.GRAY + "[ICDiscordSrvAddon] Downloading client jar");
                        }
                        break;
                    case EXTRACT:
                        if (!InteractiveChatDiscordSrvAddon.plugin.reducedAssetsDownloadInfo) {
                            Bukkit.getConsoleSender().sendMessage(ChatColor.GRAY + "[ICDiscordSrvAddon] Extracting " + fileName);
                        }
                        break;
                    case DOWNLOAD:
                        if (!InteractiveChatDiscordSrvAddon.plugin.reducedAssetsDownloadInfo) {
                            Bukkit.getConsoleSender().sendMessage(ChatColor.GRAY + "[ICDiscordSrvAddon] Downloading " + fileName + " (" + FORMAT.format(percentage) + "%)");
                        }
                        break;
                    case DONE:
                        Bukkit.getConsoleSender().sendMessage(ChatColor.AQUA + "[ICDiscordSrvAddon] Done!");
                        break;
                }
            });
        }
        downloadManager.downloadExtras(() -> {
            InteractiveChatDiscordSrvAddon.plugin.extras.clear();
        }, (key, dataBytes) -> {
            InteractiveChatDiscordSrvAddon.plugin.extras.put(key, dataBytes);
        });
        InteractiveChatDiscordSrvAddon.plugin.defaultResourceHash = hash;
        json.put("Default", hash);
        json.put("version", InteractiveChatDiscordSrvAddon.plugin.getDescription().getVersion());
        try (PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(hashes), StandardCharsets.UTF_8))) {
            Gson g = new GsonBuilder().setPrettyPrinting().create();
            pw.println(g.toJson(new JsonParser().parse(json.toString())));
            pw.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    LOCK.unlock();
}
Also used : InputStreamReader(java.io.InputStreamReader) GsonBuilder(com.google.gson.GsonBuilder) ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) FileInputStream(java.io.FileInputStream) JSONObject(com.loohp.interactivechat.libs.org.json.simple.JSONObject) ResourceDownloadManager(com.loohp.interactivechatdiscordsrvaddon.resources.ResourceDownloadManager) FileOutputStream(java.io.FileOutputStream) CommandSender(org.bukkit.command.CommandSender) OutputStreamWriter(java.io.OutputStreamWriter) JSONParser(com.loohp.interactivechat.libs.org.json.simple.parser.JSONParser) File(java.io.File) PrintWriter(java.io.PrintWriter) JsonParser(com.google.gson.JsonParser)

Example 10 with JSONParser

use of com.loohp.interactivechat.libs.org.json.simple.parser.JSONParser in project InteractiveChat-DiscordSRV-Addon by LOOHP.

the class ItemRenderUtils method processItemForRendering.

public static ItemStackProcessResult processItemForRendering(OfflineICPlayer player, ItemStack item) throws IOException {
    boolean requiresEnchantmentGlint = false;
    XMaterial xMaterial = XMaterialUtils.matchXMaterial(item);
    String directLocation = null;
    if (xMaterial.equals(XMaterial.DEBUG_STICK)) {
        requiresEnchantmentGlint = true;
    } else if (xMaterial.equals(XMaterial.ENCHANTED_GOLDEN_APPLE)) {
        requiresEnchantmentGlint = true;
    } else if (xMaterial.equals(XMaterial.WRITTEN_BOOK)) {
        requiresEnchantmentGlint = true;
    } else if (xMaterial.equals(XMaterial.ENCHANTED_BOOK)) {
        requiresEnchantmentGlint = true;
    } else if (item.getEnchantments().size() > 0) {
        requiresEnchantmentGlint = true;
    }
    TintIndexData tintIndexData = TintUtils.getTintData(xMaterial);
    Map<ModelOverrideType, Float> predicates = new EnumMap<>(ModelOverrideType.class);
    Map<String, TextureResource> providedTextures = new HashMap<>();
    if (NBTEditor.contains(item, "CustomModelData")) {
        int customModelData = NBTEditor.getInt(item, "CustomModelData");
        predicates.put(ModelOverrideType.CUSTOM_MODEL_DATA, (float) customModelData);
    }
    if (xMaterial.equals(XMaterial.CHEST) || xMaterial.equals(XMaterial.TRAPPED_CHEST)) {
        LocalDate time = LocalDate.now();
        if (time.getMonth().equals(Month.DECEMBER) && (time.getDayOfMonth() == 24 || time.getDayOfMonth() == 25 || time.getDayOfMonth() == 26)) {
            directLocation = ResourceRegistry.BUILTIN_ENTITY_MODEL_LOCATION + "christmas_chest";
        }
    } else if (xMaterial.isOneOf(Arrays.asList("CONTAINS:banner"))) {
        BannerAssetResult bannerAsset = BannerGraphics.generateBannerAssets(item);
        providedTextures.put(ResourceRegistry.BANNER_BASE_TEXTURE_PLACEHOLDER, new GeneratedTextureResource(bannerAsset.getBase()));
        providedTextures.put(ResourceRegistry.BANNER_PATTERNS_TEXTURE_PLACEHOLDER, new GeneratedTextureResource(bannerAsset.getPatterns()));
    } else if (xMaterial.equals(XMaterial.SHIELD)) {
        BannerAssetResult shieldAsset = BannerGraphics.generateShieldAssets(item);
        providedTextures.put(ResourceRegistry.SHIELD_BASE_TEXTURE_PLACEHOLDER, new GeneratedTextureResource(shieldAsset.getBase()));
        providedTextures.put(ResourceRegistry.SHIELD_PATTERNS_TEXTURE_PLACEHOLDER, new GeneratedTextureResource(shieldAsset.getPatterns()));
    } else if (xMaterial.equals(XMaterial.PLAYER_HEAD)) {
        BufferedImage skinImage = InteractiveChatDiscordSrvAddon.plugin.resourceManager.getTextureManager().getTexture(ResourceRegistry.ENTITY_TEXTURE_LOCATION + "steve").getTexture();
        try {
            String base64 = SkinUtils.getSkinValue(item.getItemMeta());
            if (base64 != null) {
                JSONObject json = (JSONObject) new JSONParser().parse(new String(Base64.getDecoder().decode(base64)));
                String value = (String) ((JSONObject) ((JSONObject) json.get("textures")).get("SKIN")).get("url");
                skinImage = ImageUtils.downloadImage(value);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        providedTextures.put(ResourceRegistry.SKIN_TEXTURE_PLACEHOLDER, new GeneratedTextureResource(ModelUtils.convertToModernSkinTexture(skinImage)));
    } else if (xMaterial.equals(XMaterial.ELYTRA)) {
        int durability = item.getType().getMaxDurability() - (InteractiveChat.version.isLegacy() ? item.getDurability() : ((Damageable) item.getItemMeta()).getDamage());
        if (durability <= 1) {
            predicates.put(ModelOverrideType.BROKEN, 1F);
        }
    } else if (xMaterial.equals(XMaterial.CROSSBOW)) {
        CrossbowMeta meta = (CrossbowMeta) item.getItemMeta();
        List<ItemStack> charged = meta.getChargedProjectiles();
        if (charged != null && !charged.isEmpty()) {
            predicates.put(ModelOverrideType.CHARGED, 1F);
            ItemStack charge = charged.get(0);
            XMaterial chargeType = XMaterialUtils.matchXMaterial(charge);
            if (chargeType.equals(XMaterial.FIREWORK_ROCKET)) {
                predicates.put(ModelOverrideType.FIREWORK, 1F);
            }
        }
    } else if (xMaterial.equals(XMaterial.CLOCK)) {
        ICPlayer onlinePlayer = player.getPlayer();
        long time = ((onlinePlayer != null && onlinePlayer.isLocal() ? ((ICPlayer) player).getLocalPlayer().getPlayerTime() : Bukkit.getWorlds().get(0).getTime()) % 24000) - 6000;
        if (time < 0) {
            time += 24000;
        }
        double timePhase = (double) time / 24000;
        predicates.put(ModelOverrideType.TIME, (float) (timePhase - 0.0078125));
    } else if (xMaterial.equals(XMaterial.COMPASS)) {
        double angle;
        ICPlayer icplayer = player.getPlayer();
        if (icplayer != null && icplayer.isLocal()) {
            if (InteractiveChat.version.isNewerOrEqualTo(MCVersion.V1_16)) {
                CompassMeta meta = (CompassMeta) item.getItemMeta();
                Location target;
                if (meta.hasLodestone()) {
                    Location lodestone = meta.getLodestone();
                    target = new Location(lodestone.getWorld(), lodestone.getBlockX() + 0.5, lodestone.getBlockY(), lodestone.getBlockZ() + 0.5, lodestone.getYaw(), lodestone.getPitch());
                    requiresEnchantmentGlint = true;
                } else if (icplayer.getLocalPlayer().getWorld().getEnvironment().equals(Environment.NORMAL)) {
                    Location spawn = icplayer.getLocalPlayer().getWorld().getSpawnLocation();
                    target = new Location(spawn.getWorld(), spawn.getBlockX() + 0.5, spawn.getBlockY(), spawn.getBlockZ() + 0.5, spawn.getYaw(), spawn.getPitch());
                } else {
                    target = null;
                }
                if (target != null && target.getWorld().equals(icplayer.getLocalPlayer().getWorld())) {
                    Location playerLocation = icplayer.getLocalPlayer().getEyeLocation();
                    playerLocation.setPitch(0);
                    Vector looking = playerLocation.getDirection();
                    Vector pointing = target.toVector().subtract(playerLocation.toVector());
                    pointing.setY(0);
                    double degree = VectorUtils.getBearing(looking, pointing);
                    if (degree < 0) {
                        degree += 360;
                    }
                    angle = degree / 360;
                } else {
                    angle = RANDOM.nextDouble();
                }
            } else {
                if (icplayer.getLocalPlayer().getWorld().getEnvironment().equals(Environment.NORMAL)) {
                    Location spawn = icplayer.getLocalPlayer().getWorld().getSpawnLocation();
                    Location target = new Location(spawn.getWorld(), spawn.getBlockX() + 0.5, spawn.getBlockY(), spawn.getBlockZ() + 0.5, spawn.getYaw(), spawn.getPitch());
                    Location playerLocation = icplayer.getLocalPlayer().getEyeLocation();
                    playerLocation.setPitch(0);
                    Vector looking = playerLocation.getDirection();
                    Vector pointing = target.toVector().subtract(playerLocation.toVector());
                    pointing.setY(0);
                    double degree = VectorUtils.getBearing(looking, pointing);
                    if (degree < 0) {
                        degree += 360;
                    }
                    angle = degree / 360;
                } else {
                    angle = RANDOM.nextDouble();
                }
            }
        } else {
            if (InteractiveChat.version.isNewerOrEqualTo(MCVersion.V1_16)) {
                CompassMeta meta = (CompassMeta) item.getItemMeta();
                if (meta.hasLodestone()) {
                    requiresEnchantmentGlint = true;
                }
            }
            angle = 0;
        }
        predicates.put(ModelOverrideType.ANGLE, (float) (angle - 0.015625));
    } else if (xMaterial.equals(XMaterial.LIGHT)) {
        int level = 15;
        Object blockStateObj = item.getItemMeta().serialize().get("BlockStateTag");
        if (blockStateObj != null && blockStateObj instanceof Map) {
            Object levelObj = ((Map<?, Object>) blockStateObj).get("level");
            if (levelObj != null) {
                try {
                    level = Integer.parseInt(levelObj.toString().replace("i", ""));
                } catch (NumberFormatException e) {
                }
            }
        }
        predicates.put(ModelOverrideType.LEVEL, (float) level / 16F);
    } else if (item.getItemMeta() instanceof LeatherArmorMeta) {
        LeatherArmorMeta meta = (LeatherArmorMeta) item.getItemMeta();
        Color color = new Color(meta.getColor().asRGB());
        if (xMaterial.equals(XMaterial.LEATHER_HORSE_ARMOR)) {
            BufferedImage itemImage = InteractiveChatDiscordSrvAddon.plugin.resourceManager.getTextureManager().getTexture(ResourceRegistry.ITEM_TEXTURE_LOCATION + xMaterial.name().toLowerCase()).getTexture(32, 32);
            BufferedImage colorOverlay = ImageUtils.changeColorTo(ImageUtils.copyImage(itemImage), color);
            itemImage = ImageUtils.multiply(itemImage, colorOverlay);
            providedTextures.put(ResourceRegistry.LEATHER_HORSE_ARMOR_PLACEHOLDER, new GeneratedTextureResource(itemImage));
        } else {
            BufferedImage itemImage = InteractiveChatDiscordSrvAddon.plugin.resourceManager.getTextureManager().getTexture(ResourceRegistry.ITEM_TEXTURE_LOCATION + xMaterial.name().toLowerCase()).getTexture(32, 32);
            BufferedImage colorOverlay = ImageUtils.changeColorTo(ImageUtils.copyImage(itemImage), color);
            itemImage = ImageUtils.multiply(itemImage, colorOverlay);
            if (xMaterial.name().contains("HELMET")) {
                providedTextures.put(ResourceRegistry.LEATHER_HELMET_PLACEHOLDER, new GeneratedTextureResource(itemImage));
            } else if (xMaterial.name().contains("CHESTPLATE")) {
                providedTextures.put(ResourceRegistry.LEATHER_CHESTPLATE_PLACEHOLDER, new GeneratedTextureResource(itemImage));
            } else if (xMaterial.name().contains("LEGGINGS")) {
                providedTextures.put(ResourceRegistry.LEATHER_LEGGINGS_PLACEHOLDER, new GeneratedTextureResource(itemImage));
            } else if (xMaterial.name().contains("BOOTS")) {
                providedTextures.put(ResourceRegistry.LEATHER_BOOTS_PLACEHOLDER, new GeneratedTextureResource(itemImage));
            }
        }
    } else if (item.getItemMeta() instanceof PotionMeta) {
        if (xMaterial.equals(XMaterial.TIPPED_ARROW)) {
            PotionMeta meta = (PotionMeta) item.getItemMeta();
            PotionType potiontype = InteractiveChat.version.isOld() ? Potion.fromItemStack(item).getType() : meta.getBasePotionData().getType();
            BufferedImage tippedArrowHead = InteractiveChatDiscordSrvAddon.plugin.resourceManager.getTextureManager().getTexture(ResourceRegistry.ITEM_TEXTURE_LOCATION + "tipped_arrow_head").getTexture(32, 32);
            int color;
            try {
                if (meta.hasColor()) {
                    color = meta.getColor().asRGB();
                } else {
                    color = PotionUtils.getPotionBaseColor(potiontype);
                }
            } catch (Throwable e) {
                color = PotionUtils.getPotionBaseColor(PotionType.WATER);
            }
            BufferedImage colorOverlay = ImageUtils.changeColorTo(ImageUtils.copyImage(tippedArrowHead), color);
            tippedArrowHead = ImageUtils.multiply(tippedArrowHead, colorOverlay);
            providedTextures.put(ResourceRegistry.TIPPED_ARROW_HEAD_PLACEHOLDER, new GeneratedTextureResource(tippedArrowHead));
        } else {
            PotionMeta meta = (PotionMeta) item.getItemMeta();
            PotionType potiontype = InteractiveChat.version.isOld() ? Potion.fromItemStack(item).getType() : meta.getBasePotionData().getType();
            BufferedImage potionOverlay = InteractiveChatDiscordSrvAddon.plugin.resourceManager.getTextureManager().getTexture(ResourceRegistry.ITEM_TEXTURE_LOCATION + "potion_overlay").getTexture(32, 32);
            int color;
            try {
                if (meta.hasColor()) {
                    color = meta.getColor().asRGB();
                } else {
                    color = PotionUtils.getPotionBaseColor(potiontype);
                }
            } catch (Throwable e) {
                color = PotionUtils.getPotionBaseColor(PotionType.WATER);
            }
            BufferedImage colorOverlay = ImageUtils.changeColorTo(ImageUtils.copyImage(potionOverlay), color);
            potionOverlay = ImageUtils.multiply(potionOverlay, colorOverlay);
            providedTextures.put(ResourceRegistry.POTION_OVERLAY_PLACEHOLDER, new GeneratedTextureResource(potionOverlay));
            if (potiontype != null) {
                if (!(potiontype.name().equals("WATER") || potiontype.name().equals("AWKWARD") || potiontype.name().equals("MUNDANE") || potiontype.name().equals("THICK") || potiontype.name().equals("UNCRAFTABLE"))) {
                    requiresEnchantmentGlint = true;
                }
            }
        }
    } else if (xMaterial.isOneOf(Arrays.asList("CONTAINS:spawn_egg"))) {
        SpawnEggTintData tintData = TintUtils.getSpawnEggTint(xMaterial);
        if (tintData != null) {
            BufferedImage baseImage = InteractiveChatDiscordSrvAddon.plugin.resourceManager.getTextureManager().getTexture(ResourceRegistry.ITEM_TEXTURE_LOCATION + "spawn_egg").getTexture();
            BufferedImage overlayImage = InteractiveChatDiscordSrvAddon.plugin.resourceManager.getTextureManager().getTexture(ResourceRegistry.ITEM_TEXTURE_LOCATION + "spawn_egg_overlay").getTexture(baseImage.getWidth(), baseImage.getHeight());
            BufferedImage colorBase = ImageUtils.changeColorTo(ImageUtils.copyImage(baseImage), tintData.getBase());
            BufferedImage colorOverlay = ImageUtils.changeColorTo(ImageUtils.copyImage(overlayImage), tintData.getOverlay());
            baseImage = ImageUtils.multiply(baseImage, colorBase);
            overlayImage = ImageUtils.multiply(overlayImage, colorOverlay);
            providedTextures.put(ResourceRegistry.SPAWN_EGG_PLACEHOLDER, new GeneratedTextureResource(baseImage));
            providedTextures.put(ResourceRegistry.SPAWN_EGG_OVERLAY_PLACEHOLDER, new GeneratedTextureResource(overlayImage));
        }
    } else if (InteractiveChat.version.isLegacy() && xMaterial.isOneOf(Arrays.asList("CONTAINS:bed"))) {
        String colorName = xMaterial.name().replace("_BED", "").toLowerCase();
        BufferedImage bedTexture = InteractiveChatDiscordSrvAddon.plugin.resourceManager.getTextureManager().getTexture(ResourceRegistry.ENTITY_TEXTURE_LOCATION + "bed/" + colorName).getTexture();
        providedTextures.put(ResourceRegistry.LEGACY_BED_TEXTURE_PLACEHOLDER, new GeneratedTextureResource(bedTexture));
    }
    return new ItemStackProcessResult(requiresEnchantmentGlint, predicates, providedTextures, tintIndexData, directLocation);
}
Also used : GeneratedTextureResource(com.loohp.interactivechatdiscordsrvaddon.resources.textures.GeneratedTextureResource) TextureResource(com.loohp.interactivechatdiscordsrvaddon.resources.textures.TextureResource) ICPlayer(com.loohp.interactivechat.objectholders.ICPlayer) OfflineICPlayer(com.loohp.interactivechat.objectholders.OfflineICPlayer) HashMap(java.util.HashMap) LocalDate(java.time.LocalDate) BufferedImage(java.awt.image.BufferedImage) BannerAssetResult(com.loohp.interactivechatdiscordsrvaddon.graphics.BannerGraphics.BannerAssetResult) List(java.util.List) CompassMeta(org.bukkit.inventory.meta.CompassMeta) ModelOverrideType(com.loohp.interactivechatdiscordsrvaddon.resources.models.ModelOverride.ModelOverrideType) EnumMap(java.util.EnumMap) Vector(org.bukkit.util.Vector) SpawnEggTintData(com.loohp.interactivechatdiscordsrvaddon.utils.TintUtils.SpawnEggTintData) CrossbowMeta(org.bukkit.inventory.meta.CrossbowMeta) Color(java.awt.Color) GeneratedTextureResource(com.loohp.interactivechatdiscordsrvaddon.resources.textures.GeneratedTextureResource) PotionMeta(org.bukkit.inventory.meta.PotionMeta) XMaterial(com.loohp.interactivechat.libs.com.cryptomorin.xseries.XMaterial) TintIndexData(com.loohp.interactivechatdiscordsrvaddon.utils.TintUtils.TintIndexData) JSONObject(com.loohp.interactivechat.libs.org.json.simple.JSONObject) LeatherArmorMeta(org.bukkit.inventory.meta.LeatherArmorMeta) JSONParser(com.loohp.interactivechat.libs.org.json.simple.parser.JSONParser) JSONObject(com.loohp.interactivechat.libs.org.json.simple.JSONObject) ParseException(com.loohp.interactivechat.libs.org.json.simple.parser.ParseException) PotionType(org.bukkit.potion.PotionType) ItemStack(org.bukkit.inventory.ItemStack) HashMap(java.util.HashMap) Map(java.util.Map) EnumMap(java.util.EnumMap) Location(org.bukkit.Location)

Aggregations

JSONObject (com.loohp.interactivechat.libs.org.json.simple.JSONObject)11 JSONParser (com.loohp.interactivechat.libs.org.json.simple.parser.JSONParser)11 InputStreamReader (java.io.InputStreamReader)7 HashMap (java.util.HashMap)6 BOMInputStream (com.loohp.interactivechat.libs.org.apache.commons.io.input.BOMInputStream)5 BufferedImage (java.awt.image.BufferedImage)5 ArrayList (java.util.ArrayList)5 ResourceLoadingException (com.loohp.interactivechatdiscordsrvaddon.resources.ResourceLoadingException)4 ResourcePackFile (com.loohp.interactivechatdiscordsrvaddon.resources.ResourcePackFile)4 IOException (java.io.IOException)4 JSONArray (com.loohp.interactivechat.libs.org.json.simple.JSONArray)3 ICPlayer (com.loohp.interactivechat.objectholders.ICPlayer)3 OfflineICPlayer (com.loohp.interactivechat.objectholders.OfflineICPlayer)3 ModelOverrideType (com.loohp.interactivechatdiscordsrvaddon.resources.models.ModelOverride.ModelOverrideType)3 Gson (com.google.gson.Gson)2 GsonBuilder (com.google.gson.GsonBuilder)2 JsonParser (com.google.gson.JsonParser)2 XMaterial (com.loohp.interactivechat.libs.com.cryptomorin.xseries.XMaterial)2 Component (com.loohp.interactivechat.libs.net.kyori.adventure.text.Component)2 GeneratedTextureResource (com.loohp.interactivechatdiscordsrvaddon.resources.textures.GeneratedTextureResource)2