248. Oam memory and oamdata

Implement OAM memory and OAMADDR/OAMDATA behavior.

Lesson 248 of 356 · tests/chapter_03_ppu_memory_and_graphics_data/test_248_oam_memory_and_oamdata.py

References

https://www.nesdev.org/wiki/PPU_registers#OAMADDR
https://www.nesdev.org/wiki/PPU_registers#OAMDATA
https://www.nesdev.org/wiki/PPU_OAM

File to update

emulator/ppu/ppu.py

State to add

OAM_SIZE = 256
oam: bytearray = field(default_factory=lambda: bytearray(OAM_SIZE))

Why this step exists

OAM means Object Attribute Memory. It is the PPU's internal 256-byte sprite memory. The PPU renders sprites from OAM, not directly from CPU RAM.

Sprite layout

NES OAM stores 64 sprites.
Each sprite uses 4 bytes.

64 sprites * 4 bytes = 256 bytes

Basic sprite byte layout

byte 0: Y position
byte 1: tile index
byte 2: attributes
byte 3: X position

CPU-visible registers

$2003 OAMADDR
    selects which OAM byte is currently addressed

$2004 OAMDATA
    reads/writes OAM at the current OAMADDR

Important behavior for this step

  • writing $2003 sets oam_addr
  • writing $2004 stores into oam[oam_addr]
  • writing $2004 increments oam_addr with & 0xFF
  • reading $2004 returns oam[oam_addr]

Why OAM is not PpuBus VRAM

PpuBus handles the PPU address space used by PPUADDR/PPUDATA

$0000-$3FFF

OAM is separate internal sprite memory accessed through OAMADDR/OAMDATA

$2003/$2004

Suggested implementation pseudocode

OAM_SIZE = 256

@dataclass
class PPU:
    ...
    oam_addr: int = 0
    oam_data: int = 0
    oam: bytearray = field(default_factory=lambda: bytearray(OAM_SIZE))

    def write_register(self, addr: int, value: int) -> None:
        value = value & 0xFF

        match addr:
            ...
            case 0x2003:
                self.oam_addr = value

            case 0x2004:
                # Preserve old compatibility/debug field.
                self.oam_data = value

                # Write to current OAM byte.
                self.oam[self.oam_addr] = value

                # OAMADDR increments after OAMDATA write.
                self.oam_addr = (self.oam_addr + 1) & 0xFF

            ...

    def read_register(self, addr: int) -> int:
        match addr:
            ...
            case 0x2004:
                self.oam_data = self.oam[self.oam_addr]
                return self.oam_data

Out of scope

  • OAMDMA at $4014
  • sprite evaluation
  • sprite rendering
  • sprite overflow behavior
  • sprite 0 hit behavior

Run this lesson

uv run pytest tests/chapter_03_ppu_memory_and_graphics_data/test_248_oam_memory_and_oamdata.py -v