Add a research page, and keep the topics that views are rebuilt from

The mod sends the research state of a force (researched technologies,
levels, current research, progress and queue) whenever research changes,
and every minute for the progress. events-server-web keeps the latest state
and serves it at /kafkatorio/data/servers/{id}/research.

The web map has a research page (/servers/{id}/research, linked from the
header), with:
- progress, the current research and the queue
- the science packs needed for everything that's left
- every technology, filterable by status, science pack and name, with its
  cost (including levelled technologies' count formulas)
- details: the total cost to reach a technology, its prerequisites, what it
  leads to and what it unlocks

The technology tree comes from export_building_icons.py, which now also
exports technologies.json, items.json and technology/science pack icons.

Kafka deleted data older than 7 days, but the building, resource and
research views are rebuilt by reading their topics from the beginning, so
buildings disappeared after a restart. These topics are now kept forever.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lazzexus 2026-11-03 10:46:09 +01:00
parent 4d02928081
commit e31971c58e
23 changed files with 1517 additions and 11 deletions

View file

@ -4,6 +4,7 @@ import dev.adamko.kafkatorio.schema.packets.EventServerPacket
import dev.adamko.kafkatorio.webmap.layout.headerNav
import dev.adamko.kafkatorio.webmap.layout.homePage
import dev.adamko.kafkatorio.webmap.layout.servers.serverPage
import dev.adamko.kafkatorio.webmap.research.researchPage
import dev.adamko.kafkatorio.webmap.routing.SiteRouter
import dev.adamko.kafkatorio.webmap.routing.SiteView
import dev.adamko.kafkatorio.webmap.services.WebsocketService
@ -82,14 +83,15 @@ object App : Application() {
// Only re-render when the page itself changes. Re-rendering on every state update (e.g. each
// player position update) re-attaches the Leaflet map to a new element, which blanks the map.
val pageState = siteStateStore.sub { state ->
Triple(state.view, state.serverIds, state.factorioGameState?.map)
listOf(state.view, state.serverIds, state.factorioGameState?.map, state.serverId)
}
main().bind(pageState) { _ ->
val state = siteStateStore.getState()
div(className = "container-fluid") {
when (state.view) {
SiteView.HOME -> homePage(state)
SiteView.SERVER -> serverPage(state)
SiteView.SERVER -> serverPage(state)
SiteView.RESEARCH -> researchPage(state)
}
}
SiteRouter.updatePageLinks()

View file

@ -4,13 +4,22 @@ import dev.adamko.kafkatorio.webmap.routing.SiteView
import dev.adamko.kafkatorio.webmap.state.SiteState
import io.kvision.core.Container
import io.kvision.navbar.nav
import io.kvision.navbar.navLink
import io.kvision.navbar.navbar
fun Container.headerNav(state: SiteState) {
navbar(label = "Kafkatorio", link = SiteView.HOME.path) {
val serverId = state.serverId ?: return@navbar
nav {
// navLink("Home", SiteView.HOME.path)
navLink("Map", "/servers/${serverId.id}", className = navClass(state.view == SiteView.SERVER)) {
setAttribute("data-navigo", "true")
}
navLink("Research", "/servers/${serverId.id}/research", className = navClass(state.view == SiteView.RESEARCH)) {
setAttribute("data-navigo", "true")
}
}
}
}
private fun navClass(active: Boolean) = if (active) "active" else null

View file

@ -0,0 +1,252 @@
package dev.adamko.kafkatorio.webmap.research
import dev.adamko.kafkatorio.schema.packets.ResearchUpdate
import dev.adamko.kafkatorio.webmap.services.TechnologyInfo
import kotlin.math.max
import kotlin.math.pow
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.doubleOrNull
import kotlinx.serialization.json.intOrNull
enum class TechnologyStatus(val label: String) {
RESEARCHING("Researching"),
QUEUED("Queued"),
AVAILABLE("Available"),
LOCKED("Locked"),
RESEARCHED("Researched"),
}
/** Science packs, by name, and the amount of each */
typealias SciencePackCost = Map<String, Double>
/**
* The technology tree, combined with the research state of a force.
*/
class ResearchModel(
val technologies: Map<String, TechnologyInfo>,
val research: ResearchUpdate?,
) {
private val researched: Set<String> = research?.researched?.toSet() ?: emptySet()
private val queue: List<String> = research?.queue?.toList() ?: emptyList()
private val priceMultiplier: Double = research?.technologyPriceMultiplier ?: 1.0
/** The technologies that need each technology */
val successors: Map<String, List<String>> = buildMap<String, MutableList<String>> {
technologies.forEach { (name, tech) ->
tech.prerequisites.forEach { prerequisite -> getOrPut(prerequisite) { mutableListOf() }.add(name) }
}
}
/** The length of the longest chain of prerequisites, so early technologies sort first */
val depth: Map<String, Int> = buildMap {
fun depthOf(name: String, visiting: Set<String>): Int = getOrElse(name) {
val prerequisites = technologies[name]?.prerequisites.orEmpty().filter { it !in visiting }
val depth = prerequisites.maxOfOrNull { depthOf(it, visiting + name) + 1 } ?: 0
put(name, depth)
depth
}
technologies.keys.forEach { depthOf(it, emptySet()) }
}
val status: Map<String, TechnologyStatus> = technologies.mapValues { (name, tech) ->
when {
name in researched -> TechnologyStatus.RESEARCHED
name == research?.current -> TechnologyStatus.RESEARCHING
name in queue -> TechnologyStatus.QUEUED
!tech.disabled && tech.prerequisites.all { it in researched } -> TechnologyStatus.AVAILABLE
else -> TechnologyStatus.LOCKED
}
}
/** Science packs, sorted by how early in the tech tree they're first needed */
val sciencePacks: List<String> =
technologies.flatMap { (name, tech) -> tech.packs().map { pack -> pack to (depth[name] ?: 0) } }
.groupBy({ it.first }, { it.second })
.mapValues { (_, depths) -> depths.min() }
.entries
.sortedWith(compareBy({ it.value }, { it.key }))
.map { it.key }
val researchedCount: Int get() = researched.count { it in technologies }
/** Technologies that can be researched more than once never finish, so don't count them */
val finiteCount: Int get() = technologies.count { (_, tech) -> !tech.isInfinite() }
/** The level that will be researched next, for technologies with levels */
fun level(name: String): Int? {
val tech = technologies[name] ?: return null
if (tech.maxLevel == null) return null
return research?.levels?.get(name) ?: tech.level ?: 1
}
/** The science packs needed to research the next level of a technology */
fun cost(name: String): SciencePackCost {
val tech = technologies[name] ?: return emptyMap()
return tech.levelCost(level(name) ?: tech.level ?: 1)
}
/** Seconds per unit */
fun timePerUnit(name: String): Double? = technologies[name]?.cost?.time
/** The number of units of the next level */
fun units(name: String): Double? {
val tech = technologies[name] ?: return null
return tech.units(level(name) ?: tech.level ?: 1)
}
/**
* The science packs needed to research a technology, including all its prerequisites that
* aren't researched yet.
*/
fun costToReach(name: String): Pair<SciencePackCost, Int> {
val needed = mutableSetOf<String>()
fun visit(tech: String) {
if (status[tech] == TechnologyStatus.RESEARCHED || !needed.add(tech)) return
technologies[tech]?.prerequisites?.forEach { visit(it) }
}
visit(name)
return needed.map { cost(it) }.sum() to needed.size
}
/**
* The science packs needed to research everything that's left, excluding infinite
* technologies. For technologies with a limited number of levels, include all levels left.
*/
fun remainingCost(): SciencePackCost =
technologies.filter { (name, tech) -> status[name] != TechnologyStatus.RESEARCHED && !tech.isInfinite() }
.map { (name, tech) ->
val maxLevel = tech.maxLevel?.intOrNull
val level = level(name)
if (maxLevel != null && level != null) {
(level..maxLevel).map { tech.levelCost(it) }.sum()
} else {
cost(name)
}
}.sum()
private fun TechnologyInfo.levelCost(level: Int): SciencePackCost {
val units = units(level) ?: return emptyMap()
return packAmounts().mapValues { (_, amount) -> amount * units }
}
private fun TechnologyInfo.units(level: Int): Double? {
val cost = cost ?: return null
val units = cost.count ?: cost.countFormula?.let { evaluateCountFormula(it, level) } ?: return null
val multiplier = if (cost.ignoreMultiplier) 1.0 else priceMultiplier
return max(1.0, units * multiplier)
}
}
private fun TechnologyInfo.isInfinite(): Boolean = maxLevel?.contentOrNull == "infinite"
/** Science pack -> amount per unit */
fun TechnologyInfo.packAmounts(): Map<String, Double> =
cost?.ingredients.orEmpty().mapNotNull { ingredient ->
val pack = ingredient.getOrNull(0)?.contentOrNull ?: return@mapNotNull null
val amount = ingredient.getOrNull(1)?.doubleOrNull ?: 1.0
pack to amount
}.toMap()
fun TechnologyInfo.packs(): Set<String> = packAmounts().keys
private fun List<SciencePackCost>.sum(): SciencePackCost = buildMap {
this@sum.forEach { cost ->
cost.forEach { (pack, amount) -> put(pack, (get(pack) ?: 0.0) + amount) }
}
}
/**
* Evaluate a technology count formula, like `2^(L-6)*1000`.
*
* Factorio's formulas support `+ - * / ^`, brackets, numbers, and `L` (or `l`) for the level.
*/
fun evaluateCountFormula(formula: String, level: Int): Double? = runCatching {
FormulaParser(formula.replace(" ", ""), level.toDouble()).parse()
}.getOrNull()
private class FormulaParser(private val input: String, private val level: Double) {
private var pos = 0
fun parse(): Double {
val value = expression()
require(pos == input.length) { "unexpected '${input[pos]}' in $input" }
return value
}
private fun expression(): Double {
var value = term()
while (pos < input.length && input[pos] in "+-") {
value = if (input[pos++] == '+') value + term() else value - term()
}
return value
}
private fun term(): Double {
var value = power()
while (pos < input.length && input[pos] in "*/") {
value = if (input[pos++] == '*') value * power() else value / power()
}
return value
}
private fun power(): Double {
val base = unary()
if (pos < input.length && input[pos] == '^') {
pos++
return base.pow(power()) // right associative
}
return base
}
private fun unary(): Double {
if (pos < input.length && input[pos] == '-') {
pos++
return -unary()
}
return atom()
}
private fun atom(): Double {
require(pos < input.length) { "unexpected end of $input" }
val c = input[pos]
return when {
c == '(' -> {
pos++
val value = expression()
require(input.getOrNull(pos) == ')') { "missing ')' in $input" }
pos++
value
}
c == 'L' || c == 'l' -> {
pos++
level
}
c.isDigit() || c == '.' -> {
val start = pos
while (pos < input.length && (input[pos].isDigit() || input[pos] == '.')) pos++
input.substring(start, pos).toDouble()
}
else -> error("unexpected '$c' in $input")
}
}
}

View file

@ -0,0 +1,427 @@
package dev.adamko.kafkatorio.webmap.research
import dev.adamko.kafkatorio.schema.common.FactorioServerId
import dev.adamko.kafkatorio.webmap.services.EventsServerClient
import dev.adamko.kafkatorio.webmap.services.TechnologyInfo
import dev.adamko.kafkatorio.webmap.state.SiteState
import io.kvision.core.Container
import io.kvision.core.onClick
import io.kvision.core.onEvent
import io.kvision.form.text.TextInput
import io.kvision.form.text.TextInputType
import io.kvision.html.Div
import io.kvision.html.button
import io.kvision.html.div
import io.kvision.html.h1
import io.kvision.html.h2
import io.kvision.html.h3
import io.kvision.html.image
import io.kvision.html.p
import io.kvision.html.span
import kotlinx.browser.document
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.jsonPrimitive
import org.w3c.dom.events.KeyboardEvent
private val researchPageScope = CoroutineScope(Dispatchers.Default + SupervisorJob())
/** The technology tree, and what's researched, with the science packs each technology needs. */
fun Container.researchPage(state: SiteState) {
val serverId = state.serverId ?: return
val page = div(className = "research-page") {
p("Loading research…", className = "home-muted")
}
researchPageScope.launch {
val technologies = async {
runCatching { EventsServerClient.technologies() }
.onFailure { println("[researchPage] failed to load technologies: $it") }
.getOrDefault(emptyMap())
}
val itemNames = async { runCatching { EventsServerClient.itemNames() }.getOrDefault(emptyMap()) }
val recipeNames = async { runCatching { EventsServerClient.recipeNames() }.getOrDefault(emptyMap()) }
val research = async { runCatching { EventsServerClient.research(serverId) }.getOrNull() }
val model = ResearchModel(technologies.await(), research.await())
page.removeAll()
if (model.technologies.isEmpty()) {
page.p("The technology tree hasn't been exported yet - see docs/guide.md.", className = "home-muted")
} else {
ResearchView(page, serverId, model, Names(itemNames.await(), recipeNames.await())).render()
}
}
}
private class Names(
val items: Map<String, String>,
val recipes: Map<String, String>,
) {
fun item(name: String) = items[name] ?: name
fun recipe(name: String) = recipes[name] ?: name
}
private class ResearchView(
private val page: Container,
private val serverId: FactorioServerId,
private val model: ResearchModel,
private val names: Names,
) {
private val cards = mutableMapOf<String, Div>()
// filters
private var search = ""
private var statusFilter: Set<TechnologyStatus>? = null
private var packFilter: String? = null
private lateinit var packFilterButtons: Map<String, Div>
private lateinit var statusButtons: Map<Set<TechnologyStatus>?, io.kvision.html.Button>
private lateinit var resultCount: Div
private lateinit var detailOverlay: Div
fun render() {
page.header()
page.remaining()
page.filters()
resultCount = page.div(className = "research-count home-muted")
page.div(className = "research-grid") {
sortedTechnologies().forEach { name -> cards[name] = technologyCard(name) }
}
detailOverlay = page.div(className = "research-detail-overlay") {
visible = false
onClick { event -> if (event.target == getElement()) closeDetail() }
}
document.addEventListener("keydown", { event ->
if ((event as KeyboardEvent).key == "Escape") closeDetail()
})
applyFilters()
}
private fun sortedTechnologies(): List<String> =
model.technologies.keys.sortedWith(
compareBy<String>(
{ model.status[it]?.ordinal ?: 0 },
{ if (model.status[it] == TechnologyStatus.QUEUED) model.research?.queue?.indexOf(it) ?: 0 else 0 },
{ model.depth[it] ?: 0 },
{ model.technologies[it]?.order ?: "" },
{ model.technologies[it]?.name ?: it },
)
)
private fun Container.header() {
div(className = "research-header") {
h1("Research")
val total = model.finiteCount
val done = model.researchedCount
div(className = "research-summary") {
span("$done of $total technologies researched", className = "research-summary-count")
div(className = "research-progress") {
div(className = "research-progress-bar") {
setStyle("width", "${if (total == 0) 0 else 100 * done / total}%")
}
}
}
val research = model.research
when {
research == null -> p(
"The game hasn't sent its research yet. It's sent once a minute, and whenever research changes.",
className = "home-muted",
)
research.current == null -> p("Nothing is being researched.", className = "home-muted")
else -> div(className = "research-current") {
val current = research.current!!
span("Researching ", className = "home-muted")
technologyLink(current)
val progress = ((research.progress ?: 0.0) * 100).toInt()
span(" — $progress%")
div(className = "research-progress research-progress-small") {
div(className = "research-progress-bar") { setStyle("width", "$progress%") }
}
val queued = research.queue.filter { it != current }
if (queued.isNotEmpty()) {
div(className = "research-queue") {
span("Queue: ", className = "home-muted")
queued.forEach { technologyLink(it) }
}
}
}
}
}
}
private fun Container.remaining() {
val remaining = model.remainingCost()
if (remaining.isEmpty()) return
div(className = "research-section") {
h2("Science packs needed for everything left")
p("Excluding infinite research. Click a science pack to show the technologies that need it.", className = "home-muted")
packFilterButtons = model.sciencePacks.filter { it in remaining }.associateWith { pack ->
div(className = "pack-total") {
title = names.item(pack)
packIcon(pack)
span(formatAmount(remaining.getValue(pack)))
onClick { togglePackFilter(pack) }
}
}
}
}
private fun Container.filters() {
div(className = "research-filters") {
val searchInput = TextInput(TextInputType.SEARCH) {
placeholder = "Search technologies or recipes"
addCssClass("research-search")
}
searchInput.onEvent {
input = {
search = searchInput.value?.trim()?.lowercase() ?: ""
applyFilters()
}
}
add(searchInput)
val options = listOf(
"All" to null,
"Available" to setOf(TechnologyStatus.RESEARCHING, TechnologyStatus.QUEUED, TechnologyStatus.AVAILABLE),
"Locked" to setOf(TechnologyStatus.LOCKED),
"Researched" to setOf(TechnologyStatus.RESEARCHED),
)
div(className = "research-status-filter") {
statusButtons = options.associate { (label, statuses) ->
statuses to button(label, className = "research-filter-button") {
onClick {
statusFilter = statuses
applyFilters()
}
}
}
}
}
}
private fun togglePackFilter(pack: String) {
packFilter = if (packFilter == pack) null else pack
applyFilters()
}
private fun applyFilters() {
var shown = 0
cards.forEach { (name, card) ->
val tech = model.technologies.getValue(name)
val visible = (statusFilter == null || model.status[name] in statusFilter!!)
&& (packFilter == null || packFilter in tech.packs())
&& (search.isEmpty() || matchesSearch(name, tech))
card.visible = visible
if (visible) shown++
}
statusButtons.forEach { (statuses, button) ->
if (statuses == statusFilter) button.addCssClass("active") else button.removeCssClass("active")
}
if (::packFilterButtons.isInitialized) {
packFilterButtons.forEach { (pack, button) ->
if (pack == packFilter) button.addCssClass("active") else button.removeCssClass("active")
}
}
val packText = packFilter?.let { " that need ${names.item(it)}" } ?: ""
resultCount.content = "$shown technologies$packText"
}
private fun matchesSearch(name: String, tech: TechnologyInfo): Boolean =
tech.name.lowercase().contains(search)
|| name.contains(search)
|| tech.unlocks.any { names.recipe(it).lowercase().contains(search) }
private fun Container.technologyCard(name: String): Div {
val tech = model.technologies.getValue(name)
val status = model.status[name] ?: TechnologyStatus.LOCKED
return div(className = "tech-card tech-${status.name.lowercase()}") {
image("/kafkatorio/icons/technology/$name.png", alt = "", className = "tech-card-icon") {
setAttribute("loading", "lazy")
}
div(className = "tech-card-body") {
div(className = "tech-card-name") { content = tech.displayName(name) }
div(className = "tech-card-cost") { costSummary(name, tech) }
span(status.label, className = "tech-status")
}
onClick { showDetail(name) }
}
}
/** e.g. `150 × [packs]`, or `Craft 10 Iron plate` */
private fun Container.costSummary(name: String, tech: TechnologyInfo) {
val units = model.units(name)
if (units == null) {
span(tech.triggerDescription(names), className = "home-muted")
return
}
span("${formatAmount(units)} ×")
tech.packs().forEach { pack -> packIcon(pack, small = true) }
}
private fun Container.packIcon(pack: String, small: Boolean = false) {
image("/kafkatorio/icons/item/$pack.png", alt = names.item(pack), className = if (small) "pack-icon pack-icon-small" else "pack-icon") {
title = names.item(pack)
}
}
private fun Container.technologyLink(name: String) {
span(model.technologies[name]?.displayName(name) ?: name, className = "tech-link") {
onClick { showDetail(name) }
}
}
private fun closeDetail() {
detailOverlay.visible = false
detailOverlay.removeAll()
}
private fun showDetail(name: String) {
val tech = model.technologies[name] ?: return
val status = model.status[name] ?: TechnologyStatus.LOCKED
detailOverlay.removeAll()
detailOverlay.div(className = "research-detail tech-${status.name.lowercase()}") {
button("×", className = "research-detail-close") {
title = "Close"
onClick { closeDetail() }
}
div(className = "research-detail-title") {
image("/kafkatorio/icons/technology/$name.png", alt = "", className = "research-detail-icon")
div {
h3(tech.displayName(name))
span(status.label, className = "tech-status")
model.level(name)?.let { level ->
val max = tech.maxLevel?.jsonPrimitive?.let { it.intOrNull?.toString() ?: it.contentOrNull }
span(" Level $level${if (max == "infinite") " (infinite)" else ""}", className = "home-muted")
}
}
}
val units = model.units(name)
div(className = "research-detail-section") {
h3("Cost")
if (units == null) {
p(tech.triggerDescription(names))
} else {
val time = model.timePerUnit(name)
p("${formatAmount(units)} units${time?.let { ", ${formatAmount(it)}s each" } ?: ""}", className = "home-muted")
packList(model.cost(name))
}
}
if (status != TechnologyStatus.RESEARCHED) {
val (toReach, count) = model.costToReach(name)
if (count > 1) {
div(className = "research-detail-section") {
h3("Total to reach")
p("$count technologies, including the prerequisites that aren't researched yet", className = "home-muted")
packList(toReach)
}
}
}
technologyList("Requires", tech.prerequisites)
technologyList("Leads to", model.successors[name].orEmpty())
if (tech.unlocks.isNotEmpty()) {
div(className = "research-detail-section") {
h3("Unlocks")
div(className = "recipe-list") {
tech.unlocks.forEach { recipe ->
div(className = "recipe-item") {
image("/kafkatorio/icons/recipe/$recipe.png", alt = "", className = "pack-icon pack-icon-small")
span(names.recipe(recipe))
}
}
}
}
}
}
detailOverlay.visible = true
}
private fun Container.packList(cost: SciencePackCost) {
div(className = "pack-list") {
model.sciencePacks.filter { it in cost }.forEach { pack ->
div(className = "pack-total") {
title = names.item(pack)
packIcon(pack)
span(formatAmount(cost.getValue(pack)))
}
}
}
}
private fun Container.technologyList(title: String, technologies: List<String>) {
val known = technologies.filter { it in model.technologies }
if (known.isEmpty()) return
div(className = "research-detail-section") {
h3(title)
div(className = "tech-chip-list") {
known.sortedBy { model.depth[it] ?: 0 }.forEach { name ->
val status = model.status[name] ?: TechnologyStatus.LOCKED
div(className = "tech-chip tech-${status.name.lowercase()}") {
image("/kafkatorio/icons/technology/$name.png", alt = "", className = "pack-icon pack-icon-small")
span(model.technologies.getValue(name).displayName(name))
onClick { showDetail(name) }
}
}
}
}
}
}
/** The in-game name. Technologies with levels (e.g. `Mining productivity 3`) already include it. */
private fun TechnologyInfo.displayName(id: String): String = name.ifBlank { id }
/** e.g. `Craft 10 Iron plate`, for technologies researched by doing something */
private fun TechnologyInfo.triggerDescription(names: Names): String {
val trigger = trigger ?: return "Unknown cost"
fun field(key: String) = trigger[key]?.jsonPrimitive?.contentOrNull
val type = field("type") ?: return "Unknown cost"
val count = field("count")?.let { "$it " } ?: ""
return when (type) {
"craft-item" -> "Craft $count${names.item(field("item") ?: "?")}"
"mine-entity" -> "Mine ${names.item(field("entity") ?: "?").replace('-', ' ')}"
"build-entity" -> "Build ${names.item(field("entity") ?: "?").replace('-', ' ')}"
else -> type.replace('-', ' ').replaceFirstChar { it.uppercase() }
}
}
private fun formatAmount(amount: Double): String = when {
amount >= 1_000_000_000 -> "${(amount / 100_000_000).toLong() / 10.0}B"
amount >= 1_000_000 -> "${(amount / 100_000).toLong() / 10.0}M"
amount >= 10_000 -> "${(amount / 100).toLong() / 10.0}k"
amount == kotlin.math.floor(amount) -> amount.toLong().toString()
else -> "${(amount * 10).toLong() / 10.0}"
}

View file

@ -37,6 +37,10 @@ object SiteRouter : CoroutineScope {
log("routing.on HOME")
homepageView()
}
.on(SiteView.RESEARCH) { match ->
val serverId = match.data["serverId"] as? String ?: error("invalid server id")
App.siteStateStore.dispatch(SiteAction.ResearchPage(FactorioServerId(serverId)))
}
.on(SiteView.SERVER) { match ->
println("routing.on SERVER ${JSON.stringify(match)}")
val serverId = match.data["serverId"] as? String ?: error("invalid server id")

View file

@ -19,4 +19,8 @@ sealed interface SiteView {
object SERVER : DynamicPath {
override val path: String = "/servers/:serverId/"
}
object RESEARCH : DynamicPath {
override val path: String = "/servers/:serverId/research"
}
}

View file

@ -4,11 +4,15 @@ import dev.adamko.kafkatorio.schema.common.FactorioServerId
import dev.adamko.kafkatorio.schema.common.MapBuilding
import dev.adamko.kafkatorio.schema.common.MapSurface
import dev.adamko.kafkatorio.schema.common.ResourcePatch
import dev.adamko.kafkatorio.schema.packets.ResearchUpdate
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 kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import io.kvision.rest.RestClient
import io.kvision.rest.call
import kotlinx.browser.window
@ -84,6 +88,32 @@ object EventsServerClient :
suspend fun resourceNames(): Map<String, String> = displayNames("resources.json")
/** Fetch the display name of science packs and other items used by research. */
suspend fun itemNames(): Map<String, String> = displayNames("items.json")
/** Fetch the research state of the players' force, or `null` if the mod hasn't sent it yet. */
suspend fun research(serverId: FactorioServerId): ResearchUpdate? {
val response = window.fetch("${window.location.origin}/kafkatorio/data/servers/${serverId.id}/research").await()
if (!response.ok) return null
val json = response.text().await()
return jsonMapper.decodeFromString(ResearchUpdate.serializer(), json)
}
/** Fetch the technology tree (exported like [buildingInfo]). */
suspend fun technologies(): Map<String, TechnologyInfo> {
val response = window.fetch("${window.location.origin}/kafkatorio/icons/technologies.json").await()
if (!response.ok) return emptyMap()
val json = response.text().await()
return lenientJson.decodeFromString(MapSerializer(String.serializer(), TechnologyInfo.serializer()), json)
}
/** For data exported from Factorio, which might have more properties in future */
private val lenientJson = Json { ignoreUnknownKeys = true }
private suspend fun displayNames(filename: String): Map<String, String> {
val response = window.fetch("${window.location.origin}/kafkatorio/icons/$filename").await()
if (!response.ok) return emptyMap()
@ -100,3 +130,38 @@ data class BuildingInfo(
val h: Int,
val name: String,
)
/** A technology, from Factorio's prototype data */
@Serializable
data class TechnologyInfo(
val name: String,
val prerequisites: List<String> = emptyList(),
val order: String = "",
/** The recipes that this technology unlocks */
val unlocks: List<String> = emptyList(),
/** The science packs needed, or `null` if this is researched by a [trigger] */
val cost: TechnologyCost? = null,
/** e.g. `{"type": "craft-item", "item": "iron-plate", "count": 10}` */
val trigger: JsonObject? = null,
/** A number, or `"infinite"`, for technologies that have levels */
val maxLevel: JsonPrimitive? = null,
/** The level of the first technology of a series (e.g. 3 for `mining-productivity-3`) */
val level: Int? = null,
val upgrade: Boolean = false,
val disabled: Boolean = false,
)
@Serializable
data class TechnologyCost(
/** The number of units, or `null` if [countFormula] is used instead */
val count: Double? = null,
/** The number of units for each level, e.g. `2^(L-6)*1000` */
val countFormula: String? = null,
/** Seconds per unit */
val time: Double? = null,
/** `[science pack, amount per unit]` */
val ingredients: List<List<JsonPrimitive>> = emptyList(),
val ignoreMultiplier: Boolean = false,
)

View file

@ -11,6 +11,7 @@ import dev.adamko.kafkatorio.schema.packets.MapChunkResourceUpdate
import dev.adamko.kafkatorio.schema.packets.MapChunkTileUpdate
import dev.adamko.kafkatorio.schema.packets.PlayerUpdate
import dev.adamko.kafkatorio.schema.packets.PrototypesUpdate
import dev.adamko.kafkatorio.schema.packets.ResearchUpdate
import dev.adamko.kafkatorio.schema.packets.SurfaceUpdate
import dev.adamko.kafkatorio.webmap.App
import dev.adamko.kafkatorio.webmap.state.SiteAction
@ -98,6 +99,7 @@ object WebsocketService : CoroutineScope {
is MapChunkResourceUpdate,
is MapChunkTileUpdate,
is PrototypesUpdate,
is ResearchUpdate,
is SurfaceUpdate,
is KafkatorioPacketDataError -> {
// to be continued...

View file

@ -10,6 +10,7 @@ import io.kvision.redux.RAction
sealed interface SiteAction : RAction {
object HomePage : SiteAction
data class ServerPage(val serverId: FactorioServerId) : SiteAction
data class ResearchPage(val serverId: FactorioServerId) : SiteAction
data class ServerIdsLoaded(val serverIds: List<FactorioServerId>) : SiteAction

View file

@ -18,19 +18,27 @@ data class SiteState(
val serverIds: List<FactorioServerId>? = null,
val factorioGameState: FactorioGameState? = null,
/** The server whose pages are shown (the map, or research) */
val serverId: FactorioServerId? = null,
) : CoroutineScope {
override val coroutineContext: CoroutineContext =
Dispatchers.Default + SupervisorJob(rootJob) + CoroutineName("SiteState")
operator fun plus(action: SiteAction): SiteState = when (action) {
is SiteAction.HomePage -> copy(view = SiteView.HOME)
is SiteAction.HomePage -> copy(view = SiteView.HOME, serverId = null)
is SiteAction.ServerPage -> copy(
view = SiteView.SERVER,
factorioGameState = FactorioGameState(action.serverId),
serverId = action.serverId,
// keep the map when coming back from another page of the same server
factorioGameState = factorioGameState?.takeIf { it.serverId == action.serverId }
?: FactorioGameState(action.serverId),
)
is SiteAction.ResearchPage -> copy(view = SiteView.RESEARCH, serverId = action.serverId)
is SiteAction.ServerIdsLoaded -> copy(serverIds = action.serverIds)
is SiteAction.FactorioUpdate -> copy(

View file

@ -202,6 +202,398 @@ header .navbar-brand:hover {
}
/* Header navigation */
header .navbar .nav-link {
color: var(--kt-muted);
font-weight: 600;
}
header .navbar .nav-link:hover,
header .navbar .nav-link.active {
color: var(--kt-heading);
}
header .navbar .nav-link.active {
box-shadow: inset 0 -2px 0 var(--kt-accent);
}
header .navbar .navbar-toggler {
border-color: var(--kt-border);
filter: invert(1);
}
/* Research */
.research-page {
max-width: 1300px;
margin: 0 auto;
padding: 24px 0 48px;
}
.research-header h1 {
color: var(--kt-heading);
font-weight: 700;
font-size: 2rem;
margin-bottom: 8px;
}
.research-summary {
display: flex;
align-items: center;
gap: 16px;
flex-wrap: wrap;
margin-bottom: 12px;
}
.research-summary-count {
font-weight: 600;
}
.research-progress {
flex: 1;
min-width: 200px;
max-width: 480px;
height: 10px;
background: var(--kt-panel-raised);
border-radius: 5px;
overflow: hidden;
}
.research-progress-small {
height: 6px;
margin: 6px 0;
}
.research-progress-bar {
height: 100%;
background: var(--kt-accent);
}
.research-current,
.research-queue {
margin-bottom: 8px;
}
.research-queue {
display: flex;
flex-wrap: wrap;
gap: 4px 12px;
}
.tech-link {
color: var(--kt-accent);
cursor: pointer;
font-weight: 600;
}
.tech-link:hover {
color: var(--kt-accent-hover);
text-decoration: underline;
}
.research-section {
margin: 20px 0;
}
.research-section h2 {
color: var(--kt-heading);
font-size: 1.25rem;
font-weight: 600;
margin-bottom: 4px;
}
.research-section > p {
margin-bottom: 10px;
}
.research-section .pack-total,
.pack-list .pack-total {
display: inline-flex;
align-items: center;
gap: 6px;
margin: 0 8px 8px 0;
padding: 4px 10px 4px 4px;
background: var(--kt-panel);
border: 1px solid var(--kt-border);
border-radius: 6px;
font-variant-numeric: tabular-nums;
font-weight: 600;
}
.research-section .pack-total {
cursor: pointer;
}
.research-section .pack-total:hover {
border-color: var(--kt-accent-hover);
}
.research-section .pack-total.active {
border-color: var(--kt-accent);
background: #4a3a1e;
}
.pack-icon {
width: 32px;
height: 32px;
}
.pack-icon-small {
width: 20px;
height: 20px;
}
.research-filters {
display: flex;
flex-wrap: wrap;
gap: 12px;
align-items: center;
margin: 20px 0 8px;
}
.research-filters .research-search {
width: 320px;
max-width: 100%;
background: var(--kt-panel);
border: 1px solid var(--kt-border);
color: var(--kt-text);
}
.research-filters .research-search:focus {
background: var(--kt-panel);
color: var(--kt-text);
border-color: var(--kt-accent);
box-shadow: none;
}
.research-filters .research-search::placeholder {
color: var(--kt-muted);
}
.research-status-filter {
display: flex;
flex-wrap: wrap;
gap: 4px;
}
.research-filter-button {
background: var(--kt-panel);
border: 1px solid var(--kt-border);
color: var(--kt-text);
border-radius: 6px;
padding: 4px 12px;
}
.research-filter-button:hover {
border-color: var(--kt-accent-hover);
}
.research-filter-button.active {
background: var(--kt-accent);
border-color: var(--kt-accent);
color: #1e1d1e;
font-weight: 600;
}
.research-count {
margin-bottom: 12px;
}
.research-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
gap: 10px;
}
.tech-card {
display: flex;
gap: 10px;
padding: 8px;
background: var(--kt-panel);
border: 1px solid var(--kt-border);
border-left: 4px solid var(--tech-status-colour);
border-radius: 6px;
cursor: pointer;
transition: border-color 0.15s, background 0.15s;
}
.tech-card:hover {
background: var(--kt-panel-raised);
border-color: var(--tech-status-colour);
}
.tech-card-icon {
width: 56px;
height: 56px;
flex-shrink: 0;
}
.tech-card-body {
min-width: 0;
display: flex;
flex-direction: column;
gap: 2px;
}
.tech-card-name {
font-weight: 600;
line-height: 1.2;
color: var(--kt-heading);
}
.tech-card-cost {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 2px;
font-size: 0.9rem;
}
.tech-card-cost > span:first-child {
margin-right: 4px;
}
.tech-status {
font-size: 0.8rem;
font-weight: 600;
color: var(--tech-status-colour);
}
/* status colours, like Factorio's technology screen */
.tech-researched { --tech-status-colour: #5fb948; }
.tech-researching { --tech-status-colour: #ff9f1b; }
.tech-queued { --tech-status-colour: #e8c547; }
.tech-available { --tech-status-colour: #e8c547; }
.tech-locked { --tech-status-colour: #8a8784; }
.tech-locked .tech-card-icon {
filter: grayscale(0.7) brightness(0.8);
}
.research-detail-overlay {
position: fixed;
inset: 0;
z-index: 2000;
background: rgba(0, 0, 0, 0.65);
display: flex;
align-items: flex-start;
justify-content: center;
padding: 48px 16px;
overflow-y: auto;
}
.research-detail {
position: relative;
width: 640px;
max-width: 100%;
background: var(--kt-panel);
border: 1px solid var(--kt-border);
border-top: 4px solid var(--tech-status-colour);
border-radius: 8px;
padding: 20px 24px;
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.6);
}
.research-detail-close {
position: absolute;
top: 8px;
right: 12px;
background: none;
border: none;
color: var(--kt-muted);
font-size: 1.8rem;
line-height: 1;
}
.research-detail-close:hover {
color: var(--kt-text);
}
.research-detail-title {
display: flex;
gap: 16px;
align-items: center;
margin-bottom: 8px;
}
.research-detail-title h3 {
color: var(--kt-heading);
font-size: 1.5rem;
font-weight: 700;
margin: 0;
}
.research-detail-icon {
width: 96px;
height: 96px;
flex-shrink: 0;
}
.research-detail-section {
margin-top: 16px;
}
.research-detail-section h3 {
color: var(--kt-heading);
font-size: 1.05rem;
font-weight: 600;
margin-bottom: 6px;
}
.research-detail-section p {
margin-bottom: 6px;
}
.tech-chip-list,
.recipe-list {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.tech-chip,
.recipe-item {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 3px 10px 3px 4px;
background: var(--kt-panel-raised);
border: 1px solid var(--kt-border);
border-left: 3px solid var(--tech-status-colour, var(--kt-border));
border-radius: 6px;
font-size: 0.9rem;
}
.tech-chip {
cursor: pointer;
}
.tech-chip:hover {
border-color: var(--tech-status-colour);
}
@media (max-width: 600px) {
.research-page {
padding-top: 12px;
}
.research-detail-overlay {
padding: 16px 8px;
}
.research-detail {
padding: 16px;
}
.research-detail-icon {
width: 64px;
height: 64px;
}
}
/* Map */
.leaflet-tile {