| 25 | import java.util.concurrent.atomic.AtomicInteger; |
| 26 | |
| 27 | public class PowergenBE extends BlockEntity { |
| 28 | |
| 29 | // Never create lazy optionals in getCapability. Always place them as fields in the tile entity: |
| 30 | private final ItemStackHandler itemHandler = createHandler(); |
| 31 | private final LazyOptional<IItemHandler> handler = LazyOptional.of(() -> itemHandler); |
| 32 | |
| 33 | private final CustomEnergyStorage energyStorage = createEnergy(); |
| 34 | private final LazyOptional<IEnergyStorage> energy = LazyOptional.of(() -> energyStorage); |
| 35 | |
| 36 | private int counter; |
| 37 | |
| 38 | public PowergenBE(BlockPos pos, BlockState state) { |
| 39 | super(Registration.POWERGEN_BE.get(), pos, state); |
| 40 | } |
| 41 | |
| 42 | |
| 43 | @Override |
| 44 | public void setRemoved() { |
| 45 | super.setRemoved(); |
| 46 | handler.invalidate(); |
| 47 | energy.invalidate(); |
| 48 | } |
| 49 | |
| 50 | public void tickServer() { |
| 51 | if (counter > 0) { |
| 52 | energyStorage.addEnergy(PowergenConfig.POWERGEN_GENERATE.get()); |
| 53 | counter--; |
| 54 | setChanged(); |
| 55 | } |
| 56 | |
| 57 | if (counter <= 0) { |
| 58 | ItemStack stack = itemHandler.getStackInSlot(0); |
| 59 | int burnTime = ForgeHooks.getBurnTime(stack, RecipeType.SMELTING); |
| 60 | if (burnTime > 0) { |
| 61 | itemHandler.extractItem(0, 1, false); |
| 62 | counter = burnTime; |
| 63 | setChanged(); |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | BlockState blockState = level.getBlockState(worldPosition); |
| 68 | if (blockState.getValue(BlockStateProperties.POWERED) != counter > 0) { |
| 69 | level.setBlock(worldPosition, blockState.setValue(BlockStateProperties.POWERED, counter > 0), |
| 70 | Block.UPDATE_ALL); |
| 71 | } |
| 72 | |
| 73 | sendOutPower(); |
| 74 | } |
| 75 | |
| 76 | private void sendOutPower() { |
| 77 | AtomicInteger capacity = new AtomicInteger(energyStorage.getEnergyStored()); |
| 78 | if (capacity.get() > 0) { |
| 79 | for (Direction direction : Direction.values()) { |
| 80 | BlockEntity be = level.getBlockEntity(worldPosition.relative(direction)); |
| 81 | if (be != null) { |
| 82 | boolean doContinue = be.getCapability(CapabilityEnergy.ENERGY, direction.getOpposite()).map(handler -> { |
| 83 | if (handler.canReceive()) { |
| 84 | int received = handler.receiveEnergy(Math.min(capacity.get(), PowergenConfig.POWERGEN_SEND.get()), false); |
nothing calls this directly
no test coverage detected