PhysicalConnectivity/src/main/kotlin/net/shadowfacts/phycon/network/NetworkUtil.kt

58 lines
1.5 KiB
Kotlin
Raw Normal View History

2019-10-27 01:36:31 +00:00
package net.shadowfacts.phycon.network
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.Direction
import net.minecraft.world.World
import net.shadowfacts.phycon.api.NetworkCable
import net.shadowfacts.phycon.api.NetworkComponent
2019-10-27 01:36:31 +00:00
import net.shadowfacts.phycon.api.PacketSink
import net.shadowfacts.phycon.api.PhyAttributes
import java.util.*
/**
* @author shadowfacts
*/
object NetworkUtil {
2019-10-27 03:13:26 +00:00
fun findDestinations(world: World, startPos: BlockPos, direction: Direction? = null): List<PacketSink> {
2019-10-27 01:49:34 +00:00
val results = LinkedList<PacketSink>()
2019-10-27 01:36:31 +00:00
val visited = hashSetOf(startPos)
val queue = LinkedList<BlockPos>()
2019-10-27 03:13:26 +00:00
if (direction != null) {
queue.add(startPos.offset(direction))
} else {
findEdges(queue, visited, world, startPos, includeNonCables = true)
2019-10-27 03:13:26 +00:00
}
2019-10-27 01:49:34 +00:00
2019-10-27 01:36:31 +00:00
while (queue.isNotEmpty()) {
val pos = queue.pop()
2019-10-27 01:49:34 +00:00
2019-10-27 01:36:31 +00:00
val sink = PhyAttributes.PACKET_SINK.getFirstOrNull(world, pos)
if (sink != null) {
results.add(sink)
}
2019-10-27 01:49:34 +00:00
findEdges(queue, visited, world, pos)
2019-10-27 01:49:34 +00:00
2019-10-27 01:36:31 +00:00
visited.add(pos)
}
2019-10-27 01:49:34 +00:00
2019-10-27 01:36:31 +00:00
return results
}
private fun findEdges(queue: MutableList<BlockPos>, visited: Set<BlockPos>, world: World, pos: BlockPos, includeNonCables: Boolean = false) {
val state = world.getBlockState(pos)
val block = state.block
if (block is NetworkComponent && (includeNonCables || block is NetworkCable)) {
val connections = block.getNetworkConnectedSides(state, world, pos)
for (side in connections) {
val newPos = pos.offset(side)
if (newPos !in visited) {
queue.add(newPos)
}
}
}
}
2019-10-27 01:36:31 +00:00
}