Example #1
0
  @EventHandler
  public void asyncChatTrigger(final AsyncPlayerChatEvent event) {
    if (event.isCancelled()) return;

    // Return if "Use asynchronous event" is false in config file
    if (!Settings.ChatAsynchronous()) return;

    Callable<Boolean> call =
        new Callable<Boolean>() {
          public Boolean call() {
            return process(event.getPlayer(), event.getMessage());
          }
        };

    Boolean cancelled = false;

    try {
      cancelled =
          event.isAsynchronous()
              ? Bukkit.getScheduler().callSyncMethod(DenizenAPI.getCurrentInstance(), call).get()
              : call.call();
    } catch (InterruptedException e) {
      // dB.echoError(e);
    } catch (ExecutionException e) {
      dB.echoError(e);
    } catch (Exception e) {
      dB.echoError(e);
    }

    event.setCancelled(cancelled);
  }
  @Override
  public boolean check(RequirementsContext context, List<String> args)
      throws RequirementCheckException {

    boolean outcome = false;
    String name = null;
    String value = "true";
    String index = "";
    Type type = Type.PLAYER;

    for (String arg : args) {

      if (aH.matchesArg("GLOBAL, NPC, DENIZEN, GLOBAL", arg))
        type = Type.valueOf(arg.toUpperCase().replace("DENIZEN", "NPC"));
      else if (arg.split(":", 2).length > 1) {
        String[] flagArgs = arg.split(":");
        value = flagArgs[1].toUpperCase();

        if (flagArgs[0].contains("[")) {
          name = flagArgs[0].split("\\[", 2)[0].trim();
          index = flagArgs[0].split("\\[", 2)[1].split("\\]", 2)[0].trim();
        } else {
          name = flagArgs[0].toUpperCase();
        }
      } else name = arg.toUpperCase();
    }

    FlagManager flagMng = DenizenAPI.getCurrentInstance().flagManager();
    FlagManager.Flag flag = null;
    String player = context.getPlayer().getName();

    switch (type) {
      case NPC:
        flag = flagMng.getNPCFlag(context.getNPC().getId(), name);
        break;
      case PLAYER:
        flag = flagMng.getPlayerFlag(player, name);
        break;
      case GLOBAL:
        flag = flagMng.getGlobalFlag(name);
        break;
    }

    if (index.length() == 0) {
      if (flag.getLast().asString().equalsIgnoreCase(value)) outcome = true;
      else
        dB.echoDebug(
            context.getScriptContainer(),
            "... does not match '" + flag.getLast().asString() + "'.");
    } else if (index.matches("\\d+")) {
      if (flag.get(Integer.parseInt(index)).asString().equalsIgnoreCase(value)) outcome = true;
      else
        dB.echoDebug(
            context.getScriptContainer(),
            "... does not match '" + flag.get(Integer.parseInt(index)).asString() + "'.");
    }

    return outcome;
  }
Example #3
0
 public void action(String actionName, Player player) {
   if (getCitizen() != null) {
     if (getCitizen().hasTrait(AssignmentTrait.class))
       DenizenAPI.getCurrentInstance()
           .getNPCRegistry()
           .getActionHandler()
           .doAction(actionName, this, player, getAssignmentTrait().getAssignment());
   }
 }
Example #4
0
  @Override
  public void onSpawn() {

    if (text != null) {
      Bukkit.getScheduler()
          .scheduleSyncDelayedTask(
              DenizenAPI.getCurrentInstance(),
              new Runnable() {
                @Override
                public void run() {
                  npc.getBukkitEntity().setCustomNameVisible(true);
                  npc.getBukkitEntity().setCustomName(text);
                }
              },
              2);
    }

    if (getColor() != null) {
      refreshTag(getNPC());
    }
  }
Example #5
0
  public static void walkTo(
      final Entity entity, Location location, double speed, final Runnable callback) {
    if (entity == null || location == null) return;

    net.minecraft.server.v1_8_R3.Entity nmsEntityEntity = ((CraftEntity) entity).getHandle();
    if (!(nmsEntityEntity instanceof EntityInsentient)) return;
    final EntityInsentient nmsEntity = (EntityInsentient) nmsEntityEntity;
    final NavigationAbstract entityNavigation = nmsEntity.getNavigation();

    final PathEntity path;
    final boolean aiDisabled = isAIDisabled(entity);
    if (aiDisabled) {
      toggleAI(entity, true);
      nmsEntity.onGround = true;
    }
    path = entityNavigation.a(location.getX(), location.getY(), location.getZ());
    if (path != null) {
      entityNavigation.a(path, 1D);
      entityNavigation.a(2D);
      final double oldSpeed = nmsEntity.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).b();
      nmsEntity.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(speed);
      new BukkitRunnable() {
        @Override
        public void run() {
          if (entityNavigation.m() || path.b()) {
            if (callback != null) callback.run();
            nmsEntity.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(oldSpeed);
            if (aiDisabled) toggleAI(entity, false);
            cancel();
          }
        }
      }.runTaskTimer(DenizenAPI.getCurrentInstance(), 1, 1);
    }
    // if (!Utilities.checkLocation(location, entity.getLocation(), 20)) {
    // TODO: generate waypoints to the target location?
    else {
      entity.teleport(location);
    }
  }
Example #6
0
 @Override
 public void onEnable() {
   Bukkit.getServer().getPluginManager().registerEvents(this, DenizenAPI.getCurrentInstance());
 }
Example #7
0
  public boolean execute(ScriptEntry scriptEntry) {
    Matcher m;
    StringBuffer sb;
    if (scriptEntry.getCommandName().indexOf('%') != -1) {
      m = definition_pattern.matcher(scriptEntry.getCommandName());
      sb = new StringBuffer();
      while (m.find()) {
        String definition = scriptEntry.getResidingQueue().getDefinition(m.group(1));
        if (definition == null) definition = "null";
        m.appendReplacement(sb, definition);
      }
      m.appendTail(sb);
      scriptEntry.setCommandName(sb.toString());
    }

    // Get the command instance ready for the execution of the scriptEntry
    AbstractCommand command = plugin.getCommandRegistry().get(scriptEntry.getCommandName());

    if (command == null) {
      dB.echoDebug(
          scriptEntry, DebugElement.Header, "Executing command: " + scriptEntry.getCommandName());
      dB.echoError(
          scriptEntry.getCommandName() + " is an invalid dCommand! Are you sure it loaded?");
      dB.echoDebug(scriptEntry, DebugElement.Footer);
      return false;
    }

    // Debugger information
    if (scriptEntry.getPlayer() != null)
      dB.echoDebug(
          scriptEntry,
          DebugElement.Header,
          "Executing dCommand: "
              + scriptEntry.getCommandName()
              + "/"
              + scriptEntry.getPlayer().getName());
    else
      dB.echoDebug(
          scriptEntry,
          DebugElement.Header,
          "Executing dCommand: "
              + scriptEntry.getCommandName()
              + (scriptEntry.getNPC() != null ? "/" + scriptEntry.getNPC().getName() : ""));

    // Don't execute() if problems arise in parseArgs()
    boolean keepGoing = true;

    try {

      // Throw exception if arguments are required for this command, but not supplied.
      if (command.getOptions().REQUIRED_ARGS > scriptEntry.getArguments().size())
        throw new InvalidArgumentsException("");

      if (scriptEntry.has_tags)
        scriptEntry.setArguments(
            TagManager.fillArguments(
                scriptEntry.getArguments(), scriptEntry, true)); // Replace tags

      /*  If using NPC:# or PLAYER:Name arguments, these need to be changed out immediately because...
       *  1) Denizen/Player flags need the desired NPC/PLAYER before parseArgs's getFilledArguments() so that
       *     the Player/Denizen flags will read from the correct Object. If using PLAYER or NPCID arguments,
       *     the desired Objects are obviously not the same objects that were sent with the ScriptEntry.
       *  2) These arguments should be valid for EVERY ScriptCommand, so why not just take care of it
       *     here, instead of requiring each command to take care of the argument.
       */

      List<String> newArgs = new ArrayList<String>();

      // Don't fill in tags if there were brackets detected..
      // This means we're probably in a nested if.
      int nested_depth = 0;
      // Watch for IF command to avoid filling player and npc arguments
      // prematurely
      boolean if_ignore = false;

      for (aH.Argument arg : aH.interpret(scriptEntry.getArguments())) {
        if (arg.getValue().equals("{")) nested_depth++;
        if (arg.getValue().equals("}")) nested_depth--;

        // If nested, continue.
        if (nested_depth > 0) {
          newArgs.add(arg.raw_value);
          continue;
        }

        if (arg.raw_value.indexOf('%') != -1) {
          m = definition_pattern.matcher(arg.raw_value);
          sb = new StringBuffer();
          while (m.find()) {
            String definition = scriptEntry.getResidingQueue().getDefinition(m.group(1));
            if (definition == null) definition = "null";
            m.appendReplacement(sb, definition);
          }
          m.appendTail(sb);
          arg = aH.Argument.valueOf(sb.toString());
        }

        // If using IF, check if we've reached the command + args
        // so that we don't fill player: or npc: prematurely
        if (command.getName().equalsIgnoreCase("if")
            && DenizenAPI.getCurrentInstance().getCommandRegistry().get(arg.getValue()) != null)
          if_ignore = true;

        // Fill player/off-line player
        if (arg.matchesPrefix("player") && !if_ignore) {
          dB.echoDebug(scriptEntry, "...replacing the linked player with " + arg.getValue());
          String value =
              TagManager.tag(
                  scriptEntry.getPlayer(),
                  scriptEntry.getNPC(),
                  arg.getValue(),
                  false,
                  scriptEntry);
          dPlayer player = dPlayer.valueOf(value);
          if (player == null || !player.isValid()) {
            dB.echoError(value + " is an invalid player!");
            return false;
          }
          scriptEntry.setPlayer(player);
        }

        // Fill NPCID/NPC argument
        else if (arg.matchesPrefix("npc, npcid") && !if_ignore) {
          dB.echoDebug(scriptEntry, "...replacing the linked NPC with " + arg.getValue());
          String value =
              TagManager.tag(
                  scriptEntry.getPlayer(),
                  scriptEntry.getNPC(),
                  arg.getValue(),
                  false,
                  scriptEntry);
          dNPC npc = dNPC.valueOf(value);
          if (npc == null || !npc.isValid()) {
            dB.echoError(value + " is an invalid NPC!");
            return false;
          }
          scriptEntry.setNPC(npc);
        }

        // Save the scriptentry if needed later for fetching scriptentry context
        else if (arg.matchesPrefix("save") && !if_ignore) {
          dB.echoDebug(scriptEntry, "...remembering this script entry!");
          scriptEntry.getResidingQueue().holdScriptEntry(arg.getValue(), scriptEntry);
        } else newArgs.add(arg.raw_value);
      }

      // Add the arguments back to the scriptEntry.
      scriptEntry.setArguments(newArgs);

      // Now process non-instant tags.
      if (scriptEntry.has_tags)
        scriptEntry.setArguments(
            TagManager.fillArguments(scriptEntry.getArguments(), scriptEntry, false));

      // Parse the rest of the arguments for execution.
      command.parseArgs(scriptEntry);

    } catch (InvalidArgumentsException e) {

      keepGoing = false;
      // Give usage hint if InvalidArgumentsException was called.
      dB.echoError("Woah! Invalid arguments were specified!");
      if (e.getMessage() != null && e.getMessage().length() > 0)
        dB.log(
            ChatColor.YELLOW
                + "+> MESSAGE follows: "
                + ChatColor.WHITE
                + "'"
                + e.getMessage()
                + "'");
      dB.log("Usage: " + command.getUsageHint());
      dB.echoDebug(scriptEntry, DebugElement.Footer);
      scriptEntry.setFinished(true);

    } catch (Exception e) {

      keepGoing = false;
      dB.echoError("Woah! An exception has been called with this command!");
      dB.echoError(e);
      dB.echoDebug(scriptEntry, DebugElement.Footer);
      scriptEntry.setFinished(true);

    } finally {

      if (keepGoing)
        try {
          // Run the execute method in the command
          command.execute(scriptEntry);
        } catch (Exception e) {
          dB.echoError("Woah!! An exception has been called with this command!");
          dB.echoError(e);
          scriptEntry.setFinished(true);
        }
    }

    return true;
  }
Example #8
0
 public static dNPCRegistry getCurrentInstance() {
   return DenizenAPI.getCurrentInstance().getNPCRegistry();
 }
Example #9
0
 @Deprecated
 public boolean isInteracting() {
   if (!DenizenAPI._commandRegistry().get(EngageCommand.class).getEngaged(getCitizen()))
     return true;
   else return false;
 }
Example #10
0
  public static void follow(
      final Entity target,
      final Entity follower,
      final double speed,
      final double lead,
      final double maxRange,
      final boolean allowWander) {
    if (target == null || follower == null) return;

    final net.minecraft.server.v1_8_R3.Entity nmsEntityFollower =
        ((CraftEntity) follower).getHandle();
    if (!(nmsEntityFollower instanceof EntityInsentient)) return;
    final EntityInsentient nmsFollower = (EntityInsentient) nmsEntityFollower;
    final NavigationAbstract followerNavigation = nmsFollower.getNavigation();

    UUID uuid = follower.getUniqueId();

    if (followTasks.containsKey(uuid)) followTasks.get(uuid).cancel();

    final int locationNearInt = (int) Math.floor(lead);
    final boolean hasMax = maxRange > lead;

    followTasks.put(
        follower.getUniqueId(),
        new BukkitRunnable() {

          private boolean inRadius = false;

          public void run() {
            if (!target.isValid() || !follower.isValid()) {
              this.cancel();
            }
            followerNavigation.a(2F);
            Location targetLocation = target.getLocation();
            PathEntity path;

            if (hasMax
                && !Utilities.checkLocation(targetLocation, follower.getLocation(), maxRange)
                && !target.isDead()
                && target.isOnGround()) {
              if (!inRadius) {
                follower.teleport(
                    Utilities.getWalkableLocationNear(targetLocation, locationNearInt));
              } else {
                inRadius = false;
                path =
                    followerNavigation.a(
                        targetLocation.getX(), targetLocation.getY(), targetLocation.getZ());
                if (path != null) {
                  followerNavigation.a(path, 1D);
                  followerNavigation.a(2D);
                }
              }
            } else if (!inRadius
                && !Utilities.checkLocation(targetLocation, follower.getLocation(), lead)) {
              path =
                  followerNavigation.a(
                      targetLocation.getX(), targetLocation.getY(), targetLocation.getZ());
              if (path != null) {
                followerNavigation.a(path, 1D);
                followerNavigation.a(2D);
              }
            } else {
              inRadius = true;
            }
            if (inRadius && !allowWander) {
              followerNavigation.n();
            }
            nmsFollower.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(speed);
          }
        }.runTaskTimer(DenizenAPI.getCurrentInstance(), 0, 20));
  }