Add resource patch labels to the web map
Group nearby resource tiles of the same type into patches, and label
them on the map, e.g. "Iron ore / 2.4M", or "Crude oil / 12 wells".
- events-library: ResourcePatch model, shared by the server and map.
- events-server-web: ResourcePatchService reads the map-chunk-resource
topic from the beginning (read_committed) into memory, and on request
groups tiles into connected patches (join distance 2 tiles for ore,
12 for infinite resources, whose wells are spread out). Results are
cached until new data arrives.
New endpoint: GET .../servers/{id}/map/resources/s{surface}/patches
- web-map: toggleable "Resource patches" overlay with labels at each
patch centre and a hover tooltip, refreshed every minute. Patches
under 10 tiles are hidden. (Surface 1 only, like the rest of the map.)
- events-mod: mark resources infinite based on the prototype's
infinite_resource. Entity initial_amount is nil for e.g. crude oil, so
oil fields were treated as hundreds of tiny ore patches.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
d5f722b998
commit
3d8673fe03
10 changed files with 388 additions and 5 deletions
|
|
@ -4,6 +4,7 @@ import dev.adamko.kafkatorio.processor.config.ApplicationProperties
|
|||
import dev.adamko.kafkatorio.processor.core.launchTopology
|
||||
import dev.adamko.kafkatorio.server.processor.topology.broadcastToWebsocket
|
||||
import dev.adamko.kafkatorio.server.processor.topology.saveMapTiles
|
||||
import dev.adamko.kafkatorio.server.web.resources.ResourcePatchService
|
||||
import dev.adamko.kafkatorio.server.web.websocket.WebmapWebsocketServer
|
||||
import kotlin.time.Duration.Companion.milliseconds
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
|
|
@ -17,6 +18,7 @@ internal val appProps = ApplicationProperties.load()
|
|||
|
||||
suspend fun main(): Unit = coroutineScope {
|
||||
val wsServer = WebmapWebsocketServer()
|
||||
val resourcePatchService = ResourcePatchService(appProps)
|
||||
|
||||
launch {
|
||||
websocketBroadcaster(wsServer)
|
||||
|
|
@ -30,10 +32,15 @@ suspend fun main(): Unit = coroutineScope {
|
|||
saveTiles(appProps)
|
||||
}
|
||||
|
||||
launch {
|
||||
resourcePatchService.consume()
|
||||
}
|
||||
|
||||
launch {
|
||||
startWebServer(
|
||||
appProps = appProps,
|
||||
wsServer = wsServer,
|
||||
resourcePatchService = resourcePatchService,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,227 @@
|
|||
package dev.adamko.kafkatorio.server.web.resources
|
||||
|
||||
import dev.adamko.kafkatorio.processor.config.ApplicationProperties
|
||||
import dev.adamko.kafkatorio.server.web.config.jsonMapper
|
||||
import dev.adamko.kafkatorio.processor.config.topicName
|
||||
import dev.adamko.kafkatorio.schema.common.FactorioServerId
|
||||
import dev.adamko.kafkatorio.schema.common.MapChunkPosition
|
||||
import dev.adamko.kafkatorio.schema.common.MapEntityPosition
|
||||
import dev.adamko.kafkatorio.schema.common.PrototypeId
|
||||
import dev.adamko.kafkatorio.schema.common.ResourcePatch
|
||||
import dev.adamko.kafkatorio.schema.common.SurfaceIndex
|
||||
import dev.adamko.kafkatorio.schema.packets.KafkatorioPacket
|
||||
import dev.adamko.kafkatorio.schema.packets.MapChunkResourceUpdate
|
||||
import java.time.Duration
|
||||
import java.util.Properties
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
import kotlin.math.floor
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.runInterruptible
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.apache.kafka.clients.consumer.ConsumerConfig
|
||||
import org.apache.kafka.clients.consumer.KafkaConsumer
|
||||
import org.apache.kafka.common.TopicPartition
|
||||
import org.apache.kafka.common.serialization.StringDeserializer
|
||||
|
||||
|
||||
/**
|
||||
* Keeps the latest amount of every resource tile in memory, and groups nearby tiles of the same
|
||||
* resource into [ResourcePatch]es.
|
||||
*
|
||||
* Resource data is small, so instead of a Kafka Streams state store, the whole
|
||||
* [MapChunkResourceUpdate] topic is read from the beginning on startup, and then followed.
|
||||
*/
|
||||
class ResourcePatchService(
|
||||
private val appProps: ApplicationProperties,
|
||||
) {
|
||||
|
||||
private data class ChunkKey(
|
||||
val serverId: FactorioServerId,
|
||||
val protoId: PrototypeId,
|
||||
val surfaceIndex: SurfaceIndex,
|
||||
val chunkPosition: MapChunkPosition,
|
||||
)
|
||||
|
||||
private class ChunkResources(
|
||||
val amounts: MutableMap<MapEntityPosition, UInt> = mutableMapOf(),
|
||||
var isInfinite: Boolean = false,
|
||||
)
|
||||
|
||||
private val chunks = ConcurrentHashMap<ChunkKey, ChunkResources>()
|
||||
|
||||
/** Incremented on every update, so cached patches can be invalidated. */
|
||||
private val version = AtomicLong(0)
|
||||
|
||||
private data class CachedPatches(val version: Long, val patches: List<ResourcePatch>)
|
||||
|
||||
private val patchCache = ConcurrentHashMap<Pair<FactorioServerId, SurfaceIndex>, CachedPatches>()
|
||||
|
||||
|
||||
/** Read all resource updates from the beginning of the topic, and keep following it. */
|
||||
suspend fun consume(): Unit = withContext(Dispatchers.IO) {
|
||||
val topic = MapChunkResourceUpdate::class.topicName
|
||||
|
||||
KafkaConsumer(consumerProperties(), StringDeserializer(), StringDeserializer()).use { consumer ->
|
||||
val partitions = consumer.partitionsFor(topic).map { TopicPartition(it.topic(), it.partition()) }
|
||||
consumer.assign(partitions)
|
||||
consumer.seekToBeginning(partitions)
|
||||
println("[ResourcePatchService] consuming $topic, partitions: ${partitions.size}")
|
||||
|
||||
while (isActive) {
|
||||
val records = runInterruptible { consumer.poll(Duration.ofSeconds(1)) }
|
||||
for (record in records) {
|
||||
runCatching { handleRecord(record.key(), record.value()) }
|
||||
.onFailure { println("[ResourcePatchService] failed to read record: $it") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private fun consumerProperties() = Properties().apply {
|
||||
putAll(appProps.kafkaStreamsConfig.filterKeys { it == ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG })
|
||||
// Kafkatorio processors write transactionally - only read committed data
|
||||
put(ConsumerConfig.ISOLATION_LEVEL_CONFIG, "read_committed")
|
||||
put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false")
|
||||
put(ConsumerConfig.CLIENT_ID_CONFIG, "kafkatorio.events-server-web.resource-patches")
|
||||
}
|
||||
|
||||
|
||||
private fun handleRecord(key: String?, value: String?) {
|
||||
if (key == null || value == null) return
|
||||
|
||||
val serverId = jsonMapper.decodeFromString(FactorioServerId.serializer(), key)
|
||||
val update = jsonMapper.decodeFromString(KafkatorioPacket.serializer(), value).data
|
||||
as? MapChunkResourceUpdate ?: return
|
||||
|
||||
val chunkKey = ChunkKey(
|
||||
serverId = serverId,
|
||||
protoId = update.key.protoId,
|
||||
surfaceIndex = update.key.surfaceIndex,
|
||||
chunkPosition = update.key.chunkPosition,
|
||||
)
|
||||
|
||||
val chunk = chunks.computeIfAbsent(chunkKey) { ChunkResources() }
|
||||
synchronized(chunk) {
|
||||
// Updates contain the current amount of the tiles that were (re-)scanned, so merge them.
|
||||
// Note: depleted tiles aren't reported by the mod, so they keep their last known amount.
|
||||
update.amounts.forEach { (position, amount) -> chunk.amounts[position] = amount }
|
||||
if (update.initialAmounts.any()) chunk.isInfinite = true
|
||||
}
|
||||
version.incrementAndGet()
|
||||
}
|
||||
|
||||
|
||||
fun patches(serverId: FactorioServerId, surfaceIndex: SurfaceIndex): List<ResourcePatch> {
|
||||
val currentVersion = version.get()
|
||||
val cacheKey = serverId to surfaceIndex
|
||||
|
||||
patchCache[cacheKey]?.let { cached ->
|
||||
if (cached.version == currentVersion) return cached.patches
|
||||
}
|
||||
|
||||
val patches = computePatches(serverId, surfaceIndex)
|
||||
patchCache[cacheKey] = CachedPatches(currentVersion, patches)
|
||||
return patches
|
||||
}
|
||||
|
||||
|
||||
private fun computePatches(
|
||||
serverId: FactorioServerId,
|
||||
surfaceIndex: SurfaceIndex,
|
||||
): List<ResourcePatch> {
|
||||
|
||||
// collect all tiles per resource prototype
|
||||
val tilesByProto = mutableMapOf<PrototypeId, MutableMap<Long, UInt>>()
|
||||
val infiniteProtos = mutableSetOf<PrototypeId>()
|
||||
|
||||
chunks.forEach { (key, chunk) ->
|
||||
if (key.serverId != serverId || key.surfaceIndex != surfaceIndex) return@forEach
|
||||
val tiles = tilesByProto.getOrPut(key.protoId) { mutableMapOf() }
|
||||
synchronized(chunk) {
|
||||
if (chunk.isInfinite) infiniteProtos += key.protoId
|
||||
chunk.amounts.forEach { (position, amount) ->
|
||||
tiles[packTile(floor(position.x).toInt(), floor(position.y).toInt())] = amount
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return tilesByProto.flatMap { (protoId, tiles) ->
|
||||
val isInfinite = protoId in infiniteProtos
|
||||
// Ore tiles in a patch are (nearly) contiguous, but oil wells are spread out.
|
||||
val joinDistance = if (isInfinite) INFINITE_RESOURCE_JOIN_DISTANCE else ORE_JOIN_DISTANCE
|
||||
groupIntoPatches(tiles, joinDistance).map { patchTiles ->
|
||||
createPatch(protoId, surfaceIndex, isInfinite, patchTiles, tiles)
|
||||
}
|
||||
}.sortedByDescending { it.tileCount }
|
||||
}
|
||||
|
||||
|
||||
/** Group tiles into connected components, where tiles within [joinDistance] are connected. */
|
||||
private fun groupIntoPatches(tiles: Map<Long, UInt>, joinDistance: Int): List<List<Long>> {
|
||||
val unvisited = tiles.keys.toMutableSet()
|
||||
val patches = mutableListOf<List<Long>>()
|
||||
|
||||
while (unvisited.isNotEmpty()) {
|
||||
val start = unvisited.first()
|
||||
unvisited.remove(start)
|
||||
|
||||
val patch = mutableListOf(start)
|
||||
val queue = ArrayDeque(listOf(start))
|
||||
|
||||
while (queue.isNotEmpty()) {
|
||||
val tile = queue.removeFirst()
|
||||
val x = unpackX(tile)
|
||||
val y = unpackY(tile)
|
||||
for (dx in -joinDistance..joinDistance) {
|
||||
for (dy in -joinDistance..joinDistance) {
|
||||
val neighbour = packTile(x + dx, y + dy)
|
||||
if (unvisited.remove(neighbour)) {
|
||||
patch += neighbour
|
||||
queue += neighbour
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
patches += patch
|
||||
}
|
||||
return patches
|
||||
}
|
||||
|
||||
|
||||
private fun createPatch(
|
||||
protoId: PrototypeId,
|
||||
surfaceIndex: SurfaceIndex,
|
||||
isInfinite: Boolean,
|
||||
patchTiles: List<Long>,
|
||||
amounts: Map<Long, UInt>,
|
||||
): ResourcePatch {
|
||||
val xs = patchTiles.map { unpackX(it) }
|
||||
val ys = patchTiles.map { unpackY(it) }
|
||||
|
||||
return ResourcePatch(
|
||||
protoId = protoId,
|
||||
surfaceIndex = surfaceIndex,
|
||||
totalAmount = patchTiles.sumOf { amounts.getValue(it).toLong() },
|
||||
tileCount = patchTiles.size,
|
||||
isInfinite = isInfinite,
|
||||
// +0.5: the centre of the tile
|
||||
centre = MapEntityPosition(xs.average() + 0.5, ys.average() + 0.5),
|
||||
leftTop = MapEntityPosition(xs.min().toDouble(), ys.min().toDouble()),
|
||||
rightBottom = MapEntityPosition(xs.max() + 1.0, ys.max() + 1.0),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
companion object {
|
||||
private const val ORE_JOIN_DISTANCE = 2
|
||||
private const val INFINITE_RESOURCE_JOIN_DISTANCE = 12
|
||||
|
||||
/** Pack a tile coordinate into a single Long, for fast set lookups. */
|
||||
private fun packTile(x: Int, y: Int): Long = (x.toLong() shl 32) or (y.toLong() and 0xFFFFFFFFL)
|
||||
private fun unpackX(packed: Long): Int = (packed shr 32).toInt()
|
||||
private fun unpackY(packed: Long): Int = packed.toInt()
|
||||
}
|
||||
}
|
||||
|
|
@ -7,6 +7,9 @@ import dev.adamko.kafkatorio.schema.common.ServerMapTilePngFilename
|
|||
import dev.adamko.kafkatorio.schema.common.SurfaceIndex
|
||||
import dev.adamko.kafkatorio.processor.config.ApplicationProperties
|
||||
import dev.adamko.kafkatorio.server.web.config.jsonMapper
|
||||
import dev.adamko.kafkatorio.server.web.resources.ResourcePatchService
|
||||
import dev.adamko.kafkatorio.schema.common.ResourcePatch
|
||||
import kotlinx.serialization.builtins.ListSerializer
|
||||
import io.ktor.http.HttpStatusCode
|
||||
import io.ktor.http.content.EntityTagVersion
|
||||
import io.ktor.http.content.versions
|
||||
|
|
@ -27,6 +30,7 @@ import kotlinx.serialization.json.encodeToJsonElement
|
|||
|
||||
internal fun Routing.factorioServersRoutes(
|
||||
appProps: ApplicationProperties,
|
||||
resourcePatchService: ResourcePatchService,
|
||||
) {
|
||||
|
||||
get<FactorioServers> {
|
||||
|
|
@ -38,6 +42,11 @@ internal fun Routing.factorioServersRoutes(
|
|||
get<FactorioServer.MapData.Tile> { tile ->
|
||||
handleTileRequest(tile, appProps)
|
||||
}
|
||||
|
||||
get<FactorioServer.MapData.ResourcePatches> { request ->
|
||||
val patches = resourcePatchService.patches(request.mapData.server.factorioServerId, request.surfaceIndex)
|
||||
call.respond(jsonMapper.encodeToJsonElement(ListSerializer(ResourcePatch.serializer()), patches))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
|
@ -101,6 +110,13 @@ data class FactorioServer(
|
|||
val chunkY: Int,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
@Resource("resources/s{surfaceIndex}/patches")
|
||||
data class ResourcePatches(
|
||||
val mapData: MapData,
|
||||
val surfaceIndex: SurfaceIndex,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
@Resource("buildings/s{surfaceIndex}")
|
||||
data class Buildings(
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
package dev.adamko.kafkatorio.server.web.rest
|
||||
|
||||
import dev.adamko.kafkatorio.processor.config.ApplicationProperties
|
||||
import dev.adamko.kafkatorio.server.web.resources.ResourcePatchService
|
||||
import io.ktor.http.ContentType
|
||||
import io.ktor.http.HttpStatusCode
|
||||
import io.ktor.http.isSuccess
|
||||
|
|
@ -22,7 +23,10 @@ import io.ktor.server.response.respondText
|
|||
import io.ktor.server.routing.routing
|
||||
|
||||
|
||||
internal fun Application.webmapTileServer(appProps: ApplicationProperties) {
|
||||
internal fun Application.webmapTileServer(
|
||||
appProps: ApplicationProperties,
|
||||
resourcePatchService: ResourcePatchService,
|
||||
) {
|
||||
|
||||
install(AutoHeadResponse)
|
||||
install(CallLogging) {
|
||||
|
|
@ -51,6 +55,6 @@ internal fun Application.webmapTileServer(appProps: ApplicationProperties) {
|
|||
}
|
||||
|
||||
routing {
|
||||
factorioServersRoutes(appProps)
|
||||
factorioServersRoutes(appProps, resourcePatchService)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package dev.adamko.kafkatorio.server.web
|
|||
|
||||
|
||||
import dev.adamko.kafkatorio.processor.config.ApplicationProperties
|
||||
import dev.adamko.kafkatorio.server.web.resources.ResourcePatchService
|
||||
import dev.adamko.kafkatorio.server.web.rest.webmapTileServer
|
||||
import dev.adamko.kafkatorio.server.web.websocket.WebmapWebsocketServer
|
||||
import dev.adamko.kafkatorio.server.web.websocket.webmapWebsocketServer
|
||||
|
|
@ -13,6 +14,7 @@ import kotlinx.coroutines.coroutineScope
|
|||
internal suspend fun startWebServer(
|
||||
appProps: ApplicationProperties,
|
||||
wsServer: WebmapWebsocketServer,
|
||||
resourcePatchService: ResourcePatchService,
|
||||
): Unit = coroutineScope {
|
||||
|
||||
embeddedServer(
|
||||
|
|
@ -22,7 +24,7 @@ internal suspend fun startWebServer(
|
|||
|
||||
webmapWebsocketServer(wsServer)
|
||||
|
||||
webmapTileServer(appProps)
|
||||
webmapTileServer(appProps, resourcePatchService)
|
||||
|
||||
}.start(wait = true)
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue