Mirgrated Common

This commit is contained in:
lucsoft
2021-05-29 19:16:17 +02:00
parent 51a92d81f4
commit 5ea1736dcb
80 changed files with 813 additions and 825 deletions

View File

@@ -52,7 +52,7 @@ public final class BusCableBlock extends Block {
INTERFACE;
@Override
public String getString() {
public String getSerializedName() {
switch (this) {
case NONE:
return "none";
@@ -87,7 +87,7 @@ public final class BusCableBlock extends Block {
public static ConnectionType getConnectionType(final BlockState state, @Nullable final Direction direction) {
if (direction != null) {
return state.get(BusCableBlock.FACING_TO_CONNECTION_MAP.get(direction));
return state.getValue(BusCableBlock.FACING_TO_CONNECTION_MAP.get(direction));
} else {
return ConnectionType.NONE;
}
@@ -96,7 +96,7 @@ public final class BusCableBlock extends Block {
public static int getInterfaceCount(final BlockState state) {
int partCount = 0;
for (final EnumProperty<ConnectionType> connectionType : FACING_TO_CONNECTION_MAP.values()) {
if (state.get(connectionType) == ConnectionType.INTERFACE) {
if (state.getValue(connectionType) == ConnectionType.INTERFACE) {
partCount++;
}
}
@@ -104,8 +104,8 @@ public final class BusCableBlock extends Block {
}
public static Direction getHitSide(final BlockPos pos, final BlockRayTraceResult hit) {
final Vector3d localHitPos = hit.getHitVec().subtract(Vector3d.copyCentered(pos));
return Direction.getFacingFromVector(localHitPos.x, localHitPos.y, localHitPos.z);
final Vector3d localHitPos = hit.getLocation().subtract(Vector3d.atCenterOf(pos));
return Direction.getNearest(localHitPos.x, localHitPos.y, localHitPos.z);
}
///////////////////////////////////////////////////////////////////
@@ -116,16 +116,16 @@ public final class BusCableBlock extends Block {
public BusCableBlock() {
super(Properties
.create(Material.IRON)
.of(Material.METAL)
.sound(SoundType.METAL)
.hardnessAndResistance(1.5f, 6.0f));
.strength(1.5f, 6.0f));
BlockState defaultState = getStateContainer().getBaseState();
BlockState defaultState = getStateDefinition().any();
for (final EnumProperty<ConnectionType> property : FACING_TO_CONNECTION_MAP.values()) {
defaultState = defaultState.with(property, ConnectionType.NONE);
defaultState = defaultState.setValue(property, ConnectionType.NONE);
}
defaultState = defaultState.with(HAS_CABLE, true);
setDefaultState(defaultState);
defaultState = defaultState.setValue(HAS_CABLE, true);
registerDefaultState(defaultState);
shapes = makeShapes();
}
@@ -134,11 +134,11 @@ public final class BusCableBlock extends Block {
public boolean addInterface(final World world, final BlockPos pos, final BlockState state, final Direction side) {
final EnumProperty<BusCableBlock.ConnectionType> property = FACING_TO_CONNECTION_MAP.get(side);
if (state.get(property) != ConnectionType.NONE) {
if (state.getValue(property) != ConnectionType.NONE) {
return false;
}
world.setBlockState(pos, state.with(property, ConnectionType.INTERFACE), BlockFlags.DEFAULT_AND_RERENDER);
world.setBlock(pos, state.setValue(property, ConnectionType.INTERFACE), BlockFlags.DEFAULT_AND_RERENDER);
onConnectionTypeChanged(world, pos, side);
@@ -146,11 +146,11 @@ public final class BusCableBlock extends Block {
}
public boolean addCable(final World world, final BlockPos pos, final BlockState state) {
if (state.get(HAS_CABLE)) {
if (state.getValue(HAS_CABLE)) {
return false;
}
world.setBlockState(pos, state.with(HAS_CABLE, true), BlockFlags.DEFAULT_AND_RERENDER);
world.setBlock(pos, state.setValue(HAS_CABLE, true), BlockFlags.DEFAULT_AND_RERENDER);
onConnectionTypeChanged(world, pos, null);
@@ -170,7 +170,7 @@ public final class BusCableBlock extends Block {
@SuppressWarnings("deprecation")
@Override
public void neighborChanged(final BlockState state, final World world, final BlockPos pos, final Block changedBlock, final BlockPos changedBlockPos, final boolean isMoving) {
final TileEntity tileEntity = world.getTileEntity(pos);
final TileEntity tileEntity = world.getBlockEntity(pos);
if (tileEntity instanceof BusCableTileEntity) {
final BusCableTileEntity busCable = (BusCableTileEntity) tileEntity;
busCable.handleNeighborChanged(changedBlockPos);
@@ -179,31 +179,31 @@ public final class BusCableBlock extends Block {
@SuppressWarnings("deprecation")
@Override
public ActionResultType onBlockActivated(final BlockState state, final World world, final BlockPos pos, final PlayerEntity player, final Hand hand, final BlockRayTraceResult hit) {
if (Wrenches.isWrench(player.getHeldItem(hand))) {
if (player.isSneaking()) {
public ActionResultType use(final BlockState state, final World world, final BlockPos pos, final PlayerEntity player, final Hand hand, final BlockRayTraceResult hit) {
if (Wrenches.isWrench(player.getItemInHand(hand))) {
if (player.isShiftKeyDown()) {
// NB: leave wrenching logic up to wrench when the to-be-removed interface is the last
// part of this bus. This ensures we properly remove the block itself without having
// to duplicate the logic needed for that.
if (getPartCount(state) > 1)
if (tryRemovePlug(state, world, pos, player, hit) || tryRemoveCable(state, world, pos, player)) {
return ActionResultType.func_233537_a_(world.isRemote());
return ActionResultType.sidedSuccess(world.isClientSide);
}
} else {
final TileEntity tileEntity = world.getTileEntity(pos);
final TileEntity tileEntity = world.getBlockEntity(pos);
if (tileEntity instanceof BusCableTileEntity) {
final BusCableTileEntity busCableTileEntity = (BusCableTileEntity) tileEntity;
final Direction side = getHitSide(pos, hit);
if (getConnectionType(state, side) == ConnectionType.INTERFACE) {
openBusInterfaceScreen(busCableTileEntity, side);
return ActionResultType.func_233537_a_(world.isRemote());
return ActionResultType.sidedSuccess(world.isClientSide);
}
}
}
}
return super.onBlockActivated(state, world, pos, player, hand, hit);
return super.use(state, world, pos, player, hand, hit);
}
@SuppressWarnings("deprecation")
@@ -211,13 +211,13 @@ public final class BusCableBlock extends Block {
public List<ItemStack> getDrops(final BlockState state, final LootContext.Builder builder) {
final List<ItemStack> drops = new ArrayList<>(super.getDrops(state, builder));
if (state.get(HAS_CABLE)) {
if (state.getValue(HAS_CABLE)) {
drops.add(new ItemStack(Items.BUS_CABLE.get()));
}
int interfaceCount = 0;
for (final Direction side : Constants.DIRECTIONS) {
final ConnectionType connectionType = state.get(FACING_TO_CONNECTION_MAP.get(side));
final ConnectionType connectionType = state.getValue(FACING_TO_CONNECTION_MAP.get(side));
if (connectionType == ConnectionType.INTERFACE) {
interfaceCount++;
}
@@ -232,16 +232,16 @@ public final class BusCableBlock extends Block {
@Override
public BlockState getStateForPlacement(final BlockItemUseContext context) {
BlockState state = getDefaultState();
BlockState state = defaultBlockState();
final World world = context.getWorld();
final BlockPos position = context.getPos();
final World world = context.getLevel();
final BlockPos position = context.getClickedPos();
for (final Map.Entry<Direction, EnumProperty<ConnectionType>> entry : FACING_TO_CONNECTION_MAP.entrySet()) {
final Direction facing = entry.getKey();
final BlockPos facingPos = position.offset(facing);
if (context.getItem().getItem() == Items.BUS_CABLE.get() &&
final BlockPos facingPos = position.relative(facing);
if (context.getItemInHand().getItem() == Items.BUS_CABLE.get() &&
canHaveCableTo(world.getBlockState(facingPos), facing.getOpposite())) {
state = state.with(entry.getValue(), ConnectionType.CABLE);
state = state.setValue(entry.getValue(), ConnectionType.CABLE);
}
}
@@ -250,15 +250,15 @@ public final class BusCableBlock extends Block {
@SuppressWarnings("deprecation")
@Override
public BlockState updatePostPlacement(BlockState state, final Direction facing, final BlockState facingState, final IWorld world, final BlockPos currentPos, final BlockPos facingPos) {
if (state.get(FACING_TO_CONNECTION_MAP.get(facing)) == ConnectionType.INTERFACE) {
public BlockState updateShape(BlockState state, final Direction facing, final BlockState facingState, final IWorld world, final BlockPos currentPos, final BlockPos facingPos) {
if (state.getValue(FACING_TO_CONNECTION_MAP.get(facing)) == ConnectionType.INTERFACE) {
return state;
}
if (state.get(HAS_CABLE) && canHaveCableTo(facingState, facing.getOpposite())) {
state = state.with(FACING_TO_CONNECTION_MAP.get(facing), ConnectionType.CABLE);
if (state.getValue(HAS_CABLE) && canHaveCableTo(facingState, facing.getOpposite())) {
state = state.setValue(FACING_TO_CONNECTION_MAP.get(facing), ConnectionType.CABLE);
} else {
state = state.with(FACING_TO_CONNECTION_MAP.get(facing), ConnectionType.NONE);
state = state.setValue(FACING_TO_CONNECTION_MAP.get(facing), ConnectionType.NONE);
}
onConnectionTypeChanged(world, currentPos, facing);
@@ -275,8 +275,8 @@ public final class BusCableBlock extends Block {
///////////////////////////////////////////////////////////////////
@Override
protected void fillStateContainer(final StateContainer.Builder<Block, BlockState> builder) {
super.fillStateContainer(builder);
protected void createBlockStateDefinition(final StateContainer.Builder<Block, BlockState> builder) {
super.createBlockStateDefinition(builder);
FACING_TO_CONNECTION_MAP.values().forEach(builder::add);
builder.add(HAS_CABLE);
}
@@ -285,13 +285,13 @@ public final class BusCableBlock extends Block {
private static boolean canHaveCableTo(final BlockState state, final Direction side) {
return state.getBlock() == Blocks.BUS_CABLE.get() &&
state.get(HAS_CABLE) &&
state.get(FACING_TO_CONNECTION_MAP.get(side)) != ConnectionType.INTERFACE;
state.getValue(HAS_CABLE) &&
state.getValue(FACING_TO_CONNECTION_MAP.get(side)) != ConnectionType.INTERFACE;
}
private static int getPartCount(final BlockState state) {
int partCount = getInterfaceCount(state);
if (state.get(HAS_CABLE)) {
if (state.getValue(HAS_CABLE)) {
partCount++;
}
return partCount;
@@ -301,15 +301,15 @@ public final class BusCableBlock extends Block {
final Direction side = getHitSide(pos, hit);
final EnumProperty<ConnectionType> property = FACING_TO_CONNECTION_MAP.get(side);
if (state.get(property) != ConnectionType.INTERFACE) {
if (state.getValue(property) != ConnectionType.INTERFACE) {
return false;
}
final BlockPos neighborPos = pos.offset(side);
if (state.get(HAS_CABLE) && canHaveCableTo(world.getBlockState(neighborPos), side.getOpposite())) {
world.setBlockState(pos, state.with(property, ConnectionType.CABLE));
final BlockPos neighborPos = pos.relative(side);
if (state.getValue(HAS_CABLE) && canHaveCableTo(world.getBlockState(neighborPos), side.getOpposite())) {
world.setBlockAndUpdate(pos, state.setValue(property, ConnectionType.CABLE));
} else {
world.setBlockState(pos, state.with(property, ConnectionType.NONE));
world.setBlockAndUpdate(pos, state.setValue(property, ConnectionType.NONE));
}
handlePartRemoved(state, world, pos, side, player, new ItemStack(Items.BUS_INTERFACE.get()));
@@ -318,11 +318,11 @@ public final class BusCableBlock extends Block {
}
private static boolean tryRemoveCable(final BlockState state, final World world, final BlockPos pos, final PlayerEntity player) {
if (!state.get(HAS_CABLE)) {
if (!state.getValue(HAS_CABLE)) {
return false;
}
world.setBlockState(pos, state.with(HAS_CABLE, false));
world.setBlockAndUpdate(pos, state.setValue(HAS_CABLE, false));
handlePartRemoved(state, world, pos, null, player, new ItemStack(Items.BUS_CABLE.get()));
@@ -332,10 +332,10 @@ public final class BusCableBlock extends Block {
private static void handlePartRemoved(final BlockState state, final World world, final BlockPos pos, @Nullable final Direction side, final PlayerEntity player, final ItemStack drop) {
onConnectionTypeChanged(world, pos, side);
if (!player.isCreative() && world.getGameRules().getBoolean(GameRules.DO_TILE_DROPS)) {
if (!player.isCreative() && world.getGameRules().getBoolean(GameRules.RULE_DOBLOCKDROPS)) {
ItemStackUtils.spawnAsEntity(world, pos, drop, side).ifPresent(entity -> {
entity.setNoPickupDelay();
entity.onCollideWithPlayer(player);
entity.setNoPickUpDelay();
entity.playerTouch(player);
});
}
@@ -343,7 +343,7 @@ public final class BusCableBlock extends Block {
}
private static void onConnectionTypeChanged(final IWorld world, final BlockPos pos, @Nullable final Direction face) {
final TileEntity tileEntity = world.getTileEntity(pos);
final TileEntity tileEntity = world.getBlockEntity(pos);
if (tileEntity instanceof BusCableTileEntity) {
final BusCableTileEntity busCable = (BusCableTileEntity) tileEntity;
busCable.handleConnectivityChanged(face);
@@ -353,11 +353,11 @@ public final class BusCableBlock extends Block {
@OnlyIn(Dist.CLIENT)
private static void openBusInterfaceScreen(final BusCableTileEntity tileEntity, final Direction side) {
final BusInterfaceScreen screen = new BusInterfaceScreen(tileEntity, side);
Minecraft.getInstance().displayGuiScreen(screen);
Minecraft.getInstance().setScreen(screen);
}
private static VoxelShape[] makeShapes() {
final VoxelShape ownCableBounds = Block.makeCuboidShape(5, 5, 5, 11, 11, 11);
final VoxelShape ownCableBounds = Block.box(5, 5, 5, 11, 11, 11);
final VoxelShape[] cableShapes = new VoxelShape[Constants.BLOCK_FACE_COUNT];
final VoxelShape[] interfaceShapes = new VoxelShape[Constants.BLOCK_FACE_COUNT];
for (int i = 0; i < Constants.BLOCK_FACE_COUNT; i++) {
@@ -404,20 +404,20 @@ public final class BusCableBlock extends Block {
final int zSize = 5;
final Direction yDirection = zDirection.getAxis() == Direction.Axis.Y ? Direction.NORTH : Direction.UP;
final Direction xDirection = zDirection.getAxis() == Direction.Axis.Y ? Direction.WEST : zDirection.rotateY();
final Direction xDirection = zDirection.getAxis() == Direction.Axis.Y ? Direction.WEST : zDirection.getClockWise();
final Vector3i min = new Vector3i(8, 8, 8)
.offset(xDirection, -xSize / 2)
.offset(yDirection, -ySize / 2)
.offset(zDirection, 8 - zSize);
.relative(xDirection, -xSize / 2)
.relative(yDirection, -ySize / 2)
.relative(zDirection, 8 - zSize);
final Vector3i max = new Vector3i(8, 8, 8)
.offset(xDirection, xSize / 2)
.offset(yDirection, ySize / 2)
.offset(zDirection, 8);
.relative(xDirection, xSize / 2)
.relative(yDirection, ySize / 2)
.relative(zDirection, 8);
final AxisAlignedBB bounds = new AxisAlignedBB(
Vector3d.copy(min).scale(1 / 16.0),
Vector3d.copy(max).scale(1 / 16.0)
Vector3d.atLowerCornerOf(min).scale(1 / 16.0),
Vector3d.atLowerCornerOf(max).scale(1 / 16.0)
);
return VoxelShapes.create(bounds);
@@ -429,20 +429,20 @@ public final class BusCableBlock extends Block {
final int zSize = 1;
final Direction yDirection = zDirection.getAxis() == Direction.Axis.Y ? Direction.NORTH : Direction.UP;
final Direction xDirection = zDirection.getAxis() == Direction.Axis.Y ? Direction.WEST : zDirection.rotateY();
final Direction xDirection = zDirection.getAxis() == Direction.Axis.Y ? Direction.WEST : zDirection.getClockWise();
final Vector3i min = new Vector3i(8, 8, 8)
.offset(xDirection, -xSize / 2)
.offset(yDirection, -ySize / 2)
.offset(zDirection, 8 - zSize);
.relative(xDirection, -xSize / 2)
.relative(yDirection, -ySize / 2)
.relative(zDirection, 8 - zSize);
final Vector3i max = new Vector3i(8, 8, 8)
.offset(xDirection, xSize / 2)
.offset(yDirection, ySize / 2)
.offset(zDirection, 8);
.relative(xDirection, xSize / 2)
.relative(yDirection, ySize / 2)
.relative(zDirection, 8);
final AxisAlignedBB bounds = new AxisAlignedBB(
Vector3d.copy(min).scale(1 / 16.0),
Vector3d.copy(max).scale(1 / 16.0)
Vector3d.atLowerCornerOf(min).scale(1 / 16.0),
Vector3d.atLowerCornerOf(max).scale(1 / 16.0)
);
return VoxelShapes.or(getCableShape(zDirection), VoxelShapes.create(bounds));
@@ -454,7 +454,7 @@ public final class BusCableBlock extends Block {
for (int sideIndex = 0; sideIndex < Constants.BLOCK_FACE_COUNT; sideIndex++) {
final int cableBit = 1 << sideIndex;
final int interfaceBit = cableBit << 6;
switch (state.get(FACING_TO_CONNECTION_MAP.get(Constants.DIRECTIONS[sideIndex]))) {
switch (state.getValue(FACING_TO_CONNECTION_MAP.get(Constants.DIRECTIONS[sideIndex]))) {
case CABLE:
index |= cableBit;
break;
@@ -466,7 +466,7 @@ public final class BusCableBlock extends Block {
index = index << 1;
if (state.get(HAS_CABLE)) {
if (state.getValue(HAS_CABLE)) {
index |= 1;
}

View File

@@ -16,10 +16,10 @@ import javax.annotation.Nullable;
public final class ChargerBlock extends BreakableBlock {
public ChargerBlock() {
super(Properties
.create(Material.IRON)
.of(Material.METAL)
.sound(SoundType.METAL)
.hardnessAndResistance(1.5f, 6.0f));
setDefaultState(getStateContainer().getBaseState().with(HorizontalBlock.HORIZONTAL_FACING, Direction.NORTH));
.strength(1.5f, 6.0f));
registerDefaultState(getStateDefinition().any().setValue(HorizontalBlock.FACING, Direction.NORTH));
}
///////////////////////////////////////////////////////////////////
@@ -27,13 +27,13 @@ public final class ChargerBlock extends BreakableBlock {
@SuppressWarnings("deprecation")
@Override
public BlockState rotate(final BlockState state, final Rotation rot) {
return state.with(HorizontalBlock.HORIZONTAL_FACING, rot.rotate(state.get(HorizontalBlock.HORIZONTAL_FACING)));
return state.setValue(HorizontalBlock.FACING, rot.rotate(state.getValue(HorizontalBlock.FACING)));
}
@SuppressWarnings("deprecation")
@Override
public BlockState mirror(final BlockState state, final Mirror mirrorIn) {
return state.rotate(mirrorIn.toRotation(state.get(HorizontalBlock.HORIZONTAL_FACING)));
return state.rotate(mirrorIn.getRotation(state.getValue(HorizontalBlock.FACING)));
}
@Override
@@ -49,14 +49,14 @@ public final class ChargerBlock extends BreakableBlock {
@Override
public BlockState getStateForPlacement(final BlockItemUseContext context) {
return super.getDefaultState().with(HorizontalBlock.HORIZONTAL_FACING, context.getPlacementHorizontalFacing().getOpposite());
return super.defaultBlockState().setValue(HorizontalBlock.FACING, context.getHorizontalDirection().getOpposite());
}
///////////////////////////////////////////////////////////////////
@Override
protected void fillStateContainer(final StateContainer.Builder<Block, BlockState> builder) {
super.fillStateContainer(builder);
builder.add(HorizontalBlock.HORIZONTAL_FACING);
protected void createBlockStateDefinition(final StateContainer.Builder<Block, BlockState> builder) {
super.createBlockStateDefinition(builder);
builder.add(HorizontalBlock.FACING);
}
}

View File

@@ -52,11 +52,11 @@ public final class ComputerBlock extends HorizontalBlock {
// We bake the "screen" indent on the front into the collision shape to prevent stuff being
// placeable on that side, such as network connectors, torches, etc.
private static final VoxelShape NEG_Z_SHAPE = VoxelShapes.or(
Block.makeCuboidShape(0, 0, 1, 16, 16, 16), // main body
Block.makeCuboidShape(0, 15, 0, 16, 16, 1), // across top
Block.makeCuboidShape(0, 0, 0, 16, 6, 1), // across bottom
Block.makeCuboidShape(0, 0, 0, 1, 16, 1), // up left
Block.makeCuboidShape(15, 0, 0, 16, 16, 1) // up right
Block.box(0, 0, 1, 16, 16, 16), // main body
Block.box(0, 15, 0, 16, 16, 1), // across top
Block.box(0, 0, 0, 16, 6, 1), // across bottom
Block.box(0, 0, 0, 1, 16, 1), // up left
Block.box(15, 0, 0, 16, 16, 1) // up right
);
private static final VoxelShape NEG_X_SHAPE = VoxelShapeUtils.rotateHorizontalClockwise(NEG_Z_SHAPE);
private static final VoxelShape POS_Z_SHAPE = VoxelShapeUtils.rotateHorizontalClockwise(NEG_X_SHAPE);
@@ -66,25 +66,25 @@ public final class ComputerBlock extends HorizontalBlock {
public ComputerBlock() {
super(Properties
.create(Material.IRON)
.of(Material.METAL)
.sound(SoundType.METAL)
.hardnessAndResistance(1.5f, 6.0f));
setDefaultState(getStateContainer().getBaseState().with(HORIZONTAL_FACING, Direction.NORTH));
.strength(1.5f, 6.0f));
registerDefaultState(getStateDefinition().any().setValue(FACING, Direction.NORTH));
}
///////////////////////////////////////////////////////////////////
@Override
public void fillItemGroup(final ItemGroup group, final NonNullList<ItemStack> items) {
super.fillItemGroup(group, items);
public void fillItemCategory(final ItemGroup group, final NonNullList<ItemStack> items) {
super.fillItemCategory(group, items);
items.add(getPreconfiguredComputer());
}
@OnlyIn(Dist.CLIENT)
@Override
public void addInformation(final ItemStack stack, @Nullable final IBlockReader world, final List<ITextComponent> tooltip, final ITooltipFlag advanced) {
super.addInformation(stack, world, tooltip, advanced);
public void appendHoverText(final ItemStack stack, @Nullable final IBlockReader world, final List<ITextComponent> tooltip, final ITooltipFlag advanced) {
super.appendHoverText(stack, world, tooltip, advanced);
TooltipUtils.addEnergyConsumption(Config.computerEnergyPerTick, tooltip);
TooltipUtils.addTileEntityInventoryInformation(stack, tooltip);
}
@@ -101,14 +101,14 @@ public final class ComputerBlock extends HorizontalBlock {
@SuppressWarnings("deprecation")
@Override
public boolean canProvidePower(final BlockState state) {
public boolean isSignalSource(final BlockState state) {
return true;
}
@SuppressWarnings("deprecation")
@Override
public int getWeakPower(final BlockState state, final IBlockReader world, final BlockPos pos, final Direction side) {
final TileEntity tileEntity = world.getTileEntity(pos);
public int getSignal(final BlockState state, final IBlockReader world, final BlockPos pos, final Direction side) {
final TileEntity tileEntity = world.getBlockEntity(pos);
if (tileEntity != null) {
// Redstone requests info for faces with external perspective. Capabilities treat
// the Direction from internal perspective, so flip it.
@@ -117,13 +117,13 @@ public final class ComputerBlock extends HorizontalBlock {
.orElse(0);
}
return super.getWeakPower(state, world, pos, side);
return super.getSignal(state, world, pos, side);
}
@SuppressWarnings("deprecation")
@Override
public int getStrongPower(final BlockState state, final IBlockReader world, final BlockPos pos, final Direction side) {
return getWeakPower(state, world, pos, side);
public int getDirectSignal(final BlockState state, final IBlockReader world, final BlockPos pos, final Direction side) {
return getSignal(state, world, pos, side);
}
@Override
@@ -134,7 +134,7 @@ public final class ComputerBlock extends HorizontalBlock {
@SuppressWarnings("deprecation")
@Override
public void neighborChanged(final BlockState state, final World world, final BlockPos pos, final Block changedBlock, final BlockPos changedBlockPos, final boolean isMoving) {
final TileEntity tileEntity = world.getTileEntity(pos);
final TileEntity tileEntity = world.getBlockEntity(pos);
if (tileEntity instanceof ComputerTileEntity) {
final ComputerTileEntity computer = (ComputerTileEntity) tileEntity;
computer.handleNeighborChanged();
@@ -144,7 +144,7 @@ public final class ComputerBlock extends HorizontalBlock {
@SuppressWarnings("deprecation")
@Override
public VoxelShape getShape(final BlockState state, final IBlockReader world, final BlockPos pos, final ISelectionContext context) {
switch (state.get(HORIZONTAL_FACING)) {
switch (state.getValue(FACING)) {
case NORTH:
return NEG_Z_SHAPE;
case SOUTH:
@@ -159,21 +159,21 @@ public final class ComputerBlock extends HorizontalBlock {
@SuppressWarnings("deprecation")
@Override
public ActionResultType onBlockActivated(final BlockState state, final World world, final BlockPos pos, final PlayerEntity player, final Hand hand, final BlockRayTraceResult hit) {
final TileEntity tileEntity = world.getTileEntity(pos);
public ActionResultType use(final BlockState state, final World world, final BlockPos pos, final PlayerEntity player, final Hand hand, final BlockRayTraceResult hit) {
final TileEntity tileEntity = world.getBlockEntity(pos);
if (!(tileEntity instanceof ComputerTileEntity)) {
return super.onBlockActivated(state, world, pos, player, hand, hit);
return super.use(state, world, pos, player, hand, hit);
}
final ComputerTileEntity computer = (ComputerTileEntity) tileEntity;
final ItemStack heldItem = player.getHeldItem(hand);
if (!world.isRemote()) {
final ItemStack heldItem = player.getItemInHand(hand);
if (!world.isClientSide) {
if (Wrenches.isWrench(heldItem)) {
if (player instanceof ServerPlayerEntity) {
computer.openContainerScreen((ServerPlayerEntity) player);
}
} else {
if (player.isSneaking()) {
if (player.isShiftKeyDown()) {
computer.start();
} else if (player instanceof ServerPlayerEntity) {
computer.openTerminalScreen((ServerPlayerEntity) player);
@@ -181,13 +181,13 @@ public final class ComputerBlock extends HorizontalBlock {
}
}
return world.isRemote() ? ActionResultType.SUCCESS : ActionResultType.CONSUME;
return world.isClientSide ? ActionResultType.SUCCESS : ActionResultType.CONSUME;
}
@Override
public void onBlockHarvested(final World world, final BlockPos pos, final BlockState state, final PlayerEntity player) {
final TileEntity tileEntity = world.getTileEntity(pos);
if (!world.isRemote() && tileEntity instanceof ComputerTileEntity) {
public void playerWillDestroy(final World world, final BlockPos pos, final BlockState state, final PlayerEntity player) {
final TileEntity tileEntity = world.getBlockEntity(pos);
if (!world.isClientSide && tileEntity instanceof ComputerTileEntity) {
final ComputerTileEntity computer = (ComputerTileEntity) tileEntity;
if (!computer.getItemStackHandlers().isEmpty()) {
computer.getItemStackHandlers().exportDeviceDataToItemStacks();
@@ -195,25 +195,25 @@ public final class ComputerBlock extends HorizontalBlock {
if (player.isCreative()) {
final ItemStack stack = new ItemStack(Items.COMPUTER.get());
computer.exportToItemStack(stack);
spawnAsEntity(world, pos, stack);
popResource(world, pos, stack);
}
}
}
super.onBlockHarvested(world, pos, state, player);
super.playerWillDestroy(world, pos, state, player);
}
@Override
public BlockState getStateForPlacement(final BlockItemUseContext context) {
return super.getDefaultState().with(HORIZONTAL_FACING, context.getPlacementHorizontalFacing().getOpposite());
return super.defaultBlockState().setValue(FACING, context.getHorizontalDirection().getOpposite());
}
///////////////////////////////////////////////////////////////////
@Override
protected void fillStateContainer(final StateContainer.Builder<Block, BlockState> builder) {
super.fillStateContainer(builder);
builder.add(HORIZONTAL_FACING);
protected void createBlockStateDefinition(final StateContainer.Builder<Block, BlockState> builder) {
super.createBlockStateDefinition(builder);
builder.add(FACING);
}
///////////////////////////////////////////////////////////////////

View File

@@ -11,9 +11,9 @@ import net.minecraft.world.IBlockReader;
public final class CreativeEnergyBlock extends Block {
public CreativeEnergyBlock() {
super(Properties
.create(Material.IRON)
.of(Material.METAL)
.sound(SoundType.METAL)
.hardnessAndResistance(-1, 3600000)
.strength(-1, 3600000)
.noDrops());
}

View File

@@ -23,17 +23,17 @@ import net.minecraft.world.World;
public final class DiskDriveBlock extends HorizontalBlock {
public DiskDriveBlock() {
super(Properties
.create(Material.IRON)
.of(Material.METAL)
.sound(SoundType.METAL)
.hardnessAndResistance(1.5f, 6.0f));
setDefaultState(getStateContainer().getBaseState().with(HORIZONTAL_FACING, Direction.NORTH));
.strength(1.5f, 6.0f));
registerDefaultState(getStateDefinition().any().setValue(FACING, Direction.NORTH));
}
///////////////////////////////////////////////////////////////////
@Override
public BlockState getStateForPlacement(final BlockItemUseContext context) {
return super.getDefaultState().with(HORIZONTAL_FACING, context.getPlacementHorizontalFacing().getOpposite());
return super.defaultBlockState().setValue(FACING, context.getHorizontalDirection().getOpposite());
}
@Override
@@ -48,23 +48,23 @@ public final class DiskDriveBlock extends HorizontalBlock {
@SuppressWarnings("deprecation")
@Override
public ActionResultType onBlockActivated(final BlockState state, final World world, final BlockPos pos, final PlayerEntity player, final Hand hand, final BlockRayTraceResult hit) {
final TileEntity tileEntity = world.getTileEntity(pos);
public ActionResultType use(final BlockState state, final World world, final BlockPos pos, final PlayerEntity player, final Hand hand, final BlockRayTraceResult hit) {
final TileEntity tileEntity = world.getBlockEntity(pos);
if (!(tileEntity instanceof DiskDriveTileEntity)) {
return super.onBlockActivated(state, world, pos, player, hand, hit);
return super.use(state, world, pos, player, hand, hit);
}
if (world.isRemote()) {
if (world.isClientSide) {
return ActionResultType.SUCCESS;
}
final DiskDriveTileEntity diskDrive = (DiskDriveTileEntity) tileEntity;
final ItemStack stack = player.getHeldItem(hand);
final ItemStack stack = player.getItemInHand(hand);
if (player.isSneaking()) {
if (player.isShiftKeyDown()) {
diskDrive.eject();
} else {
player.setHeldItem(hand, diskDrive.insert(stack));
player.setItemInHand(hand, diskDrive.insert(stack));
}
return ActionResultType.CONSUME;
@@ -73,8 +73,8 @@ public final class DiskDriveBlock extends HorizontalBlock {
///////////////////////////////////////////////////////////////////
@Override
protected void fillStateContainer(final StateContainer.Builder<Block, BlockState> builder) {
super.fillStateContainer(builder);
builder.add(HORIZONTAL_FACING);
protected void createBlockStateDefinition(final StateContainer.Builder<Block, BlockState> builder) {
super.createBlockStateDefinition(builder);
builder.add(FACING);
}
}

View File

@@ -20,29 +20,29 @@ import net.minecraft.world.World;
import java.util.Objects;
public final class NetworkConnectorBlock extends HorizontalFaceBlock {
private static final VoxelShape NEG_Z_SHAPE = Block.makeCuboidShape(5, 5, 7, 11, 11, 16);
private static final VoxelShape POS_Z_SHAPE = Block.makeCuboidShape(5, 5, 0, 11, 11, 9);
private static final VoxelShape NEG_X_SHAPE = Block.makeCuboidShape(7, 5, 5, 16, 11, 11);
private static final VoxelShape POS_X_SHAPE = Block.makeCuboidShape(0, 5, 5, 9, 11, 11);
private static final VoxelShape NEG_Y_SHAPE = Block.makeCuboidShape(5, 0, 5, 11, 9, 11);
private static final VoxelShape POS_Y_SHAPE = Block.makeCuboidShape(5, 7, 5, 11, 16, 11);
private static final VoxelShape NEG_Z_SHAPE = Block.box(5, 5, 7, 11, 11, 16);
private static final VoxelShape POS_Z_SHAPE = Block.box(5, 5, 0, 11, 11, 9);
private static final VoxelShape NEG_X_SHAPE = Block.box(7, 5, 5, 16, 11, 11);
private static final VoxelShape POS_X_SHAPE = Block.box(0, 5, 5, 9, 11, 11);
private static final VoxelShape NEG_Y_SHAPE = Block.box(5, 0, 5, 11, 9, 11);
private static final VoxelShape POS_Y_SHAPE = Block.box(5, 7, 5, 11, 16, 11);
///////////////////////////////////////////////////////////////////
public NetworkConnectorBlock() {
super(Properties
.create(Material.IRON)
.of(Material.METAL)
.sound(SoundType.METAL)
.hardnessAndResistance(1.5f, 6.0f));
setDefaultState(getStateContainer().getBaseState()
.with(HORIZONTAL_FACING, Direction.NORTH)
.with(FACE, AttachFace.WALL));
.strength(1.5f, 6.0f));
registerDefaultState(getStateDefinition().any()
.setValue(FACING, Direction.NORTH)
.setValue(FACE, AttachFace.WALL));
}
///////////////////////////////////////////////////////////////////
public static Direction getFacing(final BlockState state) {
return HorizontalFaceBlock.getFacing(state);
return HorizontalFaceBlock.getConnectedDirection(state);
}
@Override
@@ -58,8 +58,8 @@ public final class NetworkConnectorBlock extends HorizontalFaceBlock {
@SuppressWarnings("deprecation")
@Override
public void neighborChanged(final BlockState state, final World world, final BlockPos pos, final Block changedBlock, final BlockPos changedBlockPos, final boolean isMoving) {
if (Objects.equals(changedBlockPos, pos.offset(getFacing(state).getOpposite()))) {
final TileEntity tileEntity = world.getTileEntity(pos);
if (Objects.equals(changedBlockPos, pos.relative(getFacing(state).getOpposite()))) {
final TileEntity tileEntity = world.getBlockEntity(pos);
if (tileEntity instanceof NetworkConnectorTileEntity) {
final NetworkConnectorTileEntity connector = (NetworkConnectorTileEntity) tileEntity;
connector.setLocalInterfaceChanged();
@@ -70,9 +70,9 @@ public final class NetworkConnectorBlock extends HorizontalFaceBlock {
@SuppressWarnings("deprecation")
@Override
public VoxelShape getShape(final BlockState state, final IBlockReader world, final BlockPos pos, final ISelectionContext context) {
switch (state.get(FACE)) {
switch (state.getValue(FACE)) {
case WALL:
switch (state.get(HORIZONTAL_FACING)) {
switch (state.getValue(FACING)) {
case EAST:
return POS_X_SHAPE;
case WEST:
@@ -93,7 +93,7 @@ public final class NetworkConnectorBlock extends HorizontalFaceBlock {
///////////////////////////////////////////////////////////////////
protected void fillStateContainer(final StateContainer.Builder<Block, BlockState> builder) {
builder.add(FACE, HORIZONTAL_FACING);
protected void createBlockStateDefinition(final StateContainer.Builder<Block, BlockState> builder) {
builder.add(FACE, FACING);
}
}

View File

@@ -18,17 +18,17 @@ import net.minecraft.world.World;
public final class NetworkHubBlock extends HorizontalBlock {
public NetworkHubBlock() {
super(Properties
.create(Material.IRON)
.of(Material.METAL)
.sound(SoundType.METAL)
.hardnessAndResistance(1.5f, 6.0f));
setDefaultState(getStateContainer().getBaseState().with(HORIZONTAL_FACING, Direction.NORTH));
.strength(1.5f, 6.0f));
registerDefaultState(getStateDefinition().any().setValue(FACING, Direction.NORTH));
}
///////////////////////////////////////////////////////////////////
@Override
public BlockState getStateForPlacement(final BlockItemUseContext context) {
return super.getDefaultState().with(HORIZONTAL_FACING, context.getPlacementHorizontalFacing().getOpposite());
return super.defaultBlockState().setValue(FACING, context.getHorizontalDirection().getOpposite());
}
@Override
@@ -44,7 +44,7 @@ public final class NetworkHubBlock extends HorizontalBlock {
@SuppressWarnings("deprecation")
@Override
public void neighborChanged(final BlockState state, final World world, final BlockPos pos, final Block changedBlock, final BlockPos changedBlockPos, final boolean isMoving) {
final TileEntity tileEntity = world.getTileEntity(pos);
final TileEntity tileEntity = world.getBlockEntity(pos);
if (tileEntity instanceof NetworkHubTileEntity) {
final NetworkHubTileEntity hub = (NetworkHubTileEntity) tileEntity;
hub.handleNeighborChanged();
@@ -54,8 +54,8 @@ public final class NetworkHubBlock extends HorizontalBlock {
///////////////////////////////////////////////////////////////////
@Override
protected void fillStateContainer(final StateContainer.Builder<Block, BlockState> builder) {
super.fillStateContainer(builder);
builder.add(HORIZONTAL_FACING);
protected void createBlockStateDefinition(final StateContainer.Builder<Block, BlockState> builder) {
super.createBlockStateDefinition(builder);
builder.add(FACING);
}
}

View File

@@ -18,17 +18,17 @@ import net.minecraft.world.IWorldReader;
public final class RedstoneInterfaceBlock extends HorizontalBlock {
public RedstoneInterfaceBlock() {
super(Properties
.create(Material.IRON)
.of(Material.METAL)
.sound(SoundType.METAL)
.hardnessAndResistance(1.5f, 6.0f));
setDefaultState(getStateContainer().getBaseState().with(HORIZONTAL_FACING, Direction.NORTH));
.strength(1.5f, 6.0f));
registerDefaultState(getStateDefinition().any().setValue(FACING, Direction.NORTH));
}
///////////////////////////////////////////////////////////////////
@Override
public BlockState getStateForPlacement(final BlockItemUseContext context) {
return super.getDefaultState().with(HORIZONTAL_FACING, context.getPlacementHorizontalFacing().getOpposite());
return super.defaultBlockState().setValue(FACING, context.getHorizontalDirection().getOpposite());
}
@Override
@@ -43,14 +43,14 @@ public final class RedstoneInterfaceBlock extends HorizontalBlock {
@SuppressWarnings("deprecation")
@Override
public boolean canProvidePower(final BlockState state) {
public boolean isSignalSource(final BlockState state) {
return true;
}
@SuppressWarnings("deprecation")
@Override
public int getWeakPower(final BlockState state, final IBlockReader world, final BlockPos pos, final Direction side) {
final TileEntity tileEntity = world.getTileEntity(pos);
public int getSignal(final BlockState state, final IBlockReader world, final BlockPos pos, final Direction side) {
final TileEntity tileEntity = world.getBlockEntity(pos);
if (tileEntity instanceof RedstoneInterfaceTileEntity) {
final RedstoneInterfaceTileEntity redstoneInterface = (RedstoneInterfaceTileEntity) tileEntity;
// Redstone requests info for faces with external perspective. We treat
@@ -58,7 +58,7 @@ public final class RedstoneInterfaceBlock extends HorizontalBlock {
return redstoneInterface.getOutputForDirection(side.getOpposite());
}
return super.getWeakPower(state, world, pos, side);
return super.getSignal(state, world, pos, side);
}
@Override
@@ -68,15 +68,15 @@ public final class RedstoneInterfaceBlock extends HorizontalBlock {
@SuppressWarnings("deprecation")
@Override
public int getStrongPower(final BlockState state, final IBlockReader world, final BlockPos pos, final Direction side) {
return getWeakPower(state, world, pos, side);
public int getDirectSignal(final BlockState state, final IBlockReader world, final BlockPos pos, final Direction side) {
return getSignal(state, world, pos, side);
}
///////////////////////////////////////////////////////////////////
@Override
protected void fillStateContainer(final StateContainer.Builder<Block, BlockState> builder) {
super.fillStateContainer(builder);
builder.add(HORIZONTAL_FACING);
protected void createBlockStateDefinition(final StateContainer.Builder<Block, BlockState> builder) {
super.createBlockStateDefinition(builder);
builder.add(FACING);
}
}

View File

@@ -54,7 +54,7 @@ public abstract class AbstractGroupingDeviceBusElement<TProvider extends IForgeR
final CompoundNBT sideTag = new CompoundNBT();
sideTag.putUniqueId(GROUP_ID_TAG_NAME, groupIds[i]);
sideTag.putUUID(GROUP_ID_TAG_NAME, groupIds[i]);
sideTag.put(GROUP_DATA_TAG_NAME, groupData[i]);
listTag.add(sideTag);
@@ -68,8 +68,8 @@ public abstract class AbstractGroupingDeviceBusElement<TProvider extends IForgeR
for (int i = 0; i < count; i++) {
final CompoundNBT sideTag = nbt.getCompound(i);
if (sideTag.hasUniqueId(GROUP_ID_TAG_NAME)) {
groupIds[i] = sideTag.getUniqueId(GROUP_ID_TAG_NAME);
if (sideTag.hasUUID(GROUP_ID_TAG_NAME)) {
groupIds[i] = sideTag.getUUID(GROUP_ID_TAG_NAME);
}
if (sideTag.contains(GROUP_DATA_TAG_NAME, NBTTagIds.TAG_COMPOUND)) {
groupData[i] = sideTag.getCompound(GROUP_DATA_TAG_NAME);

View File

@@ -43,7 +43,7 @@ public class TileEntityDeviceBusController extends CommonDeviceBusController {
protected void onAfterBusScan() {
super.onAfterBusScan();
final World world = tileEntity.getWorld();
final World world = tileEntity.getLevel();
if (world == null) {
return;
}
@@ -52,19 +52,19 @@ public class TileEntityDeviceBusController extends CommonDeviceBusController {
for (final DeviceBusElement element : getElements()) {
if (element instanceof BlockDeviceBusElement) {
final BlockDeviceBusElement blockElement = (BlockDeviceBusElement) element;
final IWorld elementWorld = blockElement.getWorld();
final IWorld elementWorld = blockElement.getLevel();
final BlockPos elementPosition = blockElement.getPosition();
newTrackedChunks.add(new TrackedChunk(elementWorld, elementPosition));
newTrackedChunks.add(new TrackedChunk(elementWorld, elementPosition.offset(Direction.NORTH)));
newTrackedChunks.add(new TrackedChunk(elementWorld, elementPosition.offset(Direction.EAST)));
newTrackedChunks.add(new TrackedChunk(elementWorld, elementPosition.offset(Direction.SOUTH)));
newTrackedChunks.add(new TrackedChunk(elementWorld, elementPosition.offset(Direction.WEST)));
newTrackedChunks.add(new TrackedChunk(elementWorld, elementPosition.relative(Direction.NORTH)));
newTrackedChunks.add(new TrackedChunk(elementWorld, elementPosition.relative(Direction.EAST)));
newTrackedChunks.add(new TrackedChunk(elementWorld, elementPosition.relative(Direction.SOUTH)));
newTrackedChunks.add(new TrackedChunk(elementWorld, elementPosition.relative(Direction.WEST)));
}
}
// Do not track the chunk the controller itself is in -- this is unneeded because
// we expect the controller to be disposed if its chunk is unloaded.
newTrackedChunks.remove(new TrackedChunk(world, tileEntity.getPos()));
newTrackedChunks.remove(new TrackedChunk(world, tileEntity.getBlockPos()));
final HashSet<TrackedChunk> removedChunks = new HashSet<>(trackedChunks);
removedChunks.removeAll(newTrackedChunks);

View File

@@ -40,19 +40,19 @@ public class TileEntityDeviceBusElement extends AbstractGroupingBlockDeviceBusEl
///////////////////////////////////////////////////////////////////
@Override
public IWorld getWorld() {
return tileEntity.getWorld();
public IWorld getLevel() {
return tileEntity.getLevel();
}
@Override
public BlockPos getPosition() {
return tileEntity.getPos();
return tileEntity.getBlockPos();
}
@Override
public Optional<Collection<LazyOptional<DeviceBusElement>>> getNeighbors() {
final World world = tileEntity.getWorld();
if (world == null || world.isRemote()) {
final World world = tileEntity.getLevel();
if (world == null || world.isClientSide) {
return Optional.empty();
}
@@ -62,14 +62,14 @@ public class TileEntityDeviceBusElement extends AbstractGroupingBlockDeviceBusEl
continue;
}
final BlockPos neighborPos = tileEntity.getPos().offset(neighborDirection);
final BlockPos neighborPos = tileEntity.getBlockPos().relative(neighborDirection);
final ChunkPos chunkPos = new ChunkPos(neighborPos);
if (!world.chunkExists(chunkPos.x, chunkPos.z)) {
if (!world.hasChunk(chunkPos.x, chunkPos.z)) {
return Optional.empty();
}
final TileEntity tileEntity = world.getTileEntity(neighborPos);
final TileEntity tileEntity = world.getBlockEntity(neighborPos);
if (tileEntity == null) {
continue;
}
@@ -84,18 +84,18 @@ public class TileEntityDeviceBusElement extends AbstractGroupingBlockDeviceBusEl
}
public void handleNeighborChanged(final BlockPos pos) {
final World world = tileEntity.getWorld();
if (world == null || world.isRemote()) {
final World world = tileEntity.getLevel();
if (world == null || world.isClientSide) {
return;
}
final BlockPos toPos = pos.subtract(tileEntity.getPos());
final Direction direction = Direction.byLong(toPos.getX(), toPos.getY(), toPos.getZ());
final BlockPos toPos = pos.subtract(tileEntity.getBlockPos());
final Direction direction = Direction.fromNormal(toPos.getX(), toPos.getY(), toPos.getZ());
if (direction == null) {
return;
}
final int index = direction.getIndex();
final int index = direction.get3DDataValue();
final HashSet<BlockDeviceInfo> newDevices = new HashSet<>();
if (canDetectDevicesTowards(direction)) {
@@ -112,7 +112,7 @@ public class TileEntityDeviceBusElement extends AbstractGroupingBlockDeviceBusEl
}
public void initialize() {
final World world = requireNonNull(tileEntity.getWorld());
final World world = requireNonNull(tileEntity.getLevel());
ServerScheduler.schedule(world, () -> {
if (tileEntity.isRemoved()) {
return;
@@ -144,16 +144,16 @@ public class TileEntityDeviceBusElement extends AbstractGroupingBlockDeviceBusEl
private void scanNeighborsForDevices() {
for (final Direction direction : Constants.DIRECTIONS) {
handleNeighborChanged(tileEntity.getPos().offset(direction));
handleNeighborChanged(tileEntity.getBlockPos().relative(direction));
}
}
private void scheduleBusScanInAdjacentBusElements() {
final World world = requireNonNull(tileEntity.getWorld());
final BlockPos pos = tileEntity.getPos();
final World world = requireNonNull(tileEntity.getLevel());
final BlockPos pos = tileEntity.getBlockPos();
for (final Direction direction : Constants.DIRECTIONS) {
final BlockPos neighborPos = pos.offset(direction);
final TileEntity tileEntity = WorldUtils.getTileEntityIfChunkExists(world, neighborPos);
final BlockPos neighborPos = pos.relative(direction);
final TileEntity tileEntity = WorldUtils.getBlockEntityIfChunkExists(world, neighborPos);
if (tileEntity == null) {
continue;
}

View File

@@ -54,7 +54,7 @@ public final class FileSystems {
LOGGER.info("Searching for datapack filesystems...");
final Collection<ResourceLocation> fileSystemDescriptorLocations = resourceManager
.getAllResourceLocations("file_systems", s -> s.endsWith(".json"));
.listResources("file_systems", s -> s.endsWith(".json"));
final ArrayList<ZipStreamFileSystem> fileSystems = new ArrayList<>();
final Object2IntArrayMap<ZipStreamFileSystem> fileSystemOrder = new Object2IntArrayMap<>();
@@ -117,7 +117,7 @@ public final class FileSystems {
public CompletableFuture<Void> reload(final IFutureReloadListener.IStage stage, final IResourceManager resourceManager, final IProfiler preparationsProfiler, final IProfiler reloadProfiler, final Executor backgroundExecutor, final Executor gameExecutor) {
return CompletableFuture
.runAsync(() -> FileSystems.reload(resourceManager), backgroundExecutor)
.thenCompose(stage::markCompleteAwaitingOthers);
.thenCompose(stage::wait);
}
}
}

View File

@@ -111,14 +111,14 @@ public abstract class AbstractBlockDeviceVMDevice<TBlock extends BlockDevice, TI
getSerializationStream(data).ifPresent(stream -> blobHandle = BlobStorage.validateHandle(blobHandle));
}
if (blobHandle != null) {
nbt.putUniqueId(BLOB_HANDLE_TAG_NAME, blobHandle);
nbt.putUUID(BLOB_HANDLE_TAG_NAME, blobHandle);
}
}
@Override
public void importFromItemStack(final CompoundNBT nbt) {
if (nbt.hasUniqueId(BLOB_HANDLE_TAG_NAME)) {
blobHandle = nbt.getUniqueId(BLOB_HANDLE_TAG_NAME);
if (nbt.hasUUID(BLOB_HANDLE_TAG_NAME)) {
blobHandle = nbt.getUUID(BLOB_HANDLE_TAG_NAME);
}
}
@@ -141,7 +141,7 @@ public abstract class AbstractBlockDeviceVMDevice<TBlock extends BlockDevice, TI
}
if (blobHandle != null) {
tag.putUniqueId(BLOB_HANDLE_TAG_NAME, blobHandle);
tag.putUUID(BLOB_HANDLE_TAG_NAME, blobHandle);
}
return tag;
@@ -149,8 +149,8 @@ public abstract class AbstractBlockDeviceVMDevice<TBlock extends BlockDevice, TI
@Override
public void deserializeNBT(final CompoundNBT tag) {
if (tag.hasUniqueId(BLOB_HANDLE_TAG_NAME)) {
blobHandle = tag.getUniqueId(BLOB_HANDLE_TAG_NAME);
if (tag.hasUUID(BLOB_HANDLE_TAG_NAME)) {
blobHandle = tag.getUUID(BLOB_HANDLE_TAG_NAME);
}
if (tag.contains(DEVICE_TAG_NAME, NBTTagIds.TAG_COMPOUND)) {

View File

@@ -76,7 +76,7 @@ public final class BlockOperationsModuleDevice extends IdentityProxy<ItemStack>
@Override
public void deserializeNBT(final CompoundNBT tag) {
lastOperation = MathHelper.clamp(tag.getLong(LAST_OPERATION_TAG_NAME), 0, entity.getEntityWorld().getGameTime());
lastOperation = MathHelper.clamp(tag.getLong(LAST_OPERATION_TAG_NAME), 0, entity.getCommandSenderWorld().getGameTime());
}
@Override
@@ -97,7 +97,7 @@ public final class BlockOperationsModuleDevice extends IdentityProxy<ItemStack>
beginCooldown();
final World world = entity.getEntityWorld();
final World world = entity.getCommandSenderWorld();
if (!(world instanceof ServerWorld)) {
return false;
}
@@ -107,7 +107,7 @@ public final class BlockOperationsModuleDevice extends IdentityProxy<ItemStack>
final List<ItemEntity> oldItems = getItemsInRange();
if (!tryHarvestBlock(world, entity.getPosition().offset(getAdjustedDirection(direction)))) {
if (!tryHarvestBlock(world, entity.blockPosition().relative(getAdjustedDirection(direction)))) {
return false;
}
@@ -131,7 +131,7 @@ public final class BlockOperationsModuleDevice extends IdentityProxy<ItemStack>
beginCooldown();
final World world = entity.getEntityWorld();
final World world = entity.getCommandSenderWorld();
if (!(world instanceof ServerWorld)) {
return false;
}
@@ -144,10 +144,10 @@ public final class BlockOperationsModuleDevice extends IdentityProxy<ItemStack>
return false;
}
final BlockPos blockPos = entity.getPosition().offset(getAdjustedDirection(direction));
final BlockPos blockPos = entity.blockPosition().relative(getAdjustedDirection(direction));
final Direction side = getAdjustedDirection(direction).getOpposite();
final BlockRayTraceResult hit = new BlockRayTraceResult(
Vector3d.copyCentered(blockPos).add(Vector3d.copy(side.getDirectionVec()).scale(0.5)),
Vector3d.atCenterOf(blockPos).add(Vector3d.atCenterOf(side.getNormal()).scale(0.5)),
side,
blockPos,
false);
@@ -157,8 +157,8 @@ public final class BlockOperationsModuleDevice extends IdentityProxy<ItemStack>
final ServerPlayerEntity player = FakePlayerUtils.getFakePlayer((ServerWorld) world, entity);
final BlockItemUseContext context = new BlockItemUseContext(player, Hand.MAIN_HAND, itemStack, hit);
final ActionResultType result = blockItem.tryPlace(context);
if (!result.isSuccessOrConsume()) {
final ActionResultType result = blockItem.place(context);
if (!result.consumesAction()) {
return false;
}
@@ -171,7 +171,7 @@ public final class BlockOperationsModuleDevice extends IdentityProxy<ItemStack>
@Callback(synchronize = false)
public int durability() {
return identity.getMaxDamage() - identity.getDamage();
return identity.getMaxDamage() - identity.getDamageValue();
}
@Callback
@@ -182,7 +182,7 @@ public final class BlockOperationsModuleDevice extends IdentityProxy<ItemStack>
beginCooldown();
if (identity.getDamage() == 0) {
if (identity.getDamageValue() == 0) {
return false;
}
@@ -196,7 +196,7 @@ public final class BlockOperationsModuleDevice extends IdentityProxy<ItemStack>
return false;
}
final int repairValue = tier.getMaxUses();
final int repairValue = tier.getUses();
if (repairValue == 0) {
return false;
}
@@ -206,7 +206,7 @@ public final class BlockOperationsModuleDevice extends IdentityProxy<ItemStack>
return false;
}
identity.setDamage(identity.getDamage() - repairValue);
identity.setDamageValue(identity.getDamageValue() - repairValue);
return true;
}
@@ -214,11 +214,11 @@ public final class BlockOperationsModuleDevice extends IdentityProxy<ItemStack>
///////////////////////////////////////////////////////////////////
private void beginCooldown() {
lastOperation = entity.getEntityWorld().getGameTime();
lastOperation = entity.getCommandSenderWorld().getGameTime();
}
private boolean isOnCooldown() {
return entity.getEntityWorld().getGameTime() - lastOperation < COOLDOWN;
return entity.getCommandSenderWorld().getGameTime() - lastOperation < COOLDOWN;
}
private Direction getAdjustedDirection(@Nullable final PlacementDirection placementDirection) {
@@ -228,16 +228,16 @@ public final class BlockOperationsModuleDevice extends IdentityProxy<ItemStack>
return Direction.DOWN;
} else {
Direction direction = Direction.SOUTH;
final int horizontalIndex = entity.getHorizontalFacing().getHorizontalIndex();
final int horizontalIndex = entity.getDirection().get2DDataValue();
for (int i = 0; i < horizontalIndex; i++) {
direction = direction.rotateY();
direction = direction.getClockWise();
}
return direction;
}
}
private List<ItemEntity> getItemsInRange() {
return entity.getEntityWorld().getEntitiesWithinAABB(ItemEntity.class, entity.getBoundingBox().grow(2));
return entity.getCommandSenderWorld().getEntitiesOfClass(ItemEntity.class, entity.getBoundingBox().inflate(2));
}
private boolean tryHarvestBlock(final World world, final BlockPos blockPos) {
@@ -253,10 +253,10 @@ public final class BlockOperationsModuleDevice extends IdentityProxy<ItemStack>
return false;
}
final TileEntity tileEntity = world.getTileEntity(blockPos);
final TileEntity tileEntity = world.getBlockEntity(blockPos);
final Block block = blockState.getBlock();
final boolean isCommandBlock = block instanceof CommandBlockBlock || block instanceof StructureBlock || block instanceof JigsawBlock;
if (isCommandBlock && !player.canUseCommandBlock()) {
if (isCommandBlock && !player.canUseGameMasterBlocks()) {
return false;
}
@@ -273,7 +273,7 @@ public final class BlockOperationsModuleDevice extends IdentityProxy<ItemStack>
return false;
}
if (identity.attemptDamageItem(1, world.rand, null)) {
if (identity.hurt(1, world.random, null)) {
return false;
}
@@ -281,8 +281,8 @@ public final class BlockOperationsModuleDevice extends IdentityProxy<ItemStack>
return false;
}
block.onPlayerDestroy(world, blockPos, blockState);
block.harvestBlock(world, player, blockPos, blockState, tileEntity, ItemStack.EMPTY);
block.destroy(world, blockPos, blockState);
block.playerDestroy(world, player, blockPos, blockState, tileEntity, ItemStack.EMPTY);
return true;
}

View File

@@ -78,7 +78,7 @@ public final class InventoryOperationsModuleDevice extends IdentityProxy<ItemSta
// And if putting it back fails, just drop it. Avoid destroying items.
if (!remaining.isEmpty()) {
entity.entityDropItem(remaining);
entity.spawnAtLocation(remaining);
}
}
@@ -112,7 +112,7 @@ public final class InventoryOperationsModuleDevice extends IdentityProxy<ItemSta
if (!stack.isEmpty()) {
dropped += stack.getCount();
entity.entityDropItem(stack);
entity.spawnAtLocation(stack);
}
return dropped;
@@ -146,7 +146,7 @@ public final class InventoryOperationsModuleDevice extends IdentityProxy<ItemSta
if (!stack.isEmpty()) {
dropped += stack.getCount();
entity.entityDropItem(stack);
entity.spawnAtLocation(stack);
}
return dropped;
@@ -187,9 +187,9 @@ public final class InventoryOperationsModuleDevice extends IdentityProxy<ItemSta
}
if (direction.getAxis().isHorizontal()) {
final int horizontalIndex = entity.getHorizontalFacing().getHorizontalIndex();
final int horizontalIndex = entity.getDirection().get2DDataValue();
for (int i = 0; i < horizontalIndex; i++) {
direction = direction.rotateY();
direction = direction.getClockWise();
}
}
@@ -209,8 +209,8 @@ public final class InventoryOperationsModuleDevice extends IdentityProxy<ItemSta
}
private Stream<IItemHandler> getItemStackHandlersInDirection(final Direction direction) {
final Vector3i directionVec = direction.getDirectionVec();
return getItemStackHandlersAt(entity.getPositionVec().add(Vector3d.copy(directionVec)), direction.getOpposite());
final Vector3i directionVec = direction.getNormal();
return getItemStackHandlersAt(entity.position().add(Vector3d.atCenterOf(directionVec)), direction.getOpposite());
}
private Stream<IItemHandler> getItemStackHandlersAt(final Vector3d position, final Direction side) {
@@ -218,8 +218,8 @@ public final class InventoryOperationsModuleDevice extends IdentityProxy<ItemSta
}
private Stream<IItemHandler> getEntityItemHandlersAt(final Vector3d position, final Direction side) {
final AxisAlignedBB bounds = AxisAlignedBB.fromVector(position.subtract(0.5, 0.5, 0.5));
return entity.getEntityWorld().getEntitiesWithinAABBExcludingEntity(entity, bounds).stream()
final AxisAlignedBB bounds = AxisAlignedBB.unitCubeFromLowerCorner(position.subtract(0.5, 0.5, 0.5));
return entity.getCommandSenderWorld().getEntities(entity, bounds).stream()
.map(e -> e.getCapability(Capabilities.ITEM_HANDLER, side))
.filter(LazyOptional::isPresent)
.map(c -> c.orElseThrow(AssertionError::new));
@@ -227,7 +227,7 @@ public final class InventoryOperationsModuleDevice extends IdentityProxy<ItemSta
private Stream<IItemHandler> getBlockItemHandlersAt(final Vector3d position, final Direction side) {
final BlockPos pos = new BlockPos(position);
final TileEntity tileEntity = entity.getEntityWorld().getTileEntity(pos);
final TileEntity tileEntity = entity.getCommandSenderWorld().getBlockEntity(pos);
if (tileEntity == null) {
return Stream.empty();
}
@@ -241,7 +241,7 @@ public final class InventoryOperationsModuleDevice extends IdentityProxy<ItemSta
}
private List<ItemEntity> getItemsInRange() {
return entity.getEntityWorld().getEntitiesWithinAABB(ItemEntity.class, entity.getBoundingBox().grow(1));
return entity.getCommandSenderWorld().getEntitiesOfClass(ItemEntity.class, entity.getBoundingBox().inflate(1));
}
private int takeFromWorld(final int count) {
@@ -298,7 +298,7 @@ public final class InventoryOperationsModuleDevice extends IdentityProxy<ItemSta
// And if putting it back fails, just drop it. Avoid destroying items.
if (!overflow.isEmpty()) {
remaining -= overflow.getCount();
entity.entityDropItem(overflow);
entity.spawnAtLocation(overflow);
}
}
@@ -331,7 +331,7 @@ public final class InventoryOperationsModuleDevice extends IdentityProxy<ItemSta
// And if putting it back fails, just drop it. Avoid destroying items.
if (!overflow.isEmpty()) {
// NB: not counting this towards taken count since it did not end up in our inventory.
entity.entityDropItem(overflow);
entity.spawnAtLocation(overflow);
}
return taken;

View File

@@ -83,7 +83,7 @@ public final class MemoryDevice extends IdentityProxy<ItemStack> implements VMDe
if (device != null) {
blobHandle = BlobStorage.validateHandle(blobHandle);
tag.putUniqueId(BLOB_HANDLE_TAG_NAME, blobHandle);
tag.putUUID(BLOB_HANDLE_TAG_NAME, blobHandle);
jobHandle = BlobStorage.submitSave(blobHandle, new PhysicalMemoryInputStream(device));
}
@@ -96,8 +96,8 @@ public final class MemoryDevice extends IdentityProxy<ItemStack> implements VMDe
@Override
public void deserializeNBT(final CompoundNBT tag) {
if (tag.hasUniqueId(BLOB_HANDLE_TAG_NAME)) {
blobHandle = tag.getUniqueId(BLOB_HANDLE_TAG_NAME);
if (tag.hasUUID(BLOB_HANDLE_TAG_NAME)) {
blobHandle = tag.getUUID(BLOB_HANDLE_TAG_NAME);
}
if (tag.contains(ADDRESS_TAG_NAME, NBTTagIds.TAG_LONG)) {
address.set(tag.getLong(ADDRESS_TAG_NAME));

View File

@@ -64,7 +64,7 @@ public final class RedstoneInterfaceCardItemDevice extends IdentityProxy<ItemSta
@Override
public <T> LazyOptional<T> getCapability(@Nonnull final Capability<T> capability, @Nullable final Direction side) {
if (capability == Capabilities.REDSTONE_EMITTER && side != null) {
return LazyOptional.of(() -> capabilities[side.getIndex()]).cast();
return LazyOptional.of(() -> capabilities[side.get3DDataValue()]).cast();
}
return LazyOptional.empty();
@@ -95,37 +95,37 @@ public final class RedstoneInterfaceCardItemDevice extends IdentityProxy<ItemSta
@Callback(name = GET_REDSTONE_INPUT)
public int getRedstoneInput(@Parameter(SIDE) final Direction side) {
final World world = tileEntity.getWorld();
final World world = tileEntity.getLevel();
if (world == null) {
return 0;
}
final BlockPos pos = tileEntity.getPos();
final BlockPos pos = tileEntity.getBlockPos();
final Direction direction = HorizontalBlockUtils.toGlobal(tileEntity.getBlockState(), side);
assert direction != null;
final BlockPos neighborPos = pos.offset(direction);
final BlockPos neighborPos = pos.relative(direction);
final ChunkPos chunkPos = new ChunkPos(neighborPos.getX(), neighborPos.getZ());
if (!world.chunkExists(chunkPos.x, chunkPos.z)) {
if (!world.hasChunk(chunkPos.x, chunkPos.z)) {
return 0;
}
return world.getRedstonePower(neighborPos, direction);
return world.getSignal(neighborPos, direction);
}
@Callback(name = GET_REDSTONE_OUTPUT, synchronize = false)
public int getRedstoneOutput(@Parameter(SIDE) final Direction side) {
return output[side.getIndex()];
return output[side.get3DDataValue()];
}
@Callback(name = SET_REDSTONE_OUTPUT)
public void setRedstoneOutput(@Parameter(SIDE) final Direction side, @Parameter(VALUE) final int value) {
final byte clampedValue = (byte) MathHelper.clamp(value, 0, 15);
if (clampedValue == output[side.getIndex()]) {
if (clampedValue == output[side.get3DDataValue()]) {
return;
}
output[side.getIndex()] = clampedValue;
output[side.get3DDataValue()] = clampedValue;
final Direction direction = HorizontalBlockUtils.toGlobal(tileEntity.getBlockState(), side);
if (direction != null) {
@@ -162,12 +162,12 @@ public final class RedstoneInterfaceCardItemDevice extends IdentityProxy<ItemSta
///////////////////////////////////////////////////////////////////
private void notifyNeighbor(final Direction direction) {
final World world = tileEntity.getWorld();
final World world = tileEntity.getLevel();
if (world == null) {
return;
}
world.notifyNeighborsOfStateChange(tileEntity.getPos(), tileEntity.getBlockState().getBlock());
world.notifyNeighborsOfStateChange(tileEntity.getPos().offset(direction), tileEntity.getBlockState().getBlock());
world.updateNeighborsAt(tileEntity.getBlockPos(), tileEntity.getBlockState().getBlock());
world.updateNeighborsAt(tileEntity.getBlockPos().relative(direction), tileEntity.getBlockState().getBlock());
}
}

View File

@@ -14,7 +14,7 @@ import net.minecraftforge.common.util.LazyOptional;
public final class BlockStateDeviceProvider extends AbstractBlockDeviceProvider {
@Override
public LazyOptional<Device> getDevice(final BlockDeviceQuery query) {
final World world = query.getWorld();
final World world = query.getLevel();
final BlockPos position = query.getQueryPosition();
final BlockState blockState = world.getBlockState(position);

View File

@@ -17,7 +17,7 @@ public final class DiskDriveDeviceProvider extends AbstractTileEntityDeviceProvi
protected LazyOptional<Device> getBlockDevice(final BlockDeviceQuery query, final DiskDriveTileEntity tileEntity) {
// We only allow connecting to exactly one face of the disk drive to ensure only one
// bus (and thus, one VM) will access the device at any single time.
if (query.getQuerySide() != tileEntity.getBlockState().get(HorizontalBlock.HORIZONTAL_FACING)) {
if (query.getQuerySide() != tileEntity.getBlockState().getValue(HorizontalBlock.FACING)) {
return LazyOptional.empty();
}

View File

@@ -25,7 +25,7 @@ public abstract class AbstractTileEntityDeviceProvider<T extends TileEntity> ext
@SuppressWarnings("unchecked")
@Override
public final LazyOptional<Device> getDevice(final BlockDeviceQuery query) {
final TileEntity tileEntity = WorldUtils.getTileEntityIfChunkExists(query.getWorld(), query.getQueryPosition());
final TileEntity tileEntity = WorldUtils.getBlockEntityIfChunkExists(query.getLevel(), query.getQueryPosition());
if (tileEntity == null) {
return LazyOptional.empty();
}

View File

@@ -24,8 +24,8 @@ import static java.util.Objects.requireNonNull;
public final class Devices {
public static BlockDeviceQuery makeQuery(final TileEntity tileEntity, @Nullable final Direction side) {
final World world = requireNonNull(tileEntity.getWorld());
final BlockPos pos = tileEntity.getPos();
final World world = requireNonNull(tileEntity.getLevel());
final BlockPos pos = tileEntity.getBlockPos();
return new BlockQuery(world, pos, side);
}
@@ -106,7 +106,7 @@ public final class Devices {
}
@Override
public World getWorld() {
public World getLevel() {
return world;
}

View File

@@ -21,46 +21,46 @@ public abstract class AbstractContainer extends Container {
}
@Override
public ItemStack transferStackInSlot(final PlayerEntity player, final int index) {
final Slot from = inventorySlots.get(index);
public ItemStack quickMoveStack(final PlayerEntity player, final int index) {
final Slot from = slots.get(index);
if (from == null) {
return ItemStack.EMPTY;
}
final ItemStack stack = from.getStack().copy();
final ItemStack stack = from.getItem().copy();
if (stack.isEmpty()) {
return ItemStack.EMPTY;
}
final boolean intoPlayerInventory = from.inventory != player.inventory;
final ItemStack fromStack = from.getStack();
final boolean intoPlayerInventory = from.container != player.inventory;
final ItemStack fromStack = from.getItem();
final int step, begin;
if (intoPlayerInventory) {
step = -1;
begin = inventorySlots.size() - 1;
begin = slots.size() - 1;
} else {
step = 1;
begin = 0;
}
if (fromStack.getMaxStackSize() > 1) {
for (int i = begin; i >= 0 && i < inventorySlots.size(); i += step) {
final Slot into = inventorySlots.get(i);
if (into.inventory == from.inventory) {
for (int i = begin; i >= 0 && i < slots.size(); i += step) {
final Slot into = slots.get(i);
if (into.container == from.container) {
continue;
}
final ItemStack intoStack = into.getStack();
final ItemStack intoStack = into.getItem();
if (intoStack.isEmpty()) {
continue;
}
final boolean itemsAreEqual = fromStack.isItemEqual(intoStack) && ItemStack.areItemStackTagsEqual(fromStack, intoStack);
final boolean itemsAreEqual = fromStack.sameItem(intoStack) && ItemStack.tagMatches(fromStack, intoStack);
if (!itemsAreEqual) {
continue;
}
final int maxSizeInSlot = Math.min(fromStack.getMaxStackSize(), into.getItemStackLimit(stack));
final int maxSizeInSlot = Math.min(fromStack.getMaxStackSize(), into.getMaxStackSize(stack));
final int spaceInSlot = maxSizeInSlot - intoStack.getCount();
if (spaceInSlot <= 0) {
continue;
@@ -71,39 +71,39 @@ public abstract class AbstractContainer extends Container {
continue;
}
intoStack.grow(from.decrStackSize(itemsMoved).getCount());
into.onSlotChanged();
intoStack.grow(from.remove(itemsMoved).getCount());
into.setChanged();
if (from.getStack().isEmpty()) {
if (from.getItem().isEmpty()) {
break;
}
}
}
for (int i = begin; i >= 0 && i < inventorySlots.size(); i += step) {
if (from.getStack().isEmpty()) {
for (int i = begin; i >= 0 && i < slots.size(); i += step) {
if (from.getItem().isEmpty()) {
break;
}
final Slot into = inventorySlots.get(i);
if (into.inventory == from.inventory) {
final Slot into = slots.get(i);
if (into.container == from.container) {
continue;
}
if (into.getHasStack()) {
if (into.hasItem()) {
continue;
}
if (!into.isItemValid(fromStack)) {
if (!into.mayPlace(fromStack)) {
continue;
}
final int maxSizeInSlot = Math.min(fromStack.getMaxStackSize(), into.getItemStackLimit(fromStack));
final int maxSizeInSlot = Math.min(fromStack.getMaxStackSize(), into.getMaxStackSize(fromStack));
final int itemsMoved = Math.min(maxSizeInSlot, fromStack.getCount());
into.putStack(from.decrStackSize(itemsMoved));
into.set(from.remove(itemsMoved));
}
return from.getStack().getCount() < stack.getCount() ? from.getStack() : ItemStack.EMPTY;
return from.getItem().getCount() < stack.getCount() ? from.getItem() : ItemStack.EMPTY;
}
protected int createPlayerInventoryAndHotbarSlots(final PlayerInventory inventory, final int startX, final int startY) {

View File

@@ -17,7 +17,7 @@ public final class ComputerInventoryContainer extends AbstractContainer {
@Nullable
public static ComputerInventoryContainer create(final int id, final PlayerInventory playerInventory, final PacketBuffer data) {
final BlockPos pos = data.readBlockPos();
final TileEntity tileEntity = playerInventory.player.getEntityWorld().getTileEntity(pos);
final TileEntity tileEntity = playerInventory.player.getCommandSenderWorld().getBlockEntity(pos);
if (!(tileEntity instanceof ComputerTileEntity)) {
return null;
}
@@ -66,7 +66,7 @@ public final class ComputerInventoryContainer extends AbstractContainer {
///////////////////////////////////////////////////////////////////
@Override
public boolean canInteractWith(final PlayerEntity player) {
return isWithinUsableDistance(IWorldPosCallable.of(computer.getWorld(), computer.getPos()), player, Blocks.COMPUTER.get());
public boolean stillValid(final PlayerEntity player) {
return stillValid(IWorldPosCallable.create(computer.getLevel(), computer.getBlockPos()), player, Blocks.COMPUTER.get());
}
}

View File

@@ -21,7 +21,7 @@ public final class ComputerTerminalContainer extends AbstractContainer {
@Nullable
public static ComputerTerminalContainer create(final int id, final PlayerInventory playerInventory, final PacketBuffer data) {
final BlockPos pos = data.readBlockPos();
final TileEntity tileEntity = playerInventory.player.getEntityWorld().getTileEntity(pos);
final TileEntity tileEntity = playerInventory.player.getCommandSenderWorld().getBlockEntity(pos);
if (!(tileEntity instanceof ComputerTileEntity)) {
return null;
}
@@ -42,8 +42,8 @@ public final class ComputerTerminalContainer extends AbstractContainer {
this.computer.addTerminalUser(player);
assertIntArraySize(energyInfo, ENERGY_INFO_SIZE);
trackIntArray(energyInfo);
checkContainerDataCount(energyInfo, ENERGY_INFO_SIZE);
addDataSlots(energyInfo);
}
///////////////////////////////////////////////////////////////////
@@ -65,13 +65,13 @@ public final class ComputerTerminalContainer extends AbstractContainer {
}
@Override
public boolean canInteractWith(final PlayerEntity player) {
return isWithinUsableDistance(IWorldPosCallable.of(computer.getWorld(), computer.getPos()), player, Blocks.COMPUTER.get());
public boolean stillValid(final PlayerEntity player) {
return stillValid(IWorldPosCallable.create(computer.getLevel(), computer.getBlockPos()), player, Blocks.COMPUTER.get());
}
@Override
public void onContainerClosed(final PlayerEntity player) {
super.onContainerClosed(player);
public void removed(final PlayerEntity player) {
super.removed(player);
this.computer.removeTerminalUser(player);
}

View File

@@ -16,7 +16,7 @@ public final class RobotContainer extends AbstractContainer {
@Nullable
public static RobotContainer create(final int id, final PlayerInventory inventory, final PacketBuffer data) {
final int entityId = data.readVarInt();
final Entity entity = inventory.player.getEntityWorld().getEntityByID(entityId);
final Entity entity = inventory.player.getCommandSenderWorld().getEntity(entityId);
if (!(entity instanceof RobotEntity)) {
return null;
}
@@ -76,7 +76,7 @@ public final class RobotContainer extends AbstractContainer {
}
@Override
public boolean canInteractWith(final PlayerEntity player) {
return robot.isEntityInRange(player, 8);
public boolean stillValid(final PlayerEntity player) {
return robot.closerThan(player, 8);
}
}

View File

@@ -21,7 +21,7 @@ public final class RobotTerminalContainer extends AbstractContainer {
@Nullable
public static RobotTerminalContainer create(final int id, final PlayerInventory inventory, final PacketBuffer data) {
final int entityId = data.readVarInt();
final Entity entity = inventory.player.getEntityWorld().getEntityByID(entityId);
final Entity entity = inventory.player.getCommandSenderWorld().getEntity(entityId);
if (!(entity instanceof RobotEntity)) {
return null;
}
@@ -40,8 +40,8 @@ public final class RobotTerminalContainer extends AbstractContainer {
this.robot = robot;
this.energyInfo = energyInfo;
assertIntArraySize(energyInfo, ENERGY_INFO_SIZE);
trackIntArray(energyInfo);
checkContainerDataCount(energyInfo, ENERGY_INFO_SIZE);
addDataSlots(energyInfo);
final ItemStackHandler inventory = robot.getInventory();
for (int slot = 0; slot < inventory.getSlots(); slot++) {
@@ -69,7 +69,7 @@ public final class RobotTerminalContainer extends AbstractContainer {
}
@Override
public boolean canInteractWith(final PlayerEntity player) {
return robot.isEntityInRange(player, 8);
public boolean stillValid(final PlayerEntity player) {
return robot.closerThan(player, 8);
}
}

View File

@@ -23,11 +23,11 @@ public final class TypedSlotItemHandler extends SlotItemHandler {
@Nullable
@Override
public Pair<ResourceLocation, ResourceLocation> getBackground() {
if (getHasStack()) {
return super.getBackground();
public Pair<ResourceLocation, ResourceLocation> getNoItemIcon() {
if (hasItem()) {
return super.getNoItemIcon();
} else {
return Pair.of(PlayerContainer.LOCATION_BLOCKS_TEXTURE, deviceType.getBackgroundIcon());
return Pair.of(PlayerContainer.BLOCK_ATLAS, deviceType.getBackgroundIcon());
}
}
}

View File

@@ -16,7 +16,7 @@ public final class Entities {
///////////////////////////////////////////////////////////////////
public static final RegistryObject<EntityType<RobotEntity>> ROBOT = register("robot", RobotEntity::new, EntityClassification.MISC, b -> b.size(14f / 16f, 14f / 16f).immuneToFire().disableSummoning());
public static final RegistryObject<EntityType<RobotEntity>> ROBOT = register("robot", RobotEntity::new, EntityClassification.MISC, b -> b.sized(14f / 16f, 14f / 16f).fireImmune().noSummon());
///////////////////////////////////////////////////////////////////
@@ -27,6 +27,6 @@ public final class Entities {
///////////////////////////////////////////////////////////////////
private static <T extends Entity> RegistryObject<EntityType<T>> register(final String name, final EntityType.IFactory<T> factory, final EntityClassification classification, final Function<EntityType.Builder<T>, EntityType.Builder<T>> customizer) {
return ENTITIES.register(name, () -> customizer.apply(EntityType.Builder.create(factory, classification)).build(name));
return ENTITIES.register(name, () -> customizer.apply(EntityType.Builder.of(factory, classification)).build(name));
}
}

View File

@@ -81,9 +81,9 @@ import java.util.function.Consumer;
import static li.cil.oc2.common.Constants.*;
public final class RobotEntity extends Entity implements Robot {
public static final DataParameter<BlockPos> TARGET_POSITION = EntityDataManager.createKey(RobotEntity.class, DataSerializers.BLOCK_POS);
public static final DataParameter<Direction> TARGET_DIRECTION = EntityDataManager.createKey(RobotEntity.class, DataSerializers.DIRECTION);
public static final DataParameter<Byte> SELECTED_SLOT = EntityDataManager.createKey(RobotEntity.class, DataSerializers.BYTE);
public static final DataParameter<BlockPos> TARGET_POSITION = EntityDataManager.defineId(RobotEntity.class, DataSerializers.BLOCK_POS);
public static final DataParameter<Direction> TARGET_DIRECTION = EntityDataManager.defineId(RobotEntity.class, DataSerializers.DIRECTION);
public static final DataParameter<Byte> SELECTED_SLOT = EntityDataManager.defineId(RobotEntity.class, DataSerializers.BYTE);
private static final String TERMINAL_TAG_NAME = "terminal";
private static final String STATE_TAG_NAME = "state";
@@ -121,7 +121,7 @@ public final class RobotEntity extends Entity implements Robot {
public RobotEntity(final EntityType<?> type, final World world) {
super(type, world);
this.preventEntitySpawning = true;
this.blocksBuilding = true;
setNoGravity(true);
final CommonDeviceBusController busController = new CommonDeviceBusController(busElement, Config.robotEnergyPerTick);
@@ -157,12 +157,12 @@ public final class RobotEntity extends Entity implements Robot {
@Override
public int getSelectedSlot() {
return getDataManager().get(SELECTED_SLOT);
return getEntityData().get(SELECTED_SLOT);
}
@Override
public void setSelectedSlot(final int value) {
getDataManager().set(SELECTED_SLOT, (byte) MathHelper.clamp(value, 0, INVENTORY_SIZE - 1));
getEntityData().set(SELECTED_SLOT, (byte) MathHelper.clamp(value, 0, INVENTORY_SIZE - 1));
}
@Override
@@ -199,8 +199,8 @@ public final class RobotEntity extends Entity implements Robot {
}
public void start() {
final World world = getEntityWorld();
if (world == null || world.isRemote()) {
final World world = getCommandSenderWorld();
if (world.isClientSide) {
return;
}
@@ -208,8 +208,8 @@ public final class RobotEntity extends Entity implements Robot {
}
public void stop() {
final World world = getEntityWorld();
if (world == null || world.isRemote()) {
final World world = getCommandSenderWorld();
if (world.isClientSide) {
return;
}
@@ -223,18 +223,17 @@ public final class RobotEntity extends Entity implements Robot {
final ItemStack stack = new ItemStack(Items.ROBOT.get());
exportToItemStack(stack);
entityDropItem(stack);
exportToItemStack(stack);
remove();
WorldUtils.playSound(world, getPosition(), SoundType.METAL, SoundType::getBreakSound);
WorldUtils.playSound(level, blockPosition(), SoundType.METAL, SoundType::getBreakSound);
}
@Override
public void tick() {
final World world = getEntityWorld();
final boolean isClient = world.isRemote();
final boolean isClient = level.isClientSide;
if (firstUpdate) {
if (firstTick) {
if (isClient) {
requestInitialState();
} else {
@@ -254,35 +253,35 @@ public final class RobotEntity extends Entity implements Robot {
actionProcessor.tick();
if (!isClient && world instanceof ServerWorld) {
if (!isClient && level instanceof ServerWorld) {
final VoxelShape shape = VoxelShapes.create(getBoundingBox());
final CubeCoordinateIterator iterator = getBlockPosIterator();
while (iterator.hasNext()) {
final int x = iterator.getX();
final int y = iterator.getY();
final int z = iterator.getZ();
mutablePosition.setPos(x, y, z);
final BlockState blockState = world.getBlockState(mutablePosition);
if (blockState.isAir(world, mutablePosition) ||
blockState.isIn(Blocks.MOVING_PISTON) ||
blockState.isIn(Blocks.PISTON_HEAD)) {
while (iterator.advance()) {
final int x = iterator.nextX();
final int y = iterator.nextY();
final int z = iterator.nextZ();
mutablePosition.set(x, y, z);
final BlockState blockState = level.getBlockState(mutablePosition);
if (blockState.isAir(level, mutablePosition) ||
blockState.is(Blocks.MOVING_PISTON) ||
blockState.is(Blocks.PISTON_HEAD)) {
continue;
}
final VoxelShape blockShape = blockState.getCollisionShape(world, mutablePosition);
if (VoxelShapes.compare(shape, blockShape.withOffset(x, y, z), IBooleanFunction.AND)) {
final TileEntity tileEntity = blockState.hasTileEntity() ? world.getTileEntity(mutablePosition) : null;
final LootContext.Builder builder = new LootContext.Builder((ServerWorld) world)
.withRandom(world.rand)
final VoxelShape blockShape = blockState.getCollisionShape(level, mutablePosition);
if (VoxelShapes.joinIsNotEmpty(shape, blockShape.move(x, y, z), IBooleanFunction.AND)) {
final TileEntity tileEntity = blockState.hasTileEntity() ? level.getBlockEntity(mutablePosition) : null;
final LootContext.Builder builder = new LootContext.Builder((ServerWorld) level)
.withRandom(level.random)
.withParameter(LootParameters.THIS_ENTITY, this)
.withParameter(LootParameters.field_237457_g_, getPositionVec())
.withParameter(LootParameters.ORIGIN, position())
.withParameter(LootParameters.TOOL, ItemStack.EMPTY)
.withParameter(LootParameters.BLOCK_STATE, blockState)
.withNullableParameter(LootParameters.BLOCK_ENTITY, tileEntity);
.withOptionalParameter(LootParameters.BLOCK_ENTITY, tileEntity);
final List<ItemStack> drops = blockState.getDrops(builder);
world.setBlockState(mutablePosition, Blocks.AIR.getDefaultState());
level.setBlockAndUpdate(mutablePosition, Blocks.AIR.defaultBlockState());
for (final ItemStack drop : drops) {
Block.spawnAsEntity(world, mutablePosition, drop);
Block.popResource(level, mutablePosition, drop);
}
}
}
@@ -290,17 +289,17 @@ public final class RobotEntity extends Entity implements Robot {
}
@Override
public ActionResultType processInitialInteract(final PlayerEntity player, final Hand hand) {
final ItemStack stack = player.getHeldItem(hand);
if (!world.isRemote()) {
public ActionResultType interact(final PlayerEntity player, final Hand hand) {
final ItemStack stack = player.getItemInHand(hand);
if (!level.isClientSide) {
if (Wrenches.isWrench(stack)) {
if (player.isSneaking()) {
if (player.isShiftKeyDown()) {
dropSelf();
} else if (player instanceof ServerPlayerEntity) {
openContainerScreen((ServerPlayerEntity) player);
}
} else {
if (player.isSneaking()) {
if (player.isShiftKeyDown()) {
start();
} else if (player instanceof ServerPlayerEntity) {
openTerminalScreen((ServerPlayerEntity) player);
@@ -312,7 +311,7 @@ public final class RobotEntity extends Entity implements Robot {
}
@Override
public IPacket<?> createSpawnPacket() {
public IPacket<?> getAddEntityPacket() {
return NetworkHooks.getEntitySpawningPacket(this);
}
@@ -332,21 +331,16 @@ public final class RobotEntity extends Entity implements Robot {
}
@Override
public boolean canCollide(final Entity entity) {
public boolean canCollideWith(final Entity entity) {
return entity != this;
}
@Override
public void applyEntityCollision(final Entity entity) {
public void push(final Entity entity) {
}
@Override
public boolean func_241845_aY() {
return true;
}
@Override
public boolean shouldSpawnRunningEffects() {
public boolean canSpawnSprintParticle() {
return false;
}
@@ -370,15 +364,15 @@ public final class RobotEntity extends Entity implements Robot {
///////////////////////////////////////////////////////////////////
@Override
protected void registerData() {
final EntityDataManager dataManager = getDataManager();
dataManager.register(TARGET_POSITION, BlockPos.ZERO);
dataManager.register(TARGET_DIRECTION, Direction.NORTH);
dataManager.register(SELECTED_SLOT, (byte) 0);
protected void defineSynchedData() {
final EntityDataManager dataManager = getEntityData();
dataManager.set(TARGET_POSITION, BlockPos.ZERO);
dataManager.set(TARGET_DIRECTION, Direction.NORTH);
dataManager.set(SELECTED_SLOT, (byte) 0);
}
@Override
protected void writeAdditional(final CompoundNBT tag) {
protected void addAdditionalSaveData(final CompoundNBT tag) {
tag.put(STATE_TAG_NAME, virtualMachine.serialize());
tag.put(TERMINAL_TAG_NAME, NBTSerialization.serialize(terminal));
tag.put(COMMAND_PROCESSOR_TAG_NAME, actionProcessor.serialize());
@@ -386,11 +380,11 @@ public final class RobotEntity extends Entity implements Robot {
tag.put(Constants.ITEMS_TAG_NAME, deviceItems.serialize());
tag.put(ENERGY_TAG_NAME, energy.serializeNBT());
tag.put(INVENTORY_TAG_NAME, inventory.serializeNBT());
tag.putByte(SELECTED_SLOT_TAG_NAME, dataManager.get(SELECTED_SLOT));
tag.putByte(SELECTED_SLOT_TAG_NAME, getEntityData().get(SELECTED_SLOT));
}
@Override
protected void readAdditional(final CompoundNBT tag) {
protected void readAdditionalSaveData(final CompoundNBT tag) {
virtualMachine.deserialize(tag.getCompound(STATE_TAG_NAME));
NBTSerialization.deserialize(tag.getCompound(TERMINAL_TAG_NAME), terminal);
actionProcessor.deserialize(tag.getCompound(COMMAND_PROCESSOR_TAG_NAME));
@@ -402,18 +396,19 @@ public final class RobotEntity extends Entity implements Robot {
}
@Override
protected boolean canTriggerWalking() {
protected boolean isMovementNoisy() {
return false;
}
@Override
protected void doBlockCollisions() {
protected void checkInsideBlocks() {
}
@Override
protected Vector3d handlePistonMovement(final Vector3d pos) {
lastPistonMovement = getEntityWorld().getGameTime();
return super.handlePistonMovement(pos);
protected Vector3d limitPistonMovement(final Vector3d pos) {
lastPistonMovement = getCommandSenderWorld().getGameTime();
return super.limitPistonMovement(pos);
}
///////////////////////////////////////////////////////////////////
@@ -434,11 +429,11 @@ public final class RobotEntity extends Entity implements Robot {
}
private void handleChunkUnload(final ChunkEvent.Unload event) {
if (event.getWorld() != getEntityWorld()) {
if (event.getWorld() != getCommandSenderWorld()) {
return;
}
final ChunkPos chunkPos = new ChunkPos(getPosition());
final ChunkPos chunkPos = new ChunkPos(blockPosition());
if (!Objects.equals(chunkPos, event.getChunk().getPos())) {
return;
}
@@ -448,7 +443,7 @@ public final class RobotEntity extends Entity implements Robot {
}
private void handleWorldUnload(final WorldEvent.Unload event) {
if (event.getWorld() != getEntityWorld()) {
if (event.getWorld() != getCommandSenderWorld()) {
return;
}
@@ -489,12 +484,10 @@ public final class RobotEntity extends Entity implements Robot {
}
@Override
public int size() {
return 3;
}
public int getCount() { return 3; }
});
}
}, b -> b.writeVarInt(getEntityId()));
}, b -> b.writeVarInt(getId()));
}
private void openContainerScreen(final ServerPlayerEntity player) {
@@ -508,7 +501,7 @@ public final class RobotEntity extends Entity implements Robot {
public Container createMenu(final int id, final PlayerInventory inventory, final PlayerEntity player) {
return new RobotContainer(id, RobotEntity.this, inventory);
}
}, b -> b.writeVarInt(getEntityId()));
}, b -> b.writeVarInt(getId()));
}
private CubeCoordinateIterator getBlockPosIterator() {
@@ -639,7 +632,7 @@ public final class RobotEntity extends Entity implements Robot {
}
public void tick() {
if (getEntityWorld().isRemote()) {
if (getCommandSenderWorld().isClientSide) {
RobotActions.performClient(RobotEntity.this);
} else {
if (action != null) {
@@ -722,7 +715,7 @@ public final class RobotEntity extends Entity implements Robot {
}
private boolean addAction(final AbstractRobotAction action) {
if (getEntityWorld().isRemote()) {
if (getCommandSenderWorld().isClientSide) {
return false;
}
@@ -785,13 +778,13 @@ public final class RobotEntity extends Entity implements Robot {
public CompoundNBT serialize() {
final CompoundNBT tag = new CompoundNBT();
tag.putUniqueId(DEVICE_ID_TAG_NAME, deviceId);
tag.putUUID(DEVICE_ID_TAG_NAME, deviceId);
return tag;
}
public void deserialize(final CompoundNBT tag) {
if (tag.hasUniqueId(DEVICE_ID_TAG_NAME)) {
deviceId = tag.getUniqueId(DEVICE_ID_TAG_NAME);
if (tag.hasUUID(DEVICE_ID_TAG_NAME)) {
deviceId = tag.getUUID(DEVICE_ID_TAG_NAME);
}
}
}

View File

@@ -50,12 +50,12 @@ public final class RobotMovementAction extends AbstractRobotAction {
///////////////////////////////////////////////////////////////////
public static Vector3d getTargetPositionInBlock(final BlockPos position) {
return Vector3d.copyCenteredHorizontally(position).add(0, 0.5f * (1 - Entities.ROBOT.get().getHeight()), 0);
return Vector3d.atBottomCenterOf(position).add(0, 0.5f * (1 - Entities.ROBOT.get().getHeight()), 0);
}
public static void moveTowards(final RobotEntity robot, final Vector3d targetPosition) {
Vector3d delta = targetPosition.subtract(robot.getPositionVec());
if (delta.lengthSquared() > MOVEMENT_SPEED * MOVEMENT_SPEED) {
Vector3d delta = targetPosition.subtract(robot.position());
if (delta.lengthSqr() > MOVEMENT_SPEED * MOVEMENT_SPEED) {
delta = delta.normalize().scale(MOVEMENT_SPEED);
}
@@ -67,27 +67,27 @@ public final class RobotMovementAction extends AbstractRobotAction {
@Override
public void initialize(final RobotEntity robot) {
if (origin == null || start == null || target == null) {
origin = robot.getPosition();
origin = robot.blockPosition();
start = origin;
target = start;
switch (direction) {
case UP:
target = target.offset(Direction.UP);
target = target.relative(Direction.UP);
break;
case DOWN:
target = target.offset(Direction.DOWN);
target = target.relative(Direction.DOWN);
break;
case FORWARD:
target = target.offset(robot.getHorizontalFacing());
target = target.relative(robot.getDirection());
break;
case BACKWARD:
target = target.offset(robot.getHorizontalFacing().getOpposite());
target = target.relative(robot.getDirection().getOpposite());
break;
}
}
targetPos = getTargetPositionInBlock(target);
robot.getDataManager().set(RobotEntity.TARGET_POSITION, target);
robot.getEntityData().set(RobotEntity.TARGET_POSITION, target);
}
@Override
@@ -100,7 +100,7 @@ public final class RobotMovementAction extends AbstractRobotAction {
moveAndResolveCollisions(robot);
if (robot.getPositionVec().squareDistanceTo(targetPos) < TARGET_EPSILON) {
if (robot.position().distanceToSqr(targetPos) < TARGET_EPSILON) {
if (Objects.equals(target, origin)) {
return RobotActionResult.FAILURE; // Collided and returned.
} else {
@@ -149,20 +149,20 @@ public final class RobotMovementAction extends AbstractRobotAction {
private void moveAndResolveCollisions(final RobotEntity robot) {
moveTowards(robot, targetPos);
final boolean didCollide = robot.collidedHorizontally || robot.collidedVertically;
final long gameTime = robot.getEntityWorld().getGameTime();
if (didCollide && !robot.getEntityWorld().isRemote()
final boolean didCollide = robot.horizontalCollision || robot.verticalCollision;
final long gameTime = robot.level.getGameTime();
if (didCollide && !robot.level.isClientSide
&& robot.getLastPistonMovement() < gameTime - 1) {
final BlockPos newStart = target;
target = start;
start = newStart;
targetPos = getTargetPositionInBlock(target);
robot.getDataManager().set(RobotEntity.TARGET_POSITION, target);
robot.getEntityData().set(RobotEntity.TARGET_POSITION, target);
}
}
private void validateTarget(final RobotEntity robot) {
final BlockPos currentPosition = robot.getPosition();
final BlockPos currentPosition = robot.blockPosition();
if (Objects.equals(currentPosition, start) || Objects.equals(currentPosition, target)) {
return;
}
@@ -176,13 +176,13 @@ public final class RobotMovementAction extends AbstractRobotAction {
if (deltaStart < deltaTarget) {
start = currentPosition;
target = target.add(fromStart);
target = target.offset(fromStart);
} else {
start = start.add(fromTarget);
start = start.offset(fromTarget);
target = currentPosition;
}
targetPos = getTargetPositionInBlock(target);
robot.getDataManager().set(RobotEntity.TARGET_POSITION, target);
robot.getEntityData().set(RobotEntity.TARGET_POSITION, target);
}
}

View File

@@ -13,20 +13,20 @@ public final class RobotMovementActionType extends AbstractRobotActionType {
@Override
public void initializeData(final RobotEntity robot) {
robot.getDataManager().set(RobotEntity.TARGET_POSITION, robot.getPosition());
robot.getEntityData().set(RobotEntity.TARGET_POSITION, robot.blockPosition());
}
@Override
public void performServer(final RobotEntity robot, final AbstractRobotAction currentAction) {
if (!(currentAction instanceof RobotMovementAction)) {
robot.getDataManager().set(RobotEntity.TARGET_POSITION, robot.getPosition());
robot.getEntityData().set(RobotEntity.TARGET_POSITION, robot.blockPosition());
}
}
@Override
public void performClient(final RobotEntity robot) {
final Vector3d target = RobotMovementAction.getTargetPositionInBlock(robot.getDataManager().get(RobotEntity.TARGET_POSITION));
if (robot.getPositionVec().squareDistanceTo(target) > RobotMovementAction.TARGET_EPSILON) {
final Vector3d target = RobotMovementAction.getTargetPositionInBlock(robot.getEntityData().get(RobotEntity.TARGET_POSITION));
if (robot.position().distanceToSqr(target) > RobotMovementAction.TARGET_EPSILON) {
RobotMovementAction.moveTowards(robot, target);
}
}

View File

@@ -40,7 +40,7 @@ public final class RobotRotationAction extends AbstractRobotAction {
///////////////////////////////////////////////////////////////////
public static void rotateTowards(final RobotEntity robot, final Direction targetRotation) {
robot.rotationYaw = MathHelper.approachDegrees(robot.rotationYaw, targetRotation.getHorizontalAngle(), ROTATION_SPEED);
robot.yRot = MathHelper.approachDegrees(robot.yRot, targetRotation.toYRot(), ROTATION_SPEED);
}
///////////////////////////////////////////////////////////////////
@@ -48,18 +48,18 @@ public final class RobotRotationAction extends AbstractRobotAction {
@Override
public void initialize(final RobotEntity robot) {
if (target == null) {
target = robot.getHorizontalFacing();
target = robot.getDirection();
switch (direction) {
case LEFT:
target = target.rotateYCCW();
target = target.getCounterClockWise();
break;
case RIGHT:
target = target.rotateY();
target = target.getClockWise();
break;
}
}
robot.getDataManager().set(RobotEntity.TARGET_DIRECTION, target);
robot.getEntityData().set(RobotEntity.TARGET_DIRECTION, target);
}
@Override
@@ -70,7 +70,7 @@ public final class RobotRotationAction extends AbstractRobotAction {
rotateTowards(robot, target);
if (MathHelper.degreesDifferenceAbs(robot.rotationYaw, target.getHorizontalAngle()) < TARGET_EPSILON) {
if (MathHelper.degreesDifferenceAbs(robot.yRot, target.toYRot()) < TARGET_EPSILON) {
return RobotActionResult.SUCCESS;
}

View File

@@ -14,20 +14,20 @@ public final class RobotRotationActionType extends AbstractRobotActionType {
@Override
public void initializeData(final RobotEntity robot) {
robot.getDataManager().set(RobotEntity.TARGET_DIRECTION, robot.getHorizontalFacing());
robot.getEntityData().set(RobotEntity.TARGET_DIRECTION, robot.getDirection());
}
@Override
public void performServer(final RobotEntity robot, final AbstractRobotAction currentAction) {
if (!(currentAction instanceof RobotRotationAction)) {
robot.getDataManager().set(RobotEntity.TARGET_DIRECTION, robot.getHorizontalFacing());
robot.getEntityData().set(RobotEntity.TARGET_DIRECTION, robot.getDirection());
}
}
@Override
public void performClient(final RobotEntity robot) {
final Direction target = robot.getDataManager().get(RobotEntity.TARGET_DIRECTION);
if (MathHelper.degreesDifferenceAbs(robot.rotationYaw, target.getHorizontalAngle()) > RobotRotationAction.TARGET_EPSILON) {
final Direction target = robot.getEntityData().get(RobotEntity.TARGET_DIRECTION);
if (MathHelper.degreesDifferenceAbs(robot.yRot, target.toYRot()) > RobotRotationAction.TARGET_EPSILON) {
RobotRotationAction.rotateTowards(robot, target);
}
}

View File

@@ -13,11 +13,11 @@ public final class Wrenches {
}
public static boolean isWrench(final Item item) {
return item.isIn(ItemTags.WRENCHES);
return item.is(ItemTags.WRENCHES);
}
public static boolean isHoldingWrench(final Entity entity) {
for (final ItemStack stack : entity.getHeldEquipment()) {
for (final ItemStack stack : entity.getHandSlots()) {
if (isWrench(stack.getItem())) {
return true;
}

View File

@@ -22,7 +22,7 @@ public abstract class AbstractBlockDeviceItem extends ModItem {
///////////////////////////////////////////////////////////////////
protected AbstractBlockDeviceItem(final Properties properties, final ResourceLocation defaultData) {
super(properties.maxStackSize(1));
super(properties.stacksTo(1));
this.defaultData = defaultData;
}
@@ -71,16 +71,16 @@ public abstract class AbstractBlockDeviceItem extends ModItem {
}
@Override
public ITextComponent getDisplayName(final ItemStack stack) {
public ITextComponent getName(final ItemStack stack) {
final BlockDeviceData data = getData(stack);
if (data != null) {
return new StringTextComponent("")
.append(super.getDisplayName(stack))
.appendString(" (")
.append(super.getName(stack))
.append(" (")
.append(data.getDisplayName())
.appendString(")");
.append(")");
} else {
return super.getDisplayName(stack);
return super.getName(stack);
}
}
}

View File

@@ -47,12 +47,12 @@ public abstract class AbstractStorageItem extends ModItem {
}
@Override
public ITextComponent getDisplayName(final ItemStack stack) {
public ITextComponent getName(final ItemStack stack) {
final int capacity = getCapacity(stack);
return new StringTextComponent("")
.append(super.getDisplayName(stack))
.appendString(" (")
.appendString(TextFormatUtils.formatSize(capacity))
.appendString(")");
.append(super.getName(stack))
.append(" (")
.append(TextFormatUtils.formatSize(capacity))
.append(")");
}
}

View File

@@ -6,6 +6,6 @@ public final class BlockOperationsModule extends ModItem {
///////////////////////////////////////////////////////////////////
public BlockOperationsModule() {
super(createProperties().maxDamage(DURABILITY));
super(createProperties().durability(DURABILITY));
}
}

View File

@@ -34,21 +34,21 @@ public final class BusCableItem extends ModBlockItem {
@OnlyIn(Dist.CLIENT)
@Override
public void addInformation(final ItemStack stack, final @Nullable World world, final List<ITextComponent> tooltip, final ITooltipFlag flag) {
super.addInformation(stack, world, tooltip, flag);
public void appendHoverText(final ItemStack stack, final @Nullable World world, final List<ITextComponent> tooltip, final ITooltipFlag flag) {
super.appendHoverText(stack, world, tooltip, flag);
TooltipUtils.addEnergyConsumption(Config.busCableEnergyPerTick, tooltip);
}
@Override
public ActionResultType onItemUse(final ItemUseContext context) {
public ActionResultType useOn(final ItemUseContext context) {
final ActionResultType result = tryAddToBlock(context);
return result.isSuccessOrConsume() ? result : super.onItemUse(context);
return result.consumesAction() ? result : super.useOn(context);
}
@Override
public ActionResultType tryPlace(final BlockItemUseContext context) {
public ActionResultType place(final BlockItemUseContext context) {
final ActionResultType result = tryAddToBlock(context);
return result.isSuccessOrConsume() ? result : super.tryPlace(context);
return result.consumesAction() ? result : super.place(context);
}
///////////////////////////////////////////////////////////////////
@@ -56,13 +56,13 @@ public final class BusCableItem extends ModBlockItem {
private ActionResultType tryAddToBlock(final ItemUseContext context) {
final BusCableBlock busCableBlock = Blocks.BUS_CABLE.get();
final World world = context.getWorld();
final BlockPos pos = context.getPos();
final World world = context.getLevel();
final BlockPos pos = context.getClickedPos();
final BlockState state = world.getBlockState(pos);
if (state.getBlock() == busCableBlock && busCableBlock.addCable(world, pos, state)) {
final PlayerEntity player = context.getPlayer();
final ItemStack stack = context.getItem();
final ItemStack stack = context.getItemInHand();
if (player instanceof ServerPlayerEntity) {
CriteriaTriggers.PLACED_BLOCK.trigger((ServerPlayerEntity) player, pos, stack);
@@ -70,11 +70,11 @@ public final class BusCableItem extends ModBlockItem {
WorldUtils.playSound(world, pos, state.getSoundType(world, pos, player), SoundType::getPlaceSound);
if (player == null || !player.abilities.isCreativeMode) {
if (player == null || !player.abilities.instabuild) {
stack.shrink(1);
}
return ActionResultType.func_233537_a_(world.isRemote);
return ActionResultType.sidedSuccess(world.isClientSide);
}
return ActionResultType.PASS;

View File

@@ -39,39 +39,39 @@ public final class BusInterfaceItem extends ModBlockItem {
@OnlyIn(Dist.CLIENT)
@Override
public void addInformation(final ItemStack stack, final @Nullable World world, final List<ITextComponent> tooltip, final ITooltipFlag flag) {
super.addInformation(stack, world, tooltip, flag);
public void appendHoverText(final ItemStack stack, final @Nullable World world, final List<ITextComponent> tooltip, final ITooltipFlag flag) {
super.appendHoverText(stack, world, tooltip, flag);
TooltipUtils.addEnergyConsumption(Config.busInterfaceEnergyPerTick, tooltip);
}
@Override
public ActionResultType onItemUse(final ItemUseContext context) {
final Vector3d localHitPos = context.getHitVec().subtract(Vector3d.copyCentered(context.getPos()));
final Direction side = Direction.getFacingFromVector(localHitPos.x, localHitPos.y, localHitPos.z);
public ActionResultType useOn(final ItemUseContext context) {
final Vector3d localHitPos = context.getClickLocation().subtract(Vector3d.atCenterOf(context.getClickedPos()));
final Direction side = Direction.getNearest(localHitPos.x, localHitPos.y, localHitPos.z);
final ActionResultType result = tryAddToBlock(context, side);
return result.isSuccessOrConsume() ? result : super.onItemUse(context);
return result.consumesAction() ? result : super.useOn(context);
}
@Override
public ActionResultType tryPlace(final BlockItemUseContext context) {
final ActionResultType result = tryAddToBlock(context, context.getFace().getOpposite());
return result.isSuccessOrConsume() ? result : super.tryPlace(context);
public ActionResultType place(final BlockItemUseContext context) {
final ActionResultType result = tryAddToBlock(context, context.getClickedFace().getOpposite());
return result.consumesAction() ? result : super.place(context);
}
@Override
public String getTranslationKey() {
return getDefaultTranslationKey();
public String getDescriptionId() {
return getOrCreateDescriptionId();
}
@Override
public void fillItemGroup(final ItemGroup group, final NonNullList<ItemStack> items) {
if (isInGroup(group)) {
public void fillItemCategory(final ItemGroup group, final NonNullList<ItemStack> items) {
if (allowdedIn(group)) {
items.add(new ItemStack(this));
}
}
@Override
public void addToBlockToItemMap(final Map<Block, Item> map, final Item item) {
public void registerBlocks(final Map<Block, Item> map, final Item item) {
}
@Override
@@ -82,13 +82,13 @@ public final class BusInterfaceItem extends ModBlockItem {
@Nullable
@Override
protected BlockState getStateForPlacement(final BlockItemUseContext context) {
final BlockState state = super.getStateForPlacement(context);
protected BlockState getPlacementState(final BlockItemUseContext context) {
final BlockState state = super.getPlacementState(context);
final EnumProperty<ConnectionType> connectionTypeProperty =
BusCableBlock.FACING_TO_CONNECTION_MAP.get(context.getFace().getOpposite());
BusCableBlock.FACING_TO_CONNECTION_MAP.get(context.getClickedFace().getOpposite());
return state
.with(BusCableBlock.HAS_CABLE, false)
.with(connectionTypeProperty, ConnectionType.INTERFACE);
.setValue(BusCableBlock.HAS_CABLE, false)
.setValue(connectionTypeProperty, ConnectionType.INTERFACE);
}
///////////////////////////////////////////////////////////////////
@@ -96,13 +96,13 @@ public final class BusInterfaceItem extends ModBlockItem {
private ActionResultType tryAddToBlock(final ItemUseContext context, final Direction side) {
final BusCableBlock busCableBlock = Blocks.BUS_CABLE.get();
final World world = context.getWorld();
final BlockPos pos = context.getPos();
final World world = context.getLevel();
final BlockPos pos = context.getClickedPos();
final BlockState state = world.getBlockState(pos);
if (state.getBlock() == busCableBlock && busCableBlock.addInterface(world, pos, state, side)) {
final PlayerEntity player = context.getPlayer();
final ItemStack stack = context.getItem();
final ItemStack stack = context.getItemInHand();
if (player instanceof ServerPlayerEntity) {
CriteriaTriggers.PLACED_BLOCK.trigger((ServerPlayerEntity) player, pos, stack);
@@ -110,11 +110,11 @@ public final class BusInterfaceItem extends ModBlockItem {
WorldUtils.playSound(world, pos, state.getSoundType(world, pos, player), SoundType::getPlaceSound);
if (player == null || !player.abilities.isCreativeMode) {
if (player == null || !player.abilities.instabuild) {
stack.shrink(1);
}
return ActionResultType.func_233537_a_(world.isRemote);
return ActionResultType.sidedSuccess(world.isClientSide);
}
return ActionResultType.PASS;

View File

@@ -14,9 +14,9 @@ public final class ChargerItem extends ModBlockItem {
///////////////////////////////////////////////////////////////////
@Override
public void fillItemGroup(final ItemGroup group, final NonNullList<ItemStack> items) {
public void fillItemCategory(final ItemGroup group, final NonNullList<ItemStack> items) {
if (Config.chargerUseEnergy()) {
super.fillItemGroup(group, items);
super.fillItemCategory(group, items);
}
}
}

View File

@@ -10,7 +10,7 @@ import javax.annotation.Nullable;
public final class FlashMemoryItem extends AbstractStorageItem {
public FlashMemoryItem(final int defaultCapacity) {
super(createProperties().maxStackSize(1), defaultCapacity);
super(createProperties().stacksTo(1), defaultCapacity);
}
///////////////////////////////////////////////////////////////////
@@ -28,7 +28,7 @@ public final class FlashMemoryItem extends AbstractStorageItem {
///////////////////////////////////////////////////////////////////
@Override
protected String getDefaultTranslationKey() {
protected String getOrCreateDescriptionId() {
return "item.oc2.flash_memory";
}
}

View File

@@ -22,7 +22,7 @@ public final class FlashMemoryWithExternalDataItem extends ModItem {
///////////////////////////////////////////////////////////////////
public FlashMemoryWithExternalDataItem(final ResourceLocation defaultData) {
super(createProperties().maxStackSize(1));
super(createProperties().stacksTo(1));
this.defaultData = defaultData;
}
@@ -67,23 +67,23 @@ public final class FlashMemoryWithExternalDataItem extends ModItem {
}
@Override
public ITextComponent getDisplayName(final ItemStack stack) {
public ITextComponent getName(final ItemStack stack) {
final Firmware firmware = getFirmware(stack);
if (firmware != null) {
return new StringTextComponent("")
.append(super.getDisplayName(stack))
.appendString(" (")
.append(super.getName(stack))
.append(" (")
.append(firmware.getDisplayName())
.appendString(")");
.append(")");
} else {
return super.getDisplayName(stack);
return super.getName(stack);
}
}
///////////////////////////////////////////////////////////////////
@Override
protected String getDefaultTranslationKey() {
protected String getOrCreateDescriptionId() {
return "item.oc2.flash_memory";
}
}

View File

@@ -18,13 +18,13 @@ public final class HardDriveItem extends AbstractStorageItem implements IDyeable
@Override
public int getColor(final ItemStack stack) {
return hasColor(stack) ? IDyeableArmorItem.super.getColor(stack) : defaultColor;
return hasCustomColor(stack) ? IDyeableArmorItem.super.getColor(stack) : defaultColor;
}
///////////////////////////////////////////////////////////////////
@Override
protected String getDefaultTranslationKey() {
protected String getOrCreateDescriptionId() {
return "item.oc2.hard_drive";
}
}

View File

@@ -19,13 +19,13 @@ public final class HardDriveWithExternalDataItem extends AbstractBlockDeviceItem
@Override
public int getColor(final ItemStack stack) {
return hasColor(stack) ? IDyeableArmorItem.super.getColor(stack) : defaultColor;
return hasCustomColor(stack) ? IDyeableArmorItem.super.getColor(stack) : defaultColor;
}
///////////////////////////////////////////////////////////////////
@Override
protected String getDefaultTranslationKey() {
protected String getOrCreateDescriptionId() {
return "item.oc2.hard_drive";
}
}

View File

@@ -6,7 +6,7 @@ import net.minecraft.item.ItemStack;
public final class ItemGroup {
public static final net.minecraft.item.ItemGroup COMMON = new net.minecraft.item.ItemGroup(API.MOD_ID + ".common") {
@Override
public ItemStack createIcon() {
public ItemStack makeIcon() {
return new ItemStack(Items.COMPUTER.get());
}
};

View File

@@ -8,7 +8,8 @@ public final class MemoryItem extends AbstractStorageItem {
///////////////////////////////////////////////////////////////////
@Override
protected String getDefaultTranslationKey() {
protected String getOrCreateDescriptionId() {
return "item.oc2.memory";
}
}

View File

@@ -15,7 +15,7 @@ import java.util.List;
public class ModBlockItem extends BlockItem {
public ModBlockItem(final Block block, final Properties properties) {
super(block, properties.group(ItemGroup.COMMON));
super(block, properties.tab(ItemGroup.COMMON));
}
public ModBlockItem(final Block block) {
@@ -26,9 +26,9 @@ public class ModBlockItem extends BlockItem {
@OnlyIn(Dist.CLIENT)
@Override
public void addInformation(final ItemStack stack, @Nullable final World world, final List<ITextComponent> tooltip, final ITooltipFlag flag) {
public void appendHoverText(final ItemStack stack, @Nullable final World world, final List<ITextComponent> tooltip, final ITooltipFlag flag) {
TooltipUtils.tryAddDescription(stack, tooltip);
super.addInformation(stack, world, tooltip, flag);
super.appendHoverText(stack, world, tooltip, flag);
}
///////////////////////////////////////////////////////////////////

View File

@@ -14,7 +14,7 @@ import java.util.List;
public class ModItem extends Item {
public ModItem(final Properties properties) {
super(properties.group(ItemGroup.COMMON));
super(properties.tab(ItemGroup.COMMON));
}
public ModItem() {
@@ -25,8 +25,8 @@ public class ModItem extends Item {
@OnlyIn(Dist.CLIENT)
@Override
public void addInformation(final ItemStack stack, @Nullable final World world, final List<ITextComponent> tooltip, final ITooltipFlag flag) {
super.addInformation(stack, world, tooltip, flag);
public void appendHoverText(final ItemStack stack, @Nullable final World world, final List<ITextComponent> tooltip, final ITooltipFlag flag) {
super.appendHoverText(stack, world, tooltip, flag);
TooltipUtils.tryAddDescription(stack, tooltip);
}

View File

@@ -24,51 +24,51 @@ public final class NetworkCableItem extends ModItem {
///////////////////////////////////////////////////////////////////
@Override
public ActionResult<ItemStack> onItemRightClick(final World world, final PlayerEntity player, final Hand hand) {
if (player.isSneaking()) {
public ActionResult<ItemStack> use(final World world, final PlayerEntity player, final Hand hand) {
if (player.isShiftKeyDown()) {
if (player instanceof ServerPlayerEntity) {
LINK_STARTS.remove(player);
}
return ActionResult.resultSuccess(player.getHeldItem(hand));
return ActionResult.success(player.getItemInHand(hand));
}
return super.onItemRightClick(world, player, hand);
return super.use(world, player, hand);
}
@Override
public ActionResultType onItemUse(final ItemUseContext context) {
public ActionResultType useOn(final ItemUseContext context) {
final PlayerEntity player = context.getPlayer();
if (player == null) {
return super.onItemUse(context);
return super.useOn(context);
}
final ItemStack stack = player.getHeldItem(context.getHand());
final ItemStack stack = player.getItemInHand(context.getHand());
if (stack.isEmpty() || stack.getItem() != this) {
return super.onItemUse(context);
return super.useOn(context);
}
final World world = context.getWorld();
final BlockPos currentPos = context.getPos();
final World world = context.getLevel();
final BlockPos currentPos = context.getClickedPos();
final TileEntity currentTileEntity = world.getTileEntity(currentPos);
final TileEntity currentTileEntity = world.getBlockEntity(currentPos);
if (!(currentTileEntity instanceof NetworkConnectorTileEntity)) {
return super.onItemUse(context);
return super.useOn(context);
}
if (!world.isRemote() && player instanceof ServerPlayerEntity) {
if (!world.isClientSide && player instanceof ServerPlayerEntity) {
final BlockPos startPos = LINK_STARTS.remove(player);
if (startPos == null || Objects.equals(startPos, currentPos)) {
if (((NetworkConnectorTileEntity) currentTileEntity).canConnectMore()) {
LINK_STARTS.put((ServerPlayerEntity) player, currentPos);
} else {
player.sendStatusMessage(new TranslationTextComponent(Constants.CONNECTOR_ERROR_FULL), true);
player.displayClientMessage(new TranslationTextComponent(Constants.CONNECTOR_ERROR_FULL), true);
}
} else {
final TileEntity startTileEntity = world.getTileEntity(startPos);
final TileEntity startTileEntity = world.getBlockEntity(startPos);
if (!(startTileEntity instanceof NetworkConnectorTileEntity)) {
// Starting connector was removed in the meantime.
return super.onItemUse(context);
return super.useOn(context);
}
final NetworkConnectorTileEntity connectorA = (NetworkConnectorTileEntity) startTileEntity;
@@ -87,15 +87,15 @@ public final class NetworkCableItem extends ModItem {
break;
case FAILURE_FULL:
LINK_STARTS.put((ServerPlayerEntity) player, startPos);
player.sendStatusMessage(new TranslationTextComponent(Constants.CONNECTOR_ERROR_FULL), true);
player.displayClientMessage(new TranslationTextComponent(Constants.CONNECTOR_ERROR_FULL), true);
break;
case FAILURE_TOO_FAR:
LINK_STARTS.put((ServerPlayerEntity) player, startPos);
player.sendStatusMessage(new TranslationTextComponent(Constants.CONNECTOR_ERROR_TOO_FAR), true);
player.displayClientMessage(new TranslationTextComponent(Constants.CONNECTOR_ERROR_TOO_FAR), true);
break;
case FAILURE_OBSTRUCTED:
LINK_STARTS.put((ServerPlayerEntity) player, startPos);
player.sendStatusMessage(new TranslationTextComponent(Constants.CONNECTOR_ERROR_OBSTRUCTED), true);
player.displayClientMessage(new TranslationTextComponent(Constants.CONNECTOR_ERROR_OBSTRUCTED), true);
break;
}
}

View File

@@ -37,8 +37,8 @@ public final class RobotItem extends ModItem {
///////////////////////////////////////////////////////////////////
@Override
public void addInformation(final ItemStack stack, @Nullable final World world, final List<ITextComponent> tooltip, final ITooltipFlag flag) {
super.addInformation(stack, world, tooltip, flag);
public void appendHoverText(final ItemStack stack, @Nullable final World world, final List<ITextComponent> tooltip, final ITooltipFlag flag) {
super.appendHoverText(stack, world, tooltip, flag);
TooltipUtils.addEnergyConsumption(Config.robotEnergyPerTick, tooltip);
TooltipUtils.addEntityEnergyInformation(stack, tooltip);
TooltipUtils.addEntityInventoryInformation(stack, tooltip);
@@ -55,37 +55,37 @@ public final class RobotItem extends ModItem {
}
@Override
public ActionResultType onItemUse(final ItemUseContext context) {
final World world = context.getWorld();
final BlockPos pos = context.getPos();
public ActionResultType useOn(final ItemUseContext context) {
final World world = context.getLevel();
final BlockPos pos = context.getClickedPos();
final Vector3d position;
if (world.getBlockState(pos).isReplaceable(new BlockItemUseContext(context))) {
position = Vector3d.copyCentered(pos);
if (world.getBlockState(pos).canBeReplaced(new BlockItemUseContext(context))) {
position = Vector3d.atCenterOf(pos);
} else {
position = Vector3d.copyCentered(pos.offset(context.getFace()));
position = Vector3d.atCenterOf(pos.relative(context.getClickedFace()));
}
final RobotEntity robot = Entities.ROBOT.get().create(context.getWorld());
robot.setLocationAndAngles(position.getX(), position.getY() - robot.getHeight() * 0.5f, position.getZ(),
Direction.fromAngle(context.getPlacementYaw()).getOpposite().getHorizontalAngle(), 0);
if (!world.hasNoCollisions(robot)) {
return super.onItemUse(context);
final RobotEntity robot = Entities.ROBOT.get().create(context.getLevel());
robot.moveTo(position.x, position.y - robot.getEyeHeight() * 0.5f, position.z,
Direction.fromYRot(context.getRotation()).getOpposite().toYRot(), 0);
if (!world.noCollision(robot)) {
return super.useOn(context);
}
if (!world.isRemote()) {
if (!world.isClientSide) {
RobotActions.initializeData(robot);
robot.importFromItemStack(context.getItem());
robot.importFromItemStack(context.getItemInHand());
world.addEntity(robot);
world.addFreshEntity(robot);
WorldUtils.playSound(world, new BlockPos(position), SoundType.METAL, SoundType::getPlaceSound);
if (!context.getPlayer().isCreative()) {
context.getItem().shrink(1);
context.getItemInHand().shrink(1);
}
}
context.getPlayer().addStat(Stats.ITEM_USED.get(this));
context.getPlayer().awardStat(Stats.ITEM_USED.get(this));
return ActionResultType.SUCCESS;
}

View File

@@ -14,26 +14,26 @@ import net.minecraft.world.World;
public final class WrenchItem extends ModItem {
@Override
public ActionResultType onItemUse(final ItemUseContext context) {
public ActionResultType useOn(final ItemUseContext context) {
final PlayerEntity player = context.getPlayer();
if (!player.isSneaking()) {
return super.onItemUse(context);
if (!player.isShiftKeyDown()) {
return super.useOn(context);
}
final World world = context.getWorld();
final BlockPos pos = context.getPos();
final World world = context.getLevel();
final BlockPos pos = context.getClickedPos();
final BlockState state = world.getBlockState(pos);
if (!state.isIn(BlockTags.WRENCH_BREAKABLE)) {
return super.onItemUse(context);
if (!state.is(BlockTags.WRENCH_BREAKABLE)) {
return super.useOn(context);
}
if (world.isRemote()) {
Minecraft.getInstance().playerController.onPlayerDestroyBlock(pos);
if (world.isClientSide) {
Minecraft.getInstance().gameMode.destroyBlock(pos);
} else if (player instanceof ServerPlayerEntity) {
((ServerPlayerEntity) player).interactionManager.tryHarvestBlock(pos);
((ServerPlayerEntity) player).gameMode.destroyBlock(pos);
}
return ActionResultType.func_233537_a_(world.isRemote);
return ActionResultType.sidedSuccess(world.isClientSide);
}
@Override

View File

@@ -14,15 +14,15 @@ import org.jetbrains.annotations.Nullable;
public final class WrenchRecipe extends ShapelessRecipe {
public WrenchRecipe(final ShapelessRecipe recipe) {
super(recipe.getId(), recipe.getGroup(), recipe.getRecipeOutput(), recipe.getIngredients());
super(recipe.getId(), recipe.getGroup(), recipe.getResultItem(), recipe.getIngredients());
}
@Override
public NonNullList<ItemStack> getRemainingItems(final CraftingInventory inventory) {
final NonNullList<ItemStack> result = NonNullList.withSize(inventory.getSizeInventory(), ItemStack.EMPTY);
final NonNullList<ItemStack> result = NonNullList.withSize(inventory.getContainerSize(), ItemStack.EMPTY);
for (int slot = 0; slot < inventory.getSizeInventory(); slot++) {
final ItemStack stack = inventory.getStackInSlot(slot);
for (int slot = 0; slot < inventory.getContainerSize(); slot++) {
final ItemStack stack = inventory.getItem(slot);
if (stack.hasContainerItem()) {
result.set(slot, stack.getContainerItem());
} else if (Wrenches.isWrench(stack)) {
@@ -42,19 +42,19 @@ public final class WrenchRecipe extends ShapelessRecipe {
public static final class Serializer extends ForgeRegistryEntry<IRecipeSerializer<?>> implements IRecipeSerializer<WrenchRecipe> {
@Override
public WrenchRecipe read(final ResourceLocation location, final JsonObject json) {
return new WrenchRecipe(CRAFTING_SHAPELESS.read(location, json));
public WrenchRecipe fromJson(final ResourceLocation location, final JsonObject json) {
return new WrenchRecipe(SHAPELESS_RECIPE.fromJson(location, json));
}
@Nullable
@Override
public WrenchRecipe read(final ResourceLocation location, final PacketBuffer buffer) {
return new WrenchRecipe(CRAFTING_SHAPELESS.read(location, buffer));
public WrenchRecipe fromNetwork(final ResourceLocation location, final PacketBuffer buffer) {
return new WrenchRecipe(SHAPELESS_RECIPE.fromNetwork(location, buffer));
}
@Override
public void write(final PacketBuffer buffer, final WrenchRecipe recipe) {
CRAFTING_SHAPELESS.write(buffer, recipe);
public void toNetwork(final PacketBuffer buffer, final WrenchRecipe recipe) {
SHAPELESS_RECIPE.toNetwork(buffer, recipe);
}
}
}

View File

@@ -22,7 +22,7 @@ public final class MessageUtils {
}
final ServerWorld world = player.getLevel();
final TileEntity tileEntity = WorldUtils.getTileEntityIfChunkExists(world, pos);
final TileEntity tileEntity = WorldUtils.getBlockEntityIfChunkExists(world, pos);
if (type.isInstance(tileEntity)) {
callback.accept((T) tileEntity);
}

View File

@@ -118,7 +118,7 @@ public final class BlobStorage {
*/
public static void setServer(final MinecraftServer server) {
synchronize();
dataDirectory = server.func_240776_a_(BLOBS_FOLDER_NAME);
dataDirectory = server.getWorldPath(BLOBS_FOLDER_NAME);
try {
Files.createDirectories(dataDirectory);
} catch (final IOException e) {

View File

@@ -132,7 +132,7 @@ public final class NBTSerialization {
tag.putString(name, (String) value);
} else if (type == UUID.class) {
final CompoundNBT uuidTag = new CompoundNBT();
uuidTag.putUniqueId(name, (UUID) value);
uuidTag.putUUID(name, (UUID) value);
tag.put(name, uuidTag);
} else {
final CompoundNBT valueTag = new CompoundNBT();
@@ -277,7 +277,7 @@ public final class NBTSerialization {
} else if (type == String.class) {
return tag.getString(name);
} else if (type == UUID.class) {
return tag.getCompound(name).getUniqueId(name);
return tag.getCompound(name).getUUID(name);
} else {
final CompoundNBT valueTag = tag.getCompound(name);
return Ceres.getSerializer(type).deserialize(new Deserializer(valueTag), (Class) type, into);
@@ -382,7 +382,7 @@ public final class NBTSerialization {
public Object deserialize(final INBT tag, final Class<?> type, @Nullable final Object into) {
boolean[] data = (boolean[]) into;
if (tag instanceof ByteArrayNBT) {
final byte[] convertedData = ((ByteArrayNBT) tag).getByteArray();
final byte[] convertedData = ((ByteArrayNBT) tag).getAsByteArray();
if (data == null || data.length != convertedData.length) {
data = new boolean[convertedData.length];
}
@@ -404,7 +404,7 @@ public final class NBTSerialization {
public Object deserialize(final INBT tag, final Class<?> type, @Nullable final Object into) {
final byte[] data = (byte[]) into;
if (tag instanceof ByteArrayNBT) {
final byte[] serializedData = ((ByteArrayNBT) tag).getByteArray();
final byte[] serializedData = ((ByteArrayNBT) tag).getAsByteArray();
if (data == null || data.length != serializedData.length) {
return serializedData;
}
@@ -429,7 +429,7 @@ public final class NBTSerialization {
public Object deserialize(final INBT tag, final Class<?> type, @Nullable final Object into) {
char[] data = (char[]) into;
if (tag instanceof IntArrayNBT) {
final int[] convertedData = ((IntArrayNBT) tag).getIntArray();
final int[] convertedData = ((IntArrayNBT) tag).getAsIntArray();
if (data == null || data.length != convertedData.length) {
data = new char[convertedData.length];
}
@@ -456,7 +456,7 @@ public final class NBTSerialization {
public Object deserialize(final INBT tag, final Class<?> type, @Nullable final Object into) {
short[] data = (short[]) into;
if (tag instanceof IntArrayNBT) {
final int[] convertedData = ((IntArrayNBT) tag).getIntArray();
final int[] convertedData = ((IntArrayNBT) tag).getAsIntArray();
if (data == null || data.length != convertedData.length) {
data = new short[convertedData.length];
}
@@ -478,7 +478,7 @@ public final class NBTSerialization {
public Object deserialize(final INBT tag, final Class<?> type, @Nullable final Object into) {
final int[] data = (int[]) into;
if (tag instanceof IntArrayNBT) {
final int[] serializedData = ((IntArrayNBT) tag).getIntArray();
final int[] serializedData = ((IntArrayNBT) tag).getAsIntArray();
if (data == null || data.length != serializedData.length) {
return serializedData;
}
@@ -523,7 +523,7 @@ public final class NBTSerialization {
public Object deserialize(final INBT tag, final Class<?> type, @Nullable final Object into) {
float[] data = (float[]) into;
if (tag instanceof IntArrayNBT) {
final int[] convertedData = ((IntArrayNBT) tag).getIntArray();
final int[] convertedData = ((IntArrayNBT) tag).getAsIntArray();
if (data == null || data.length != convertedData.length) {
data = new float[convertedData.length];
}
@@ -581,7 +581,7 @@ public final class NBTSerialization {
Enum[] data = (Enum[]) into;
if (tag instanceof IntArrayNBT) {
final int[] serializedData = ((IntArrayNBT) tag).getIntArray();
final int[] serializedData = ((IntArrayNBT) tag).getAsIntArray();
if (data == null || data.length != serializedData.length) {
data = (Enum[]) Array.newInstance(componentType, serializedData.length);
}
@@ -609,7 +609,7 @@ public final class NBTSerialization {
String[] data = (String[]) into;
if (tag instanceof ListNBT) {
final ListNBT serializedData = (ListNBT) tag;
if (serializedData.isEmpty() || serializedData.getTagType() == NBTTagIds.TAG_STRING) {
if (serializedData.isEmpty() || serializedData.getElementType() == NBTTagIds.TAG_STRING) {
if (data == null || data.length != serializedData.size()) {
data = new String[serializedData.size()];
}
@@ -638,7 +638,7 @@ public final class NBTSerialization {
UUID[] data = (UUID[]) into;
if (tag instanceof ListNBT) {
final ListNBT serializedData = (ListNBT) tag;
if (serializedData.isEmpty() || serializedData.getTagType() == NBTTagIds.TAG_STRING) {
if (serializedData.isEmpty() || serializedData.getElementType() == NBTTagIds.TAG_STRING) {
if (data == null || data.length != serializedData.size()) {
data = new UUID[serializedData.size()];
}

View File

@@ -14,33 +14,33 @@ public final class NBTToJsonConverter {
switch (tag.getId()) {
case NBTTagIds.TAG_BYTE: {
return new JsonPrimitive(((ByteNBT) tag).getByte());
return new JsonPrimitive(((ByteNBT) tag).getAsByte());
}
case NBTTagIds.TAG_SHORT: {
return new JsonPrimitive(((ShortNBT) tag).getShort());
return new JsonPrimitive(((ShortNBT) tag).getAsShort());
}
case NBTTagIds.TAG_INT: {
return new JsonPrimitive(((IntNBT) tag).getInt());
return new JsonPrimitive(((IntNBT) tag).getAsInt());
}
case NBTTagIds.TAG_LONG: {
return new JsonPrimitive(((LongNBT) tag).getLong());
return new JsonPrimitive(((LongNBT) tag).getAsLong());
}
case NBTTagIds.TAG_FLOAT: {
return new JsonPrimitive(((FloatNBT) tag).getFloat());
return new JsonPrimitive(((FloatNBT) tag).getAsFloat());
}
case NBTTagIds.TAG_DOUBLE: {
return new JsonPrimitive(((DoubleNBT) tag).getDouble());
return new JsonPrimitive(((DoubleNBT) tag).getAsDouble());
}
case NBTTagIds.TAG_BYTE_ARRAY: {
final JsonArray json = new JsonArray();
final byte[] array = ((ByteArrayNBT) tag).getByteArray();
final byte[] array = ((ByteArrayNBT) tag).getAsByteArray();
for (int i = 0; i < array.length; i++) {
json.add(array[i]);
}
return json;
}
case NBTTagIds.TAG_STRING: {
return new JsonPrimitive(tag.getString());
return new JsonPrimitive(tag.getAsString());
}
case NBTTagIds.TAG_LIST: {
final JsonArray json = new JsonArray();
@@ -53,14 +53,14 @@ public final class NBTToJsonConverter {
case NBTTagIds.TAG_COMPOUND: {
final JsonObject json = new JsonObject();
final CompoundNBT compoundTag = (CompoundNBT) tag;
for (final String key : compoundTag.keySet()) {
for (final String key : compoundTag.getAllKeys()) {
json.add(key, convert(compoundTag.get(key)));
}
return json;
}
case NBTTagIds.TAG_INT_ARRAY: {
final JsonArray json = new JsonArray();
final int[] array = ((IntArrayNBT) tag).getIntArray();
final int[] array = ((IntArrayNBT) tag).getAsIntArray();
for (int i = 0; i < array.length; i++) {
json.add(array[i]);
}

View File

@@ -24,7 +24,7 @@ public final class DirectionJsonSerializer implements JsonDeserializer<Direction
}
if (primitive.isNumber()) {
return Direction.byIndex(json.getAsInt());
return Direction.from3DDataValue(json.getAsInt());
}
return null;
@@ -35,7 +35,7 @@ public final class DirectionJsonSerializer implements JsonDeserializer<Direction
if (src == null) {
return JsonNull.INSTANCE;
} else {
return new JsonPrimitive(src.getString());
return new JsonPrimitive(src.toString());
}
}
}

View File

@@ -23,6 +23,6 @@ public final class TextComponentSerializer implements Serializer<ITextComponent>
}
final String json = (String) visitor.getObject("value", String.class, null);
return ITextComponent.Serializer.getComponentFromJson(json);
return ITextComponent.Serializer.fromJson(json);
}
}

View File

@@ -68,18 +68,17 @@ public abstract class AbstractTileEntity extends TileEntity {
public void onLoad() {
super.onLoad();
final World world = getWorld();
if (world == null) {
if (level == null) {
return;
}
if (world.isRemote()) {
if (level.isClientSide) {
loadClient();
} else {
loadServer();
if (needsWorldUnloadEvent) {
ServerScheduler.scheduleOnUnload(world, onWorldUnloaded);
ServerScheduler.scheduleOnUnload(level, onWorldUnloaded);
}
}
}
@@ -96,8 +95,8 @@ public abstract class AbstractTileEntity extends TileEntity {
}
@Override
public void remove() {
super.remove(); // -> invalidateCaps()
public void setRemoved() {
super.setRemoved();
onUnload();
}
@@ -122,10 +121,9 @@ public abstract class AbstractTileEntity extends TileEntity {
}
protected void onUnload() {
final World world = getWorld();
if (world != null && !world.isRemote()) {
if (level != null && !level.isClientSide) {
unloadServer();
ServerScheduler.cancelOnUnload(world, onWorldUnloaded);
ServerScheduler.cancelOnUnload(level, onWorldUnloaded);
}
}

View File

@@ -41,21 +41,21 @@ public final class BusCableTileEntity extends AbstractTileEntity {
///////////////////////////////////////////////////////////////////
public String getInterfaceName(final Direction side) {
final String interfaceName = interfaceNames[side.getIndex()];
final String interfaceName = interfaceNames[side.get3DDataValue()];
return interfaceName == null ? "" : interfaceName;
}
public void setInterfaceName(final Direction side, final String name) {
final String validatedName = validateName(name);
if (Objects.equals(validatedName, interfaceNames[side.getIndex()])) {
if (Objects.equals(validatedName, interfaceNames[side.get3DDataValue()])) {
return;
}
interfaceNames[side.getIndex()] = validatedName;
if (!getWorld().isRemote()) {
final BusInterfaceNameMessage message = new BusInterfaceNameMessage.ToClient(this, side, interfaceNames[side.getIndex()]);
Network.sendToClientsTrackingChunk(message, getWorld().getChunkAt(getPos()));
handleNeighborChanged(getPos().offset(side));
interfaceNames[side.get3DDataValue()] = validatedName;
if (!level.isClientSide) {
final BusInterfaceNameMessage message = new BusInterfaceNameMessage.ToClient(this, side, interfaceNames[side.get3DDataValue()]);
Network.sendToClientsTrackingChunk(message, level.getChunkAt(getBlockPos()));
handleNeighborChanged(getBlockPos().relative(side));
}
}
@@ -73,13 +73,13 @@ public final class BusCableTileEntity extends AbstractTileEntity {
setInterfaceName(side, "");
invalidateCapability(Capabilities.DEVICE_BUS_ELEMENT, side);
handleNeighborChanged(getPos().offset(side));
handleNeighborChanged(getBlockPos().relative(side));
}
}
@Override
public void remove() {
super.remove();
public void setRemoved() {
super.setRemoved();
// Bus element will usually be discovered via bus scan, not via capability request, so
// automatic invalidation via capability will *not* necessarily schedule a scan on the
@@ -102,8 +102,8 @@ public final class BusCableTileEntity extends AbstractTileEntity {
}
@Override
public CompoundNBT write(CompoundNBT tag) {
tag = super.write(tag);
public CompoundNBT save(CompoundNBT tag) {
tag = super.save(tag);
tag.put(BUS_ELEMENT_TAG_NAME, busElement.serializeNBT());
tag.put(INTERFACE_NAMES_TAG_NAME, serializeInterfaceNames());
@@ -111,8 +111,8 @@ public final class BusCableTileEntity extends AbstractTileEntity {
}
@Override
public void read(final BlockState state, final CompoundNBT tag) {
super.read(state, tag);
public void load(final BlockState state, final CompoundNBT tag) {
super.load(state, tag);
busElement.deserializeNBT(tag.getList(BUS_ELEMENT_TAG_NAME, NBTTagIds.TAG_COMPOUND));
deserializeInterfaceNames(tag.getList(INTERFACE_NAMES_TAG_NAME, NBTTagIds.TAG_STRING));
}
@@ -138,7 +138,7 @@ public final class BusCableTileEntity extends AbstractTileEntity {
private ListNBT serializeInterfaceNames() {
final ListNBT tag = new ListNBT();
for (int i = 0; i < Constants.BLOCK_FACE_COUNT; i++) {
tag.add(StringNBT.valueOf(getInterfaceName(Direction.byIndex(i))));
tag.add(StringNBT.valueOf(getInterfaceName(Direction.from3DDataValue(i))));
}
return tag;
}
@@ -178,7 +178,7 @@ public final class BusCableTileEntity extends AbstractTileEntity {
@Override
protected void collectSyntheticDevices(final World world, final BlockPos pos, final Direction direction, final HashSet<BlockDeviceInfo> devices) {
super.collectSyntheticDevices(world, pos, direction, devices);
final String interfaceName = interfaceNames[direction.getIndex()];
final String interfaceName = interfaceNames[direction.get3DDataValue()];
if (!StringUtils.isNullOrEmpty(interfaceName)) {
devices.add(new BlockDeviceInfo(null, new TypeNameRPCDevice(interfaceName)));
}

View File

@@ -37,8 +37,8 @@ public final class ChargerTileEntity extends AbstractTileEntity implements ITick
}
@Override
public CompoundNBT write(CompoundNBT tag) {
tag = super.write(tag);
public CompoundNBT save(CompoundNBT tag) {
tag = super.save(tag);
tag.put(Constants.ENERGY_TAG_NAME, energy.serializeNBT());
@@ -46,8 +46,8 @@ public final class ChargerTileEntity extends AbstractTileEntity implements ITick
}
@Override
public void read(final BlockState state, final CompoundNBT tag) {
super.read(state, tag);
public void load(final BlockState state, final CompoundNBT tag) {
super.load(state, tag);
energy.deserializeNBT(tag.getCompound(Constants.ENERGY_TAG_NAME));
}
@@ -66,7 +66,7 @@ public final class ChargerTileEntity extends AbstractTileEntity implements ITick
return;
}
final TileEntity tileEntity = getWorld().getTileEntity(getPos().up());
final TileEntity tileEntity = getLevel().getBlockEntity(getBlockPos().above());
if (tileEntity != null) {
chargeCapabilityProvider(tileEntity);
}
@@ -77,7 +77,7 @@ public final class ChargerTileEntity extends AbstractTileEntity implements ITick
return;
}
final List<Entity> entities = getWorld().getEntitiesInAABBexcluding(null, new AxisAlignedBB(getPos().up()), null);
final List<Entity> entities = getLevel().getEntities((Entity) null, new AxisAlignedBB(getBlockPos().above()), null);
for (final Entity entity : entities) {
chargeCapabilityProvider(entity);
}

View File

@@ -103,8 +103,7 @@ public final class ComputerTileEntity extends AbstractTileEntity implements ITic
}
public void start() {
final World world = getWorld();
if (world == null || world.isRemote()) {
if (level == null || level.isClientSide) {
return;
}
@@ -112,8 +111,7 @@ public final class ComputerTileEntity extends AbstractTileEntity implements ITic
}
public void stop() {
final World world = getWorld();
if (world == null || world.isRemote()) {
if (level == null || level.isClientSide) {
return;
}
@@ -124,7 +122,7 @@ public final class ComputerTileEntity extends AbstractTileEntity implements ITic
NetworkHooks.openGui(player, new INamedContainerProvider() {
@Override
public ITextComponent getDisplayName() {
return new TranslationTextComponent(getBlockState().getBlock().getTranslationKey());
return new TranslationTextComponent(getBlockState().getBlock().getDescriptionId());
}
@Override
@@ -149,26 +147,26 @@ public final class ComputerTileEntity extends AbstractTileEntity implements ITic
}
@Override
public int size() {
public int getCount() {
return 3;
}
});
}
}, getPos());
}, getBlockPos());
}
public void openContainerScreen(final ServerPlayerEntity player) {
NetworkHooks.openGui(player, new INamedContainerProvider() {
@Override
public ITextComponent getDisplayName() {
return new TranslationTextComponent(getBlockState().getBlock().getTranslationKey());
return new TranslationTextComponent(getBlockState().getBlock().getDescriptionId());
}
@Override
public Container createMenu(final int id, final PlayerInventory inventory, final PlayerEntity player) {
return new ComputerInventoryContainer(id, ComputerTileEntity.this, inventory);
}
}, getPos());
}, getBlockPos());
}
public void addTerminalUser(final PlayerEntity player) {
@@ -214,8 +212,7 @@ public final class ComputerTileEntity extends AbstractTileEntity implements ITic
@Override
public void tick() {
final World world = getWorld();
if (world == null || world.isRemote()) {
if (level == null || level.isClientSide) {
return;
}
@@ -231,15 +228,15 @@ public final class ComputerTileEntity extends AbstractTileEntity implements ITic
if (isNeighborUpdateScheduled) {
isNeighborUpdateScheduled = false;
world.notifyNeighborsOfStateChange(getPos(), getBlockState().getBlock());
level.updateNeighborsAt(getBlockPos(), getBlockState().getBlock());
}
virtualMachine.tick();
}
@Override
public void remove() {
super.remove();
public void setRemoved() {
super.setRemoved();
// super.remove() calls onUnload. This in turn only suspends, but we want to do
// a full clean-up when we get destroyed, so stuff inside us can delete out-of-nbt
@@ -266,12 +263,12 @@ public final class ComputerTileEntity extends AbstractTileEntity implements ITic
NBTSerialization.deserialize(tag.getCompound(TERMINAL_TAG_NAME), terminal);
virtualMachine.setBusStateClient(CommonDeviceBusController.BusState.values()[tag.getInt(AbstractVirtualMachine.BUS_STATE_TAG_NAME)]);
virtualMachine.setRunStateClient(VMRunState.values()[tag.getInt(AbstractVirtualMachine.RUN_STATE_TAG_NAME)]);
virtualMachine.setBootErrorClient(ITextComponent.Serializer.getComponentFromJson(tag.getString(AbstractVirtualMachine.BOOT_ERROR_TAG_NAME)));
virtualMachine.setBootErrorClient(ITextComponent.Serializer.fromJson(tag.getString(AbstractVirtualMachine.BOOT_ERROR_TAG_NAME)));
}
@Override
public CompoundNBT write(CompoundNBT tag) {
tag = super.write(tag);
public CompoundNBT save(final CompoundNBT tag) {
super.save(tag);
tag.put(STATE_TAG_NAME, virtualMachine.serialize());
tag.put(TERMINAL_TAG_NAME, NBTSerialization.serialize(terminal));
@@ -282,8 +279,8 @@ public final class ComputerTileEntity extends AbstractTileEntity implements ITic
}
@Override
public void read(final BlockState blockState, final CompoundNBT tag) {
super.read(blockState, tag);
public void load(final BlockState blockState, final CompoundNBT tag) {
super.load(blockState, tag);
virtualMachine.deserialize(tag.getCompound(STATE_TAG_NAME));
NBTSerialization.deserialize(tag.getCompound(TERMINAL_TAG_NAME), terminal);
@@ -324,7 +321,7 @@ public final class ComputerTileEntity extends AbstractTileEntity implements ITic
super.loadServer();
busElement.initialize();
virtualMachine.state.builtinDevices.rtcMinecraft.setWorld(getWorld());
virtualMachine.state.builtinDevices.rtcMinecraft.setWorld(level);
}
@Override
@@ -361,7 +358,7 @@ public final class ComputerTileEntity extends AbstractTileEntity implements ITic
@Override
protected void onContentsChanged(final DeviceItemStackHandler itemStackHandler, final int slot) {
super.onContentsChanged(itemStackHandler, slot);
markDirty();
setChanged();
isNeighborUpdateScheduled = true;
}
}
@@ -382,7 +379,7 @@ public final class ComputerTileEntity extends AbstractTileEntity implements ITic
@Override
public boolean canScanContinueTowards(@Nullable final Direction direction) {
return getBlockState().get(ComputerBlock.HORIZONTAL_FACING) != direction;
return getBlockState().getValue(ComputerBlock.FACING) != direction;
}
}
@@ -411,7 +408,7 @@ public final class ComputerTileEntity extends AbstractTileEntity implements ITic
if (value == VMRunState.RUNNING) {
if (!LoopingSoundManager.isPlaying(ComputerTileEntity.this)) {
LoopingSoundManager.play(ComputerTileEntity.this, SoundEvents.COMPUTER_RUNNING.get(), getWorld().getRandom().nextInt(MAX_RUNNING_SOUND_DELAY));
LoopingSoundManager.play(ComputerTileEntity.this, SoundEvents.COMPUTER_RUNNING.get(), level.getRandom().nextInt(MAX_RUNNING_SOUND_DELAY));
}
} else {
LoopingSoundManager.stop(ComputerTileEntity.this);
@@ -421,11 +418,11 @@ public final class ComputerTileEntity extends AbstractTileEntity implements ITic
@Override
public void tick() {
if (chunk == null) {
chunk = world.getChunkAt(getPos());
chunk = level.getChunkAt(getBlockPos());
}
if (isRunning()) {
chunk.markDirty();
chunk.markUnsaved();
}
super.tick();
@@ -465,7 +462,7 @@ public final class ComputerTileEntity extends AbstractTileEntity implements ITic
if (value == CommonDeviceBusController.BusState.READY) {
// Bus just became ready, meaning new devices may be available, meaning new
// capabilities may be available, so we need to tell our neighbors.
world.notifyNeighborsOfStateChange(getPos(), getBlockState().getBlock());
level.updateNeighborsAt(getBlockPos(), getBlockState().getBlock());
}
}

View File

@@ -21,10 +21,10 @@ public final class CreativeEnergyTileEntity extends TileEntity implements ITicka
@Override
public void tick() {
for (final Direction side : SIDES) {
final BlockPos neighborPos = getPos().offset(side);
final BlockPos neighborPos = getBlockPos().relative(side);
final ChunkPos neighborChunkPos = new ChunkPos(neighborPos);
if (getWorld().chunkExists(neighborChunkPos.x, neighborChunkPos.z)) {
final TileEntity tileEntity = getWorld().getTileEntity(neighborPos);
if (getLevel().hasChunk(neighborChunkPos.x, neighborChunkPos.z)) {
final TileEntity tileEntity = getLevel().getBlockEntity(neighborPos);
if (tileEntity != null) {
tileEntity.getCapability(Capabilities.ENERGY_STORAGE, side.getOpposite()).ifPresent(energy -> {
energy.receiveEnergy(Integer.MAX_VALUE, false);

View File

@@ -89,8 +89,8 @@ public final class DiskDriveTileEntity extends AbstractTileEntity {
public void eject() {
final ItemStack stack = itemHandler.extractItem(0, 1, false);
if (!stack.isEmpty()) {
final Direction facing = getBlockState().get(DiskDriveBlock.HORIZONTAL_FACING);
ItemStackUtils.spawnAsEntity(getWorld(), getPos().offset(facing), stack, facing);
final Direction facing = getBlockState().getValue(DiskDriveBlock.FACING);
ItemStackUtils.spawnAsEntity(level, getBlockPos().relative(facing), stack, facing);
ejectSoundEmitter.play();
}
}
@@ -123,8 +123,8 @@ public final class DiskDriveTileEntity extends AbstractTileEntity {
}
@Override
public CompoundNBT write(CompoundNBT tag) {
tag = super.write(tag);
public CompoundNBT save(CompoundNBT tag) {
tag = super.save(tag);
tag.put(Constants.ITEMS_TAG_NAME, itemHandler.serializeNBT());
@@ -132,8 +132,8 @@ public final class DiskDriveTileEntity extends AbstractTileEntity {
}
@Override
public void read(final BlockState state, final CompoundNBT tag) {
super.read(state, tag);
public void load(final BlockState state, final CompoundNBT tag) {
super.load(state, tag);
itemHandler.deserializeNBT(tag.getCompound(Constants.ITEMS_TAG_NAME));
}
@@ -174,8 +174,7 @@ public final class DiskDriveTileEntity extends AbstractTileEntity {
protected void onContentsChanged(final int slot) {
super.onContentsChanged(slot);
final World world = getWorld();
if (world == null || world.isRemote()) {
if (level == null || level.isClientSide) {
return;
}
@@ -187,7 +186,7 @@ public final class DiskDriveTileEntity extends AbstractTileEntity {
device.updateBlockDevice(tag);
}
Network.sendToClientsTrackingChunk(new DiskDriveFloppyMessage(DiskDriveTileEntity.this), world.getChunkAt(getPos()));
Network.sendToClientsTrackingChunk(new DiskDriveFloppyMessage(DiskDriveTileEntity.this), level.getChunkAt(getBlockPos()));
}
private void exportDeviceDataToItemStack(final ItemStack stack) {
@@ -195,8 +194,7 @@ public final class DiskDriveTileEntity extends AbstractTileEntity {
return;
}
final World world = getWorld();
if (world == null || world.isRemote()) {
if (level == null || level.isClientSide) {
return;
}

View File

@@ -81,12 +81,12 @@ public final class NetworkConnectorTileEntity extends AbstractTileEntity impleme
return ConnectionResult.FAILURE;
}
final World world = connectorA.getWorld();
if (world == null || world.isRemote()) {
final World world = connectorA.level;
if (world == null || world.isClientSide) {
return ConnectionResult.FAILURE;
}
if (connectorB.getWorld() != world) {
if (connectorB.level != world) {
return ConnectionResult.FAILURE;
}
@@ -94,10 +94,10 @@ public final class NetworkConnectorTileEntity extends AbstractTileEntity impleme
return ConnectionResult.FAILURE_FULL;
}
final BlockPos posA = connectorA.getPos();
final BlockPos posB = connectorB.getPos();
final BlockPos posA = connectorA.getBlockPos();
final BlockPos posB = connectorB.getBlockPos();
if (!posA.withinDistance(posB, MAX_CONNECTION_DISTANCE)) {
if (!posA.closerThan(posB, MAX_CONNECTION_DISTANCE)) {
return ConnectionResult.FAILURE_TOO_FAR;
}
@@ -125,8 +125,8 @@ public final class NetworkConnectorTileEntity extends AbstractTileEntity impleme
result = ConnectionResult.SUCCESS;
}
connectorA.markDirty();
connectorB.markDirty();
connectorA.setChanged();
connectorB.setChanged();
return result;
}
@@ -136,10 +136,9 @@ public final class NetworkConnectorTileEntity extends AbstractTileEntity impleme
connectors.remove(pos);
if (ownedCables.remove(pos)) {
final World world = getWorld();
if (world != null) {
final Vector3d middle = Vector3d.copyCentered(getPos().add(pos)).scale(0.5f);
ItemStackUtils.spawnAsEntity(world, middle, new ItemStack(Items.NETWORK_CABLE.get()));
if (level != null) {
final Vector3d middle = Vector3d.atCenterOf(getBlockPos().offset(pos)).scale(0.5f);
ItemStackUtils.spawnAsEntity(level, middle, new ItemStack(Items.NETWORK_CABLE.get()));
}
}
@@ -148,7 +147,7 @@ public final class NetworkConnectorTileEntity extends AbstractTileEntity impleme
onConnectedPositionsChanged();
}
markDirty();
setChanged();
}
}
@@ -224,8 +223,8 @@ public final class NetworkConnectorTileEntity extends AbstractTileEntity impleme
}
@Override
public CompoundNBT write(CompoundNBT tag) {
tag = super.write(tag);
public CompoundNBT save(CompoundNBT tag) {
tag = super.save(tag);
final ListNBT connections = new ListNBT();
for (final BlockPos position : connectorPositions) {
@@ -241,8 +240,8 @@ public final class NetworkConnectorTileEntity extends AbstractTileEntity impleme
}
@Override
public void read(final BlockState state, final CompoundNBT tag) {
super.read(state, tag);
public void load(final BlockState state, final CompoundNBT tag) {
super.load(state, tag);
final ListNBT connections = tag.getList(CONNECTIONS_TAG_NAME, NBTTagIds.TAG_COMPOUND);
for (int i = 0; i < Math.min(connections.size(), MAX_CONNECTION_COUNT); i++) {
@@ -264,16 +263,16 @@ public final class NetworkConnectorTileEntity extends AbstractTileEntity impleme
}
@Override
public void remove() {
super.remove();
public void setRemoved() {
super.setRemoved();
// When we're being removed we want to break the actual link to any connected
// connectors. This will also cause cables to be dropped.
final ArrayList<NetworkConnectorTileEntity> list = new ArrayList<>(connectors.values());
connectors.clear();
for (final NetworkConnectorTileEntity connector : list) {
disconnectFrom(connector.getPos());
connector.disconnectFrom(getPos());
disconnectFrom(connector.getBlockPos());
connector.disconnectFrom(getBlockPos());
}
}
@@ -283,7 +282,7 @@ public final class NetworkConnectorTileEntity extends AbstractTileEntity impleme
// When unloading, we just want to remove the reference to this tile entity
// from connected connectors; we don't want to actually break the link.
final BlockPos pos = getPos();
final BlockPos pos = getBlockPos();
for (final NetworkConnectorTileEntity connector : connectors.values()) {
connector.connectors.remove(pos);
if (connector.connectorPositions.contains(pos)) {
@@ -294,8 +293,11 @@ public final class NetworkConnectorTileEntity extends AbstractTileEntity impleme
@Override
public AxisAlignedBB getRenderBoundingBox() {
if (Minecraft.isFabulousGraphicsEnabled()) {
return new AxisAlignedBB(pos.add(-MAX_CONNECTION_DISTANCE, -MAX_CONNECTION_DISTANCE, -MAX_CONNECTION_DISTANCE), pos.add(1 + MAX_CONNECTION_DISTANCE, 1 + MAX_CONNECTION_DISTANCE, 1 + MAX_CONNECTION_DISTANCE));
if (Minecraft.useShaderTransparency()) {
return new AxisAlignedBB(
getBlockPos().offset(-MAX_CONNECTION_DISTANCE, -MAX_CONNECTION_DISTANCE, -MAX_CONNECTION_DISTANCE),
getBlockPos().offset(1 + MAX_CONNECTION_DISTANCE, 1 + MAX_CONNECTION_DISTANCE, 1 + MAX_CONNECTION_DISTANCE)
);
} else {
return super.getRenderBoundingBox();
}
@@ -319,21 +321,20 @@ public final class NetworkConnectorTileEntity extends AbstractTileEntity impleme
return;
}
final World world = getWorld();
if (world == null || world.isRemote()) {
if (level == null || level.isClientSide) {
return;
}
final Direction facing = NetworkConnectorBlock.getFacing(getBlockState());
final BlockPos sourcePos = getPos().offset(facing.getOpposite());
final BlockPos sourcePos = getBlockPos().relative(facing.getOpposite());
final ChunkPos sourceChunk = new ChunkPos(sourcePos);
if (!world.chunkExists(sourceChunk.x, sourceChunk.z)) {
ServerScheduler.schedule(world, this::setLocalInterfaceChanged, RETRY_UNLOADED_CHUNK_INTERVAL);
if (!level.hasChunk(sourceChunk.x, sourceChunk.z)) {
ServerScheduler.schedule(level, this::setLocalInterfaceChanged, RETRY_UNLOADED_CHUNK_INTERVAL);
return;
}
final TileEntity tileEntity = world.getTileEntity(sourcePos);
final TileEntity tileEntity = level.getBlockEntity(sourcePos);
if (tileEntity == null) {
return;
}
@@ -351,18 +352,17 @@ public final class NetworkConnectorTileEntity extends AbstractTileEntity impleme
return;
}
final World world = getWorld();
if (world == null || world.isRemote()) {
if (level == null || level.isClientSide) {
return;
}
final ChunkPos destinationChunk = new ChunkPos(connectedPosition);
if (!world.chunkExists(destinationChunk.x, destinationChunk.z)) {
ServerScheduler.schedule(world, () -> dirtyConnectors.add(connectedPosition), RETRY_UNLOADED_CHUNK_INTERVAL);
if (!level.hasChunk(destinationChunk.x, destinationChunk.z)) {
ServerScheduler.schedule(level, () -> dirtyConnectors.add(connectedPosition), RETRY_UNLOADED_CHUNK_INTERVAL);
return;
}
final TileEntity tileEntity = world.getTileEntity(connectedPosition);
final TileEntity tileEntity = level.getBlockEntity(connectedPosition);
if (!(tileEntity instanceof NetworkConnectorTileEntity)) {
disconnectFrom(connectedPosition);
return;
@@ -370,15 +370,15 @@ public final class NetworkConnectorTileEntity extends AbstractTileEntity impleme
final NetworkConnectorTileEntity connector = (NetworkConnectorTileEntity) tileEntity;
if (!connectedPosition.withinDistance(getPos(), MAX_CONNECTION_DISTANCE)) {
if (!connectedPosition.closerThan(getBlockPos(), MAX_CONNECTION_DISTANCE)) {
disconnectFrom(connectedPosition);
connector.disconnectFrom(getPos());
connector.disconnectFrom(getBlockPos());
return;
}
if (isObstructed(world, getPos(), connectedPosition)) {
if (isObstructed(level, getBlockPos(), connectedPosition)) {
disconnectFrom(connectedPosition);
connector.disconnectFrom(getPos());
connector.disconnectFrom(getBlockPos());
return;
}
@@ -386,21 +386,21 @@ public final class NetworkConnectorTileEntity extends AbstractTileEntity impleme
}
private static boolean isObstructed(final World world, final BlockPos a, final BlockPos b) {
final Vector3d va = Vector3d.copyCentered(a);
final Vector3d vb = Vector3d.copyCentered(b);
final Vector3d va = Vector3d.atCenterOf(a);
final Vector3d vb = Vector3d.atCenterOf(b);
final Vector3d ab = vb.subtract(va).normalize().scale(0.5);
// Because of floating point inaccuracies the raytrace is not necessarily
// symmetric. In particular when grazing corners perfectly, e.g. two connectors
// attached to the same block at a 90 degree angle. So we check both ways.
final BlockRayTraceResult hitAB = world.rayTraceBlocks(new RayTraceContext(
final BlockRayTraceResult hitAB = world.clip(new RayTraceContext(
va.add(ab),
vb.subtract(ab),
RayTraceContext.BlockMode.COLLIDER,
RayTraceContext.FluidMode.NONE,
null
));
final BlockRayTraceResult hitBA = world.rayTraceBlocks(new RayTraceContext(
final BlockRayTraceResult hitBA = world.clip(new RayTraceContext(
vb.subtract(ab),
va.add(ab),
RayTraceContext.BlockMode.COLLIDER,
@@ -413,10 +413,10 @@ public final class NetworkConnectorTileEntity extends AbstractTileEntity impleme
}
private void onConnectedPositionsChanged() {
final World world = getWorld();
if (world != null && !world.isRemote()) {
if (level != null && !level.isClientSide) {
final NetworkConnectorConnectionsMessage message = new NetworkConnectorConnectionsMessage(this);
final Chunk chunk = world.getChunkAt(getPos());
final Chunk chunk = level.getChunkAt(getBlockPos());
Network.sendToClientsTrackingChunk(message, chunk);
}
}

View File

@@ -63,20 +63,20 @@ public final class NetworkHubTileEntity extends AbstractTileEntity implements Ne
areAdjacentInterfacesDirty = false;
final World world = getWorld();
if (world == null || world.isRemote()) {
final World world = getLevel();
if (world == null || world.isClientSide) {
return;
}
final BlockPos pos = getPos();
final BlockPos pos = getBlockPos();
for (final Direction side : Constants.DIRECTIONS) {
adjacentInterfaces[side.getIndex()] = null;
adjacentInterfaces[side.get3DDataValue()] = null;
final TileEntity neighborTileEntity = world.getTileEntity(pos.offset(side));
final TileEntity neighborTileEntity = world.getBlockEntity(pos.relative(side));
if (neighborTileEntity != null) {
final LazyOptional<NetworkInterface> capability = neighborTileEntity.getCapability(Capabilities.NETWORK_INTERFACE, side.getOpposite());
capability.ifPresent(adjacentInterface -> {
adjacentInterfaces[side.getIndex()] = adjacentInterface;
adjacentInterfaces[side.get3DDataValue()] = adjacentInterface;
capability.addListener(unused -> handleNeighborChanged());
});
}

View File

@@ -41,15 +41,15 @@ public final class RedstoneInterfaceTileEntity extends TileEntity implements Nam
///////////////////////////////////////////////////////////////////
@Override
public CompoundNBT write(CompoundNBT compound) {
compound = super.write(compound);
public CompoundNBT save(CompoundNBT compound) {
compound = super.save(compound);
compound.putByteArray(OUTPUT_TAG_NAME, output);
return compound;
}
@Override
public void read(final BlockState state, final CompoundNBT compound) {
super.read(state, compound);
public void load(final BlockState state, final CompoundNBT compound) {
super.load(state, compound);
final byte[] serializedOutput = compound.getByteArray(OUTPUT_TAG_NAME);
System.arraycopy(serializedOutput, 0, output, 0, Math.min(serializedOutput.length, output.length));
}
@@ -58,49 +58,49 @@ public final class RedstoneInterfaceTileEntity extends TileEntity implements Nam
final Direction localDirection = HorizontalBlockUtils.toLocal(getBlockState(), direction);
assert localDirection != null;
return output[localDirection.getIndex()];
return output[localDirection.get3DDataValue()];
}
@Callback(name = GET_REDSTONE_INPUT)
public int getRedstoneInput(@Parameter(SIDE) final Direction side) {
final World world = getWorld();
public int setSignal(@Parameter(SIDE) final Direction side) {
final World world = getLevel();
if (world == null) {
return 0;
}
final BlockPos pos = getPos();
final BlockPos pos = getBlockPos();
final Direction direction = HorizontalBlockUtils.toGlobal(getBlockState(), side);
assert direction != null;
final BlockPos neighborPos = pos.offset(direction);
final BlockPos neighborPos = pos.relative(direction);
final ChunkPos chunkPos = new ChunkPos(neighborPos.getX(), neighborPos.getZ());
if (!world.chunkExists(chunkPos.x, chunkPos.z)) {
if (!world.hasChunk(chunkPos.x, chunkPos.z)) {
return 0;
}
return world.getRedstonePower(neighborPos, direction);
return world.getSignal(neighborPos, direction);
}
@Callback(name = GET_REDSTONE_OUTPUT, synchronize = false)
public int getRedstoneOutput(@Parameter(SIDE) final Direction side) {
return output[side.getIndex()];
public int getSignal(@Parameter(SIDE) final Direction side) {
return output[side.get3DDataValue()];
}
@Callback(name = SET_REDSTONE_OUTPUT)
public void setRedstoneOutput(@Parameter(SIDE) final Direction side, @Parameter(VALUE) final int value) {
public void getSignal(@Parameter(SIDE) final Direction side, @Parameter(VALUE) final int value) {
final byte clampedValue = (byte) MathHelper.clamp(value, 0, 15);
if (clampedValue == output[side.getIndex()]) {
if (clampedValue == output[side.get3DDataValue()]) {
return;
}
output[side.getIndex()] = clampedValue;
output[side.get3DDataValue()] = clampedValue;
final Direction direction = HorizontalBlockUtils.toGlobal(getBlockState(), side);
if (direction != null) {
notifyNeighbor(direction);
}
markDirty();
setChanged();
}
@Override
@@ -137,12 +137,12 @@ public final class RedstoneInterfaceTileEntity extends TileEntity implements Nam
///////////////////////////////////////////////////////////////////
private void notifyNeighbor(final Direction direction) {
final World world = getWorld();
final World world = getLevel();
if (world == null) {
return;
}
world.notifyNeighborsOfStateChange(getPos(), getBlockState().getBlock());
world.notifyNeighborsOfStateChange(getPos().offset(direction), getBlockState().getBlock());
world.updateNeighborsAt(getBlockPos(), getBlockState().getBlock());
world.updateNeighborsAt(getBlockPos().relative(direction), getBlockState().getBlock());
}
}

View File

@@ -36,6 +36,6 @@ public final class TileEntities {
@SuppressWarnings("ConstantConditions") // .build(null) is fine
private static <B extends Block, T extends TileEntity> RegistryObject<TileEntityType<T>> register(final RegistryObject<B> block, final Supplier<T> factory) {
return TILES.register(block.getId().getPath(), () -> TileEntityType.Builder.create(factory, block.get()).build(null));
return TILES.register(block.getId().getPath(), () -> TileEntityType.Builder.of(factory, block.get()).build(null));
}
}

View File

@@ -24,11 +24,11 @@ public final class FakePlayerUtils {
public static ServerPlayerEntity getFakePlayer(final ServerWorld world, final Entity entity) {
final ServerPlayerEntity player = getFakePlayer(world);
player.copyLocationAndAnglesFrom(entity);
player.prevRotationPitch = player.rotationPitch;
player.prevRotationYaw = player.rotationYaw;
player.rotationYawHead = player.rotationYaw;
player.prevRotationYawHead = player.rotationYawHead;
player.copyPosition(entity);
player.xRotO = player.xRot;
player.yRotO = player.yRot;
player.yHeadRot = player.yRot;
player.yHeadRotO = player.yHeadRot;
return player;
}
@@ -52,7 +52,7 @@ public final class FakePlayerUtils {
}
@Override
public void sendPacket(final IPacket<?> packetIn, @Nullable final GenericFutureListener<? extends Future<? super Void>> futureListeners) {
public void send(final IPacket<?> packetIn, @Nullable final GenericFutureListener<? extends Future<? super Void>> futureListeners) {
}
}
}

View File

@@ -17,19 +17,19 @@ public final class HorizontalBlockUtils {
return null;
}
final int index = direction.getHorizontalIndex();
final int index = direction.get2DDataValue();
if (index < 0) {
return direction;
}
if (!blockState.hasProperty(HorizontalBlock.HORIZONTAL_FACING)) {
if (!blockState.hasProperty(HorizontalBlock.FACING)) {
return direction;
}
final Direction facing = blockState.get(HorizontalBlock.HORIZONTAL_FACING);
final int toLocal = HORIZONTAL_DIRECTION_COUNT - facing.getHorizontalIndex();
final Direction facing = blockState.getValue(HorizontalBlock.FACING);
final int toLocal = HORIZONTAL_DIRECTION_COUNT - facing.get2DDataValue();
final int rotatedIndex = (index + toLocal) % HORIZONTAL_DIRECTION_COUNT;
return Direction.byHorizontalIndex(rotatedIndex);
return Direction.from2DDataValue(rotatedIndex);
}
@Nullable
@@ -38,18 +38,18 @@ public final class HorizontalBlockUtils {
return null;
}
final int index = direction.getHorizontalIndex();
final int index = direction.get2DDataValue();
if (index < 0) {
return direction;
}
if (!blockState.hasProperty(HorizontalBlock.HORIZONTAL_FACING)) {
if (!blockState.hasProperty(HorizontalBlock.FACING)) {
return direction;
}
final Direction facing = blockState.get(HorizontalBlock.HORIZONTAL_FACING);
final int toGlobal = facing.getHorizontalIndex();
final Direction facing = blockState.getValue(HorizontalBlock.FACING);
final int toGlobal = facing.get2DDataValue();
final int rotatedIndex = (index + toGlobal) % HORIZONTAL_DIRECTION_COUNT;
return Direction.byHorizontalIndex(rotatedIndex);
return Direction.from2DDataValue(rotatedIndex);
}
}

View File

@@ -24,32 +24,32 @@ public final class ItemStackUtils {
}
public static Optional<ItemEntity> spawnAsEntity(final World world, final BlockPos pos, final ItemStack stack) {
return spawnAsEntity(world, Vector3d.copyCentered(pos), stack);
return spawnAsEntity(world, Vector3d.atCenterOf(pos), stack);
}
public static Optional<ItemEntity> spawnAsEntity(final World world, final Vector3d pos, final ItemStack stack) {
if (world.isRemote() || stack.isEmpty()) {
if (world.isClientSide() || stack.isEmpty()) {
return Optional.empty();
}
final Random rng = world.rand;
final Random rng = world.random;
final float tx = 0.5f * (rng.nextFloat() - 1.0f);
final float ty = 0.5f * (rng.nextFloat() - 1.0f);
final float tz = 0.5f * (rng.nextFloat() - 1.0f);
final double px = pos.getX() + tx;
final double py = pos.getY() + ty;
final double pz = pos.getZ() + tz;
final double px = pos.x + tx;
final double py = pos.y + ty;
final double pz = pos.z + tz;
final ItemEntity entity = new ItemEntity(world, px, py, pz, stack);
entity.setDefaultPickupDelay();
world.addEntity(entity);
entity.setDefaultPickUpDelay();
world.addFreshEntity(entity);
return Optional.of(entity);
}
public static Optional<ItemEntity> spawnAsEntity(final World world, final BlockPos pos, final ItemStack stack, @Nullable final Direction direction) {
return spawnAsEntity(world, Vector3d.copyCentered(pos), stack, direction);
return spawnAsEntity(world, Vector3d.atCenterOf(pos), stack, direction);
}
public static Optional<ItemEntity> spawnAsEntity(final World world, final Vector3d pos, final ItemStack stack, @Nullable final Direction direction) {
@@ -57,32 +57,32 @@ public final class ItemStackUtils {
return spawnAsEntity(world, pos, stack);
}
if (world.isRemote() || stack.isEmpty()) {
if (world.isClientSide || stack.isEmpty()) {
return Optional.empty();
}
final Random rng = world.rand;
final Random rng = world.random;
final float ox = direction.getXOffset();
final float oy = direction.getYOffset();
final float oz = direction.getZOffset();
final float ox = direction.getStepX();
final float oy = direction.getStepY();
final float oz = direction.getStepZ();
final float tx = 0.1f * (rng.nextFloat() - 0.5f) + ox * 0.65f;
final float ty = 0.1f * (rng.nextFloat() - 0.5f) + oy * 0.75f + (ox + oz) * 0.25f;
final float tz = 0.1f * (rng.nextFloat() - 0.5f) + oz * 0.65f;
final double px = pos.getX() + tx;
final double py = pos.getY() + ty;
final double pz = pos.getZ() + tz;
final double px = pos.x + tx;
final double py = pos.y + ty;
final double pz = pos.z + tz;
final ItemEntity entity = new ItemEntity(world, px, py, pz, stack);
entity.setMotion(
entity.moveTo(
0.0125 * (rng.nextDouble() - 0.5) + ox * 0.03,
0.0125 * (rng.nextDouble() - 0.5) + oy * 0.08 + (ox + oz) * 0.03,
0.0125 * (rng.nextDouble() - 0.5) + oz * 0.03
);
entity.setDefaultPickupDelay();
world.addEntity(entity);
entity.setDefaultPickUpDelay();
world.addFreshEntity(entity);
return Optional.of(entity);
}

View File

@@ -5,6 +5,7 @@ import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IWorld;
import java.util.Objects;
import java.util.Optional;
public final class Location {
@@ -18,7 +19,7 @@ public final class Location {
public static Optional<Location> of(final Entity entity) {
if (entity.isAlive()) {
return Optional.of(new Location(entity.getEntityWorld(), entity.getPosition()));
return Optional.of(new Location(entity.level, entity.blockPosition()));
} else {
return Optional.empty();
}
@@ -26,7 +27,7 @@ public final class Location {
public static Optional<Location> of(final TileEntity tileEntity) {
if (!tileEntity.isRemoved()) {
return Optional.of(new Location(tileEntity.getWorld(), tileEntity.getPos()));
return Optional.of(new Location(Objects.requireNonNull(tileEntity.getLevel()), tileEntity.getBlockPos()));
} else {
return Optional.empty();
}

View File

@@ -18,7 +18,7 @@ public final class LocationSupplierUtils {
}
public static Supplier<Optional<Location>> of(final BlockDeviceQuery query) {
final Optional<Location> location = Optional.of(new Location(query.getWorld(), query.getQueryPosition()));
final Optional<Location> location = Optional.of(new Location(query.getLevel(), query.getQueryPosition()));
return () -> location;
}

View File

@@ -56,6 +56,6 @@ public final class NBTUtils {
}
public static CompoundNBT makeInventoryTag(final ItemStack... items) {
return new ItemStackHandler(NonNullList.from(ItemStack.EMPTY, items)).serializeNBT();
return new ItemStackHandler(NonNullList.of(ItemStack.EMPTY, items)).serializeNBT();
}
}

View File

@@ -24,18 +24,18 @@ public final class ResourceUtils {
try (final IResource metadataResource = manager.getResource(metadataLocation)) {
final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(metadataResource.getInputStream(), StandardCharsets.UTF_8));
final JsonObject metadataJson = JSONUtils.fromJson(bufferedReader);
final JsonObject metadataJson = JSONUtils.parse(bufferedReader);
if (metadataJson == null) {
return null;
}
final String sectionName = serializer.getSectionName();
final String sectionName = serializer.getMetadataSectionName();
if (!metadataJson.has(sectionName)) {
return null;
}
final JsonObject section = JSONUtils.getJsonObject(metadataJson, sectionName);
return serializer.deserialize(section);
final JsonObject section = JSONUtils.convertToJsonObject(metadataJson, sectionName);
return serializer.fromJson(section);
}
}
}

View File

@@ -131,7 +131,7 @@ public final class ServerScheduler {
@SubscribeEvent
public static void handleChunkLoad(final ChunkEvent.Load event) {
final HashMap<ChunkPos, SimpleScheduler> chunkMap = chunkLoadSchedulers.get(event.getWorld());
final HashMap<ChunkPos, SimpleScheduler> chunkMap = chunkLoadSchedulers.get(event.getChunk());
if (chunkMap == null) {
return;
}
@@ -144,7 +144,7 @@ public final class ServerScheduler {
@SubscribeEvent
public static void handleChunkUnload(final ChunkEvent.Unload event) {
final HashMap<ChunkPos, SimpleScheduler> chunkMap = chunkUnloadSchedulers.get(event.getWorld());
final HashMap<ChunkPos, SimpleScheduler> chunkMap = chunkUnloadSchedulers.get(event.getChunk());
if (chunkMap == null) {
return;
}

View File

@@ -26,7 +26,7 @@ import static li.cil.oc2.common.Constants.*;
public final class TooltipUtils {
private static final IFormattableTextComponent DEVICE_NEEDS_REBOOT =
new TranslationTextComponent(Constants.TOOLTIP_DEVICE_NEEDS_REBOOT)
.modifyStyle(s -> s.setColor(Color.fromTextFormatting(TextFormatting.YELLOW)));
.withStyle(s -> s.withColor(Color.fromLegacyFormat(TextFormatting.YELLOW)));
private static final ThreadLocal<List<ItemStack>> ITEM_STACKS = ThreadLocal.withInitial(ArrayList::new);
private static final ThreadLocal<IntList> ITEM_STACKS_SIZES = ThreadLocal.withInitial(IntArrayList::new);
@@ -38,9 +38,9 @@ public final class TooltipUtils {
return;
}
final String translationKey = stack.getTranslationKey() + Constants.TOOLTIP_DESCRIPTION_SUFFIX;
final String translationKey = stack.getDescriptionId() + Constants.TOOLTIP_DESCRIPTION_SUFFIX;
final LanguageMap languagemap = LanguageMap.getInstance();
if (languagemap.func_230506_b_(translationKey)) {
if (languagemap.has(translationKey)) {
final TranslationTextComponent description = new TranslationTextComponent(translationKey);
tooltip.add(withColor(description, TextFormatting.GRAY));
}
@@ -48,7 +48,7 @@ public final class TooltipUtils {
// Tooltips get queried very early in Minecraft initialization, meaning tags may not
// have been initialized. Trying to directly use our tag would lead to an exception
// in that case, so we do the detour through the collection instead.
final ITag<Item> tag = net.minecraft.tags.ItemTags.getCollection().get(ItemTags.DEVICE_NEEDS_REBOOT.getName());
final ITag<Item> tag = net.minecraft.tags.ItemTags.getAllTags().getTag(ItemTags.DEVICE_NEEDS_REBOOT.getName());
if (tag != null && tag.contains(stack.getItem())) {
tooltip.add(DEVICE_NEEDS_REBOOT);
}
@@ -91,10 +91,10 @@ public final class TooltipUtils {
final ItemStack itemStack = itemStacks.get(i);
tooltip.add(new StringTextComponent("- ")
.append(itemStack.getDisplayName())
.modifyStyle(style -> style.setColor(Color.fromTextFormatting(TextFormatting.GRAY)))
.withStyle(style -> style.withColor(Color.fromLegacyFormat(TextFormatting.GRAY)))
.append(new StringTextComponent(" x")
.appendString(String.valueOf(itemStackSizes.getInt(i)))
.modifyStyle(style -> style.setColor(Color.fromTextFormatting(TextFormatting.DARK_GRAY))))
.append(String.valueOf(itemStackSizes.getInt(i)))
.withStyle(style -> style.withColor(Color.fromLegacyFormat(TextFormatting.DARK_GRAY))))
);
}
}
@@ -121,7 +121,7 @@ public final class TooltipUtils {
}
public static IFormattableTextComponent withColor(final IFormattableTextComponent text, final TextFormatting formatting) {
return text.modifyStyle(s -> s.setColor(Color.fromTextFormatting(formatting)));
return text.withStyle(s -> s.withColor(Color.fromLegacyFormat(formatting)));
}
///////////////////////////////////////////////////////////////////
@@ -140,13 +140,13 @@ public final class TooltipUtils {
final ListNBT itemsTag = tag.getList("Items", NBTTagIds.TAG_COMPOUND);
for (int i = 0; i < itemsTag.size(); i++) {
final CompoundNBT itemTag = itemsTag.getCompound(i);
final ItemStack itemStack = ItemStack.read(itemTag);
final ItemStack itemStack = ItemStack.of(itemTag);
boolean didMerge = false;
for (int j = 0; j < stacks.size(); j++) {
final ItemStack existingStack = stacks.get(j);
if (ItemStack.areItemsEqual(existingStack, itemStack) &&
ItemStack.areItemStackTagsEqual(existingStack, itemStack)) {
if (ItemStack.matches(existingStack, itemStack) &&
ItemStack.matches(existingStack, itemStack)) {
final int existingCount = stackSizes.getInt(j);
stackSizes.set(j, existingCount + itemStack.getCount());
didMerge = true;

View File

@@ -8,9 +8,9 @@ public final class VoxelShapeUtils {
public static VoxelShape rotateHorizontalClockwise(final VoxelShape shape) {
TEMP_SHAPE.set(VoxelShapes.empty());
shape.forEachBox((minX, minY, minZ, maxX, maxY, maxZ) -> {
shape.forAllBoxes((minX, minY, minZ, maxX, maxY, maxZ) -> {
TEMP_SHAPE.set(VoxelShapes.or(TEMP_SHAPE.get(),
VoxelShapes.create(minZ, minY, 1.0 - minX, maxZ, maxY, 1.0 - maxX)
VoxelShapes.box(minZ, minY, 1.0 - minX, maxZ, maxY, 1.0 - maxX)
));
});
return TEMP_SHAPE.get();

View File

@@ -15,23 +15,23 @@ import java.util.function.Function;
public final class WorldUtils {
@Nullable
public static TileEntity getTileEntityIfChunkExists(final IWorld world, final BlockPos pos) {
public static TileEntity getBlockEntityIfChunkExists(final IWorld world, final BlockPos pos) {
final ChunkPos chunkPos = new ChunkPos(pos);
if (!world.chunkExists(chunkPos.x, chunkPos.z)) {
if (!world.hasChunk(chunkPos.x, chunkPos.z)) {
return null;
}
return world.getTileEntity(pos);
return world.getBlockEntity(pos);
}
@Nullable
public static String getBlockName(final IWorld world, final BlockPos pos) {
final ChunkPos chunkPos = new ChunkPos(pos);
if (!world.chunkExists(chunkPos.x, chunkPos.z)) {
if (!world.hasChunk(chunkPos.x, chunkPos.z)) {
return null;
}
final TileEntity tileEntity = world.getTileEntity(pos);
final TileEntity tileEntity = world.getBlockEntity(pos);
if (tileEntity != null) {
final ResourceLocation registryName = tileEntity.getType().getRegistryName();
if (registryName != null) {

View File

@@ -115,7 +115,7 @@ public final class Terminal {
if (hasPendingBell) {
hasPendingBell = false;
final Minecraft client = Minecraft.getInstance();
client.execute(() -> client.getSoundHandler().play(SimpleSound.master(NoteBlockInstrument.PLING.getSound(), 1)));
client.execute(() -> client.getSoundManager().play(SimpleSound.forUI(NoteBlockInstrument.PLING.getSoundEvent(), 1)));
}
if (renderer == null) {
@@ -552,23 +552,23 @@ public final class Terminal {
///////////////////////////////////////////////////////////////
private void renderBuffer() {
GlStateManager.depthMask(false);
Minecraft.getInstance().getTextureManager().bindTexture(LOCATION_FONT_TEXTURE);
GlStateManager._depthMask(false);
Minecraft.getInstance().getTextureManager().bind(LOCATION_FONT_TEXTURE);
final BufferBuilder buffer = Tessellator.getInstance().getBuffer();
final BufferBuilder buffer = Tessellator.getInstance().getBuilder();
for (final Object line : lines) {
buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_COLOR_TEX);
buffer.setVertexState((BufferBuilder.State) line);
buffer.finishDrawing();
WorldVertexBufferUploader.draw(buffer);
buffer.restoreState((BufferBuilder.State) line);
buffer.end();
WorldVertexBufferUploader.end(buffer);
}
GlStateManager.depthMask(true);
GlStateManager._depthMask(true);
}
private void validateLineCache(final AtomicInteger dirty, final MatrixStack stack) {
if (!Objects.equals(lastMatrix, stack.getLast().getMatrix())) {
lastMatrix = stack.getLast().getMatrix();
if (!Objects.equals(lastMatrix, stack.last().pose())) {
lastMatrix = stack.last().pose();
dirty.set(-1);
}
@@ -576,7 +576,7 @@ public final class Terminal {
return;
}
final BufferBuilder buffer = Tessellator.getInstance().getBuffer();
final BufferBuilder buffer = Tessellator.getInstance().getBuilder();
final int mask = dirty.getAndSet(0);
for (int row = 0; row < lines.length; row++) {
@@ -584,20 +584,20 @@ public final class Terminal {
continue;
}
stack.push();
stack.pushPose();
stack.translate(0, row * CHAR_HEIGHT, 0);
final Matrix4f matrix = stack.getLast().getMatrix();
final Matrix4f matrix = stack.last().pose();
buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_COLOR_TEX);
renderBackground(matrix, buffer, row);
renderForeground(matrix, buffer, row);
lines[row] = buffer.getVertexState();
buffer.finishDrawing();
lines[row] = buffer.getState();
buffer.end();
buffer.discard();
stack.pop();
stack.popPose();
}
}
@@ -651,10 +651,10 @@ public final class Terminal {
final float ulu = (TEXTURE_RESOLUTION - 1) / (float) TEXTURE_RESOLUTION;
final float ulv = 1 / (float) TEXTURE_RESOLUTION;
buffer.pos(matrix, x0, CHAR_HEIGHT, 0).color(r, g, b, 1).tex(ulu, ulv).endVertex();
buffer.pos(matrix, x1, CHAR_HEIGHT, 0).color(r, g, b, 1).tex(ulu, ulv).endVertex();
buffer.pos(matrix, x1, 0, 0).color(r, g, b, 1).tex(ulu, ulv).endVertex();
buffer.pos(matrix, x0, 0, 0).color(r, g, b, 1).tex(ulu, ulv).endVertex();
buffer.vertex(matrix, x0, CHAR_HEIGHT, 0).color(r, g, b, 1).uv(ulu, ulv).endVertex();
buffer.vertex(matrix, x1, CHAR_HEIGHT, 0).color(r, g, b, 1).uv(ulu, ulv).endVertex();
buffer.vertex(matrix, x1, 0, 0).color(r, g, b, 1).uv(ulu, ulv).endVertex();
buffer.vertex(matrix, x0, 0, 0).color(r, g, b, 1).uv(ulu, ulv).endVertex();
}
private void renderForeground(final Matrix4f matrix, final BufferBuilder buffer, final int row) {
@@ -692,20 +692,20 @@ public final class Terminal {
final float v0 = y * (CHAR_HEIGHT * ONE_OVER_TEXTURE_RESOLUTION);
final float v1 = (y + 1) * (CHAR_HEIGHT * ONE_OVER_TEXTURE_RESOLUTION);
buffer.pos(matrix, offset, CHAR_HEIGHT, 0).color(r, g, b, 1).tex(u0, v1).endVertex();
buffer.pos(matrix, offset + CHAR_WIDTH, CHAR_HEIGHT, 0).color(r, g, b, 1).tex(u1, v1).endVertex();
buffer.pos(matrix, offset + CHAR_WIDTH, 0, 0).color(r, g, b, 1).tex(u1, v0).endVertex();
buffer.pos(matrix, offset, 0, 0).color(r, g, b, 1).tex(u0, v0).endVertex();
buffer.vertex(matrix, offset, CHAR_HEIGHT, 0).color(r, g, b, 1).uv(u0, v1).endVertex();
buffer.vertex(matrix, offset + CHAR_WIDTH, CHAR_HEIGHT, 0).color(r, g, b, 1).uv(u1, v1).endVertex();
buffer.vertex(matrix, offset + CHAR_WIDTH, 0, 0).color(r, g, b, 1).uv(u1, v0).endVertex();
buffer.vertex(matrix, offset, 0, 0).color(r, g, b, 1).uv(u0, v0).endVertex();
}
if ((style & STYLE_UNDERLINE_MASK) != 0) {
final float ulu = (TEXTURE_RESOLUTION - 1) / (float) TEXTURE_RESOLUTION;
final float ulv = 1 / (float) TEXTURE_RESOLUTION;
buffer.pos(matrix, offset, CHAR_HEIGHT - 3, 0).color(r, g, b, 1).tex(ulu, ulv).endVertex();
buffer.pos(matrix, offset + CHAR_WIDTH, CHAR_HEIGHT - 3, 0).color(r, g, b, 1).tex(ulu, ulv).endVertex();
buffer.pos(matrix, offset + CHAR_WIDTH, CHAR_HEIGHT - 2, 0).color(r, g, b, 1).tex(ulu, ulv).endVertex();
buffer.pos(matrix, offset, CHAR_HEIGHT - 2, 0).color(r, g, b, 1).tex(ulu, ulv).endVertex();
buffer.vertex(matrix, offset, CHAR_HEIGHT - 3, 0).color(r, g, b, 1).uv(ulu, ulv).endVertex();
buffer.vertex(matrix, offset + CHAR_WIDTH, CHAR_HEIGHT - 3, 0).color(r, g, b, 1).uv(ulu, ulv).endVertex();
buffer.vertex(matrix, offset + CHAR_WIDTH, CHAR_HEIGHT - 2, 0).color(r, g, b, 1).uv(ulu, ulv).endVertex();
buffer.vertex(matrix, offset, CHAR_HEIGHT - 2, 0).color(r, g, b, 1).uv(ulu, ulv).endVertex();
}
}
@@ -714,14 +714,14 @@ public final class Terminal {
return;
}
GlStateManager.depthMask(false);
GlStateManager._depthMask(false);
RenderSystem.disableTexture();
stack.push();
stack.pushPose();
stack.translate(terminal.x * CHAR_WIDTH, terminal.y * CHAR_HEIGHT, 0);
final Matrix4f matrix = stack.getLast().getMatrix();
final BufferBuilder buffer = Tessellator.getInstance().getBuffer();
final Matrix4f matrix = stack.last().pose();
final BufferBuilder buffer = Tessellator.getInstance().getBuilder();
buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_COLOR);
final int foreground = COLORS[COLOR_WHITE];
@@ -729,18 +729,18 @@ public final class Terminal {
final float g = ((foreground >> 8) & 0xFF) / 255f;
final float b = ((foreground) & 0xFF) / 255f;
buffer.pos(matrix, 0, CHAR_HEIGHT, 0).color(r, g, b, 1).endVertex();
buffer.pos(matrix, CHAR_WIDTH, CHAR_HEIGHT, 0).color(r, g, b, 1).endVertex();
buffer.pos(matrix, CHAR_WIDTH, 0, 0).color(r, g, b, 1).endVertex();
buffer.pos(matrix, 0, 0, 0).color(r, g, b, 1).endVertex();
buffer.vertex(matrix, 0, CHAR_HEIGHT, 0).color(r, g, b, 1).endVertex();
buffer.vertex(matrix, CHAR_WIDTH, CHAR_HEIGHT, 0).color(r, g, b, 1).endVertex();
buffer.vertex(matrix, CHAR_WIDTH, 0, 0).color(r, g, b, 1).endVertex();
buffer.vertex(matrix, 0, 0, 0).color(r, g, b, 1).endVertex();
buffer.finishDrawing();
WorldVertexBufferUploader.draw(buffer);
buffer.end();
WorldVertexBufferUploader.end(buffer);
stack.pop();
stack.popPose();
RenderSystem.enableTexture();
GlStateManager.depthMask(true);
GlStateManager._depthMask(true);
}
private static boolean isPrintableCharacter(final char ch) {