feat(codegen): generate the decomp trainers and their parties (#115)
This commit is contained in:
1 parent
a6ee4bc91d
commit
457f21c17f
14 files changed
+429
-10
No files matched your search
@@ -0,0 +1,31 @@
|
||||
@import java.util.List
|
||||
@import de.fiereu.openmmo.codegen.trainer.ParsedTrainer
|
||||
@import de.fiereu.openmmo.codegen.trainer.RenderUtil
|
||||
|
||||
@param String pkg
|
||||
@param String objectName
|
||||
@param String region
|
||||
@param List<List<ParsedTrainer>> chunks
|
||||
package ${pkg}
|
||||
|
||||
import de.fiereu.openmmo.common.enums.Region
|
||||
import de.fiereu.openmmo.trainer.TrainerDef
|
||||
import de.fiereu.openmmo.trainer.TrainerMon
|
||||
import de.fiereu.openmmo.trainer.TrainerRegistry
|
||||
|
||||
internal object ${objectName} {
|
||||
fun loadInto(reg: TrainerRegistry) {
|
||||
@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: TrainerRegistry) {
|
||||
@for(ParsedTrainer t : chunks.get(c))
|
||||
${RenderUtil.INSTANCE.trainer(region, t)}
|
||||
@endfor
|
||||
}
|
||||
|
||||
@endfor
|
||||
}
|
||||
@@ -2,12 +2,18 @@ package de.fiereu.openmmo.codegen
|
||||
|
||||
import java.io.File
|
||||
|
||||
/** Reads a `#define <prefix><name> <number>` block, keyed by the full constant name. */
|
||||
/**
|
||||
* Reads a `#define <prefix><name> <number>` block, keyed by the full constant name. Emerald writes
|
||||
* its trainer classes in hex, FireRed in decimal.
|
||||
*/
|
||||
fun defineTable(file: File, prefix: String): Map<String, Int> {
|
||||
if (!file.exists()) return emptyMap()
|
||||
val regex = Regex("""^#define\s+($prefix\w+)\s+(\d+)\s*$""")
|
||||
val regex = Regex("""^#define\s+($prefix\w+)\s+(0[xX][0-9a-fA-F]+|\d+)\s*(?://.*)?$""")
|
||||
return file
|
||||
.readLines()
|
||||
.mapNotNull { regex.find(it.trim()) }
|
||||
.associate { it.groupValues[1] to it.groupValues[2].toInt() }
|
||||
.associate { it.groupValues[1] to parseNumber(it.groupValues[2]) }
|
||||
}
|
||||
|
||||
private fun parseNumber(text: String): Int =
|
||||
if (text.startsWith("0x", ignoreCase = true)) text.substring(2).toInt(16) else text.toInt()
|
||||
@@ -0,0 +1,22 @@
|
||||
@file:JvmName("Main")
|
||||
|
||||
package de.fiereu.openmmo.codegen.trainer
|
||||
|
||||
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()}"
|
||||
}
|
||||
val outputDir = File(args[0])
|
||||
val templatesDir = File(args[1])
|
||||
val classCacheDir = File(args[2])
|
||||
|
||||
for (spec in args.drop(3)) {
|
||||
val (region, decomp) = spec.split("|")
|
||||
val trainers = TrainerParser(File(decomp)).parseAll()
|
||||
println("[trainer] $region: parsed ${trainers.size} trainers from $decomp")
|
||||
TrainerRenderer(region, templatesDir, outputDir, classCacheDir).render(trainers)
|
||||
}
|
||||
println("[trainer] done")
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package de.fiereu.openmmo.codegen.trainer
|
||||
|
||||
/** A monster on a trainer's team. Empty [moveIds] means the level up moveset is used. */
|
||||
data class ParsedTrainerMon(
|
||||
val dexId: Int,
|
||||
val level: Int,
|
||||
val iv: Int,
|
||||
val heldItem: Int,
|
||||
val moveIds: List<Int>,
|
||||
)
|
||||
|
||||
data class ParsedTrainer(
|
||||
val id: Int,
|
||||
val name: String,
|
||||
val trainerClass: Int,
|
||||
val doubleBattle: Boolean,
|
||||
val party: List<ParsedTrainerMon>,
|
||||
)
|
||||
@@ -0,0 +1,17 @@
|
||||
package de.fiereu.openmmo.codegen.trainer
|
||||
|
||||
object RenderUtil {
|
||||
|
||||
fun trainer(region: String, t: ParsedTrainer): String {
|
||||
val party = t.party.joinToString(", ", "listOf(", ")") { mon(it) }
|
||||
return "reg.register(Region.${region.uppercase()}, TrainerDef(${t.id}, \"${escape(t.name)}\", " +
|
||||
"${t.trainerClass}, ${t.doubleBattle}, $party))"
|
||||
}
|
||||
|
||||
private fun mon(m: ParsedTrainerMon): String {
|
||||
val moves = m.moveIds.joinToString(", ", "listOf(", ")")
|
||||
return "TrainerMon(${m.dexId}, ${m.level}, ${m.iv}, ${m.heldItem}, $moves)"
|
||||
}
|
||||
|
||||
private fun escape(name: String) = name.replace("\\", "\\\\").replace("\"", "\\\"")
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package de.fiereu.openmmo.codegen.trainer
|
||||
|
||||
import de.fiereu.openmmo.codegen.defineTable
|
||||
import de.fiereu.openmmo.codegen.pokemon.NationalDex
|
||||
import de.fiereu.openmmo.codegen.pokemon.SpeciesParser
|
||||
import de.fiereu.openmmo.common.enums.MAX_IV
|
||||
import java.io.File
|
||||
|
||||
class TrainerParser(private val rootDir: File) {
|
||||
|
||||
private val trainerIds = defines("include/constants/opponents.h", "TRAINER_")
|
||||
private val classIds = defines("include/constants/trainers.h", "TRAINER_CLASS_")
|
||||
private val speciesIds = defines("include/constants/species.h", "SPECIES_")
|
||||
private val moveIds = defines("include/constants/moves.h", "MOVE_")
|
||||
private val itemIds = defines("include/constants/items.h", "ITEM_")
|
||||
private val nationalDex = NationalDex.read(rootDir)
|
||||
private val knownDexIds = SpeciesParser(rootDir).parseAll().mapTo(HashSet()) { it.id }
|
||||
|
||||
fun parseAll(): List<ParsedTrainer> {
|
||||
val parties = readParties()
|
||||
return readTrainers()
|
||||
.mapNotNull { entry ->
|
||||
val id = trainerIds[entry.constant]
|
||||
if (id == null) {
|
||||
println("[trainer] skipped ${entry.constant}, it has no id in opponents.h")
|
||||
return@mapNotNull null
|
||||
}
|
||||
val party = parties[entry.partySymbol]?.mapNotNull(::toMon).orEmpty()
|
||||
// A trainer whose party stopped parsing would otherwise vanish without a trace.
|
||||
if (party.isEmpty()) {
|
||||
println(
|
||||
"[trainer] skipped ${entry.constant}, ${entry.partySymbol} has no usable members")
|
||||
return@mapNotNull null
|
||||
}
|
||||
ParsedTrainer(
|
||||
id = id,
|
||||
name = entry.name,
|
||||
trainerClass = classIds[entry.trainerClass] ?: 0,
|
||||
doubleBattle = entry.doubleBattle,
|
||||
party = party,
|
||||
)
|
||||
}
|
||||
.sortedBy { it.id }
|
||||
}
|
||||
|
||||
private fun toMon(fields: Map<String, String>): ParsedTrainerMon? {
|
||||
val dexId = speciesIds[fields["species"]]?.let { nationalDex[it] } ?: return null
|
||||
if (dexId !in knownDexIds) return null
|
||||
val level = fields["lvl"]?.toIntOrNull() ?: return null
|
||||
val moves =
|
||||
fields["moves"]
|
||||
?.let { MOVE.findAll(it).mapNotNull { m -> moveIds[m.value] }.toList() }
|
||||
?.filter { it != 0 }
|
||||
.orEmpty()
|
||||
// The decomp stores a 0 to 255 difficulty here and scales it to a real IV when it builds the
|
||||
// party, so scale it once here rather than leaving a 255 that looks like an IV but is not.
|
||||
val difficulty = fields["iv"]?.toIntOrNull() ?: 0
|
||||
return ParsedTrainerMon(
|
||||
dexId = dexId,
|
||||
level = level,
|
||||
iv = difficulty * MAX_IV / 255,
|
||||
heldItem = itemIds[fields["heldItem"]] ?: 0,
|
||||
moveIds = moves,
|
||||
)
|
||||
}
|
||||
|
||||
private data class TrainerEntry(
|
||||
val constant: String,
|
||||
val name: String,
|
||||
val trainerClass: String,
|
||||
val doubleBattle: Boolean,
|
||||
val partySymbol: String,
|
||||
)
|
||||
|
||||
// [TRAINER_X] = { .trainerClass = ..., .trainerName = _("NAME"), .party = MACRO(sParty_X), }
|
||||
private fun readTrainers(): List<TrainerEntry> =
|
||||
ENTRY.findAll(read("src/data/trainers.h"))
|
||||
.mapNotNull { match ->
|
||||
val body = match.groupValues[2]
|
||||
val party = PARTY.find(body)?.groupValues?.get(1) ?: return@mapNotNull null
|
||||
TrainerEntry(
|
||||
constant = match.groupValues[1],
|
||||
name = NAME.find(body)?.groupValues?.get(1).orEmpty(),
|
||||
trainerClass = CLASS.find(body)?.groupValues?.get(1).orEmpty(),
|
||||
doubleBattle = body.contains(".doubleBattle = TRUE"),
|
||||
partySymbol = party,
|
||||
)
|
||||
}
|
||||
.toList()
|
||||
|
||||
/**
|
||||
* The party arrays keyed by symbol. The RS placeholder teams are written as bare macro names, so
|
||||
* the macro bodies are read first and pasted in before the members are split out.
|
||||
*/
|
||||
private fun readParties(): Map<String, List<Map<String, String>>> {
|
||||
val text = read("src/data/trainer_parties.h")
|
||||
val macros =
|
||||
MACRO.findAll(text).associate { it.groupValues[1] to it.groupValues[2].replace("\\", " ") }
|
||||
return ARRAY.findAll(text).associate { match ->
|
||||
val body =
|
||||
macros.entries.fold(match.groupValues[2]) { acc, (name, b) -> acc.replace(name, b) }
|
||||
match.groupValues[1] to MEMBER.findAll(body).map { fields(it.groupValues[1]) }.toList()
|
||||
}
|
||||
}
|
||||
|
||||
private fun fields(body: String): Map<String, String> =
|
||||
FIELD.findAll(body).associate { it.groupValues[1] to it.groupValues[2].trim() }
|
||||
|
||||
private fun defines(path: String, prefix: String): Map<String, Int> =
|
||||
defineTable(File(rootDir, path), prefix)
|
||||
|
||||
private fun read(path: String): String {
|
||||
val file = File(rootDir, path)
|
||||
require(file.exists()) {
|
||||
"Decomp not initialized at $rootDir (missing ${file.path}). " +
|
||||
"Run: git submodule update --init --recursive"
|
||||
}
|
||||
return file.readText()
|
||||
}
|
||||
|
||||
private companion object {
|
||||
val ENTRY = Regex("""\[(TRAINER_\w+)]\s*=\s*\{(.*?)\n\s*},""", RegexOption.DOT_MATCHES_ALL)
|
||||
val NAME = Regex("""\.trainerName\s*=\s*_\("([^"]*)"\)""")
|
||||
val CLASS = Regex("""\.trainerClass\s*=\s*(TRAINER_CLASS_\w+)""")
|
||||
val PARTY = Regex("""\.party\s*=\s*\w+\(\s*(\w+)\s*\)""")
|
||||
val MACRO = Regex("""#define\s+(DUMMY_\w+)\s+((?:.*\\\r?\n)*.*)""")
|
||||
val ARRAY =
|
||||
Regex(
|
||||
"""static\s+const\s+struct\s+TrainerMon\w+\s+(\w+)\s*\[\s*]\s*=\s*\{(.*?)};""",
|
||||
RegexOption.DOT_MATCHES_ALL,
|
||||
)
|
||||
// One member, allowing the single nested brace list that .moves brings.
|
||||
val MEMBER = Regex("""\{((?:[^{}]|\{[^{}]*})*)}""", RegexOption.DOT_MATCHES_ALL)
|
||||
val FIELD = Regex("""\.(\w+)\s*=\s*(\{[^}]*}|[^,}]+)""")
|
||||
val MOVE = Regex("""MOVE_\w+""")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package de.fiereu.openmmo.codegen.trainer
|
||||
|
||||
import gg.jte.ContentType
|
||||
import gg.jte.TemplateEngine
|
||||
import gg.jte.output.FileOutput
|
||||
import gg.jte.resolve.DirectoryCodeResolver
|
||||
import java.io.File
|
||||
|
||||
/** Emits one object of trainer registrations per region, namespaced the same way story keys are. */
|
||||
class TrainerRenderer(
|
||||
private val region: String,
|
||||
private val templatesDir: File,
|
||||
private val outputDir: File,
|
||||
private val classCacheDir: File,
|
||||
private val chunkSize: Int = 25,
|
||||
) {
|
||||
|
||||
fun render(trainers: List<ParsedTrainer>) {
|
||||
classCacheDir.mkdirs()
|
||||
val engine =
|
||||
TemplateEngine.create(
|
||||
DirectoryCodeResolver(templatesDir.toPath()),
|
||||
classCacheDir.toPath(),
|
||||
ContentType.Plain,
|
||||
)
|
||||
|
||||
val objectName = "Generated${region.replaceFirstChar { it.uppercase() }}Trainers"
|
||||
val file = File(outputDir, "${BASE_PACKAGE.replace('.', '/')}/$objectName.kt")
|
||||
file.parentFile.mkdirs()
|
||||
FileOutput(file.toPath()).use { out ->
|
||||
engine.render(
|
||||
"TrainerRegistry.jte",
|
||||
mapOf(
|
||||
"pkg" to BASE_PACKAGE,
|
||||
"objectName" to objectName,
|
||||
"region" to region,
|
||||
"chunks" to trainers.chunked(chunkSize),
|
||||
),
|
||||
out,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val BASE_PACKAGE = "de.fiereu.openmmo.trainer.generated"
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user