Show building rotation, recipes and other surfaces on the web map

The mod now sends each building's direction and recipe (furnaces: the last
recipe, since they only have one while working).
- Rotated buildings are drawn at their real footprint.
- Crafting machines show their recipe icon, like Factorio's alt mode, and
  the hover tooltip includes the recipe.

The web map has a surface drop-down (e.g. Space Exploration planets and
orbits), backed by a new surfaces endpoint. Every layer, the resource labels
and the player markers follow the chosen surface.

Resource labels use the in-game names (e.g. "Iridite" instead of
"Se iridium ore"). export_building_icons.py also exports recipe icons, plus
recipe and resource names.

The three in-memory views in events-server-web now share one helper for
following a Kafka topic.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lazzexus 2026-10-21 10:14:39 +02:00
parent 7ef4918a5c
commit b9adb9ea83
20 changed files with 482 additions and 139 deletions

View file

@ -6,21 +6,10 @@ import dev.adamko.kafkatorio.schema.common.FactorioServerId
import dev.adamko.kafkatorio.schema.common.MapBuilding
import dev.adamko.kafkatorio.schema.common.MapEntityPosition
import dev.adamko.kafkatorio.schema.common.SurfaceIndex
import dev.adamko.kafkatorio.schema.packets.KafkatorioPacket
import dev.adamko.kafkatorio.schema.packets.MapChunkEntityUpdate
import dev.adamko.kafkatorio.server.web.config.jsonMapper
import java.time.Duration
import java.util.Properties
import dev.adamko.kafkatorio.server.web.kafka.followTopic
import java.util.concurrent.ConcurrentHashMap
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
/**
@ -45,41 +34,16 @@ class BuildingService(
/** Read all building updates from the beginning of the topic, and keep following it. */
suspend fun consume(): Unit = withContext(Dispatchers.IO) {
val topic = MapChunkEntityUpdate::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("[BuildingService] 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("[BuildingService] failed to read record: $it") }
}
}
}
suspend fun consume(): Unit = followTopic(
appProps,
MapChunkEntityUpdate::class.topicName,
clientId = "kafkatorio.events-server-web.buildings",
) { serverId, data ->
if (data is MapChunkEntityUpdate) handleUpdate(serverId, data)
}
private fun consumerProperties() = Properties().apply {
putAll(appProps.kafkaStreamsConfig.filterKeys { it == ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG })
put(ConsumerConfig.ISOLATION_LEVEL_CONFIG, "read_committed")
put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false")
put(ConsumerConfig.CLIENT_ID_CONFIG, "kafkatorio.events-server-web.buildings")
}
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? MapChunkEntityUpdate ?: return
private fun handleUpdate(serverId: FactorioServerId, update: MapChunkEntityUpdate) {
// ghosts are planned buildings, not built ones
if (update.key.protoId.type.toString() in IGNORED_TYPES) return
@ -105,6 +69,8 @@ class BuildingService(
status = entity.status,
health = entity.health,
unitNumber = entity.unitNumber,
direction = entity.direction,
recipe = entity.recipe,
)
}
}

View file

@ -0,0 +1,59 @@
package dev.adamko.kafkatorio.server.web.kafka
import dev.adamko.kafkatorio.processor.config.ApplicationProperties
import dev.adamko.kafkatorio.schema.common.FactorioServerId
import dev.adamko.kafkatorio.schema.packets.KafkatorioPacket
import dev.adamko.kafkatorio.schema.packets.KafkatorioPacketData
import dev.adamko.kafkatorio.server.web.config.jsonMapper
import java.time.Duration
import java.util.Properties
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
/**
* Read all packets from the beginning of a topic, and keep following it.
*
* This is for small in-memory views of the data. Unlike Kafka Streams there's no state store, so
* the whole topic is re-read on every startup.
*/
suspend fun followTopic(
appProps: ApplicationProperties,
topic: String,
clientId: String,
handle: (serverId: FactorioServerId, data: KafkatorioPacketData) -> Unit,
): Unit = withContext(Dispatchers.IO) {
val properties = 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, clientId)
}
KafkaConsumer(properties, StringDeserializer(), StringDeserializer()).use { consumer ->
val partitions = consumer.partitionsFor(topic).map { TopicPartition(it.topic(), it.partition()) }
consumer.assign(partitions)
consumer.seekToBeginning(partitions)
println("[$clientId] consuming $topic, partitions: ${partitions.size}")
while (isActive) {
val records = runInterruptible { consumer.poll(Duration.ofSeconds(1)) }
for (record in records) {
runCatching {
val key = record.key() ?: return@runCatching
val value = record.value() ?: return@runCatching
val serverId = jsonMapper.decodeFromString(FactorioServerId.serializer(), key)
val packet = jsonMapper.decodeFromString(KafkatorioPacket.serializer(), value)
handle(serverId, packet.data)
}.onFailure { println("[$clientId] failed to read record: $it") }
}
}
}
}

View file

@ -6,6 +6,7 @@ import dev.adamko.kafkatorio.server.processor.topology.broadcastToWebsocket
import dev.adamko.kafkatorio.server.processor.topology.saveMapTiles
import dev.adamko.kafkatorio.server.web.buildings.BuildingService
import dev.adamko.kafkatorio.server.web.resources.ResourcePatchService
import dev.adamko.kafkatorio.server.web.surfaces.SurfaceService
import dev.adamko.kafkatorio.server.web.websocket.WebmapWebsocketServer
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
@ -21,6 +22,7 @@ suspend fun main(): Unit = coroutineScope {
val wsServer = WebmapWebsocketServer()
val resourcePatchService = ResourcePatchService(appProps)
val buildingService = BuildingService(appProps)
val surfaceService = SurfaceService(appProps)
launch {
websocketBroadcaster(wsServer)
@ -42,12 +44,17 @@ suspend fun main(): Unit = coroutineScope {
buildingService.consume()
}
launch {
surfaceService.consume()
}
launch {
startWebServer(
appProps = appProps,
wsServer = wsServer,
resourcePatchService = resourcePatchService,
buildingService = buildingService,
surfaceService = surfaceService,
)
}
}

View file

@ -1,7 +1,6 @@
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
@ -9,21 +8,11 @@ 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 dev.adamko.kafkatorio.server.web.kafka.followTopic
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
/**
@ -60,42 +49,16 @@ class ResourcePatchService(
/** 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") }
}
}
}
suspend fun consume(): Unit = followTopic(
appProps,
MapChunkResourceUpdate::class.topicName,
clientId = "kafkatorio.events-server-web.resource-patches",
) { serverId, data ->
if (data is MapChunkResourceUpdate) handleUpdate(serverId, data)
}
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
private fun handleUpdate(serverId: FactorioServerId, update: MapChunkResourceUpdate) {
val chunkKey = ChunkKey(
serverId = serverId,
protoId = update.key.protoId,

View file

@ -9,6 +9,8 @@ import dev.adamko.kafkatorio.processor.config.ApplicationProperties
import dev.adamko.kafkatorio.server.web.config.jsonMapper
import dev.adamko.kafkatorio.server.web.buildings.BuildingService
import dev.adamko.kafkatorio.server.web.resources.ResourcePatchService
import dev.adamko.kafkatorio.server.web.surfaces.SurfaceService
import dev.adamko.kafkatorio.schema.common.MapSurface
import dev.adamko.kafkatorio.schema.common.MapBuilding
import dev.adamko.kafkatorio.schema.common.MapEntityPosition
import dev.adamko.kafkatorio.schema.common.ResourcePatch
@ -35,6 +37,7 @@ internal fun Routing.factorioServersRoutes(
appProps: ApplicationProperties,
resourcePatchService: ResourcePatchService,
buildingService: BuildingService,
surfaceService: SurfaceService,
) {
get<FactorioServers> {
@ -43,6 +46,11 @@ internal fun Routing.factorioServersRoutes(
call.respond(serverIdsJson)
}
get<FactorioServer.MapData.Surfaces> { request ->
val surfaces = surfaceService.surfaces(request.mapData.server.factorioServerId)
call.respond(jsonMapper.encodeToJsonElement(ListSerializer(MapSurface.serializer()), surfaces))
}
get<FactorioServer.MapData.Tile> { tile ->
handleTileRequest(tile, appProps)
}
@ -124,6 +132,12 @@ data class FactorioServer(
val chunkY: Int,
)
@Serializable
@Resource("surfaces")
data class Surfaces(
val mapData: MapData,
)
@Serializable
@Resource("resources/s{surfaceIndex}/patches")
data class ResourcePatches(

View file

@ -3,6 +3,7 @@ package dev.adamko.kafkatorio.server.web.rest
import dev.adamko.kafkatorio.processor.config.ApplicationProperties
import dev.adamko.kafkatorio.server.web.buildings.BuildingService
import dev.adamko.kafkatorio.server.web.resources.ResourcePatchService
import dev.adamko.kafkatorio.server.web.surfaces.SurfaceService
import io.ktor.http.ContentType
import io.ktor.http.HttpStatusCode
import io.ktor.http.isSuccess
@ -28,6 +29,7 @@ internal fun Application.webmapTileServer(
appProps: ApplicationProperties,
resourcePatchService: ResourcePatchService,
buildingService: BuildingService,
surfaceService: SurfaceService,
) {
install(AutoHeadResponse)
@ -57,6 +59,6 @@ internal fun Application.webmapTileServer(
}
routing {
factorioServersRoutes(appProps, resourcePatchService, buildingService)
factorioServersRoutes(appProps, resourcePatchService, buildingService, surfaceService)
}
}

View file

@ -0,0 +1,49 @@
package dev.adamko.kafkatorio.server.web.surfaces
import dev.adamko.kafkatorio.processor.config.ApplicationProperties
import dev.adamko.kafkatorio.processor.config.topicName
import dev.adamko.kafkatorio.schema.common.FactorioServerId
import dev.adamko.kafkatorio.schema.common.MapSurface
import dev.adamko.kafkatorio.schema.common.ServerMapTileLayer
import dev.adamko.kafkatorio.schema.common.ServerMapTilePngFilename
import dev.adamko.kafkatorio.schema.common.SurfaceIndex
import dev.adamko.kafkatorio.schema.packets.SurfaceUpdate
import dev.adamko.kafkatorio.server.web.kafka.followTopic
import java.util.concurrent.ConcurrentHashMap
import kotlin.io.path.isDirectory
/** Keeps the names of the surfaces, so the web map can list them. */
class SurfaceService(
private val appProps: ApplicationProperties,
) {
private val surfaceNames = ConcurrentHashMap<Pair<FactorioServerId, SurfaceIndex>, String>()
/** The mod regularly sends the name of every surface. */
suspend fun consume(): Unit = followTopic(
appProps,
SurfaceUpdate::class.topicName,
clientId = "kafkatorio.events-server-web.surfaces",
) { serverId, data ->
if (data is SurfaceUpdate) surfaceNames[serverId to data.index] = data.name
}
/** The surfaces that have a map, sorted by index. */
fun surfaces(serverId: FactorioServerId): List<MapSurface> =
surfaceNames
.filterKeys { (id, index) -> id == serverId && hasTerrain(serverId, index) }
.map { (key, name) -> MapSurface(index = key.second, name = name) }
.sortedBy { it.index.toString().toInt() }
/** Surfaces without terrain tiles (e.g. surfaces that only exist for mod internals) can't be shown. */
private fun hasTerrain(serverId: FactorioServerId, surfaceIndex: SurfaceIndex): Boolean {
// the tile files are in `.../s{surfaceIndex}/z{zoom}/x{x}/y{y}.png`
val tile = ServerMapTilePngFilename(serverId, ServerMapTileLayer.TERRAIN, surfaceIndex, 0, 0, 0)
val surfaceDir = appProps.serverDataDir.resolve(tile.value).parent.parent.parent
return surfaceDir.isDirectory()
}
}

View file

@ -4,6 +4,7 @@ package dev.adamko.kafkatorio.server.web
import dev.adamko.kafkatorio.processor.config.ApplicationProperties
import dev.adamko.kafkatorio.server.web.buildings.BuildingService
import dev.adamko.kafkatorio.server.web.resources.ResourcePatchService
import dev.adamko.kafkatorio.server.web.surfaces.SurfaceService
import dev.adamko.kafkatorio.server.web.rest.webmapTileServer
import dev.adamko.kafkatorio.server.web.websocket.WebmapWebsocketServer
import dev.adamko.kafkatorio.server.web.websocket.webmapWebsocketServer
@ -17,6 +18,7 @@ internal suspend fun startWebServer(
wsServer: WebmapWebsocketServer,
resourcePatchService: ResourcePatchService,
buildingService: BuildingService,
surfaceService: SurfaceService,
): Unit = coroutineScope {
embeddedServer(
@ -26,7 +28,7 @@ internal suspend fun startWebServer(
webmapWebsocketServer(wsServer)
webmapTileServer(appProps, resourcePatchService, buildingService)
webmapTileServer(appProps, resourcePatchService, buildingService, surfaceService)
}.start(wait = true)
}