use of com.loohp.interactivechat.objectholders.OfflineICPlayer in project InteractiveChat-DiscordSRV-Addon by LOOHP.
the class ImageGeneration method getPlayerInventoryImage.
public static BufferedImage getPlayerInventoryImage(Inventory inventory, OfflineICPlayer player) throws Exception {
InteractiveChatDiscordSrvAddon.plugin.imageCounter.incrementAndGet();
InteractiveChatDiscordSrvAddon.plugin.inventoryImageCounter.incrementAndGet();
Debug.debug("ImageGeneration creating player inventory image of " + player.getName());
BufferedImage background = resourceManager.get().getTextureManager().getTexture(ResourceRegistry.IC_GUI_TEXTURE_LOCATION + "player_inventory").getTexture(356, 336);
Object playerInventoryData = player.getProperty("player_inventory");
if (playerInventoryData != null && playerInventoryData instanceof BufferedImage) {
BufferedImage playerBackground = ImageUtils.copyImage((BufferedImage) playerInventoryData);
Object mask = player.getProperty("player_inventory_mask");
if (mask == null) {
background = playerBackground;
} else {
background = ImageUtils.combineWithBinMask(background, playerBackground, (byte[]) mask);
}
}
String key = PLAYER_INVENTORY_CACHE_KEY + HashUtils.createSha1(player.getUniqueId().toString(), inventory) + ImageUtils.hash(background);
if (!inventory.contains(XMaterial.COMPASS.parseMaterial()) && !inventory.contains(XMaterial.CLOCK.parseMaterial()) && Stream.of(inventory.getContents()).anyMatch(each -> each != null && NBTEditor.contains(each, "CustomModelData"))) {
Cache<?> cache = Cache.getCache(key);
if (cache != null) {
return ImageUtils.copyImage((BufferedImage) cache.getObject());
}
}
BufferedImage target = new BufferedImage(background.getWidth(), background.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g = target.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
g.drawImage(background, 0, 0, null);
int i = 0;
// hotbar
for (; i < 9; i++) {
ItemStack item = inventory.getItem(i);
if (item == null || item.getType().equals(Material.AIR)) {
continue;
}
BufferedImage itemImage = getRawItemImage(item, player);
if (itemImage != null) {
g.drawImage(itemImage, 18 + (SPACING * (i % 9)), 286 + (SPACING * (i / 9)), null);
}
}
// inv
for (; i < 36; i++) {
ItemStack item = inventory.getItem(i);
if (item == null || item.getType().equals(Material.AIR)) {
continue;
}
BufferedImage itemImage = getRawItemImage(item, player);
if (itemImage != null) {
g.drawImage(itemImage, 18 + (SPACING * (i % 9)), 170 + (SPACING * ((i - 9) / 9)), null);
}
}
// boots
ItemStack boots = inventory.getItem(i);
if (boots == null || boots.getType().equals(Material.AIR)) {
g.drawImage(resourceManager.get().getTextureManager().getTexture(ResourceRegistry.ITEM_TEXTURE_LOCATION + "empty_armor_slot_boots").getTexture(32, 32), 18, 126 - (SPACING * (i - 36)), 32, 32, null);
} else {
BufferedImage itemImage = getRawItemImage(boots, player);
if (itemImage != null) {
g.drawImage(itemImage, 18, 126 - (SPACING * (i - 36)), null);
}
}
i++;
// leggings
ItemStack leggings = inventory.getItem(i);
if (leggings == null || leggings.getType().equals(Material.AIR)) {
g.drawImage(resourceManager.get().getTextureManager().getTexture(ResourceRegistry.ITEM_TEXTURE_LOCATION + "empty_armor_slot_leggings").getTexture(32, 32), 18, 126 - (SPACING * (i - 36)), 32, 32, null);
} else {
BufferedImage itemImage = getRawItemImage(leggings, player);
if (itemImage != null) {
g.drawImage(itemImage, 18, 126 - (SPACING * (i - 36)), null);
}
}
i++;
// chestplate
ItemStack chestplate = inventory.getItem(i);
if (chestplate == null || chestplate.getType().equals(Material.AIR)) {
g.drawImage(resourceManager.get().getTextureManager().getTexture(ResourceRegistry.ITEM_TEXTURE_LOCATION + "empty_armor_slot_chestplate").getTexture(32, 32), 18, 126 - (SPACING * (i - 36)), 32, 32, null);
} else {
BufferedImage itemImage = getRawItemImage(chestplate, player);
if (itemImage != null) {
g.drawImage(itemImage, 18, 126 - (SPACING * (i - 36)), null);
}
}
i++;
// helmet
ItemStack helmet = inventory.getItem(i);
if (helmet == null || helmet.getType().equals(Material.AIR)) {
g.drawImage(resourceManager.get().getTextureManager().getTexture(ResourceRegistry.ITEM_TEXTURE_LOCATION + "empty_armor_slot_helmet").getTexture(32, 32), 18, 126 - (SPACING * (i - 36)), 32, 32, null);
} else {
BufferedImage itemImage = getRawItemImage(helmet, player);
if (itemImage != null) {
g.drawImage(itemImage, 18, 126 - (SPACING * (i - 36)), null);
}
}
i++;
// offhand
if (!version.get().isOld()) {
ItemStack offhand = inventory.getItem(i);
if (offhand == null || offhand.getType().equals(Material.AIR)) {
g.drawImage(resourceManager.get().getTextureManager().getTexture(ResourceRegistry.ITEM_TEXTURE_LOCATION + "empty_armor_slot_shield").getTexture(32, 32), 162, 126, 32, 32, null);
} else {
BufferedImage itemImage = getRawItemImage(offhand, player);
if (itemImage != null) {
g.drawImage(itemImage, 162, 126, null);
}
}
}
// puppet
EntityEquipment equipment = player.getEquipment();
BufferedImage puppet = getFullBodyImage(player, equipment.getHelmet(), equipment.getChestplate(), equipment.getLeggings(), equipment.getBoots());
g.drawImage(puppet, 45, -10, null);
g.dispose();
Cache.putCache(key, target, InteractiveChatDiscordSrvAddon.plugin.cacheTimeout);
return target;
}
use of com.loohp.interactivechat.objectholders.OfflineICPlayer in project InteractiveChat-DiscordSRV-Addon by LOOHP.
the class ImageGeneration method getInventoryImage.
public static BufferedImage getInventoryImage(Inventory inventory, Component title, OfflineICPlayer player) throws Exception {
InteractiveChatDiscordSrvAddon.plugin.imageCounter.incrementAndGet();
InteractiveChatDiscordSrvAddon.plugin.inventoryImageCounter.incrementAndGet();
Debug.debug("ImageGeneration creating inventory image of " + player.getName());
String key = INVENTORY_CACHE_KEY + HashUtils.createSha1("Inventory", inventory);
if (!inventory.contains(XMaterial.COMPASS.parseMaterial()) && !inventory.contains(XMaterial.CLOCK.parseMaterial()) && Stream.of(inventory.getContents()).anyMatch(each -> each != null && NBTEditor.contains(each, "CustomModelData"))) {
Cache<?> cache = Cache.getCache(key);
if (cache != null) {
return ImageUtils.copyImage((BufferedImage) cache.getObject());
}
}
int rows = inventory.getSize() / 9;
GenericContainerBackgroundResult result = getGenericContainerBackground(rows, (image, x, y, fontSize, defaultTextColor) -> {
Component defaultColorTitle = title == null ? Component.translatable(TranslationKeyUtils.getDefaultContainerTitle()).color(defaultTextColor) : title.colorIfAbsent(defaultTextColor);
return ImageUtils.printComponentShadowless(resourceManager.get(), image, defaultColorTitle, InteractiveChatDiscordSrvAddon.plugin.language, version.get().isLegacyRGB(), x, y, fontSize);
});
BufferedImage background = result.getBackgroundImage();
BufferedImage target = new BufferedImage(background.getWidth(), background.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g = target.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
g.drawImage(background, 0, 0, null);
for (int i = 0; i < inventory.getSize(); i++) {
ItemStack item = inventory.getItem(i);
if (item == null || item.getType().equals(Material.AIR)) {
continue;
}
BufferedImage itemImage = getRawItemImage(item, player);
if (itemImage != null) {
g.drawImage(itemImage, result.getExpandedX() + 18 + (SPACING * (i % 9)), result.getExpandedY() + 38 + (SPACING * (i / 9)), null);
}
}
g.dispose();
Cache.putCache(key, target, InteractiveChatDiscordSrvAddon.plugin.cacheTimeout);
return target;
}
use of com.loohp.interactivechat.objectholders.OfflineICPlayer 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;
}
use of com.loohp.interactivechat.objectholders.OfflineICPlayer 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);
}
use of com.loohp.interactivechat.objectholders.OfflineICPlayer in project InteractiveChat-DiscordSRV-Addon by LOOHP.
the class DiscordCommands method onSlashCommand.
@Override
public void onSlashCommand(SlashCommandEvent event) {
if (!(event.getChannel() instanceof TextChannel)) {
return;
}
TextChannel channel = (TextChannel) event.getChannel();
String label = event.getName();
if (InteractiveChatDiscordSrvAddon.plugin.resourcepackCommandEnabled && label.equalsIgnoreCase(RESOURCEPACK_LABEL)) {
if (InteractiveChatDiscordSrvAddon.plugin.resourcepackCommandIsMainServer) {
event.deferReply().setEphemeral(true).queue();
List<MessageEmbed> messageEmbeds = new ArrayList<>();
Map<String, byte[]> attachments = new HashMap<>();
int i = 0;
for (ResourcePackInfo packInfo : InteractiveChatDiscordSrvAddon.plugin.resourceManager.getResourcePackInfo()) {
i++;
String packName = packInfo.getName();
Component description = packInfo.getDescription();
EmbedBuilder builder = new EmbedBuilder().setAuthor(packName).setThumbnail("attachment://" + i + ".png");
if (packInfo.getStatus()) {
builder.setDescription(PlainTextComponentSerializer.plainText().serialize(description));
ChatColor firstColor = ChatColorUtils.getColor(LegacyComponentSerializer.builder().useUnusualXRepeatedCharacterHexFormat().character(ChatColorUtils.COLOR_CHAR).build().serialize(description));
Color color = ColorUtils.getColor(firstColor);
if (color == null) {
color = new Color(0xAAAAAA);
} else if (color.equals(Color.WHITE)) {
color = new Color(0xFFFFFE);
}
builder.setColor(color);
if (packInfo.comparePackFormat() > 0) {
builder.setFooter(LanguageUtils.getTranslation(TranslationKeyUtils.getNewIncompatiblePack(), InteractiveChatDiscordSrvAddon.plugin.language));
} else if (packInfo.comparePackFormat() < 0) {
builder.setFooter(LanguageUtils.getTranslation(TranslationKeyUtils.getOldIncompatiblePack(), InteractiveChatDiscordSrvAddon.plugin.language));
}
} else {
builder.setColor(0xFF0000).setDescription(packInfo.getRejectedReason());
}
messageEmbeds.add(builder.build());
try {
attachments.put(i + ".png", ImageUtils.toArray(ImageUtils.resizeImageAbs(packInfo.getIcon(), 128, 128)));
} catch (IOException e) {
e.printStackTrace();
}
}
WebhookMessageUpdateAction<Message> action = event.getHook().setEphemeral(true).editOriginal("**" + LanguageUtils.getTranslation(TranslationKeyUtils.getServerResourcePack(), InteractiveChatDiscordSrvAddon.plugin.language) + "**").setEmbeds(messageEmbeds);
for (Entry<String, byte[]> entry : attachments.entrySet()) {
action = action.addFile(entry.getValue(), entry.getKey());
}
action.queue();
}
} else if (InteractiveChatDiscordSrvAddon.plugin.playerlistCommandEnabled && label.equalsIgnoreCase(PLAYERLIST_LABEL)) {
String minecraftChannel = discordsrv.getChannels().entrySet().stream().filter(entry -> channel.getId().equals(entry.getValue())).map(Map.Entry::getKey).findFirst().orElse(null);
if (minecraftChannel == null) {
if (InteractiveChatDiscordSrvAddon.plugin.respondToCommandsInInvalidChannels && InteractiveChatDiscordSrvAddon.plugin.playerlistCommandIsMainServer) {
event.reply(ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.invalidDiscordChannel)).setEphemeral(true).queue();
}
return;
}
AtomicBoolean deleted = new AtomicBoolean(false);
event.deferReply().queue(hook -> {
if (InteractiveChatDiscordSrvAddon.plugin.playerlistCommandDeleteAfter > 0) {
Bukkit.getScheduler().runTaskLaterAsynchronously(InteractiveChatDiscordSrvAddon.plugin, () -> {
if (!deleted.get()) {
hook.deleteOriginal().queue();
}
}, InteractiveChatDiscordSrvAddon.plugin.playerlistCommandDeleteAfter * 20L);
}
});
Map<OfflinePlayer, Integer> players;
if (InteractiveChat.bungeecordMode && InteractiveChatDiscordSrvAddon.plugin.playerlistCommandBungeecord && !Bukkit.getOnlinePlayers().isEmpty()) {
try {
List<ValueTrios<UUID, String, Integer>> bungeePlayers = InteractiveChatAPI.getBungeecordPlayerList().get();
players = new LinkedHashMap<>(bungeePlayers.size());
for (ValueTrios<UUID, String, Integer> playerinfo : bungeePlayers) {
if (!VanishUtils.isVanished(playerinfo.getFirst())) {
players.put(Bukkit.getOfflinePlayer(playerinfo.getFirst()), playerinfo.getThird());
}
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
event.getHook().editOriginal(ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.unableToRetrieveData) + " (-1)").queue();
return;
}
} else {
players = Bukkit.getOnlinePlayers().stream().filter(each -> !VanishUtils.isVanished(each.getUniqueId())).collect(Collectors.toMap(each -> each, each -> PlayerUtils.getPing(each)));
}
if (players.isEmpty()) {
event.getHook().editOriginal(ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.playerlistCommandEmptyServer)).queue();
} else {
int errorCode = -2;
try {
String[] groups = getGroups();
List<ValueTrios<UUID, Component, Integer>> player = new ArrayList<>();
Map<UUID, Integer> playerGroups = new HashMap<>();
for (Entry<OfflinePlayer, Integer> entry : players.entrySet()) {
OfflinePlayer bukkitOfflinePlayer = entry.getKey();
@SuppressWarnings("deprecation") OfflineICPlayer offlinePlayer = ICPlayerFactory.getUnsafe().getOfflineICPPlayerWithoutInitialization(bukkitOfflinePlayer.getUniqueId());
playerGroups.put(offlinePlayer.getUniqueId(), getPlayerGroupOrder(groups, bukkitOfflinePlayer));
player.add(new ValueTrios<>(offlinePlayer.getUniqueId(), LegacyComponentSerializer.legacySection().deserialize(ChatColorUtils.translateAlternateColorCodes('&', PlaceholderParser.parse(offlinePlayer, InteractiveChatDiscordSrvAddon.plugin.playerlistCommandPlayerFormat))), entry.getValue()));
}
errorCode--;
player.sort(Comparator.comparing(each -> playerGroups.getOrDefault(((ValueTrios<UUID, Component, Integer>) each).getFirst(), Integer.MIN_VALUE)).thenComparing(each -> ((ValueTrios<UUID, Component, Integer>) each).getFirst()));
errorCode--;
@SuppressWarnings("deprecation") OfflineICPlayer firstPlayer = ICPlayerFactory.getUnsafe().getOfflineICPPlayerWithoutInitialization(players.keySet().iterator().next().getUniqueId());
List<Component> header = new ArrayList<>();
if (!InteractiveChatDiscordSrvAddon.plugin.playerlistCommandHeader.isEmpty()) {
header = ComponentStyling.splitAtLineBreaks(LegacyComponentSerializer.legacySection().deserialize(ChatColorUtils.translateAlternateColorCodes('&', PlaceholderParser.parse(firstPlayer, InteractiveChatDiscordSrvAddon.plugin.playerlistCommandHeader.replace("{OnlinePlayers}", players.size() + "")))));
}
errorCode--;
List<Component> footer = new ArrayList<>();
if (!InteractiveChatDiscordSrvAddon.plugin.playerlistCommandFooter.isEmpty()) {
footer = ComponentStyling.splitAtLineBreaks(LegacyComponentSerializer.legacySection().deserialize(ChatColorUtils.translateAlternateColorCodes('&', PlaceholderParser.parse(firstPlayer, InteractiveChatDiscordSrvAddon.plugin.playerlistCommandFooter.replace("{OnlinePlayers}", players.size() + "")))));
}
errorCode--;
BufferedImage image = ImageGeneration.getTabListImage(header, footer, player, InteractiveChatDiscordSrvAddon.plugin.playerlistCommandAvatar, InteractiveChatDiscordSrvAddon.plugin.playerlistCommandPing);
errorCode--;
byte[] data = ImageUtils.toArray(image);
errorCode--;
event.getHook().editOriginalEmbeds(new EmbedBuilder().setImage("attachment://Tablist.png").setColor(InteractiveChatDiscordSrvAddon.plugin.playerlistCommandColor).build()).addFile(data, "Tablist.png").queue(success -> {
if (InteractiveChatDiscordSrvAddon.plugin.playerlistCommandDeleteAfter > 0) {
deleted.set(true);
success.delete().queueAfter(InteractiveChatDiscordSrvAddon.plugin.playerlistCommandDeleteAfter, TimeUnit.SECONDS);
}
});
} catch (Exception e) {
e.printStackTrace();
event.getHook().editOriginal(ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.unableToRetrieveData) + " (" + errorCode + ")").queue();
return;
}
}
} else if (InteractiveChatDiscordSrvAddon.plugin.shareItemCommandEnabled && (label.equalsIgnoreCase(ITEM_LABEL) || label.equalsIgnoreCase(ITEM_OTHER_LABEL))) {
String minecraftChannel = discordsrv.getChannels().entrySet().stream().filter(entry -> channel.getId().equals(entry.getValue())).map(Map.Entry::getKey).findFirst().orElse(null);
if (minecraftChannel == null) {
if (InteractiveChatDiscordSrvAddon.plugin.respondToCommandsInInvalidChannels && InteractiveChatDiscordSrvAddon.plugin.shareInvCommandIsMainServer) {
event.reply(ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.invalidDiscordChannel)).setEphemeral(true).queue();
}
return;
}
String discordUserId = event.getUser().getId();
List<OptionMapping> options = event.getOptionsByType(OptionType.USER);
if (options.size() > 0) {
discordUserId = options.get(0).getAsUser().getId();
}
UUID uuid = discordsrv.getAccountLinkManager().getUuid(discordUserId);
if (uuid == null) {
if (InteractiveChatDiscordSrvAddon.plugin.shareItemCommandIsMainServer) {
event.reply(ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.accountNotLinked)).setEphemeral(true).queue();
}
return;
}
int errorCode = -1;
try {
OfflineICPlayer offlineICPlayer = ICPlayerFactory.getOfflineICPlayer(uuid);
if (offlineICPlayer == null) {
if (InteractiveChatDiscordSrvAddon.plugin.shareItemCommandIsMainServer) {
event.reply(ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.unableToRetrieveData) + " (" + errorCode + ")").setEphemeral(true).queue();
}
return;
}
errorCode--;
if (InteractiveChatDiscordSrvAddon.plugin.shareItemCommandIsMainServer) {
event.deferReply().queue();
}
errorCode--;
ICPlayer icplayer = offlineICPlayer.getPlayer();
if (InteractiveChat.bungeecordMode && icplayer != null) {
if (icplayer.isLocal()) {
ItemStack[] equipment;
if (InteractiveChat.version.isOld()) {
// noinspection deprecation
equipment = new ItemStack[] { icplayer.getEquipment().getHelmet(), icplayer.getEquipment().getChestplate(), icplayer.getEquipment().getLeggings(), icplayer.getEquipment().getBoots(), icplayer.getEquipment().getItemInHand() };
} else {
equipment = new ItemStack[] { icplayer.getEquipment().getHelmet(), icplayer.getEquipment().getChestplate(), icplayer.getEquipment().getLeggings(), icplayer.getEquipment().getBoots(), icplayer.getEquipment().getItemInMainHand(), icplayer.getEquipment().getItemInOffHand() };
}
try {
BungeeMessageSender.forwardEquipment(System.currentTimeMillis(), icplayer.getUniqueId(), icplayer.isRightHanded(), icplayer.getSelectedSlot(), icplayer.getExperienceLevel(), equipment);
} catch (IOException e) {
e.printStackTrace();
}
} else {
TimeUnit.MILLISECONDS.sleep(InteractiveChat.remoteDelay);
}
}
errorCode--;
ItemStack itemStack = resolveItemStack(event, offlineICPlayer);
if (itemStack == null) {
itemStack = new ItemStack(Material.AIR);
}
errorCode--;
BufferedImage itemImage = ImageGeneration.getItemStackImage(itemStack, offlineICPlayer, true);
errorCode--;
String title = ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.shareItemCommandTitle.replace("{Player}", offlineICPlayer.getName()));
errorCode--;
Component itemTag = ItemDisplay.createItemDisplay(offlineICPlayer, itemStack, title, true, null);
Component resolvedItemTag = ComponentStringUtils.convertTranslatables(ComponentModernizing.modernize(itemTag), InteractiveChatDiscordSrvAddon.plugin.resourceManager.getLanguageManager().getTranslateFunction().ofLanguage(InteractiveChatDiscordSrvAddon.plugin.language));
Component component = LegacyComponentSerializer.legacySection().deserialize(InteractiveChatDiscordSrvAddon.plugin.shareItemCommandInGameMessageText.replace("{Player}", offlineICPlayer.getName())).replaceText(TextReplacementConfig.builder().matchLiteral("{ItemTag}").replacement(itemTag).build());
Component resolvedComponent = LegacyComponentSerializer.legacySection().deserialize(InteractiveChatDiscordSrvAddon.plugin.shareItemCommandInGameMessageText.replace("{Player}", offlineICPlayer.getName())).replaceText(TextReplacementConfig.builder().matchLiteral("{ItemTag}").replacement(resolvedItemTag).build());
errorCode--;
String key = "<DiscordShare=" + UUID.randomUUID() + ">";
components.put(key, component);
Bukkit.getScheduler().runTaskLater(InteractiveChatDiscordSrvAddon.plugin, () -> components.remove(key), 100);
errorCode--;
discordsrv.broadcastMessageToMinecraftServer(minecraftChannel, ComponentStringUtils.toDiscordSRVComponent(Component.text(key)), event.getUser());
if (InteractiveChatDiscordSrvAddon.plugin.shareItemCommandIsMainServer) {
errorCode--;
Player bukkitPlayer = icplayer == null || !icplayer.isLocal() ? null : icplayer.getLocalPlayer();
DiscordDescription description = DiscordItemStackUtils.getDiscordDescription(itemStack, bukkitPlayer);
errorCode--;
Color color = DiscordItemStackUtils.getDiscordColor(itemStack);
if (color == null || color.equals(Color.WHITE)) {
color = new Color(0xFFFFFE);
}
EmbedBuilder embedBuilder = new EmbedBuilder().setAuthor(description.getName(), null, "attachment://Item.png").setColor(color);
WebhookMessageUpdateAction<Message> action = event.getHook().editOriginal(PlainTextComponentSerializer.plainText().serialize(resolvedComponent));
errorCode--;
byte[] data = ImageUtils.toArray(itemImage);
action.addFile(data, "Item.png");
errorCode--;
if (InteractiveChatDiscordSrvAddon.plugin.itemUseTooltipImage) {
DiscordToolTip discordToolTip = DiscordItemStackUtils.getToolTip(itemStack, bukkitPlayer);
if (!discordToolTip.isBaseItem() || InteractiveChatDiscordSrvAddon.plugin.itemUseTooltipImageOnBaseItem) {
BufferedImage tooltip = ImageGeneration.getToolTipImage(discordToolTip.getComponents());
byte[] tooltipData = ImageUtils.toArray(tooltip);
action.addFile(tooltipData, "ToolTip.png");
embedBuilder.setImage("attachment://ToolTip.png");
} else {
embedBuilder.setDescription(description.getDescription().orElse(null));
}
} else {
embedBuilder.setDescription(description.getDescription().orElse(null));
}
errorCode--;
action.setEmbeds(embedBuilder.build()).queue();
}
} catch (Exception e) {
e.printStackTrace();
event.getHook().editOriginal(ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.unableToRetrieveData) + " (" + errorCode + ")").queue();
return;
}
} else if (InteractiveChatDiscordSrvAddon.plugin.shareInvCommandEnabled && (label.equalsIgnoreCase(INVENTORY_LABEL) || label.equalsIgnoreCase(INVENTORY_OTHER_LABEL))) {
String minecraftChannel = discordsrv.getChannels().entrySet().stream().filter(entry -> channel.getId().equals(entry.getValue())).map(Map.Entry::getKey).findFirst().orElse(null);
if (minecraftChannel == null) {
if (InteractiveChatDiscordSrvAddon.plugin.respondToCommandsInInvalidChannels && InteractiveChatDiscordSrvAddon.plugin.shareInvCommandIsMainServer) {
event.reply(ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.invalidDiscordChannel)).setEphemeral(true).queue();
}
return;
}
String discordUserId = event.getUser().getId();
List<OptionMapping> options = event.getOptionsByType(OptionType.USER);
if (options.size() > 0) {
discordUserId = options.get(0).getAsUser().getId();
}
UUID uuid = discordsrv.getAccountLinkManager().getUuid(discordUserId);
if (uuid == null) {
if (InteractiveChatDiscordSrvAddon.plugin.shareInvCommandIsMainServer) {
event.reply(ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.accountNotLinked)).setEphemeral(true).queue();
}
return;
}
int errorCode = -1;
try {
OfflineICPlayer offlineICPlayer = ICPlayerFactory.getOfflineICPlayer(uuid);
if (offlineICPlayer == null) {
if (InteractiveChatDiscordSrvAddon.plugin.shareInvCommandIsMainServer) {
event.reply(ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.unableToRetrieveData) + " (" + errorCode + ")").setEphemeral(true).queue();
}
return;
}
errorCode--;
if (InteractiveChatDiscordSrvAddon.plugin.shareInvCommandIsMainServer) {
event.deferReply().queue();
}
errorCode--;
ICPlayer icplayer = offlineICPlayer.getPlayer();
if (InteractiveChat.bungeecordMode && icplayer != null) {
if (icplayer.isLocal()) {
BungeeMessageSender.forwardInventory(System.currentTimeMillis(), uuid, icplayer.isRightHanded(), icplayer.getSelectedSlot(), icplayer.getExperienceLevel(), null, icplayer.getInventory());
} else {
TimeUnit.MILLISECONDS.sleep(InteractiveChat.remoteDelay);
}
}
errorCode--;
BufferedImage image = InteractiveChatDiscordSrvAddon.plugin.usePlayerInvView ? ImageGeneration.getPlayerInventoryImage(offlineICPlayer.getInventory(), offlineICPlayer) : ImageGeneration.getInventoryImage(offlineICPlayer.getInventory(), Component.translatable(TranslationKeyUtils.getDefaultContainerTitle()), offlineICPlayer);
errorCode--;
Component component = LegacyComponentSerializer.legacySection().deserialize(InteractiveChatDiscordSrvAddon.plugin.shareInvCommandInGameMessageText.replace("{Player}", offlineICPlayer.getName()));
errorCode--;
String title = ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.shareInvCommandTitle.replace("{Player}", offlineICPlayer.getName()));
errorCode--;
String sha1 = HashUtils.createSha1(true, offlineICPlayer.getSelectedSlot(), offlineICPlayer.getExperienceLevel(), title, offlineICPlayer.getInventory());
errorCode--;
layout0(offlineICPlayer, sha1, title);
errorCode--;
layout1(offlineICPlayer, sha1, title);
errorCode--;
component = component.hoverEvent(HoverEvent.showText(LegacyComponentSerializer.legacySection().deserialize(InteractiveChatDiscordSrvAddon.plugin.shareInvCommandInGameMessageHover)));
component = component.clickEvent(ClickEvent.runCommand("/interactivechat viewinv " + sha1));
errorCode--;
String key = "<DiscordShare=" + UUID.randomUUID() + ">";
components.put(key, component);
Bukkit.getScheduler().runTaskLater(InteractiveChatDiscordSrvAddon.plugin, () -> components.remove(key), 100);
errorCode--;
discordsrv.broadcastMessageToMinecraftServer(minecraftChannel, ComponentStringUtils.toDiscordSRVComponent(Component.text(key)), event.getUser());
if (InteractiveChatDiscordSrvAddon.plugin.shareInvCommandIsMainServer) {
errorCode--;
EmbedBuilder embedBuilder = new EmbedBuilder().setAuthor(title).setImage("attachment://Inventory.png").setColor(InteractiveChatDiscordSrvAddon.plugin.invColor);
WebhookMessageUpdateAction<Message> action = event.getHook().editOriginal(PlainTextComponentSerializer.plainText().serialize(component));
errorCode--;
byte[] data = ImageUtils.toArray(image);
action.addFile(data, "Inventory.png");
errorCode--;
if (InteractiveChatDiscordSrvAddon.plugin.invShowLevel) {
int level = offlineICPlayer.getExperienceLevel();
byte[] bottleData = ImageUtils.toArray(InteractiveChatDiscordSrvAddon.plugin.modelRenderer.render(32, 32, InteractiveChatDiscordSrvAddon.plugin.resourceManager, InteractiveChat.version.isOld(), "minecraft:item/experience_bottle", ModelDisplayPosition.GUI, false).getImage());
embedBuilder.setFooter(LanguageUtils.getTranslation(TranslationKeyUtils.getLevelTranslation(level), InteractiveChatDiscordSrvAddon.plugin.language).replaceFirst("%s|%d", level + ""), "attachment://Level.png");
action.addFile(bottleData, "Level.png");
}
errorCode--;
action.setEmbeds(embedBuilder.build()).queue();
}
} catch (Exception e) {
e.printStackTrace();
event.getHook().editOriginal(ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.unableToRetrieveData) + " (" + errorCode + ")").queue();
return;
}
} else if (InteractiveChatDiscordSrvAddon.plugin.shareEnderCommandEnabled && (label.equals(ENDERCHEST_LABEL) || label.equals(ENDERCHEST_OTHER_LABEL))) {
String minecraftChannel = discordsrv.getChannels().entrySet().stream().filter(entry -> channel.getId().equals(entry.getValue())).map(Map.Entry::getKey).findFirst().orElse(null);
if (minecraftChannel == null) {
if (InteractiveChatDiscordSrvAddon.plugin.respondToCommandsInInvalidChannels && InteractiveChatDiscordSrvAddon.plugin.shareEnderCommandIsMainServer) {
event.reply(ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.invalidDiscordChannel)).setEphemeral(true).queue();
}
return;
}
String discordUserId = event.getUser().getId();
List<OptionMapping> options = event.getOptionsByType(OptionType.USER);
if (options.size() > 0) {
discordUserId = options.get(0).getAsUser().getId();
}
UUID uuid = discordsrv.getAccountLinkManager().getUuid(discordUserId);
if (uuid == null) {
if (InteractiveChatDiscordSrvAddon.plugin.shareEnderCommandIsMainServer) {
event.reply(ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.accountNotLinked)).setEphemeral(true).queue();
}
return;
}
int errorCode = -1;
try {
OfflineICPlayer offlineICPlayer = ICPlayerFactory.getOfflineICPlayer(uuid);
if (offlineICPlayer == null) {
if (InteractiveChatDiscordSrvAddon.plugin.shareEnderCommandIsMainServer) {
event.reply(ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.unableToRetrieveData) + " (" + errorCode + ")").setEphemeral(true).queue();
}
return;
}
errorCode--;
if (InteractiveChatDiscordSrvAddon.plugin.shareEnderCommandIsMainServer) {
event.deferReply().queue();
}
errorCode--;
ICPlayer icplayer = offlineICPlayer.getPlayer();
if (InteractiveChat.bungeecordMode && icplayer != null) {
if (icplayer.isLocal()) {
BungeeMessageSender.forwardEnderchest(System.currentTimeMillis(), uuid, icplayer.isRightHanded(), icplayer.getSelectedSlot(), icplayer.getExperienceLevel(), null, icplayer.getEnderChest());
} else {
TimeUnit.MILLISECONDS.sleep(InteractiveChat.remoteDelay);
}
}
errorCode--;
BufferedImage image = ImageGeneration.getInventoryImage(offlineICPlayer.getEnderChest(), Component.translatable(TranslationKeyUtils.getEnderChestContainerTitle()), offlineICPlayer);
errorCode--;
Component component = LegacyComponentSerializer.legacySection().deserialize(InteractiveChatDiscordSrvAddon.plugin.shareEnderCommandInGameMessageText.replace("{Player}", offlineICPlayer.getName()));
errorCode--;
String title = ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.shareEnderCommandTitle.replace("{Player}", offlineICPlayer.getName()));
errorCode--;
String sha1 = HashUtils.createSha1(true, offlineICPlayer.getSelectedSlot(), offlineICPlayer.getExperienceLevel(), title, offlineICPlayer.getEnderChest());
errorCode--;
ender(offlineICPlayer, sha1, title);
errorCode--;
component = component.hoverEvent(HoverEvent.showText(LegacyComponentSerializer.legacySection().deserialize(InteractiveChatDiscordSrvAddon.plugin.shareEnderCommandInGameMessageHover)));
component = component.clickEvent(ClickEvent.runCommand("/interactivechat viewender " + sha1));
errorCode--;
String key = "<DiscordShare=" + UUID.randomUUID() + ">";
components.put(key, component);
Bukkit.getScheduler().runTaskLater(InteractiveChatDiscordSrvAddon.plugin, () -> components.remove(key), 100);
errorCode--;
discordsrv.broadcastMessageToMinecraftServer(minecraftChannel, ComponentStringUtils.toDiscordSRVComponent(Component.text(key)), event.getUser());
if (InteractiveChatDiscordSrvAddon.plugin.shareEnderCommandIsMainServer) {
errorCode--;
byte[] data = ImageUtils.toArray(image);
errorCode--;
event.getHook().editOriginal(PlainTextComponentSerializer.plainText().serialize(component)).setEmbeds(new EmbedBuilder().setAuthor(title).setImage("attachment://Inventory.png").setColor(InteractiveChatDiscordSrvAddon.plugin.enderColor).build()).addFile(data, "Inventory.png").queue();
}
} catch (Exception e) {
e.printStackTrace();
event.getHook().editOriginal(ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.unableToRetrieveData) + " (" + errorCode + ")").queue();
return;
}
}
}
Aggregations