feat(game): start a wild battle when a player steps in grass (#68)

* feat(game): start a wild battle when a player steps in grass

* fix(codegen): key species by national dex so the client shows the right mon
This commit is contained in:
Fiereu authored and GitHub committed 2026-07-26 11:04:35 +02:00
1 parent 300bc52531
commit 109cf5f814
18 files changed
+488 -9

No files matched your search

+1
View File
@@ -9,6 +9,7 @@ dependencies {
api(project(":common"))
api(project(":protocols.game"))
api(libs.dagger)
"generatorImplementation"(project(":common"))
"generatorImplementation"(libs.jte)
"generatorImplementation"(libs.kotlinx.serialization.json)
testImplementation(libs.bundles.kotest)
@@ -8,6 +8,7 @@ package ${packageName}
import de.fiereu.openmmo.common.Tile2D
import de.fiereu.openmmo.common.enums.Direction
import de.fiereu.openmmo.common.enums.EncounterMethod
import de.fiereu.openmmo.common.enums.EncounterType
import de.fiereu.openmmo.common.enums.Lighting
import de.fiereu.openmmo.common.enums.MapType
@@ -17,6 +18,8 @@ import de.fiereu.openmmo.maps.BgEventDef
import de.fiereu.openmmo.maps.MapDef
import de.fiereu.openmmo.maps.NpcDef
import de.fiereu.openmmo.maps.WarpTile
import de.fiereu.openmmo.maps.WildEncounterSlot
import de.fiereu.openmmo.maps.WildEncounterTable
import de.fiereu.openmmo.net.game.packets.MapData
internal val ${objectName}: MapDef =
@@ -32,6 +35,8 @@ internal val ${objectName}: MapDef =
unknownByte = ${map.getMapsecId()},
borderTiles = ${RenderUtil.INSTANCE.borderTiles(map.getBorderTiles())},
blockData = "${map.getBlockData()}",
behaviorData = "${map.getBehaviorData()}",
wildEncounters = ${RenderUtil.INSTANCE.encounters(map.getEncounters())},
lighting = ${map.getLighting()},
weather = ${map.getWeather()},
mapType = ${map.getMapType()},
@@ -52,6 +52,15 @@ internal val COMMON_ENCOUNTER_MAP =
"MAP_TYPE_SECRET_BASE" to ENCOUNTER_UNKNOWN_0X03,
)
// wild_encounters.json method keys mapped to their EncounterMethod ref, in a stable order.
internal val ENCOUNTER_METHODS =
listOf(
"land_mons" to "EncounterMethod.LAND",
"water_mons" to "EncounterMethod.WATER",
"rock_smash_mons" to "EncounterMethod.ROCK_SMASH",
"fishing_mons" to "EncounterMethod.FISHING",
)
private val FACING_REFS =
listOf("Direction.DOWN", "Direction.UP", "Direction.LEFT", "Direction.RIGHT")
@@ -25,7 +25,7 @@ fun main(args: Array<String>) {
val maps =
sources.flatMap { (region, dir) ->
println("[maps] parsing ${region.name} (region ${region.regionId}) from $dir")
PretGbaParser(dir, region, MovementTypes.read(dir)).parseAll()
PretGbaParser(dir, region, MovementTypes.read(dir), MetatileBehaviors.read(dir)).parseAll()
}
println("[maps] parsed ${maps.size} maps. writing to $outputDir")
MapsRenderer(templatesDir, outputDir, classCacheDir).render(maps)
@@ -0,0 +1,163 @@
package de.fiereu.openmmo.codegen.maps
import de.fiereu.openmmo.common.enums.TileBehavior
import java.io.File
import java.util.Base64
/**
* Resolves the [TileBehavior] of each tile from the decomp tileset metatile attributes, so the
* server can tell grass from plain ground. Emerald packs attributes as 16-bit words (behavior in
* bits 0-7), FireRed as 32-bit words (behavior in bits 0-8). Behaviors are classified by name so
* the two games' differing numeric values do not matter.
*/
class MetatileBehaviors
private constructor(
private val rootDir: File,
private val primaryCount: Int,
private val attrWidth: Int,
private val behaviorMask: Int,
private val idToCategory: Map<Int, TileBehavior>,
private val attributePaths: Map<String, String>,
private val tilesetAttributeSymbol: Map<String, String>,
) {
// gTileset_X -> per local metatile index -> behavior ordinal, read from its .bin on first use.
private val tilesetCache = HashMap<String, IntArray>()
/** Base64 of one behavior ordinal byte per tile, in the same order as the block data. */
fun behaviorData(
primaryTileset: String?,
secondaryTileset: String?,
blockBytes: ByteArray
): String {
val tileCount = blockBytes.size / 2
if (tileCount == 0) return ""
val primary = primaryTileset?.let { categories(it) } ?: IntArray(0)
val secondary = secondaryTileset?.let { categories(it) } ?: IntArray(0)
val out = ByteArray(tileCount)
for (i in 0 until tileCount) {
val raw =
(blockBytes[i * 2].toInt() and 0xFF) or ((blockBytes[i * 2 + 1].toInt() and 0xFF) shl 8)
val metatileId = raw and 0x3FF
val ordinal =
if (metatileId < primaryCount) primary.getOrNull(metatileId)
else secondary.getOrNull(metatileId - primaryCount)
out[i] = (ordinal ?: TileBehavior.NORMAL.ordinal).toByte()
}
return Base64.getEncoder().encodeToString(out)
}
private fun categories(tilesetName: String): IntArray =
tilesetCache.getOrPut(tilesetName) {
val symbol = tilesetAttributeSymbol[tilesetName] ?: return@getOrPut IntArray(0)
val path = attributePaths[symbol] ?: return@getOrPut IntArray(0)
val file = File(rootDir, path)
if (!file.exists()) return@getOrPut IntArray(0)
val bytes = file.readBytes()
IntArray(bytes.size / attrWidth) { m ->
var attr = 0
for (b in 0 until attrWidth) {
attr = attr or ((bytes[m * attrWidth + b].toInt() and 0xFF) shl (8 * b))
}
(idToCategory[attr and behaviorMask] ?: TileBehavior.NORMAL).ordinal
}
}
companion object {
fun read(rootDir: File): MetatileBehaviors {
val behaviorIds = parseBehaviorIds(File(rootDir, "include/constants/metatile_behaviors.h"))
val idToCategory =
behaviorIds.mapNotNull { (name, id) -> classify(name)?.let { id to it } }.toMap()
val (attributePaths, width) =
parseAttributeIncbins(File(rootDir, "src/data/tilesets/metatiles.h"))
val behaviorMask = if (width == 4) 0x1FF else 0xFF
return MetatileBehaviors(
rootDir = rootDir,
primaryCount = readPrimaryCount(File(rootDir, "include/fieldmap.h")),
attrWidth = width,
behaviorMask = behaviorMask,
idToCategory = idToCategory,
attributePaths = attributePaths,
tilesetAttributeSymbol =
parseTilesetAttributes(File(rootDir, "src/data/tilesets/headers.h")),
)
}
// Only the behaviors we act on are mapped, everything else stays NORMAL.
private fun classify(name: String): TileBehavior? =
when (name) {
"MB_TALL_GRASS" -> TileBehavior.TALL_GRASS
"MB_LONG_GRASS" -> TileBehavior.LONG_GRASS
else -> null
}
// FireRed lists behaviors as #define constants, Emerald as a plain enum (with a stray #define
// or two). Parse both so either game resolves regardless of which style it mixes in.
private fun parseBehaviorIds(file: File): Map<String, Int> {
if (!file.exists()) return emptyMap()
val out = LinkedHashMap<String, Int>()
val defineRe = Regex("""#define\s+(MB_\w+)\s+(0x[0-9A-Fa-f]+|\d+)""")
for (m in defineRe.findAll(file.readText())) out[m.groupValues[1]] =
parseInt(m.groupValues[2])
// Enum entries take sequential values, but some are given an explicit value mid-list.
val entryRe = Regex("""^(MB_\w+)\s*(?:=\s*(0x[0-9A-Fa-f]+|\d+))?""")
var next = 0
var inEnum = false
for (raw in file.readLines()) {
val line = raw.trim()
if (line.startsWith("enum")) {
inEnum = true
continue
}
if (!inEnum) continue
if (line.startsWith("}")) {
inEnum = false
continue
}
val m = entryRe.find(line) ?: continue
val id = m.groupValues[2].takeIf { it.isNotEmpty() }?.let { parseInt(it) } ?: next
out.putIfAbsent(m.groupValues[1], id)
next = id + 1
}
return out
}
private fun readPrimaryCount(file: File): Int {
if (!file.exists()) return 512
val re = Regex("""#define\s+NUM_METATILES_IN_PRIMARY\s+(\d+)""")
return file.readLines().firstNotNullOfOrNull {
re.find(it.trim())?.groupValues?.get(1)?.toInt()
} ?: 512
}
// gMetatileAttributes_X[] = INCBIN_U16/U32("path"). The width tells us the attribute size.
private fun parseAttributeIncbins(file: File): Pair<Map<String, String>, Int> {
if (!file.exists()) return emptyMap<String, String>() to 2
val re = Regex("""(gMetatileAttributes_\w+)\[]\s*=\s*INCBIN_U(16|32)\("([^"]+)"\)""")
val map = LinkedHashMap<String, String>()
var width = 2
for (m in re.findAll(file.readText())) {
map[m.groupValues[1]] = m.groupValues[3]
width = if (m.groupValues[2] == "32") 4 else 2
}
return map to width
}
// Walk the tileset structs and pair each gTileset_X with its metatileAttributes symbol.
private fun parseTilesetAttributes(file: File): Map<String, String> {
if (!file.exists()) return emptyMap()
val tilesetRe = Regex("""const struct Tileset\s+(gTileset_\w+)""")
val attrRe = Regex("""\.metatileAttributes\s*=\s*(gMetatileAttributes_\w+)""")
val out = LinkedHashMap<String, String>()
var current: String? = null
for (line in file.readLines()) {
tilesetRe.find(line)?.let { current = it.groupValues[1] }
attrRe.find(line)?.let { m -> current?.let { out[it] = m.groupValues[1] } }
}
return out
}
private fun parseInt(s: String): Int =
if (s.startsWith("0x") || s.startsWith("0X")) s.substring(2).toInt(16) else s.toInt()
}
}
@@ -16,6 +16,8 @@ data class ParsedMap(
val mapsecId: Int,
val borderTiles: List<Int>,
val blockData: String,
val behaviorData: String,
val encounters: List<ParsedEncounterTable>,
val lighting: String,
val weather: String,
val mapType: String,
@@ -65,3 +67,16 @@ data class ParsedBgEvent(
val facingDir: String,
val script: String,
)
data class ParsedEncounterTable(
val method: String,
val encounterRate: Int,
val slots: List<ParsedEncounterSlot>,
)
data class ParsedEncounterSlot(
val speciesId: Int,
val minLevel: Int,
val maxLevel: Int,
val weight: Int,
)
@@ -1,5 +1,6 @@
package de.fiereu.openmmo.codegen.maps
import de.fiereu.openmmo.codegen.pokemon.NationalDex
import java.io.File
import java.nio.ByteBuffer
import java.nio.ByteOrder
@@ -18,6 +19,7 @@ class PretGbaParser(
private val rootDir: File,
private val region: RegionConstants,
private val movementTypes: MovementTypes,
private val metatileBehaviors: MetatileBehaviors,
) {
private val json = Json { ignoreUnknownKeys = true }
@@ -26,6 +28,12 @@ class PretGbaParser(
private class MapGroups(val order: List<String>, val entries: Map<String, List<String>>)
// The wild tables keyed by map constant, plus the shared per-slot weights for each method.
private class EncounterData(
val weightsByType: Map<String, List<Int>>,
val byMap: Map<String, JsonObject>,
)
private class Context(
val layouts: Map<String, JsonObject>,
val musicIds: Map<String, Int>,
@@ -34,6 +42,9 @@ class PretGbaParser(
val tilesetPaletteIds: Map<String, Int>,
val addresses: Map<String, Address>,
val mapJsons: Map<String, JsonObject>,
val speciesIds: Map<String, Int>,
val nationalDex: Map<Int, Int>,
val encounters: EncounterData,
)
fun parseAll(): List<ParsedMap> {
@@ -103,9 +114,39 @@ class PretGbaParser(
tilesetPaletteIds = readTilesetPaletteIds(),
addresses = addresses,
mapJsons = mapJsons,
speciesIds = readDefineTable(File(rootDir, "include/constants/species.h"), "SPECIES_"),
nationalDex = NationalDex.read(rootDir),
encounters = readEncounters(),
)
}
private fun readEncounters(): EncounterData {
val file = File(rootDir, "src/data/wild_encounters.json")
if (!file.exists()) return EncounterData(emptyMap(), emptyMap())
val group =
readJson(file)
.jsonObject["wild_encounter_groups"]
?.jsonArrayOrNull()
?.firstOrNull()
?.jsonObject ?: return EncounterData(emptyMap(), emptyMap())
val weights =
group["fields"]?.jsonArrayOrNull().orEmpty().mapNotNull { field ->
val obj = field.jsonObject
val type = obj["type"]?.jsonPrimitive?.contentOrNull ?: return@mapNotNull null
val rates =
obj["encounter_rates"]?.jsonArrayOrNull()?.mapNotNull { it.jsonPrimitive.intOrNull }
?: return@mapNotNull null
type to rates
}
val byMap =
group["encounters"]?.jsonArrayOrNull().orEmpty().mapNotNull { entry ->
val obj = entry.jsonObject
val mapId = obj["map"]?.jsonPrimitive?.contentOrNull ?: return@mapNotNull null
mapId to obj
}
return EncounterData(weights.toMap(), byMap.toMap())
}
private fun parseMap(
groupIndex: Int,
groupName: String,
@@ -139,6 +180,8 @@ class PretGbaParser(
mapsecId = ctx.mapsecIds[mapsecName] ?: 0,
borderTiles = parseBorderTiles(layout),
blockData = parseBlockData(layout),
behaviorData = parseBehaviorData(layout),
encounters = parseEncounters(mapJson, ctx),
lighting = "Lighting.REGULAR",
weather =
region.weatherMap[mapJson["weather"]?.jsonPrimitive?.contentOrNull]
@@ -249,6 +292,43 @@ class PretGbaParser(
return Base64.getEncoder().encodeToString(file.readBytes())
}
// One behavior byte per tile, resolved from the layout's tilesets. Empty when there is no block
// data to align with.
private fun parseBehaviorData(layout: JsonObject): String {
val path = layout["blockdata_filepath"]?.jsonPrimitive?.contentOrNull ?: return ""
val file = File(rootDir, path)
if (!file.exists()) return ""
val primary = layout["primary_tileset"]?.jsonPrimitive?.contentOrNull
val secondary = layout["secondary_tileset"]?.jsonPrimitive?.contentOrNull
return metatileBehaviors.behaviorData(primary, secondary, file.readBytes())
}
private fun parseEncounters(mapJson: JsonObject, ctx: Context): List<ParsedEncounterTable> {
val mapId = mapJson["id"]?.jsonPrimitive?.contentOrNull ?: return emptyList()
val entry = ctx.encounters.byMap[mapId] ?: return emptyList()
return ENCOUNTER_METHODS.mapNotNull { (jsonKey, methodRef) ->
val table = (entry[jsonKey] as? JsonObject) ?: return@mapNotNull null
val rate = table["encounter_rate"]?.jsonPrimitive?.intOrNull ?: 0
val weights = ctx.encounters.weightsByType[jsonKey].orEmpty()
val slots =
table["mons"]?.jsonArrayOrNull().orEmpty().mapIndexedNotNull { i, mon ->
val obj = mon.jsonObject
val speciesName =
obj["species"]?.jsonPrimitive?.contentOrNull ?: return@mapIndexedNotNull null
val internalId = ctx.speciesIds[speciesName] ?: return@mapIndexedNotNull null
val speciesId = ctx.nationalDex[internalId] ?: return@mapIndexedNotNull null
ParsedEncounterSlot(
speciesId = speciesId,
minLevel = obj["min_level"]?.jsonPrimitive?.intOrNull ?: 1,
maxLevel = obj["max_level"]?.jsonPrimitive?.intOrNull ?: 1,
weight = weights.getOrElse(i) { 1 },
)
}
if (slots.isEmpty()) null
else ParsedEncounterTable(method = methodRef, encounterRate = rate, slots = slots)
}
}
private fun readJson(file: File): JsonElement = json.parseToJsonElement(file.readText())
private fun readDefineTable(file: File, prefix: String): Map<String, Int> {
@@ -54,6 +54,19 @@ object RenderUtil {
}
}
fun encounters(tables: List<ParsedEncounterTable>): String {
if (tables.isEmpty()) return EMPTY_LIST
return tables.joinToString(LIST_SEP, LIST_OPEN, LIST_CLOSE) { table ->
val slots =
table.slots.joinToString(", ", "listOf(", ")") {
"WildEncounterSlot(speciesId = ${it.speciesId}, minLevel = ${it.minLevel}," +
" maxLevel = ${it.maxLevel}, weight = ${it.weight})"
}
"WildEncounterTable(method = ${table.method}," +
" encounterRate = ${table.encounterRate}, slots = $slots)"
}
}
private fun escapeString(s: String): String =
"\"" + s.replace("\\", "\\\\").replace("\"", "\\\"") + "\""
}
@@ -0,0 +1,52 @@
package de.fiereu.openmmo.codegen.pokemon
import java.io.File
/**
* Maps the decomp's internal species id to its national dex number. The two match through gen 1 but
* diverge from gen 3 on. The client identifies a species by its national dex number, so all
* generated data must use the national number rather than the internal one.
*/
object NationalDex {
fun read(rootDir: File): Map<Int, Int> {
val internalBySuffix = defineTable(File(rootDir, "include/constants/species.h"), "SPECIES_")
val nationalBySuffix = enumTable(File(rootDir, "include/constants/pokedex.h"), "NATIONAL_DEX_")
return internalBySuffix
.mapNotNull { (suffix, internal) -> nationalBySuffix[suffix]?.let { internal to it } }
.toMap()
}
// #define SPECIES_<suffix> <n>
private fun defineTable(file: File, prefix: String): Map<String, Int> {
if (!file.exists()) return emptyMap()
val re = Regex("""^#define\s+$prefix(\w+)\s+(\d+)\s*$""")
return file
.readLines()
.mapNotNull { re.find(it.trim()) }
.associate { it.groupValues[1] to it.groupValues[2].toInt() }
}
// A plain enum where each NATIONAL_DEX_<suffix> takes the next value, starting at NONE = 0.
private fun enumTable(file: File, prefix: String): Map<String, Int> {
if (!file.exists()) return emptyMap()
val re = Regex("""^$prefix(\w+)\s*(?:=\s*(\d+))?,?$""")
val out = LinkedHashMap<String, Int>()
var next = 0
var inEnum = false
for (raw in file.readLines()) {
val line = raw.trim()
if (line.startsWith("enum")) {
inEnum = true
continue
}
if (!inEnum) continue
if (line.startsWith("}")) break
val m = re.find(line) ?: continue
val id = m.groupValues[2].takeIf { it.isNotEmpty() }?.toInt() ?: next
out[m.groupValues[1]] = id
next = id + 1
}
return out
}
}
@@ -6,13 +6,15 @@ class SpeciesParser(private val rootDir: File) {
fun parseAll(): List<ParsedSpecies> {
val ids = readDefineTable("include/constants/species.h", "SPECIES_")
val nationalDex = NationalDex.read(rootDir)
val names = readSpeciesNames()
val items = readDefineTable("include/constants/items.h", "ITEM_")
val entries = readSpeciesInfo()
return entries
.mapNotNull { (constant, f) ->
val id = ids[constant] ?: return@mapNotNull null
// The client keys species by national dex, so that is the id we store.
val id = ids[constant]?.let { nationalDex[it] } ?: return@mapNotNull null
if (!f.containsKey("baseHP")) return@mapNotNull null
val types = braceList(f.getValue("types"))
val eggGroups = braceList(f.getValue("eggGroups"))
@@ -1,9 +1,11 @@
package de.fiereu.openmmo.maps
import de.fiereu.openmmo.common.Tile2D
import de.fiereu.openmmo.common.enums.EncounterMethod
import de.fiereu.openmmo.common.enums.EncounterType
import de.fiereu.openmmo.common.enums.Lighting
import de.fiereu.openmmo.common.enums.MapType
import de.fiereu.openmmo.common.enums.TileBehavior
import de.fiereu.openmmo.common.enums.Weather
import de.fiereu.openmmo.net.game.packets.MapData
import java.util.Base64
@@ -31,19 +33,34 @@ class MapDef(
val npcs: List<NpcDef> = emptyList(),
val bgEvents: List<BgEventDef> = emptyList(),
private val blockData: String = "",
private val behaviorData: String = "",
) {
val tiles: List<Tile2D> by lazy { decodeBlockData(blockData) }
val tiles: List<Tile2D> by lazy { decodeBlockData(blockData, behaviorData) }
fun tileAt(x: Int, y: Int): Tile2D? =
if (x in 0 until width && y in 0 until height) tiles.getOrNull(y * width + x) else null
/** The wild table for [method] on this map, or null when the map has no such encounters. */
fun encounterTable(method: EncounterMethod): WildEncounterTable? =
wildEncounters.firstOrNull { it.method == method }
}
private fun decodeBlockData(blockData: String): List<Tile2D> {
private fun decodeBlockData(blockData: String, behaviorData: String): List<Tile2D> {
if (blockData.isEmpty()) return emptyList()
val bytes = Base64.getDecoder().decode(blockData)
// One behavior byte per tile, generated alongside the block data. Empty on maps we could not
// resolve behaviors for, in which case every tile stays NORMAL.
val behaviors =
if (behaviorData.isEmpty()) ByteArray(0) else Base64.getDecoder().decode(behaviorData)
val behaviorValues = TileBehavior.entries
return List(bytes.size / 2) { i ->
val raw = (bytes[i * 2].toInt() and 0xFF) or ((bytes[i * 2 + 1].toInt() and 0xFF) shl 8)
Tile2D(material = (raw and 0x3FF).toShort(), collision = ((raw shr 10) and 0x3F).toByte())
val behavior = behaviors.getOrNull(i)?.toInt()?.let { behaviorValues.getOrNull(it) }
Tile2D(
material = (raw and 0x3FF).toShort(),
collision = ((raw shr 10) and 0x3F).toByte(),
behavior = behavior ?: TileBehavior.NORMAL,
)
}
}
@@ -1,5 +1,21 @@
package de.fiereu.openmmo.maps
data class WildEncounterTable(val encounterRate: Int, val pokemon: List<WildPokemon>)
import de.fiereu.openmmo.common.enums.EncounterMethod
data class WildPokemon(val dexId: Int, val minLevel: Int, val maxLevel: Int, val weight: Int)
/** One slot in a wild encounter table: a species, its level range, and its pick weight. */
data class WildEncounterSlot(
val speciesId: Int,
val minLevel: Int,
val maxLevel: Int,
val weight: Int,
)
/**
* The wild monsters met by one [method] on a map. [encounterRate] drives how often a step meets
* anything, the per-slot weights decide which one.
*/
data class WildEncounterTable(
val method: EncounterMethod,
val encounterRate: Int,
val slots: List<WildEncounterSlot>,
)