271. 帧缓冲像素访问

添加简单的帧缓冲像素访问辅助函数。

271 / 356 · tests/chapter_05_rendering_pipeline/test_271_framebuffer_pixel_access.py

待更新的文件

emulator/rendering/framebuffer.py

为什么需要这一步

帧缓冲现在存储的是一个扁平的 RGB 像素列表。渲染代码不应该到处重复扁平索引公式,因此 Framebuffer 暴露了两个小巧的辅助方法:

get_pixel(x, y) -> RGBColor
set_pixel(x, y, color) -> None

什么是扁平像素索引?扁平索引把二维图像坐标存储在一维列表中。

公式

index = y * width + x

宽度为 width = 4 的最小示例:

(x=0, y=0) -> index 0
(x=1, y=0) -> index 1
(x=0, y=1) -> index 4
(x=2, y=1) -> index 6

建议的实现示例

class Framebuffer:
    ...

    def get_pixel(self, x: int, y: int) -> RGBColor:
        return self.pixels[y * self.width + x]

    def set_pixel(self, x: int, y: int, color: RGBColor) -> None:
        self.pixels[y * self.width + x] = color

重要的简化

本教程步骤有意让这些辅助方法保持简单。将来我们可以为以下内容添加校验:

x/y out of bounds
negative coordinates
RGB tuple length
RGB component byte range 0-255

目前,测试只使用有效坐标和有效 RGB 颜色。

本步骤不涉及

  • 坐标校验
  • RGB 校验
  • 调色板查找
  • 渲染图案表
  • 渲染名称表
  • pygame 显示

运行本课

uv run pytest tests/chapter_05_rendering_pipeline/test_271_framebuffer_pixel_access.py -v