package net.shadowfacts.phycon.network.block.redstone import net.minecraft.block.Block import net.minecraft.block.BlockState import net.minecraft.block.Material import net.minecraft.item.ItemPlacementContext import net.minecraft.server.world.ServerWorld import net.minecraft.state.StateManager import net.minecraft.state.property.Properties import net.minecraft.util.Identifier import net.minecraft.util.math.BlockPos import net.minecraft.util.math.Direction import net.minecraft.world.BlockView import net.minecraft.world.World import net.shadowfacts.phycon.PhysicalConnectivity import net.shadowfacts.phycon.network.FaceDeviceBlock import java.util.* /** * @author shadowfacts */ class RedstoneControllerBlock: FaceDeviceBlock(Settings.of(Material.METAL)) { companion object { val ID = Identifier(PhysicalConnectivity.MODID, "redstone_controller") val LIT = Properties.LIT } // todo: don't just copy this from the Interface block override val faceThickness = 2.0 override val faceShapes = mapOf( Direction.DOWN to createCuboidShape(0.0, 0.0, 0.0, 16.0, 2.0, 16.0), Direction.UP to createCuboidShape(0.0, 14.0, 0.0, 16.0, 16.0, 16.0), Direction.NORTH to createCuboidShape(0.0, 0.0, 0.0, 16.0, 16.0, 2.0), Direction.SOUTH to createCuboidShape(0.0, 0.0, 14.0, 16.0, 16.0, 16.0), Direction.WEST to createCuboidShape(0.0, 0.0, 0.0, 2.0, 16.0, 16.0), Direction.EAST to createCuboidShape(14.0, 0.0, 0.0, 16.0, 16.0, 16.0) ) override fun appendProperties(builder: StateManager.Builder) { super.appendProperties(builder) builder.add(LIT) } override fun createBlockEntity(world: BlockView) = RedstoneControllerBlockEntity() override fun getPlacementState(context: ItemPlacementContext): BlockState { val state = super.getPlacementState(context) return state.with(LIT, isPowered(context.world, context.blockPos, state[FACING])) } // todo: does this need to be separate from getStateForNeighborUpdate? override fun neighborUpdate(state: BlockState, world: World, pos: BlockPos, neighborBlock: Block, neighborPos: BlockPos, bl: Boolean) { if (!world.isClient) { val wasLit = state[LIT] val isLit = isPowered(world, pos, state[FACING]) if (wasLit != isLit) { if (wasLit) { world.blockTickScheduler.schedule(pos, this, 4) } else { toggleLit(state, world, pos) } } } } override fun scheduledTick(state: BlockState, world: ServerWorld, pos: BlockPos, random: Random) { if (state[LIT] && !isPowered(world, pos, state[FACING])) { toggleLit(state, world, pos) } } private fun isPowered(world: World, pos: BlockPos, facing: Direction): Boolean { val offset = pos.offset(facing) return world.getEmittedRedstonePower(offset, facing) > 0 } private fun toggleLit(state: BlockState, world: World, pos: BlockPos) { world.setBlockState(pos, state.cycle(LIT), 2) getBlockEntity(world, pos)!!.redstoneStateChanged() } }