tuanp.dev

Part 9 of 20 · about an hour

Open a real window

Welcome to the second half. The first eight parts built a skeleton; the next twelve turn it into something you can play a game on. The steps stay the same size. Only the destination has moved.

Last time the cartridge drew its own picture, and we printed a corner of it as dots and hashes. But a NES picture is 256 by 240 pixels, far more than a terminal can show. Today the emulator opens a window and paints every one of those pixels.

By the end of this part

  • Your project uses a library written by someone else.
  • The PPU paints its picture into a block of memory, one number per pixel.
  • A window shows that picture until you close it.

Borrow a window

Opening a window means talking to the operating system, and every operating system does it differently. We will not write that ourselves. Rust programmers share code as packages called crates. What is a crate? A crate is a library of Rust code, published so that any project can use it by naming it.

The crate we want is called minifb, "mini frame buffer". It does one thing: it opens a window and shows a block of pixels in it. To use it, name it in Cargo.toml, the file cargo made for us in Part 1:

Cargo.tomlSnapshot
[package]
name = "nes"
version = "0.1.0"
edition = "2024"

[dependencies]
minifb = "0.29"

The next cargo run will download minifb and everything it depends on, and compile it all. Expect about a hundred lines of Compiling … and a wait of a minute or so. It happens once. (You need to be online for it. On Linux, if the build stops with a complaint about a missing system library, the minifb page lists the packages to install.)

A picture is a long row of numbers

What does minifb want from us? A frame buffer. What is a frame buffer? A frame buffer is a block of memory holding one number for each pixel of a picture, row after row.

A grid of pixels. The top row is numbered 0, 1, 2, 3 up to 255. The second row starts at 256. The third row starts at 512, and its fourth box, at x 3 and y 2, is highlighted and numbered 515.x = 0123255y = 0120123…255256257258259…511512513514515…767position = y × 256 + x = 2 × 256 + 3
The rows are laid end to end. To find a pixel, skip y whole rows and then go x further.

And the number in each box? A colour, written as 0xRRGGBB: two hex digits each for how much red, green and blue. 0x000000 is black, 0xFFFFFF is white, 0xFF0000 is pure red. The hex you learned in Part 1 is how every computer screen describes colour. Such a number needs more room than a byte, so we use u32, an unsigned 32-bit number.

At the top of main.rs, replace SHADES and the two VIEW constants with these:

src/main.rsSnapshot
use minifb::{Key, Scale, Window, WindowOptions};
use std::fs;

// The NES screen, in pixels.
const WIDTH: usize = 256;
const HEIGHT: usize = 240;

// Four shades of grey, as 0xRRGGBB, for the four colours of a tile.
const GREYS: [u32; 4] = [0x000000, 0x555555, 0xAAAAAA, 0xFFFFFF];

The four tile colours become four greys for now. The use minifb::{…} line brings four names from the crate into our file.

Paint instead of print

The PPU gets the frame buffer as a new field, and draw fills it where it used to print:

struct Ppu {
    vram: [u8; 0x4000],
    addr: u16,
    frame: Vec<u32>,
}

impl Ppu {
    fn new() -> Ppu {
        Ppu { vram: [0; 0x4000], addr: 0, frame: vec![0; WIDTH * HEIGHT] }
    ...
    // Paint the picture into `frame`: for every pixel, which tile is it in,
    // and which pixel of that tile?
    fn draw(&mut self) {
        for py in 0..HEIGHT {
            for px in 0..WIDTH {
                let tile = self.vram[0x2000 + (py / 8) * 32 + px / 8] as usize;
                let colour = tile_pixel(&self.vram, tile, px % 8, py % 8);
                self.frame[py * WIDTH + px] = GREYS[colour as usize];
            }
        }
    }
  • Vec<u32> is a Vec (Part 6) of colours. vec![0; WIDTH * HEIGHT] makes one with 61,440 zeros in it.
  • The two loops now cover the whole screen, 240 rows of 256, where Part 8 stopped at 24 rows of 80.
  • The last line is the picture above: row py, column px, at position py * WIDTH + px.
  • draw takes &mut self now, because it changes the PPU's own frame buffer.

Everything that decides which colour goes where is untouched: the name-table lookup and tile_pixel are exactly as they were.

Show it

At the end of main, after cpu.ppu.draw():

    let mut options = WindowOptions::default();
    options.scale = Scale::X2;
    let mut window = Window::new("NES", WIDTH, HEIGHT, options).expect("could not open a window");
    window.set_target_fps(60);

    while window.is_open() && !window.is_key_down(Key::Escape) {
        window
            .update_with_buffer(&cpu.ppu.frame, WIDTH, HEIGHT)
            .expect("could not draw to the window");
    }
}
  • Window::new opens a window. Scale::X2 makes every NES pixel two screen pixels wide and high, because 256 by 240 is tiny on a modern display.
  • while is a loop with a condition: it repeats as long as the window is open and (&&) the Escape key is not (!) down.
  • Each time round, update_with_buffer hands the window our frame buffer and lets it react to the mouse and keyboard. set_target_fps(60) makes it wait so that this happens 60 times a second and no faster.

Run it, with hello.nes in the project folder as before.

A black window with HELLO NES and a small heart in white and grey near the top left.
The same ten tiles as in Part 8, now in their real place on a full NES screen. Press Escape to close the window.

The message sits in the top-left corner because that is where the cartridge put it: row 1, column 0. The rest of the screen is tile 0, the blank one. And the heart has four shades now, where the letters have two.

Shortcuts we took on purpose

  • Greys stand in for colours. Fixed in Part 16.
  • We paint the picture once and then show the same one for ever. Fixed in Part 15.
  • main.rs is one long file holding three different things. Fixed next time.

What changed today

  • Cargo.toml names the minifb crate as a dependency.
  • The PPU owns a frame buffer, frame, and draw paints all 256 × 240 pixels into it.
  • main opens a window and shows the frame buffer until Escape is pressed.

Now you

  1. Change GREYS to four colours of your own. What is 0xFFFF00? Guess before you look.
  2. Comment out the call to cpu.ppu.draw() and predict what the window shows. Then comment out cpu.run() instead. Why are the two results the same?
  3. Write a second painting method, draw_tiles, that ignores the name table and shows all the cartridge's tiles in a grid, 32 to a row, starting with tile 0. It is a useful thing to have when a picture looks wrong.
    HintIn draw, the tile number comes from the name table. Work it out from the position instead: (py / 8) * 32 + px / 8. Only the first 16 rows hold tiles; leave the rest black.
  4. Scroll through main.rs from top to bottom and write down, for each chunk, whether it is about the cartridge, the processor, the PPU, or the window. Next time we cut along those lines.

Check your understanding

  1. What is a crate?
    AnswerA library of Rust code, published so that any project can use it by naming it in Cargo.toml.
  2. What is a frame buffer?
    AnswerA block of memory holding one number for each pixel of a picture, row after row.
  3. In a frame buffer 256 pixels wide, where is the pixel at x = 10, y = 3?
    AnswerAt position 3 × 256 + 10 = 778.
  4. What colour is 0x00FF00?
    AnswerPure green: no red, full green, no blue.

Next time

Right now everything lives in one file of about 230 lines, and it is about to grow fast. In Part 10 we split it into one file per chip, and learn how Rust decides who may touch what.