示例#1
0
  @EventHandler
  public void onPlayerMove(PlayerMoveEvent e) {
    if (b) return;
    if (getObjID() == null) {
      return;
    }
    if (getObjID().getSQLAction().equals(SQLAction.REMOVE)) {
      return;
    }
    if (e.isCancelled()) {
      return;
    }

    if (e.getFrom().getWorld() == e.getTo().getWorld()
        && e.getFrom().getBlockX() == e.getTo().getBlockX()
        && e.getFrom().getBlockY() == e.getTo().getBlockY()
        && e.getFrom().getBlockZ() == e.getTo().getBlockZ()) return;

    Player player = e.getPlayer();
    if (player.getHealth() <= 0.0D) return;
    Location loc = e.getTo().getBlock().getLocation();
    Location loc2 = getLocation();
    if (loc.toVector().distance(loc2.toVector()) < 1) {
      setStatus(true);
      player.damage(main.damage);
    }
  }
 private void checkInventory(Inventory inv, Set<BlockData> goals, Location loc) {
   for (ItemStack item : inv.getContents()) {
     BlockData bd = BlockData.fromItemStack(item);
     for (BlockData data : goals)
       if (data.equals(bd)) master.found.add(new _Entry<BlockData, Vector>(data, loc.toVector()));
   }
 }
  private void Scalae(String[] components, PlayerChatEvent ev) {
    boolean ow = IsForceful(components, ev);
    Material _cp = null;

    Location location = ev.getPlayer().getTargetBlock(null, 500).getLocation();
    int x = location.getBlockX();
    int y = location.getBlockY();
    int z = location.getBlockZ();
    for (int scale = 0; scale <= this.size; scale++) {
      write_block(ow, x - 1, y, z - 1, _cp);
      write_block(ow, x - 1, y + 1, z, _cp);
      write_block(ow, x - 1, y + 2, z + 1, _cp);
      write_block(ow, x, y + 3, z + 1, _cp);
      write_block(ow, x + 1, y + 4, z + 1, _cp);
      write_block(ow, x + 1, y + 5, z, _cp);
      write_block(ow, x + 1, y + 6, z - 1, _cp);
      write_block(ow, x, y + 7, z - 1, _cp);
      for (int h = 0; h < 8; h++) {
        write_block(ow, x, y++, z, _cp);
      }
    }
    if (IsMotion(components, ev))
      ev.getPlayer()
          .teleport(
              location
                  .toVector()
                  .add(new Vector(0, (this.size + 1) * 8, 0))
                  .toLocation(ev.getPlayer().getWorld()));
  }
示例#4
0
  public static void sendToLocation(
      final ParticleEffect effect,
      final Location location,
      final float offsetX,
      final float offsetY,
      final float offsetZ,
      final float speed,
      final int count)
      throws Exception {
    // Hive.log.info(effect.name + " @ " + location.toString());
    Object packet = null;
    try {
      packet = createPacket(effect, location, offsetX, offsetY, offsetZ, speed, count);
    } catch (Exception e) {
      e.printStackTrace();
    }
    double radius = 32D;

    for (String s : MonsterMechanics.player_locations.keySet()) {
      if (Bukkit.getPlayerExact(s) != null) {
        Player pl = Main.plugin.getServer().getPlayer(s);
        if (pl.getWorld().getName().equalsIgnoreCase(location.getWorld().getName())
            && pl.getLocation().toVector().distanceSquared(location.toVector())
                <= Math.pow(radius, 2)) {
          try {
            sendPacket(pl, packet);
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }
    }
  }
  public ArenaRegion newRegion(
      String name, Arena arena, Location pos1, Location pos2, RegionShape shape) {
    for (ArenaRegion region : regions) {
      if (region.getShape().equals(shape)) {
        ArenaRegion result = region.clone();
        result.name = name;
        result.min = pos1.toVector();
        result.max = pos2.toVector();
        result.arena = arena;
        result.world = pos1.getWorld();

        setRegionTypeByName(result, name);

        result.initialize();
        return result;
      }
    }
    return null;
  }
示例#6
0
 @Override
 public void stopMusic(Location location) {
   /** get players in radius of the jukebox and start it for only those players * */
   for (Player p : location.getWorld().getPlayers()) {
     double distance = location.toVector().distance(p.getLocation().toVector());
     if (distance <= (double) range) {
       SpoutPlayer sp = SpoutManager.getPlayer(p);
       if (sp.isSpoutCraftEnabled()) {
         SpoutManager.getSoundManager().stopMusic(sp);
       }
     }
   }
 }
示例#7
0
 public static void checkSecond() {
   for (Item i : Bukkit.getWorld("PrisonMap").getEntitiesByClass(Item.class)) {
     if (tnts.contains(i.getUniqueId())) {
       ParticleEffect.SMOKE_NORMAL.display(
           0.25f, 0.25f, 0.25f, 0.0001f, 5, i.getLocation().clone().add(0, 0.5, 0), 100);
       if (i.getTicksLived() > 30) {
         ParticleEffect.EXPLOSION_HUGE.display(
             0.5f, 0.5f, 0.5f, 0.1f, 5, i.getLocation().clone().add(0, 1, 0), 100);
         for (Entity e : i.getNearbyEntities(3.5, 3.5, 3.5)) {
           if (e instanceof Player) {
             Location midPoint = i.getLocation();
             Vector direction =
                 e.getLocation().toVector().subtract(midPoint.toVector()).normalize();
             direction.multiply(1.1).setY(0.7);
             e.setVelocity(direction);
             ((Player) e).damage(0.0);
           }
         }
         final List<Location> blocks = new ArrayList<Location>();
         int radius = 3;
         int bX = i.getLocation().getBlockX();
         int bY = i.getLocation().getBlockY();
         int bZ = i.getLocation().getBlockZ();
         for (int x = bX - radius; x <= bX + radius; x++) {
           for (int y = bY - radius; y <= bY + radius; y++) {
             for (int z = bZ - radius; z <= bZ + radius; z++) {
               double distance =
                   ((bX - x) * (bX - x) + ((bZ - z) * (bZ - z)) + ((bY - y) * (bY - y)));
               if (distance < radius * radius) {
                 Location loc = new Location(i.getWorld(), x, y, z);
                 if (loc.getBlock().getType() != Material.AIR) {
                   blocks.add(loc);
                 }
               }
             }
           }
         }
         for (Location loc : blocks) {
           Random r = new Random();
           int i1 = r.nextInt(3) + 1;
           if (Game.isBreakable(loc.getBlock().getType()) && (i1 == 1 || i1 == 2)) {
             loc.getBlock().setType(Material.AIR);
           }
         }
         Game.playSound(Sound.EXPLODE, i.getLocation(), 1f, 1f);
         tnts.remove(i.getUniqueId());
         i.teleport(i.getLocation().subtract(0, 500, 0));
       }
     }
   }
 }
示例#8
0
  public void onRun() {
    Location location = getLocation();
    // Lines
    int mL = RandomUtils.random.nextInt(maxLines - 2) + 2;
    for (int m = 0; m < mL * 2; m++) {
      double x = RandomUtils.random.nextInt(max - max * (-1)) + max * (-1);
      double y = RandomUtils.random.nextInt(max - max * (-1)) + max * (-1);
      double z = RandomUtils.random.nextInt(max - max * (-1)) + max * (-1);
      if (direction == Direction.DOWN) y = RandomUtils.random.nextInt(max * 2 - max) + max;
      else if (direction == Direction.UP)
        y = RandomUtils.random.nextInt(max * (-1) - max * (-2)) + max * (-2);
      Location target = location.clone().subtract(x, y, z);
      if (target == null) {
        cancel();
        return;
      }
      Vector link = target.toVector().subtract(location.toVector());
      float length = (float) link.length();
      link.normalize();

      float ratio = length / lineParticles;
      Vector v = link.multiply(ratio);
      Location loc = location.clone().subtract(v);
      for (int i = 0; i < lineParticles; i++) {
        loc.add(v);
        display(lineParticle, loc, lineColor);
      }
    }

    // Sphere
    for (int i = 0; i < sphereParticles; i++) {
      Vector vector = RandomUtils.getRandomVector().multiply(sphereRadius);
      location.add(vector);
      display(sphereParticle, location, sphereColor);
      location.subtract(vector);
    }
  }
示例#9
0
  public boolean inBounds(final Location locationToCheck) {
    if (!locationToCheck.getWorld().equals(getPointOne().getWorld())) {
      return false;
    }

    // For open worlds that do not have specified points
    if (globalRegion) {
      return false; // needs to return false to allow nested override
    }

    return locationToCheck
        .toVector()
        .isInAABB(
            Vector.getMinimum(getPointOne().toVector(), getPointTwo().toVector()),
            Vector.getMaximum(getPointOne().toVector(), getPointTwo().toVector()));
  }
示例#10
0
 @Override
 public void playMusic(String url, Location location) {
   /** get players in radius of the jukebox and start it for only those players * */
   for (Player p : location.getWorld().getPlayers()) {
     double distance = location.toVector().distance(p.getLocation().toVector());
     if (distance <= (double) range) {
       SpoutPlayer sp = SpoutManager.getPlayer(p);
       if (sp.isSpoutCraftEnabled()) {
         try {
           SpoutManager.getSoundManager().playCustomMusic(plugin, sp, url, true, location, range);
         } catch (Exception e) {
           // the disc has an error.
           // player.sendMessage(e.getMessage());
           SpoutManager.getSoundManager()
               .playGlobalCustomSoundEffect(
                   plugin, CustomsManager.SF_JUKEBOX_ERROR, false, location, 3);
         }
       }
     }
   }
 }
示例#11
0
 public static void checkThird() {
   for (Player p : Bukkit.getOnlinePlayers()) {
     if (Game.playerInGame(p) && ultimate.contains(p.getName())) {
       if (p.getLocation().clone().subtract(0, 1, 0).getBlock().getType() != Material.AIR) {
         int radius = 4;
         int bX = p.getLocation().getBlockX();
         int bY = p.getLocation().getBlockY();
         int bZ = p.getLocation().getBlockZ();
         for (int x = bX - radius; x <= bX + radius; x++) {
           for (int y = bY - radius; y <= bY + radius; y++) {
             for (int z = bZ - radius; z <= bZ + radius; z++) {
               double distance =
                   ((bX - x) * (bX - x) + ((bZ - z) * (bZ - z)) + ((bY - y) * (bY - y)));
               if (distance < radius * radius && !(distance < ((radius - 1) * (radius - 1)))) {
                 Location loc = new Location(p.getWorld(), x, y, z);
                 if (Game.isBreakable(loc.getBlock().getType())) {
                   ParticleEffect.EXPLOSION_LARGE.display(
                       0.1f, 0.1f, 0.1f, 0.1f, 3, loc.clone().add(0, 0.2, 0), 100);
                 }
               }
             }
           }
         }
         for (Entity e : p.getNearbyEntities(3, 2, 3)) {
           if (e instanceof Player) {
             Location midPoint = p.getLocation();
             Vector direction =
                 e.getLocation().toVector().subtract(midPoint.toVector()).normalize();
             direction.multiply(0.5).setY(0.3);
             e.setVelocity(direction);
             ((Player) e).damage(0.0);
           }
         }
       }
     }
   }
 }
示例#12
0
 /**
  * Creates region around specified location with specified size.
  *
  * @param center center
  * @param size size
  * @return region
  */
 public static Region createAroundBox(final Location center, final int size) {
   return new Region(
       center.toVector().add(new Vector(size, size, size)),
       center.toVector().subtract(new Vector(size, size, size)),
       center.getWorld());
 }
示例#13
0
 /**
  * Returns whether the location intersects X and Z coordinate of this region.
  *
  * @param loc location to check
  * @return
  */
 public boolean intersectsXZ(final Location loc) {
   if (this.w.getName().equals(loc.getWorld().getName())) return this.intersectsXZ(loc.toVector());
   else return false;
 }
示例#14
0
  public void target(TargetMode mode) {
    targetMode = mode == null ? TargetMode.STABILIZE : mode;
    switch (targetMode) {
      case FLEE:
      case HUNT:
      case DIRECTED:
        Target bestTarget = null;
        reverseTargetDistanceScore = true;
        if (targetType == TargetType.ANY || targetType == TargetType.MOB) {
          List<Entity> entities =
              CompatibilityUtils.getNearbyEntities(
                  center, huntMaxRange, huntMaxRange, huntMaxRange);
          for (Entity entity : entities) {
            // We'll get the players from the Mages list
            if (entity instanceof Player || !(entity instanceof LivingEntity) || entity.isDead())
              continue;
            if (!entity.getLocation().getWorld().equals(center.getWorld())) continue;
            LivingEntity li = (LivingEntity) entity;
            if (li.hasPotionEffect(PotionEffectType.INVISIBILITY)) continue;
            Target newScore =
                new Target(center, entity, huntMinRange, huntMaxRange, huntFov, false);
            int score = newScore.getScore();
            if (bestTarget == null || score > bestTarget.getScore()) {
              bestTarget = newScore;
            }
          }
        }
        if (targetType == TargetType.MAGE
            || targetType == TargetType.AUTOMATON
            || targetType == TargetType.ANY
            || targetType == TargetType.PLAYER) {
          Collection<Mage> mages = controller.getMages();
          for (Mage mage : mages) {
            if (mage == this.mage) continue;
            if (targetType == TargetType.AUTOMATON && mage.getPlayer() != null) continue;
            if (targetType == TargetType.PLAYER && mage.getPlayer() == null) continue;
            if (mage.isDead() || !mage.isOnline() || !mage.hasLocation()) continue;
            if (!mage.getLocation().getWorld().equals(center.getWorld())) continue;
            if (!mage.getLocation().getWorld().equals(center.getWorld())) continue;

            if (!mage.isPlayer()) {
              // Check for automata of the same type, kinda hacky.. ?
              Block block = mage.getLocation().getBlock();
              if (block.getType() == Material.COMMAND) {
                BlockState blockState = block.getState();
                if (blockState != null && blockState instanceof CommandBlock) {
                  CommandBlock command = (CommandBlock) blockState;
                  String commandString = command.getCommand();
                  if (commandString != null
                      && commandString.length() > 0
                      && commandString.startsWith("cast " + spell.getKey())) {
                    continue;
                  }
                }
              }
            } else {
              Player player = mage.getPlayer();
              if (player.hasPotionEffect(PotionEffectType.INVISIBILITY)) continue;
            }

            Target newScore = new Target(center, mage, huntMinRange, huntMaxRange, huntFov, false);
            int score = newScore.getScore();
            if (bestTarget == null || score > bestTarget.getScore()) {
              bestTarget = newScore;
            }
          }
        }

        if (bestTarget != null) {
          String targetDescription =
              bestTarget.getEntity() == null
                  ? "NONE"
                  : ((bestTarget instanceof Player)
                      ? ((Player) bestTarget.getEntity()).getName()
                      : bestTarget.getEntity().getType().name());

          if (DEBUG) {
            controller
                .getLogger()
                .info(
                    " *Tracking "
                        + targetDescription
                        + " score: "
                        + bestTarget.getScore()
                        + " location: "
                        + center
                        + " -> "
                        + bestTarget.getLocation()
                        + " move "
                        + commandMoveRangeSquared);
          }
          Vector direction = null;

          if (targetMode == TargetMode.DIRECTED) {
            direction = bestTarget.getLocation().getDirection();
            if (DEBUG) {
              controller.getLogger().info(" *Directed: " + direction);
            }
          } else {
            Location targetLocation = bestTarget.getLocation();
            direction = targetLocation.toVector().subtract(center.toVector());
          }

          if (direction != null) {
            center.setDirection(direction);
          }

          // Check for obstruction
          // TODO Think about this more..
          /*
          Block block = spell.getInteractBlock();
          if (block.getType() != Material.AIR && block.getType() != POWER_MATERIAL && !!birthMaterial.is(block)) {
          	// TODO: Use location.setDirection in 1.7+
          	center = CompatibilityUtils.setDirection(center, new Vector(0, 1, 0));
          }
          */

          if (level != null
              && center.distanceSquared(bestTarget.getLocation()) < castRange * castRange) {
            level.onTick(mage, birthMaterial);
          }

          // After ticking, re-position for movement. This way spells still fire towards the target.
          if (targetMode == TargetMode.FLEE) {
            direction = direction.multiply(-1);
            // Don't Flee upward
            if (direction.getY() > 0) {
              direction.setY(-direction.getY());
            }
          }
        }
        break;
      case GLIDE:
        reverseTargetDistanceScore = true;
        break;
      default:
        reverseTargetDistanceScore = false;
    }
  }
示例#15
0
  @Override
  public int process(int maxBlocks) {
    int processedBlocks = 0;
    if (state == SimulationState.SCANNING_COMMAND) {
      // Process the casting command block first, and only if specially configured to do so.
      if (includeCommands && castCommandBlock != null) {
        // We are going to rely on the block toggling to kick this back to life when the chunk
        // reloads, so for now just bail and hope the timing works out.
        if (!castCommandBlock.getChunk().isLoaded()) {
          finish();
          // TODO: Maybe Scatter-shot and register all 6 surrounding power blocks for reload toggle.
          // Can't really do it without the chunk being loaded though, so hrm.
          return processedBlocks;
        }

        // Check for death since activation (e.g. during delay period)
        if (castCommandBlock.getType() != Material.COMMAND) {
          die();
          finish();
          return processedBlocks;
        }

        // Check for power blocks
        for (BlockFace powerFace : POWER_FACES) {
          Block checkForPower = castCommandBlock.getRelative(powerFace);
          if (checkForPower.getType() == POWER_MATERIAL) {
            if (commandReload) {
              controller.unregisterAutomata(checkForPower);
            }
            powerSimMaterial.modify(checkForPower);
            commandPowered = true;
          }
        }

        if (!commandPowered) {
          die();
          finish();
          return processedBlocks;
        }

        // Make this a normal block so the sim will process it
        // this also serves to reset the command block for the next tick, if it lives.
        birthMaterial.modify(castCommandBlock);
      }

      processedBlocks++;
      state = SimulationState.SCANNING;
    }

    while (state == SimulationState.SCANNING && processedBlocks <= maxBlocks) {
      if (!simulateBlocks(x, y, z)) {
        return processedBlocks;
      }

      y++;
      if (y > yRadius) {
        y = 0;
        if (x < radius) {
          x++;
        } else {
          z--;
          if (z < 0) {
            r++;
            z = r;
            x = 0;
          }
        }
      }

      if (r > radius) {
        state = SimulationState.UPDATING;
      }
    }

    while (state == SimulationState.UPDATING && processedBlocks <= maxBlocks) {
      int deadIndex = updatingIndex;
      if (deadIndex >= 0 && deadIndex < deadBlocks.size()) {
        Block killBlock = deadBlocks.get(deadIndex);
        if (!killBlock.getChunk().isLoaded()) {
          killBlock.getChunk().load();
          return processedBlocks;
        }

        if (birthMaterial.is(killBlock)) {
          registerForUndo(killBlock);
          killBlock.setType(deathMaterial);
        } else {
          // If this block was destroyed while we were processing,
          // avoid spawning a random birth block.
          // This tries to make it so automata don't "cheat" when
          // getting destroyed. A bit hacky though, I'm not about
          // to re-simulate...
          if (bornBlocks.size() > 0) {
            bornBlocks.remove(bornBlocks.size() - 1);
          }
        }
        processedBlocks++;
      }

      int bornIndex = updatingIndex - deadBlocks.size();
      if (bornIndex >= 0 && bornIndex < bornBlocks.size()) {
        Block birthBlock = bornBlocks.get(bornIndex);
        if (!birthBlock.getChunk().isLoaded()) {
          birthBlock.getChunk().load();
          return processedBlocks;
        }
        registerForUndo(birthBlock);
        birthMaterial.modify(birthBlock);
      }

      updatingIndex++;
      if (updatingIndex >= deadBlocks.size() + bornBlocks.size()) {
        state = SimulationState.COMMAND_SEARCH;

        // Wait at least a tick before re-populating the command block.
        return maxBlocks;
      }
    }

    // Each of the following states will end in this tick, to give the
    // MC sim time to register power updates.
    if (state == SimulationState.COMMAND_SEARCH) {
      if (includeCommands && potentialCommandBlocks.size() > 0) {
        switch (targetMode) {
          case HUNT:
            Collections.sort(potentialCommandBlocks);
            break;
          case FLEE:
            Collections.sort(potentialCommandBlocks);
            break;
          default:
            Collections.shuffle(potentialCommandBlocks);
            break;
        }

        // Find a valid block for the command
        powerTargetBlock = null;
        commandTargetBlock = null;
        Block backupBlock = null;
        while (commandTargetBlock == null && potentialCommandBlocks.size() > 0) {
          Block block = potentialCommandBlocks.remove(0).getBlock();
          if (block != null && birthMaterial.is(block)) {
            // If we're powering the block, look for one with a powerable neighbor.
            if (!commandPowered) {
              commandTargetBlock = block;
            } else {
              backupBlock = block;
              BlockFace powerFace = findPowerLocation(block, powerSimMaterial);
              if (powerFace != null) {
                commandTargetBlock = block;
              }
            }
          }
        }

        // If we didn't find any powerable blocks, but we did find at least one valid sim block
        // just use that one.
        if (commandTargetBlock == null) commandTargetBlock = backupBlock;

        // Search for a power block
        if (commandTargetBlock != null) {
          // First try and replace a live cell
          BlockFace powerDirection = findPowerLocation(commandTargetBlock, powerSimMaterial);
          // Next try to replace a dead cell, which will affect the simulation outcome
          // but this is perhaps better than it dying?
          if (powerDirection == null) {
            if (DEBUG) {
              controller
                  .getLogger()
                  .info("Had to fall back to backup location, pattern may diverge");
            }
            powerDirection = findPowerLocation(commandTargetBlock, powerSimMaterialBackup);
          }
          // If it's *still* not valid, search for something breakable.
          if (powerDirection == null) {
            for (BlockFace face : POWER_FACES) {
              if (blockSpell.isDestructible(commandTargetBlock.getRelative(face))) {
                if (DEBUG) {
                  controller
                      .getLogger()
                      .info(
                          "Had to fall back to destructible location, pattern may diverge and may destroy blocks");
                }
                powerDirection = face;
                break;
              }
            }
          }

          if (powerDirection != null) {
            powerTargetBlock = commandTargetBlock.getRelative(powerDirection);
          }
        }
      }
      if (DEBUG) {
        if (commandTargetBlock != null) {
          controller
              .getLogger()
              .info(
                  "MOVED: "
                      + commandTargetBlock.getLocation().toVector().subtract(center.toVector()));
        }
      }
      state = SimulationState.COMMON_RESET_REDSTONE;
      return processedBlocks;
    }

    if (state == SimulationState.COMMON_RESET_REDSTONE) {
      if (includeCommands && commandTargetBlock != null) {
        DeprecatedUtils.setData(commandTargetBlock, (byte) 0);
      }
      if (includeCommands && powerTargetBlock != null) {
        DeprecatedUtils.setData(powerTargetBlock, (byte) 0);
      }
      state = SimulationState.COMMAND_UPDATE;
      return processedBlocks;
    }

    if (state == SimulationState.COMMAND_UPDATE) {
      if (includeCommands) {
        if (commandTargetBlock != null) {
          if (!commandTargetBlock.getChunk().isLoaded()) {
            commandTargetBlock.getChunk().load();
            return processedBlocks;
          }

          commandTargetBlock.setType(Material.COMMAND);
          BlockState commandData = commandTargetBlock.getState();
          if (castCommand != null && commandData != null && commandData instanceof CommandBlock) {
            CommandBlock copyCommand = (CommandBlock) commandData;
            copyCommand.setCommand(castCommand);
            copyCommand.setName(commandName);
            copyCommand.update();

            // Also move the mage
            Location newLocation = commandTargetBlock.getLocation();
            newLocation.setPitch(center.getPitch());
            newLocation.setYaw(center.getYaw());
            mage.setLocation(newLocation);
          } else {
            commandTargetBlock = null;
          }
        } else {
          die();
        }
      }
      powerDelayTicks = POWER_DELAY_TICKS;
      state = SimulationState.COMMAND_POWER;
      return processedBlocks;
    }

    if (state == SimulationState.COMMAND_POWER) {
      // Continue to power the command block
      if (commandPowered && powerTargetBlock != null && includeCommands) {
        // Wait a bit before powering for redstone signals to reset
        if (powerDelayTicks > 0) {
          powerDelayTicks--;
          return processedBlocks;
        }

        if (powerTargetBlock != null) {
          powerTargetBlock.setType(POWER_MATERIAL);
          if (commandReload) {
            String automataName = commandName;
            if (automataName == null || automataName.length() <= 1) {
              automataName = controller.getMessages().get("automata.default_name");
            }
            controller.registerAutomata(powerTargetBlock, automataName, "automata.awaken");
          }
        }
      }
      state = SimulationState.FINISHED;
      return processedBlocks;
    }

    if (state == SimulationState.FINISHED) {
      finish();
    }

    return processedBlocks;
  }
示例#16
0
  /**
   * Teleports the passed in Entity through the portal.
   *
   * <p>Given an Entity object, attempts to teleport them through the portal. This involves many
   * steps. 1) Verify the portal on the other end still exists. If it doesn't, mark this as such. 2)
   * If there is no counterpart, figure out where it would be, and get it. This may involve
   * generating and placing a portal into the world. 3) Assuming we now have a counterpart, figure
   * out where to teleport the entity to. 3a) Figure out the entity's position relative to the entry
   * portal. 3b) Translate this to a position relative to the exit portal. 3c) Preserve the entity's
   * camera's orientation relative to the portal. 4) Teleport the entity. 4a) If the entity is a
   * Player in a vehicle, we do a dance. - Raise the destination by 1 (vehicles have to 'fall' into
   * the portal to avoid losing momentum, so they should be one higher). - Make the player leave the
   * vehicle. - Spawn a new minecart at the destination. - Teleport the player to the destination. -
   * Make the player a passenger of the minecart. - Give the new minecart the (properly translated)
   * velocity of the old vehicle. - Remove the old vehicle.
   *
   * @param e The entity to teleport.
   * @return The location the entity was teleported to, or null if the entity was not teleported.
   */
  public Location teleport(Entity e, Location interaction) {
    if (this.counterpart != null) {
      if (!this.counterpart.isValid()) {
        PortalUtil.removePortal(this.counterpart);
        this.counterpart = null;
        PortalUtil.getCounterpartPortalFor(this);
      } else {
        BlockData bd = this.getWorldBlockType();
        if (bd != null
            && !bd.m.equals(Material.AIR)
            && !bd.m.equals(Material.OBSIDIAN)
            && !this.counterpart
                .getKeyBlock()
                .getWorld()
                .equals(PortalUtil.getDestWorldFor(this))) {

          // Did my keyblock change, and if so, change my destination.
          this.counterpart = null;
          PortalUtil.getCounterpartPortalFor(this);
        }
      }
    } else {
      PortalUtil.getCounterpartPortalFor(this);
    }

    if (this.counterpart == null) {
      // Could not establish a link, for whatever reason.
      return null;
    }

    double destX, destY, destZ;
    float destPitch, destYaw;
    int rotateVehicleVelocity = 0;

    Vector offset = interaction.toVector().subtract(this.keyBlock.getLocation().toVector());

    Vector finalOffset;

    if (this.facingNorth) {
      if (offset.getX() < .5) {
        // Player moving south.
        offset.setX(offset.getX() + OFFSET);
      } else {
        // Player moving north.
        offset.setX(offset.getX() - OFFSET);
      }

      if (this.counterpart.isFacingNorth()) {
        destYaw = e.getLocation().getYaw();
        finalOffset = offset;
      } else {
        destYaw = e.getLocation().getYaw() - 90;
        finalOffset = new Vector(offset.getZ(), offset.getY(), -offset.getX() + OFFSET);
        rotateVehicleVelocity = 1;
      }
    } else {
      if (offset.getZ() < .5) {
        // Player moving west
        offset.setZ(offset.getZ() + OFFSET);
      } else {
        // Player moving east.
        offset.setZ(offset.getZ() - OFFSET);
      }
      if (this.counterpart.isFacingNorth()) {
        destYaw = e.getLocation().getYaw() + 90;
        finalOffset = new Vector(-offset.getZ() + OFFSET, offset.getY(), offset.getX());
        rotateVehicleVelocity = 2;
      } else {
        destYaw = e.getLocation().getYaw();
        finalOffset = offset;
      }
    }

    World destWorld = this.counterpart.getKeyBlock().getWorld();
    String permission = "nethrar.block." + destWorld.getName();

    if ((Nethrar.getPlugin().shouldUsePermissions())
        && ((e instanceof Player))
        && (((Player) e).hasPermission(permission))
        && !((Player) e).isOp()) {
      return null;
    }

    destX = this.counterpart.getKeyBlock().getX() + finalOffset.getX();
    destY = this.counterpart.getKeyBlock().getY() + finalOffset.getY();
    destZ = this.counterpart.getKeyBlock().getZ() + finalOffset.getZ();

    destPitch = e.getLocation().getPitch();

    // Jitter the location just a bit so the resulting minecart doesn't
    // end up underground, if there is a minecart being teleported.
    if ((e instanceof Player && ((Player) e).isInsideVehicle())
        || (e instanceof Vehicle && !(e instanceof Pig))) {
      // +.11 is necessary to get a minecart to spawn on top of, instead
      // of inside, rails on the same level on the other side. However,
      // if there are *not* rails on the other side, then the minecart
      // will fall into the block underneath, unless a +1 is added.
      destY += 1.0;
    }

    Location dest;
    dest = new Location(destWorld, destX, destY, destZ, destYaw, destPitch);

    // Bug: Player camera orientation not preserved when teleporting
    // in a vehicle. Probably because vehicle takes over player
    // camera.
    Vehicle oldV = null, newV = null;
    if (e instanceof Player) {
      if (((Player) e).isInsideVehicle()) {
        oldV = (Vehicle) ((Player) e).getVehicle();
        ((Player) e).leaveVehicle();
      }
    } else if (e instanceof StorageMinecart || e instanceof Minecart || e instanceof Boat) {

      oldV = ((Vehicle) e);
    }

    if (oldV != null) {
      if (oldV instanceof StorageMinecart) {
        newV = destWorld.spawn(dest, StorageMinecart.class);
        ((StorageMinecart) newV)
            .getInventory()
            .setContents(((StorageMinecart) oldV).getInventory().getContents());
      } else if (oldV instanceof Minecart) {
        newV = destWorld.spawn(dest, Minecart.class);
      } else if (oldV instanceof Boat) {
        newV = destWorld.spawn(dest, Boat.class);
      } else {
        log.warning("[NETHRAR] Unsupported vehicle hit a portal.");
      }

      Vector oldVelocity = oldV.getVelocity();
      Vector newVelocity;
      switch (rotateVehicleVelocity) {
          // Left-handed system - clockwise is positive.
        case 1:
          // In a north-facing portal, out a west-facing portal.
          // Rotate 90 degrees counterclockwise.
          newVelocity = new Vector(oldVelocity.getZ(), oldVelocity.getY(), oldVelocity.getX() * -1);
          break;
        case 2:
          // In a west-facing portal, out a north-facing portal.
          // Rotate 90 degrees clockwise.
          newVelocity = new Vector(oldVelocity.getZ() * -1, oldVelocity.getY(), oldVelocity.getX());
          break;
        default:
          newVelocity = oldVelocity;
          break;
      }

      PortalUtil.markTeleported(e);
      Bukkit.getServer()
          .getScheduler()
          .scheduleSyncDelayedTask(
              PortalUtil.getPlugin(), new NethrarTeleporter(e, dest, newV, newVelocity, oldV));
    } else {
      PortalUtil.markTeleported(e);
      // Regular player teleportation doesn't need to be delayed.
      NethrarTeleporter tp = new NethrarTeleporter(e, dest);
      tp.run();
    }
    return null;
  }
示例#17
0
  @EventHandler
  public void onGrapple(PlayerFishEvent event)
      throws NoSuchFieldException, SecurityException, IllegalArgumentException,
          IllegalAccessException {

    final Player player = event.getPlayer();

    // if (isIn(player, 37))
    {
      if (event.getState() == State.IN_GROUND) {

        if (hooks.containsKey(player.getName())) {

          final Location location =
              hooks
                  .get(player.getName())
                  .getLocation(); // hooks.get(player.getName()).getLocation().getBlock().getRelative(BlockFace.DOWN).getType() != Material.AIR ? hooks.get(player.getName()).getLocation() : hooks.get(player.getName()).getLocation().getBlock().getRelative(BlockFace.UP).getLocation();

          if (location.getBlock().getType() == Material.AIR
              || location.getBlock().getType() == Material.SNOW) {

            // player.setVelocity(hooks.get(player.getName()).getLocation().toVector().subtract(player.getLocation().subtract(0, 1, 0).toVector()).normalize().multiply(new Vector(2, 2, 2)));
            // Projectile fishing = player.launchProjectile(Snowball.class);
            final Vector velocity =
                location
                    .toVector()
                    .subtract(player.getLocation().subtract(0, 1, 0).toVector())
                    .normalize()
                    .multiply(new Vector(2, 2, 2));

            if (Math.abs(location.getBlockY() - player.getLocation().getBlockY()) < 2
                && location.distance(player.getLocation()) > 4) {

              player.setVelocity(velocity.multiply(new Vector(1, 1, 1)));

              Bukkit.getServer()
                  .getScheduler()
                  .scheduleSyncDelayedTask(
                      Plugin.getPlugin(),
                      new Runnable() {

                        @Override
                        public void run() {
                          player.setVelocity(velocity.multiply(new Vector(1, 1, 1)));
                          // player.setVelocity(location.toVector().subtract(player.getLocation().subtract(0, 1, 0).toVector().normalize().multiply(2)));

                        }
                      },
                      1L);

            } else {

              player.setVelocity(velocity);

              Bukkit.getServer()
                  .getScheduler()
                  .scheduleSyncDelayedTask(
                      Plugin.getPlugin(),
                      new Runnable() {

                        @Override
                        public void run() {
                          player.setVelocity(velocity.multiply(new Vector(1, 1, 1)));
                          // player.setVelocity(location.toVector().subtract(player.getLocation().subtract(0, 1, 0).toVector().normalize().multiply(0.5)));

                        }
                      },
                      0L);
            }
            // fishing.setPassenger(player);
            // projectiles.add(fishing);
          }
        }
      }
    }
  }
示例#18
0
 @SuppressWarnings("unchecked")
 public void readSphereList(File filename, Server server) {
   // Read from disk using FileInputStream
   try {
     thisspheres.clear();
     FileInputStream f_in;
     f_in = new FileInputStream(filename);
     // Read object using ObjectInputStream
     ObjectInputStream obj_in = new ObjectInputStream(f_in);
     // Read an object
     Object obj = obj_in.readObject();
     if (obj instanceof List<?>) {
       thisspheres = (List<Sphere>) obj;
     }
     for (Sphere s : thisspheres) {
       s.setV(new Vector(s.getX(), s.getY(), s.getZ()));
     }
   } catch (Exception e) {
     System.out.print("First run. Let's generate the spheres.");
     thisspheres.clear();
     // Now test if we make a new
     {
       try {
         /*Sphere ns = new Sphere();
         ns.setSize(SphereWorldConfig.maxradius);
         // set the Spawn.
                        Move this to post world generation?
         server.getWorld(SphereWorldConfig.world).loadChunk(0,0);
         server.getWorld(SphereWorldConfig.world).setSpawnLocation(0,server.getWorld(SphereWorldConfig.world).getHighestBlockYAt(0,0),0);
         ns.setV(server.getWorld(SphereWorldConfig.world).getSpawnLocation().toVector());
         ns.setWorld(SphereWorldConfig.world);
         ns.setX(server.getWorld(SphereWorldConfig.world).getSpawnLocation().getX());
         ns.setY(server.getWorld(SphereWorldConfig.world).getSpawnLocation().getY());
         ns.setZ(server.getWorld(SphereWorldConfig.world).getSpawnLocation().getZ());
         System.out.println("Spawnlocation on world is:"+
          " x"+server.getWorld(SphereWorldConfig.world).getSpawnLocation().getX()+
          " y"+server.getWorld(SphereWorldConfig.world).getSpawnLocation().getY()+
          " z"+server.getWorld(SphereWorldConfig.world).getSpawnLocation().getZ());
                       */
         System.out.println("Creating new Spheres... First run");
         System.out.print("working.. please wait.. this may take several minutes");
         // thisspheres.add(ns);
       } catch (Exception e1) {
         // Well seems like world is not default world.. so we cannot
         // get spawnpoint.
         // System.out.print("World does not exist... This is not Good. Should not happen");
         return;
       }
     }
     // Add this for start
     for (int x = -SphereWorldConfig.worldsize; x < SphereWorldConfig.worldsize; x = x + 20) {
       for (int y = -SphereWorldConfig.worldsize; y < SphereWorldConfig.worldsize; y = y + 20) {
         Boolean makenew = true;
         Location loc =
             new Location(
                 null,
                 x + r.nextInt(20),
                 r.nextInt(SphereWorldConfig.maxheight - SphereWorldConfig.minheight)
                     + SphereWorldConfig.minheight,
                 y + r.nextInt(20));
         for (Sphere s : thisspheres) {
           if (s.getV().distance(loc.toVector()) < SphereWorldConfig.mindist) makenew = false;
         }
         if (r.nextInt(100) > SphereWorldConfig.spherechance) makenew = false;
         if (makenew) {
           // distance ok make sphere
           Sphere ns = new Sphere();
           ns.setSize(
               r.nextInt(SphereWorldConfig.maxradius - SphereWorldConfig.minradius)
                   + SphereWorldConfig.minradius);
           ns.setV(new Vector(loc.getX(), loc.getY(), loc.getZ()));
           ns.setWorld(SphereWorldConfig.world);
           ns.setX(loc.getX());
           ns.setY(loc.getY());
           ns.setZ(loc.getZ());
           thisspheres.add(ns);
           ns = null;
         }
       }
     }
     writeSphereList(filename);
   }
   System.out.println("Created / Loaded Spheres: " + thisspheres.size());
 }
示例#19
0
  public void onLive() {
    if (this.pet == null) {
      this.remove(false);
    }

    if (this.getPlayerOwner() == null
        || !this.getPlayerOwner().isOnline()
        || Bukkit.getPlayerExact(this.getPlayerOwner().getName()) == null) {
      EchoPet.getManager().removePet(this.getPet(), true);
      return;
    }

    if (((CraftPlayer) this.getPlayerOwner()).getHandle().isInvisible() != this.isInvisible()
        && !this.shouldVanish) {
      this.setInvisible(!this.isInvisible());
    }

    if (((CraftPlayer) this.getPlayerOwner()).getHandle().isSneaking() != this.isSneaking()) {
      this.setSneaking(!this.isSneaking());
    }

    if (((CraftPlayer) this.getPlayerOwner()).getHandle().isSprinting() != this.isSprinting()) {
      this.setSprinting(!this.isSprinting());
    }

    if (this.getPet().isHat()) {

      this.lastYaw =
          this.yaw =
              (this.getPet().getPetType() == PetType.ENDERDRAGON
                  ? this.getPlayerOwner().getLocation().getYaw() - 180
                  : this.getPlayerOwner().getLocation().getYaw());
    }

    if (this.particle == this.particleCounter) {
      this.particle = 0;
      this.particleCounter = this.random.nextInt(50);
    } else {
      this.particle++;
    }

    if (this.getPlayerOwner().isFlying()
        && EchoPet.getOptions().canFly(this.getPet().getPetType())) {
      Location petLoc = this.getLocation();
      Location ownerLoc = this.getPlayerOwner().getLocation();
      Vector v = ownerLoc.toVector().subtract(petLoc.toVector());

      double x = v.getX();
      double y = v.getY();
      double z = v.getZ();

      Vector vo = this.getPlayerOwner().getLocation().getDirection();
      if (vo.getX() > 0) {
        x -= 1.5;
      } else if (vo.getX() < 0) {
        x += 1.5;
      }
      if (vo.getZ() > 0) {
        z -= 1.5;
      } else if (vo.getZ() < 0) {
        z += 1.5;
      }

      this.setVelocity(new Vector(x, y, z).normalize().multiply(0.3F));
    }
  }
示例#20
0
 /**
  * Creates a new region from two locations.
  *
  * @param loc1 first location
  * @param loc2 second location
  */
 public Region(final Location loc1, final Location loc2) {
   this.v1 = new SerializableVector(loc1.toVector());
   this.v2 = new SerializableVector(loc2.toVector());
   this.w = loc1.getWorld();
   this.w_name = loc1.getWorld().getName();
 }
  @EventHandler(priority = EventPriority.HIGH)
  public void onPlayerInteract(PlayerInteractEvent event) {
    Player player = event.getPlayer();

    switch (event.getAction()) {
      case RIGHT_CLICK_AIR:
      case RIGHT_CLICK_BLOCK:
        {
          switch (event.getMaterial()) {
            case WATER_BUCKET:
              {
                if (!TotalFreedomMod.allowWaterPlace) {
                  player
                      .getInventory()
                      .setItem(
                          player.getInventory().getHeldItemSlot(),
                          new ItemStack(Material.COOKIE, 1));
                  player.sendMessage(ChatColor.GRAY + "Water buckets are currently disabled.");
                  event.setCancelled(true);
                }
                break;
              }
            case LAVA_BUCKET:
              {
                if (!TotalFreedomMod.allowLavaPlace) {
                  player
                      .getInventory()
                      .setItem(
                          player.getInventory().getHeldItemSlot(),
                          new ItemStack(Material.COOKIE, 1));
                  player.sendMessage(ChatColor.GRAY + "Lava buckets are currently disabled.");
                  event.setCancelled(true);
                }
                break;
              }
            case EXPLOSIVE_MINECART:
              {
                if (!TotalFreedomMod.allowTntMinecarts) {
                  player.getInventory().clear(player.getInventory().getHeldItemSlot());
                  player.sendMessage(ChatColor.GRAY + "TNT minecarts are currently disabled.");
                  event.setCancelled(true);
                }
                break;
              }
          }
          break;
        }
      case LEFT_CLICK_AIR:
      case LEFT_CLICK_BLOCK:
        {
          switch (event.getMaterial()) {
            case STICK:
              {
                TFM_PlayerData playerdata = TFM_PlayerData.getPlayerData(player);
                if (playerdata.mobThrowerEnabled()) {
                  Location player_pos = player.getLocation();
                  Vector direction = player_pos.getDirection().normalize();

                  LivingEntity rezzed_mob =
                      (LivingEntity)
                          player
                              .getWorld()
                              .spawnEntity(
                                  player_pos.add(direction.multiply(2.0)),
                                  playerdata.mobThrowerCreature());
                  rezzed_mob.setVelocity(direction.multiply(playerdata.mobThrowerSpeed()));
                  playerdata.enqueueMob(rezzed_mob);

                  event.setCancelled(true);
                }
                break;
              }
            case SULPHUR:
              {
                TFM_PlayerData playerdata = TFM_PlayerData.getPlayerData(player);
                if (playerdata.isMP44Armed()) {
                  if (playerdata.toggleMP44Firing()) {
                    playerdata.startArrowShooter(TotalFreedomMod.plugin);
                  } else {
                    playerdata.stopArrowShooter();
                  }

                  event.setCancelled(true);
                }
                break;
              }
            case BLAZE_ROD:
              {
                if (TotalFreedomMod.allowExplosions) {
                  if (TFM_SuperadminList.isSeniorAdmin(player, true)) {
                    Block target_block;

                    if (event.getAction().equals(Action.LEFT_CLICK_AIR)) {
                      target_block = player.getTargetBlock(null, 120);
                    } else {
                      target_block = event.getClickedBlock();
                    }

                    if (target_block != null) {
                      player.getWorld().createExplosion(target_block.getLocation(), 4F, true);
                      player.getWorld().strikeLightning(target_block.getLocation());
                    } else {
                      player.sendMessage("Can't resolve target block.");
                    }

                    event.setCancelled(true);
                  }
                }
                break;
              }
            case CARROT:
              {
                if (TotalFreedomMod.allowExplosions) {
                  if (TFM_SuperadminList.isSeniorAdmin(player, true)) {
                    Location player_location = player.getLocation().clone();

                    Vector player_pos = player_location.toVector().add(new Vector(0.0, 1.65, 0.0));
                    Vector player_dir = player_location.getDirection().normalize();

                    double distance = 150.0;
                    Block target_block = player.getTargetBlock(null, Math.round((float) distance));
                    if (target_block != null) {
                      distance = player_location.distance(target_block.getLocation());
                    }

                    final List<Block> affected = new ArrayList<Block>();

                    Block last_block = null;
                    for (double offset = 0.0; offset <= distance; offset += (distance / 25.0)) {
                      Block test_block =
                          player_pos
                              .clone()
                              .add(player_dir.clone().multiply(offset))
                              .toLocation(player.getWorld())
                              .getBlock();

                      if (!test_block.equals(last_block)) {
                        if (test_block.isEmpty()) {
                          affected.add(test_block);
                          test_block.setType(Material.TNT);
                        } else {
                          break;
                        }
                      }

                      last_block = test_block;
                    }

                    new BukkitRunnable() {
                      @Override
                      public void run() {
                        for (Block tnt_block : affected) {
                          TNTPrimed tnt_primed =
                              tnt_block.getWorld().spawn(tnt_block.getLocation(), TNTPrimed.class);
                          tnt_primed.setFuseTicks(5);
                          tnt_block.setType(Material.AIR);
                        }
                      }
                    }.runTaskLater(TotalFreedomMod.plugin, 30L);

                    event.setCancelled(true);
                  }
                }
                break;
              }
          }
          break;
        }
    }
  }
示例#22
0
  public void onLive() {
    if (this.pet == null) {
      this.remove(false);
      return;
    }

    if (this.getPlayerOwner() == null || !this.getPlayerOwner().isOnline()) {
      EchoPet.getManager().removePet(this.getPet(), true);
      return;
    }

    if (pet.isOwnerRiding() && this.passenger == null && !pet.isOwnerInMountingProcess()) {
      pet.ownerRidePet(false);
    }

    if (!forceInvisible
        && ((CraftPlayer) this.getPlayerOwner()).getHandle().isInvisible() != this.isInvisible()
        && !this.shouldVanish) {
      this.setInvisible(!this.isInvisible());
    }

    if (((CraftPlayer) this.getPlayerOwner()).getHandle().isSneaking() != this.isSneaking()) {
      this.setSneaking(!this.isSneaking());
    }

    if (((CraftPlayer) this.getPlayerOwner()).getHandle().isSprinting() != this.isSprinting()) {
      this.setSprinting(!this.isSprinting());
    }

    if (this.getPet().isHat()) {
      this.lastYaw =
          this.yaw =
              (this.getPet().getPetType() == PetType.ENDERDRAGON
                  ? this.getPlayerOwner().getLocation().getYaw() - 180
                  : this.getPlayerOwner().getLocation().getYaw());
    }

    if (this.getPlayerOwner().isFlying()
        && EchoPet.getOptions().canFly(this.getPet().getPetType())) {
      Location petLoc = this.getLocation();
      Location ownerLoc = this.getPlayerOwner().getLocation();
      Vector v = ownerLoc.toVector().subtract(petLoc.toVector());

      double x = v.getX();
      double y = v.getY();
      double z = v.getZ();

      Vector vo = this.getPlayerOwner().getLocation().getDirection();
      if (vo.getX() > 0) {
        x -= 1.5;
      } else if (vo.getX() < 0) {
        x += 1.5;
      }
      if (vo.getZ() > 0) {
        z -= 1.5;
      } else if (vo.getZ() < 0) {
        z += 1.5;
      }

      this.setVelocity(new Vector(x, y, z).normalize().multiply(0.3F));
    }
  }
示例#23
0
 public boolean contains(Location location) {
   return contains(location.toVector());
 }
示例#24
0
  private boolean circleLineCollide(
      Location startLoc, Location endLoc, Location circleLoc, double radiusSquared) {
    Location lineStart = startLoc.clone();
    Location lineEnd = endLoc.clone();
    Location circleCenter = circleLoc.clone();

    Vector direction = vectorFromLocations(lineStart, lineEnd);

    if (direction.getZ() == 0) {
      if (direction.getBlockX() == 0) {
        return false;
      }
      flipXZ(lineStart);
      flipXZ(lineEnd);
      flipXZ(circleCenter);
      flipXZ(direction);
    }

    Vector start = lineStart.toVector();
    Vector end = lineEnd.toVector();

    Vector circle = circleCenter.toVector();

    double slope = direction.getZ() / direction.getX();
    double perpSlope = -1 / slope;

    // This is the closest x if this line segment was extended for ever
    double closestX =
        (slope * start.getX() - perpSlope * circle.getX() + circle.getBlockZ() - start.getZ())
            / (slope - perpSlope);

    // Getting the Z from the x is easy
    double closestZ = slope * (closestX - start.getX()) + start.getZ();

    Vector closest = new Vector(closestX, 0, closestZ);

    double distanceSquared = closest.clone().subtract(circle).lengthSquared();

    if (distanceSquared > radiusSquared) {
      return false;
    }

    if (((closest.getX() > lineStart.getX() && closest.getX() > lineEnd.getX())
            || (closest.getZ() > lineStart.getZ() && closest.getZ() > lineEnd.getZ()))
        || ((closest.getX() < lineStart.getX() && closest.getX() < lineEnd.getX())
            || (closest.getZ() < lineStart.getZ() && closest.getZ() < lineEnd.getZ()))) {
      if (closest.clone().subtract(end).lengthSquared()
          < closest.clone().subtract(start).lengthSquared()) {
        closest = end;
      } else {
        closest = start;
      }
    }

    distanceSquared = closest.subtract(circle).lengthSquared();

    if (distanceSquared > radiusSquared) {
      return false;
    }

    return true;
  }
  @EventHandler(priority = EventPriority.HIGH)
  public void onPlayerInteract(PlayerInteractEvent event) {
    final Player player = event.getPlayer();
    final TFM_PlayerData playerdata = TFM_PlayerData.getPlayerData(player);

    switch (event.getAction()) {
      case RIGHT_CLICK_AIR:
      case RIGHT_CLICK_BLOCK:
        {
          switch (event.getMaterial()) {
            case WATER_BUCKET:
              {
                if (TFM_AdminList.isSuperAdmin(player)
                    || TFM_ConfigEntry.ALLOW_WATER_PLACE.getBoolean()) {
                  break;
                }

                player
                    .getInventory()
                    .setItem(
                        player.getInventory().getHeldItemSlot(), new ItemStack(Material.COOKIE, 1));
                player.sendMessage(ChatColor.GRAY + "Water buckets are currently disabled.");
                event.setCancelled(true);
                break;
              }

            case LAVA_BUCKET:
              {
                if (TFM_AdminList.isSuperAdmin(player)
                    || TFM_ConfigEntry.ALLOW_LAVA_PLACE.getBoolean()) {
                  break;
                }

                player
                    .getInventory()
                    .setItem(
                        player.getInventory().getHeldItemSlot(), new ItemStack(Material.COOKIE, 1));
                player.sendMessage(ChatColor.GRAY + "Lava buckets are currently disabled.");
                event.setCancelled(true);
                break;
              }

            case EXPLOSIVE_MINECART:
              {
                if (TFM_ConfigEntry.ALLOW_TNT_MINECARTS.getBoolean()) {
                  break;
                }

                player.getInventory().clear(player.getInventory().getHeldItemSlot());
                player.sendMessage(ChatColor.GRAY + "TNT minecarts are currently disabled.");
                event.setCancelled(true);
                break;
              }
          }
          break;
        }

      case LEFT_CLICK_AIR:
      case LEFT_CLICK_BLOCK:
        {
          switch (event.getMaterial()) {
            case STICK:
              {
                if (!TFM_AdminList.isSuperAdmin(player)) {
                  break;
                }

                event.setCancelled(true);

                final Location location =
                    TFM_DepreciationAggregator.getTargetBlock(player, null, 5).getLocation();
                final List<RollbackEntry> entries =
                    TFM_RollbackManager.getEntriesAtLocation(location);

                if (entries.isEmpty()) {
                  TFM_Util.playerMsg(player, "No block edits at that location.");
                  break;
                }

                TFM_Util.playerMsg(
                    player,
                    "Block edits at ("
                        + ChatColor.WHITE
                        + "x"
                        + location.getBlockX()
                        + ", y"
                        + location.getBlockY()
                        + ", z"
                        + location.getBlockZ()
                        + ChatColor.BLUE
                        + ")"
                        + ChatColor.WHITE
                        + ":",
                    ChatColor.BLUE);
                for (RollbackEntry entry : entries) {
                  TFM_Util.playerMsg(
                      player,
                      " - "
                          + ChatColor.BLUE
                          + entry.author
                          + " "
                          + entry.getType()
                          + " "
                          + StringUtils.capitalize(entry.getMaterial().toString().toLowerCase())
                          + (entry.data == 0 ? "" : ":" + entry.data));
                }

                break;
              }

            case BONE:
              {
                if (!playerdata.mobThrowerEnabled()) {
                  break;
                }

                Location player_pos = player.getLocation();
                Vector direction = player_pos.getDirection().normalize();

                LivingEntity rezzed_mob =
                    (LivingEntity)
                        player
                            .getWorld()
                            .spawnEntity(
                                player_pos.add(direction.multiply(2.0)),
                                playerdata.mobThrowerCreature());
                rezzed_mob.setVelocity(direction.multiply(playerdata.mobThrowerSpeed()));
                playerdata.enqueueMob(rezzed_mob);

                event.setCancelled(true);
                break;
              }

            case SULPHUR:
              {
                if (!playerdata.isMP44Armed()) {
                  break;
                }

                event.setCancelled(true);

                if (playerdata.toggleMP44Firing()) {
                  playerdata.startArrowShooter(TotalFreedomMod.plugin);
                } else {
                  playerdata.stopArrowShooter();
                }
                break;
              }

            case BLAZE_ROD:
              {
                if (!TFM_ConfigEntry.ALLOW_EXPLOSIONS.getBoolean()) {
                  break;
                }

                if (!TFM_AdminList.isSeniorAdmin(player, true)) {
                  break;
                }

                event.setCancelled(true);
                Block targetBlock;

                if (event.getAction().equals(Action.LEFT_CLICK_AIR)) {
                  targetBlock = TFM_DepreciationAggregator.getTargetBlock(player, null, 120);
                } else {
                  targetBlock = event.getClickedBlock();
                }

                if (targetBlock == null) {
                  player.sendMessage("Can't resolve target block.");
                  break;
                }

                player.getWorld().createExplosion(targetBlock.getLocation(), 4F, true);
                player.getWorld().strikeLightning(targetBlock.getLocation());

                break;
              }

            case CARROT:
              {
                if (!TFM_ConfigEntry.ALLOW_EXPLOSIONS.getBoolean()) {
                  break;
                }

                if (!TFM_AdminList.isSeniorAdmin(player, true)) {
                  break;
                }

                Location location = player.getLocation().clone();

                Vector playerPostion = location.toVector().add(new Vector(0.0, 1.65, 0.0));
                Vector playerDirection = location.getDirection().normalize();

                double distance = 150.0;
                Block targetBlock =
                    TFM_DepreciationAggregator.getTargetBlock(
                        player, null, Math.round((float) distance));
                if (targetBlock != null) {
                  distance = location.distance(targetBlock.getLocation());
                }

                final List<Block> affected = new ArrayList<Block>();

                Block lastBlock = null;
                for (double offset = 0.0; offset <= distance; offset += (distance / 25.0)) {
                  Block block =
                      playerPostion
                          .clone()
                          .add(playerDirection.clone().multiply(offset))
                          .toLocation(player.getWorld())
                          .getBlock();

                  if (!block.equals(lastBlock)) {
                    if (block.isEmpty()) {
                      affected.add(block);
                      block.setType(Material.TNT);
                    } else {
                      break;
                    }
                  }

                  lastBlock = block;
                }

                new BukkitRunnable() {
                  @Override
                  public void run() {
                    for (Block tntBlock : affected) {
                      TNTPrimed tnt =
                          tntBlock.getWorld().spawn(tntBlock.getLocation(), TNTPrimed.class);
                      tnt.setFuseTicks(5);
                      tntBlock.setType(Material.AIR);
                    }
                  }
                }.runTaskLater(TotalFreedomMod.plugin, 30L);

                event.setCancelled(true);
                break;
              }

            case RAW_FISH:
              {
                final int RADIUS_HIT = 5;
                final int STRENGTH = 4;

                // Clownfish
                if (TFM_DepreciationAggregator.getData_MaterialData(event.getItem().getData())
                    == 2) {
                  if (TFM_AdminList.isSeniorAdmin(player, true)
                      || TFM_AdminList.isTelnetAdmin(player, true)) {
                    boolean didHit = false;

                    final Location playerLoc = player.getLocation();
                    final Vector playerLocVec = playerLoc.toVector();

                    final List<Player> players = player.getWorld().getPlayers();
                    for (final Player target : players) {
                      if (target == player) {
                        continue;
                      }

                      final Location targetPos = target.getLocation();
                      final Vector targetPosVec = targetPos.toVector();

                      try {
                        if (targetPosVec.distanceSquared(playerLocVec)
                            < (RADIUS_HIT * RADIUS_HIT)) {
                          TFM_Util.setFlying(player, false);
                          target.setVelocity(
                              targetPosVec.subtract(playerLocVec).normalize().multiply(STRENGTH));
                          didHit = true;
                        }
                      } catch (IllegalArgumentException ex) {
                      }
                    }

                    if (didHit) {
                      final Sound[] sounds = Sound.values();
                      for (Sound sound : sounds) {
                        if (sound.toString().contains("HIT")) {
                          playerLoc
                              .getWorld()
                              .playSound(
                                  randomOffset(playerLoc, 5.0),
                                  sound,
                                  100.0f,
                                  randomDoubleRange(0.5, 2.0).floatValue());
                        }
                      }
                    }
                  } else {
                    final StringBuilder msg = new StringBuilder();
                    final char[] chars = (player.getName() + " is a clown.").toCharArray();
                    for (char c : chars) {
                      msg.append(TFM_Util.randomChatColor()).append(c);
                    }
                    TFM_Util.bcastMsg(msg.toString());

                    player.getInventory().getItemInHand().setType(Material.POTATO_ITEM);
                  }

                  event.setCancelled(true);
                  break;
                }
              }
          }
          break;
        }
    }
  }
  @EventHandler(priority = EventPriority.HIGH)
  public void onPlayerInteract(PlayerInteractEvent event) {
    final Player player = event.getPlayer();
    final TFM_PlayerData playerdata = TFM_PlayerData.getPlayerData(player);

    switch (event.getAction()) {
      case RIGHT_CLICK_AIR:
      case RIGHT_CLICK_BLOCK:
        {
          switch (event.getMaterial()) {
            case WATER_BUCKET:
              {
                if (TFM_ConfigEntry.ALLOW_WATER_PLACE.getBoolean()) {
                  break;
                }

                player
                    .getInventory()
                    .setItem(
                        player.getInventory().getHeldItemSlot(), new ItemStack(Material.COOKIE, 1));
                player.sendMessage(ChatColor.GRAY + "Water buckets are currently disabled.");
                event.setCancelled(true);
                break;
              }

            case LAVA_BUCKET:
              {
                if (TFM_ConfigEntry.ALLOW_LAVA_PLACE.getBoolean()) {
                  break;
                }

                player
                    .getInventory()
                    .setItem(
                        player.getInventory().getHeldItemSlot(), new ItemStack(Material.COOKIE, 1));
                player.sendMessage(ChatColor.GRAY + "Lava buckets are currently disabled.");
                event.setCancelled(true);
                break;
              }

            case EXPLOSIVE_MINECART:
              {
                if (TFM_ConfigEntry.ALLOW_TNT_MINECARTS.getBoolean()) {
                  break;
                }

                player.getInventory().clear(player.getInventory().getHeldItemSlot());
                player.sendMessage(ChatColor.GRAY + "TNT minecarts are currently disabled.");
                event.setCancelled(true);
                break;
              }
          }
          break;
        }

      case LEFT_CLICK_AIR:
      case LEFT_CLICK_BLOCK:
        {
          switch (event.getMaterial()) {
            case STICK:
              {
                if (!TFM_AdminList.isSuperAdmin(player)) {
                  break;
                }

                event.setCancelled(true);

                final Location location = player.getTargetBlock(null, 5).getLocation();
                final List<RollbackEntry> entries =
                    TFM_RollbackManager.getEntriesAtLocation(location);

                if (entries.isEmpty()) {
                  TFM_Util.playerMsg(player, "No block edits at that location.");
                  break;
                }

                TFM_Util.playerMsg(
                    player,
                    "Block edits at ("
                        + ChatColor.WHITE
                        + "x"
                        + location.getBlockX()
                        + ", y"
                        + location.getBlockY()
                        + ", z"
                        + location.getBlockZ()
                        + ChatColor.BLUE
                        + ")"
                        + ChatColor.WHITE
                        + ":",
                    ChatColor.BLUE);
                for (RollbackEntry entry : entries) {
                  TFM_Util.playerMsg(
                      player,
                      " - "
                          + ChatColor.BLUE
                          + entry.author
                          + " "
                          + entry.getType()
                          + " "
                          + StringUtils.capitalize(entry.getMaterial().toString().toLowerCase())
                          + (entry.data == 0 ? "" : ":" + entry.data));
                }

                break;
              }

            case BONE:
              {
                if (!playerdata.mobThrowerEnabled()) {
                  break;
                }

                Location player_pos = player.getLocation();
                Vector direction = player_pos.getDirection().normalize();

                LivingEntity rezzed_mob =
                    (LivingEntity)
                        player
                            .getWorld()
                            .spawnEntity(
                                player_pos.add(direction.multiply(2.0)),
                                playerdata.mobThrowerCreature());
                rezzed_mob.setVelocity(direction.multiply(playerdata.mobThrowerSpeed()));
                playerdata.enqueueMob(rezzed_mob);

                event.setCancelled(true);
                break;
              }

            case SULPHUR:
              {
                if (!playerdata.isMP44Armed()) {
                  break;
                }

                event.setCancelled(true);

                if (playerdata.toggleMP44Firing()) {
                  playerdata.startArrowShooter(TotalFreedomMod.plugin);
                } else {
                  playerdata.stopArrowShooter();
                }
                break;
              }

            case BLAZE_ROD:
              {
                if (!TFM_ConfigEntry.ALLOW_EXPLOSIONS.getBoolean()) {
                  break;
                }

                if (!TFM_AdminList.isSeniorAdmin(player, true)) {
                  break;
                }

                event.setCancelled(true);
                Block targetBlock;

                if (event.getAction().equals(Action.LEFT_CLICK_AIR)) {
                  targetBlock = player.getTargetBlock(null, 120);
                } else {
                  targetBlock = event.getClickedBlock();
                }

                if (targetBlock == null) {
                  player.sendMessage("Can't resolve target block.");
                  break;
                }

                player.getWorld().createExplosion(targetBlock.getLocation(), 4F, true);
                player.getWorld().strikeLightning(targetBlock.getLocation());

                break;
              }

            case CARROT:
              {
                if (!TFM_ConfigEntry.ALLOW_EXPLOSIONS.getBoolean()) {
                  break;
                }

                if (!TFM_AdminList.isSeniorAdmin(player, true)) {
                  break;
                }

                Location location = player.getLocation().clone();

                Vector playerPostion = location.toVector().add(new Vector(0.0, 1.65, 0.0));
                Vector playerDirection = location.getDirection().normalize();

                double distance = 150.0;
                Block targetBlock = player.getTargetBlock(null, Math.round((float) distance));
                if (targetBlock != null) {
                  distance = location.distance(targetBlock.getLocation());
                }

                final List<Block> affected = new ArrayList<Block>();

                Block lastBlock = null;
                for (double offset = 0.0; offset <= distance; offset += (distance / 25.0)) {
                  Block block =
                      playerPostion
                          .clone()
                          .add(playerDirection.clone().multiply(offset))
                          .toLocation(player.getWorld())
                          .getBlock();

                  if (!block.equals(lastBlock)) {
                    if (block.isEmpty()) {
                      affected.add(block);
                      block.setType(Material.TNT);
                    } else {
                      break;
                    }
                  }

                  lastBlock = block;
                }

                new BukkitRunnable() {
                  @Override
                  public void run() {
                    for (Block tntBlock : affected) {
                      TNTPrimed tnt =
                          tntBlock.getWorld().spawn(tntBlock.getLocation(), TNTPrimed.class);
                      tnt.setFuseTicks(5);
                      tntBlock.setType(Material.AIR);
                    }
                  }
                }.runTaskLater(TotalFreedomMod.plugin, 30L);

                event.setCancelled(true);
                break;
              }
          }
          break;
        }
    }
  }