From 7ef4918a5cf8532c3572929ad7519ff2120db0a5 Mon Sep 17 00:00:00 2001 From: Lazzexus Date: Wed, 21 Oct 2026 09:52:07 +0200 Subject: [PATCH] Add a building icon layer to the web map events-server-web keeps the latest state of every building in memory (read from the map-chunk-entity topic, like the resource patches) and serves them per area. The web map draws the icons at their real size onto canvas tiles, so large bases stay fast, and shows each building's name, status and health on hover. Ghosts are ignored, and buildings are removed when they're mined. The icons belong to Wube and the mod authors, so they aren't in the repo. export_building_icons.py builds them from a Factorio client's --dump-data/--dump-prototype-locale/--dump-icon-sprites output, and the web-map nginx serves them from a mounted volume. Also label single-well oil fields "1 well". Co-Authored-By: Claude Opus 5.5 --- docs/guide.md | 13 + .../building-icons/export_building_icons.py | 71 +++++ docs/kafkatorio-platform/docker-compose.yml | 3 + .../unraid/docker-compose.yml | 3 + .../kafkatorio/schema/common/mapBuildings.kt | 17 ++ .../server/web/buildings/BuildingService.kt | 155 +++++++++++ .../dev/adamko/kafkatorio/server/web/main.kt | 7 + .../server/web/rest/factorioServersRoutes.kt | 20 +- .../kafkatorio/server/web/rest/restApi.kt | 4 +- .../adamko/kafkatorio/server/web/webServer.kt | 4 +- modules/web-map/docker/nginx.conf | 6 + .../kafkatorio/webmap/BuildingIconsLayer.kt | 242 ++++++++++++++++++ .../adamko/kafkatorio/webmap/FactorioMap.kt | 23 +- .../kafkatorio/webmap/externals/leaflet.kt | 11 + .../webmap/services/EventsServerClient.kt | 41 +++ 15 files changed, 615 insertions(+), 5 deletions(-) create mode 100644 docs/kafkatorio-platform/building-icons/export_building_icons.py create mode 100644 modules/events-library/src/commonMain/kotlin/dev/adamko/kafkatorio/schema/common/mapBuildings.kt create mode 100644 modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/buildings/BuildingService.kt create mode 100644 modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/BuildingIconsLayer.kt diff --git a/docs/guide.md b/docs/guide.md index 7b9167f..3132982 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -88,3 +88,16 @@ on `127.0.0.1`, and Kafka isn't exposed at all. WebSocket support is enabled. 7. In Factorio, run `/kafkatorio prototypes` and then `/kafkatorio chunks 10` to send the existing map. +8. Optional: building icons. The web map's 'Building icons' layer uses icons and building sizes + exported from a Factorio client that has the same mods as the server (they're not in this repo, + since they belong to Wube and the mod authors). With the game closed, run + + ```terminal + factorio --dump-data + factorio --dump-prototype-locale + SteamAppId=427520 factorio --dump-icon-sprites # SteamAppId stops Steam relaunching the game + python3 docs/kafkatorio-platform/building-icons/export_building_icons.py ~/.factorio/script-output ./icons + scp -r ./icons root@:/mnt/user/appdata/kafkatorio-platform/ + ``` + + Re-export them when the mods change. diff --git a/docs/kafkatorio-platform/building-icons/export_building_icons.py b/docs/kafkatorio-platform/building-icons/export_building_icons.py new file mode 100644 index 0000000..afc186c --- /dev/null +++ b/docs/kafkatorio-platform/building-icons/export_building_icons.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +""" +Export building icons and metadata for the web map's "Building icons" layer. + +The icons belong to Wube and the mod authors, so they're not in this repo. Instead, export them +from a Factorio client that has the same mods as the server: + + factorio --dump-data # script-output/data-raw-dump.json + factorio --dump-prototype-locale # script-output/entity-locale.json + factorio --dump-icon-sprites # script-output/entity/*.png + +(For a Steam install, set `SteamAppId=427520` so that Steam doesn't relaunch the game.) + +Then run + + export_building_icons.py ~/.factorio/script-output + +and mount in the web-map container at /usr/share/nginx/icons. + +The output contains + - buildings.json: {"": {"w": , "h": , "name": ""}} + - entity/.png +""" + +import json +import math +import shutil +import sys +from pathlib import Path + + +def footprint(selection_box) -> tuple[int, int]: + """The size in tiles, from a selection box like [[-1.5, -1.5], [1.5, 1.5]]""" + (x0, y0), (x1, y1) = selection_box + return max(1, math.ceil(x1 - x0 - 0.1)), max(1, math.ceil(y1 - y0 - 0.1)) + + +def main(script_output: Path, output_dir: Path): + data_raw = json.loads((script_output / "data-raw-dump.json").read_text()) + names = json.loads((script_output / "entity-locale.json").read_text()).get("names", {}) + icons_dir = script_output / "entity" + + (output_dir / "entity").mkdir(parents=True, exist_ok=True) + + buildings = {} + for prototypes in data_raw.values(): + if not isinstance(prototypes, dict): + continue + for name, proto in prototypes.items(): + if not isinstance(proto, dict): + continue + # only things that players can build + if "player-creation" not in proto.get("flags", []): + continue + selection_box = proto.get("selection_box") + icon = icons_dir / f"{name}.png" + if not selection_box or not icon.exists(): + continue + + w, h = footprint(selection_box) + buildings[name] = {"w": w, "h": h, "name": names.get(name, name)} + shutil.copyfile(icon, output_dir / "entity" / f"{name}.png") + + (output_dir / "buildings.json").write_text(json.dumps(buildings, indent=1, sort_keys=True)) + print(f"exported {len(buildings)} buildings to {output_dir}") + + +if __name__ == "__main__": + if len(sys.argv) != 3: + sys.exit(f"usage: {sys.argv[0]} ") + main(Path(sys.argv[1]).expanduser(), Path(sys.argv[2]).expanduser()) diff --git a/docs/kafkatorio-platform/docker-compose.yml b/docs/kafkatorio-platform/docker-compose.yml index a22568d..82924b9 100644 --- a/docs/kafkatorio-platform/docker-compose.yml +++ b/docs/kafkatorio-platform/docker-compose.yml @@ -35,6 +35,9 @@ services: - "12081:80" # web map (also proxies /kafkatorio/ to events-server-web) networks: - kafkatorio-infra-nw +# volumes: +# # building icons - see building-icons/export_building_icons.py +# - "./icons:/usr/share/nginx/icons:ro" ## Process Kafkatorio events diff --git a/docs/kafkatorio-platform/unraid/docker-compose.yml b/docs/kafkatorio-platform/unraid/docker-compose.yml index 04c44c2..dbb8cbf 100644 --- a/docs/kafkatorio-platform/unraid/docker-compose.yml +++ b/docs/kafkatorio-platform/unraid/docker-compose.yml @@ -84,6 +84,9 @@ services: ports: - "12081:80" networks: [ kafkatorio-nw ] + volumes: + # building icons - see docs/kafkatorio-platform/building-icons/export_building_icons.py + - "${APPDATA}/icons:/usr/share/nginx/icons:ro" ## Kafka admin UI - LAN/DMZ only, don't proxy this publicly infra-kafka-ui: diff --git a/modules/events-library/src/commonMain/kotlin/dev/adamko/kafkatorio/schema/common/mapBuildings.kt b/modules/events-library/src/commonMain/kotlin/dev/adamko/kafkatorio/schema/common/mapBuildings.kt new file mode 100644 index 0000000..172eb88 --- /dev/null +++ b/modules/events-library/src/commonMain/kotlin/dev/adamko/kafkatorio/schema/common/mapBuildings.kt @@ -0,0 +1,17 @@ +package dev.adamko.kafkatorio.schema.common + +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable + + +/** The latest known state of a building (a player-built entity), as shown on the web map. */ +@Serializable +@SerialName("kafkatorio.building.MapBuilding") +data class MapBuilding( + val protoId: PrototypeId, + /** The centre of the building */ + val position: MapEntityPosition, + val status: FactorioEntityData.Status? = null, + val health: Float? = null, + val unitNumber: UnitNumber? = null, +) diff --git a/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/buildings/BuildingService.kt b/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/buildings/BuildingService.kt new file mode 100644 index 0000000..189ce6d --- /dev/null +++ b/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/buildings/BuildingService.kt @@ -0,0 +1,155 @@ +package dev.adamko.kafkatorio.server.web.buildings + +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.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 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 + + +/** + * Keeps the latest state of every building in memory, so the web map can draw them as icons. + * + * Like [dev.adamko.kafkatorio.server.web.resources.ResourcePatchService], the whole + * [MapChunkEntityUpdate] topic is read from the beginning on startup, and then followed. + */ +class BuildingService( + private val appProps: ApplicationProperties, +) { + + private data class ChunkKey( + val serverId: FactorioServerId, + val surfaceIndex: SurfaceIndex, + val chunkX: Int, + val chunkY: Int, + ) + + /** Buildings per chunk, by position */ + private val chunks = ConcurrentHashMap>() + + + /** 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") } + } + } + } + } + + + 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 + + // ghosts are planned buildings, not built ones + if (update.key.protoId.type.toString() in IGNORED_TYPES) return + + // The mod groups updates per prototype and chunk, so an update only says which events + // happened, not which event affected which building. If the buildings were only mined, + // then they're gone. (If they were built and mined in the same update, then keep them.) + val eventNames = update.events?.keys?.map { it.toString() }.orEmpty() + val isRemoved = eventNames.isNotEmpty() && eventNames.all { it in REMOVAL_EVENTS } + + update.entities().forEach { entity -> + val chunkKey = ChunkKey( + serverId = serverId, + surfaceIndex = update.key.surfaceIndex, + chunkX = floor(entity.position.x / CHUNK_SIZE).toInt(), + chunkY = floor(entity.position.y / CHUNK_SIZE).toInt(), + ) + if (isRemoved) { + chunks[chunkKey]?.remove(entity.position) + } else { + chunks.computeIfAbsent(chunkKey) { ConcurrentHashMap() }[entity.position] = MapBuilding( + protoId = entity.protoId, + position = entity.position, + status = entity.status, + health = entity.health, + unitNumber = entity.unitNumber, + ) + } + } + } + + + /** Get the buildings whose centre is within an area (inclusive left/top, exclusive right/bottom). */ + fun buildings( + serverId: FactorioServerId, + surfaceIndex: SurfaceIndex, + leftTop: MapEntityPosition, + rightBottom: MapEntityPosition, + ): List { + val chunkX0 = floor(leftTop.x / CHUNK_SIZE).toInt() + val chunkY0 = floor(leftTop.y / CHUNK_SIZE).toInt() + val chunkX1 = floor(rightBottom.x / CHUNK_SIZE).toInt() + val chunkY1 = floor(rightBottom.y / CHUNK_SIZE).toInt() + + val result = mutableListOf() + for (chunkX in chunkX0..chunkX1) { + for (chunkY in chunkY0..chunkY1) { + val chunk = chunks[ChunkKey(serverId, surfaceIndex, chunkX, chunkY)] ?: continue + chunk.values.filterTo(result) { building -> + building.position.x >= leftTop.x && building.position.x < rightBottom.x + && building.position.y >= leftTop.y && building.position.y < rightBottom.y + } + if (result.size >= MAX_BUILDINGS) return result + } + } + return result + } + + + companion object { + private const val CHUNK_SIZE = 32.0 + + /** Limit the response size, if a client requests a huge area */ + private const val MAX_BUILDINGS = 50_000 + + private val IGNORED_TYPES = setOf("entity-ghost", "tile-ghost") + + private val REMOVAL_EVENTS = setOf( + "on_player_mined_entity", + "on_robot_mined_entity", + "on_entity_died", + ) + } +} 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 8ada9d8..d44c4a6 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.buildings.BuildingService import dev.adamko.kafkatorio.server.web.resources.ResourcePatchService import dev.adamko.kafkatorio.server.web.websocket.WebmapWebsocketServer import kotlin.time.Duration.Companion.milliseconds @@ -19,6 +20,7 @@ internal val appProps = ApplicationProperties.load() suspend fun main(): Unit = coroutineScope { val wsServer = WebmapWebsocketServer() val resourcePatchService = ResourcePatchService(appProps) + val buildingService = BuildingService(appProps) launch { websocketBroadcaster(wsServer) @@ -36,11 +38,16 @@ suspend fun main(): Unit = coroutineScope { resourcePatchService.consume() } + launch { + buildingService.consume() + } + launch { startWebServer( appProps = appProps, wsServer = wsServer, resourcePatchService = resourcePatchService, + buildingService = buildingService, ) } } 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 1da9648..dc2b9c9 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,7 +7,10 @@ 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.buildings.BuildingService import dev.adamko.kafkatorio.server.web.resources.ResourcePatchService +import dev.adamko.kafkatorio.schema.common.MapBuilding +import dev.adamko.kafkatorio.schema.common.MapEntityPosition import dev.adamko.kafkatorio.schema.common.ResourcePatch import kotlinx.serialization.builtins.ListSerializer import io.ktor.http.HttpStatusCode @@ -31,6 +34,7 @@ import kotlinx.serialization.json.encodeToJsonElement internal fun Routing.factorioServersRoutes( appProps: ApplicationProperties, resourcePatchService: ResourcePatchService, + buildingService: BuildingService, ) { get { @@ -47,6 +51,16 @@ internal fun Routing.factorioServersRoutes( val patches = resourcePatchService.patches(request.mapData.server.factorioServerId, request.surfaceIndex) call.respond(jsonMapper.encodeToJsonElement(ListSerializer(ResourcePatch.serializer()), patches)) } + + get { request -> + val buildings = buildingService.buildings( + serverId = request.mapData.server.factorioServerId, + surfaceIndex = request.surfaceIndex, + leftTop = MapEntityPosition(request.left, request.top), + rightBottom = MapEntityPosition(request.right, request.bottom), + ) + call.respond(jsonMapper.encodeToJsonElement(ListSerializer(MapBuilding.serializer()), buildings)) + } } @@ -122,7 +136,11 @@ data class FactorioServer( data class Buildings( val mapData: MapData, val surfaceIndex: SurfaceIndex, - // a list of buildings... (Sealed interface, different types?) + // the area, as query parameters + val left: Double, + val top: Double, + val right: Double, + val bottom: Double, ) } 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 0c1d8a0..df63eb9 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.buildings.BuildingService import dev.adamko.kafkatorio.server.web.resources.ResourcePatchService import io.ktor.http.ContentType import io.ktor.http.HttpStatusCode @@ -26,6 +27,7 @@ import io.ktor.server.routing.routing internal fun Application.webmapTileServer( appProps: ApplicationProperties, resourcePatchService: ResourcePatchService, + buildingService: BuildingService, ) { install(AutoHeadResponse) @@ -55,6 +57,6 @@ internal fun Application.webmapTileServer( } routing { - factorioServersRoutes(appProps, resourcePatchService) + factorioServersRoutes(appProps, resourcePatchService, buildingService) } } 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 4e69183..8e149a7 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.buildings.BuildingService import dev.adamko.kafkatorio.server.web.resources.ResourcePatchService import dev.adamko.kafkatorio.server.web.rest.webmapTileServer import dev.adamko.kafkatorio.server.web.websocket.WebmapWebsocketServer @@ -15,6 +16,7 @@ internal suspend fun startWebServer( appProps: ApplicationProperties, wsServer: WebmapWebsocketServer, resourcePatchService: ResourcePatchService, + buildingService: BuildingService, ): Unit = coroutineScope { embeddedServer( @@ -24,7 +26,7 @@ internal suspend fun startWebServer( webmapWebsocketServer(wsServer) - webmapTileServer(appProps, resourcePatchService) + webmapTileServer(appProps, resourcePatchService, buildingService) }.start(wait = true) } diff --git a/modules/web-map/docker/nginx.conf b/modules/web-map/docker/nginx.conf index a83624e..2d31521 100644 --- a/modules/web-map/docker/nginx.conf +++ b/modules/web-map/docker/nginx.conf @@ -19,6 +19,12 @@ http { # Docker's internal DNS - resolve the backend lazily, so nginx can start before it resolver 127.0.0.11 valid=10s; + # building icons, exported from Factorio (see docs/kafkatorio-platform/building-icons) + location /kafkatorio/icons/ { + alias /usr/share/nginx/icons/; + expires 1d; + } + # proxy REST + WebSocket requests to events-server-web, so the map and the API share an origin location /kafkatorio/ { set $events_server_web http://events-server-web:80; diff --git a/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/BuildingIconsLayer.kt b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/BuildingIconsLayer.kt new file mode 100644 index 0000000..3265b64 --- /dev/null +++ b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/BuildingIconsLayer.kt @@ -0,0 +1,242 @@ +package dev.adamko.kafkatorio.webmap + +import dev.adamko.kafkatorio.schema.common.FactorioServerId +import dev.adamko.kafkatorio.schema.common.MapBuilding +import dev.adamko.kafkatorio.webmap.externals.leaflet +import dev.adamko.kafkatorio.webmap.services.BuildingInfo +import dev.adamko.kafkatorio.webmap.services.EventsServerClient +import io.kvision.maps.externals.leaflet.geo.LatLng +import io.kvision.maps.externals.leaflet.layer.Layer +import io.kvision.maps.externals.leaflet.map.LeafletMap +import js.core.jso +import kotlin.math.floor +import kotlin.math.max +import kotlin.math.min +import kotlin.math.pow +import kotlinx.browser.document +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Deferred +import kotlinx.coroutines.async +import kotlinx.coroutines.launch +import org.w3c.dom.CanvasRenderingContext2D +import org.w3c.dom.HTMLCanvasElement +import org.w3c.dom.Image + + +/** + * Draws building icons at their real size, onto canvas tiles. + * + * Bases have many thousands of buildings, so drawing them onto a few canvases is much faster than + * adding a marker per building. + * + * Hovering over a building shows its name and status. + */ +class BuildingIconsLayer( + private val serverId: FactorioServerId, + private val coroutineScope: CoroutineScope, +) { + + private val buildingInfo: Deferred> = coroutineScope.async { + runCatching { EventsServerClient.buildingInfo() } + .onFailure { println("[BuildingIconsLayer] failed to load building info: $it") } + .getOrDefault(emptyMap()) + .also { loadedBuildingInfo = it } + } + + /** [buildingInfo], once loaded (for use outside of coroutines) */ + private var loadedBuildingInfo: Map = emptyMap() + + private val icons = mutableMapOf>() + + /** The buildings on loaded tiles, by [cellKey], for finding the hovered building. */ + private val hoverIndex = mutableMapOf>() + + /** A Leaflet `GridLayer`, which draws each tile with [drawTile] */ + val layer: Layer<*> = leaflet.gridLayer(jso { + this.tileSize = TILE_SIZE + this.minZoom = MIN_ZOOM + this.maxZoom = 6 + this.noWrap = true + }).unsafeCast>() + + init { + layer.asDynamic().createTile = { coords: dynamic, done: (Any?, HTMLCanvasElement) -> Unit -> + val canvas = document.createElement("canvas") as HTMLCanvasElement + canvas.width = TILE_SIZE + canvas.height = TILE_SIZE + coroutineScope.launch { + runCatching { drawTile(canvas, coords.x as Int, coords.y as Int, coords.z as Int) } + .onFailure { println("[BuildingIconsLayer] failed to draw tile: $it") } + done(null, canvas) + } + canvas + } + } + + + /** Re-draw the visible tiles, without clearing them first (which would make them flicker). */ + fun refresh() { + val tiles: dynamic = layer.asDynamic()._tiles ?: return + js("Object").values(tiles).unsafeCast>().forEach { tile -> + val canvas = tile.el.unsafeCast() + val coords = tile.coords + coroutineScope.launch { + runCatching { drawTile(canvas, coords.x as Int, coords.y as Int, coords.z as Int) } + .onFailure { println("[BuildingIconsLayer] failed to refresh tile: $it") } + } + } + } + + + /** Show a tooltip for the building under the mouse */ + fun onMouseMove(map: LeafletMap, latLng: LatLng) { + if (!map.hasLayer(layer) || map.getZoom().toDouble() < MIN_ZOOM) { + map.closeTooltip(hoverTooltip) + return + } + // CRS.Simple: lng is the Factorio x, -lat is the Factorio y + val x = latLng.lng.toDouble() + val y = -latLng.lat.toDouble() + val info = loadedBuildingInfo + + val hovered = (-1..1).asSequence().flatMap { dx -> + (-1..1).asSequence().mapNotNull { dy -> + hoverIndex[cellKey(x + dx * CELL_SIZE, y + dy * CELL_SIZE)] + } + }.flatMap { it.values } + .firstOrNull { building -> + val half = building.iconSize(info) / 2.0 + x >= building.position.x - half && x < building.position.x + half + && y >= building.position.y - half && y < building.position.y + half + } + + if (hovered == null) { + map.closeTooltip(hoverTooltip) + } else { + hoverTooltip.setLatLng(latLng) + hoverTooltip.setContent(hovered.tooltip(info)) + if (!map.hasLayer(hoverTooltip)) map.openTooltip(hoverTooltip) + } + } + + private val hoverTooltip: dynamic = leaflet.tooltip(jso { + this.direction = "top" + this.offset = leaflet.point(0, -8) + }) + + + private suspend fun drawTile(canvas: HTMLCanvasElement, tileX: Int, tileY: Int, zoom: Int) { + // CRS.Simple: at zoom z, 1 Factorio tile is 2^z pixels + val scale = 2.0.pow(zoom) + val tileSizeInMap = TILE_SIZE / scale + val left = tileX * tileSizeInMap + val top = tileY * tileSizeInMap + + // also get buildings that are centred on a neighbouring tile, but overlap this one + val buildings = EventsServerClient.buildings( + serverId, + surfaceIndex = 1, // TODO the map only shows surface 1 (Nauvis) for now + left = left - MAX_BUILDING_SIZE, + top = top - MAX_BUILDING_SIZE, + right = left + tileSizeInMap + MAX_BUILDING_SIZE, + bottom = top + tileSizeInMap + MAX_BUILDING_SIZE, + ) + val info = buildingInfo.await() + + updateHoverIndex(left, top, left + tileSizeInMap, top + tileSizeInMap, buildings) + + // load the icons before drawing, so the canvas is updated in one go + val buildingIcons = buildings.associateWith { icon(it.protoId.name.toString(), info) } + .mapValues { (_, icon) -> icon?.await() } + + val ctx = canvas.getContext("2d") as CanvasRenderingContext2D + ctx.clearRect(0.0, 0.0, TILE_SIZE.toDouble(), TILE_SIZE.toDouble()) + + // draw big buildings first, so small ones (like inserters) are on top + buildings.sortedByDescending { it.iconSize(info) }.forEach { building -> + val size = building.iconSize(info) * scale + val px = (building.position.x - left) * scale - size / 2 + val py = (building.position.y - top) * scale - size / 2 + + val icon = buildingIcons[building] + if (icon != null) { + ctx.drawImage(icon, px, py, size, size) + } else { + // no icon - show the outline of the building + ctx.fillStyle = "rgba(160, 160, 160, 0.6)" + ctx.fillRect(px, py, size, size) + } + } + } + + + private fun icon(name: String, info: Map): Deferred? { + if (name !in info) return null + return icons.getOrPut(name) { + val deferred = CompletableDeferred() + val img = Image() + img.onload = { deferred.complete(img) } + img.onerror = { _, _, _, _, _ -> deferred.complete(null) } + img.src = "/kafkatorio/icons/entity/$name.png" + deferred + } + } + + + private fun updateHoverIndex( + left: Double, + top: Double, + right: Double, + bottom: Double, + buildings: List, + ) { + // remove buildings that were in this area, in case they've been removed since + hoverIndex.values.forEach { cell -> + cell.values.removeAll { b -> + b.position.x >= left && b.position.x < right && b.position.y >= top && b.position.y < bottom + } + } + buildings.forEach { building -> + hoverIndex.getOrPut(cellKey(building.position.x, building.position.y)) { mutableMapOf() }[ + "${building.position.x},${building.position.y}" + ] = building + } + } + + + companion object { + private const val TILE_SIZE = 256 + + /** At lower zoom levels icons are too small to see. (At zoom 2, 1 Factorio tile is 4 pixels.) */ + private const val MIN_ZOOM = 2 + + /** The largest building, in tiles, so buildings that overlap tile edges are included */ + private const val MAX_BUILDING_SIZE = 16.0 + + /** The size of the [hoverIndex] cells, in Factorio tiles */ + private const val CELL_SIZE = 16.0 + + private fun cellKey(x: Double, y: Double): String = + "${floor(x / CELL_SIZE).toInt()},${floor(y / CELL_SIZE).toInt()}" + } +} + + +/** + * The icon is drawn as a square, because the mod doesn't send the direction of buildings, so + * whether a building like a boiler (3x2) is rotated isn't known. + */ +private fun MapBuilding.iconSize(info: Map): Int { + val building = info[protoId.name.toString()] ?: return 1 + return max(1, min(building.w, building.h)) +} + + +private fun MapBuilding.tooltip(info: Map): String = buildString { + val name = protoId.name.toString() + append("${info[name]?.name ?: name}") + status?.let { append("
${it.name.lowercase().replace('_', ' ').replaceFirstChar(Char::uppercase)}") } + health?.let { append("
Health: ${it.toInt()}") } + append("
[${floor(position.x).toInt()}, ${floor(position.y).toInt()}]") +} 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 312c6ab..1cd2f30 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 @@ -72,6 +72,8 @@ class FactorioMap( private val resourcePatchesLayer: LayerGroup = LayerGroup() + private val buildingIconsLayer = BuildingIconsLayer(serverId, coroutineScope) + init { val baseLayers: Control.LayersObject = jso { @@ -83,6 +85,7 @@ class FactorioMap( set("Resource patches", resourcePatchesLayer) set("Resources", resourcesTileLayer) set("Buildings", buildingsTileLayer) + set("Building icons", buildingIconsLayer.layer) } val layersControl = Layers( @@ -111,8 +114,14 @@ class FactorioMap( resourcesTileLayer.addTo(this) buildingsTileLayer.addTo(this) + buildingIconsLayer.layer.addTo(this) playerIconsLayer.addTo(this) resourcePatchesLayer.addTo(this) + + val map = this + on("mousemove", { event -> + buildingIconsLayer.onMouseMove(map, event.asDynamic().latlng.unsafeCast()) + }) } coroutineScope.launch { @@ -123,6 +132,13 @@ class FactorioMap( } } + coroutineScope.launch { + while (true) { + delay(60.seconds) + buildingIconsLayer.refresh() + } + } + WebsocketService.packetsFlow .filterIsInstance() @@ -240,12 +256,15 @@ private fun ResourcePatch.displayName(): String = /** e.g. `2.4M`, or `12 wells` for infinite resources */ private fun ResourcePatch.displayAmount(): String = - if (isInfinite) "$tileCount wells" else formatAmount(totalAmount) + if (isInfinite) wells() else formatAmount(totalAmount) + + +private fun ResourcePatch.wells(): String = if (tileCount == 1) "1 well" else "$tileCount wells" private fun ResourcePatch.tooltip(): String = buildString { append("${displayName()}: ") - append(if (isInfinite) "$tileCount wells" else "${formatAmount(totalAmount)} in $tileCount tiles") + append(if (isInfinite) 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()}])") diff --git a/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/externals/leaflet.kt b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/externals/leaflet.kt index b72d539..9bd976a 100644 --- a/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/externals/leaflet.kt +++ b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/externals/leaflet.kt @@ -43,3 +43,14 @@ inline fun Polyline<*>.getLatLngs2(): PolylinePathPoints? { else -> null } } + + +/** + * The Leaflet module itself. + * + * KVision's [io.kvision.maps.Maps.L] only wraps some of Leaflet's functions (e.g. not + * `gridLayer` or `tooltip`). + */ +@JsModule("leaflet") +@JsNonModule +external val leaflet: dynamic 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 9c7a12a..d7a6679 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,9 +1,13 @@ package dev.adamko.kafkatorio.webmap.services import dev.adamko.kafkatorio.schema.common.FactorioServerId +import dev.adamko.kafkatorio.schema.common.MapBuilding import dev.adamko.kafkatorio.schema.common.ResourcePatch import dev.adamko.kafkatorio.webmap.config.jsonMapper +import kotlinx.serialization.Serializable import kotlinx.serialization.builtins.ListSerializer +import kotlinx.serialization.builtins.MapSerializer +import kotlinx.serialization.builtins.serializer import io.kvision.rest.RestClient import io.kvision.rest.call import kotlinx.browser.window @@ -33,4 +37,41 @@ object EventsServerClient : } + /** Fetch the buildings whose centre is within an area. */ + suspend fun buildings( + serverId: FactorioServerId, + surfaceIndex: Int, + left: Double, + top: Double, + right: Double, + bottom: Double, + ): List { + val url = "${window.location.origin}/kafkatorio/data/servers/${serverId.id}/map/buildings/s$surfaceIndex" + + "?left=$left&top=$top&right=$right&bottom=$bottom" + val json = window.fetch(url).await().text().await() + return jsonMapper.decodeFromString(ListSerializer(MapBuilding.serializer()), json) + } + + + /** + * Fetch the size and display name of each building, by entity name. + * + * These are exported from Factorio separately (see `docs/kafkatorio-platform/building-icons`), + * so they might not exist. + */ + suspend fun buildingInfo(): Map { + val response = window.fetch("${window.location.origin}/kafkatorio/icons/buildings.json").await() + if (!response.ok) return emptyMap() + val json = response.text().await() + return jsonMapper.decodeFromString(MapSerializer(String.serializer(), BuildingInfo.serializer()), json) + } } + + +/** The size (in tiles) and display name of a building */ +@Serializable +data class BuildingInfo( + val w: Int, + val h: Int, + val name: String, +)