Search in sources :

Example 6 with Entity

use of net.md_5.bungee.api.chat.hover.content.Entity in project solinia3-core by mixxit.

the class CommandPet method onCommand.

@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
    // TODO Auto-generated method stub
    if (sender instanceof Player) {
        try {
            Player player = (Player) sender;
            LivingEntity pet = StateManager.getInstance().getEntityManager().getPet(player.getUniqueId());
            if (pet == null) {
                player.sendMessage("You don't have a pet");
                return true;
            }
            if (pet instanceof Sittable) {
                Sittable sittable = (Sittable) pet;
                if (sittable.isSitting()) {
                    player.sendMessage("You cannot control a pet which is sitting");
                    return true;
                }
            }
            ISoliniaLivingEntity petLivingEntity = SoliniaLivingEntityAdapter.Adapt(pet);
            ISoliniaPlayer solPlayer = SoliniaPlayerAdapter.Adapt(player);
            if (petLivingEntity == null || solPlayer == null)
                return false;
            if (args.length > 0) {
                String petcommand = args[0];
                if (petcommand.equals("leave")) {
                    if (petLivingEntity != null) {
                        petLivingEntity.clearHateList();
                        if (petLivingEntity.IsCorePet()) {
                            solPlayer.killAllPets();
                        } else {
                            StateManager.getInstance().getEntityManager().removePet(player.getUniqueId(), !petLivingEntity.isCharmed());
                            petLivingEntity.clearHateList();
                        }
                        player.setLastDamageCause(null);
                    }
                }
                if (petcommand.equals("back")) {
                    if (petLivingEntity != null) {
                        ISoliniaNPC npc = StateManager.getInstance().getConfigurationManager().getNPC(petLivingEntity.getNpcid());
                        if (npc != null)
                            if (npc.isPetControllable() == false) {
                                player.sendMessage("This pet is not controllable");
                                return true;
                            }
                        player.setLastDamageCause(null);
                        petLivingEntity.clearHateList();
                        ChatUtils.SendHint(player, HINT.PET_BACKINGOFFTGT, "", false);
                        EntityUtils.teleportSafely(pet, player.getLocation());
                    }
                }
                if (petcommand.equals("attack")) {
                    if (solPlayer.getEntityTarget() == null) {
                        ChatUtils.SendHint(player, HINT.NEED_TARGET, "", false);
                    }
                    LivingEntity targetentity = solPlayer.getEntityTarget();
                    if (targetentity != null && !targetentity.getUniqueId().equals(player.getUniqueId())) {
                        if (petLivingEntity != null) {
                            ISoliniaNPC npc = StateManager.getInstance().getConfigurationManager().getNPC(petLivingEntity.getNpcid());
                            if (npc != null)
                                if (npc.isPetControllable() == false) {
                                    player.sendMessage("This pet is not controllable");
                                    return true;
                                }
                        }
                        EntityUtils.teleportSafely(pet, player.getLocation());
                        petLivingEntity.setAttackTarget(null);
                        // Mez cancel target
                        Timestamp mezExpiry = StateManager.getInstance().getEntityManager().getMezzed(targetentity);
                        if (mezExpiry != null) {
                            petLivingEntity.setAttackTarget(null);
                            player.sendMessage("You cannot send your pet to attack a mezzed target");
                            return false;
                        }
                        if (pet.getUniqueId().equals(targetentity.getUniqueId())) {
                            petLivingEntity.setAttackTarget(null);
                            player.sendMessage("You cannot send your pet to attack itself");
                            return false;
                        }
                        if (petLivingEntity.getOwnerEntity().getUniqueId().equals(targetentity.getUniqueId())) {
                            petLivingEntity.setAttackTarget(null);
                            player.sendMessage("You cannot send your pet to attack you!");
                            return false;
                        }
                        ISoliniaPlayer tmpPlayer = SoliniaPlayerAdapter.Adapt(player);
                        if (tmpPlayer != null && tmpPlayer.isInGroup(targetentity)) {
                            petLivingEntity.setAttackTarget(null);
                            player.sendMessage("You cannot send your pet to attack your group!");
                            return false;
                        }
                        if (!pet.getUniqueId().equals(targetentity.getUniqueId())) {
                            petLivingEntity.setAttackTarget(targetentity);
                            player.sendMessage("You send your pet to attack!");
                            return true;
                        }
                        ChatUtils.SendHint(player, HINT.PET_ATTACKINGTGT, targetentity.getCustomName(), false);
                    }
                    return true;
                }
                if (petcommand.equals("equip")) {
                    if (petLivingEntity != null) {
                        ISoliniaNPC npc = StateManager.getInstance().getConfigurationManager().getNPC(petLivingEntity.getNpcid());
                        if (npc != null)
                            if (npc.isPetControllable() == false) {
                                player.sendMessage("This pet is not controllable/equippable");
                                return true;
                            }
                    }
                    PetEquip(player, pet);
                }
                if (petcommand.equals("hatelist")) {
                    player.sendMessage("Hate List: ");
                    if (petLivingEntity != null) {
                        petLivingEntity.sendHateList(player);
                    }
                }
            }
            player.sendMessage("Pet Name: " + pet.getName() + " Pet Level: " + petLivingEntity.getMentorLevel());
            player.sendMessage("Pet HP: " + pet.getHealth() + "/" + pet.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue());
            EntityInsentient entityhandle = (EntityInsentient) ((org.bukkit.craftbukkit.v1_15_R1.entity.CraftLivingEntity) pet).getHandle();
            double dmg = entityhandle.getAttributeInstance(GenericAttributes.ATTACK_DAMAGE).getValue();
            player.sendMessage("Pet DMG: " + dmg + " (Hand to Hand)");
            Entity target = ((Creature) pet).getTarget();
            if (target == null) {
                player.sendMessage("Pet Target: None");
            } else {
                player.sendMessage("Pet Target: " + target.getCustomName() + "/" + target.getName());
            }
            player.sendMessage("STR: " + petLivingEntity.getStrength() + " STA: " + petLivingEntity.getStamina() + " AGI: " + petLivingEntity.getAgility() + " DEX: " + petLivingEntity.getDexterity() + " INT: " + petLivingEntity.getIntelligence() + " WIS: " + petLivingEntity.getWisdom() + " CHA: " + petLivingEntity.getCharisma());
            player.sendMessage("Pet Armour Class Mitigation (AC): " + petLivingEntity.getMitigationAC());
            player.sendMessage("Pet Attack Value: " + petLivingEntity.getTotalAtk());
            player.sendMessage("Pet Attack Speed: " + ChatColor.GOLD + petLivingEntity.getHaste() + "%" + ChatColor.RESET);
            player.sendMessage("Pet MainWeapon Attack Rate (Seconds): " + ChatColor.GOLD + petLivingEntity.getAutoAttackTimerFrequencySeconds() + ChatColor.RESET);
            player.sendMessage("Pet Total Rune of: " + petLivingEntity.getRune());
            player.sendMessage("Skills:");
            if (petLivingEntity.getClassObj() != null) {
                if (petLivingEntity.getClassObj().getDodgelevel() > 0)
                    if (petLivingEntity.getMentorLevel() >= petLivingEntity.getClassObj().getDodgelevel())
                        player.sendMessage(ChatColor.GRAY + "Dodge Skill: " + petLivingEntity.getSkill(SkillType.Dodge));
                if (petLivingEntity.getClassObj().getRipostelevel() > 0)
                    if (petLivingEntity.getMentorLevel() >= petLivingEntity.getClassObj().getRipostelevel())
                        player.sendMessage(ChatColor.GRAY + "Riposte Skill: " + petLivingEntity.getSkill(SkillType.Riposte));
                if (petLivingEntity.getClassObj().getDoubleattacklevel() > 0)
                    if (petLivingEntity.getMentorLevel() >= petLivingEntity.getClassObj().getDoubleattacklevel())
                        player.sendMessage(ChatColor.GRAY + "Double Attack Skill: " + petLivingEntity.getSkill(SkillType.DoubleAttack));
                if (petLivingEntity.getClassObj().getSafefalllevel() > 0)
                    if (petLivingEntity.getMentorLevel() >= petLivingEntity.getClassObj().getSafefalllevel())
                        player.sendMessage(ChatColor.GRAY + "Safefall Skill: " + petLivingEntity.getSkill(SkillType.SafeFall));
                if (petLivingEntity.getClassObj().getDualwieldlevel() > 0)
                    if (petLivingEntity.getMentorLevel() >= petLivingEntity.getClassObj().getDualwieldlevel())
                        player.sendMessage(ChatColor.GRAY + "Dual Wield: " + petLivingEntity.getSkill(SkillType.DualWield));
            }
            player.sendMessage("Active Effects:");
            SoliniaEntitySpells spells = StateManager.getInstance().getEntityManager().getActiveEntitySpells(pet);
            for (SoliniaActiveSpell activeSpell : spells.getActiveSpells()) {
                ISoliniaSpell spell = StateManager.getInstance().getConfigurationManager().getSpell(activeSpell.getSpellId());
                String removetext = "";
                ChatColor spellcolor = ChatColor.GREEN;
                if (spell.isBeneficial()) {
                    removetext = "Removable spell";
                } else {
                    removetext = "Unremovable spell";
                    spellcolor = ChatColor.RED;
                }
                TextComponent tc = new TextComponent();
                tc.setText("- " + spellcolor + spell.getName() + ChatColor.RESET + " " + activeSpell.getTicksLeft() + " ticks left - ");
                TextComponent tc2 = new TextComponent();
                tc2.setText(removetext);
                tc.addExtra(tc2);
                sender.spigot().sendMessage(tc);
            }
            player.sendMessage("Pet subcommands: /pet back | /pet equip | /pet attack | /pet leave");
            return true;
        } catch (CoreStateInitException e) {
        }
    }
    return true;
}
Also used : TextComponent(net.md_5.bungee.api.chat.TextComponent) ISoliniaLivingEntity(com.solinia.solinia.Interfaces.ISoliniaLivingEntity) Entity(org.bukkit.entity.Entity) LivingEntity(org.bukkit.entity.LivingEntity) Player(org.bukkit.entity.Player) ISoliniaPlayer(com.solinia.solinia.Interfaces.ISoliniaPlayer) Sittable(org.bukkit.entity.Sittable) Creature(org.bukkit.entity.Creature) ISoliniaSpell(com.solinia.solinia.Interfaces.ISoliniaSpell) EntityInsentient(net.minecraft.server.v1_15_R1.EntityInsentient) Timestamp(java.sql.Timestamp) SoliniaEntitySpells(com.solinia.solinia.Models.SoliniaEntitySpells) ISoliniaLivingEntity(com.solinia.solinia.Interfaces.ISoliniaLivingEntity) LivingEntity(org.bukkit.entity.LivingEntity) ISoliniaLivingEntity(com.solinia.solinia.Interfaces.ISoliniaLivingEntity) CoreStateInitException(com.solinia.solinia.Exceptions.CoreStateInitException) ISoliniaNPC(com.solinia.solinia.Interfaces.ISoliniaNPC) ISoliniaPlayer(com.solinia.solinia.Interfaces.ISoliniaPlayer) ChatColor(net.md_5.bungee.api.ChatColor) SoliniaActiveSpell(com.solinia.solinia.Models.SoliniaActiveSpell)

Example 7 with Entity

use of net.md_5.bungee.api.chat.hover.content.Entity in project solinia3-core by mixxit.

the class ChatUtils method SendHint.

public static void SendHint(LivingEntity entity, HINT hint, String referenceCode, boolean sendNearby, ItemStack itemStack) {
    if (entity == null)
        return;
    String channelCode = "" + hint.ordinal();
    String message = "";
    boolean showItemLinks = false;
    switch(hint) {
        case NPC_RAMPAGE:
            message = "* " + entity.getCustomName() + " goes on a RAMPAGE!";
            break;
        case PET_FLURRY:
            message = "* " + entity.getCustomName() + " unleashes a flurry of attacks!";
            break;
        case NPC_FLURRY:
            message = "* " + entity.getCustomName() + " unleashes a flurry of attacks!";
            break;
        case YOU_FLURRY:
            message = "* You unleash a flurry of attacks";
            break;
        case SKILLUP:
            String[] skill = referenceCode.split("\\^");
            message = ChatColor.YELLOW + "* You get better at " + skill[0] + " (" + skill[1] + ")";
            break;
        case INTERRUPTED:
            message = referenceCode + "'s casting was interrupted";
            break;
        case PET_BEGIN_ABILITY:
            String[] potherBeginAbility = referenceCode.split("\\^");
            message = potherBeginAbility[0] + " begins their ability [" + potherBeginAbility[1] + "]";
            break;
        case NPC_BEGIN_ABILITY:
            String[] notherBeginAbility = referenceCode.split("\\^");
            message = notherBeginAbility[0] + " begins their ability [" + notherBeginAbility[1] + "]";
            break;
        case OTHER_BEGIN_ABILITY:
            String[] otherBeginAbility = referenceCode.split("\\^");
            message = otherBeginAbility[0] + " begins their ability [" + otherBeginAbility[1] + "]";
            break;
        case FINISH_ABILITY:
            message = "You finish your ability";
            break;
        case PET_BACKINGOFFTGT:
            message = "As you wish master";
            break;
        case PET_ATTACKINGTGT:
            message = "Attacking " + referenceCode + " master";
            break;
        case OOC_MESSAGE:
            message = referenceCode;
            if (message.contains("itemlink"))
                showItemLinks = true;
            break;
        case DISCORD_MESSAGE:
            message = referenceCode;
            break;
        case MASTERWUFULL:
            message = "The spirit of The Master fills you!  You gain " + referenceCode + " additional attack(s).";
            break;
        case HITFORDMGBY:
            String[] referenceCodes = referenceCode.split(",");
            String defender = referenceCodes[0];
            String damage = referenceCodes[1];
            String skilltype = referenceCodes[2];
            String attacker = referenceCodes[3];
            message = attacker + " hit " + defender + " for " + damage + " points of " + skilltype + " damage";
            break;
        case HITTHEMBUTMISSED:
            message = "You tried to hit " + referenceCode + ", but missed!";
            break;
        case PETHITTHEMBUTMISSED:
            message = "Your pet tried to hit " + referenceCode + ", but missed!";
            break;
        case HITYOUBUTMISSED:
            message = referenceCode + " tried to hit you but missed!";
            break;
        case NEED_TARGET:
            message = "You must select a target (See SoliniaMOD Keybinds)";
            break;
        case PICKEDUP_SPELL:
            message = "You have picked up a spell. You can add this to your spellbook with /spellbook add. Up to 8 spells can be memorised and cast from the memorisation bar at the top of the screen  (See SoliniaMOD Keybinds)";
            break;
        case INSUFFICIENT_REAGENTS:
            message = "Insufficient Reagents [" + referenceCode + "] (Check spell and see /reagents)";
            break;
        case RUNE_ABSORBED:
            message = "Your Rune absorbed " + referenceCode + " points of damage";
            break;
        case SERVER_SAVE_BEGIN:
            message = "RPG State is backing up, this may take some time";
            break;
        case SERVER_SAVE_FINISH:
            message = "RPG State backup complete";
            break;
        case SPELL_INVALIDEFFECT:
            message = "This is not a valid effect for this entity: " + referenceCode;
            break;
        case FOCUSEFFECTFLICKER:
            String[] referenceCodesFocus = referenceCode.split("\\^");
            message = "Your " + referenceCodesFocus[0] + " " + referenceCodesFocus[1];
            break;
        case INSUFFICIENT_LEVEL_GEAR:
            message = "You are not sufficient level to use this equipment";
            break;
        case EXCEEDED_CLAIMXP:
            message = "You have exceeded your maximum pending XP! Please /claimxp your additional XP before more can be gained (max: " + referenceCode + ")";
            break;
        case PLAYER_JOIN:
            message = referenceCode;
            break;
        case BER_CRITICAL_DMG:
            message = "Your berserker status causes additional critical blow damage! " + referenceCode;
            break;
        case CRITICAL_DMG:
            message = "You scored additional critical damage! " + referenceCode;
            break;
        case CHARM_CHA_FAIL:
            message = ChatColor.DARK_AQUA + "Your pet has freed themselves of your control! (Charisma)" + ChatColor.RESET;
            break;
        case STARTS_TO_SING:
            String[] sings = referenceCode.split("\\^");
            message = sings[0] + " starts to sing " + sings[1];
            break;
        case STOPS_SINGING:
            String[] stopsing = referenceCode.split("\\^");
            message = stopsing[0] + " stops singing " + stopsing[1];
            break;
        case SPELL_WORN_OFF_OF:
            String[] referenceCodesWornOffOf = referenceCode.split("\\^");
            message = ChatColor.DARK_AQUA + "Your " + referenceCodesWornOffOf[0] + " spell has worn off of " + referenceCodesWornOffOf[1] + ChatColor.RESET;
            break;
        case CAST_ON_YOU_SONG:
            message = referenceCode;
            break;
        case CAST_ON_YOU:
            message = referenceCode;
            break;
        case CAST_ON_OTHER_SONG:
            String[] castonothersong = referenceCode.split("\\^");
            message = castonothersong[0] + castonothersong[1];
            break;
        case CAST_ON_OTHER:
            String[] castonother = referenceCode.split("\\^");
            message = castonother[0] + castonother[1];
            break;
        case ASSASSINATES:
            message = referenceCode + " ASSASSINATES their victim!!";
            break;
        case BONUSEXPERIENCE:
            message = "You were given bonus XP from a xp bonus /hotzone or potion! (See /stats && /hotzones)";
            break;
        case GAINEXPERIENCE:
            message = ChatColor.YELLOW + "You gain experience (" + referenceCode + "% into level)";
            break;
        case LOSTEXPERIENCE:
            message = ChatColor.RED + "You lost experience (" + referenceCode + "% into level)";
            break;
        case FACTION_GOTBETTER:
            message = "Your faction standing with " + referenceCode + " could not possibly got better";
            break;
        case FACTION_GOTWORSE:
            message = "Your faction standing with " + referenceCode + " could not possibly got worse";
            break;
        case FACTION_COULDNOTGETWORSE:
            message = "Your faction standing with " + referenceCode + " could not possibly get any worse";
            break;
        case FACTION_COULDNOTGETBETTER:
            message = "Your faction standing with " + referenceCode + " could not possibly get any better";
            break;
        case DUALWIELD:
            message = "You dual wield!";
            break;
        case DOUBLEATTACK:
            message = "You double attack!";
            break;
        case SLAYUNDEAD:
            message = referenceCode + "'s holy blade cleanses their target!";
            break;
        case ITEM_DISCOVERED:
            String[] itemDiscoveryData = referenceCode.split("\\^");
            try {
                ISoliniaItem discoveredSolItem = StateManager.getInstance().getConfigurationManager().getItem(Integer.parseInt(itemDiscoveryData[0]));
                if (discoveredSolItem == null)
                    return;
                itemStack = discoveredSolItem.asItemStack();
                showItemLinks = true;
            } catch (Exception e) {
                e.printStackTrace();
                return;
            }
            message = "An item has been discovered by " + itemDiscoveryData[1];
            break;
        case ARTIFACT_DISCOVERED:
            try {
                ISoliniaItem discoveredSolItem = StateManager.getInstance().getConfigurationManager().getItem(Integer.parseInt(referenceCode));
                if (discoveredSolItem == null)
                    return;
                itemStack = discoveredSolItem.asItemStack();
                showItemLinks = true;
            } catch (Exception e) {
                e.printStackTrace();
                return;
            }
            message = "A unique artifact has been discovered";
            break;
    }
    try {
        TextComponent tc = new TextComponent("");
        if (!hint.equals(HINT.OOC_MESSAGE)) {
            TextComponent clickTextComponent = new TextComponent("");
            String title = ChatColor.GRAY + "<" + channelCode + ">" + ChatColor.RESET;
            clickTextComponent.setText(title);
            clickTextComponent.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, "/togglehint " + hint.name().toUpperCase()));
            clickTextComponent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder("Click to toggle off").create()));
            tc.addExtra(clickTextComponent);
        }
        TextComponent fullTextComponent = new TextComponent(TextComponent.fromLegacyText(ChatColor.GRAY + message + ChatColor.RESET));
        if (itemStack != null)
            fullTextComponent = decorateTextComponentsWithHovers(fullTextComponent, itemStack, showItemLinks);
        tc.addExtra(fullTextComponent);
        if (entity instanceof Player) {
            ISoliniaPlayer solPlayer = SoliniaPlayerAdapter.Adapt((Player) entity);
            if (solPlayer != null && solPlayer.getHintSetting(hint) != HintSetting.Off) {
                ((Player) entity).spigot().sendMessage(solPlayer.getHintSettingAsChatMessageType(hint), tc);
            }
        }
        if (sendNearby && entity != null)
            for (Player player : Bukkit.getOnlinePlayers()) {
                if (player.getLocation().distance(entity.getLocation()) <= ChatUtils.GetLocalSayRange(entity.getLocation().getWorld().getName())) {
                    // already received message thankst
                    if (player.getUniqueId().equals(entity.getUniqueId()))
                        continue;
                    ISoliniaPlayer solPlayer = SoliniaPlayerAdapter.Adapt(player);
                    if (solPlayer != null && solPlayer.getHintSetting(hint) != HintSetting.Off)
                        player.spigot().sendMessage(solPlayer.getHintSettingAsChatMessageType(hint), tc);
                }
            }
    } catch (CoreStateInitException e) {
    }
}
Also used : TextComponent(net.md_5.bungee.api.chat.TextComponent) HoverEvent(net.md_5.bungee.api.chat.HoverEvent) Player(org.bukkit.entity.Player) ISoliniaPlayer(com.solinia.solinia.Interfaces.ISoliniaPlayer) ISoliniaItem(com.solinia.solinia.Interfaces.ISoliniaItem) CoreStateInitException(com.solinia.solinia.Exceptions.CoreStateInitException) ClickEvent(net.md_5.bungee.api.chat.ClickEvent) ISoliniaPlayer(com.solinia.solinia.Interfaces.ISoliniaPlayer) ComponentBuilder(net.md_5.bungee.api.chat.ComponentBuilder) CoreStateInitException(com.solinia.solinia.Exceptions.CoreStateInitException)

Example 8 with Entity

use of net.md_5.bungee.api.chat.hover.content.Entity in project solinia3-core by mixxit.

the class SoliniaPlayer method setInteraction.

@Override
public void setInteraction(UUID interaction, ISoliniaNPC npc) {
    if (interaction == null) {
        this.interaction = interaction;
        this.getBukkitPlayer().sendMessage(ChatColor.GRAY + "* You are no longer interacting");
        return;
    }
    Entity e = Bukkit.getEntity(interaction);
    if (e == null)
        return;
    if (!(e instanceof LivingEntity))
        return;
    if (((Creature) e).getTarget() != null) {
        if (interaction != null) {
            this.getBukkitPlayer().sendMessage(ChatColor.GRAY + "* You are no longer interacting");
            interaction = null;
        }
        return;
    }
    if (Bukkit.getEntity(interaction) instanceof Wolf) {
        Wolf w = (Wolf) Bukkit.getEntity(interaction);
        if (w.getOwner() != null)
            return;
    }
    this.interaction = interaction;
    if (npc != null) {
        this.getBukkitPlayer().sendMessage(ChatColor.GRAY + "* You are now interacting with " + Bukkit.getEntity(interaction).getName() + " [" + npc.getId() + "] - Anything you type will be heared by the NPC and possibly responded to. Words in pink are trigger words you can type");
        if (npc.getMerchantid() > 0) {
            try {
                StateManager.getInstance().getEntityManager().getLivingEntity((LivingEntity) e).say("i have a [" + ChatColor.LIGHT_PURPLE + "SHOP" + ChatColor.AQUA + "] available if you are interested in buying or selling something", getBukkitPlayer());
            } catch (CoreStateInitException cse) {
            // 
            }
        }
        for (ISoliniaNPCEventHandler eventHandler : npc.getEventHandlers()) {
            if (!eventHandler.getInteractiontype().equals(InteractionType.ITEM))
                continue;
            // See if player has any items that are wanted
            int itemId = Integer.parseInt(eventHandler.getTriggerdata());
            if (itemId == 0)
                continue;
            if (Utils.getPlayerTotalCountOfItemId(getBukkitPlayer(), itemId) < 1)
                continue;
            try {
                ISoliniaItem item = StateManager.getInstance().getConfigurationManager().getItem(itemId);
                TextComponent tc = new TextComponent();
                tc.setText(ChatColor.YELLOW + "[QUEST] ");
                TextComponent tc2 = new TextComponent();
                tc2.setText(ChatColor.GRAY + "- Click here to give " + item.getDisplayname() + ChatColor.RESET);
                tc2.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/npcgive " + itemId));
                tc.addExtra(tc2);
                getBukkitPlayer().spigot().sendMessage(tc);
            } catch (CoreStateInitException eNotInitialised) {
                continue;
            }
        }
    }
}
Also used : ISoliniaLivingEntity(com.solinia.solinia.Interfaces.ISoliniaLivingEntity) LivingEntity(org.bukkit.entity.LivingEntity) TextComponent(net.md_5.bungee.api.chat.TextComponent) ISoliniaLivingEntity(com.solinia.solinia.Interfaces.ISoliniaLivingEntity) Entity(org.bukkit.entity.Entity) LivingEntity(org.bukkit.entity.LivingEntity) ISoliniaItem(com.solinia.solinia.Interfaces.ISoliniaItem) ISoliniaNPCEventHandler(com.solinia.solinia.Interfaces.ISoliniaNPCEventHandler) CoreStateInitException(com.solinia.solinia.Exceptions.CoreStateInitException) ClickEvent(net.md_5.bungee.api.chat.ClickEvent) Wolf(org.bukkit.entity.Wolf)

Example 9 with Entity

use of net.md_5.bungee.api.chat.hover.content.Entity in project Denizen-For-Bukkit by DenizenScript.

the class BukkitElementProperties method registerTags.

public static void registerTags() {
    // <--[tag]
    // @attribute <ElementTag.as_biome>
    // @returns BiomeTag
    // @group conversion
    // @description
    // Returns the element as a BiomeTag. Note: the value must be a valid biome.
    // -->
    PropertyParser.<BukkitElementProperties, BiomeTag>registerStaticTag(BiomeTag.class, "as_biome", (attribute, object) -> {
        return ElementTag.handleNull(object.asString(), BiomeTag.valueOf(object.asString(), new BukkitTagContext(attribute.getScriptEntry())), "BiomeTag", attribute.hasAlternative());
    });
    // <--[tag]
    // @attribute <ElementTag.as_chunk>
    // @returns ChunkTag
    // @group conversion
    // @description
    // Returns the element as a chunk. Note: the value must be a valid chunk.
    // -->
    PropertyParser.<BukkitElementProperties, ChunkTag>registerTag(ChunkTag.class, "as_chunk", (attribute, object) -> {
        return ElementTag.handleNull(object.asString(), ChunkTag.valueOf(object.asString(), new BukkitTagContext(attribute.getScriptEntry())), "ChunkTag", attribute.hasAlternative());
    }, "aschunk");
    // <--[tag]
    // @attribute <ElementTag.as_color>
    // @returns ColorTag
    // @group conversion
    // @description
    // Returns the element as a ColorTag. Note: the value must be a valid color.
    // -->
    PropertyParser.<BukkitElementProperties, ColorTag>registerStaticTag(ColorTag.class, "as_color", (attribute, object) -> {
        return ElementTag.handleNull(object.asString(), ColorTag.valueOf(object.asString(), new BukkitTagContext(attribute.getScriptEntry())), "ColorTag", attribute.hasAlternative());
    }, "ascolor");
    // <--[tag]
    // @attribute <ElementTag.as_cuboid>
    // @returns CuboidTag
    // @group conversion
    // @description
    // Returns the element as a cuboid. Note: the value must be a valid cuboid.
    // -->
    PropertyParser.<BukkitElementProperties, CuboidTag>registerTag(CuboidTag.class, "as_cuboid", (attribute, object) -> {
        return ElementTag.handleNull(object.asString(), CuboidTag.valueOf(object.asString(), new BukkitTagContext(attribute.getScriptEntry())), "CuboidTag", attribute.hasAlternative());
    }, "ascuboid");
    // <--[tag]
    // @attribute <ElementTag.as_ellipsoid>
    // @returns EllipsoidTag
    // @group conversion
    // @description
    // Returns the element as an EllipsoidTag. Note: the value must be a valid ellipsoid.
    // -->
    PropertyParser.<BukkitElementProperties, EllipsoidTag>registerTag(EllipsoidTag.class, "as_ellipsoid", (attribute, object) -> {
        return ElementTag.handleNull(object.asString(), EllipsoidTag.valueOf(object.asString(), new BukkitTagContext(attribute.getScriptEntry())), "EllipsoidTag", attribute.hasAlternative());
    });
    // <--[tag]
    // @attribute <ElementTag.as_enchantment>
    // @returns EnchantmentTag
    // @group conversion
    // @description
    // Returns the element as an EnchantmentTag. Note: the value must be a valid enchantment.
    // -->
    PropertyParser.<BukkitElementProperties, EnchantmentTag>registerStaticTag(EnchantmentTag.class, "as_enchantment", (attribute, object) -> {
        return ElementTag.handleNull(object.asString(), EnchantmentTag.valueOf(object.asString(), new BukkitTagContext(attribute.getScriptEntry())), "EnchantmentTag", attribute.hasAlternative());
    });
    // <--[tag]
    // @attribute <ElementTag.as_entity>
    // @returns EntityTag
    // @group conversion
    // @description
    // Returns the element as an entity. Note: the value must be a valid entity.
    // -->
    PropertyParser.<BukkitElementProperties, EntityTag>registerTag(EntityTag.class, "as_entity", (attribute, object) -> {
        return ElementTag.handleNull(object.asString(), EntityTag.valueOf(object.asString(), new BukkitTagContext(attribute.getScriptEntry())), "EntityTag", attribute.hasAlternative());
    }, "asentity");
    // <--[tag]
    // @attribute <ElementTag.as_inventory>
    // @returns InventoryTag
    // @group conversion
    // @description
    // Returns the element as an inventory. Note: the value must be a valid inventory.
    // -->
    PropertyParser.<BukkitElementProperties, InventoryTag>registerTag(InventoryTag.class, "as_inventory", (attribute, object) -> {
        return ElementTag.handleNull(object.asString(), InventoryTag.valueOf(object.asString(), new BukkitTagContext(attribute.getScriptEntry())), "InventoryTag", attribute.hasAlternative());
    }, "asinventory");
    // <--[tag]
    // @attribute <ElementTag.as_item>
    // @returns ItemTag
    // @group conversion
    // @description
    // Returns the element as an item. Note: the value must be a valid item.
    // -->
    PropertyParser.<BukkitElementProperties, ItemTag>registerTag(ItemTag.class, "as_item", (attribute, object) -> {
        return ElementTag.handleNull(object.asString(), ItemTag.valueOf(object.asString(), new BukkitTagContext(attribute.getScriptEntry())), "ItemTag", attribute.hasAlternative());
    }, "asitem");
    // <--[tag]
    // @attribute <ElementTag.as_location>
    // @returns LocationTag
    // @group conversion
    // @description
    // Returns the element as a location. Note: the value must be a valid location.
    // -->
    PropertyParser.<BukkitElementProperties, LocationTag>registerTag(LocationTag.class, "as_location", (attribute, object) -> {
        return ElementTag.handleNull(object.asString(), LocationTag.valueOf(object.asString(), new BukkitTagContext(attribute.getScriptEntry())), "LocationTag", attribute.hasAlternative());
    }, "aslocation");
    // <--[tag]
    // @attribute <ElementTag.as_material>
    // @returns MaterialTag
    // @group conversion
    // @description
    // Returns the element as a material. Note: the value must be a valid material.
    // -->
    PropertyParser.<BukkitElementProperties, MaterialTag>registerStaticTag(MaterialTag.class, "as_material", (attribute, object) -> {
        return ElementTag.handleNull(object.asString(), MaterialTag.valueOf(object.asString(), new BukkitTagContext(attribute.getScriptEntry())), "MaterialTag", attribute.hasAlternative());
    }, "asmaterial");
    // <--[tag]
    // @attribute <ElementTag.as_npc>
    // @returns NPCTag
    // @group conversion
    // @description
    // Returns the element as an NPC. Note: the value must be a valid NPC.
    // -->
    PropertyParser.<BukkitElementProperties, NPCTag>registerTag(NPCTag.class, "as_npc", (attribute, object) -> {
        return ElementTag.handleNull(object.asString(), NPCTag.valueOf(object.asString(), new BukkitTagContext(attribute.getScriptEntry())), "NPCTag", attribute.hasAlternative());
    }, "asnpc");
    // <--[tag]
    // @attribute <ElementTag.as_player>
    // @returns PlayerTag
    // @group conversion
    // @description
    // Returns the element as a player. Note: the value must be a valid player. Can be online or offline.
    // -->
    PropertyParser.<BukkitElementProperties, PlayerTag>registerTag(PlayerTag.class, "as_player", (attribute, object) -> {
        return ElementTag.handleNull(object.asString(), PlayerTag.valueOf(object.asString(), new BukkitTagContext(attribute.getScriptEntry())), "PlayerTag", attribute.hasAlternative());
    }, "asplayer");
    // <--[tag]
    // @attribute <ElementTag.as_plugin>
    // @returns PluginTag
    // @group conversion
    // @description
    // Returns the element as a plugin. Note: the value must be a valid plugin.
    // -->
    PropertyParser.<BukkitElementProperties, PluginTag>registerStaticTag(PluginTag.class, "as_plugin", (attribute, object) -> {
        return ElementTag.handleNull(object.asString(), PluginTag.valueOf(object.asString(), new BukkitTagContext(attribute.getScriptEntry())), "PluginTag", attribute.hasAlternative());
    }, "asplugin");
    // <--[tag]
    // @attribute <ElementTag.as_polygon>
    // @returns PolygonTag
    // @group conversion
    // @description
    // Returns the element as a PolygonTag. Note: the value must be a valid polygon.
    // -->
    PropertyParser.<BukkitElementProperties, PolygonTag>registerTag(PolygonTag.class, "as_polygon", (attribute, object) -> {
        return ElementTag.handleNull(object.asString(), PolygonTag.valueOf(object.asString(), new BukkitTagContext(attribute.getScriptEntry())), "PolygonTag", attribute.hasAlternative());
    });
    // <--[tag]
    // @attribute <ElementTag.as_trade>
    // @returns TradeTag
    // @group conversion
    // @description
    // Returns the element as a TradeTag. Note: the value must be a valid trade.
    // -->
    PropertyParser.<BukkitElementProperties, TradeTag>registerStaticTag(TradeTag.class, "as_trade", (attribute, object) -> {
        return ElementTag.handleNull(object.asString(), TradeTag.valueOf(object.asString(), new BukkitTagContext(attribute.getScriptEntry())), "TradeTag", attribute.hasAlternative());
    });
    // <--[tag]
    // @attribute <ElementTag.as_world>
    // @returns WorldTag
    // @group conversion
    // @description
    // Returns the element as a world. Note: the value must be a valid world.
    // -->
    PropertyParser.<BukkitElementProperties, WorldTag>registerTag(WorldTag.class, "as_world", (attribute, object) -> {
        return ElementTag.handleNull(object.asString(), WorldTag.valueOf(object.asString(), new BukkitTagContext(attribute.getScriptEntry())), "WorldTag", attribute.hasAlternative());
    }, "asworld");
    // <--[tag]
    // @attribute <ElementTag.format[<script>]>
    // @returns ElementTag
    // @group text manipulation
    // @description
    // Returns the text re-formatted according to a format script.
    // -->
    PropertyParser.<BukkitElementProperties, ElementTag>registerTag(ElementTag.class, "format", (attribute, object) -> {
        if (!attribute.hasParam()) {
            return null;
        }
        FormatScriptContainer format = ScriptRegistry.getScriptContainer(attribute.getParam());
        if (format == null) {
            attribute.echoError("Could not find format script matching '" + attribute.getParam() + "'");
            return null;
        } else {
            return new ElementTag(format.getFormattedText(object.asString(), attribute.getScriptEntry() != null ? ((BukkitScriptEntryData) attribute.getScriptEntry().entryData).getNPC() : null, attribute.getScriptEntry() != null ? ((BukkitScriptEntryData) attribute.getScriptEntry().entryData).getPlayer() : null));
        }
    });
    // <--[tag]
    // @attribute <ElementTag.split_lines_by_width[<#>]>
    // @returns ElementTag
    // @group element manipulation
    // @description
    // Returns the element split into separate lines based on a maximum width in pixels per line.
    // This uses character width, so for example 20 "W"s and 20 "i"s will be treated differently.
    // The width used is based on the vanilla minecraft font. This will not be accurate for other fonts.
    // This only currently supports ASCII symbols properly. Unicode symbols will be estimated as 6 pixels.
    // Spaces will be preferred to become newlines, unless a line does not contain any spaces.
    // -->
    PropertyParser.<BukkitElementProperties, ElementTag>registerStaticTag(ElementTag.class, "split_lines_by_width", (attribute, object) -> {
        int width = attribute.getIntParam();
        return new ElementTag(TextWidthHelper.splitLines(object.asString(), width));
    });
    // <--[tag]
    // @attribute <ElementTag.text_width>
    // @returns ElementTag(Number)
    // @group element manipulation
    // @description
    // Returns the width, in pixels, of the text.
    // The width used is based on the vanilla minecraft font. This will not be accurate for other fonts.
    // This only currently supports ASCII symbols properly. Unicode symbols will be estimated as 6 pixels.
    // If the element contains newlines, will return the widest line width.
    // -->
    PropertyParser.<BukkitElementProperties, ElementTag>registerStaticTag(ElementTag.class, "text_width", (attribute, object) -> {
        return new ElementTag(TextWidthHelper.getWidth(object.asString()));
    });
    // <--[tag]
    // @attribute <ElementTag.lines_to_colored_list>
    // @returns ListTag
    // @group element manipulation
    // @description
    // Returns a list of lines in the element, with colors spread over the lines manually.
    // Useful for things like item lore.
    // -->
    PropertyParser.<BukkitElementProperties, ListTag>registerStaticTag(ListTag.class, "lines_to_colored_list", (attribute, object) -> {
        ListTag output = new ListTag();
        String colors = "";
        for (String line : CoreUtilities.split(object.asString(), '\n')) {
            output.add(colors + line);
            colors = org.bukkit.ChatColor.getLastColors(colors + line);
        }
        return output;
    });
    // <--[tag]
    // @attribute <ElementTag.last_color>
    // @returns ElementTag
    // @group text checking
    // @description
    // Returns the ChatColors used last in an element.
    // -->
    PropertyParser.<BukkitElementProperties, ElementTag>registerStaticTag(ElementTag.class, "last_color", (attribute, object) -> {
        return new ElementTag(org.bukkit.ChatColor.getLastColors(object.asString()));
    });
    // <--[tag]
    // @attribute <ElementTag.strip_color>
    // @returns ElementTag
    // @group text manipulation
    // @description
    // Returns the element with all color encoding stripped.
    // -->
    PropertyParser.<BukkitElementProperties, ElementTag>registerStaticTag(ElementTag.class, "strip_color", (attribute, object) -> {
        return new ElementTag(FormattedTextHelper.parse(object.asString(), ChatColor.WHITE)[0].toPlainText());
    });
    // <--[tag]
    // @attribute <ElementTag.parse_color[(<prefix>)]>
    // @returns ElementTag
    // @group text manipulation
    // @description
    // Returns the element with all color codes parsed.
    // Optionally, specify a character to prefix the color ids. Defaults to '&' if not specified.
    // -->
    PropertyParser.<BukkitElementProperties, ElementTag>registerStaticTag(ElementTag.class, "parse_color", (attribute, object) -> {
        char prefix = '&';
        if (attribute.hasParam()) {
            prefix = attribute.getParam().charAt(0);
        }
        String parsed = ChatColor.translateAlternateColorCodes(prefix, object.asString());
        parsed = replaceEssentialsHexColors(prefix, parsed);
        return new ElementTag(parsed);
    });
    // <--[tag]
    // @attribute <ElementTag.to_itemscript_hash>
    // @returns ElementTag
    // @group conversion
    // @description
    // Shortens the element down to an itemscript hash ID, made of invisible color codes.
    // -->
    PropertyParser.<BukkitElementProperties, ElementTag>registerTag(ElementTag.class, "to_itemscript_hash", (attribute, object) -> {
        return new ElementTag(ItemScriptHelper.createItemScriptID(object.asString()));
    });
    // <--[tag]
    // @attribute <ElementTag.to_secret_colors>
    // @returns ElementTag
    // @group conversion
    // @description
    // Hides the element's text in invisible color codes.
    // Inverts <@link tag ElementTag.from_secret_colors>.
    // -->
    PropertyParser.<BukkitElementProperties, ElementTag>registerStaticTag(ElementTag.class, "to_secret_colors", (attribute, object) -> {
        String text = object.asString();
        byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
        String hex = CoreUtilities.hexEncode(bytes);
        StringBuilder colors = new StringBuilder(text.length() * 2);
        for (int i = 0; i < hex.length(); i++) {
            colors.append(ChatColor.COLOR_CHAR).append(hex.charAt(i));
        }
        return new ElementTag(colors.toString());
    });
    // <--[tag]
    // @attribute <ElementTag.from_secret_colors>
    // @returns ElementTag
    // @group conversion
    // @description
    // Un-hides the element's text from invisible color codes back to normal text.
    // Inverts <@link tag ElementTag.to_secret_colors>.
    // -->
    PropertyParser.<BukkitElementProperties, ElementTag>registerStaticTag(ElementTag.class, "from_secret_colors", (attribute, object) -> {
        String text = object.asString().replace(String.valueOf(ChatColor.COLOR_CHAR), "");
        byte[] bytes = CoreUtilities.hexDecode(text);
        return new ElementTag(new String(bytes, StandardCharsets.UTF_8));
    });
    // <--[tag]
    // @attribute <ElementTag.to_raw_json>
    // @returns ElementTag
    // @group conversion
    // @description
    // Converts normal colored text to Minecraft-style "raw JSON" format.
    // Inverts <@link tag ElementTag.from_raw_json>.
    // -->
    PropertyParser.<BukkitElementProperties, ElementTag>registerStaticTag(ElementTag.class, "to_raw_json", (attribute, object) -> {
        return new ElementTag(ComponentSerializer.toString(FormattedTextHelper.parse(object.asString(), ChatColor.WHITE)));
    });
    // <--[tag]
    // @attribute <ElementTag.from_raw_json>
    // @returns ElementTag
    // @group conversion
    // @description
    // Un-hides the element's text from invisible color codes back to normal text.
    // Inverts <@link tag ElementTag.to_raw_json>.
    // -->
    PropertyParser.<BukkitElementProperties, ElementTag>registerStaticTag(ElementTag.class, "from_raw_json", (attribute, object) -> {
        return new ElementTag(FormattedTextHelper.stringify(ComponentSerializer.parse(object.asString()), ChatColor.WHITE));
    });
    // <--[tag]
    // @attribute <ElementTag.on_hover[<message>]>
    // @returns ElementTag
    // @group text manipulation
    // @description
    // Adds a hover message to the element, which makes the element display the input hover text when the mouse is left over it.
    // Note that this is a magic Denizen tool - refer to <@link language Denizen Text Formatting>.
    // -->
    PropertyParser.<BukkitElementProperties, ElementTag>registerTag(ElementTag.class, "on_hover", (attribute, object) -> {
        // non-static due to hacked sub-tag
        if (!attribute.hasParam()) {
            return null;
        }
        String hoverText = attribute.getParam();
        String type = "SHOW_TEXT";
        // -->
        if (attribute.startsWith("type", 2)) {
            type = attribute.getContext(2);
            attribute.fulfill(1);
        }
        return new ElementTag(ChatColor.COLOR_CHAR + "[hover=" + type + ";" + FormattedTextHelper.escape(hoverText) + "]" + object.asString() + ChatColor.COLOR_CHAR + "[/hover]");
    });
    // <--[tag]
    // @attribute <ElementTag.on_click[<command>]>
    // @returns ElementTag
    // @group text manipulation
    // @description
    // Adds a click command to the element, which makes the element execute the input command when clicked.
    // To execute a command "/" should be used at the start. Otherwise, it will display as chat.
    // For example: - narrate "You can <element[click here].on_click[wow]> to say wow!"
    // For example: - narrate "You can <element[click here].on_click[/help]> for help!"
    // Note that this is a magic Denizen tool - refer to <@link language Denizen Text Formatting>.
    // -->
    PropertyParser.<BukkitElementProperties, ElementTag>registerTag(ElementTag.class, "on_click", (attribute, object) -> {
        // non-static due to hacked sub-tag
        if (!attribute.hasParam()) {
            return null;
        }
        String clickText = attribute.getParam();
        String type = "RUN_COMMAND";
        // -->
        if (attribute.startsWith("type", 2)) {
            type = attribute.getContext(2);
            attribute.fulfill(1);
        }
        return new ElementTag(ChatColor.COLOR_CHAR + "[click=" + type + ";" + FormattedTextHelper.escape(clickText) + "]" + object.asString() + ChatColor.COLOR_CHAR + "[/click]");
    });
    // <--[tag]
    // @attribute <ElementTag.with_insertion[<message>]>
    // @returns ElementTag
    // @group text manipulation
    // @description
    // Adds an insertion message to the element, which makes the element insert the input message to chat when shift-clicked.
    // Note that this is a magic Denizen tool - refer to <@link language Denizen Text Formatting>.
    // -->
    PropertyParser.<BukkitElementProperties, ElementTag>registerStaticTag(ElementTag.class, "with_insertion", (attribute, object) -> {
        if (!attribute.hasParam()) {
            return null;
        }
        String insertionText = attribute.getParam();
        return new ElementTag(ChatColor.COLOR_CHAR + "[insertion=" + FormattedTextHelper.escape(insertionText) + "]" + object.asString() + ChatColor.COLOR_CHAR + "[/insertion]");
    });
    // <--[tag]
    // @attribute <ElementTag.no_reset>
    // @returns ElementTag
    // @group text manipulation
    // @description
    // Makes a color code (&0123456789abcdef) not reset other formatting details.
    // Use like '<&c.no_reset>' or '<red.no_reset>'.
    // Note that this is a magic Denizen tool - refer to <@link language Denizen Text Formatting>.
    // -->
    PropertyParser.<BukkitElementProperties, ElementTag>registerStaticTag(ElementTag.class, "no_reset", (attribute, object) -> {
        if (object.asString().length() == 2 && object.asString().charAt(0) == ChatColor.COLOR_CHAR) {
            return new ElementTag(ChatColor.COLOR_CHAR + "[color=" + object.asString().charAt(1) + "]");
        }
        return null;
    });
    // <--[tag]
    // @attribute <ElementTag.end_format>
    // @returns ElementTag
    // @group text manipulation
    // @description
    // Makes a chat format code (&klmno, or &[font=...]) be the end of a format, as opposed to the start.
    // Use like '<&o.end_format>' or '<italic.end_format>'.
    // Note that this is a magic Denizen tool - refer to <@link language Denizen Text Formatting>.
    // -->
    PropertyParser.<BukkitElementProperties, ElementTag>registerStaticTag(ElementTag.class, "end_format", (attribute, object) -> {
        if (object.asString().length() == 2 && object.asString().charAt(0) == ChatColor.COLOR_CHAR) {
            return new ElementTag(ChatColor.COLOR_CHAR + "[reset=" + object.asString().charAt(1) + "]");
        } else if (object.asString().startsWith(ChatColor.COLOR_CHAR + "[font=") && object.asString().endsWith("]")) {
            return new ElementTag(ChatColor.COLOR_CHAR + "[reset=font]");
        }
        return null;
    });
    // <--[tag]
    // @attribute <ElementTag.italicize>
    // @returns ElementTag
    // @group text manipulation
    // @description
    // Makes the input text italic. Equivalent to "<&o><ELEMENT_HERE><&o.end_format>"
    // Note that this is a magic Denizen tool - refer to <@link language Denizen Text Formatting>.
    // -->
    PropertyParser.<BukkitElementProperties, ElementTag>registerStaticTag(ElementTag.class, "italicize", (attribute, object) -> {
        return new ElementTag(ChatColor.ITALIC + object.asString() + ChatColor.COLOR_CHAR + "[reset=o]");
    });
    // <--[tag]
    // @attribute <ElementTag.bold>
    // @returns ElementTag
    // @group text manipulation
    // @description
    // Makes the input text bold. Equivalent to "<&l><ELEMENT_HERE><&l.end_format>"
    // Note that this is a magic Denizen tool - refer to <@link language Denizen Text Formatting>.
    // -->
    PropertyParser.<BukkitElementProperties, ElementTag>registerStaticTag(ElementTag.class, "bold", (attribute, object) -> {
        return new ElementTag(ChatColor.BOLD + object.asString() + ChatColor.COLOR_CHAR + "[reset=l]");
    });
    // <--[tag]
    // @attribute <ElementTag.underline>
    // @returns ElementTag
    // @group text manipulation
    // @description
    // Makes the input text underlined. Equivalent to "<&n><ELEMENT_HERE><&n.end_format>"
    // Note that this is a magic Denizen tool - refer to <@link language Denizen Text Formatting>.
    // -->
    PropertyParser.<BukkitElementProperties, ElementTag>registerStaticTag(ElementTag.class, "underline", (attribute, object) -> {
        return new ElementTag(ChatColor.UNDERLINE + object.asString() + ChatColor.COLOR_CHAR + "[reset=n]");
    });
    // <--[tag]
    // @attribute <ElementTag.strikethrough>
    // @returns ElementTag
    // @group text manipulation
    // @description
    // Makes the input text struck-through. Equivalent to "<&m><ELEMENT_HERE><&m.end_format>"
    // Note that this is a magic Denizen tool - refer to <@link language Denizen Text Formatting>.
    // -->
    PropertyParser.<BukkitElementProperties, ElementTag>registerStaticTag(ElementTag.class, "strikethrough", (attribute, object) -> {
        return new ElementTag(ChatColor.STRIKETHROUGH + object.asString() + ChatColor.COLOR_CHAR + "[reset=m]");
    });
    // <--[tag]
    // @attribute <ElementTag.obfuscate>
    // @returns ElementTag
    // @group text manipulation
    // @description
    // Makes the input text obfuscated. Equivalent to "<&k><ELEMENT_HERE><&k.end_format>"
    // Note that this is a magic Denizen tool - refer to <@link language Denizen Text Formatting>.
    // -->
    PropertyParser.<BukkitElementProperties, ElementTag>registerStaticTag(ElementTag.class, "obfuscate", (attribute, object) -> {
        return new ElementTag(ChatColor.MAGIC + object.asString() + ChatColor.COLOR_CHAR + "[reset=k]");
    });
    // <--[tag]
    // @attribute <ElementTag.custom_color[<name>]>
    // @returns ElementTag
    // @group text manipulation
    // @description
    // Makes the input text colored by the custom color value based on the common base color names defined in the Denizen config file.
    // If the color name is unrecognized, returns the value of color named 'default'.
    // Default color names are 'base', 'emphasis', 'warning', 'error'.
    // Note that this is a magic Denizen tool - refer to <@link language Denizen Text Formatting>.
    // -->
    PropertyParser.<BukkitElementProperties, ElementTag>registerStaticTag(ElementTag.class, "custom_color", (attribute, object) -> {
        if (!attribute.hasParam()) {
            return null;
        }
        return new ElementTag(ChatColor.COLOR_CHAR + "[color=f]" + CustomColorTagBase.getColor(attribute.getParam(), attribute.context) + object.asString() + ChatColor.COLOR_CHAR + "[reset=color]");
    });
    // <--[tag]
    // @attribute <ElementTag.color[<color>]>
    // @returns ElementTag
    // @group text manipulation
    // @description
    // Makes the input text colored by the input color. Equivalent to "<COLOR><ELEMENT_HERE><COLOR.end_format>"
    // Color can be a color name, color code, hex, or ColorTag... that is: ".color[gold]", ".color[6]", and ".color[#AABB00]" are all valid.
    // Note that this is a magic Denizen tool - refer to <@link language Denizen Text Formatting>.
    // -->
    PropertyParser.<BukkitElementProperties, ElementTag>registerStaticTag(ElementTag.class, "color", (attribute, object) -> {
        if (!attribute.hasParam()) {
            return null;
        }
        String colorName = attribute.getParam();
        String colorOut = null;
        if (colorName.length() == 1) {
            ChatColor color = ChatColor.getByChar(colorName.charAt(0));
            if (color != null) {
                colorOut = color.toString();
            }
        } else if (colorName.length() == 7 && colorName.startsWith("#")) {
            return new ElementTag(ChatColor.COLOR_CHAR + "[color=" + colorName + "]" + object.asString() + ChatColor.COLOR_CHAR + "[reset=color]");
        } else if (colorName.length() == 14 && colorName.startsWith(ChatColor.COLOR_CHAR + "x")) {
            return new ElementTag(ChatColor.COLOR_CHAR + "[color=#" + CoreUtilities.replace(colorName.substring(2), String.valueOf(ChatColor.COLOR_CHAR), "") + "]" + object.asString() + ChatColor.COLOR_CHAR + "[reset=color]");
        } else if (colorName.startsWith("co@")) {
            ColorTag color = ColorTag.valueOf(colorName, attribute.context);
            StringBuilder hex = new StringBuilder(Integer.toHexString(color.getColor().asRGB()));
            while (hex.length() < 6) {
                hex.insert(0, "0");
            }
            return new ElementTag(ChatColor.COLOR_CHAR + "[color=#" + hex + "]" + object.asString() + ChatColor.COLOR_CHAR + "[reset=color]");
        }
        if (colorOut == null) {
            try {
                ChatColor color = ChatColor.of(colorName.toUpperCase());
                String colorStr = color.toString().replace(String.valueOf(ChatColor.COLOR_CHAR), "").replace("x", "#");
                colorOut = ChatColor.COLOR_CHAR + "[color=" + colorStr + "]";
            } catch (IllegalArgumentException ex) {
                attribute.echoError("Color '" + colorName + "' doesn't exist (for ElementTag.color[...]).");
                return null;
            }
        }
        return new ElementTag(colorOut + object.asString() + ChatColor.COLOR_CHAR + "[reset=color]");
    });
    // <--[tag]
    // @attribute <ElementTag.font[<font>]>
    // @returns ElementTag
    // @group text manipulation
    // @description
    // Makes the input text display with the input font name. Equivalent to "<&font[new-font]><ELEMENT_HERE><&font[new-font].end_format>"
    // The default font is "minecraft:default".
    // Note that this is a magic Denizen tool - refer to <@link language Denizen Text Formatting>.
    // -->
    PropertyParser.<BukkitElementProperties, ElementTag>registerStaticTag(ElementTag.class, "font", (attribute, object) -> {
        if (!attribute.hasParam()) {
            return null;
        }
        String fontName = attribute.getParam();
        return new ElementTag(ChatColor.COLOR_CHAR + "[font=" + fontName + "]" + object.asString() + ChatColor.COLOR_CHAR + "[reset=font]");
    });
    // <--[tag]
    // @attribute <ElementTag.rainbow[(<pattern>)]>
    // @returns ElementTag
    // @group text manipulation
    // @description
    // Returns the element with rainbow colors applied.
    // Optionally, specify a color pattern to follow. By default, this is "4c6e2ab319d5".
    // That is, a repeating color of: Red, Orange, Yellow, Green, Cyan, Blue, Purple.
    // -->
    PropertyParser.<BukkitElementProperties, ElementTag>registerStaticTag(ElementTag.class, "rainbow", (attribute, object) -> {
        String str = object.asString();
        String pattern = "4c6e2ab319d5";
        if (attribute.hasParam()) {
            pattern = attribute.getParam();
        }
        StringBuilder output = new StringBuilder(str.length() * 3);
        for (int i = 0; i < str.length(); i++) {
            output.append(ChatColor.COLOR_CHAR).append(pattern.charAt(i % pattern.length())).append(str.charAt(i));
        }
        return new ElementTag(output.toString());
    });
    // <--[tag]
    // @attribute <ElementTag.hex_rainbow[(<length>)]>
    // @returns ElementTag
    // @group text manipulation
    // @description
    // Returns the element with RGB rainbow colors applied.
    // Optionally, specify a length (how many characters before the colors repeat). If unspecified, will use the input element length.
    // If the element starts with a hex color code, that will be used as the starting color of the rainbow.
    // -->
    PropertyParser.<BukkitElementProperties, ElementTag>registerStaticTag(ElementTag.class, "hex_rainbow", (attribute, object) -> {
        String str = object.asString();
        int[] HSB = new int[] { 0, 255, 255 };
        if (str.startsWith(ChatColor.COLOR_CHAR + "x") && str.length() > 14) {
            char[] colors = new char[6];
            for (int i = 0; i < 6; i++) {
                colors[i] = str.charAt(3 + (i * 2));
            }
            int rgb = Integer.parseInt(new String(colors), 16);
            HSB = new ColorTag(Color.fromRGB(rgb)).toHSB();
            str = str.substring(14);
        }
        float hue = HSB[0] / 255f;
        int length = ChatColor.stripColor(str).length();
        if (length == 0) {
            return new ElementTag("");
        }
        if (attribute.hasParam()) {
            length = attribute.getIntParam();
        }
        float increment = 1.0f / length;
        String addedFormat = "";
        StringBuilder output = new StringBuilder(str.length() * 8);
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (c == ChatColor.COLOR_CHAR && i + 1 < str.length()) {
                char c2 = str.charAt(i + 1);
                if (FORMAT_CODES_MATCHER.isMatch(c2)) {
                    addedFormat += String.valueOf(ChatColor.COLOR_CHAR) + c2;
                } else {
                    addedFormat = "";
                }
                i++;
                continue;
            }
            String hex = Integer.toHexString(ColorTag.fromHSB(HSB).getColor().asRGB());
            output.append(FormattedTextHelper.stringifyRGBSpigot(hex)).append(addedFormat).append(c);
            hue += increment;
            HSB[0] = Math.round(hue * 255f);
        }
        return new ElementTag(output.toString());
    });
    // <--[tag]
    // @attribute <ElementTag.color_gradient[from=<color>;to=<color>]>
    // @returns ElementTag
    // @group text manipulation
    // @description
    // Returns the element with an RGB color gradient applied - tends to produce smooth gradients, as opposed to <@link tag ElementTag.hsb_color_gradient>,
    // with a unique color per character.
    // Specify the input as a map with keys 'from' and 'to' both set to hex colors (or any valid ColorTag).
    // For example: <element[these are the shades of gray].color_gradient[from=white;to=black]>
    // Or: <element[this looks kinda like fire doesn't it].color_gradient[from=#FF0000;to=#FFFF00]>
    // -->
    PropertyParser.<BukkitElementProperties, ElementTag>registerStaticTag(ElementTag.class, "color_gradient", (attribute, object) -> {
        if (!attribute.hasParam()) {
            return null;
        }
        String str = object.asString();
        int length = ChatColor.stripColor(str).length();
        if (length == 0) {
            return new ElementTag("");
        }
        MapTag inputMap = attribute.paramAsType(MapTag.class);
        if (inputMap == null) {
            return null;
        }
        ObjectTag fromObj = inputMap.getObject("from");
        ObjectTag toObj = inputMap.getObject("to");
        if (fromObj == null || toObj == null) {
            return null;
        }
        ColorTag fromColor = fromObj.asType(ColorTag.class, attribute.context);
        ColorTag toColor = toObj.asType(ColorTag.class, attribute.context);
        if (fromColor == null || toColor == null) {
            return null;
        }
        float red = ColorTag.fromSRGB(fromColor.getColor().getRed());
        float green = ColorTag.fromSRGB(fromColor.getColor().getGreen());
        float blue = ColorTag.fromSRGB(fromColor.getColor().getBlue());
        float targetRed = ColorTag.fromSRGB(toColor.getColor().getRed());
        float targetGreen = ColorTag.fromSRGB(toColor.getColor().getGreen());
        float targetBlue = ColorTag.fromSRGB(toColor.getColor().getBlue());
        float brightness = (float) Math.pow(red + green + blue, 0.43);
        float toBrightness = (float) Math.pow(targetRed + targetGreen + targetBlue, 0.43);
        float brightnessMove = (toBrightness - brightness) / length;
        float redMove = (targetRed - red) / length;
        float greenMove = (targetGreen - green) / length;
        float blueMove = (targetBlue - blue) / length;
        String addedFormat = "";
        StringBuilder output = new StringBuilder(str.length() * 15);
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (c == ChatColor.COLOR_CHAR && i + 1 < str.length()) {
                char c2 = str.charAt(i + 1);
                if (FORMAT_CODES_MATCHER.isMatch(c2)) {
                    addedFormat += String.valueOf(ChatColor.COLOR_CHAR) + c2;
                } else {
                    addedFormat = "";
                }
                i++;
                continue;
            }
            // Based on https://stackoverflow.com/questions/22607043/color-gradient-algorithm/49321304#49321304
            float newRed = red, newGreen = green, newBlue = blue;
            float sum = newRed + newGreen + newBlue;
            if (sum > 0) {
                float multiplier = (float) Math.pow(brightness, 1f / 0.43f) / sum;
                newRed *= multiplier;
                newGreen *= multiplier;
                newBlue *= multiplier;
            }
            newRed = ColorTag.toSRGB(newRed);
            newGreen = ColorTag.toSRGB(newGreen);
            newBlue = ColorTag.toSRGB(newBlue);
            String hex = Integer.toHexString((((int) newRed) << 16) | (((int) newGreen) << 8) | ((int) newBlue));
            output.append(FormattedTextHelper.stringifyRGBSpigot(hex)).append(addedFormat).append(str.charAt(i));
            brightness += brightnessMove;
            red += redMove;
            green += greenMove;
            blue += blueMove;
        }
        return new ElementTag(output.toString());
    });
    // <--[tag]
    // @attribute <ElementTag.hsb_color_gradient[from=<color>;to=<color>]>
    // @returns ElementTag
    // @group text manipulation
    // @description
    // Returns the element with an HSB color gradient applied - tends to produce bright rainbow-like color patterns, as opposed to <@link tag ElementTag.color_gradient>,
    // with a unique color per character.
    // Specify the input as a map with keys 'from' and 'to' both set to hex colors (or any valid ColorTag).
    // -->
    PropertyParser.<BukkitElementProperties, ElementTag>registerStaticTag(ElementTag.class, "hsb_color_gradient", (attribute, object) -> {
        if (!attribute.hasParam()) {
            return null;
        }
        String str = object.asString();
        int length = ChatColor.stripColor(str).length();
        if (length == 0) {
            return new ElementTag("");
        }
        MapTag inputMap = attribute.paramAsType(MapTag.class);
        if (inputMap == null) {
            return null;
        }
        ObjectTag fromObj = inputMap.getObject("from");
        ObjectTag toObj = inputMap.getObject("to");
        if (fromObj == null || toObj == null) {
            return null;
        }
        ColorTag fromColor = fromObj.asType(ColorTag.class, attribute.context);
        ColorTag toColor = toObj.asType(ColorTag.class, attribute.context);
        if (fromColor == null || toColor == null) {
            return null;
        }
        int[] fromHSB = fromColor.toHSB();
        int[] toHSB = toColor.toHSB();
        float hue = fromHSB[0];
        float saturation = fromHSB[1];
        float brightness = fromHSB[2];
        float targetHue = toHSB[0];
        float targetSaturation = toHSB[1];
        float targetBrightness = toHSB[2];
        float hueMove = (targetHue - hue) / length;
        float saturationMove = (targetSaturation - saturation) / length;
        float brightnessMove = (targetBrightness - brightness) / length;
        String addedFormat = "";
        StringBuilder output = new StringBuilder(str.length() * 15);
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (c == ChatColor.COLOR_CHAR && i + 1 < str.length()) {
                char c2 = str.charAt(i + 1);
                if (FORMAT_CODES_MATCHER.isMatch(c2)) {
                    addedFormat += String.valueOf(ChatColor.COLOR_CHAR) + c2;
                } else {
                    addedFormat = "";
                }
                i++;
                continue;
            }
            fromHSB[0] = (int) hue;
            fromHSB[1] = (int) saturation;
            fromHSB[2] = (int) brightness;
            ColorTag currentColor = ColorTag.fromHSB(fromHSB);
            String hex = Integer.toHexString(currentColor.getColor().asRGB());
            output.append(FormattedTextHelper.stringifyRGBSpigot(hex)).append(addedFormat).append(c);
            hue += hueMove;
            saturation += saturationMove;
            brightness += brightnessMove;
        }
        return new ElementTag(output.toString());
    });
}
Also used : FormatScriptContainer(com.denizenscript.denizen.scripts.containers.core.FormatScriptContainer) MapTag(com.denizenscript.denizencore.objects.core.MapTag) ObjectTag(com.denizenscript.denizencore.objects.ObjectTag) ListTag(com.denizenscript.denizencore.objects.core.ListTag) BukkitTagContext(com.denizenscript.denizen.tags.BukkitTagContext) ElementTag(com.denizenscript.denizencore.objects.core.ElementTag) ChatColor(net.md_5.bungee.api.ChatColor)

Example 10 with Entity

use of net.md_5.bungee.api.chat.hover.content.Entity in project Denizen-For-Bukkit by DenizenScript.

the class HoverFormatHelper method processHoverInput.

public static boolean processHoverInput(HoverEvent.Action action, TextComponent hoverableText, String input) {
    Content content;
    if (action == HoverEvent.Action.SHOW_ITEM) {
        ItemTag item = ItemTag.valueOf(FormattedTextHelper.unescape(input), CoreUtilities.noDebugContext);
        if (item == null) {
            return true;
        }
        // TODO: Why is there not a direct conversion method for Spigot ItemStack -> BungeeChat Item?
        String itemNbt = NMSHandler.getItemHelper().getRawHoverText(item.getItemStack());
        content = new Item(item.getBukkitMaterial().getKey().toString(), item.getAmount(), net.md_5.bungee.api.chat.ItemTag.ofNbt(itemNbt));
    } else if (action == HoverEvent.Action.SHOW_ENTITY) {
        EntityTag entity = EntityTag.valueOf(FormattedTextHelper.unescape(input), CoreUtilities.basicContext);
        if (entity == null) {
            return true;
        }
        BaseComponent name = null;
        if (entity.getBukkitEntity() != null && entity.getBukkitEntity().isCustomNameVisible()) {
            name = new TextComponent();
            for (BaseComponent component : FormattedTextHelper.parse(entity.getBukkitEntity().getCustomName(), ChatColor.WHITE)) {
                name.addExtra(component);
            }
        }
        content = new Entity(entity.getBukkitEntityType().getKey().toString(), entity.getUUID().toString(), name);
    } else {
        content = new Text(FormattedTextHelper.parse(FormattedTextHelper.unescape(input), ChatColor.WHITE));
    }
    hoverableText.setHoverEvent(new HoverEvent(action, content));
    return false;
}
Also used : TextComponent(net.md_5.bungee.api.chat.TextComponent) Item(net.md_5.bungee.api.chat.hover.content.Item) Entity(net.md_5.bungee.api.chat.hover.content.Entity) HoverEvent(net.md_5.bungee.api.chat.HoverEvent) BaseComponent(net.md_5.bungee.api.chat.BaseComponent) Content(net.md_5.bungee.api.chat.hover.content.Content) EntityTag(com.denizenscript.denizen.objects.EntityTag) Text(net.md_5.bungee.api.chat.hover.content.Text) ItemTag(com.denizenscript.denizen.objects.ItemTag)

Aggregations

TextComponent (net.md_5.bungee.api.chat.TextComponent)8 Player (org.bukkit.entity.Player)8 CoreStateInitException (com.solinia.solinia.Exceptions.CoreStateInitException)6 Entity (org.bukkit.entity.Entity)6 ArrayList (java.util.ArrayList)4 BaseComponent (net.md_5.bungee.api.chat.BaseComponent)4 ISoliniaItem (com.solinia.solinia.Interfaces.ISoliniaItem)3 ISoliniaLivingEntity (com.solinia.solinia.Interfaces.ISoliniaLivingEntity)3 ISoliniaPlayer (com.solinia.solinia.Interfaces.ISoliniaPlayer)3 ClickEvent (net.md_5.bungee.api.chat.ClickEvent)3 ItemStack (org.bukkit.inventory.ItemStack)3 ClientOption (com.destroystokyo.paper.ClientOption)2 MaterialTags (com.destroystokyo.paper.MaterialTags)2 Title (com.destroystokyo.paper.Title)2 PlayerProfile (com.destroystokyo.paper.profile.PlayerProfile)2 Message (com.flowpowered.network.Message)2 Preconditions (com.google.common.base.Preconditions)2 Preconditions.checkArgument (com.google.common.base.Preconditions.checkArgument)2 Preconditions.checkNotNull (com.google.common.base.Preconditions.checkNotNull)2 ImmutableList (com.google.common.collect.ImmutableList)2