feat(game): open the mart shop and key items by the ids the client reads (#151)
This commit is contained in:
1 parent
a69fd0d07f
commit
499d20fdb3
46 files changed
+7863
-269
No files matched your search
@@ -13,6 +13,7 @@ dependencies {
|
||||
"generatorImplementation"(libs.jte)
|
||||
"generatorImplementation"(libs.kotlinx.serialization.json)
|
||||
testImplementation(sourceSets["generator"].output)
|
||||
testImplementation(libs.kotlinx.serialization.json)
|
||||
testImplementation(libs.bundles.kotest)
|
||||
}
|
||||
|
||||
@@ -28,6 +29,11 @@ val regionSources =
|
||||
// is the canonical pick, same as byRegion is for maps.
|
||||
val sourceDecompDir = rootProject.layout.projectDirectory.dir("decomp/pokeemerald")
|
||||
|
||||
// The Gen 5 table the live client speaks, not the GBA decomps, which number the same items
|
||||
// differently. Committed rather than a submodule because openmmo-org/pokeblack is private, taken
|
||||
// from its src/data/items.json and container 54 of its src/data/text1.json.
|
||||
val itemDataDir = rootProject.layout.projectDirectory.dir("decomp/pokeblack")
|
||||
|
||||
// ROMs (gitignored) that dialog codegen reads offsets from
|
||||
val romsDir = rootProject.layout.projectDirectory.dir("roms")
|
||||
|
||||
@@ -41,15 +47,10 @@ jteCodegen {
|
||||
"$region|${rootProject.layout.projectDirectory.dir("decomp/$decomp").asFile.absolutePath}"
|
||||
})
|
||||
}
|
||||
// Item ids scripts hand to giveItem. Both GBA games number items the same, so one decomp is
|
||||
// enough, like moves and species. The client holds one item table per region, so the region
|
||||
// decides what a number means. Checked against a real client: region 0 reads 3, 4 and 13 as
|
||||
// Great Ball, Poke Ball and Potion, matching the decomp, while region 1 and region 5 read the
|
||||
// same numbers as unrelated items.
|
||||
register("item") {
|
||||
mainClass.set("de.fiereu.openmmo.codegen.item.Main")
|
||||
inputDirs.from(sourceDecompDir)
|
||||
extraArgs.set(listOf("kanto|${sourceDecompDir.asFile.absolutePath}"))
|
||||
inputDirs.from(itemDataDir)
|
||||
extraArgs.set(listOf(itemDataDir.asFile.absolutePath))
|
||||
}
|
||||
register("moves") {
|
||||
mainClass.set("de.fiereu.openmmo.codegen.move.Main")
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
@import java.util.List
|
||||
@import de.fiereu.openmmo.codegen.item.ParsedItem
|
||||
@import de.fiereu.openmmo.codegen.item.RenderUtil
|
||||
|
||||
@param List<ParsedItem> items
|
||||
package de.fiereu.openmmo.items.generated
|
||||
|
||||
/**
|
||||
* Item ids the client uses, already carrying the region prefix of the decomp they were read from.
|
||||
* Generated from the GBA decomp item header, do not edit by hand.
|
||||
*/
|
||||
import de.fiereu.openmmo.items.ItemDef
|
||||
|
||||
/** Generated, do not edit by hand. The KDoc on an entry is the wire ids it answers to. */
|
||||
object Items {
|
||||
@for(ParsedItem item : items)
|
||||
const val ${item.getName()} = ${item.getId()}
|
||||
${RenderUtil.INSTANCE.declaration(item)}
|
||||
@endfor
|
||||
|
||||
private fun item(name: String, price: Int) = ItemDef(name, price)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
@import java.util.List
|
||||
@import de.fiereu.openmmo.codegen.item.ParsedItem
|
||||
@import de.fiereu.openmmo.codegen.item.RenderUtil
|
||||
|
||||
@param List<List<ParsedItem>> chunks
|
||||
package de.fiereu.openmmo.items.generated
|
||||
|
||||
import de.fiereu.openmmo.items.ItemRegistry
|
||||
|
||||
internal object GeneratedItems {
|
||||
fun loadInto(reg: ItemRegistry) {
|
||||
@for(int i = 0; i < chunks.size(); i++)
|
||||
registerChunk${i}(reg)
|
||||
@endfor
|
||||
}
|
||||
|
||||
@for(int c = 0; c < chunks.size(); c++)
|
||||
private fun registerChunk${c}(reg: ItemRegistry) {
|
||||
@for(ParsedItem item : chunks.get(c))
|
||||
${RenderUtil.INSTANCE.register(item)}
|
||||
@endfor
|
||||
}
|
||||
|
||||
@endfor
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package de.fiereu.openmmo.codegen.item
|
||||
|
||||
import java.io.File
|
||||
import java.text.Normalizer
|
||||
import java.util.Locale
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.int
|
||||
import kotlinx.serialization.json.jsonArray
|
||||
import kotlinx.serialization.json.jsonObject
|
||||
import kotlinx.serialization.json.jsonPrimitive
|
||||
|
||||
// A wire id is regionId * 1000 + index, and the client answers in the region 5 table.
|
||||
private const val ITEM_REGION_BLOCK = 5000
|
||||
|
||||
private val PLACEHOLDER_NAMES = setOf("None", "?????", "???", "-", "?", "")
|
||||
|
||||
/** A name's position in `item_names.json` is the index `items.json` keys by. */
|
||||
class ItemDataParser(private val dataDir: File) {
|
||||
|
||||
private val json = Json { ignoreUnknownKeys = true }
|
||||
|
||||
fun parseAll(): List<ParsedItem> {
|
||||
val itemsFile = File(dataDir, "items.json")
|
||||
val namesFile = File(dataDir, "item_names.json")
|
||||
require(itemsFile.exists() && namesFile.exists()) {
|
||||
"Item data not found at $dataDir (missing ${itemsFile.name} or ${namesFile.name})"
|
||||
}
|
||||
|
||||
val names =
|
||||
json.parseToJsonElement(namesFile.readText()).jsonArray.map { it.jsonPrimitive.content }
|
||||
val prices =
|
||||
json.parseToJsonElement(itemsFile.readText()).jsonArray.associate { entry ->
|
||||
val obj = entry.jsonObject
|
||||
obj.getValue("index").jsonPrimitive.int to obj.getValue("price").jsonPrimitive.int
|
||||
}
|
||||
|
||||
return names
|
||||
.withIndex()
|
||||
.filterNot { (index, name) -> index == 0 || name.trim() in PLACEHOLDER_NAMES }
|
||||
.mapNotNull { (index, name) ->
|
||||
val identifier = identifierOf(name)
|
||||
if (identifier.isEmpty()) null else Triple(identifier, name, index)
|
||||
}
|
||||
.groupBy { it.first }
|
||||
.map { (identifier, group) ->
|
||||
// Two different names normalising the same would silently become one item.
|
||||
val grouped = group.map { it.second }.distinct()
|
||||
check(grouped.size == 1) { "Items $grouped all derive the identifier $identifier" }
|
||||
val lowest = group.minBy { it.third }
|
||||
ParsedItem(
|
||||
identifier = identifier,
|
||||
name = lowest.second,
|
||||
price = prices[lowest.third] ?: 0,
|
||||
ids = group.map { ITEM_REGION_BLOCK + it.third }.sorted(),
|
||||
)
|
||||
}
|
||||
.sortedBy { it.ids.first() }
|
||||
}
|
||||
|
||||
/** Turns a display name into a Kotlin constant name: "Poké Ball" becomes POKE_BALL. */
|
||||
private fun identifierOf(name: String): String =
|
||||
Normalizer.normalize(name, Normalizer.Form.NFD)
|
||||
.replace(Regex("\\p{Mn}+"), "")
|
||||
.uppercase(Locale.ROOT)
|
||||
.replace(Regex("[^A-Z0-9]+"), "_")
|
||||
.trim('_')
|
||||
.let { if (it.firstOrNull()?.isDigit() == true) "_$it" else it }
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
package de.fiereu.openmmo.codegen.item
|
||||
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Reads the item constants out of a GBA decomp header. The two GBA decomps use the same item
|
||||
* numbering, so one decomp is the single source of truth, the same way moves and species are.
|
||||
*
|
||||
* The client keys an item by `regionId * 1000 + itemId` and holds one item table per region.
|
||||
* [regionId] picks the table that matches the decomp's own numbering, which leaves the Poke Ball at
|
||||
* its decomp 4.
|
||||
*/
|
||||
class ItemParser(private val decompDir: File, private val regionId: Int) {
|
||||
|
||||
fun parseAll(): List<ParsedItem> {
|
||||
val header = File(decompDir, "include/constants/items.h")
|
||||
require(header.exists()) { "Missing ${header.path}" }
|
||||
val define = Regex("""^#define\s+ITEM_([A-Z0-9_]+)\s+(\d+)\s*$""")
|
||||
// ITEMS_COUNT closes the item list. Everything after it reuses the ITEM_ prefix for unrelated
|
||||
// constants like the bag usage types, so parsing stops there.
|
||||
return header
|
||||
.readLines()
|
||||
.takeWhile { !it.trimStart().startsWith("#define ITEMS_COUNT") }
|
||||
.mapNotNull { define.find(it.trim()) }
|
||||
.map { ParsedItem(it.groupValues[1], regionId * 1000 + it.groupValues[2].toInt()) }
|
||||
// Placeholder slots are named after their hex index, for example ITEM_15C.
|
||||
.filterNot { it.name.first().isDigit() }
|
||||
.distinctBy(ParsedItem::name)
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ class ItemsRenderer(
|
||||
private val templatesDir: File,
|
||||
private val outputDir: File,
|
||||
private val classCacheDir: File,
|
||||
private val registryChunkSize: Int = 50,
|
||||
) {
|
||||
|
||||
fun render(items: List<ParsedItem>) {
|
||||
@@ -28,6 +29,9 @@ class ItemsRenderer(
|
||||
FileOutput(File(packageRoot, "Items.kt").toPath()).use { out ->
|
||||
engine.render("Items.jte", mapOf("items" to items), out)
|
||||
}
|
||||
FileOutput(File(packageRoot, "GeneratedItems.kt").toPath()).use { out ->
|
||||
engine.render("ItemsRegistry.jte", mapOf("chunks" to items.chunked(registryChunkSize)), out)
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
|
||||
@@ -2,23 +2,21 @@
|
||||
|
||||
package de.fiereu.openmmo.codegen.item
|
||||
|
||||
import de.fiereu.openmmo.common.enums.Region
|
||||
import java.io.File
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
require(args.size >= 4) {
|
||||
"Usage: <output-dir> <templates-dir> <class-cache-dir> <region|decomp> got ${args.toList()}"
|
||||
"Usage: <output-dir> <templates-dir> <class-cache-dir> <item-data-dir> got ${args.toList()}"
|
||||
}
|
||||
val outputDir = File(args[0])
|
||||
val templatesDir = File(args[1])
|
||||
val classCacheDir = File(args[2])
|
||||
val (region, decomp) = args[3].split("|")
|
||||
val decompDir = File(decomp)
|
||||
val regionId = Region.valueOf(region.uppercase()).wireValue.toInt()
|
||||
val dataDir = File(args[3])
|
||||
|
||||
println("[item] parsing $region items from $decompDir")
|
||||
val items = ItemParser(decompDir, regionId).parseAll()
|
||||
println("[item] parsed ${items.size} items. writing to $outputDir")
|
||||
println("[item] parsing from $dataDir")
|
||||
val items = ItemDataParser(dataDir).parseAll()
|
||||
val ids = items.sumOf { it.ids.size }
|
||||
println("[item] parsed ${items.size} items carrying $ids ids. writing to $outputDir")
|
||||
ItemsRenderer(templatesDir, outputDir, classCacheDir).render(items)
|
||||
println("[item] done")
|
||||
}
|
||||
@@ -1,4 +1,9 @@
|
||||
package de.fiereu.openmmo.codegen.item
|
||||
|
||||
/** One item constant: the decomp name without its ITEM_ prefix and the id the client uses. */
|
||||
data class ParsedItem(val name: String, val id: Int)
|
||||
/** [ids] is a list because the table lists some items in more than one slot. */
|
||||
data class ParsedItem(
|
||||
val identifier: String,
|
||||
val name: String,
|
||||
val price: Int,
|
||||
val ids: List<Int>,
|
||||
)
|
||||
@@ -0,0 +1,14 @@
|
||||
package de.fiereu.openmmo.codegen.item
|
||||
|
||||
object RenderUtil {
|
||||
|
||||
fun declaration(item: ParsedItem): String =
|
||||
" /** ${item.ids.joinToString(", ")} */\n" +
|
||||
" val ${item.identifier} = item(${escapeString(item.name)}, ${item.price})"
|
||||
|
||||
fun register(item: ParsedItem): String =
|
||||
"reg.register(Items.${item.identifier}, ${item.ids.joinToString(", ")})"
|
||||
|
||||
private fun escapeString(s: String): String =
|
||||
"\"" + s.replace("\\", "\\\\").replace("\"", "\\\"") + "\""
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package de.fiereu.openmmo.items
|
||||
|
||||
/** Not a data class on purpose. The catalogue instance is the identity, so equality is by it. */
|
||||
class ItemDef(val name: String, val price: Int) {
|
||||
override fun toString(): String = name
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package de.fiereu.openmmo.items
|
||||
|
||||
import de.fiereu.openmmo.items.generated.GeneratedItems
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
@Singleton
|
||||
class ItemRegistry @Inject constructor() {
|
||||
|
||||
private val byId = ConcurrentHashMap<Int, ItemDef>()
|
||||
private val idsByItem = ConcurrentHashMap<ItemDef, List<Int>>()
|
||||
|
||||
init {
|
||||
GeneratedItems.loadInto(this)
|
||||
}
|
||||
|
||||
fun register(item: ItemDef, vararg ids: Int) {
|
||||
for (id in ids) {
|
||||
val previous = byId.put(id, item)
|
||||
// Generated data, so a clash is a codegen bug rather than bad input.
|
||||
check(previous == null || previous === item) {
|
||||
"Item id $id is claimed by both ${previous?.name} and ${item.name}"
|
||||
}
|
||||
}
|
||||
idsByItem.merge(item, ids.toList()) { old, new -> (old + new).distinct().sorted() }
|
||||
}
|
||||
|
||||
fun get(id: Int): ItemDef? = byId[id]
|
||||
|
||||
fun idsOf(item: ItemDef): List<Int> = idsByItem[item].orEmpty()
|
||||
|
||||
/** An item with several ids is named by its lowest. */
|
||||
fun idOf(item: ItemDef): Int =
|
||||
idsOf(item).firstOrNull() ?: error("Item '${item.name}' has no id in this build")
|
||||
|
||||
fun idOrNull(item: ItemDef): Int? = idsOf(item).firstOrNull()
|
||||
|
||||
fun all(): Collection<ItemDef> = idsByItem.keys
|
||||
|
||||
fun size(): Int = idsByItem.size
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package de.fiereu.openmmo.codegen.item
|
||||
|
||||
import io.kotest.assertions.throwables.shouldThrow
|
||||
import io.kotest.core.spec.style.FunSpec
|
||||
import io.kotest.matchers.collections.shouldContainExactly
|
||||
import io.kotest.matchers.shouldBe
|
||||
import java.io.File
|
||||
|
||||
private fun dataDir(names: List<String>, prices: Map<Int, Int>): File {
|
||||
val dir = kotlin.io.path.createTempDirectory("item-data").toFile()
|
||||
dir.resolve("item_names.json").writeText(names.joinToString(",", "[", "]") { "\"$it\"" })
|
||||
dir.resolve("items.json")
|
||||
.writeText(
|
||||
prices.entries.joinToString(",", "[", "]") { (index, price) ->
|
||||
"""{"index":$index,"price":$price,"hold_effect":0}"""
|
||||
})
|
||||
return dir
|
||||
}
|
||||
|
||||
class ItemDataParserTest :
|
||||
FunSpec({
|
||||
test("reads a name and its price into the region 5 id block") {
|
||||
val items =
|
||||
ItemDataParser(
|
||||
dataDir(
|
||||
listOf("None", "Master Ball", "Ultra Ball", "Poké Ball"),
|
||||
mapOf(1 to 0, 2 to 1200, 3 to 200)))
|
||||
.parseAll()
|
||||
|
||||
items.single { it.identifier == "POKE_BALL" } shouldBe
|
||||
ParsedItem("POKE_BALL", "Poké Ball", 200, listOf(5003))
|
||||
}
|
||||
|
||||
test("collects every slot sharing a name into one item with several ids") {
|
||||
val items =
|
||||
ItemDataParser(
|
||||
dataDir(
|
||||
listOf("None", "Potion", "Antidote", "Potion"),
|
||||
mapOf(1 to 300, 2 to 100, 3 to 300)))
|
||||
.parseAll()
|
||||
|
||||
items.single { it.identifier == "POTION" }.ids shouldContainExactly listOf(5001, 5003)
|
||||
}
|
||||
|
||||
test("skips index 0 and the placeholder slots") {
|
||||
val items =
|
||||
ItemDataParser(dataDir(listOf("None", "?????", "-", "", "Potion"), mapOf(4 to 300)))
|
||||
.parseAll()
|
||||
|
||||
items.map { it.identifier } shouldContainExactly listOf("POTION")
|
||||
}
|
||||
|
||||
test("derives identifiers that are legal Kotlin names") {
|
||||
val names = listOf("None", "Poké Ball", "Parlyz Heal", "Up-Grade", "10 Coins", "X Attack")
|
||||
val items = ItemDataParser(dataDir(names, emptyMap())).parseAll()
|
||||
|
||||
items.map { it.identifier } shouldContainExactly
|
||||
listOf("POKE_BALL", "PARLYZ_HEAL", "UP_GRADE", "_10_COINS", "X_ATTACK")
|
||||
}
|
||||
|
||||
test("prices an item the table has no entry for at zero") {
|
||||
val items = ItemDataParser(dataDir(listOf("None", "Parcel"), emptyMap())).parseAll()
|
||||
|
||||
items.single().price shouldBe 0
|
||||
}
|
||||
|
||||
test("fails loudly when the vendored data is missing") {
|
||||
val empty = kotlin.io.path.createTempDirectory("item-data-empty").toFile()
|
||||
|
||||
shouldThrow<IllegalArgumentException> { ItemDataParser(empty).parseAll() }
|
||||
}
|
||||
})
|
||||
@@ -1,41 +0,0 @@
|
||||
package de.fiereu.openmmo.codegen.item
|
||||
|
||||
import de.fiereu.openmmo.common.enums.Region
|
||||
import io.kotest.core.spec.style.FunSpec
|
||||
import io.kotest.matchers.shouldBe
|
||||
|
||||
class ItemParserTest :
|
||||
FunSpec({
|
||||
test("prefixes decomp item ids with their region and stops at the list end") {
|
||||
val decomp = kotlin.io.path.createTempDirectory("items").toFile()
|
||||
decomp.resolve("include/constants").mkdirs()
|
||||
decomp
|
||||
.resolve("include/constants/items.h")
|
||||
.writeText(
|
||||
"""
|
||||
#define ITEM_NONE 0
|
||||
#define ITEM_GREAT_BALL 3
|
||||
#define ITEM_POKE_BALL 4
|
||||
#define ITEM_15C 348
|
||||
#define ITEM_LIST_END 0xFFFF
|
||||
#define ITEMS_COUNT 377
|
||||
#define ITEM_USE_MAIL 0
|
||||
#define ITEM_HAS_EFFECT(item) ((item) >= ITEM_POTION)
|
||||
"""
|
||||
.trimIndent())
|
||||
|
||||
ItemParser(decomp, Region.KANTO.wireValue.toInt()).parseAll() shouldBe
|
||||
listOf(
|
||||
ParsedItem("NONE", 0),
|
||||
ParsedItem("GREAT_BALL", 3),
|
||||
ParsedItem("POKE_BALL", 4),
|
||||
)
|
||||
|
||||
ItemParser(decomp, Region.HOENN.wireValue.toInt()).parseAll() shouldBe
|
||||
listOf(
|
||||
ParsedItem("NONE", 1000),
|
||||
ParsedItem("GREAT_BALL", 1003),
|
||||
ParsedItem("POKE_BALL", 1004),
|
||||
)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,78 @@
|
||||
package de.fiereu.openmmo.items
|
||||
|
||||
import de.fiereu.openmmo.items.generated.Items
|
||||
import io.kotest.assertions.throwables.shouldThrow
|
||||
import io.kotest.core.spec.style.FunSpec
|
||||
import io.kotest.matchers.collections.shouldContainExactly
|
||||
import io.kotest.matchers.ints.shouldBeGreaterThan
|
||||
import io.kotest.matchers.nulls.shouldBeNull
|
||||
import io.kotest.matchers.shouldBe
|
||||
|
||||
class ItemRegistryTest :
|
||||
FunSpec({
|
||||
// Kotest shares the spec instance, so the tests that register have to work on their own
|
||||
// registry rather than a shared one.
|
||||
fun registry() = ItemRegistry()
|
||||
|
||||
test("loads the generated catalogue") { registry().size() shouldBeGreaterThan 500 }
|
||||
|
||||
test("resolves the ids the live client sends") {
|
||||
val items = registry()
|
||||
|
||||
items.idOf(Items.POKE_BALL) shouldBe 5004
|
||||
items.idOf(Items.POTION) shouldBe 5017
|
||||
items.idOf(Items.ANTIDOTE) shouldBe 5018
|
||||
items.idOf(Items.PARLYZ_HEAL) shouldBe 5022
|
||||
items.idOf(Items.PARCEL) shouldBe 5459
|
||||
}
|
||||
|
||||
test("carries the price the item table gives") {
|
||||
Items.POKE_BALL.price shouldBe 200
|
||||
Items.POTION.price shouldBe 300
|
||||
Items.ANTIDOTE.price shouldBe 100
|
||||
Items.PARLYZ_HEAL.price shouldBe 200
|
||||
}
|
||||
|
||||
test("round trips every item through its ids") {
|
||||
val items = registry()
|
||||
|
||||
for (item in items.all()) {
|
||||
for (id in items.idsOf(item)) {
|
||||
items.get(id) shouldBe item
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
test("answers nothing for an id no item claims") { registry().get(1).shouldBeNull() }
|
||||
|
||||
test("an item is its identity, so a look-alike does not resolve") {
|
||||
val items = registry()
|
||||
|
||||
items.idOrNull(ItemDef(Items.POTION.name, Items.POTION.price)).shouldBeNull()
|
||||
}
|
||||
|
||||
test("refuses an id already claimed by another item") {
|
||||
val items = registry()
|
||||
|
||||
shouldThrow<IllegalStateException> {
|
||||
items.register(ItemDef("Impostor", 0), items.idOf(Items.POTION))
|
||||
}
|
||||
}
|
||||
|
||||
test("registering the same item twice merges its ids") {
|
||||
val items = registry()
|
||||
val item = ItemDef("Multi", 10)
|
||||
|
||||
items.register(item, 90002)
|
||||
items.register(item, 90001, 90002)
|
||||
|
||||
items.idsOf(item) shouldContainExactly listOf(90001, 90002)
|
||||
items.idOf(item) shouldBe 90001
|
||||
}
|
||||
|
||||
test("throws by name for an item this build has no id for") {
|
||||
val thrown = shouldThrow<IllegalStateException> { registry().idOf(ItemDef("Teachy TV", 0)) }
|
||||
|
||||
thrown.message shouldBe "Item 'Teachy TV' has no id in this build"
|
||||
}
|
||||
})
|
||||
Reference in new issue
Block a user