Last time we opened a window. The emulator works, but it is one file with a cartridge loader, a processor, a picture chip and a window all in a row. Today adds no new ability at all. We put each of those in its own file, so that the next ten parts have somewhere to grow. It is a short part, and a necessary one.
By the end of this part
- The code is in four files: one per chip, one for the cartridge, and
main.rsto connect them. - You decide, with one keyword, what each file lets the others see.
- The cartridge to run is named on the command line.
Cut along the seams
The last exercise asked you to label each chunk of main.rs. Those labels are the files we want:
main.rs.In Rust each of those files is a module. What is a module? A module is a named group of code, usually one file, with its own inside and outside.
Move the PPU out
Start with the easiest one. Create a new file, src/ppu.rs, and move into it everything about the PPU: the WIDTH, HEIGHT and GREYS constants, tile_pixel, struct Ppu and its impl. Then tell main.rs that the file exists, with one line at the very top:
mod ppu;
Build it, and Rust objects. Among the errors is this one:
error[E0616]: field `frame` of struct `Ppu` is private
--> src/main.rs:30:42
|
30 | .update_with_buffer(&cpu.ppu.frame, ppu::WIDTH, ppu::HEIGHT)
| ^^^^^ private field
Nothing was private five minutes ago. What changed is that frame now lives in a different module from the code that uses it, and in Rust everything inside a module is hidden from the outside unless you say otherwise. You say otherwise with the keyword pub. What does pub do? pub, short for public, marks one item as visible from outside its module.
So go through ppu.rs and put pub on exactly the things the rest of the program needs, and on nothing else:
// The NES screen, in pixels.
pub const WIDTH: usize = 256;
pub 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 colour (0 to 3) of one pixel of one tile.
fn tile_pixel(chr: &[u8], tile: usize, x: usize, y: usize) -> u8 {
let lo = chr[tile * 16 + y];
let hi = chr[tile * 16 + y + 8];
let shift = 7 - x;
let lo_bit = (lo >> shift) & 1;
let hi_bit = (hi >> shift) & 1;
hi_bit * 2 + lo_bit
}
pub struct Ppu {
vram: [u8; 0x4000],
addr: u16,
pub frame: Vec<u32>,
}
impl Ppu {
pub fn new() -> Ppu { ...
Look at what did not get a pub: GREYS, tile_pixel, and the fields vram and addr. No code outside this file can touch the PPU's memory any more, except through the methods we chose to open. In Part 8 we promised ourselves to go through write_addr and write_data. Now the compiler holds us to it.
The processor and the cartridge
Do the same for the processor: move struct Cpu and its impl to src/cpu.rs. The Cpu has a Ppu inside it, so this file must say where to find that type. Its first line is:
use crate::ppu::Ppu;Read it as a path: start at the top of our own crate, go into the module ppu, and bring in the name Ppu. Then add pub to the struct, to its ppu field, and to new, load, reset and run.
The cartridge code was loose lines in main. It deserves a struct of its own:
use std::fs;
// Everything we need from a .nes file.
pub struct Cartridge {
pub prg: Vec<u8>,
pub chr: Vec<u8>,
}
impl Cartridge {
pub fn load(path: &str) -> Cartridge {
let rom: Vec<u8> = fs::read(path).expect("could not read the cartridge file");
if rom[0..4] != [0x4E, 0x45, 0x53, 0x1A] {
panic!("this is not a NES cartridge file");
}
let prg_size = rom[4] as usize * 16384;
let chr_size = rom[5] as usize * 8192;
let prg = rom[16..16 + prg_size].to_vec();
let chr = rom[16 + prg_size..16 + prg_size + chr_size].to_vec();
Cartridge { prg, chr }
}
}One thing is new. In Part 6, prg was a slice borrowed from rom. But rom is a local variable, gone when load returns, and a Cartridge has to outlive it. So .to_vec() copies each slice into a fresh Vec that the Cartridge owns. Borrow when you are only looking; own when you need to keep.
What is left in main
mod cartridge;
mod cpu;
mod ppu;
use cartridge::Cartridge;
use cpu::Cpu;
use minifb::{Key, Scale, Window, WindowOptions};
use std::env;
fn main() {
let path = env::args().nth(1).expect("usage: nes <file.nes>");
let cart = Cartridge::load(&path);
let mut cpu = Cpu::new();
cpu.load(&cart.prg);
cpu.ppu.load_chr(&cart.chr);
cpu.reset();
cpu.run();
cpu.ppu.draw();
let mut options = WindowOptions::default();
options.scale = Scale::X2;
let mut window =
Window::new("NES", ppu::WIDTH, ppu::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, ppu::WIDTH, ppu::HEIGHT)
.expect("could not draw to the window");
}
}Thirty-odd lines that read almost like a description of the machine: load a cartridge, give its two halves to the two chips, reset, run, draw, show.
The first line of main answers an exercise from Part 6. env::args() is the list of words on the command line, and .nth(1) asks for the one after the program's name. There might not be one, so the answer comes wrapped in an Option. What is an Option? An Option is a value that is either Some with a thing inside, or None. Like the Result from Part 6, it has an .expect that unwraps it or stops with a message:
$ cargo run -q
thread 'main' (163418) panicked at src/main.rs:11:35:
usage: nes <file.nes>
From now on the cartridge is named when you run. Copy the course's whole code/roms folder into your project folder; it holds every cartridge the rest of the course uses. Words after a -- are passed to our program and not to cargo:
$ cargo run -q -- roms/hello.nes
The same window as last time opens. Nothing has changed, which is the whole point of a tidy-up.
Shortcuts we took on purpose
mainstill copies the cartridge's halves into the chips by hand. Fixed in Part 11, where the Cpu takes the whole Cartridge.
What changed today
ppu.rs,cpu.rsandcartridge.rseach hold one part of the machine;main.rsdeclares them withmod.pubmarks what each module shows to the others. Everything else is private.- A
Cartridgestruct owns the two halves of the file. - The cartridge's file name comes from the command line.
Now you
- In
main, try to printcpu.ppu.addr. Read the error. Then decide: should you add apub, or was the compiler right to stop you? - Remove the
pubfromfn resetincpu.rsand build. The error has a different number from the one above. What does it say is private this time? - The
romsfolder has a cartridge callednestest.nes, written by an emulator author to test processors. Run your emulator on it. You get an empty black window and no error. Add a line tomainto printcart.prg.len(), and compare withhello.nes. Can you explain the black window from that one number? Part 11 starts here.Hint
Where doesloadput the program's last byte? And where doesresetlook for the reset vector?
Check your understanding
- What is a module?
Answer
A named group of code, usually one file, with its own inside and outside. - What does
pubdo?Answer
It marks one item as visible from outside its module. Without it, the item is private. - What is an Option?
Answer
A value that is eitherSomewith a thing inside, orNone. - Why does
Cartridge::loadcall.to_vec()?Answer
A slice only borrows fromrom, which disappears when the function returns. The Cartridge needs copies that it owns.
Next time
Right now our emulator has only ever run a cartridge that I wrote to suit it. In Part 11 we feed it a cartridge written to test real emulators, find out why it shows nothing, and build the tool that will guide the next three parts.