@Override
 public Vector getMaximumPoint() {
   return new Vector(
       Math.max(pos1.getX(), pos2.getX()),
       Math.max(pos1.getY(), pos2.getY()),
       Math.max(pos1.getZ(), pos2.getZ()));
 }
  /**
   * Set the minimum and maximum points of the bounding box for a region
   *
   * @param points the points to set with at least one entry
   */
  protected void setMinMaxPoints(List<Vector> points) {
    int minX = points.get(0).getBlockX();
    int minY = points.get(0).getBlockY();
    int minZ = points.get(0).getBlockZ();
    int maxX = minX;
    int maxY = minY;
    int maxZ = minZ;

    for (Vector v : points) {
      int x = v.getBlockX();
      int y = v.getBlockY();
      int z = v.getBlockZ();

      if (x < minX) minX = x;
      if (y < minY) minY = y;
      if (z < minZ) minZ = z;

      if (x > maxX) maxX = x;
      if (y > maxY) maxY = y;
      if (z > maxZ) maxZ = z;
    }

    setDirty(true);
    min = new BlockVector(minX, minY, minZ);
    max = new BlockVector(maxX, maxY, maxZ);
  }
Exemplo n.º 3
0
  @Command(
      aliases = {"/hsphere"},
      usage = "<block> <radius> [raised?] ",
      desc = "Generate a hollow sphere",
      min = 2,
      max = 3)
  @CommandPermissions({"worldedit.generation.sphere"})
  @Logging(PLACEMENT)
  public static void hsphere(
      CommandContext args,
      WorldEdit we,
      LocalSession session,
      LocalPlayer player,
      EditSession editSession)
      throws WorldEditException {

    Pattern block = we.getBlockPattern(player, args.getString(0));
    double radius = Math.max(1, args.getDouble(1));
    boolean raised =
        args.argsLength() > 2
            ? (args.getString(2).equalsIgnoreCase("true")
                || args.getString(2).equalsIgnoreCase("yes"))
            : false;

    Vector pos = session.getPlacementPosition(player);
    if (raised) {
      pos = pos.add(0, radius, 0);
    }

    int affected = editSession.makeSphere(pos, block, radius, false);
    player.findFreePosition();
    player.print(affected + " block(s) have been created.");
  }
Exemplo n.º 4
0
 public void forEachTileInChunk(int cx, int cz, RunnableVal2<Vector, BaseBlock> onEach) {
   int bx = cx << 4;
   int bz = cz << 4;
   Vector mutable = new Vector(0, 0, 0);
   for (int x = 0; x < 16; x++) {
     int xx = x + bx;
     for (int z = 0; z < 16; z++) {
       int zz = z + bz;
       for (int y = 0; y < getMaxY(); y++) {
         int combined = getCombinedId4Data(xx, y, zz);
         if (combined == 0) {
           continue;
         }
         int id = FaweCache.getId(combined);
         if (FaweCache.hasNBT(id)) {
           mutable.x = xx;
           mutable.z = zz;
           mutable.y = y;
           CompoundTag tile = getTileEntity(x, y, z);
           BaseBlock block = new BaseBlock(id, FaweCache.getData(combined), tile);
           onEach.run(mutable, block);
         }
       }
     }
   }
 }
Exemplo n.º 5
0
  @Command(
      aliases = {"/copy"},
      flags = "e",
      desc = "Копирует выделенную территорию в буфер обмена",
      help =
          "Копирует выделенную территорию в буфер обмен\n"
              + "Флаги:\n"
              + "  -e определяет, будут ли объекты копироваться в буфер обмена\n"
              + "ПРЕДУПРЕЖДЕНИЕ: Вставленные объекты не могут быть отменены!",
      min = 0,
      max = 0)
  @CommandPermissions("worldedit.clipboard.copy")
  public void copy(
      CommandContext args, LocalSession session, LocalPlayer player, EditSession editSession)
      throws WorldEditException {

    Region region = session.getSelection(player.getWorld());
    Vector min = region.getMinimumPoint();
    Vector max = region.getMaximumPoint();
    Vector pos = session.getPlacementPosition(player);

    CuboidClipboard clipboard =
        new CuboidClipboard(max.subtract(min).add(new Vector(1, 1, 1)), min, min.subtract(pos));
    clipboard.copy(editSession);
    if (args.hasFlag('e')) {
      for (LocalEntity entity : player.getWorld().getEntities(region)) {
        clipboard.storeEntity(entity);
      }
    }
    session.setClipboard(clipboard);

    player.print("Блок(и) скопирован(ы).");
  }
Exemplo n.º 6
0
 public CuboidRegionSelector(LocalWorld world, Vector pos1, Vector pos2) {
   this(world);
   this.pos1 = pos1.toBlockVector();
   this.pos2 = pos2.toBlockVector();
   region.setPos1(pos1);
   region.setPos2(pos2);
 }
  @Command(
      aliases = {"clipboard", "copy"},
      usage = "",
      desc = "Choose the clipboard brush",
      help =
          "Chooses the clipboard brush.\n"
              + "The -a flag makes it not paste air.\n"
              + "Without the -p flag, the paste will appear centered at the target location. "
              + "With the flag, then the paste will appear relative to where you had "
              + "stood relative to the copied area when you copied it.")
  @CommandPermissions("worldedit.brush.clipboard")
  public void clipboardBrush(
      Player player,
      LocalSession session,
      EditSession editSession,
      @Switch('a') boolean ignoreAir,
      @Switch('p') boolean usingOrigin)
      throws WorldEditException {
    ClipboardHolder holder = session.getClipboard();
    Clipboard clipboard = holder.getClipboard();

    Vector size = clipboard.getDimensions();

    worldEdit.checkMaxBrushRadius(size.getBlockX());
    worldEdit.checkMaxBrushRadius(size.getBlockY());
    worldEdit.checkMaxBrushRadius(size.getBlockZ());

    BrushTool tool = session.getBrushTool(player.getItemInHand());
    tool.setBrush(new ClipboardBrush(holder, ignoreAir, usingOrigin), "worldedit.brush.clipboard");

    player.print("Clipboard brush shape equipped.");
  }
  @Override
  public void shift(Vector change) throws RegionOperationException {
    pos1 = pos1.add(change);
    pos2 = pos2.add(change);

    recalculate();
  }
Exemplo n.º 9
0
  public boolean selectPrimary(Vector pos) {
    if (pos1 != null && (pos.compareTo(pos1) == 0)) {
      return false;
    }

    pos1 = pos.toBlockVector();
    region.setPos1(pos1);
    return true;
  }
Exemplo n.º 10
0
  public boolean selectSecondary(Vector pos) {
    if (pos2 != null && (pos.compareTo(pos2)) == 0) {
      return false;
    }

    pos2 = pos.toBlockVector();
    region.setPos2(pos2);
    return true;
  }
  /** Checks to see if a point is inside this region. */
  @Override
  public boolean contains(Vector pt) {
    int targetX = pt.getBlockX(); // wide
    int targetY = pt.getBlockY(); // height
    int targetZ = pt.getBlockZ(); // depth

    if (targetY < minY || targetY > maxY) {
      return false;
    }
    // Quick and dirty check.
    if (targetX < min.getBlockX()
        || targetX > max.getBlockX()
        || targetZ < min.getBlockZ()
        || targetZ > max.getBlockZ()) {
      return false;
    }
    boolean inside = false;
    int npoints = points.size();
    int xNew, zNew;
    int xOld, zOld;
    int x1, z1;
    int x2, z2;
    int i;

    xOld = points.get(npoints - 1).getBlockX();
    zOld = points.get(npoints - 1).getBlockZ();

    for (i = 0; i < npoints; i++) {
      xNew = points.get(i).getBlockX();
      zNew = points.get(i).getBlockZ();
      // Check for corner
      if (xNew == targetX && zNew == targetZ) {
        return true;
      }
      if (xNew > xOld) {
        x1 = xOld;
        x2 = xNew;
        z1 = zOld;
        z2 = zNew;
      } else {
        x1 = xNew;
        x2 = xOld;
        z1 = zNew;
        z2 = zOld;
      }
      if ((xNew < targetX) == (targetX <= xOld)
          && ((long) targetZ - (long) z1) * (long) (x2 - x1)
              <= ((long) z2 - (long) z1) * (long) (targetX - x1)) {
        inside = !inside;
      }
      xOld = xNew;
      zOld = zNew;
    }

    return inside;
  }
  @Command(
      aliases = {"/paste"},
      usage = "",
      flags = "sao",
      desc = "Paste the clipboard's contents",
      help =
          "Pastes the clipboard's contents.\n"
              + "Flags:\n"
              + "  -a skips air blocks\n"
              + "  -o pastes at the original position\n"
              + "  -s selects the region after pasting",
      min = 0,
      max = 0)
  @CommandPermissions("worldedit.clipboard.paste")
  @Logging(PLACEMENT)
  public void paste(
      Player player,
      LocalSession session,
      EditSession editSession,
      @Switch('a') boolean ignoreAirBlocks,
      @Switch('o') boolean atOrigin,
      @Switch('s') boolean selectPasted)
      throws WorldEditException {

    ClipboardHolder holder = session.getClipboard();
    Clipboard clipboard = holder.getClipboard();
    Region region = clipboard.getRegion();

    Vector to = atOrigin ? clipboard.getOrigin() : session.getPlacementPosition(player);
    Operation operation =
        holder
            .createPaste(editSession, editSession.getWorld().getWorldData())
            .to(to)
            .ignoreAirBlocks(ignoreAirBlocks)
            .build();
    Operations.completeLegacy(operation);

    if (selectPasted) {
      Vector clipboardOffset =
          clipboard.getRegion().getMinimumPoint().subtract(clipboard.getOrigin());
      Vector realTo = to.add(holder.getTransform().apply(clipboardOffset));
      Vector max =
          realTo.add(
              holder
                  .getTransform()
                  .apply(region.getMaximumPoint().subtract(region.getMinimumPoint())));
      RegionSelector selector = new CuboidRegionSelector(player.getWorld(), realTo, max);
      session.setRegionSelector(player.getWorld(), selector);
      selector.learnChanges();
      selector.explainRegionAdjust(player, session);
    }

    player.print("The clipboard has been pasted at " + to);
  }
Exemplo n.º 13
0
 /**
  * set block type & data
  *
  * @param pt
  * @param type
  * @param data
  * @return
  */
 @Override
 public boolean setTypeIdAndData(Vector pt, int type, int data) {
   int origType = getBlockType(pt), origData = getBlockData(pt);
   world.setBlockIdAndData(
       pt.getBlockX(),
       pt.getBlockY(),
       pt.getBlockZ(),
       (short) type,
       (short) data,
       WorldEditPlugin.getInstance());
   return origType != type && origData != data;
 }
Exemplo n.º 14
0
 @Override
 public void build(EditSession editSession, Vector position, Pattern pattern, double size)
     throws MaxChangedBlocksException {
   WorldVector min =
       new WorldVector(
           LocalWorldAdapter.adapt(editSession.getWorld()), position.subtract(size, size, size));
   Vector max = position.add(size, size + 10, size);
   Region region = new CuboidRegion(editSession.getWorld(), min, max);
   HeightMap heightMap = new HeightMap(editSession, region, naturalOnly);
   HeightMapFilter filter = new HeightMapFilter(new GaussianKernel(5, 1.0));
   heightMap.applyFilter(filter, iterations);
 }
  public boolean selectPrimary(Vector pos) {
    if (pos.equals(pos1)) {
      return false;
    }

    pos1 = pos.toBlockVector();
    region = new Polygonal2DRegion(region.getWorld());
    region.addPoint(pos);
    region.expandY(pos.getBlockY());

    return true;
  }
Exemplo n.º 16
0
  @Command(
      aliases = {"/deform"},
      usage = "<expression>",
      desc = "Deforms a selected region with an expression",
      help =
          "Deforms a selected region with an expression\n"
              + "The expression is executed for each block and is expected\n"
              + "to modify the variables x, y and z to point to a new block\n"
              + "to fetch. See also tinyurl.com/wesyntax.",
      flags = "ro",
      min = 1,
      max = -1)
  @CommandPermissions("worldedit.region.deform")
  @Logging(ALL)
  public void deform(
      Player player,
      LocalSession session,
      EditSession editSession,
      @Selection Region region,
      @Text String expression,
      @Switch('r') boolean useRawCoords,
      @Switch('o') boolean offset)
      throws WorldEditException {
    final Vector zero;
    Vector unit;

    if (useRawCoords) {
      zero = Vector.ZERO;
      unit = Vector.ONE;
    } else if (offset) {
      zero = session.getPlacementPosition(player);
      unit = Vector.ONE;
    } else {
      final Vector min = region.getMinimumPoint();
      final Vector max = region.getMaximumPoint();

      zero = max.add(min).multiply(0.5);
      unit = max.subtract(zero);

      if (unit.getX() == 0) unit = unit.setX(1.0);
      if (unit.getY() == 0) unit = unit.setY(1.0);
      if (unit.getZ() == 0) unit = unit.setZ(1.0);
    }

    try {
      final int affected = editSession.deformRegion(region, zero, unit, expression);
      player.findFreePosition();
      BBC.VISITOR_BLOCK.send(player, affected);
    } catch (ExpressionException e) {
      player.printError(e.getMessage());
    }
  }
Exemplo n.º 17
0
 public void setLobbySignsFromSelection(Player pl, int a) {
   FileConfiguration c = SettingsManager.getInstance().getSystemConfig();
   SettingsManager s = SettingsManager.getInstance();
   if (!c.getBoolean("walls-system.lobby.sign.set", false)) {
     c.set("walls-system.lobby.sign.set", true);
     s.saveSystemConfig();
   }
   WorldEditPlugin we = GameManager.getInstance().getWorldEdit();
   Selection sel = we.getSelection(pl);
   if (sel == null) {
     pl.sendMessage(ChatColor.RED + "You must make a WorldEdit Selection first");
     return;
   }
   if ((sel.getNativeMaximumPoint().getBlockX() - sel.getNativeMinimumPoint().getBlockX()) != 0
       && (sel.getNativeMinimumPoint().getBlockZ() - sel.getNativeMaximumPoint().getBlockZ()
           != 0)) {
     pl.sendMessage(ChatColor.RED + " Must be in a straight line!");
     return;
   }
   Vector max = sel.getNativeMaximumPoint();
   Vector min = sel.getNativeMinimumPoint();
   int i = c.getInt("walls-system.lobby.signno", 0) + 1;
   c.set("walls-system.lobby.signno", i);
   c.set("walls-system.lobby.signs." + i + ".id", a);
   c.set("walls-system.lobby.signs." + i + ".world", pl.getWorld().getName());
   c.set("walls-system.lobby.signs." + i + ".x1", max.getBlockX());
   c.set("walls-system.lobby.signs." + i + ".y1", max.getBlockY());
   c.set("walls-system.lobby.signs." + i + ".z1", max.getBlockZ());
   c.set("walls-system.lobby.signs." + i + ".x2", min.getBlockX());
   c.set("walls-system.lobby.signs." + i + ".y2", min.getBlockY());
   c.set("walls-system.lobby.signs." + i + ".z2", min.getBlockZ());
   pl.sendMessage(ChatColor.GREEN + "Added Lobby Wall"); // TODO
   s.saveSystemConfig();
   loadSign(i);
 }
Exemplo n.º 18
0
  @Command(
      aliases = {"/cut"},
      usage = "[leave-id]",
      desc = "Вырезает выделенную территорию в буфер обмена",
      help =
          "Вырезает выделенную территорию в буфер обмена\n"
              + "Флаги:\n"
              + "  -e controls определяет, будут ли объекты копироваться в буфер обмена\n"
              + "ПРЕДУПРЕЖДЕНИЕ: Вырезанные и вставленные объекты не могут быть отменены!",
      flags = "e",
      min = 0,
      max = 1)
  @CommandPermissions("worldedit.clipboard.cut")
  @Logging(REGION)
  public void cut(
      CommandContext args, LocalSession session, LocalPlayer player, EditSession editSession)
      throws WorldEditException {

    BaseBlock block = new BaseBlock(BlockID.AIR);
    LocalWorld world = player.getWorld();

    if (args.argsLength() > 0) {
      block = we.getBlock(player, args.getString(0));
    }

    Region region = session.getSelection(world);
    Vector min = region.getMinimumPoint();
    Vector max = region.getMaximumPoint();
    Vector pos = session.getPlacementPosition(player);

    CuboidClipboard clipboard =
        new CuboidClipboard(max.subtract(min).add(new Vector(1, 1, 1)), min, min.subtract(pos));
    clipboard.copy(editSession);
    if (args.hasFlag('e')) {
      LocalEntity[] entities = world.getEntities(region);
      for (LocalEntity entity : entities) {
        clipboard.storeEntity(entity);
      }
      world.killEntities(entities);
    }
    session.setClipboard(clipboard);

    int affected = editSession.setBlocks(session.getSelection(world), block);
    player.print(
        affected
            + " "
            + StringUtil.plural(affected, "блок вырезан", "блока вырезано", "блоков вырезано")
            + ".");
  }
Exemplo n.º 19
0
  @Command(
      aliases = {"/move"},
      usage = "[count] [direction] [leave-id]",
      flags = "s",
      desc = "Move the contents of the selection",
      min = 0,
      max = 3)
  @CommandPermissions("worldedit.region.move")
  @Logging(ORIENTATION_REGION)
  public static void move(
      CommandContext args,
      WorldEdit we,
      LocalSession session,
      LocalPlayer player,
      EditSession editSession)
      throws WorldEditException {

    int count = args.argsLength() > 0 ? Math.max(1, args.getInteger(0)) : 1;
    Vector dir =
        we.getDirection(player, args.argsLength() > 1 ? args.getString(1).toLowerCase() : "me");
    BaseBlock replace;

    // Replacement block argument
    if (args.argsLength() > 2) {
      replace = we.getBlock(player, args.getString(2));
    } else {
      replace = new BaseBlock(BlockID.AIR);
    }

    int affected =
        editSession.moveCuboidRegion(
            session.getSelection(player.getWorld()), dir, count, true, replace);

    if (args.hasFlag('s')) {
      try {
        Region region = session.getSelection(player.getWorld());
        region.expand(dir.multiply(count));
        region.contract(dir.multiply(count));

        session.getRegionSelector().learnChanges();
        session.getRegionSelector().explainRegionAdjust(player, session);
      } catch (RegionOperationException e) {
        player.printError(e.getMessage());
      }
    }

    player.print(affected + " blocks moved.");
  }
Exemplo n.º 20
0
 @Override
 public boolean equals(Object obj) {
   if (obj instanceof VectorWrapper) {
     obj = ((VectorWrapper) obj).getParent();
   }
   return m_parent.equals(obj);
 }
  public boolean selectSecondary(Vector pos) {
    if (region.size() > 0) {
      final List<BlockVector2D> points = region.getPoints();

      final BlockVector2D lastPoint = points.get(region.size() - 1);
      if (lastPoint.getBlockX() == pos.getBlockX() && lastPoint.getBlockZ() == pos.getBlockZ()) {
        return false;
      }

      if (maxPoints >= 0 && points.size() > maxPoints) {
        return false;
      }
    }

    region.addPoint(pos);
    region.expandY(pos.getBlockY());

    return true;
  }
Exemplo n.º 22
0
  @Command(
      aliases = {"/stack"},
      usage = "[count] [direction]",
      flags = "sa",
      desc = "Repeat the contents of the selection",
      help =
          "Repeats the contents of the selection.\n"
              + "Flags:\n"
              + "  -s shifts the selection to the last stacked copy\n"
              + "  -a skips air blocks",
      min = 0,
      max = 2)
  @CommandPermissions("worldedit.region.stack")
  @Logging(ORIENTATION_REGION)
  public void stack(
      Player player,
      EditSession editSession,
      LocalSession session,
      @Selection Region region,
      @Optional("1") @Range(min = 1) int count,
      @Optional(Direction.AIM) @Direction Vector direction,
      @Switch('s') boolean moveSelection,
      @Switch('a') boolean ignoreAirBlocks)
      throws WorldEditException {
    int affected = editSession.stackCuboidRegion(region, direction, count, !ignoreAirBlocks);

    if (moveSelection) {
      try {
        final Vector size = region.getMaximumPoint().subtract(region.getMinimumPoint());

        final Vector shiftVector = direction.multiply(count * (Math.abs(direction.dot(size)) + 1));
        region.shift(shiftVector);

        session.getRegionSelector(player.getWorld()).learnChanges();
        session.getRegionSelector(player.getWorld()).explainRegionAdjust(player, session);
      } catch (RegionOperationException e) {
        player.printError(e.getMessage());
      }
    }

    BBC.VISITOR_BLOCK.send(player, affected);
  }
Exemplo n.º 23
0
  @Command(
      aliases = {"/stack"},
      usage = "[count] [direction]",
      flags = "sa",
      desc = "Repeat the contents of the selection",
      min = 0,
      max = 2)
  @CommandPermissions("worldedit.region.stack")
  @Logging(ORIENTATION_REGION)
  public static void stack(
      CommandContext args,
      WorldEdit we,
      LocalSession session,
      LocalPlayer player,
      EditSession editSession)
      throws WorldEditException {

    int count = args.argsLength() > 0 ? Math.max(1, args.getInteger(0)) : 1;
    Vector dir =
        we.getDiagonalDirection(
            player, args.argsLength() > 1 ? args.getString(1).toLowerCase() : "me");

    int affected =
        editSession.stackCuboidRegion(
            session.getSelection(player.getWorld()), dir, count, !args.hasFlag('a'));

    if (args.hasFlag('s')) {
      try {
        Region region = session.getSelection(player.getWorld());
        region.expand(dir.multiply(count));
        region.contract(dir.multiply(count));

        session.getRegionSelector().learnChanges();
        session.getRegionSelector().explainRegionAdjust(player, session);
      } catch (RegionOperationException e) {
        player.printError(e.getMessage());
      }
    }

    player.print(affected + " blocks changed. Undo with //undo");
  }
Exemplo n.º 24
0
  public WorldEditSchematic(Object schematic) {
    weSchematic = (CuboidClipboard) schematic;

    // Center at the bottom X,Z center
    // This should be configurable, maybe?
    try {
      com.sk89q.worldedit.Vector weSize = weSchematic.getSize();
      size = new Vector(weSize.getBlockX(), weSize.getBlockY(), weSize.getBlockZ());
      center = new Vector(Math.floor(size.getBlockX() / 2), 0, Math.floor(size.getBlockZ() / 2));
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    if (center == null) {
      center = new Vector(0, 0, 0);
    }

    if (size == null) {
      size = new Vector(0, 0, 0);
    }
  }
 public ConstructionZoneNode add(CuboidRegion region, AccessType accessType) {
   Vector min = region.getMinimumPoint();
   Vector max = region.getMaximumPoint();
   Node n = graph.createNode(PlotNode.plotLabel(), ConstructionZoneNode.label());
   n.setProperty(ConstructionZoneNode.ID_PROPERTY, nextId());
   ConstructionZoneNode zone = new ConstructionZoneNode(n);
   zone.setAccessType(accessType);
   zone.setMinX(min.getBlockX());
   zone.setMinY(min.getBlockY());
   zone.setMinZ(min.getBlockZ());
   zone.setMaxX(max.getBlockX());
   zone.setMaxY(max.getBlockY());
   zone.setMaxZ(max.getBlockZ());
   return zone;
 }
Exemplo n.º 26
0
  /**
   * Find needed chunks in the axis-aligned bounding box of the region.
   *
   * @param region The {@link Region} to iterate
   */
  private void findNeededCuboidChunks(Region region) {
    Vector min = region.getMinimumPoint();
    Vector max = region.getMaximumPoint();

    // First, we need to group points by chunk so that we only need
    // to keep one chunk in memory at any given moment
    for (int x = min.getBlockX(); x <= max.getBlockX(); ++x) {
      for (int y = min.getBlockY(); y <= max.getBlockY(); ++y) {
        for (int z = min.getBlockZ(); z <= max.getBlockZ(); ++z) {
          Vector pos = new Vector(x, y, z);
          checkAndAddBlock(pos);
        }
      }
    }
  }
  /**
   * Transform NBT data in the given entity state and return a new instance if the NBT data needs to
   * be transformed.
   *
   * @param state the existing state
   * @return a new state or the existing one
   */
  private BaseEntity transformNbtData(BaseEntity state) {
    CompoundTag tag = state.getNbtData();

    if (tag != null) {
      // Handle hanging entities (paintings, item frames, etc.)
      boolean hasTilePosition =
          tag.containsKey("TileX") && tag.containsKey("TileY") && tag.containsKey("TileZ");
      boolean hasDirection = tag.containsKey("Direction");
      boolean hasLegacyDirection = tag.containsKey("Dir");
      boolean hasFacing = tag.containsKey("Facing");

      if (hasTilePosition) {
        Vector tilePosition =
            new Vector(tag.asInt("TileX"), tag.asInt("TileY"), tag.asInt("TileZ"));
        Vector newTilePosition = transform.apply(tilePosition.subtract(from)).add(to);

        CompoundTagBuilder builder =
            tag.createBuilder()
                .putInt("TileX", newTilePosition.getBlockX())
                .putInt("TileY", newTilePosition.getBlockY())
                .putInt("TileZ", newTilePosition.getBlockZ());

        if (hasDirection || hasLegacyDirection || hasFacing) {
          int d;
          if (hasDirection) {
            d = tag.asInt("Direction");
          } else if (hasLegacyDirection) {
            d = MCDirections.fromLegacyHanging((byte) tag.asInt("Dir"));
          } else {
            d = tag.asInt("Facing");
          }

          Direction direction = MCDirections.fromHanging(d);

          if (direction != null) {
            Vector vector =
                transform
                    .apply(direction.toVector())
                    .subtract(transform.apply(Vector.ZERO))
                    .normalize();
            Direction newDirection = Direction.findClosest(vector, Flag.CARDINAL);

            if (newDirection != null) {
              byte hangingByte = (byte) MCDirections.toHanging(newDirection);
              builder.putByte("Direction", hangingByte);
              builder.putByte("Facing", hangingByte);
              builder.putByte(
                  "Dir", MCDirections.toLegacyHanging(MCDirections.toHanging(newDirection)));
            }
          }
        }

        return new BaseEntity(state.getTypeId(), builder.build());
      }
    }

    return state;
  }
  @Command(
      aliases = {"/replacenear", "replacenear"},
      usage = "<size> <from-id> <to-id>",
      desc = "Replace nearby blocks",
      flags = "f",
      min = 3,
      max = 3)
  @CommandPermissions("worldedit.replacenear")
  @Logging(PLACEMENT)
  public void replaceNear(
      CommandContext args, LocalSession session, LocalPlayer player, EditSession editSession)
      throws WorldEditException {

    int size = Math.max(1, args.getInteger(0));
    int affected;
    Set<BaseBlock> from;
    Pattern to;
    if (args.argsLength() == 2) {
      from = null;
      to = we.getBlockPattern(player, args.getString(1));
    } else {
      from = we.getBlocks(player, args.getString(1), true, !args.hasFlag('f'));
      to = we.getBlockPattern(player, args.getString(2));
    }

    Vector base = session.getPlacementPosition(player);
    Vector min = base.subtract(size, size, size);
    Vector max = base.add(size, size, size);
    Region region = new CuboidRegion(player.getWorld(), min, max);

    if (to instanceof SingleBlockPattern) {
      affected = editSession.replaceBlocks(region, from, ((SingleBlockPattern) to).getBlock());
    } else {
      affected = editSession.replaceBlocks(region, from, to);
    }
    player.print(affected + " block(s) have been replaced.");
  }
  @Override
  public boolean apply(Entity entity) throws WorldEditException {
    BaseEntity state = entity.getState();
    if (state != null) {
      Location newLocation;
      Location location = entity.getLocation();

      Vector pivot = from.round().add(0.5, 0.5, 0.5);
      Vector newPosition = transform.apply(location.toVector().subtract(pivot));
      Vector newDirection;

      newDirection =
          transform.isIdentity()
              ? entity.getLocation().getDirection()
              : transform
                  .apply(location.getDirection())
                  .subtract(transform.apply(Vector.ZERO))
                  .normalize();
      newLocation =
          new Location(destination, newPosition.add(to.round().add(0.5, 0.5, 0.5)), newDirection);

      // Some entities store their position data in NBT
      state = transformNbtData(state);

      boolean success = destination.createEntity(newLocation, state) != null;

      // Remove
      if (isRemoving() && success) {
        entity.remove();
      }

      return success;
    } else {
      return false;
    }
  }
Exemplo n.º 30
0
 /**
  * Set block type.
  *
  * @param pt
  * @param type
  * @return
  */
 @Override
 public boolean setBlockType(Vector pt, int type) {
   world.setBlockId(
       pt.getBlockX(),
       pt.getBlockY(),
       pt.getBlockZ(),
       (short) type,
       WorldEditPlugin.getInstance());
   return world.getBlockId(pt.getBlockX(), pt.getBlockY(), pt.getBlockZ()) != type;
 }