From 3d8673fe03843efbb85307111133d5a3dda93a2d Mon Sep 17 00:00:00 2001 From: Lazzexus <54175295+ScuffedLazzexus@users.noreply.github.com> Date: Tue, 13 Oct 2026 07:07:23 +0200 Subject: [PATCH] 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 --- .../schema/common/resourcePatches.kt | 28 +++ .../events/handlers/EntityUpdateHandler.ts | 7 +- .../dev/adamko/kafkatorio/server/web/main.kt | 7 + .../web/resources/ResourcePatchService.kt | 227 ++++++++++++++++++ .../server/web/rest/factorioServersRoutes.kt | 16 ++ .../kafkatorio/server/web/rest/restApi.kt | 8 +- .../adamko/kafkatorio/server/web/webServer.kt | 4 +- .../adamko/kafkatorio/webmap/FactorioMap.kt | 65 +++++ .../webmap/services/EventsServerClient.kt | 11 + .../src/main/resources/css/kafkatorio.css | 20 ++ 10 files changed, 388 insertions(+), 5 deletions(-) create mode 100644 modules/events-library/src/commonMain/kotlin/dev/adamko/kafkatorio/schema/common/resourcePatches.kt create mode 100644 modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/resources/ResourcePatchService.kt diff --git a/modules/events-library/src/commonMain/kotlin/dev/adamko/kafkatorio/schema/common/resourcePatches.kt b/modules/events-library/src/commonMain/kotlin/dev/adamko/kafkatorio/schema/common/resourcePatches.kt new file mode 100644 index 0000000..e853b89 --- /dev/null +++ b/modules/events-library/src/commonMain/kotlin/dev/adamko/kafkatorio/schema/common/resourcePatches.kt @@ -0,0 +1,28 @@ +package dev.adamko.kafkatorio.schema.common + +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable + + +/** + * A group of nearby resource tiles of the same type (an ore field, or an oil field), as shown on + * the in-game map. + */ +@Serializable +@SerialName("kafkatorio.resource.ResourcePatch") +data class ResourcePatch( + val protoId: PrototypeId, + val surfaceIndex: SurfaceIndex, + /** + * The total remaining amount. For infinite resources (e.g. crude oil) this is the sum of the + * current yields, so it's only meaningful relative to [tileCount]. + */ + val totalAmount: Long, + /** The number of resource entities (ore tiles, or oil wells) in the patch. */ + val tileCount: Int, + /** Infinite resources (e.g. crude oil) never deplete, and are counted by wells, not amount. */ + val isInfinite: Boolean, + val centre: MapEntityPosition, + val leftTop: MapEntityPosition, + val rightBottom: MapEntityPosition, +) diff --git a/modules/events-mod/src/main/typescript/main/events/handlers/EntityUpdateHandler.ts b/modules/events-mod/src/main/typescript/main/events/handlers/EntityUpdateHandler.ts index 5ad71f6..3c28050 100644 --- a/modules/events-mod/src/main/typescript/main/events/handlers/EntityUpdateHandler.ts +++ b/modules/events-mod/src/main/typescript/main/events/handlers/EntityUpdateHandler.ts @@ -198,10 +198,13 @@ export class EntityUpdatesHandler { data.amounts[`${entity.position.x}`] ??= {} data.amounts[`${entity.position.x}`][`${entity.position.y}`] = entity.amount - if (entity.initial_amount != null) { + // initial_amount can be nil even for infinite resources (e.g. crude oil), so also + // check the prototype. An initial amount marks the resource as infinite. + if (entity.prototype.infinite_resource) { data.initialAmounts ??= {} data.initialAmounts[`${entity.position.x}`] ??= {} - data.initialAmounts[`${entity.position.x}`][`${entity.position.y}`] = entity.initial_amount + data.initialAmounts[`${entity.position.x}`][`${entity.position.y}`] = + entity.initial_amount ?? entity.prototype.normal_resource_amount ?? 0 } } } diff --git a/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/main.kt b/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/main.kt index 572a854..8ada9d8 100644 --- a/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/main.kt +++ b/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/main.kt @@ -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, ) } } diff --git a/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/resources/ResourcePatchService.kt b/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/resources/ResourcePatchService.kt new file mode 100644 index 0000000..d23b656 --- /dev/null +++ b/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/resources/ResourcePatchService.kt @@ -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 = mutableMapOf(), + var isInfinite: Boolean = false, + ) + + private val chunks = ConcurrentHashMap() + + /** 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) + + private val patchCache = ConcurrentHashMap, 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 { + 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 { + + // collect all tiles per resource prototype + val tilesByProto = mutableMapOf>() + val infiniteProtos = mutableSetOf() + + 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, joinDistance: Int): List> { + val unvisited = tiles.keys.toMutableSet() + val patches = mutableListOf>() + + 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, + amounts: Map, + ): 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() + } +} diff --git a/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/rest/factorioServersRoutes.kt b/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/rest/factorioServersRoutes.kt index 082fcde..1da9648 100644 --- a/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/rest/factorioServersRoutes.kt +++ b/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/rest/factorioServersRoutes.kt @@ -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 { @@ -38,6 +42,11 @@ internal fun Routing.factorioServersRoutes( get { tile -> handleTileRequest(tile, appProps) } + + get { 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( diff --git a/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/rest/restApi.kt b/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/rest/restApi.kt index 22f8e3e..0c1d8a0 100644 --- a/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/rest/restApi.kt +++ b/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/rest/restApi.kt @@ -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) } } diff --git a/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/webServer.kt b/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/webServer.kt index 6792e02..4e69183 100644 --- a/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/webServer.kt +++ b/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/webServer.kt @@ -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) } diff --git a/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/FactorioMap.kt b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/FactorioMap.kt index de99c9d..312c6ab 100644 --- a/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/FactorioMap.kt +++ b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/FactorioMap.kt @@ -1,12 +1,15 @@ package dev.adamko.kafkatorio.webmap import dev.adamko.kafkatorio.schema.common.FactorioServerId +import dev.adamko.kafkatorio.schema.common.ResourcePatch import dev.adamko.kafkatorio.schema.common.ServerMapTileLayer import dev.adamko.kafkatorio.schema.common.ServerMapTilePngFilename import dev.adamko.kafkatorio.schema.packets.EventServerPacket import dev.adamko.kafkatorio.webmap.externals.TileOnLoadFn import dev.adamko.kafkatorio.webmap.externals.tileOnLoad +import dev.adamko.kafkatorio.webmap.services.EventsServerClient import dev.adamko.kafkatorio.webmap.services.WebsocketService +import dev.adamko.kafkatorio.webmap.services.latLng import io.kvision.maps.Maps import io.kvision.maps.Maps.Companion.L import io.kvision.maps.externals.leaflet.DoneCallback @@ -27,6 +30,7 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.await import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.delay import kotlinx.coroutines.flow.filterIsInstance import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach @@ -39,6 +43,7 @@ import org.w3c.fetch.RELOAD import org.w3c.fetch.RequestCache import org.w3c.fetch.RequestInit import org.w3c.fetch.RequestMode +import kotlin.time.Duration.Companion.seconds class FactorioMap( @@ -65,6 +70,8 @@ class FactorioMap( val playerIconsLayer: LayerGroup = LayerGroup() + private val resourcePatchesLayer: LayerGroup = LayerGroup() + init { val baseLayers: Control.LayersObject = jso { @@ -73,6 +80,7 @@ class FactorioMap( val overlays: Control.LayersObject = jso { set("Players", playerIconsLayer) + set("Resource patches", resourcePatchesLayer) set("Resources", resourcesTileLayer) set("Buildings", buildingsTileLayer) } @@ -104,6 +112,15 @@ class FactorioMap( buildingsTileLayer.addTo(this) playerIconsLayer.addTo(this) + resourcePatchesLayer.addTo(this) + } + + coroutineScope.launch { + while (true) { + runCatching { refreshResourcePatches() } + .onFailure { println("[FactorioMap] failed to refresh resource patches: $it") } + delay(60.seconds) + } } @@ -147,6 +164,24 @@ class FactorioMap( } + private suspend fun refreshResourcePatches() { + // TODO the map only shows surface 1 (Nauvis) for now + val patches = EventsServerClient.resourcePatches(serverId, surfaceIndex = 1) + .filter { it.isInfinite || it.tileCount >= MIN_RESOURCE_PATCH_TILES } + + resourcePatchesLayer.clearLayers() + patches.forEach { patch -> + val label = L.divIcon { + className = "resource-patch-label" + html = "${patch.displayName()}
${patch.displayAmount()}
" + } + L.marker(patch.centre.latLng()) { + icon = label + }.bindTooltip(patch.tooltip()).addTo(resourcePatchesLayer) + } + } + + private fun createServerTileLayer( layer: ServerMapTileLayer ): TileLayer { @@ -191,5 +226,35 @@ class FactorioMap( companion object { /** Add this attribute to `` tiles that need to be dynamically refreshed. */ const val DYNAMIC_RELOAD_ATT = "dynamic-reload" + + /** Hide stray resource tiles that aren't really a patch */ + private const val MIN_RESOURCE_PATCH_TILES = 10 } } + + +/** e.g. `iron-ore` -> `Iron ore` */ +private fun ResourcePatch.displayName(): String = + protoId.name.toString().replace('-', ' ').replaceFirstChar { it.uppercase() } + + +/** e.g. `2.4M`, or `12 wells` for infinite resources */ +private fun ResourcePatch.displayAmount(): String = + if (isInfinite) "$tileCount wells" else formatAmount(totalAmount) + + +private fun ResourcePatch.tooltip(): String = buildString { + append("${displayName()}: ") + append(if (isInfinite) "$tileCount wells" else "${formatAmount(totalAmount)} in $tileCount tiles") + val width = (rightBottom.x - leftTop.x).toInt() + val height = (rightBottom.y - leftTop.y).toInt() + append(" (${width}x$height, centre [${centre.x.toInt()}, ${centre.y.toInt()}])") +} + + +private fun formatAmount(amount: Long): String = when { + amount >= 1_000_000_000 -> "${(amount / 100_000_000) / 10.0}B" + amount >= 1_000_000 -> "${(amount / 100_000) / 10.0}M" + amount >= 1_000 -> "${(amount / 100) / 10.0}k" + else -> "$amount" +} diff --git a/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/services/EventsServerClient.kt b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/services/EventsServerClient.kt index bc61491..9c7a12a 100644 --- a/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/services/EventsServerClient.kt +++ b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/services/EventsServerClient.kt @@ -1,6 +1,9 @@ package dev.adamko.kafkatorio.webmap.services import dev.adamko.kafkatorio.schema.common.FactorioServerId +import dev.adamko.kafkatorio.schema.common.ResourcePatch +import dev.adamko.kafkatorio.webmap.config.jsonMapper +import kotlinx.serialization.builtins.ListSerializer import io.kvision.rest.RestClient import io.kvision.rest.call import kotlinx.browser.window @@ -22,4 +25,12 @@ object EventsServerClient : .await() + /** Fetch the resource patches (ore fields, oil fields) on a surface. */ + suspend fun resourcePatches(serverId: FactorioServerId, surfaceIndex: Int): List { + val url = "${window.location.origin}/kafkatorio/data/servers/${serverId.id}/map/resources/s$surfaceIndex/patches" + val json = window.fetch(url).await().text().await() + return jsonMapper.decodeFromString(ListSerializer(ResourcePatch.serializer()), json) + } + + } diff --git a/modules/web-map/src/main/resources/css/kafkatorio.css b/modules/web-map/src/main/resources/css/kafkatorio.css index 00e0e43..2806bd7 100644 --- a/modules/web-map/src/main/resources/css/kafkatorio.css +++ b/modules/web-map/src/main/resources/css/kafkatorio.css @@ -11,3 +11,23 @@ /* make the Leaflet map background transparent, so it matches the site theme */ background-color: rgba(255, 0, 0, 0.0) !important; } + +/* resource patch labels, e.g. 'Iron ore / 2.4M' - centred on the patch, readable on any terrain */ +.resource-patch-label { + width: auto !important; + height: auto !important; + background: none; + border: none; +} + +.resource-patch-label span { + display: block; + transform: translate(-50%, -50%); + white-space: nowrap; + text-align: center; + font-size: 12px; + font-weight: bold; + line-height: 1.2; + color: #fff; + text-shadow: 0 0 3px #000, 0 0 3px #000, 0 0 2px #000; +}