Under the hood

Getting started

This repository does not carry the cartridge. It carries what you need to regenerate everything from your own copy and check that what it says is true.

What you need

The four steps

make comprueba     # is your ROM this one
make               # listing, reassembly, sanity checks and tests
make imagenes      # draws the stages, the sprites and the screens
make vram          # checks those pictures against openMSX's VRAM

make is the one that matters. It chains four things:

  1. listado traces the flow from the entry points declared in src/knightmare.entries and generates src/knightmare.asm with the comments from src/knightmare.notes.
  2. verify reassembles that listing with pasmo and compares the sha256 with your ROM's. If they differ, the disassembly is worthless and it stops there.
  3. sanity checks what the reassembly canNOT catch: that no area declared as data comes out as code, that no entry point falls inside a data block, and that not one byte is left unassigned.
  4. test runs the 23 checks in tests/.

How the listing is organised

The listing is generated; it is not hand-edited. What is edited is src/knightmare.notes, and out of it come the labels, the line comments, the block headers and the data ranges with their name and description. Every comment is anchored to its address, so it survives a re-trace.

src/knightmare.entries holds the entry points the trace cannot deduce on its own — the interrupt hook, the addresses pushed onto the stack so they run on return, the tables that sit behind a call — each with the reason it is declared. If we cannot say WHY it is code, it is not declared.

The numbers, measured

make sanity        # the bytes of code and data, which add up to 32,768
make densidad      # the routines and the share of commented lines

Not one number on this site is written by eye: they all come out of those two commands, and there are tests watching them.

The cartridge

Knightmare, Konami RC-739, 1986. 32,768 bytes seen in pages 1 and 2 of the MSX, that is from 0x4000 to 0xBFFF.

sha256  6e7a8a2d2fadc078ec9043deee804cfa5efcf2eb64f2fb6291a5161776220cf6

The two headers

At 0x4000 sits the usual one: "AB", the INIT address (0x407E), and STATEMENT, DEVICE and TEXT at zero.

And at 0x4010 sits a second one, which this cartridge never reads: the Konami Game Master, the house's cheat cartridge, reads it from the other slot. It is "CD" 07 39, that is the 0x07 of the RC-7xx family and the 0x39 of RC-739. The "CD" marks the 1986-87 cartridges; the 1985 ones carry "AB".

Behind it come twenty-one bytes laid out by a flags byte — each bit clear means the field is present — and the layout works out byte for byte: it ends at 0x4024, exactly where code starts again. With flags 0x20 this comes out:

field value what it is
scene 0xE000 the scene variable
when 4 the scene where cheats are applied
stage 0xE061 the stage, in BCD
how many 8 eight stages
lives 0xE060  
data 0xE053 the high score
score 0xE056  
— — no second player score
mode 0xE002 the mode bits
routine 0x56C8 a routine of this cartridge

That last one is the interesting bit: 0x56C8 is ten bytes nothing inside calls. What they do is take the stage the Game Master writes into (0xE061) and turn it into the internal index at (0xE062), subtracting one in BCD.

The VDP, the other way round

The register table sits at 0x44C5, eight bytes from R0 to R7:

02 E2 0E 7F 07 76 03 E4

R3 and R4 are not addresses, they are base and mask, and here they flip the usual geometry:

table where size
colour 0x0000 three banks of 0x800
sprite patterns 0x1800 64 of 32 bytes
patterns 0x2000 three banks of 0x800
names 0x3800 768 tiles
sprite attributes 0x3B00 32 of four bytes

So colour sits where one expects patterns and the other way round. An ld hl,00008h in this cartridge does not point at patterns.

Register 7 in the table says 0xE4 — dark blue background — but that only holds until the game starts: the cartridge changes it to 0xE0 with pon_registro_7, and the low nibble becomes 0, which is black.

The memory map

0xE000  scene           0xE001  subscene        0xE002  mode bits
0xE003  frame counter                           0xE004  wait
0xE009  what is pressed
0xE010  0xE01E  0xE02C  the three PSG voices, fourteen bytes each
0xE053  high score (3 BCD)                      0xE056  score (3)
0xE060  lives           0xE061  stage in BCD    0xE062  internal stage (0-7)
0xE063  extra life threshold
0xE088  the section's bitmap                    0xE091  rows scrolled
0xE092  section (0-9)   0xE093  section list    0xE095  end of the bitmap
0xE0A0  the two wave spawners, 0x10 each
0xE100  the seven enemies, 0x20 each
0xE200  the eight enemy shots, 0x10 each
0xE320  the shadow of the sprite attribute table
0xE3D0  the boss
0xE4F0  the eight creatures seeded by the stage, 0x10 each
0xE600  the player      0xE620  the four shot slots
0xE820  the tile buffer: 28 rows of 32

The machine changes nothing

Of everything below 0x4000 the cartridge reads one single address: 0x0007, the VDP data port, and it calls seventeen BIOS routines: VDP, PSG, keyboard and slots. It never touches 0x002B, 0x002C or 0x002D, the bytes that say the character set, the date format and whether the machine runs at 50 or 60 Hz.

Checked by dumping, too: the title screen's VRAM on an international machine and on a Japanese one gives 0 bytes different out of 16,384. The kanji logo is the same on both.

The hidden mark

The last thirteen bytes of the cartridge, 0xBFF3 to 0xBFFF, are the house's mark: マジョウデンセツ — Majou Densetsu — written backwards in katakana, its length (0x0A), the 0x39 of RC-739 and an 0xAA closing it. It was uncovered by Manuel Pazos.

The code

15,233 bytes of code and 17,535 of data. 7,509 instructions spread over 985 named blocks, and not one below 10 % commented.

Everything hangs off the interrupt

INIT (0x407E) does no more than set the stage: it switches the whole cartridge into pages 1 and 2 with ENASLT, writes a jp cada_cuadro into the H.KEYI hook at 0xFD9A, clears 0xE000 to 0xE7FF, builds the screen and drops into a jr $. The whole game happens inside the interrupt.

cada_cuadro (0x402E) does, in this order: read the VDP to drop the interrupt request, sound first — so its delay does not show if the frame runs long — the reentry latch, the controls, the frame, and one more VDP read on the way out.

The dispatcher

Almost all the flow goes through 0x406C:

pop hl          ; the return address IS the table
add a,a
call suma_a_a_hl
ld e,(hl) / inc hl / ld d,(hl) / ex de,hl / jp (hl)

So the table sits right behind the call. There are fifteen such places, and tools/tablas_despacho.py works out each table's size with the lowest-entry rule. Three would not yield: their first entry jumps backwards to code nothing else calls, and the rule has nothing to stand on. They were closed by hand on the first entry pointing forwards, which is always the byte right after the table.

There is a second door, 0x4065, which takes the index from (ix+0) and wants the table already in HL. Only one place uses it, 0x75F0, and that is the two-level dispatch: 0x75F3 is a table of sixteen subtables indexed by (ix+1) & 0x0F — the enemy type — and 0x4065 indexes the subtable with (ix+0), which is its state.

The scenes

(0xE000) is the scene and (0xE001) the subscene; the table at 0x40EA has ten entries:

0  intro (the KONAMI banner coming down)
1  title
2  demo
3  countdown and start of the game
4  the game            <- the scene the Game Master watches
5  stage cleared
6  a life lost
7  GAME OVER
8  next stage
9  the ending

In scenes 0, 1 and 2, haz_el_cuadro pushes 0x4262 onto the stack before dispatching, so on return from the scene that runs: look at whether anything was pressed and, if we are on the title and it is a fire button, start the game.

The decompressors

There are two formats, and it pays not to mix them up.

The block one (0x4417), for patterns, colour and tiles:

n with bit 7 set   n bytes as they come
n without bit 7    the next byte, repeated n times
0x80               change of VRAM address (two bytes)
0x00               end

Every byte also goes through lee_y_traduce (0x443B), which applies the colour bank in (0xE661).

The label one (0x43F9): a word with the VRAM address, then the tile codes, 0xFE to jump somewhere else and 0xFF to finish. The codes are not ASCII: they are tile numbers of the font, and the alphabet is read by drawing the 35 glyphs 0x45C9 decompresses.

The sound engine

It is The Goonies' (RC-734), and not by hearsay: tools/porta_nombres.py finds its routines here by normalised instruction signature, with runs of up to 150 bytes in a row.

Three fourteen-byte voices at 0xE010, 0xE01E and 0xE02C. A piece is asked for by number, and that number is also its priority: it only gets in if it outweighs whatever is already playing. The table at 0x4B38 is 63 voice pointers, not piece pointers: each piece takes one, two or three in a row.

The twelve semitones are at 0x4B2C, and dropping an octave means doubling the period: the add hl,hl at 0x4B0F.

The shared framework

tools/comun_normalizado.py gives 21 runs and 996 normalised bytes in common with The Goonies, that is 6.8 % of this cartridge. What is shared is the framework — the dispatcher, the 16-bit adds, the decompressors, the sprite mirror, the controller reader — and the sound engine. The other 13.7 KB of code are its own.

In the emulator

There are no screen captures here, but the emulator does get used: to check what Python draws against what the VDP really holds.

The check

make vram

It starts openMSX with no window, lets the demo play itself, dumps the 16 KB of VRAM at nine moments and subtracts them from the ones Python builds.

stage 0  colour 0x0000..0x17FF   6144 bytes  0 different
         patterns 0x2000..0x37FF 6144 bytes  0 different
         names, rows 0 to 21      704 tiles  0 different
...
---- 8 screens, 0 bytes different

Coming out at zero is what lets the pictures be published saying they are the cartridge's.

How the eight stages are reached without playing

No need to play, and no need to fake anything either. monta_la_fase (0x53D3) reads the stage from (0xE062) and gets everything out of it: the map from the table at 0x99CD, the tiles and colour from the one at 0x563C and the enemies from the one at 0x6A98. A breakpoint at 0x53D3 — before it reads — writes whichever stage is wanted, and the cartridge builds that stage with its own code. One starting byte is changed, exactly as a player reaching that stage would do.

The dump goes half a second later: the patterns, the colour and the name table are up by then, and the scenery has not scrolled a single row yet, which is what makes the map comparable.

Two traps that cost the check

The cartridge does not clear the patterns or the colour when the stage changes, only the name table. Stages 1, 2 and 4 carry fewer tiles than stage 0 — 61, 59 and 79 against 80 — so what is left over stays from the previous one. Building one stage on its own gave 456 bytes of difference in colour; chaining them the way the game chains them, zero.

The scoreboard is at the bottom, not the top. The screen starts four rows into the tile buffer — vuelca_la_pantalla copies from 0xE8A0 minus (0xE091) & 3 rows — and the last two rows of the screen are SCORE, HISCORE, REST and STAGE, painted over afterwards.

Watching it play

openmsx -machine Philips_VG_8020 -cart knightmare.rom

The cartridge chains intro, title and demo on its own, and the demo is a recorded game, so two boots give the same thing.

If you want to poke around

openMSX's console (F10) does the usual:

debug read memory 0xE062     ; the stage, 0 to 7
debug read memory 0xE060     ; the lives
debug write memory 0xE062 5  ; and jump to the sixth

And for the three variables that run the frame:

debug read memory 0xE000     ; the scene
debug read memory 0xE092     ; the section within the stage, 0 to 9
debug read memory 0xE091     ; the tile rows scrolled so far

Code shared with other Konami cartridges

This disassembly has been compared, instruction by instruction, with every other Konami one in the series. A block counts when the same instructions, at least six of them from a label to its ret or its unconditional jump, are in both cartridges; the addresses are left aside, because they change from one cartridge to the next. Of the other 57, 52 have at least one block in common with this one; these are the ones that share the most:

Cartridge Blocks Instructions For example (here = there)
The Goonies 31 394 lee_mando_y_teclado (0x44DF)
Yie Ar Kung-Fu II 28 261 pinta_texto (0x43F1) = pinta_guion
Konami’s Soccer 26 305 lee_mando_y_teclado (0x44DF) = lee_el_mando_1
Hyper Sports 3 24 256 cada_cuadro (0x402E) = manejador_de_interrupcion
Pippols 22 249 toca_la_nota (0x4A36) = PISTA_NOTA
Hyper Rally 20 239 lee_mando_y_teclado (0x44DF) = LEE_MANDOS
Konami's Ping Pong 20 209 pinta_texto (0x43F1) = pinta_rotulo
Road Fighter 20 244 lee_mando_y_teclado (0x44DF) = lee_el_mando
King's Valley 19 249 toca_la_nota (0x4A36) = tono_con_periodo_explicito
Yie Ar Kung-Fu 19 206 cada_cuadro (0x402E) = interrupcion

The whole matrix, the 58 cartridges against each other, is on The routines in the series database, along with the method and the program that measures it.