Java Code Examples for net.minecraft.util.math.BlockPos#subtract()

The following examples show how to use net.minecraft.util.math.BlockPos#subtract() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SchematicHelper.java    From ForgeHax with MIT License 6 votes vote down vote up
private static OptionalInt getColor(BlockPos pos, IBlockState heldBlock) {
  final Optional<Tuple<Schematic, BlockPos>> optSchematic = SchematicaHelper.getOpenSchematic();
  if (optSchematic.isPresent()) {
    final Schematic schematic = optSchematic.get().getFirst();
    final BlockPos schematicOffset = optSchematic.get().getSecond();
    final BlockPos schematicPos = pos.subtract(schematicOffset);
    
    if (schematic.inSchematic(schematicPos)) {
      final IBlockState schematicBlock = schematic.desiredState(schematicPos);
      
      return OptionalInt
          .of(schematicBlock.equals(heldBlock) ? Colors.GREEN.toBuffer() : Colors.RED.toBuffer());
    } else {
      return OptionalInt.empty();
    }
  } else {
    return OptionalInt.empty();
  }
}
 
Example 2
Source File: CapabilityCache.java    From CodeChickenLib with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Notifies {@link CapabilityCache} of a {@link Block#onNeighborChange} event.<br/>
 * Marks all empty capabilities provided by <code>from</code> block, to be re-cached
 * next query.
 *
 * @param from The from position.
 */
public void onNeighborChanged(BlockPos from) {
    if (world == null || pos == null) {
        return;
    }
    BlockPos offset = from.subtract(pos);
    int diff = MathHelper.absSum(offset);
    int side = MathHelper.toSide(offset);
    if (side < 0 || diff != 1) {
        return;
    }
    Direction sideChanged = Direction.BY_INDEX[side];

    Iterables.concat(selfCache.entrySet(), getCacheForSide(sideChanged).entrySet()).forEach(entry -> {
        Object2IntPair<LazyOptional<?>> pair = entry.getValue();
        if (pair.getKey() != null && !pair.getKey().isPresent()) {
            pair.setKey(null);
            pair.setValue(ticks);
        }
    });
}
 
Example 3
Source File: StructureLoader.java    From YUNoMakeGoodMap with Apache License 2.0 6 votes vote down vote up
@Override
public void generate(World world, BlockPos pos)
{
    PlacementSettings settings = new PlacementSettings();
    Template temp = null;
    String suffix = world.provider.getDimensionType().getSuffix();
    String opts = world.getWorldInfo().getGeneratorOptions() + suffix;

    if (!Strings.isNullOrEmpty(opts))
        temp = StructureUtil.loadTemplate(new ResourceLocation(opts), (WorldServer)world, true);
    if (temp == null)
        temp = StructureUtil.loadTemplate(new ResourceLocation("/config/", this.fileName + suffix), (WorldServer)world, !Strings.isNullOrEmpty(suffix));
    if (temp == null)
        return; //If we're not in the overworld, and we don't have a template...

    BlockPos spawn = StructureUtil.findSpawn(temp, settings);
    if (spawn != null)
    {
        pos = pos.subtract(spawn);
        world.setSpawnPoint(pos);
    }

    temp.addBlocksToWorld(world, pos, settings, 0); //Push to world, with no neighbor notifications!
    world.getPendingBlockUpdates(new StructureBoundingBox(pos, pos.add(temp.getSize())), true); //Remove block updates, so that sand doesn't fall!
}
 
Example 4
Source File: ByteBufUtils.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void writeRelativeBlockList(PacketBuffer buf, BlockPos origin, List<BlockPos> blockList) {
    buf.writeVarInt(blockList.size());
    for (BlockPos blockPos1 : blockList) {
        BlockPos blockPos = blockPos1.subtract(origin);
        buf.writeVarInt(blockPos.getX());
        buf.writeVarInt(blockPos.getY());
        buf.writeVarInt(blockPos.getZ());
    }
}
 
Example 5
Source File: TunnellerHack.java    From ForgeWurst with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void run()
{
	BlockPos player = new BlockPos(WMinecraft.getPlayer());
	KeyBinding forward = mc.gameSettings.keyBindForward;
	
	Vec3d diffVec = new Vec3d(player.subtract(start));
	Vec3d dirVec = new Vec3d(direction.getDirectionVec());
	double dotProduct = diffVec.dotProduct(dirVec);
	
	BlockPos pos1 = start.offset(direction, (int)dotProduct);
	if(!player.equals(pos1))
	{
		RotationUtils.faceVectorForWalking(toVec3d(pos1));
		KeyBindingUtils.setPressed(forward, true);
		return;
	}
	
	BlockPos pos2 = start.offset(direction, Math.max(0, length - 10));
	if(!player.equals(pos2))
	{
		RotationUtils.faceVectorForWalking(toVec3d(pos2));
		KeyBindingUtils.setPressed(forward, true);
		WMinecraft.getPlayer().setSprinting(true);
		return;
	}
	
	BlockPos pos3 = start.offset(direction, length + 1);
	RotationUtils.faceVectorForWalking(toVec3d(pos3));
	KeyBindingUtils.setPressed(forward, false);
	WMinecraft.getPlayer().setSprinting(false);
	
	if(disableTimer > 0)
	{
		disableTimer--;
		return;
	}
	
	setEnabled(false);
}
 
Example 6
Source File: AreaSelection.java    From litematica with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void moveEntireSelectionTo(BlockPos newOrigin, boolean printMessage)
{
    BlockPos old = this.getEffectiveOrigin();
    BlockPos diff = newOrigin.subtract(old);

    for (SelectionBox box : this.subRegionBoxes.values())
    {
        if (box.getPos1() != null)
        {
            this.setSubRegionCornerPos(box, Corner.CORNER_1, box.getPos1().add(diff));
        }

        if (box.getPos2() != null)
        {
            this.setSubRegionCornerPos(box, Corner.CORNER_2, box.getPos2().add(diff));
        }
    }

    if (this.getExplicitOrigin() != null)
    {
        this.setExplicitOrigin(newOrigin);
    }

    if (printMessage)
    {
        String oldStr = String.format("x: %d, y: %d, z: %d", old.getX(), old.getY(), old.getZ());
        String newStr = String.format("x: %d, y: %d, z: %d", newOrigin.getX(), newOrigin.getY(), newOrigin.getZ());
        InfoUtils.showGuiOrActionBarMessage(MessageType.SUCCESS, "litematica.message.moved_selection", oldStr, newStr);
    }
}
 
Example 7
Source File: PositionUtils.java    From litematica with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static BlockPos getPlacementPositionOffsetToInfrontOfPlayer(BlockPos newOrigin, @Nullable SchematicPlacement placement)
{
    if (Configs.Generic.PLACEMENTS_INFRONT.getBooleanValue())
    {
        Entity entity = EntityUtils.getCameraEntity();

        if (placement != null && entity != null)
        {
            SubRegionPlacement sub = placement.getSelectedSubRegionPlacement();
            Box box = null;

            if (sub != null)
            {
                String regionName = placement.getSelectedSubRegionName();
                ImmutableMap<String, SelectionBox> map = placement.getSubRegionBoxFor(regionName, RequiredEnabled.PLACEMENT_ENABLED);
                box = map.get(regionName);
            }
            else
            {
                box = placement.getEclosingBox();
            }

            if (box != null)
            {
                BlockPos originOffset = newOrigin.subtract(placement.getOrigin());
                BlockPos corner1 = box.getPos1().add(originOffset);
                BlockPos corner2 = box.getPos2().add(originOffset);
                BlockPos entityPos = new BlockPos(entity);
                EnumFacing entityFrontDirection = entity.getHorizontalFacing();
                EnumFacing entitySideDirection = fi.dy.masa.malilib.util.PositionUtils.getClosestSideDirection(entity);
                Vec3i alignmentFrontOffset = getOffsetToMoveBoxInfrontOfEntityPos(entityPos, entityFrontDirection, corner1, corner2);
                Vec3i alignmentSideOffset = getOffsetToMoveBoxInfrontOfEntityPos(entityPos, entitySideDirection, corner1, corner2);

                return newOrigin.add(alignmentFrontOffset).add(alignmentSideOffset);
            }
        }
    }

    return newOrigin;
}
 
Example 8
Source File: SingleRegionSchematic.java    From litematica with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected Vec3i getRegionOffset(ISchematicRegion region, BlockPos minCorner)
{
    // Get the offset from the region's block state container origin
    // (the minimum corner of the region) to the enclosing area's origin/minimum corner.
    BlockPos regionPos = region.getPosition();
    Vec3i endRel = PositionUtils.getRelativeEndPositionFromAreaSize(region.getSize());
    BlockPos regionEnd = regionPos.add(endRel);
    BlockPos regionMin = fi.dy.masa.malilib.util.PositionUtils.getMinCorner(regionPos, regionEnd);
    BlockPos regionOffset = regionMin.subtract(minCorner);

    return regionOffset;
}
 
Example 9
Source File: SchematicPlacement.java    From litematica with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Moves the sub-region to the given <b>absolute</b> position.
 * @param regionName
 * @param newPos
 */
void moveSubRegionTo(String regionName, BlockPos newPos)
{
    SubRegionPlacement subRegion = this.relativeSubRegionPlacements.get(regionName);

    if (subRegion != null)
    {
        // The input argument position is an absolute position, so need to convert to relative position here
        newPos = newPos.subtract(this.origin);
        // The absolute-based input position needs to be transformed if the entire placement has been rotated or mirrored
        newPos = PositionUtils.getReverseTransformedBlockPos(newPos, this.mirror, this.rotation);

        subRegion.setPos(newPos);
    }
}
 
Example 10
Source File: SchematicUtils.java    From litematica with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Nullable
private static BlockPos getReverseTransformedWorldPosition(BlockPos worldPos, ISchematic schematic,
        SchematicPlacement schematicPlacement, SubRegionPlacement regionPlacement, Vec3i regionSize)
{
    BlockPos origin = schematicPlacement.getOrigin();
    BlockPos regionPos = regionPlacement.getPos();

    // These are the untransformed relative positions
    BlockPos posEndRel = (new BlockPos(PositionUtils.getRelativeEndPositionFromAreaSize(regionSize))).add(regionPos);
    BlockPos posMinRel = fi.dy.masa.malilib.util.PositionUtils.getMinCorner(regionPos, posEndRel);

    // The transformed sub-region origin position
    BlockPos regionPosTransformed = PositionUtils.getTransformedBlockPos(regionPos, schematicPlacement.getMirror(), schematicPlacement.getRotation());

    // The relative offset of the affected region's corners, to the sub-region's origin corner
    BlockPos relPos = new BlockPos(worldPos.getX() - origin.getX() - regionPosTransformed.getX(),
                                   worldPos.getY() - origin.getY() - regionPosTransformed.getY(),
                                   worldPos.getZ() - origin.getZ() - regionPosTransformed.getZ());

    // Reverse transform that relative offset, to get the untransformed orientation's offsets
    relPos = PositionUtils.getReverseTransformedBlockPos(relPos, regionPlacement.getMirror(), regionPlacement.getRotation());

    relPos = PositionUtils.getReverseTransformedBlockPos(relPos, schematicPlacement.getMirror(), schematicPlacement.getRotation());

    // Get the offset relative to the sub-region's minimum corner, instead of the origin corner (which can be at any corner)
    relPos = relPos.subtract(posMinRel.subtract(regionPos));

    return relPos;
}
 
Example 11
Source File: Helper.java    From TFC2 with GNU General Public License v3.0 5 votes vote down vote up
/**
 * This is a 2d equation using X and Z coordinates
 */
public static BlockPos getPerpendicularPoint(BlockPos A, BlockPos B, float distance)
{
	BlockPos M = divide(A.add(B), 2);
	BlockPos p = A.subtract(B);
	BlockPos n = new BlockPos(-p.getZ(),p.getY(), p.getX());
	float norm_length = (float) Math.sqrt((n.getX() * n.getX()) + (n.getZ() * n.getZ()));
	n = divide(n, norm_length);
	return M.add(multiply(n, distance));
}
 
Example 12
Source File: TaskMoveArea.java    From enderutilities with GNU Lesser General Public License v3.0 5 votes vote down vote up
public TaskMoveArea(int dimension, BlockPos posSrcStart, BlockPos posSrcEnd, BlockPos posDstStart,
        Rotation rotationDst, Mirror mirrorDst, UUID wandUUID, int blocksPerTick)
{
    this.posSrcStart = posSrcStart;
    this.posDstStart = posDstStart;
    this.rotation = rotationDst;
    this.mirror = mirrorDst;
    this.wandUUID = wandUUID;
    this.dimension = dimension;
    this.blocksPerTick = blocksPerTick;
    this.boxRelative = new BlockPosBox(BlockPos.ORIGIN, posSrcEnd.subtract(posSrcStart));
    this.boxSource = new BlockPosBox(posSrcStart, posSrcEnd);
    this.handledPositions = new HashSet<BlockPos>();
}
 
Example 13
Source File: PumpkinHandler.java    From BetterChests with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public boolean handlePlant(IBetterChest chest, Collection<ItemStack> items, World world, BlockPos pos) {
	BlockPos diff = pos.subtract(chest.getPosition());
	if ((diff.getX() - diff.getZ()) % 2 == 0) {
		super.handlePlant(chest, Lists.newArrayList(items.stream().filter(this::matches).iterator()), world, pos);
		return true;
	}
	return false;
}
 
Example 14
Source File: ItemBuildersWand.java    From enderutilities with GNU Lesser General Public License v3.0 4 votes vote down vote up
private EnumActionResult stackArea(ItemStack stack, World world, EntityPlayer player, BlockPosEU pos1EU, BlockPosEU pos2EU)
{
    if (player.capabilities.isCreativeMode == false && Configs.buildersWandEnableStackMode == false)
    {
        player.sendStatusMessage(new TextComponentTranslation("enderutilities.chat.message.featuredisabledinsurvivalmode"), true);
        return EnumActionResult.FAIL;
    }

    if (pos1EU == null || pos2EU == null)
    {
        return EnumActionResult.FAIL;
    }

    int dim = world.provider.getDimension();
    BlockPos pos1 = pos1EU.toBlockPos();
    BlockPos pos2 = pos2EU.toBlockPos();
    BlockPos endPosRelative = pos2.subtract(pos1);
    Area3D area = Area3D.getAreaFromNBT(this.getAreaTag(stack));

    if (pos1EU.getDimension() != dim || pos2EU.getDimension() != dim ||
        this.isStackedAreaWithinLimits(pos1, pos2, endPosRelative, area, player) == false)
    {
        player.sendStatusMessage(new TextComponentTranslation("enderutilities.chat.message.areatoolargeortoofar"), true);
        return EnumActionResult.FAIL;
    }

    boolean takeEntities = player.capabilities.isCreativeMode && WandOption.AFFECT_ENTITIES.isEnabled(stack);
    PlacementSettings placement = new PlacementSettings();
    placement.setIgnoreEntities(takeEntities == false);
    ReplaceMode replaceMode = WandOption.REPLACE_EXISTING.isEnabled(stack, Mode.STACK) ? ReplaceMode.WITH_NON_AIR : ReplaceMode.NOTHING;
    TemplateEnderUtilities template = new TemplateEnderUtilities(placement, replaceMode);
    template.takeBlocksFromWorld(world, pos1, pos2.subtract(pos1), takeEntities, false);

    if (player.capabilities.isCreativeMode)
    {
        this.stackAreaImmediate(world, pos1, endPosRelative, area, template);
    }
    else
    {
        UUID wandUUID = NBTUtils.getUUIDFromItemStack(stack, WRAPPER_TAG_NAME, true);
        TaskStackArea task = new TaskStackArea(world, wandUUID, pos1, endPosRelative, template, area, Configs.buildersWandBlocksPerTick);
        PlayerTaskScheduler.getInstance().addTask(player, task, 1);
    }

    return EnumActionResult.SUCCESS;
}
 
Example 15
Source File: PlatformCommand.java    From YUNoMakeGoodMap with Apache License 2.0 4 votes vote down vote up
@Override
public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException
{
    if (args.length < 1)
        throw new WrongUsageException(getUsage(sender));

    String cmd = args[0].toLowerCase(Locale.ENGLISH);
    if ("list".equals(cmd))
    {
        sender.sendMessage(new TextComponentString("Known Platforms:"));
        for (ResourceLocation rl : getPlatforms())
        {
            sender.sendMessage(new TextComponentString("  " + rl.toString()));
        }
    }
    else if ("spawn".equals(cmd) || "preview".equals(cmd))
    {
        if (args.length < 2)
            throw new WrongUsageException(getUsage(sender));

        Entity ent = sender.getCommandSenderEntity();
        PlacementSettings settings = new PlacementSettings();
        WorldServer world = (WorldServer)sender.getEntityWorld();

        if (args.length >= 3)
        {
            //TODO: Preview doesnt quite work correctly with rotations....
            String rot = args[2].toLowerCase(Locale.ENGLISH);
            if ("0".equals(rot) || "none".equals(rot))
                settings.setRotation(Rotation.NONE);
            else if ("90".equals(rot))
                settings.setRotation(Rotation.CLOCKWISE_90);
            else if ("180".equals(rot))
                settings.setRotation(Rotation.CLOCKWISE_180);
            else if ("270".equals(rot))
                settings.setRotation(Rotation.COUNTERCLOCKWISE_90);
            else
                throw new WrongUsageException("Only rotations none, 0, 90, 180, and 270 allowed.");
        }

        BlockPos pos;
        if (args.length >= 6)
            pos = CommandBase.parseBlockPos(sender, args, 3, false);
        else if (ent != null)
            pos = ent.getPosition();
        else
            throw new WrongUsageException("Must specify a position if the command sender is not an entity");

        Template temp = StructureUtil.loadTemplate(new ResourceLocation(args[1]), world, true);

        BlockPos spawn = StructureUtil.findSpawn(temp, settings);
        if (spawn != null)
            pos = pos.subtract(spawn);

        if ("spawn".equals(cmd))
        {
            sender.sendMessage(new TextComponentString("Building \"" + args[1] +"\" at " + pos.toString()));
            temp.addBlocksToWorld(world, pos, settings, 2); //Push to world, with no neighbor notifications!
            world.getPendingBlockUpdates(new StructureBoundingBox(pos, pos.add(temp.getSize())), true); //Remove block updates, so that sand doesn't fall!
        }
        else
        {
            BlockPos tpos = pos.down();
            if (spawn != null)
                tpos = tpos.add(spawn);
            sender.sendMessage(new TextComponentString("Previewing \"" + args[1] +"\" at " + pos.toString()));
            world.setBlockState(tpos, Blocks.STRUCTURE_BLOCK.getDefaultState().withProperty(BlockStructure.MODE, TileEntityStructure.Mode.LOAD));
            TileEntityStructure te = (TileEntityStructure)world.getTileEntity(tpos);
            if (spawn != null)
                te.setPosition(te.getPosition().subtract(spawn));
            te.setSize(temp.getSize());
            te.setMode(Mode.LOAD);
            te.markDirty();
        }
    }
    else
        throw new WrongUsageException(getUsage(sender));
}