tuanp.dev

Part 8 of 20 · about an hour

Put the picture on the screen

Everything is on the table now: a processor, a memory, a cartridge, a tile decoder. Today adds less new code than you might expect. Mostly we connect things that already exist, and that is how the last step of a long build usually feels.

Last time our emulator learned to draw the cartridge's tiles, and we noticed that the program's ten data bytes are tile numbers. But the program's attempts to send those numbers anywhere are wasted. Today we build the chip it is trying to talk to, and the cartridge draws its own picture.

By the end of this part

  • Writes to two special addresses reach a second chip, the PPU, instead of plain memory.
  • The PPU keeps a grid saying which tile goes where on the screen.
  • Your emulator runs hello.nes and shows the picture the cartridge's program asked for.

Where did the ten bytes go?

The cartridge's loop stores ten tile numbers, one after another, to address $2007. In our emulator $2007 is an ordinary memory slot. What do you expect it to hold after the program has finished? Add a line at the end of Part 7's main to look:

    println!("$2006: {:02X}  $2007: {:02X}", cpu.read(0x2006), cpu.read(0x2007));
$ cargo run -q
...
$2006: 20  $2007: 07

One slot can hold one byte. Each store wiped out the one before it, and only the last tile number, 07, is left. Nine tenths of the message is gone. Clearly, on a real NES, address $2007 is not a memory slot.

A second chip

The NES has a second processor-like chip whose only job is to produce the picture. It is the PPU. What is the PPU? The PPU, or picture processing unit, is the chip in the NES that turns tiles into the image on the screen.

The PPU has a memory of its own, completely separate from the one we built in Part 3. The processor cannot read or write it directly. Instead, a few addresses in the processor's memory are wired straight to the PPU. A byte written to one of them does not get stored; it gets handed to the other chip. Such an address is a memory-mapped register. What is a memory-mapped register? A memory-mapped register is an address that is not memory at all, but a doorway to another device.

The Cpu sends "write address, value" to a decision box labelled "which address?". If the address is 2006 or 2007, the value goes up to the PPU. Anything else goes down to memory.Cpuwrite(addr,value)whichaddress?Ppumemory$2006, $2007anything else
In Part 3 we made write the only door into memory. Today that door gets a second exit.

This is why Part 3 insisted that every store go through one write method. The processor's instructions do not change at all. STA still calls write; write decides where the byte really goes.

The PPU's memory and the name table

The PPU's own memory has 16,384 slots, with addresses $0000 to $3FFF. Two regions matter to us:

$0000-$1FFF    the tiles: the cartridge's CHR ROM appears here
$2000-$23BF    the name table

The name table is new. What is the name table? The name table is a grid of bytes, one for each tile-sized cell of the screen, that says which tile to show in that cell. The NES screen is 256 by 240 pixels, which is 32 cells across and 30 down. The grid is stored row after row, so the cell in row r, column c lives at address $2000 + r × 32 + c.

The top-left corner of the name table grid, with each cell showing its address. Row 0 starts 2000, 2001, 2002. Row 1 starts 2020, 2021, 2022. Row 2 starts 2040. The cell at row 1, column 0, address 2020, is highlighted. Columns run from 0 to 31 and rows from 0 to 29.col 01231row 012200020012002202020212022204020412042…201F⋮down to row 29← our message starts here
Each row is 32 cells, and 32 is $20. That is why row 1 begins at $2020.

How the processor talks to it

Now the cartridge's program makes sense. Read it again:

LDA #$20
STA $2006       "PPU, I want to talk about address $20..
LDA #$20
STA $2006        ..20." Row 1, column 0 of the name table.
LDX #$00
LDA $8000,X     the next tile number
STA $2007       "Put this there, and move on to the next cell."
...

Two registers, two rules:

  • $2006 is the PPU's address register. A PPU address is two bytes, but a write delivers only one, so the program writes twice: high byte first, then low byte.
  • $2007 is the PPU's data register. A byte written here is stored in the PPU's memory at the current address, and then the address moves on by one, ready for the next byte.

Step through it and watch the message land.

The PPU's address register starts at 0000, becomes 0020 after the first write to 2006 and 2020 after the second. Then each write to 2007 fills one cell of name table row 1 and the address moves one cell to the right, until the ten cells hold 01, 02, 03, 03, 04, 00, 05, 02, 06, 07.PPU address0000no writes yet2020202120222029name table, row 100000000000000000000
fn write_addr(&mut self, value: u8) {
    self.addr = (self.addr << 8) | value as u16;
}

fn write_data(&mut self, value: u8) {
    self.vram[self.addr as usize % 0x4000] = value;
    self.addr = self.addr.wrapping_add(1);
}
  1. The PPU's address register starts at 0000. Row 1 of the name table is all zeros, which means "tile 0, the blank one" everywhere.
  2. First write to $2006: the byte 20 is pushed into the register from the right. It now reads 0020.
  3. Second write to $2006: the first byte slides left to make room, and the new 20 goes in behind it. The address is $2020.
  4. First write to $2007: tile number 01 is stored at $2020, and the address steps on to $2021.
  5. Second write to $2007: 02 is stored at $2021, and the address steps on again.
  6. Eight more laps of the loop, eight more cells. Nothing is overwritten this time: the whole message is in the name table.

Build the PPU

The PPU is a second struct, with its memory and its address register as fields. Put it above struct Cpu. (In the snapshot, SHADES and tile_pixel from Part 7 have moved to the top of the file, unchanged, so that everything is defined before it is used. Rust does not require that order; it is only easier to read.)

src/main.rsSnapshot
struct Ppu {
    vram: [u8; 0x4000],
    addr: u16,
}
 
impl Ppu {
    fn new() -> Ppu {
        Ppu { vram: [0; 0x4000], addr: 0 }
    }
 
    // The tiles live at the start of the PPU's memory.
    fn load_chr(&mut self, chr: &[u8]) {
        for i in 0..chr.len() {
            self.vram[i] = chr[i];
        }
    }
 
    // A write to $2006: one more byte of the address, high byte first.
    fn write_addr(&mut self, value: u8) {
        self.addr = (self.addr << 8) | value as u16;
    }
 
    // A write to $2007: store the byte, then step to the next address.
    fn write_data(&mut self, value: u8) {
        self.vram[self.addr as usize % 0x4000] = value;
        self.addr = self.addr.wrapping_add(1);
    }

Most of it is familiar. The one new line is in write_addr:

  • self.addr << 8 is a shift (Part 7) going the other way: everything slides 8 places left, so the low byte becomes the high byte and whatever was in the high byte falls off the top.
  • | is "or": it lays the bits of the new byte into the eight places the shift left empty.

Start from 0000, shift in 20, and you have 0020. Shift in another 20 and you have 2020. It is Part 3's hi * 256 + lo again, done one byte at a time. In write_data, the % 0x4000 is a remainder: it keeps the position inside the array even if a program sets an address beyond $3FFF.

Connect it

The Cpu gets a Ppu as a field. In the language of Part 6, the Cpu owns its Ppu: a struct can own other structs just as it owns numbers.

struct Cpu {
    a: u8,
    x: u8,
    pc: u16,
    zero: bool,
    trace: bool,
    memory: [u8; 0x10000],
    ppu: Ppu,
}

impl Cpu {
    fn new() -> Cpu {
        Cpu { a: 0, x: 0, pc: 0x8000, zero: false, trace: false, memory: [0; 0x10000], ppu: Ppu::new() }
    }

And now the change this whole part has been leading up to. Here is the Cpu's write, the door from the figure:

    fn write(&mut self, addr: u16, value: u8) {
        match addr {
            0x2006 => self.ppu.write_addr(value),
            0x2007 => self.ppu.write_data(value),
            _ => self.memory[addr as usize] = value,
        }
    }

A match on the address: two special cases go to the PPU, and everything else goes to memory as before. A full NES emulator has a dozen more lines in this match, for the sound chip and the controllers and the rest of the PPU's registers, but this is the shape of all of them.

Draw the picture

One method to go. The PPU has to turn its name table into pixels. For every pixel of the screen it asks two questions: which cell is this pixel in, and which pixel of that cell's tile is it?

Three stages. First, the screen pixel at x 17, y 10. Dividing both by 8 gives the name table cell at row 1, column 2, address 2022, which holds tile number 03. The remainders, 1 and 2, pick pixel 1, 2 inside tile 3, which has colour 3 and is printed as a hash sign.screen pixelx = 17, y = 10row 1, column 2address $2022holds tile 03tile 3pixel (1, 2)colour 3: #17 / 8 = 210 / 8 = 117 % 8 = 110 % 8 = 2
Dividing by 8 finds the cell; the remainder finds the place inside it.

With whole numbers, Rust's / throws away the remainder, so 17 / 8 is 2, and % gives the remainder alone, so 17 % 8 is 1. That is the whole method:

// How much of the 256x240 screen we print: the top-left corner.
const VIEW_W: usize = 80;
const VIEW_H: usize = 24;
    // Print the picture: for every pixel, which tile is it in,
    // and which pixel of that tile?
    fn draw(&self) {
        for py in 0..VIEW_H {
            for px in 0..VIEW_W {
                let tile = self.vram[0x2000 + (py / 8) * 32 + px / 8] as usize;
                let colour = tile_pixel(&self.vram, tile, px % 8, py % 8);
                print!("{}", SHADES[colour as usize]);
            }
            println!();
        }
    }

The call to tile_pixel passes &self.vram where Part 7 passed chr. That works because the tiles sit at the very start of the PPU's memory, exactly where tile_pixel expects them.

Our terminal cannot show 256 columns, so VIEW_W and VIEW_H limit the printout to the top-left corner of the screen: 80 pixels by 24, which is ten cells by three.

Last, main hands the CHR ROM to the PPU, and after the program has run, asks for the picture:

    let mut cpu = Cpu::new();
    cpu.load(prg);
    cpu.ppu.load_chr(chr);
    cpu.reset();
    cpu.run();

    cpu.ppu.draw();
}

(The line that printed the sizes is gone, and so is print_tiles; they have done their work.) Run it.

$ cargo run -q
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
##..##..######..##......##.......####...........##..##..######...#####...##.##..
##..##..##......##......##......##..##..........###.##..##......##......#oo#oo#.
##..##..##......##......##......##..##..........######..##......##......#+oooo#.
######..#####...##......##......##..##..........######..#####....####...#ooooo#.
##..##..##......##......##......##..##..........##.###..##..........##...#ooo#..
##..##..##......##......##......##..##..........##..##..##..........##....#o#...
##..##..######..######..######...####...........##..##..######..#####......#....
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................

Nobody told your Rust code what to draw. It read a cartridge file, found the program, started where the reset vector said, and ran 6502 instructions on a processor you wrote. That program spoke to a PPU you wrote, which looked up tiles you decoded. Every link in that chain is yours. It is small, and it is an emulator.

Shortcuts we took on purpose

  • We show a corner of the screen, as text. Fixed in Part 9.
  • We have 11 opcodes out of 151, one flag out of seven, and no stack. Fixed in Parts 12 to 14.
  • We run the program to its end and then draw once. A real NES draws 60 pictures a second while the program runs. Fixed in Part 15.
  • No colours (Part 16), none of the moving objects that NES people call sprites (Part 17), no controller (Part 18), no scrolling (Part 19).
  • The PPU has two registers out of eight, and it simply shifts each $2006 write in, where a real one keeps track of which of the two writes it is on. Fixed in Part 15.
  • hello.nes is a correctly laid-out file, but its program skips the start-up routine that real hardware needs (waiting for the PPU to warm up, choosing colours, switching the display on). On a real NES it would show nothing. We meet that routine in Part 15, and find out in Part 16 that our own emulator agrees.

What changed today

  • A new Ppu struct has its own memory, with the tiles at $0000 and the name table at $2000.
  • The Cpu owns a Ppu, and write sends $2006 and $2007 to it.
  • draw turns the name table into pixels using tile_pixel.
  • main loads both halves of the cartridge, runs the program, and draws.

Now you

  1. Set cpu.trace = true and run once more. Read the trace alongside the stepper above: can you point to the exact line where each cell of the name table is filled?
  2. Open code/mkrom/src/main.rs, the program that made the cartridge. You should be able to read all of it now. Change the message, or the address it is written to (try row 2: which two bytes?), build a new hello.nes with cargo run -- hello.nes, and run your emulator on it. You are now writing NES programs.
  3. Draw a new tile in mkrom, using colours 1 and 2 as well as 3, and put it in your message.
  4. Programs also read from the PPU. Give the Cpu's read a match like the one in write, so that reading $2002 returns $80. On a real NES that answer means "the PPU has finished a picture", and start-up routines wait for it.
  5. From blank, once more. It is about two hundred lines now. If you can write them, you understand them, and the second half of the course builds on every one.

Check your understanding

  1. What is the PPU?
    AnswerThe picture processing unit: the chip in the NES that turns tiles into the image on the screen.
  2. What is a memory-mapped register?
    AnswerAn address that is not memory at all, but a doorway to another device.
  3. What is the name table?
    AnswerA grid of bytes, one for each tile-sized cell of the screen, that says which tile to show in that cell.
  4. Why does the program write to $2006 twice?
    AnswerA PPU address is two bytes and one write carries one byte: high byte first, then low.
  5. In draw, what do px / 8 and px % 8 each tell us?
    Answerpx / 8 is which cell of the grid the pixel is in; px % 8 is which pixel inside that cell's tile.

Next time

You have a skeleton with every bone in the right place: a processor, a memory, a cartridge loader and the start of a picture chip. The second half of the course grows it, by the same small steps, into an emulator you can play a game on. Right now the picture is a strip of text in a terminal. In Part 9 we open a real window and fill it with real pixels.