docs: document the script system (#78)

* docs: document the script system

* chore: fix style
This commit is contained in:
Fiereu authored and GitHub committed 2026-08-02 15:42:30 +02:00
1 parent 4b49a13a8f
commit c3fd2d3f81
8 files changed
+537 -104

No files matched your search

+4
View File
@@ -9,3 +9,7 @@ Short explanations of the systems that make up OpenMMO.
seeded.
- [The InterestManager](interest-manager/): how packets reach the right
players instead of everyone online.
- [The script system](scripts/): how an npc, sign, or map entry turns into
running Kotlin, and why scripts are coroutines.
- [Story flags and vars](story-state/): how a character's story progression is
stored and where the key constants come from.
+161
View File
@@ -0,0 +1,161 @@
---
title: The script system
description: How an npc, sign, or map entry turns into running Kotlin, and why scripts are coroutines.
---
Almost everything the overworld does when a player presses A is a **script**: a
small piece of Kotlin keyed by a decomp script label. This page explains how a
button press finds that Kotlin, what runs it, and the rules that fall out of the
way it runs.
If you just want to write or fix one, read
[Writing overworld scripts](../../guides/writing-scripts/). This page is the
model behind it.
## The pieces
Everything lives in
`server.game/src/main/kotlin/de/fiereu/openmmo/server/game/script/`:
- `Script.kt`: a `fun interface` with one method, `suspend fun run(ctx: ScriptContext)`.
- `ScriptContext.kt`: everything a script is allowed to do to the player.
- `ScriptRegistry.kt`: decomp label -> `Script`.
- `ScriptRunner.kt`: launches a script and owns the dialog lock.
- `MovementStep.kt`: the small movement vocabulary cutscenes use.
- `generated/`: one file per map holding the script objects themselves.
The heavy lifting a script asks for is delegated to three services:
`DialogService` (boxes), `StoryService` (flags and vars, see
[Story flags and vars](../story-state/)), and `ScriptMovementService` (scripted
walking).
## From button press to Kotlin
```
player presses A
│
v
InteractionService finds the npc or bg event, reads its script label
│ looks the label up in
v
ScriptRegistry label -> Script (GeneratedScripts.byLabel)
│ hands it to
v
ScriptRunner claims the dialog, launches a coroutine
│ runs
v
Script.run(ctx) your code, talks to the player through ctx
```
### Labels come from the map data
A script is never found by guessing. `MapDef` carries the decomp label straight
through from the pret map json: `NpcDef.script` for an npc, `BgEventDef.script`
for a sign, `MapDef.onTransitionScript` and `MapFrameScript.script` for map
entry. `ScriptRegistry.forLabel` looks that string up and returns `null` when
nothing is wired, which is the normal case today. Nothing happens and the server
logs it:
```
NPC entityIdx=3 script=LittlerootTown_EventScript_Boy has no wired dialog
```
`GeneratedScripts.byLabel` is the one big map, built by `putAll`ing each map's
`...Scripts` map. It is emitted in chunks of 40 maps across `chunk0()`, `chunk1()`
and so on, so no single method ends up enormous.
## The three triggers
### An npc
`InteractionService.onEntityInteract` handles `EntityInteractPacket`. It resolves
the player's current map, walks `map.npcs` looking for the one whose entity id
matches the packet, and runs its script with that entity id. The script's
`ctx.entityId` is that npc, so `ctx.say` makes the box point at it.
### A sign or a piece of furniture
`InteractionService.onTileInteract` handles `TileInteractPacket`. There is no
entity, so the server computes the tile the player faces from their position and
`facingDirection`, then looks for a bg event on it. The bg event's own
`facingDir` has to agree: `BG_EVENT_PLAYER_FACING_ANY` always matches, the
`NORTH`/`SOUTH`/`WEST`/`EAST` variants only match a player facing that way.
Scripts triggered this way get `entityId = -1`.
### Entering a map
`MapScriptService.onMapEnter` runs on every entry, however the player got there:
login, a warp, or walking across a map connection. It builds a list of up to two
scripts and runs them in order:
1. `map.onTransitionScript`, unconditionally.
2. The **first** entry in `map.onFrameScripts` whose story var currently equals
its value, that is `storyService.getVar(charId, it.varKey) == it.value`.
Both go through `ScriptRunner.runAll` on one coroutine, so an on-transition
script and the cutscene it enables share a single dialog lock instead of racing.
The conditional `ON_WARP` table is not wired up yet.
## Why scripts are coroutines
A script that shows two boxes has to *wait* in the middle:
```kotlin
ctx.say(LittlerootTown.OurNewHomeLetsGoInside) // suspends here
ctx.say(LittlerootTown.SomethingElse)
```
Underneath, `DialogService.showAndWait` parks a `CompletableDeferred` in the
session attribute `PENDING_DIALOG`, sends the box, and awaits. The thing that
completes that deferred is the player's `DialogActionResponsePacket`, arriving
through the connection's normal packet handling.
So the wait can only finish if packet handling keeps running while the script is
parked. That is the whole reason `ScriptRunner` launches on a separate scope
(`SCRIPT_SCOPE` on the session, a `SupervisorJob` on `Dispatchers.Default`)
rather than running inside the packet handler. **If a script blocks or awaits a
packet directly, the reply it is waiting for never gets read and the connection
locks up.** Use `ctx.say`, `ctx.sign`, `ctx.moveNpc` and `ctx.moveSelf`, never a
raw await.
## One script at a time
`ScriptRunner` sets `state.inDialog = true` *before* launching the coroutine, and
every trigger checks `state.inDialog` and bails if it is already set. That
combination is what stops a player from mashing A and starting two scripts on top
of each other, or from walking into a map cutscene while an npc conversation is
open. `DialogService.close` in the runner's `finally` clears it again, so the
lock is released even when a script throws.
## How a script can end
`ScriptRunner` catches three things, deliberately differently:
| Outcome | What happens |
| --- | --- |
| `CancellationException` | Rethrown. Cancellation must not be swallowed. |
| `NotImplementedError` | Logged at info as "Script not ported yet". This is the `TODO("port ...")` stub firing, and it is expected, not a bug. |
| Any other `Exception` | Logged at error with the stack trace. |
In all three cases the `finally` closes the dialog, so a broken script leaves the
player able to move rather than stuck in a box.
## Scripts are per player
Nothing a script does is broadcast. `ScriptMovementService` sends its movement
packets to the acting player's session only, so a cutscene where an npc walks
across the room plays for the player who triggered it and is invisible to anyone
else standing on that map. That is the right model for story content, where two
players on the same map can legitimately be at different points in the story.
The one thing that does escape the session is story state: flags and vars are
written through to the character in the database. See
[Story flags and vars](../story-state/).
## Where the script objects come from
The files under `script/generated/` were bootstrapped once from the decomp by
`gradlew :codegen:generateScriptStubs` and are **committed source that you edit
by hand**. The task is deliberately not part of the build. Re-running it deletes
each region package and re-emits it, so it destroys every hand written port. See
[Porting a decomp script](../../guides/porting-scripts/) for the workflow.
@@ -0,0 +1,107 @@
---
title: Story flags and vars
description: How a character's story progression is stored, why the keys are opaque strings, and where the constants come from.
---
Story progression is two things: **flags**, which are booleans, and **vars**,
which are named integers. A flag records that something happened
(`FLAG_VISITED_LITTLEROOT_TOWN`), a var records where in a multi step sequence a
player is (`VAR_LITTLEROOT_INTRO_STATE`). Between them they are what makes an npc
say something different on the second visit.
## The api
Scripts touch story state through `ScriptContext`, which forwards to
`StoryService` (`server.game/.../services/StoryService.kt`) with the acting
player's character id filled in:
```kotlin
ctx.isFlagSet(HoennFlags.FLAG_ADVENTURE_STARTED) // Boolean
ctx.setFlag(HoennFlags.FLAG_VISITED_LITTLEROOT_TOWN)
ctx.clearFlag(HoennFlags.FLAG_SYS_POKEMON_GET)
ctx.getVar(HoennVars.VAR_LITTLEROOT_INTRO_STATE) // Int
ctx.setVar(HoennVars.VAR_LITTLEROOT_INTRO_STATE, 3)
```
Two defaults matter, and they are chosen to match how the decomp scripts already
think:
- A flag that was never set reads as **false**.
- A var that was never set reads as **0**.
So a fresh character needs no seeding: every flag is unset and every var is 0,
which is exactly the start-of-game state the decomp assumes. `setVar(key, 0)`
does not store a zero row, it removes the key, keeping the two representations of
"never set" identical.
## Why the keys are opaque strings
`StoryService` takes a `String` key and does nothing with it but use it as a map
key. It does not know what a flag *means*, does not know GBA flag numbering, and
does not import anything from the decomp side. The database schema
(`V2__create_story_state.sql`) is the same:
```sql
CREATE TABLE character_flags (
character_id BIGINT NOT NULL REFERENCES characters (id) ON DELETE CASCADE,
flag_key VARCHAR(128) NOT NULL,
PRIMARY KEY (character_id, flag_key)
);
```
A row in `character_flags` means the flag is set; no row means unset.
`character_vars` adds an `INT` value column.
That is deliberate. The GBA decomp is the content source *today*, but it is not
supposed to be the only one. Keeping the keys opaque means a hand authored
questline or a non GBA game can drive the same store through the same api without
the persistence layer learning anything about Pokémon Emerald. The decomp is an
adapter on top, not the model.
## Where the constants come from
You never type a raw key string. Each region gets a generated pair of constant
objects, `HoennFlags`/`HoennVars` and `KantoFlags`/`KantoVars`, in
`de.fiereu.openmmo.story.generated.<region>`.
They are produced by the `story` generator
(`codegen/.../codegen/story/`), which reads `include/constants/flags.h` and
`include/constants/vars.h` from each decomp and keeps only the names. The numeric
values are the client's business and are not needed to key the store. Unlike the
script stubs, this generator **is** wired into the build as `generateStory`, so
the constants regenerate on compile and are not committed.
Each constant's value is the name **namespaced by region**:
```kotlin
object HoennFlags {
const val FLAG_ADVENTURE_STARTED = "hoenn/FLAG_ADVENTURE_STARTED"
// ...
}
```
The namespace is what keeps Hoenn's and Kanto's overlapping flag names from
colliding in one character's store. This is also why you should always reference
the constant rather than writing the string: `"FLAG_ADVENTURE_STARTED"` and
`HoennFlags.FLAG_ADVENTURE_STARTED` are different keys, and the first one will
silently never match.
## Persistence
Reads and writes go to `CharacterStore`, the in-memory cache that fronts the
database. Every mutation marks the character dirty and the periodic flusher
writes it back after a debounce, so a script does not pay for a database round
trip mid-conversation.
Writes copy the collection instead of mutating in place, so the flusher never
snapshots a half-updated set. Setting a flag that is already set, or a var to the
value it already has, is a no-op and does not dirty the character.
## Reading story state outside a script
`MapScriptService` reads vars directly to pick which `ON_FRAME` script to run on
map entry, comparing `storyService.getVar(charId, it.varKey)` against each
entry's value. Any other service can do the same: inject `StoryService` and pass
the character id. `ScriptContext` is only a convenience wrapper for the common
case where the acting character is obvious.
+4 -2
View File
@@ -7,5 +7,7 @@ How-to guides for working on OpenMMO.
- [Writing a code generator](writing-generators/): how to add a new
build-time generator that turns pret decomp data into Kotlin game data.
- [Writing overworld scripts](writing-scripts/): how to fill in missing npc and
sign behaviour and tweak the dialog an existing script shows.
- [Writing overworld scripts](writing-scripts/): where the overworld scripts
live, what one looks like, and how to change the dialog an npc or sign shows.
- [Porting a decomp script](porting-scripts/): the decomp command reference,
which commands have an equivalent, and what to do about the ones that do not.
@@ -0,0 +1,181 @@
---
title: Porting a decomp script
description: How to turn a decomp script body into Kotlin, which commands have an equivalent, and what to do about the ones that do not.
---
Most overworld scripts are not ported yet. Of roughly 3650 generated script
objects, about 2500 are still `TODO("port ...")` stubs carrying their original
decomp body in a comment. This guide is the reference for turning one of those
bodies into Kotlin.
For the basics of editing a script file at all, read
[Writing overworld scripts](../writing-scripts/) first. For how the runtime
works, see [The script system](../../concepts/scripts/).
## The workflow
1. Find a stub. `grep -rn 'TODO("port' server.game/src/main/kotlin/.../script/generated/`
or just open the map you care about.
2. Read the decomp body in the KDoc above it. That comment is the source of
truth; you do not need the decomp checked out to port most scripts.
3. Translate it with the table below.
4. Delete the `TODO(...)`, keep the KDoc if anything is still missing, and say
what is missing.
5. Build and run it in the client.
Pick small scripts first. A `lock` / `faceplayer` / `msgbox` / `release` / `end`
body is one line of Kotlin; a body with `special`, `trainerbattle` or door
animations is not portable yet at all.
## Command reference
### Framing you can drop
These do not change what the player sees, because the runtime already handles the
equivalent. Ignore them:
`lock`, `lockall`, `faceplayer`, `release`, `releaseall`, `closemessage`,
`waitmessage`, `waitbuttonpress`, `end`, `return`.
The dialog lock is taken by `ScriptRunner` before your script starts and released
in its `finally`, which covers `lock`/`release`. `end` and `return` are just the
end of your function.
### Commands with a direct equivalent
| Decomp | Kotlin |
| --- | --- |
| `msgbox TEXT, MSGBOX_SIGN` | `ctx.sign(Map.Text)` |
| `msgbox TEXT, MSGBOX_DEFAULT` (and other types) | `ctx.say(Map.Text)` |
| `setflag FLAG_X` | `ctx.setFlag(HoennFlags.FLAG_X)` |
| `clearflag FLAG_X` | `ctx.clearFlag(HoennFlags.FLAG_X)` |
| `goto_if_set FLAG_X, Label` | `if (ctx.isFlagSet(HoennFlags.FLAG_X)) { ... }` |
| `goto_if_unset FLAG_X, Label` | `if (!ctx.isFlagSet(HoennFlags.FLAG_X)) { ... }` |
| `setvar VAR_X, n` | `ctx.setVar(HoennVars.VAR_X, n)` |
| `goto_if_eq VAR_X, n, Label` | `if (ctx.getVar(HoennVars.VAR_X) == n) { ... }` |
| `goto_if_ne VAR_X, n, Label` | `if (ctx.getVar(HoennVars.VAR_X) != n) { ... }` |
| `applymovement id, M` + `waitmovement 0` | `ctx.moveNpc(LOCALID_X, WALK_UP, ...)` |
| `applymovement OBJ_EVENT_ID_PLAYER, M` + `waitmovement 0` | `ctx.moveSelf(WALK_UP, ...)` |
| `addobject id` | `ctx.showNpc(LOCALID_X)` |
| `setdynamicwarp ...` | `ctx.setDynamicWarp(region, bank, map, x, y, facing)` |
`ctx.say` and `ctx.sign` both **wait** for the player to close the box, so
consecutive calls show consecutive boxes with no extra plumbing. `moveNpc` and
`moveSelf` likewise cover `applymovement` *and* its following `waitmovement`, so
drop the `waitmovement` line.
Flag and var constants live in the generated `HoennFlags` / `HoennVars` (or
`KantoFlags` / `KantoVars`) objects. Always use the constant, never a raw string,
because the real keys are region namespaced. See
[Story flags and vars](../../concepts/story-state/).
### `goto` and `call` between scripts
Every script in a file is an `object`, so a jump to another label in the same map
is a plain call:
```kotlin
// call LittlerootTown_EventScript_GiveRunningShoes
LittlerootTown_EventScript_GiveRunningShoes.run(ctx)
```
`call` runs the other script and comes back, which is exactly what that line
does. `goto` never comes back, so port it as the same call placed **last** in the
branch, with nothing after it:
```kotlin
// goto_if_set FLAG_ADVENTURE_STARTED, LittlerootTown_EventScript_GoodLuck
if (ctx.isFlagSet(HoennFlags.FLAG_ADVENTURE_STARTED)) {
return LittlerootTown_EventScript_GoodLuck.run(ctx)
}
```
If the target label lives in another map's file it will not be visible, since the
generated objects are `internal` and per file. Either port the shared behaviour
inline or move it somewhere both can see.
### Movement steps
`MovementStep` is the whole vocabulary, deliberately small and game agnostic:
`WALK_UP` / `WALK_DOWN` / `WALK_LEFT` / `WALK_RIGHT`, `FACE_UP` / `FACE_DOWN` /
`FACE_LEFT` / `FACE_RIGHT`, and `SET_INVISIBLE` for an npc stepping into a door.
The decomp's named movement templates (`Common_Movement_WalkInPlaceFasterUp` and
friends) expand to a list of these. Faster and slower walk variants all collapse
to the plain walk step; the animation speed is not modelled.
The npc id is the decomp **local id**, which is the npc's `entityIdx` in the map's
object events. Give it a name so the script reads like the original:
```kotlin
// Decomp local id of mom in this map's object events (LOCALID_LITTLEROOT_MOM).
private const val LOCALID_MOM = 3
```
## Commands with no equivalent yet
There is no verb for these. Do not fake them:
- **Choices.** `MSGBOX_YESNO`, `multichoice` and anything reading `VAR_RESULT`
from a prompt. `DialogService` can see a choice packet come back, but
`ScriptContext` has no way to ask a question and branch on the answer.
- **Doors.** `opendoor`, `closedoor`, `waitdooranim`.
- **Warping from a script.** `warp`, `warpsilent`, `warphole`. Only
`setDynamicWarp`, which changes where an existing `MAP_DYNAMIC` warp tile
sends the player, exists.
- **Hiding things.** `hideobjectat`, `hideplayer`/`showplayer`. `showNpc` exists,
its inverse does not, beyond ending a movement with `SET_INVISIBLE`.
- **Items, money, party.** `giveitem`, `takeitem`, `checkitemspace`,
`givemon`, `addvar` on money, and so on.
- **Battles.** `trainerbattle` in all its forms.
- **Player identity.** `checkplayergender`, and the `VAR_RESULT` branch that
usually follows it.
- **Presentation.** `playse`, `playfanfare`, `waitfanfare`, `fadescreen`,
`delay`, and `special` calls into engine C code generally.
When a script needs one of these, port the part you can and leave a scoped `TODO`
comment naming what is missing, the way the Littleroot intro does:
```kotlin
ctx.setVar(HoennVars.VAR_LITTLEROOT_INTRO_STATE, 3)
// TODO Finish the Littleroot intro cutscene
// Port the rest of GoInsideWithMom: the player jumping off the truck, the door
// open/close animations, the player following mom into the house, and the
// warpsilent inside. These need door, hideplayer, warpsilent and sound-effect
// script verbs.
```
A named `TODO` comment is much better than a `TODO(...)` stub: the script now does
something useful, and the next person knows exactly what is left. Prefer leaving
the branch a fresh save would take when a condition cannot be evaluated yet.
## Testing a port
Scripts are plain objects with one suspend method, so a test just builds a
context and calls `run`. `MapTransitionScriptTest` is the pattern to copy:
```kotlin
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), backgroundScope)
val charId = store.createCharacter(1, "Ash").info.id
val story = StoryService(store)
val session = FakeSession(characterId = charId)
val state = session.attributes[PLAYER_STATE]!!
val mapManager = MapManager()
val movement = ScriptMovementService(mapManager, NpcService(mapManager), store)
val ctx = ScriptContext(session, state, entityId = -1, DialogService(), story, movement)
LittlerootTown_OnTransition.run(ctx)
story.isFlagSet(charId, HoennFlags.FLAG_VISITED_LITTLEROOT_TOWN) shouldBe true
```
This is worth doing for scripts whose point is a state change, since those are
the ones you cannot see by looking at a dialog box. A script that only shows text
is usually faster to check in the client.
## Never re-run the generator
`gradlew :codegen:generateScriptStubs` **deletes each region's generated package
and re-emits it from scratch**. Every hand written port in it is gone. The task
is not part of the build for exactly this reason, so a normal `gradlew build`
never touches your work, but do not run it by hand once porting has started.
@@ -3,7 +3,7 @@ title: Writing a code generator
description: How to add a new build-time generator that turns pret decomp data into Kotlin game data.
---
OpenMMO builds most of its game data (maps, moves, species, …) at compile time.
OpenMMO builds most of its game data (maps, moves, species, ...) at compile time.
The `:codegen` module reads the raw data files from the pret decomps under
`decomp/` and turns them into Kotlin `*Def` objects. Those generated files are
**not committed**. They are regenerated on every build.
@@ -26,7 +26,7 @@ codegen/src/main/kotlin/ the runtime Def + Registry the server uses
```
Each generator is registered in `codegen/build.gradle.kts` and runs as its own
Gradle task (`generateMaps`, `generateMoves`, `generatePokemon`, …).
Gradle task (`generateMaps`, `generateMoves`, `generatePokemon`, ...).
## Pick a data source first
+74 -97
View File
@@ -1,32 +1,20 @@
---
title: Writing overworld scripts
description: How to fill in missing npc and sign behaviour and tweak the dialog an existing script shows.
description: Where the overworld scripts live, what one looks like, and how to change the dialog an npc or sign shows.
---
Every npc and sign in the overworld runs a **script**. A script decides what
happens when the player presses A on it: which dialog box to show, what to ask,
what to give. This guide shows how to fill in a script that is not done yet, and
how to change what an existing one does.
Every npc and sign in the overworld runs a **script**: a small piece of Kotlin
that decides what happens when the player presses A on it. Maps run scripts too,
on entry, with no button press involved.
## How it fits together
This page is the starting point. It covers where the scripts are, what one looks
like, and how to change what an existing one does. From here:
```
player presses A
│
v
InteractionService finds the entity/tile and its script label
│ looks up the label in
v
ScriptRegistry label -> Script (from GeneratedScripts.byLabel)
│ runs
v
Script.run(ctx) your code, shows dialog through ctx
```
Each script is a small object keyed by its **decomp label** (like
`LittlerootTown_EventScript_Boy`). The label comes from the map data, so we never
guess it. When the label has no script wired, the player just gets no dialog and
the server logs it.
- [Porting a decomp script](../porting-scripts/): filling in a `TODO` stub, the
decomp command reference, cutscenes, and what to do about commands that have no
equivalent yet.
- [The script system](../../concepts/scripts/): how a button press finds your
Kotlin, and the runtime rules that follow from it.
## Where the scripts live
@@ -39,9 +27,10 @@ server.game/src/main/kotlin/de/fiereu/openmmo/server/game/script/generated/
...
```
These files were made once by a generator, but you edit them **by hand** from now
on. The generator does not run on a normal build, so your changes are safe. (See
[the warning below](#never-re-run-the-generator-over-your-work).)
These files were bootstrapped once by a generator, but you edit them **by hand**
from now on. The generator is not part of the build, so a normal `gradlew build`
never touches your work. Do not run `gradlew :codegen:generateScriptStubs`
yourself: it deletes each region's package and re-emits it, wiping every port.
## What a script looks like
@@ -70,25 +59,43 @@ internal object LittlerootTown_EventScript_Twin : Script {
}
```
At the bottom of every file is a map that lists every script in it. **Every
script must be in this map** or the game cannot find it:
Most scripts are still the second kind. Roughly 2500 of the 3650 generated
objects are `TODO` stubs carrying their original decomp body in a comment;
[Porting a decomp script](../porting-scripts/) is about turning those into
Kotlin.
```kotlin
internal val LittlerootTownScripts: Map<String, Script> =
mapOf(
"LittlerootTown_EventScript_Boy" to LittlerootTown_EventScript_Boy,
"LittlerootTown_EventScript_Twin" to LittlerootTown_EventScript_Twin,
// ...
)
```
Each object is keyed by its **decomp label** (`LittlerootTown_EventScript_Boy`).
The label comes from the map data, so it is never guessed.
Use `ctx.say(line)` for an npc box and `ctx.sign(line)` for a sign or object.
Both **wait** for the player to close the box before the next line runs, so you
can just write boxes top to bottom and they show one after another.
## What a script can do
`line` is a value from the generated dialog enum for that map (like
`LittlerootTown.BirchSpendsDaysInLab`). Every text line the decomp had is already
in that enum, so type `LittlerootTown.` and let autocomplete show you the names.
Everything goes through `ctx`, the `ScriptContext`:
| Call | What it does |
| --- | --- |
| `ctx.say(line)` | An npc box from the entity the player talked to. Waits. |
| `ctx.sign(line)` | A sign or object box, no speaker. Waits. |
| `ctx.isFlagSet(f)` / `ctx.setFlag(f)` / `ctx.clearFlag(f)` | Read and write a story flag. |
| `ctx.getVar(k)` / `ctx.setVar(k, n)` | Read and write a story var. |
| `ctx.moveNpc(localId, ...steps)` | Walk a map npc through a path. Waits for it to finish. |
| `ctx.moveSelf(...steps)` | Walk the player's own avatar. Waits. |
| `ctx.showNpc(localId)` | Reveal a normally hidden npc for a cutscene. |
| `ctx.setDynamicWarp(...)` | Point this player's `MAP_DYNAMIC` warp somewhere. |
| `ctx.entityId` | The npc that was talked to, or `-1` for a sign or map script. |
That is the whole api. Plenty of decomp commands have no equivalent in it yet,
choices, doors, giving items, trainer battles,
[which the porting guide lists](../porting-scripts/#commands-with-no-equivalent-yet).
The calls that say "waits" suspend until the player acts, so you can write boxes
top to bottom and they show one after another. They are also the *only* correct
way to wait: awaiting a packet directly inside a script locks up the connection,
for [the reason explained here](../../concepts/scripts/#why-scripts-are-coroutines).
Flag and var keys come from the generated `HoennFlags` / `HoennVars` objects (or
the Kanto pair). Always use the constant, never a raw string, because the real
keys are region namespaced. See
[Story flags and vars](../../concepts/story-state/).
## Tweak an existing script
@@ -111,72 +118,42 @@ internal object LittlerootTown_EventScript_Boy : Script {
}
```
## Port a missing script
`line` is a value from the generated dialog enum for that map (like
`LittlerootTown.BirchSpendsDaysInLab`). Every text line the decomp had is already
in that enum, so type `LittlerootTown.` and let autocomplete show you the names.
A `TODO("port ...")` script has its original decomp in the comment right above
it. Read that, then replace the `TODO(...)` with real code.
## Keep the script in the map
Start simple. This decomp:
```
lock
faceplayer
msgbox LittlerootTown_Text_IfYouGoInGrassPokemonWillJumpOut, MSGBOX_DEFAULT
release
end
```
is just one npc box. Ignore the `lock` / `faceplayer` / `release` / `end` lines,
they are engine plumbing. The real content is the one `msgbox`:
At the bottom of every file is a map listing every script in it. **A script that
is not in this map cannot be found**, so if you add a brand new object, add it
here too:
```kotlin
internal object LittlerootTown_EventScript_Twin : Script {
override suspend fun run(ctx: ScriptContext) =
ctx.say(LittlerootTown.IfYouGoInGrassPokemonWillJumpOut)
}
internal val LittlerootTownScripts: Map<String, Script> =
mapOf(
"LittlerootTown_EventScript_Boy" to LittlerootTown_EventScript_Boy,
"LittlerootTown_EventScript_Twin" to LittlerootTown_EventScript_Twin,
// ...
)
```
For a branching script, the decomp uses `goto_if_set` / `goto_if_eq` to jump to
other labels based on flags or variables. Port the branch with normal Kotlin
`if`. Flags and variables are not wired up yet, so for now pick the branch that
fits a fresh save, and leave a `// TODO` for the condition:
```kotlin
internal object LittlerootTown_EventScript_Twin : Script {
override suspend fun run(ctx: ScriptContext) {
// TODO check FLAG_ADVENTURE_STARTED once flags exist
ctx.say(LittlerootTown.IfYouGoInGrassPokemonWillJumpOut)
}
}
```
## Rules to remember
### Never re-run the generator over your work
The generator overwrites these files. It does **not** run on a normal build, so
you are safe day to day. Do not run `gradlew :codegen:generateScriptStubs`
after you start porting, or it wipes your ports.
### Keep the script in the map
If you add a brand new script object, add it to the map at the bottom of the file
too. If it is not in the map, the label lookup returns null and nothing shows.
### Do not wait on packets yourself
`ctx.say` and `ctx.sign` are the only correct way to wait for the player. They run
on a separate scope so the connection keeps reading packets while the box is open.
If you `await` a packet directly inside a script, the reply never arrives and the
connection locks up.
## Test it
Restart the game server and press A on the npc or sign in the client. If nothing
shows, check the server log. A missing wiring prints something like:
shows, check the server log. Two messages mean different things:
```
NPC entityIdx=3 script=LittlerootTown_EventScript_Boy has no wired dialog
```
which means the label is not in the map.
The label is not in the map above, so the lookup returned nothing.
```
Script not ported yet
```
The label resolved fine, but the body is still a `TODO(...)` stub.
For a script whose whole point is a state change rather than a visible box, write
a test instead of squinting at the client,
[the pattern is here](../porting-scripts/#testing-a-port).