307. Composite background and sprites

Composite background and sprites into one framebuffer.

Lesson 307 of 356 · tests/chapter_09_sprite_rendering/test_307_composite_background_and_sprites.py

File to create

emulator/rendering/frame_compositor.py

Why this step exists

The emulator can now render background framebuffer data and render OAM sprites into a framebuffer. This step combines those paths:

background framebuffer + OAM sprites -> final framebuffer

Important design choice

The compositor should return a new Framebuffer. It should not mutate the original background framebuffer. This makes the function easier to reason about and easier to test.

Suggested implementation example

from emulator.rendering.framebuffer import Framebuffer
from emulator.rendering.palette_ram import SpritePalettes
from emulator.rendering.sprite_renderer import render_oam_sprites_to_framebuffer


def composite_background_and_sprites(
    background: Framebuffer,
    oam: bytes | bytearray,
    pattern_table: bytes,
    sprite_palettes: SpritePalettes,
) -> Framebuffer:
    framebuffer = Framebuffer(
        width=background.width,
        height=background.height,
        pixels=list(background.pixels),
    )

    render_oam_sprites_to_framebuffer(
        framebuffer,
        oam,
        pattern_table,
        sprite_palettes,
    )

    return framebuffer

Out of scope

  • sprite priority behind background
  • sprite 0 hit
  • sprite overflow
  • 8x16 sprites
  • Console integration
  • pygame

Run this lesson

uv run pytest tests/chapter_09_sprite_rendering/test_307_composite_background_and_sprites.py -v