Search in sources :

Example 21 with BukkitTagContext

use of com.denizenscript.denizen.tags.BukkitTagContext in project Denizen-For-Bukkit by DenizenScript.

the class Denizen method onEnable.

/*
     * Sets up Denizen on start of the CraftBukkit server.
     */
@Override
public void onEnable() {
    instance = this;
    try {
        versionTag = this.getDescription().getVersion();
        CoreUtilities.noDebugContext = new BukkitTagContext(null, null, null, false, null);
        CoreUtilities.basicContext = new BukkitTagContext(null, null, null, true, null);
        CoreUtilities.errorButNoDebugContext = new BukkitTagContext(null, null, null, false, null);
        CoreUtilities.errorButNoDebugContext.showErrors = true;
        // Load Denizen's core
        DenizenCore.init(coreImplementation);
    } catch (Exception e) {
        e.printStackTrace();
        getServer().getPluginManager().disablePlugin(this);
        startedSuccessful = false;
        return;
    }
    PlayerFlagHandler.dataFolder = new File(getDataFolder(), "player_flags");
    if (!PlayerFlagHandler.dataFolder.exists()) {
        PlayerFlagHandler.dataFolder.mkdir();
    }
    String javaVersion = System.getProperty("java.version");
    getLogger().info("Running on java version: " + javaVersion);
    if (javaVersion.startsWith("8") || javaVersion.startsWith("1.8")) {
        getLogger().info("Running on fully supported Java 8. Updating to Java 17+ is recommended.");
    } else if (javaVersion.startsWith("9") || javaVersion.startsWith("1.9") || javaVersion.startsWith("10") || javaVersion.startsWith("1.10") || javaVersion.startsWith("11") || javaVersion.startsWith("12") || javaVersion.startsWith("13") || javaVersion.startsWith("14") || javaVersion.startsWith("15")) {
        getLogger().warning("Running unreliable Java version. Old Minecraft is built for Java 8, modern Minecraft is built for Java 17. Other Java versions are not guaranteed to function properly.");
    } else if (javaVersion.startsWith("16")) {
        getLogger().info("Running on fully supported Java 16.");
    } else if (javaVersion.startsWith("17")) {
        getLogger().info("Running on fully supported Java 17.");
    } else {
        getLogger().info("Running on unrecognized (future?) Java version. May or may not work.");
    }
    if (!NMSHandler.initialize(this)) {
        getLogger().warning("-------------------------------------");
        getLogger().warning("This build of Denizen is not compatible with this Spigot version! Deactivating Denizen!");
        getLogger().warning("-------------------------------------");
        getServer().getPluginManager().disablePlugin(this);
        startedSuccessful = false;
        return;
    }
    if (!NMSHandler.getInstance().isCorrectMappingsCode()) {
        getLogger().warning("-------------------------------------");
        getLogger().warning("This build of Denizen was built for a different Spigot revision! This may potentially cause issues." + " If you are experiencing trouble, update Denizen and Spigot both to latest builds!" + " If this message appears with both Denizen and Spigot fully up-to-date, contact the Denizen team (via GitHub, Spigot, or Discord) to request an update be built.");
        getLogger().warning("-------------------------------------");
    }
    BukkitCommandRegistry commandRegistry = new BukkitCommandRegistry();
    triggerRegistry = new TriggerRegistry();
    boolean citizensBork = false;
    try {
        // Activate dependencies
        Depends.initialize();
        if (Depends.citizens == null) {
            if (Bukkit.getPluginManager().getPlugin("Citizens") != null) {
                citizensBork = true;
                getLogger().warning("Citizens is present but doesn't seem to be activated! You may have an error earlier in your logs, or you may have a broken plugin load order.");
            } else {
                getLogger().warning("Citizens does not seem to be available! Denizen will have greatly reduced functionality!");
            }
        }
        startedSuccessful = true;
    } catch (Exception e) {
        Debug.echoError(e);
    }
    try {
        // Populate config.yml if it doesn't yet exist.
        saveDefaultConfig();
        reloadConfig();
        // Startup procedure
        Debug.log(ChatColor.LIGHT_PURPLE + "+-------------------------+");
        Debug.log(ChatColor.YELLOW + " _/_ _  ._  _ _  ");
        Debug.log(ChatColor.YELLOW + "(/(-/ )/ /_(-/ ) " + ChatColor.GRAY + " scriptable minecraft");
        Debug.log("");
        Debug.log(ChatColor.GRAY + "by: " + ChatColor.WHITE + "The DenizenScript team");
        Debug.log(ChatColor.GRAY + "Chat with us at: " + ChatColor.WHITE + " https://discord.gg/Q6pZGSR");
        Debug.log(ChatColor.GRAY + "Or learn more at: " + ChatColor.WHITE + " https://denizenscript.com");
        Debug.log(ChatColor.GRAY + "version: " + ChatColor.WHITE + versionTag);
        Debug.log(ChatColor.LIGHT_PURPLE + "+-------------------------+");
    } catch (Exception e) {
        Debug.echoError(e);
    }
    try {
        if (Class.forName("com.destroystokyo.paper.PaperConfig") != null) {
            supportsPaper = true;
        }
    } catch (ClassNotFoundException ex) {
    // Ignore.
    } catch (Throwable ex) {
        Debug.echoError(ex);
    }
    // bstats.org
    try {
        BStatsMetricsLite metrics = new BStatsMetricsLite(this);
    } catch (Throwable e) {
        Debug.echoError(e);
    }
    try {
        // If Citizens is enabled, Create the NPC Helper
        if (Depends.citizens != null) {
            npcHelper = new DenizenNPCHelper();
        }
        // Create our CommandManager to handle '/denizen' commands
        commandManager = new CommandManager();
        commandManager.setInjector(new Injector(this));
        commandManager.register(DenizenCommandHandler.class);
        // If Citizens is enabled, let it handle '/npc' commands
        if (Depends.citizens != null) {
            Depends.citizens.registerCommandClass(NPCCommandHandler.class);
        }
        DenizenEntityType.registerEntityType("ITEM_PROJECTILE", ItemProjectile.class);
        DenizenEntityType.registerEntityType("FAKE_ARROW", FakeArrow.class);
        DenizenEntityType.registerEntityType("FAKE_PLAYER", FakePlayer.class);
        // Track all player names for quick PlayerTag matching
        for (OfflinePlayer player : Bukkit.getOfflinePlayers()) {
            PlayerTag.notePlayer(player);
        }
    } catch (Exception e) {
        Debug.echoError(e);
    }
    try {
        DenizenCore.commandRegistry = commandRegistry;
        commandRegistry.registerCommands();
    } catch (Exception e) {
        Debug.echoError(e);
    }
    try {
        // Register script-container types
        ScriptRegistry._registerCoreTypes();
    } catch (Exception e) {
        Debug.echoError(e);
    }
    try {
        ContainerRegistry.registerMainContainers();
    } catch (Exception e) {
        Debug.echoError(e);
    }
    try {
        // Ensure the Scripts and Midi folder exist
        new File(getDataFolder() + "/scripts").mkdirs();
        new File(getDataFolder() + "/midi").mkdirs();
        new File(getDataFolder() + "/schematics").mkdirs();
        // Ensure the example Denizen.mid sound file is available
        if (!new File(getDataFolder() + "/midi/Denizen.mid").exists()) {
            String sourceFile = URLDecoder.decode(Denizen.class.getProtectionDomain().getCodeSource().getLocation().getFile());
            Debug.log("Denizen.mid not found, extracting from " + sourceFile);
            Utilities.extractFile(new File(sourceFile), "Denizen.mid", getDataFolder() + "/midi/");
        }
    } catch (Exception e) {
        Debug.echoError(e);
    }
    try {
        // Automatic config file update
        InputStream properConfig = Denizen.class.getResourceAsStream("/config.yml");
        String properConfigString = ScriptHelper.convertStreamToString(properConfig);
        properConfig.close();
        FileInputStream currentConfig = new FileInputStream(getDataFolder() + "/config.yml");
        String currentConfigString = ScriptHelper.convertStreamToString(currentConfig);
        currentConfig.close();
        String updated = ConfigUpdater.updateConfig(currentConfigString, properConfigString);
        if (updated != null) {
            Debug.log("Your config file is outdated. Automatically updating it...");
            FileOutputStream configOutput = new FileOutputStream(getDataFolder() + "/config.yml");
            OutputStreamWriter writer = new OutputStreamWriter(configOutput);
            writer.write(updated);
            writer.close();
            configOutput.close();
            reloadConfig();
        }
    } catch (Exception e) {
        Debug.echoError(e);
    }
    try {
        worldScriptHelper = new BukkitWorldScriptHelper();
        itemScriptHelper = new ItemScriptHelper();
        new InventoryScriptHelper();
        new EntityScriptHelper();
        new CommandScriptHelper();
    } catch (Exception e) {
        Debug.echoError(e);
    }
    try {
        if (Depends.citizens != null) {
            // Register traits
            TraitRegistry.registerMainTraits();
        }
    } catch (Exception e) {
        Debug.echoError(e);
    }
    // Register Core Members in the Denizen Registries
    try {
        if (Depends.citizens != null) {
            triggerRegistry.registerCoreMembers();
        }
    } catch (Exception e) {
        Debug.echoError(e);
    }
    try {
        AdjustCommand.specialAdjustables.put("server", ServerTagBase::adjustServer);
        eventManager = new OldEventManager();
        // Register all the modern script events
        ScriptEventRegistry.registerMainEvents();
        // Register Core ObjectTags with the ObjectFetcher
        ObjectFetcher.registerCoreObjects();
        CommonRegistries.registerMainObjects();
        TagManager.registerCoreTags();
        CommonRegistries.registerMainTagHandlers();
    } catch (Exception e) {
        Debug.echoError(e);
    }
    try {
        // Initialize all properties
        PropertyRegistry.registerMainProperties();
    } catch (Exception e) {
        Debug.echoError(e);
    }
    try {
        new CommandEvents();
        if (Settings.cache_packetInterceptAutoInit) {
            NetworkInterceptHelper.enable();
        }
    } catch (Exception e) {
        Debug.echoError(e);
    }
    try {
        if (supportsPaper) {
            final Class<?> clazz = Class.forName("com.denizenscript.denizen.paper.PaperModule");
            clazz.getMethod("init").invoke(null);
        }
    } catch (ClassNotFoundException ex) {
        supportsPaper = false;
    } catch (Throwable ex) {
        supportsPaper = false;
        Debug.echoError(ex);
    }
    Debug.log("Loaded <A>" + commandRegistry.instances.size() + "<W> core commands and <A>" + ObjectFetcher.objectsByPrefix.size() + "<W> core object types.");
    exCommand = new ExCommandHandler();
    exCommand.enableFor(getCommand("ex"));
    ExSustainedCommandHandler exsCommand = new ExSustainedCommandHandler();
    exsCommand.enableFor(getCommand("exs"));
    // Load script files without processing.
    DenizenCore.preloadScripts();
    // Load the saves.yml into memory
    reloadSaves();
    try {
        // Fire the 'on Server PreStart' world event
        ServerPrestartScriptEvent.instance.specialHackRunEvent();
    } catch (Throwable ex) {
        Debug.echoError(ex);
    }
    final boolean hadCitizensBork = citizensBork;
    // Run everything else on the first server tick
    Bukkit.getScheduler().scheduleSyncDelayedTask(this, () -> {
        try {
            if (hadCitizensBork) {
                Depends.setupCitizens();
                if (Depends.citizens != null) {
                    getLogger().warning("Citizens was activated late - this means a plugin load order error occurred. You may have plugins with invalid 'plugin.yml' files (eg that use the 'loadbefore' directive, or that have circular dependencies).");
                    npcHelper = new DenizenNPCHelper();
                    Depends.citizens.registerCommandClass(NPCCommandHandler.class);
                    TraitRegistry.registerMainTraits();
                    triggerRegistry.registerCoreMembers();
                    commandRegistry.registerCitizensCommands();
                    ScriptEventRegistry.registerCitizensEvents();
                    new NPCTagBase();
                    ObjectFetcher.registerWithObjectFetcher(NPCTag.class, NPCTag.tagProcessor);
                }
            }
        } catch (Throwable ex) {
            Debug.echoError(ex);
        }
        try {
            // Process script files (events, etc).
            NoteManager.reload();
            DenizenCore.postLoadScripts();
            Debug.log(ChatColor.LIGHT_PURPLE + "+-------------------------+");
            // Fire the 'on Server Start' world event
            ServerStartScriptEvent.instance.fire();
            worldScriptHelper.serverStartEvent();
            if (Settings.allowStupidx()) {
                Debug.echoError("Don't screw with bad config values.");
                Bukkit.shutdown();
            }
            Bukkit.getScheduler().scheduleSyncRepeatingTask(Denizen.this, () -> {
                Debug.onTick();
                // Sadly, minecraft has no delta timing, so a tick is always 50ms.
                DenizenCore.tick(50);
            }, 1, 1);
            InventoryTag.setupInventoryTracker();
            if (!MapTagBasedFlagTracker.skipAllCleanings) {
                BukkitWorldScriptHelper.cleanAllWorldChunkFlags();
            }
            Bukkit.getPluginManager().registerEvents(new PlayerFlagHandler(), this);
            Debug.log("Denizen fully loaded at: " + TimeTag.now().format());
        } catch (Throwable ex) {
            Debug.echoError(ex);
        }
    }, 1);
    new BukkitRunnable() {

        @Override
        public void run() {
            if (Settings.canRecordStats()) {
                new StatsRecord().start();
            }
        }
    }.runTaskTimer(this, 100, 20 * 60 * 60);
    new BukkitRunnable() {

        @Override
        public void run() {
            PlayerFlagHandler.cleanCache();
        }
    }.runTaskTimer(this, 100, 20 * 60);
    new BukkitRunnable() {

        @Override
        public void run() {
            if (!StrongWarning.recentWarnings.isEmpty()) {
                StringBuilder warnText = new StringBuilder();
                warnText.append(ChatColor.YELLOW).append("[Denizen] ").append(ChatColor.RED).append("Recent strong system warnings, scripters need to address ASAP (check earlier console logs for details):");
                for (StrongWarning warning : StrongWarning.recentWarnings) {
                    warnText.append("\n- ").append(warning.message);
                }
                StrongWarning.recentWarnings.clear();
                Bukkit.getConsoleSender().sendMessage(warnText.toString());
                for (Player player : Bukkit.getOnlinePlayers()) {
                    if (player.isOp()) {
                        player.sendMessage(warnText.toString());
                    }
                }
            }
        }
    }.runTaskTimer(this, 100, 20 * 60 * 5);
}
Also used : NPCTagBase(com.denizenscript.denizen.tags.core.NPCTagBase) StatsRecord(com.denizenscript.denizen.utilities.debugging.StatsRecord) DenizenNPCHelper(com.denizenscript.denizen.npc.DenizenNPCHelper) BukkitCommandRegistry(com.denizenscript.denizen.scripts.commands.BukkitCommandRegistry) ServerTagBase(com.denizenscript.denizen.tags.core.ServerTagBase) StrongWarning(com.denizenscript.denizencore.utilities.debugging.StrongWarning) BStatsMetricsLite(com.denizenscript.denizen.utilities.debugging.BStatsMetricsLite) PlayerFlagHandler(com.denizenscript.denizen.utilities.flags.PlayerFlagHandler) TriggerRegistry(com.denizenscript.denizen.scripts.triggers.TriggerRegistry) CommandManager(com.denizenscript.denizen.utilities.command.manager.CommandManager) Injector(com.denizenscript.denizen.utilities.command.manager.Injector) Player(org.bukkit.entity.Player) FakePlayer(com.denizenscript.denizen.nms.interfaces.FakePlayer) BukkitRunnable(org.bukkit.scheduler.BukkitRunnable) BukkitTagContext(com.denizenscript.denizen.tags.BukkitTagContext) OldEventManager(com.denizenscript.denizencore.events.OldEventManager)

Example 22 with BukkitTagContext

use of com.denizenscript.denizen.tags.BukkitTagContext in project Denizen-For-Bukkit by DenizenScript.

the class HealthTrait method onDamage.

@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onDamage(EntityDamageEvent event) {
    // Check if the event pertains to this NPC
    if (event.getEntity() != npc.getEntity() || dying) {
        return;
    }
    // Make sure this is a killing blow
    if (this.getHealth() - event.getFinalDamage() > 0) {
        return;
    }
    dying = true;
    // Save entityId for EntityDeath event
    entityId = npc.getEntity().getUniqueId();
    if (npc.getEntity() == null) {
        return;
    }
    TagContext context = new BukkitTagContext(null, new NPCTag(npc), null, true, null);
    // TODO: debug option?
    loc = getRespawnLocation();
    if (loc == null) {
        loc = npc.getStoredLocation();
    }
    if (animatedeath) {
        // Cancel navigation to keep the NPC from damaging players
        // while the death animation is being carried out.
        npc.getNavigator().cancelNavigation();
    // Reset health now to avoid the death from happening instantly
    // setHealth();
    // Play animation (TODO)
    // playDeathAnimation(npc.getEntity());
    }
    if (respawn && (getRespawnDelay().getTicks() > 0)) {
        Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(Denizen.getInstance(), () -> {
            if (CitizensAPI.getNPCRegistry().getById(npc.getId()) == null || npc.isSpawned()) {
                return;
            } else {
                npc.spawn(loc);
            }
        }, (getRespawnDelay().getTicks()));
    }
}
Also used : BukkitTagContext(com.denizenscript.denizen.tags.BukkitTagContext) BukkitTagContext(com.denizenscript.denizen.tags.BukkitTagContext) TagContext(com.denizenscript.denizencore.tags.TagContext) NPCTag(com.denizenscript.denizen.objects.NPCTag) EventHandler(org.bukkit.event.EventHandler)

Example 23 with BukkitTagContext

use of com.denizenscript.denizen.tags.BukkitTagContext in project Denizen-For-Bukkit by DenizenScript.

the class ItemScriptContainer method getItemFrom.

public ItemTag getItemFrom(TagContext context) {
    if (isProcessing) {
        Debug.echoError("Item script contains (or chains to) a reference to itself. Cannot process.");
        return null;
    }
    if (context == null) {
        context = new BukkitTagContext(null, null, new ScriptTag(this));
    } else {
        context = new BukkitTagContext((BukkitTagContext) context);
        context.script = new ScriptTag(this);
    }
    // Try to use this script to make an item.
    ItemTag stack;
    isProcessing = true;
    try {
        if (!contains("material", String.class)) {
            Debug.echoError("Item script '" + getName() + "' does not contain a material. Script cannot function.");
            return null;
        }
        // Check validity of material
        String material = TagManager.tag(getString("material"), context);
        if (material.startsWith("m@")) {
            material = material.substring(2);
        }
        stack = ItemTag.valueOf(material, this);
        // Make sure we're working with a valid base ItemStack
        if (stack == null) {
            Debug.echoError("Item script '" + getName() + "' contains an invalid or incorrect material '" + material + "' (did you spell the material name wrong?). Script cannot function.");
            return null;
        }
        // Handle listed mechanisms
        if (contains("mechanisms", Map.class)) {
            YamlConfiguration mechs = getConfigurationSection("mechanisms");
            for (StringHolder key : mechs.getKeys(false)) {
                ObjectTag obj = CoreUtilities.objectToTagForm(mechs.get(key.low), context, true, true);
                stack.safeAdjust(new Mechanism(key.low, obj, context));
            }
        }
        // Set Display Name
        if (contains("display name", String.class)) {
            String displayName = TagManager.tag(getString("display name"), context);
            NMSHandler.getItemHelper().setDisplayName(stack, displayName);
        }
        // Set if the object is bound to the player
        if (contains("bound", String.class)) {
            Deprecations.boundWarning.warn(context);
        }
        // Set Lore
        if (contains("lore", List.class)) {
            List<String> lore = NMSHandler.getItemHelper().getLore(stack);
            if (lore == null) {
                lore = new ArrayList<>();
            }
            for (String line : getStringList("lore")) {
                line = TagManager.tag(line, context);
                lore.add(line);
            }
            CoreUtilities.fixNewLinesToListSeparation(lore);
            NMSHandler.getItemHelper().setLore(stack, lore);
        }
        // Set Durability
        if (contains("durability", String.class)) {
            short durability = Short.valueOf(getString("durability"));
            stack.setDurability(durability);
        }
        // Set Enchantments
        if (contains("enchantments", List.class)) {
            for (String enchantment : getStringList("enchantments")) {
                enchantment = TagManager.tag(enchantment, context);
                try {
                    // Build enchantment context
                    int level = 1;
                    int colon = enchantment.lastIndexOf(':');
                    if (colon == -1) {
                        Debug.echoError("Item script '" + getName() + "' has enchantment '" + enchantment + "' without a level.");
                    } else {
                        level = Integer.valueOf(enchantment.substring(colon + 1).replace(" ", ""));
                        enchantment = enchantment.substring(0, colon).replace(" ", "");
                    }
                    // Add enchantment
                    EnchantmentTag ench = EnchantmentTag.valueOf(enchantment, context);
                    if (ench == null) {
                        Debug.echoError("Item script '" + getName() + "' specifies enchantment '" + enchantment + "' which is invalid.");
                        continue;
                    }
                    if (stack.getBukkitMaterial() == Material.ENCHANTED_BOOK) {
                        EnchantmentStorageMeta meta = (EnchantmentStorageMeta) stack.getItemMeta();
                        meta.addStoredEnchant(ench.enchantment, level, true);
                        stack.setItemMeta(meta);
                    } else {
                        stack.getItemStack().addUnsafeEnchantment(ench.enchantment, level);
                        stack.resetCache();
                    }
                } catch (Exception ex) {
                    Debug.echoError("While constructing item script '" + getName() + "', encountered error while applying enchantment '" + enchantment + "':");
                    Debug.echoError(ex);
                }
            }
        }
        // Set Color
        if (contains("color", String.class)) {
            Deprecations.itemScriptColor.warn(context);
            String color = TagManager.tag(getString("color"), context);
            LeatherColorer.colorArmor(stack, color);
        }
        // Set Book
        if (contains("book", String.class)) {
            BookScriptContainer book = ScriptRegistry.getScriptContainer(TagManager.tag(getString("book"), context).replace("s@", ""));
            stack = book.writeBookTo(stack, context);
        }
        if (contains("flags", Map.class)) {
            YamlConfiguration flagSection = getConfigurationSection("flags");
            AbstractFlagTracker tracker = stack.getFlagTracker();
            for (StringHolder key : flagSection.getKeys(false)) {
                tracker.setFlag(key.str, CoreUtilities.objectToTagForm(flagSection.get(key.str), context, true, true), null);
            }
            stack.reapplyTracker(tracker);
        }
        stack.setItemScript(this);
    } catch (Exception e) {
        Debug.echoError("Woah! An exception has been called with this item script!");
        Debug.echoError(e);
        stack = null;
    } finally {
        isProcessing = false;
    }
    return stack;
}
Also used : YamlConfiguration(com.denizenscript.denizencore.utilities.YamlConfiguration) Mechanism(com.denizenscript.denizencore.objects.Mechanism) StringHolder(com.denizenscript.denizencore.utilities.text.StringHolder) ObjectTag(com.denizenscript.denizencore.objects.ObjectTag) EnchantmentStorageMeta(org.bukkit.inventory.meta.EnchantmentStorageMeta) BukkitTagContext(com.denizenscript.denizen.tags.BukkitTagContext) ScriptTag(com.denizenscript.denizencore.objects.core.ScriptTag) AbstractFlagTracker(com.denizenscript.denizencore.flags.AbstractFlagTracker) EnchantmentTag(com.denizenscript.denizen.objects.EnchantmentTag) ItemTag(com.denizenscript.denizen.objects.ItemTag)

Example 24 with BukkitTagContext

use of com.denizenscript.denizen.tags.BukkitTagContext in project Denizen-For-Bukkit by DenizenScript.

the class EntityScriptContainer method getEntityFrom.

public EntityTag getEntityFrom(PlayerTag player, NPCTag npc) {
    EntityTag entity;
    try {
        TagContext context = new BukkitTagContext(player, npc, new ScriptTag(this));
        if (contains("entity_type", String.class)) {
            String entityType = TagManager.tag((getString("entity_type", "")), context);
            entity = EntityTag.valueOf(entityType, context);
        } else {
            throw new Exception("Missing entity_type argument!");
        }
        if (contains("flags", Map.class)) {
            YamlConfiguration flagSection = getConfigurationSection("flags");
            MapTagFlagTracker tracker = new MapTagFlagTracker();
            for (StringHolder key : flagSection.getKeys(false)) {
                tracker.setFlag(key.str, CoreUtilities.objectToTagForm(flagSection.get(key.str), context, true, true), null);
            }
            entity.safeAdjust(new Mechanism("flag_map", tracker.map, context));
        }
        if (contains("mechanisms", Map.class)) {
            YamlConfiguration mechSection = getConfigurationSection("mechanisms");
            Set<StringHolder> strings = mechSection.getKeys(false);
            for (StringHolder string : strings) {
                ObjectTag obj = CoreUtilities.objectToTagForm(mechSection.get(string.low), context, true, true);
                entity.safeAdjust(new Mechanism(string.low, obj, context));
            }
        }
        boolean any = false;
        Set<StringHolder> strings = getContents().getKeys(false);
        for (StringHolder string : strings) {
            if (!nonMechanismKeys.contains(string.low)) {
                any = true;
                ObjectTag obj = CoreUtilities.objectToTagForm(getContents().get(string.low), context, true, true);
                entity.safeAdjust(new Mechanism(string.low, obj, context));
            }
        }
        if (any) {
            Deprecations.entityMechanismsFormat.warn(this);
        }
        if (entity == null || entity.isUnique()) {
            return null;
        }
        entity.setEntityScript(getName());
    } catch (Exception e) {
        Debug.echoError("Woah! An exception has been called with this entity script!");
        Debug.echoError(e);
        entity = null;
    }
    return entity;
}
Also used : BukkitTagContext(com.denizenscript.denizen.tags.BukkitTagContext) TagContext(com.denizenscript.denizencore.tags.TagContext) MapTagFlagTracker(com.denizenscript.denizencore.flags.MapTagFlagTracker) YamlConfiguration(com.denizenscript.denizencore.utilities.YamlConfiguration) Mechanism(com.denizenscript.denizencore.objects.Mechanism) StringHolder(com.denizenscript.denizencore.utilities.text.StringHolder) ObjectTag(com.denizenscript.denizencore.objects.ObjectTag) BukkitTagContext(com.denizenscript.denizen.tags.BukkitTagContext) ScriptTag(com.denizenscript.denizencore.objects.core.ScriptTag) EntityTag(com.denizenscript.denizen.objects.EntityTag)

Example 25 with BukkitTagContext

use of com.denizenscript.denizen.tags.BukkitTagContext in project Denizen-For-Bukkit by DenizenScript.

the class FormatScriptContainer method getFormattedText.

public String getFormattedText(String textToReplace, NPCTag npc, PlayerTag player) {
    String name = npc != null ? npc.getName() : (player != null ? player.getName() : "");
    String text = getFormat();
    if (text.contains("<text") || text.contains("<name")) {
        Deprecations.pseudoTagBases.warn(this);
        text = text.replace("<text", "<element[" + EscapeTagBase.escape(textToReplace) + "].unescaped").replace("<name", "<element[" + EscapeTagBase.escape(name) + "].unescaped");
    }
    BukkitTagContext context = new BukkitTagContext(player, npc, new ScriptTag(this));
    context.definitionProvider = new SimpleDefinitionProvider();
    context.definitionProvider.addDefinition("text", new ElementTag(textToReplace));
    context.definitionProvider.addDefinition("name", new ElementTag(name));
    return TagManager.tag(text, context);
}
Also used : BukkitTagContext(com.denizenscript.denizen.tags.BukkitTagContext) ScriptTag(com.denizenscript.denizencore.objects.core.ScriptTag) ElementTag(com.denizenscript.denizencore.objects.core.ElementTag) SimpleDefinitionProvider(com.denizenscript.denizencore.utilities.SimpleDefinitionProvider)

Aggregations

BukkitTagContext (com.denizenscript.denizen.tags.BukkitTagContext)28 ScriptTag (com.denizenscript.denizencore.objects.core.ScriptTag)16 PlayerTag (com.denizenscript.denizen.objects.PlayerTag)9 ElementTag (com.denizenscript.denizencore.objects.core.ElementTag)9 ObjectTag (com.denizenscript.denizencore.objects.ObjectTag)5 TagContext (com.denizenscript.denizencore.tags.TagContext)5 Player (org.bukkit.entity.Player)5 EntityTag (com.denizenscript.denizen.objects.EntityTag)4 ItemTag (com.denizenscript.denizen.objects.ItemTag)4 NPCTag (com.denizenscript.denizen.objects.NPCTag)4 ListTag (com.denizenscript.denizencore.objects.core.ListTag)4 ScriptEntry (com.denizenscript.denizencore.scripts.ScriptEntry)4 List (java.util.List)4 EventHandler (org.bukkit.event.EventHandler)4 FormatScriptContainer (com.denizenscript.denizen.scripts.containers.core.FormatScriptContainer)3 ScriptQueue (com.denizenscript.denizencore.scripts.queues.ScriptQueue)3 YamlConfiguration (com.denizenscript.denizencore.utilities.YamlConfiguration)3 StringHolder (com.denizenscript.denizencore.utilities.text.StringHolder)3 NMSHandler (com.denizenscript.denizen.nms.NMSHandler)2 TriggerTrait (com.denizenscript.denizen.npc.traits.TriggerTrait)2