"""
=============================================================================
Lecture 1 · 脚本 01：一张图到底是什么？（讲义 §3）
=============================================================================

【这个脚本要回答的问题】
    1. 在内存里，一张图是什么？（一个数组，下标先行后列，原点在左上角）
    2. 图片文件里有什么？（亲手拆开自己写的 PNG，看它的每个部分）
    3. 为什么实时图形这么难？（算一笔账：4K 60 帧，留给每个像素的时间有多少）
    4. 为什么每个通道用 8 位？（少了会出现色带）
    5. 一个像素是一个小方块吗？（不是，它只是一个采样值；同样的数字可以重建出不同的图）

【运行】python3 01_what_is_an_image.py        （约 1 秒）
【输出】out/01_gradient.png、out/01_bit_depth.png、out/01_pixel_not_square.png
"""

import os
import struct

import numpy as np

import console
import course_path
import image_io


def section_array():
    """
    第 1 节：手工造一张 4×3 的小图，把数组内容原样打印出来。

    【思路】先让读者看到"图就是数字"，再看同一批数字在内存里怎样线性排列。
    【返回】这张小图（后面拆 PNG 时会用）
    """
    console.print_header("1. 一张图就是一个数组 img[y, x, c]")
    img = image_io.new_image(4, 3, (0, 0, 0))     # 宽 4、高 3，数组形状是 (3, 4, 3)！
    img[0, 0] = (255, 0, 0)                       # 第 0 行第 0 列（左上角）：红
    img[0, 3] = (0, 255, 0)                       # 第 0 行第 3 列（右上角）：绿
    img[2, 0] = (0, 0, 255)                       # 第 2 行第 0 列（左下角）：蓝
    img[2, 3] = (255, 255, 255)                   # 第 2 行第 3 列（右下角）：白
    print(f"  宽 4、高 3 的 RGB 图：数组形状 {img.shape}（注意高度在前），每个元素 {img.dtype}")
    print("  四个角的像素：")
    rows = [["左上 img[0,0]", tuple(int(v) for v in img[0, 0])], ["右上 img[0,3]", tuple(int(v) for v in img[0, 3])],
            ["左下 img[2,0]", tuple(int(v) for v in img[2, 0])], ["右下 img[2,3]", tuple(int(v) for v in img[2, 3])]]
    console.print_table(["位置", "(R, G, B)"], rows)
    x, y = 3, 2
    offset = (y * img.shape[1] + x) * 3
    print(f"\n  在内存里所有像素连成一条线（一行接一行）：像素 (x={x}, y={y}) 的红色分量在第")
    print(f"    (y·宽 + x)·3 = ({y}×{img.shape[1]} + {x})×3 = {offset} 个字节；内容 = {int(img.tobytes()[offset])}")
    print(f"  整张图占 宽×高×3 = {img.size} 字节，tobytes() 的长度 = {len(img.tobytes())}")
    return img


def section_png(tiny):
    """
    第 2 节：把小图写成 PNG，再把文件一块一块拆开看。

    【思路】不靠任何库读懂自己写的文件，并用 Pillow（如果装了）交叉验证：别的软件也能读，读出来的像素一致。
    【参数】tiny：第 1 节的小图
    【边界】Pillow 没装时跳过交叉验证，不影响其他部分。
    """
    console.print_header("2. 拆开一个 PNG 文件：图片文件没有任何魔法")
    path = os.path.join(course_path.out_dir(), "01_tiny.png")
    image_io.save_png(path, tiny)
    with open(path, "rb") as f:                    # with 语句保证文件用完自动关闭
        data = f.read()
    print(f"  文件总长 {len(data)} 字节，前 8 个字节（签名）：{data[:8].hex(' ')}")
    pos, rows = 8, []
    while pos < len(data):
        length = struct.unpack(">I", data[pos:pos + 4])[0]
        kind = data[pos + 4:pos + 8].decode("ascii")
        rows.append([kind, length, data[pos + 8:pos + 8 + length][:13].hex(" ") or "（空）"])
        pos += 12 + length
    console.print_table(["块类型", "数据长度", "数据开头（十六进制）"], rows, align=["<", ">", "<"])
    width, height = struct.unpack(">II", data[16:24])
    print(f"\n  IHDR 的前 8 个字节就是宽和高：宽 = {width}，高 = {height}")
    back = image_io.load_png(path)
    print(f"  自己写、自己读，逐字节相同？ {np.array_equal(back, tiny)}（PNG 是无损的）")
    try:
        from PIL import Image
        other = np.asarray(Image.open(path).convert("RGB"))
        print(f"  Pillow 读这个文件，像素和原图相同？ {np.array_equal(other, tiny)}（说明我们写的是真正合法的 PNG）")
    except ImportError:
        print("  （没有安装 Pillow，跳过交叉验证）")

    # 压缩率取决于"内容有没有规律"，而且要先把规律暴露出来：PNG 的滤波步骤就是干这个的
    w, h = 256, 256
    xx, yy = np.meshgrid(np.arange(w) / (w - 1), np.arange(h) / (h - 1))
    gradient = image_io.to_uint8(np.stack([xx, yy, 1.0 - xx], axis=-1))
    noise = np.random.default_rng(1).integers(0, 256, size=(h, w, 3), dtype=np.uint8)
    raw = w * h * 3
    rows = []
    for name, picture in [("平滑渐变", gradient), ("纯随机噪声", noise)]:
        for kind, label in [(0, "不滤波"), (1, "减左边 Sub"), (2, "减上边 Up")]:
            p = os.path.join(course_path.out_dir(), "01_compress_test.png")
            image_io.save_png(p, picture, filter_kind=kind)
            assert np.array_equal(image_io.load_png(p), picture)      # 换了滤波，像素依然一字不差
            size = os.path.getsize(p)
            rows.append([name, label, raw, size, f"{raw / size:.1f} 倍"])
        os.remove(p)
    image_io.save_png(os.path.join(course_path.out_dir(), "01_gradient.png"), gradient, filter_kind=1)
    print()
    console.print_table(["256×256 的图", "滤波", "原始字节", "PNG 字节", "压缩率"], rows, align=["<", "<", ">", ">", ">"])
    print("\n  观察：渐变不滤波几乎压不动（相邻字节都不同，没有重复可压）；减一下邻居，差值几乎全相同，立刻压缩很多倍。")
    print("        噪声怎么滤波都压不动：真正随机的数据不存在规律。文件还会比原始数据略大一点（文件头 + 压缩格式开销）。")


def section_budget():
    """
    第 3 节：算实时图形的预算。

    【思路】每秒要算多少像素？一颗 3 GHz 的核心平均每个像素分到几个时钟周期？
        假设一个光照计算至少要几十条指令，就能看出为什么单靠一个 CPU 核心做不到。
    【边界】这里的 3 GHz、每个像素算一次都是简化假设；真实场景还有重绘（overdraw）和超采样，只会更紧张。
    """
    console.print_header("3. 算一笔账：留给每个像素的时间")
    formats = [("VGA 640×480", 640, 480, 30), ("1080p", 1920, 1080, 60), ("1440p", 2560, 1440, 144),
               ("4K", 3840, 2160, 60), ("8K", 7680, 4320, 60)]
    rows = []
    for name, w, h, hz in formats:
        pixels = w * h
        rate = pixels * hz
        bytes_per_second = rate * 3
        ns = 1e9 / rate
        cycles = 3e9 / rate
        rows.append([name, f"{hz} Hz", f"{pixels / 1e6:.2f} M", f"{pixels * 3 / 1e6:.1f} MB",
                     f"{rate / 1e6:.0f} M/s", f"{bytes_per_second / 1e9:.2f} GB/s", f"{ns:.2f} ns", f"{cycles:.1f}"])
    console.print_table(["格式", "刷新率", "像素数", "一帧大小", "像素速率", "数据速率", "每像素时间", "3GHz 周期数"], rows)
    print("\n  观察：4K 60 Hz 时，一颗 3 GHz 核心平均每个像素只有约 6 个时钟周期——几条指令就用完了。")
    print("        这还没算三角形处理、纹理读取，以及一个像素被画很多遍的情况。这就是 GPU 存在的理由（§8）。")


def section_bit_depth():
    """
    第 4 节：每通道的位数和色带。

    【思路】同一条渐变分别量化成 8、5、3、2 位，再放回 0~255 显示。位数越少台阶越宽，
        人眼对平滑渐变里的台阶非常敏感（马赫带效应）。
    【输出】out/01_bit_depth.png，从上到下依次是 8、5、3、2 位。
    """
    console.print_header("4. 为什么是每通道 8 位：色带（banding）")
    w, h = 512, 56
    ramp = np.tile(np.linspace(0.0, 1.0, w), (h, 1))
    strips, rows = [], []
    for bits in (8, 5, 3, 2):
        levels = 2 ** bits
        q = np.floor(ramp * (levels - 1) + 0.5) / (levels - 1)
        strips.append(q)
        distinct = len(np.unique(q))
        rows.append([f"{bits} 位", levels, f"{levels ** 3:,}", distinct, f"{w / distinct:.1f}"])
    console.print_table(["每通道", "灰阶数", "RGB 能表示的颜色数", "这条渐变实际用到的灰阶", "每个台阶的宽度（像素）"], rows)
    image_io.save_png(os.path.join(course_path.out_dir(), "01_bit_depth.png"), image_io.image_grid(strips, cols=1))
    print("\n  输出 out/01_bit_depth.png：从上到下 8、5、3、2 位。8 位时一个台阶约 2 个像素，肉眼几乎分不出。")
    print("  但 8 位也不是绝对够：大面积的暗部渐变（夜空、阴影）依然可能看到色带，这是 HDR 用 10 位的原因之一。")


def bilinear_reconstruct(samples, k):
    """
    用双线性插值把采样值重建成放大 k 倍的图。

    【思路】把每个采样值当作"所在像素中心"的高度，中间的位置取四个邻居的加权平均，权重和距离成线性关系。
    【参数】samples：h×w 的数组；k：放大倍数（正整数）
    【返回】(h·k)×(w·k) 的数组
    【边界】超出最外圈采样中心的位置，用最近的采样值（夹到边上）。
    """
    h, w = samples.shape
    ys = np.clip((np.arange(h * k) + 0.5) / k - 0.5, 0, h - 1)
    xs = np.clip((np.arange(w * k) + 0.5) / k - 0.5, 0, w - 1)
    y0, x0 = np.minimum(ys.astype(int), h - 2), np.minimum(xs.astype(int), w - 2)
    fy, fx = (ys - y0)[:, None], (xs - x0)[None, :]
    a = samples[np.ix_(y0, x0)]
    b = samples[np.ix_(y0, x0 + 1)]
    c = samples[np.ix_(y0 + 1, x0)]
    d = samples[np.ix_(y0 + 1, x0 + 1)]
    return (1 - fy) * ((1 - fx) * a + fx * b) + fy * ((1 - fx) * c + fx * d)


def section_pixel_not_square():
    """
    第 5 节：一个像素不是一个小方块。

    【思路】同样 8×8 个数字（一个光滑的亮斑的采样值），用两种规则"重建"成连续的图像：
        最近邻（每个数字铺满一个方块）和双线性。数字没变，看到的东西变了——
        所以像素只是**采样值**，"方块"只是显示时的一种重建方式。第 8 讲会把它讲透。
    【输出】out/01_pixel_not_square.png：左边最近邻，右边双线性。
    """
    console.print_header("5. 一个像素不是一个小方块（A Pixel Is Not A Little Square）")
    n = 8
    xx, yy = np.meshgrid(np.arange(n) + 0.5, np.arange(n) + 0.5)
    samples = np.exp(-((xx - 3.6) ** 2 + (yy - 4.4) ** 2) / 5.0)
    k = 32
    nearest = image_io.upscale(samples, k)
    smooth = bilinear_reconstruct(samples, k)
    image_io.save_png(os.path.join(course_path.out_dir(), "01_pixel_not_square.png"),
                      image_io.image_grid([nearest, smooth], gap=10))
    print("  8×8 个采样值（只显示前 3 行，保留两位小数）：")
    for j in range(3):
        print("    " + " ".join(f"{v:.2f}" for v in samples[j]))
    # 用两种重建回到采样点上，都应该得到原来的数字：它们是同一批数据的两种解读
    back_nearest = nearest[k // 2::k, k // 2::k]
    print(f"\n  最近邻重建在采样点处和原数字的最大差：{np.abs(back_nearest - samples).max():.4f}")
    print(f"  两种重建的最大差异：{np.abs(nearest - smooth).max():.3f}（满量程是 1）")
    print("  输出 out/01_pixel_not_square.png：左边最近邻（方块），右边双线性（光滑）。8×8 个数字完全相同。")


def main():
    tiny = section_array()
    section_png(tiny)
    section_budget()
    section_bit_depth()
    section_pixel_not_square()


if __name__ == "__main__":
    main()
