feat(game): implement Hoenn story through Rustboro (#77)
* feat(game): implement Hoenn story through Rustboro * fix(game): group dialog presentation options * fix(game): address review feedback and running movement
This commit is contained in:
1 parent
f57149eae3
commit
3b19a81201
85 files changed
+4064
-358
No files matched your search
@@ -15,6 +15,7 @@ import de.fiereu.openmmo.common.enums.MapType
|
||||
import de.fiereu.openmmo.common.enums.MovementType
|
||||
import de.fiereu.openmmo.common.enums.Weather
|
||||
import de.fiereu.openmmo.maps.BgEventDef
|
||||
import de.fiereu.openmmo.maps.MapCoordScript
|
||||
import de.fiereu.openmmo.maps.MapDef
|
||||
import de.fiereu.openmmo.maps.MapFrameScript
|
||||
import de.fiereu.openmmo.maps.NpcDef
|
||||
@@ -25,9 +26,9 @@ import de.fiereu.openmmo.net.game.packets.MapData
|
||||
|
||||
internal val ${objectName}: MapDef =
|
||||
MapDef(
|
||||
regionId = ${map.getRegion()},
|
||||
bankId = ${map.getBank()},
|
||||
mapId = ${map.getIndex()},
|
||||
regionId = ${map.getRegion()}.toByte(),
|
||||
bankId = ${map.getBank()}.toByte(),
|
||||
mapId = ${map.getIndex()}.toByte(),
|
||||
width = ${map.getWidth()},
|
||||
height = ${map.getHeight()},
|
||||
paletteIdx1 = ${map.getPaletteIdx1()},
|
||||
@@ -48,4 +49,5 @@ internal val ${objectName}: MapDef =
|
||||
bgEvents = ${RenderUtil.INSTANCE.bgEvents(map.getBgEvents())},
|
||||
onTransitionScript = "${map.getOnTransitionScript()}",
|
||||
onFrameScripts = ${RenderUtil.INSTANCE.frameScripts(map.getOnFrameScripts())},
|
||||
coordScripts = ${RenderUtil.INSTANCE.coordScripts(map.getCoordScripts())},
|
||||
)
|
||||
@@ -1,9 +1,14 @@
|
||||
@import java.util.List
|
||||
@import de.fiereu.openmmo.codegen.story.StoryConstant
|
||||
|
||||
@param String pkg
|
||||
@param String objectName
|
||||
@param String namespace
|
||||
@param List<String> names
|
||||
@param List<StoryConstant> constants
|
||||
@param List<List<StoryConstant>> idChunks
|
||||
@param List<StoryConstant> initialFlags
|
||||
@param List<StoryConstant> maleIntroFlags
|
||||
@param List<StoryConstant> femaleIntroFlags
|
||||
package ${pkg}
|
||||
|
||||
/**
|
||||
@@ -11,7 +16,52 @@ package ${pkg}
|
||||
* to ScriptContext (setFlag/isFlagSet, setVar/getVar). Generated, do not edit by hand.
|
||||
*/
|
||||
object ${objectName} {
|
||||
@for(String name : names)
|
||||
const val ${name} = "${namespace}/${name}"
|
||||
@for(StoryConstant constant : constants)
|
||||
const val ${constant.getName()} = "${namespace}/${constant.getName()}"
|
||||
@endfor
|
||||
|
||||
@if(!initialFlags.isEmpty())
|
||||
/** Flags set by the source game's new-game map reset. */
|
||||
val initiallySet: Set<String> =
|
||||
setOf(
|
||||
@for(StoryConstant constant : initialFlags)
|
||||
${constant.getName()},
|
||||
@endfor
|
||||
)
|
||||
|
||||
/** Additional flags established in the moving truck for the male player path. */
|
||||
val maleIntro: Set<String> =
|
||||
setOf(
|
||||
@for(StoryConstant constant : maleIntroFlags)
|
||||
${constant.getName()},
|
||||
@endfor
|
||||
)
|
||||
|
||||
/** Additional flags established in the moving truck for the female player path. */
|
||||
val femaleIntro: Set<String> =
|
||||
setOf(
|
||||
@for(StoryConstant constant : femaleIntroFlags)
|
||||
${constant.getName()},
|
||||
@endfor
|
||||
)
|
||||
|
||||
@endif
|
||||
/** Numeric id assigned by the source game's constants header. */
|
||||
fun numericId(key: String): Int? {
|
||||
@for(int index = 0; index < idChunks.size(); index++)
|
||||
numericId${index}(key)?.let { return it }
|
||||
@endfor
|
||||
return null
|
||||
}
|
||||
|
||||
@for(int index = 0; index < idChunks.size(); index++)
|
||||
private fun numericId${index}(key: String): Int? =
|
||||
when (key) {
|
||||
@for(StoryConstant constant : idChunks.get(index))
|
||||
${constant.getName()} -> ${constant.getNumericId()}
|
||||
@endfor
|
||||
else -> null
|
||||
}
|
||||
|
||||
@endfor
|
||||
}
|
||||
@@ -1,7 +1,5 @@
|
||||
package de.fiereu.openmmo.codegen.maps
|
||||
|
||||
internal const val BANK_GROUP_OFFSET = 50
|
||||
|
||||
internal val COMMON_DIR_MAP =
|
||||
mapOf(
|
||||
"down" to "Direction.DOWN",
|
||||
|
||||
@@ -4,6 +4,9 @@ object HoennConstants :
|
||||
RegionConstants(
|
||||
name = "hoenn",
|
||||
regionId = 1,
|
||||
// Emerald uses offset map and tileset namespaces.
|
||||
gbaBankOffset = 50,
|
||||
gbaPaletteOffset = 100,
|
||||
defaultVisibleNpcs =
|
||||
mapOf(
|
||||
"LittlerootTown_MaysHouse_1F" to listOf(0),
|
||||
|
||||
@@ -88,6 +88,10 @@ private constructor(
|
||||
when (name) {
|
||||
"MB_TALL_GRASS" -> TileBehavior.TALL_GRASS
|
||||
"MB_LONG_GRASS" -> TileBehavior.LONG_GRASS
|
||||
"MB_JUMP_EAST" -> TileBehavior.JUMP_EAST
|
||||
"MB_JUMP_WEST" -> TileBehavior.JUMP_WEST
|
||||
"MB_JUMP_NORTH" -> TileBehavior.JUMP_NORTH
|
||||
"MB_JUMP_SOUTH" -> TileBehavior.JUMP_SOUTH
|
||||
else -> null
|
||||
}
|
||||
|
||||
|
||||
@@ -30,6 +30,8 @@ data class ParsedMap(
|
||||
val onTransitionScript: String,
|
||||
// The map's ON_FRAME table: run the script once its var equals the value, on map entry.
|
||||
val onFrameScripts: List<ParsedFrameScript>,
|
||||
// Tile triggers from map.json coord_events.
|
||||
val coordScripts: List<ParsedCoordScript>,
|
||||
)
|
||||
|
||||
data class ParsedFrameScript(
|
||||
@@ -38,6 +40,15 @@ data class ParsedFrameScript(
|
||||
val script: String,
|
||||
)
|
||||
|
||||
data class ParsedCoordScript(
|
||||
val x: Int,
|
||||
val y: Int,
|
||||
val elevation: Int,
|
||||
val varKey: String,
|
||||
val value: Int,
|
||||
val script: String,
|
||||
)
|
||||
|
||||
data class ParsedConnection(
|
||||
val direction: String,
|
||||
val offset: Int,
|
||||
|
||||
@@ -168,7 +168,7 @@ class PretGbaParser(
|
||||
groupName = groupName,
|
||||
mapId = mapJson["id"]?.jsonPrimitive?.contentOrNull ?: mapDirName,
|
||||
region = region.regionId,
|
||||
bank = groupIndex + BANK_GROUP_OFFSET,
|
||||
bank = wireBank(groupIndex),
|
||||
index = mapIndex,
|
||||
width = layout["width"]?.jsonPrimitive?.intOrNull ?: 20,
|
||||
height = layout["height"]?.jsonPrimitive?.intOrNull ?: 15,
|
||||
@@ -194,6 +194,7 @@ class PretGbaParser(
|
||||
bgEvents = parseBgEvents(mapJson),
|
||||
onTransitionScript = parseOnTransitionScript(mapDirName),
|
||||
onFrameScripts = parseOnFrameScripts(mapDirName),
|
||||
coordScripts = parseCoordScripts(mapJson),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -217,7 +218,7 @@ class PretGbaParser(
|
||||
ParsedConnection(
|
||||
direction = dir,
|
||||
offset = obj["offset"]?.jsonPrimitive?.intOrNull ?: 0,
|
||||
targetBank = addr.groupIndex + BANK_GROUP_OFFSET,
|
||||
targetBank = wireBank(addr.groupIndex),
|
||||
targetMap = addr.mapIndex,
|
||||
)
|
||||
} ?: emptyList()
|
||||
@@ -257,7 +258,7 @@ class PretGbaParser(
|
||||
y = y,
|
||||
elevation = (srcElevation - 1).coerceAtLeast(0),
|
||||
targetRegion = region.regionId,
|
||||
targetBank = destAddr.groupIndex + BANK_GROUP_OFFSET,
|
||||
targetBank = wireBank(destAddr.groupIndex),
|
||||
targetMap = destAddr.mapIndex,
|
||||
targetX = target?.get("x")?.jsonPrimitive?.intOrNull ?: x,
|
||||
targetY = target?.get("y")?.jsonPrimitive?.intOrNull ?: y,
|
||||
@@ -338,6 +339,25 @@ class PretGbaParser(
|
||||
)
|
||||
} ?: emptyList()
|
||||
|
||||
/** Scripts fired on map trigger coordinates. */
|
||||
private fun parseCoordScripts(mapJson: JsonObject): List<ParsedCoordScript> =
|
||||
mapJson["coord_events"]?.jsonArrayOrNull()?.mapNotNull { event ->
|
||||
val obj = event.jsonObject
|
||||
if (obj["type"]?.jsonPrimitive?.contentOrNull != "trigger") return@mapNotNull null
|
||||
val varName = obj["var"]?.jsonPrimitive?.contentOrNull ?: return@mapNotNull null
|
||||
val value =
|
||||
obj["var_value"]?.jsonPrimitive?.contentOrNull?.toIntOrNull() ?: return@mapNotNull null
|
||||
val script = obj["script"]?.jsonPrimitive?.contentOrNull ?: return@mapNotNull null
|
||||
ParsedCoordScript(
|
||||
x = obj["x"]?.jsonPrimitive?.intOrNull ?: 0,
|
||||
y = obj["y"]?.jsonPrimitive?.intOrNull ?: 0,
|
||||
elevation = obj["elevation"]?.jsonPrimitive?.intOrNull ?: 0,
|
||||
varKey = "${region.name}/$varName",
|
||||
value = value,
|
||||
script = script,
|
||||
)
|
||||
} ?: emptyList()
|
||||
|
||||
private fun parseBorderTiles(layout: JsonObject): List<Int> =
|
||||
layout["border_filepath"]?.jsonPrimitive?.contentOrNull?.let {
|
||||
readBorderTiles(File(rootDir, it))
|
||||
@@ -435,11 +455,11 @@ class PretGbaParser(
|
||||
val file = File(rootDir, "src/data/tilesets/headers.h")
|
||||
if (!file.exists()) return emptyMap()
|
||||
val pattern = Regex("""^const struct Tileset\s+(gTileset_\w+)\s*=""")
|
||||
var index = 0
|
||||
var index = region.gbaPaletteOffset
|
||||
val out = mutableMapOf<String, Int>()
|
||||
file.forEachLine { line ->
|
||||
val m = pattern.find(line.trim()) ?: return@forEachLine
|
||||
out[m.groupValues[1]] = 100 + index
|
||||
out[m.groupValues[1]] = index
|
||||
index++
|
||||
}
|
||||
return out
|
||||
@@ -454,5 +474,7 @@ class PretGbaParser(
|
||||
return out
|
||||
}
|
||||
|
||||
private fun wireBank(groupIndex: Int): Int = groupIndex + region.gbaBankOffset
|
||||
|
||||
private fun JsonElement.jsonArrayOrNull() = (this as? JsonArray)
|
||||
}
|
||||
@@ -3,6 +3,10 @@ package de.fiereu.openmmo.codegen.maps
|
||||
open class RegionConstants(
|
||||
val name: String,
|
||||
val regionId: Int,
|
||||
/** Client map-group offset. */
|
||||
val gbaBankOffset: Int = 0,
|
||||
/** Client tileset offset. */
|
||||
val gbaPaletteOffset: Int = 0,
|
||||
val defaultVisibleNpcs: Map<String, List<Int>> = emptyMap(),
|
||||
val dirMap: Map<String, String> = COMMON_DIR_MAP,
|
||||
val weatherMap: Map<String, String> = COMMON_WEATHER_MAP,
|
||||
|
||||
@@ -29,8 +29,8 @@ object RenderUtil {
|
||||
if (warps.isEmpty()) return EMPTY_LIST
|
||||
return warps.joinToString(LIST_SEP, LIST_OPEN, LIST_CLOSE) {
|
||||
"WarpTile(x = ${it.x}, y = ${it.y}, elevation = ${it.elevation}," +
|
||||
" targetRegionId = ${it.targetRegion}, targetBankId = ${it.targetBank}," +
|
||||
" targetMapId = ${it.targetMap}," +
|
||||
" targetRegionId = ${it.targetRegion}.toByte(), targetBankId = ${it.targetBank}.toByte()," +
|
||||
" targetMapId = ${it.targetMap}.toByte()," +
|
||||
" targetX = ${it.targetX}, targetY = ${it.targetY}, targetElevation = ${it.targetElevation}," +
|
||||
" dynamic = ${it.dynamic})"
|
||||
}
|
||||
@@ -56,6 +56,15 @@ object RenderUtil {
|
||||
}
|
||||
}
|
||||
|
||||
fun coordScripts(scripts: List<ParsedCoordScript>): String {
|
||||
if (scripts.isEmpty()) return EMPTY_LIST
|
||||
return scripts.joinToString(LIST_SEP, LIST_OPEN, LIST_CLOSE) {
|
||||
"MapCoordScript(x = ${it.x}, y = ${it.y}, elevation = ${it.elevation}," +
|
||||
" varKey = ${escapeString(it.varKey)}, value = ${it.value}," +
|
||||
" script = ${escapeString(it.script)})"
|
||||
}
|
||||
}
|
||||
|
||||
fun bgEvents(events: List<ParsedBgEvent>): String {
|
||||
if (events.isEmpty()) return EMPTY_LIST
|
||||
return events.joinToString(LIST_SEP, LIST_OPEN, LIST_CLOSE) {
|
||||
|
||||
@@ -2,22 +2,311 @@ package de.fiereu.openmmo.codegen.story
|
||||
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Pulls the flag and var names out of a GBA decomp. Only the names matter here, the numeric values
|
||||
* are the client's concern and are not needed to key the game agnostic story store. The FLAG_/VAR_
|
||||
* prefix match skips the range markers like TEMP_FLAGS_START and FLAGS_COUNT on its own.
|
||||
*/
|
||||
data class StoryConstant(val name: String, val numericId: Int)
|
||||
|
||||
/** Reads GBA ids from pret headers. */
|
||||
object FlagVarParser {
|
||||
private data class Macro(
|
||||
val parameters: List<String>?,
|
||||
val expression: String,
|
||||
val numericHint: Int?,
|
||||
)
|
||||
|
||||
fun flags(decompDir: File): List<String> =
|
||||
names(File(decompDir, "include/constants/flags.h"), "FLAG_")
|
||||
fun flags(decompDir: File): List<StoryConstant> =
|
||||
constants(decompDir, "include/constants/flags.h", "FLAG_")
|
||||
|
||||
fun vars(decompDir: File): List<String> =
|
||||
names(File(decompDir, "include/constants/vars.h"), "VAR_")
|
||||
fun vars(decompDir: File): List<StoryConstant> =
|
||||
constants(decompDir, "include/constants/vars.h", "VAR_")
|
||||
|
||||
private fun names(file: File, prefix: String): List<String> {
|
||||
require(file.exists()) { "Missing ${file.path}" }
|
||||
val re = Regex("""^#define\s+($prefix\w+)\b""")
|
||||
return file.readLines().mapNotNull { re.find(it.trim())?.groupValues?.get(1) }.distinct()
|
||||
/** Emerald new-game reset flags. */
|
||||
fun initialFlags(decompDir: File): List<String> =
|
||||
scriptFlags(
|
||||
decompDir,
|
||||
"data/scripts/new_game.inc",
|
||||
"EventScript_ResetAllMapFlags",
|
||||
)
|
||||
|
||||
/** Gender-specific flags normally established by InsideOfTruck's intro script. */
|
||||
fun maleIntroFlags(decompDir: File): List<String> =
|
||||
scriptFlags(
|
||||
decompDir,
|
||||
"data/maps/InsideOfTruck/scripts.inc",
|
||||
"InsideOfTruck_EventScript_SetIntroFlagsMale",
|
||||
)
|
||||
|
||||
fun femaleIntroFlags(decompDir: File): List<String> =
|
||||
scriptFlags(
|
||||
decompDir,
|
||||
"data/maps/InsideOfTruck/scripts.inc",
|
||||
"InsideOfTruck_EventScript_SetIntroFlagsFemale",
|
||||
)
|
||||
|
||||
private fun scriptFlags(decompDir: File, relativePath: String, label: String): List<String> {
|
||||
val file = File(decompDir, relativePath)
|
||||
if (!file.exists()) return emptyList()
|
||||
val result = mutableListOf<String>()
|
||||
var inBlock = false
|
||||
for (rawLine in file.readLines()) {
|
||||
val line = rawLine.substringBefore('@').trim()
|
||||
if (!inBlock) {
|
||||
if (line == "$label::") inBlock = true
|
||||
continue
|
||||
}
|
||||
if (line.endsWith("::")) break
|
||||
Regex("""^setflag\s+(FLAG_[A-Za-z0-9_]+)\b""")
|
||||
.find(line)
|
||||
?.groupValues
|
||||
?.get(1)
|
||||
?.let(result::add)
|
||||
if (line == "end" || line == "return") break
|
||||
}
|
||||
return result.distinct()
|
||||
}
|
||||
|
||||
private fun constants(
|
||||
decompDir: File,
|
||||
relativePath: String,
|
||||
prefix: String,
|
||||
): List<StoryConstant> {
|
||||
val target = File(decompDir, relativePath)
|
||||
require(target.exists()) { "Missing ${target.path}" }
|
||||
|
||||
// Load sibling constants before the target header.
|
||||
val targetConstants = parseConstants(target)
|
||||
val macros = linkedMapOf<String, Macro>()
|
||||
targetConstants.forEach { (name, macro) -> macros[name] = macro }
|
||||
File(decompDir, "include/constants")
|
||||
.walkTopDown()
|
||||
.filter { it.isFile && it.extension == "h" && it != target }
|
||||
.sortedBy(File::getPath)
|
||||
.forEach { file ->
|
||||
parseConstants(file).forEach { (name, macro) -> macros.putIfAbsent(name, macro) }
|
||||
}
|
||||
|
||||
val wanted =
|
||||
targetConstants
|
||||
.filter { (name, macro) -> name.startsWith(prefix) && macro.parameters == null }
|
||||
.keys
|
||||
val evaluator = MacroEvaluator(macros)
|
||||
val unresolved = mutableListOf<String>()
|
||||
val result =
|
||||
wanted.mapNotNull { name ->
|
||||
evaluator.resolve(name)?.let { StoryConstant(name, it) }
|
||||
?: run {
|
||||
unresolved += name
|
||||
null
|
||||
}
|
||||
}
|
||||
check(unresolved.isEmpty()) {
|
||||
"Could not resolve ${unresolved.size} $prefix constants in ${target.path}: " +
|
||||
unresolved.take(12).joinToString()
|
||||
}
|
||||
return result.distinctBy(StoryConstant::name)
|
||||
}
|
||||
|
||||
private fun parseMacros(file: File): LinkedHashMap<String, Macro> {
|
||||
val result = linkedMapOf<String, Macro>()
|
||||
val define = Regex("""^#define\s+([A-Za-z_]\w*)(?:\(([^)]*)\))?\s+(.+)$""")
|
||||
val blockComment = Regex("""/\*.*?\*/""")
|
||||
for (line in file.readLines()) {
|
||||
val match = define.find(line.trim()) ?: continue
|
||||
val name = match.groupValues[1]
|
||||
val parameters =
|
||||
match.groupValues[2].takeIf(String::isNotEmpty)?.split(',')?.map(String::trim)
|
||||
val raw = match.groupValues[3]
|
||||
val comment = raw.substringAfter("//", "")
|
||||
val expression = raw.substringBefore("//").replace(blockComment, "").trim()
|
||||
if (expression.isEmpty()) continue
|
||||
val hint = Regex("""(?:0x[0-9A-Fa-f]+|\b\d+\b)""").find(comment)?.value?.let(::parseNumber)
|
||||
result[name] = Macro(parameters, expression, hint)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
private fun parseConstants(file: File): LinkedHashMap<String, Macro> =
|
||||
linkedMapOf<String, Macro>().apply {
|
||||
putAll(parseMacros(file))
|
||||
putAll(parseEnumConstants(file))
|
||||
}
|
||||
|
||||
/** Treat C enum members as ordinary integer macros, including implicit incrementing values. */
|
||||
private fun parseEnumConstants(file: File): LinkedHashMap<String, Macro> {
|
||||
val result = linkedMapOf<String, Macro>()
|
||||
var inEnum = false
|
||||
var previous: String? = null
|
||||
for (rawLine in file.readLines()) {
|
||||
val line = rawLine.substringBefore("//").replace(Regex("""/\*.*?\*/"""), "").trim()
|
||||
if (!inEnum) {
|
||||
if (line.startsWith("enum") && line.contains('{')) {
|
||||
inEnum = true
|
||||
previous = null
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (line.startsWith("}")) {
|
||||
inEnum = false
|
||||
previous = null
|
||||
continue
|
||||
}
|
||||
val member = line.removeSuffix(",").trim()
|
||||
val match = Regex("""^([A-Za-z_]\w*)(?:\s*=\s*(.+))?$""").matchEntire(member) ?: continue
|
||||
val name = match.groupValues[1]
|
||||
val explicit = match.groupValues[2].takeIf(String::isNotEmpty)
|
||||
val expression = explicit ?: previous?.let { "($it + 1)" } ?: "0"
|
||||
result[name] = Macro(parameters = null, expression = expression, numericHint = null)
|
||||
previous = name
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
private class MacroEvaluator(private val macros: Map<String, Macro>) {
|
||||
private val memo = mutableMapOf<String, Int>()
|
||||
private val resolving = mutableSetOf<String>()
|
||||
|
||||
fun resolve(name: String): Int? {
|
||||
memo[name]?.let {
|
||||
return it
|
||||
}
|
||||
if (!resolving.add(name)) return null
|
||||
val macro = macros[name]
|
||||
val value =
|
||||
if (macro == null || macro.parameters != null) null
|
||||
else ExpressionParser(macro.expression, this, emptyMap()).parse() ?: macro.numericHint
|
||||
resolving.remove(name)
|
||||
if (value != null) memo[name] = value
|
||||
return value
|
||||
}
|
||||
|
||||
fun resolve(name: String, arguments: List<Int>, locals: Map<String, Int>): Int? {
|
||||
locals[name]?.let {
|
||||
return it
|
||||
}
|
||||
val macro = macros[name] ?: return null
|
||||
val parameters = macro.parameters ?: return if (arguments.isEmpty()) resolve(name) else null
|
||||
if (parameters.size != arguments.size) return null
|
||||
val callLocals = locals + parameters.zip(arguments)
|
||||
return ExpressionParser(macro.expression, this, callLocals).parse() ?: macro.numericHint
|
||||
}
|
||||
}
|
||||
|
||||
private class ExpressionParser(
|
||||
expression: String,
|
||||
private val evaluator: MacroEvaluator,
|
||||
private val locals: Map<String, Int>,
|
||||
) {
|
||||
private val tokens =
|
||||
Regex("""0x[0-9A-Fa-f]+|\d+|[A-Za-z_]\w*|<<|>>|[(),+\-*/%|&~]""")
|
||||
.findAll(expression)
|
||||
.map { it.value }
|
||||
.toList()
|
||||
private val compactExpression = expression.filterNot(Char::isWhitespace)
|
||||
private var position = 0
|
||||
|
||||
fun parse(): Int? {
|
||||
if (tokens.joinToString("") != compactExpression) return null
|
||||
val value = parseBitwiseOr() ?: return null
|
||||
return value.takeIf { position == tokens.size }
|
||||
}
|
||||
|
||||
private fun parseBitwiseOr(): Int? = binary(::parseBitwiseAnd, "|") { a, b -> a or b }
|
||||
|
||||
private fun parseBitwiseAnd(): Int? = binary(::parseShift, "&") { a, b -> a and b }
|
||||
|
||||
private fun parseShift(): Int? {
|
||||
var value = parseAdditive() ?: return null
|
||||
while (peek() == "<<" || peek() == ">>") {
|
||||
val operator = take()
|
||||
val right = parseAdditive() ?: return null
|
||||
value = if (operator == "<<") value shl right else value shr right
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
private fun parseAdditive(): Int? {
|
||||
var value = parseMultiplicative() ?: return null
|
||||
while (peek() == "+" || peek() == "-") {
|
||||
val operator = take()
|
||||
val right = parseMultiplicative() ?: return null
|
||||
value = if (operator == "+") value + right else value - right
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
private fun parseMultiplicative(): Int? {
|
||||
var value = parseUnary() ?: return null
|
||||
while (peek() == "*" || peek() == "/" || peek() == "%") {
|
||||
val operator = take()
|
||||
val right = parseUnary() ?: return null
|
||||
if ((operator == "/" || operator == "%") && right == 0) return null
|
||||
value =
|
||||
when (operator) {
|
||||
"*" -> value * right
|
||||
"/" -> value / right
|
||||
else -> value % right
|
||||
}
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
private fun parseUnary(): Int? =
|
||||
when (peek()) {
|
||||
"+" -> {
|
||||
take()
|
||||
parseUnary()
|
||||
}
|
||||
"-" -> {
|
||||
take()
|
||||
parseUnary()?.let { -it }
|
||||
}
|
||||
"~" -> {
|
||||
take()
|
||||
parseUnary()?.inv()
|
||||
}
|
||||
else -> parsePrimary()
|
||||
}
|
||||
|
||||
private fun parsePrimary(): Int? {
|
||||
val token = take() ?: return null
|
||||
if (token == "(") {
|
||||
val value = parseBitwiseOr() ?: return null
|
||||
if (take() != ")") return null
|
||||
return value
|
||||
}
|
||||
if (token.firstOrNull()?.isDigit() == true) return parseNumber(token)
|
||||
if (token.firstOrNull()?.isLetter() != true && token.firstOrNull() != '_') return null
|
||||
if (peek() != "(") return evaluator.resolve(token, emptyList(), locals)
|
||||
|
||||
take()
|
||||
val arguments = mutableListOf<Int>()
|
||||
if (peek() != ")") {
|
||||
while (true) {
|
||||
arguments += parseBitwiseOr() ?: return null
|
||||
if (peek() != ",") break
|
||||
take()
|
||||
}
|
||||
}
|
||||
if (take() != ")") return null
|
||||
return evaluator.resolve(token, arguments, locals)
|
||||
}
|
||||
|
||||
private fun binary(
|
||||
operand: () -> Int?,
|
||||
operator: String,
|
||||
combine: (Int, Int) -> Int,
|
||||
): Int? {
|
||||
var value = operand() ?: return null
|
||||
while (peek() == operator) {
|
||||
take()
|
||||
value = combine(value, operand() ?: return null)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
private fun peek(): String? = tokens.getOrNull(position)
|
||||
|
||||
private fun take(): String? = tokens.getOrNull(position++)
|
||||
}
|
||||
|
||||
private fun parseNumber(value: String): Int =
|
||||
if (value.startsWith("0x", ignoreCase = true)) value.drop(2).toInt(16) else value.toInt()
|
||||
}
|
||||
@@ -18,6 +18,13 @@ fun main(args: Array<String>) {
|
||||
val flags = FlagVarParser.flags(decompDir)
|
||||
val vars = FlagVarParser.vars(decompDir)
|
||||
println("[story] $region: parsed ${flags.size} flags, ${vars.size} vars from $decompDir")
|
||||
StoryConstantsRenderer(region, templatesDir, outputDir, classCacheDir).render(flags, vars)
|
||||
StoryConstantsRenderer(region, templatesDir, outputDir, classCacheDir)
|
||||
.render(
|
||||
flags,
|
||||
vars,
|
||||
FlagVarParser.initialFlags(decompDir),
|
||||
FlagVarParser.maleIntroFlags(decompDir),
|
||||
FlagVarParser.femaleIntroFlags(decompDir),
|
||||
)
|
||||
}
|
||||
}
|
||||
+27
-4
@@ -22,7 +22,13 @@ class StoryConstantsRenderer(
|
||||
private val basePackage = "de.fiereu.openmmo.story.generated.$region"
|
||||
private val objectPrefix = region.replaceFirstChar { it.uppercase() }
|
||||
|
||||
fun render(flags: List<String>, vars: List<String>) {
|
||||
fun render(
|
||||
flags: List<StoryConstant>,
|
||||
vars: List<StoryConstant>,
|
||||
initialFlags: List<String>,
|
||||
maleIntroFlags: List<String>,
|
||||
femaleIntroFlags: List<String>,
|
||||
) {
|
||||
classCacheDir.mkdirs()
|
||||
val engine =
|
||||
TemplateEngine.create(
|
||||
@@ -35,7 +41,16 @@ class StoryConstantsRenderer(
|
||||
if (packageRoot.exists()) packageRoot.deleteRecursively()
|
||||
packageRoot.mkdirs()
|
||||
|
||||
write(engine, packageRoot, "${objectPrefix}Flags", flags)
|
||||
val knownFlags = flags.associateBy(StoryConstant::name)
|
||||
write(
|
||||
engine,
|
||||
packageRoot,
|
||||
"${objectPrefix}Flags",
|
||||
flags,
|
||||
initialFlags.mapNotNull(knownFlags::get),
|
||||
maleIntroFlags.mapNotNull(knownFlags::get),
|
||||
femaleIntroFlags.mapNotNull(knownFlags::get),
|
||||
)
|
||||
write(engine, packageRoot, "${objectPrefix}Vars", vars)
|
||||
}
|
||||
|
||||
@@ -43,7 +58,10 @@ class StoryConstantsRenderer(
|
||||
engine: TemplateEngine,
|
||||
packageRoot: File,
|
||||
objectName: String,
|
||||
names: List<String>,
|
||||
constants: List<StoryConstant>,
|
||||
initialFlags: List<StoryConstant> = emptyList(),
|
||||
maleIntroFlags: List<StoryConstant> = emptyList(),
|
||||
femaleIntroFlags: List<StoryConstant> = emptyList(),
|
||||
) {
|
||||
FileOutput(File(packageRoot, "$objectName.kt").toPath()).use { out ->
|
||||
engine.render(
|
||||
@@ -52,7 +70,12 @@ class StoryConstantsRenderer(
|
||||
"pkg" to basePackage,
|
||||
"objectName" to objectName,
|
||||
"namespace" to namespace,
|
||||
"names" to names,
|
||||
"constants" to constants,
|
||||
// Keep lookup methods comfortably below the JVM's per-method bytecode limit.
|
||||
"idChunks" to constants.chunked(128),
|
||||
"initialFlags" to initialFlags,
|
||||
"maleIntroFlags" to maleIntroFlags,
|
||||
"femaleIntroFlags" to femaleIntroFlags,
|
||||
),
|
||||
out,
|
||||
)
|
||||
|
||||
@@ -36,6 +36,8 @@ class MapDef(
|
||||
val onTransitionScript: String = "",
|
||||
/** Conditional entry scripts: run [MapFrameScript.script] when its var equals its value. */
|
||||
val onFrameScripts: List<MapFrameScript> = emptyList(),
|
||||
/** Conditional tile scripts checked after the player completes a step. */
|
||||
val coordScripts: List<MapCoordScript> = emptyList(),
|
||||
private val blockData: String = "",
|
||||
private val behaviorData: String = "",
|
||||
) {
|
||||
@@ -57,6 +59,16 @@ data class MapFrameScript(
|
||||
val script: String,
|
||||
)
|
||||
|
||||
/** One map coordinate trigger, corresponding to a decomp map.json `coord_events` entry. */
|
||||
data class MapCoordScript(
|
||||
val x: Int,
|
||||
val y: Int,
|
||||
val elevation: Int,
|
||||
val varKey: String,
|
||||
val value: Int,
|
||||
val script: String,
|
||||
)
|
||||
|
||||
private fun decodeBlockData(blockData: String, behaviorData: String): List<Tile2D> {
|
||||
if (blockData.isEmpty()) return emptyList()
|
||||
val bytes = Base64.getDecoder().decode(blockData)
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
package de.fiereu.openmmo.codegen.story
|
||||
|
||||
import io.kotest.core.spec.style.FunSpec
|
||||
import io.kotest.matchers.shouldBe
|
||||
|
||||
class FlagVarParserTest :
|
||||
FunSpec({
|
||||
test("resolves literals, aliases, expressions, hints, and function macros") {
|
||||
val decomp = kotlin.io.path.createTempDirectory("story-constants").toFile()
|
||||
val constants = decomp.resolve("include/constants").also { it.mkdirs() }
|
||||
constants.resolve("support.h").writeText("#define EXTERNAL_COUNT 0x20\n")
|
||||
constants
|
||||
.resolve("flags.h")
|
||||
.writeText(
|
||||
"""
|
||||
#define FLAGS_START 0x100
|
||||
#define FLAGS_END (FLAGS_START + EXTERNAL_COUNT - 1) // 0x11F
|
||||
#define FLAG_FACTORY(index) (FLAGS_END + 1 + (index * 2))
|
||||
#define FLAG_LITERAL 0x42
|
||||
#define FLAG_ALIAS FLAG_LITERAL
|
||||
#define FLAG_EXPRESSION (FLAGS_START + 0x0F)
|
||||
#define FLAG_HINT (UNKNOWN_VALUE + 1) // FLAG_0x234
|
||||
#define FLAG_FUNCTION FLAG_FACTORY(3)
|
||||
"""
|
||||
.trimIndent())
|
||||
constants
|
||||
.resolve("vars.h")
|
||||
.writeText(
|
||||
"""
|
||||
#define VARS_START 0x4000
|
||||
#define VAR_FIRST (VARS_START + 1)
|
||||
"""
|
||||
.trimIndent())
|
||||
|
||||
FlagVarParser.flags(decomp) shouldBe
|
||||
listOf(
|
||||
StoryConstant("FLAG_LITERAL", 0x42),
|
||||
StoryConstant("FLAG_ALIAS", 0x42),
|
||||
StoryConstant("FLAG_EXPRESSION", 0x10F),
|
||||
StoryConstant("FLAG_HINT", 0x234),
|
||||
StoryConstant("FLAG_FUNCTION", 0x126),
|
||||
)
|
||||
FlagVarParser.vars(decomp) shouldBe listOf(StoryConstant("VAR_FIRST", 0x4001))
|
||||
}
|
||||
|
||||
test("extracts initial and gender-specific flags from script blocks") {
|
||||
val decomp = kotlin.io.path.createTempDirectory("story-script-flags").toFile()
|
||||
decomp.resolve("data/scripts").mkdirs()
|
||||
decomp.resolve("data/maps/InsideOfTruck").mkdirs()
|
||||
decomp
|
||||
.resolve("data/scripts/new_game.inc")
|
||||
.writeText(
|
||||
"""
|
||||
EventScript_ResetAllMapFlags::
|
||||
setflag FLAG_INITIAL
|
||||
setflag FLAG_INITIAL
|
||||
end
|
||||
AnotherScript::
|
||||
setflag FLAG_NOT_INCLUDED
|
||||
"""
|
||||
.trimIndent())
|
||||
decomp
|
||||
.resolve("data/maps/InsideOfTruck/scripts.inc")
|
||||
.writeText(
|
||||
"""
|
||||
InsideOfTruck_EventScript_SetIntroFlagsMale::
|
||||
setflag FLAG_MALE
|
||||
end
|
||||
InsideOfTruck_EventScript_SetIntroFlagsFemale::
|
||||
setflag FLAG_FEMALE
|
||||
end
|
||||
"""
|
||||
.trimIndent())
|
||||
|
||||
FlagVarParser.initialFlags(decomp) shouldBe listOf("FLAG_INITIAL")
|
||||
FlagVarParser.maleIntroFlags(decomp) shouldBe listOf("FLAG_MALE")
|
||||
FlagVarParser.femaleIntroFlags(decomp) shouldBe listOf("FLAG_FEMALE")
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,29 @@
|
||||
package de.fiereu.openmmo.maps
|
||||
|
||||
import de.fiereu.openmmo.common.enums.TileBehavior
|
||||
import io.kotest.core.spec.style.FunSpec
|
||||
import io.kotest.matchers.collections.shouldContainAll
|
||||
import io.kotest.matchers.shouldBe
|
||||
|
||||
class HoennMapBehaviorTest :
|
||||
FunSpec({
|
||||
test("generated Hoenn maps retain the ledge behaviors used by Emerald") {
|
||||
val maps = MapManager()
|
||||
val behaviors = buildSet {
|
||||
for (bank in 50..83) {
|
||||
for (mapId in 0..255) {
|
||||
maps.getMap(1, bank, mapId)?.tiles?.forEach { add(it.behavior) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
behaviors shouldContainAll
|
||||
listOf(
|
||||
TileBehavior.JUMP_EAST,
|
||||
TileBehavior.JUMP_WEST,
|
||||
TileBehavior.JUMP_SOUTH,
|
||||
)
|
||||
|
||||
maps.getMap(1, 50, 26)!!.tiles.any { it.behavior == TileBehavior.JUMP_SOUTH } shouldBe true
|
||||
}
|
||||
})
|
||||
Reference in new issue
Block a user