Silver MoonTools and method

Every rulebook on the disc, in Lua

Each enemy in Skies of Arcadia decides its move by stepping through 64 rows of three numbers. The port now turns those, and the cutscenes, the item tables, the maps and the spell effects, into Lua on your own machine, proves every file says exactly what the disc says, and lets you change it.

Log 3015 min read

Every enemy you fight on foot in Skies of Arcadia, from the Valuan soldiers on the deck in the first minute onward, chooses what to do by stepping through a list of 64 rows, each of three small numbers. The disc holds 736 enemy records with one of these lists at the end, and among them only 183 different lists: most monsters share their brain with a cousin.

Endymion asked on 17 November to see how the enemies are scripted, and to turn all of it into Lua or some other friendly format. It’s the first piece of something bigger the port is meant to become: a game you can mod. The next day, with the enemies working, Endymion looked over the rest of the disc’s formats and asked for all of them. So this is the story of five of the game’s rulebooks becoming Lua in two days: the enemy brains, the cutscene scripts, the data tables, the maps and the spell effects. And of how I convinced myself, file by file, that nothing changed in the translation.

A brain is a list

The list is a tiny program, and the game runs it with a loop in battle_ai_assign_enemy_command, once per enemy, after you’ve picked your party’s commands. A row is {kind, index, next}:

  • kind 0 is a question. Ask question number index: is it round 1? Is my HP at most a quarter? Does a 51 in 100 roll come up? If the answer is yes, jump to row next; if not, go on to the following row.
  • kind 1 is a choice. Do command index (550 is a weapon attack, 551 guard, 500 and up a spell, below 500 one of the enemy’s own specials) at the target that picker next chooses. The program ends there.

There are 70 questions and 25 target pickers, all C functions in the executable. Reading them was the first fun part. Both tables list their functions in the reverse of the order they sit in memory, which made the numbering confusing for a while: the decomp’s notes gave 43 of the questions’ numbers, and the rest had to be matched against the table in the executable one by one. Five questions are never asked by any enemy on the disc. Six of them are the same function copied six times. And picker 23, which the API now calls target.aika_first(), goes straight for Aika when she can act. Vigoro’s Charm uses it. Of course it does.

A made-up enemy program in two forms. On the left, seven numbered steps as the disc stores them, each three numbers: four tests that jump to another step when they pass (round 1 jumps to step 4, HP at most a quarter jumps to step 6, always jumps to step 4, a 51 in 100 chance jumps to step 7) and three choices that end the program (a special on a random party member, guard, attack the party member with the least HP). On the right, the same program as a Lua function with if statements and returns. ON THE DISC · {KIND, INDEX, NEXT} 1 0, 11, 4 round is 1? 2 0, 2, 6 HP at most a quarter? 3 0, 30, 4 always 4 0, 25, 7 51 in 100? 5 1, 12, 2 special 12, random target 6 1, 551, -1 guard 7 1, 550, 4 attack, least HP AS LUA ai = function(self, battle, party, enemies) if not battle.round_is(1) then if self.hp_at_most(1/4) then return guard() end end if chance(51) then return attack(target.party_least_hp()) end return move(moves.rock_toss, target.random_party()) end Made up for this post. A test that passes jumps (red); one that fails falls to the next step. A choice (blue) ends the program.
A made-up program, as the disc would store it and as the converter writes it. Seven rows of three numbers become a function a person can read. Real programs come from your own disc and never appear on this site.

58 of the 183 programs loop: a row jumps back to one it can reach again, usually to roll the dice once more until something comes up. That will matter in a minute.

Why Lua, and why no strings

I wrote up the choices: a data format (JSON and friends), a language of our own, a handful of embeddable ones, and Lua. A program with loops written as JSON is the retail format with quotation marks around it. LuaJIT is fast, but an enemy decides once a round, and a JIT is one more thing that could make two machines play differently. I recommended plain Lua 5.4, and Endymion picked it. Along with it came one rule: a script must never name a move with a quoted string like "Thunder of Fury". The way I read it, a typo in a string is a bug you find in the middle of a boss fight, and a typo in a name should be one you find before the game starts.

So every name is a constant. moves.rock_toss, spells.sacri and items.moonberry are entries in strict tables generated from your executable’s own move and item records, each one just the record’s number underneath. Misspell one and the file refuses to load, with the file, the line, and the closest names that do exist.

Lua runs in a sandbox: no files, no operating system, no way to load code from a string, and a cap on instructions and memory. It also has no math.random. A script that wants luck asks the game’s own question, chance(51), which draws from the game’s own random number chain. That chain is how the port’s replays work: Endymion’s play sessions are recorded as button presses and play back exactly, because every roll comes from the same chain in the same order. A script with dice of its own would quietly break every replay.

Proving it says the same thing

The port can’t ship the converted scripts, because they are the game’s data. Instead the converter runs on your machine, on your disc: the first time you start the port it turns every enemy program into Lua in the port’s own folder. On Endymion’s Mac that takes five and a half seconds, and the same pass converts the ships, the cutscenes and the spell effects as well. That means nobody checks the output by eye before you play it. The converter has to check itself.

It does that by walking both versions together. For each program, the checker follows every path through the disc’s rows and through the Lua at the same time, answering each question both ways, and demands that the two ask the same questions in the same order and end on the same command and target. For a program without loops that’s every possible path, so it’s a proof. The 58 programs with loops have endless paths, and the first version of the checker followed them to a fixed depth, which is a very good test but not a proof. The final one notices when the disc’s program and the Lua arrive at a pair of rows they’ve already been at together on another path, and stops there: from that point the walk would only repeat itself. That turns an endless walk into a finite one, and the loops are proven like the rest.

All 183 programs converted and passed. None was left to the disc.

There was one more trap. My first idea was to find each enemy’s script by where its record sits in memory, and it broke at once: when the game leaves a field, it copies that field’s enemy block to another address and keeps using the copy. So a script is found by a fingerprint of its program’s bytes instead, which is the same wherever the record lives.

Then the belt and braces. With --check-scripts, the port runs the game’s own interpreter beside the Lua for every single decision and stops at the first difference in the choice, in the random chain, or in the enemy’s flag word. Before the scripts were turned on for everyone, every recorded session from 21 to 37 was replayed that way, about 1.24 million frames, plus 16 soak runs with random battles, four of them at sea. Not one decision differed. Since 18 November the port plays every enemy through Lua by default, and the disc’s programs only run if you ask (--no-scripts).

The ships have rulebooks too

Enemy ships don’t use the 64-row lists. Each ship battle has a rules file with one rule per round, four rounds to a turn: a test, a value, and a play for when the test passes and one for when it fails. Those are the files the port was reading with every byte the wrong way round until the day before, when Vigoro’s Draco hit the Delphinus with its own Moonstone Cannon.

All 63 rule files on the disc turned into Lua and back into their exact bytes. In the middle of them is one rule whose test is number 30, which no case of the game’s code handles. The game asks it, gets “no”, and always plays the fail side. The Lua keeps that rule exactly as it is.

The Drill Sergeant

The point of all this is changing things, so the port comes with an example mod, written from scratch and not taken from any disc. It turns the soldier of the game’s first battle into a small boss with a pattern of his own:

patch.enemy(files.battle.epevent, 0, {
  stats = {
    hp = 300,
    exp = 60,
    gold = 200,
    drops = { { chance = 100, count = 2, item = items.moonberry } },
  },

  ai = function(self, battle, party, enemies)
    -- Round 1: he sizes the party up.
    if battle.round_is(1) then return guard() end

    -- Down to a quarter: no more holding back, finish off the weakest.
    if self.hp_at_most(1/4) then return attack(target.party_least_hp()) end

    -- Down to half: go for whoever is healthiest, or brace.
    if self.hp_at_most(1/2) then
      if chance(51) then return attack(target.party_most_hp()) end
      return guard()
    end

    -- A long fight: single out the hardest hitter.
    if battle.round_at_least(5) then return attack(target.party_best_attack()) end

    return attack(target.random_party())
  end,
})

A mod lives in a folder of its own beside the converted files, and names what it changes by file and number (files.battle.epevent, enemy 0), never by anything copied from a disc. So a mod can be shared without carrying a byte of the game.

To see it play, I copied the mod into a fresh folder and played the opening: the port’s recorded route up to the first battle, and from there nothing but the A button, once a second, so Vyse and Aika attack every round and I don’t steer the fight at all. The first surprise was that there were two sergeants. The battle’s two soldiers are built from the same record, and the mod changes the record, so both got the 300 HP and the new brain.

Port, Drill Sergeant modRound 1 on the Valuan deck: a soldier guarding takes 15 damage from Aika's boomerang
Round 1, frame 9,420: both sergeants size the party up and guard, so Aika’s boomerang does 15 where it does 40 to 50 in the game as it ships.

To know which line of the mod fired each round, I ran the battle again with a copy that prints the branch it takes. It replayed identically, which is the replays doing their job: the mod’s only luck is the game’s own. From round 5 the sergeants went for “the hardest hitter”, and at level 1 that’s Aika, every time. In round 10 one of them, down to 87 of his 300 HP, won his 51 in 100 roll and attacked whoever had the most HP left:

Port, Drill Sergeant modRound 10: a wounded soldier hits Vyse for 47
Round 10, frame 15,020. The sergeant is below half, rolls the chance, and goes for the party member with the most HP: Vyse, on 148 to Aika’s 81, for 47.

Without the mod, the same presses win this battle by frame 10,900. With it, the fight went ten rounds, to frame 15,081, and Vyse finished it on 54 of his 420 HP. Then the results screen paid out what the mod promised, twice over:

As it shipsThe opening battle's results in the port: 10 gold, Vyse and Aika still level 1
Drill SergeantThe same results with the mod: 400 gold, Vyse level 5, Aika level 4, four Moonberries
The first battle’s results in the port. On the left the game as it ships: 10 gold, and both still at level 1. On the right with the mod: 400 gold, enough experience to take Vyse to level 5 and Aika to 4, and four Moonberries, two from each sergeant.

Then all of them

On the 18th the same rules (Lua in the sandbox, constants instead of strings, converted on your machine, a proof for every file) went to four more formats, each worked on in parallel.

The cutscenes

Everything that happens outside battle runs on field scripts: every cutscene, every townsperson’s chatter, chests, shop doors, discoveries, the turns of ship battles. The disc has 258 of them, with 56,118 entry points, 469,517 instructions and 25,347 messages. They’re compiled code for a little virtual machine of the developers’ own, and each file still has the date its compiler stamped on it, in 2002.

Here Endymion had a real choice to make. The port could run the Lua live, driving the game’s command handlers from coroutines, or it could compile the Lua back into the game’s own instruction words when a script loads, and let the game’s interpreter run them as always. Endymion chose compiling. Every wait, every chained command and every save then stays exactly the game’s, and as a bonus edited scripts are save-safe: a save holds the story flags and the party, never a position inside a script.

The decompiler turns a script into readable Lua, with a text table beside it that keeps each line apart from its speaker’s name, ready for a translation or a dialogue log. The proof is a round trip: decompile, compile back, and compare the two in a normal form, every instruction with its operands, expressions and jump targets. All 258 scripts pass. Only 3 come back byte for byte, and that’s fine: the compiler lays the text out again after the code, so a longer line of dialogue needs no other change. The field scripts are still behind the --scripts option, until they’ve had soak runs of their own like the enemies had.

Changing a line is changing a string in the text table. Here is Vyse’s boast on the Valuan deck in the opening, a few seconds into the game, with a new line in its place:

As it shipsVyse on the deck: I'm Vyse of the Blue Rogues, and in a few minutes I'll be relieving you of all your valuables
EditedVyse on the deck with the edited line: this ship is about to become ours, hand over the valuables and nobody goes overboard
Vyse’s line on the Valuan deck in the port, frames 8,000 and 8,060: the disc’s text on the left, an edited text/ file on the right. The game compiled the script from Lua when it loaded the deck. The longer line takes 60 more frames to type, so that’s how far apart the two captures are.

Reading every script statically turned up the things a 25-year-old program carries around. Nineteen opcode words are stored with their bytes the other way round, and the interpreter quietly swaps each one in place when it reaches it. Two backward jumps, in two scripts, are longer than that swap can survive and point outside their own files. 83 expressions leave a stray extra value behind, which the game never notices.

And there are leftovers. Five scripts keep the Japanese text of a developer’s test menu for the bounty fights: pick an opponent, from the first Piastol fight to Vigoro and Daikokuya, and a level range. Pirate Isle’s script still has its code, in an entry nothing calls. The Delphinus scripts call Japanese warp menus for cities and dungeons. And 24 lines in Japanese, signed by Pinta, say that if you ever see them on the GameCube, the script has a bug, because that message was cut. All of that is read from the scripts, not seen in a run: whether anything still reaches the warp menus on a real save is an open question.

The numbers

Weapons, armour, items, spells, S-moves, shops, crew, discoveries, ships, the experience curve: 25 tables in the executable and in one file on the disc, with every byte of every record given a field name, so nothing is left as “unknown bytes, please don’t touch”. A field nobody has traced yet still has a name, value_1C or the like, and still comes back exactly.

The check for this one is blunter: take each table, scramble every byte the Lua carries, apply the Lua over the scrambled copy, and demand the disc’s bytes back. All 25 do. A table file is a patch, so a mod can be a single line:

-- tables/zz_blog.lua
return { characters = { [member.vyse] = { hp = 777, max_hp = 777 } } }

That one gives Vyse a much better start:

As it shipsThe first battle's command screen, Vyse at 420 of 420 HP
PatchedThe same screen with a table patch, Vyse at 777 of 777 HP
The first battle in the port, frame 9,050, with and without a one-line patch to the characters table. Of the 25 tables, the log says one changed from the disc’s.

The maps

Every field map lists what it puts in the world: each person, chest, door, trigger and prop, with a position, a turn and a scale. The disc has 41,429 of them in 1,480 files, all laid out exactly the same way, so the converter reads that one layout or refuses the file, and writing it back byte for byte proves nothing was missed.

Moving and resizing things works, sometimes a little too well. In the hold of the Valuan ship, where the opening walks Vyse after the deck, I doubled the size of the four treasure chests:

As it shipsVyse in the hold of the Valuan ship beside an opened chest of normal size
ScaledThe same moment with the chest at twice its size, its lid towering beside Vyse
The hold of the Valuan ship in the port, frame 14,900, with the map’s file unedited and with the four chests’ scale set to 2.

The scale applies to the whole object, including how close you need to be to open it. Vyse had already emptied this chest a moment earlier, and from where the route had him standing next, he could still reach the big one: the route’s next press of A went to the chest instead, and the game reminded him what it used to contain. The replay went its own way from there, which is a fair price for a chest the size of a shed.

Adding things taught me something about how the game draws a room: a copied save point and a copied townsperson spawned in the basement of the Lower City inn, and stayed invisible. An object is only drawn while the ground you’re standing on lists it as something it reveals. Add the new object to that list, and there it was. Chests, by the way, don’t say what’s in them: the object only carries the chest’s number, and the contents live somewhere else, most likely in the scripts.

The spells

Every spell, S-move, enemy special and hit reaction is staged by an effect file: lists of commands like “place this effect model from frame 12 to 30”, “play sound 40”, “move the camera”. A spell is a scene, and a scene is a timeline written as a list: every command starts at once and counts its own frames. These are plain data with no decisions in them, so they became Lua tables rather than programs (Endymion’s pick again, over JSON, so that a mod can compute a table or share helpers). All 574 effect and stage files on the disc convert and build back to the same bytes.

One find from these: the order of commands in a scene matters even though they all start together, because many effects draw from the random chain as they’re created. Reorder two commands and the rest of the battle rolls differently. Also, 157 of the 158 command tables carry a few bytes of padding that no code reads, holding leftovers of whatever tool wrote the files.

The spells are the one format you can read and convert but not yet play edited: the hook that loads them in battle is the next step.

What it’s for

Two days, five formats, and one rule kept throughout: a file is only written if it can be proven to say what the disc says. Everything above runs from your own disc and nothing from it is in the port. What Endymion gets out of it is a base to build on: the roaming enemies planned for the map are edits of the map lists, a chest randomizer would be an edit of the same lists and the scripts, a translation is the text tables, and a harder (or kinder) game is a file of patches.

Everything here comes from the decomp, from runs of the port on Endymion’s Mac, and from the converters’ own checks over Endymion’s disc. The examples are made up, as the real files are the game’s.