net.minecraft.util.math.BlockPos#subtract ( )源码实例Demo

下面列出了net.minecraft.util.math.BlockPos#subtract ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: ForgeHax   文件: SchematicHelper.java
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();
  }
}
 
源代码2 项目: CodeChickenLib   文件: CapabilityCache.java
/**
 * 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);
        }
    });
}
 
源代码3 项目: YUNoMakeGoodMap   文件: StructureLoader.java
@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!
}
 
源代码4 项目: GregTech   文件: ByteBufUtils.java
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());
    }
}
 
源代码5 项目: ForgeWurst   文件: TunnellerHack.java
@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);
}
 
源代码6 项目: litematica   文件: AreaSelection.java
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);
    }
}
 
源代码7 项目: litematica   文件: PositionUtils.java
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;
}
 
源代码8 项目: litematica   文件: SingleRegionSchematic.java
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;
}
 
源代码9 项目: litematica   文件: SchematicPlacement.java
/**
 * 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);
    }
}
 
源代码10 项目: litematica   文件: SchematicUtils.java
@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;
}
 
源代码11 项目: TFC2   文件: Helper.java
/**
 * 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));
}
 
源代码12 项目: enderutilities   文件: TaskMoveArea.java
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>();
}
 
源代码13 项目: BetterChests   文件: PumpkinHandler.java
@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;
}
 
源代码14 项目: enderutilities   文件: ItemBuildersWand.java
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;
}
 
源代码15 项目: YUNoMakeGoodMap   文件: PlatformCommand.java
@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));
}