307. 合成背景与精灵

把背景和精灵合成到一个帧缓冲中。

307 / 356 · tests/chapter_09_sprite_rendering/test_307_composite_background_and_sprites.py

需要创建的文件

emulator/rendering/frame_compositor.py

为什么需要这一步

模拟器现在既能渲染背景帧缓冲数据,又能把 OAM 精灵渲染进帧缓冲。这一步把这两条路径结合起来:

background framebuffer + OAM sprites -> final framebuffer

重要的设计选择

合成器应该返回一个新的 Framebuffer,不应修改原始的背景帧缓冲。这样这个函数更易于推理,也更易于测试。

建议的实现示例

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

本步骤不涉及的内容

  • 精灵在背景后面的优先级
  • sprite 0 hit
  • sprite overflow
  • 8x16 精灵
  • Console 集成
  • pygame

运行本课

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