"""
=============================================================================
Lecture 1 · 脚本 04：为什么是三角形？怎样判断一个像素在不在里面？（讲义 §6）
=============================================================================

【这个脚本要回答的问题】
    1. 怎样判断一点在三角形内？（三个半平面同时成立：三个边函数同号）
    2. 要检查多少个像素？（全屏、包围盒、实际覆盖，差多少）
    3. 为什么图形学执着于三角形？（三点必共面；四边形可以不共面，也可以是凹的）
    4. 只采样像素中心够吗？采样越多就一定越准吗？（覆盖比例的误差随采样数怎样下降）

【运行】python3 04_triangles_and_coverage.py        （不到 1 秒）
【输出】out/04_coverage.png：1×1、2×2、4×4、精确 四种覆盖比例，放大显示
"""

import os

import numpy as np

import console
import course_path
import image_io
import raster2d


def section_point_in_triangle():
    """第 1 节：用具体的点走一遍边函数的符号。"""
    console.print_header("1. 点在三角形内 ⟺ 三个边函数同号")
    tri = np.array([[2.0, 1.0], [10.0, 3.0], [4.0, 9.0]])
    (ax, ay), (bx, by), (cx, cy) = tri
    print(f"  三角形 A={tri[0].tolist()}, B={tri[1].tolist()}, C={tri[2].tolist()}")
    rows = []
    for name, (px, py) in [("内部", (5.0, 4.0)), ("外部（AB 外侧）", (8.0, 1.0)), ("外部（CA 外侧）", (1.0, 5.0)),
                           ("恰好在边 AB 上", (6.0, 2.0)), ("恰好是顶点 C", (4.0, 9.0))]:
        e0 = raster2d.edge_function(ax, ay, bx, by, px, py)
        e1 = raster2d.edge_function(bx, by, cx, cy, px, py)
        e2 = raster2d.edge_function(cx, cy, ax, ay, px, py)
        inside = (e0 >= 0 and e1 >= 0 and e2 >= 0) or (e0 <= 0 and e1 <= 0 and e2 <= 0)
        rows.append([name, f"({px:g}, {py:g})", f"{e0:+.0f}", f"{e1:+.0f}", f"{e2:+.0f}", "是" if inside else "否"])
    console.print_table(["点", "坐标", "E(A,B)", "E(B,C)", "E(C,A)", "在内部？"], rows, align=["<", "<", ">", ">", ">", "<"])
    area = raster2d.triangle_area(tri)
    print(f"\n  三条边函数在内部点上的和恒等于 2 × 面积 = {2 * area:.0f}（三个数各自除以这个和，就是第 9 讲的重心坐标）")


def section_cost():
    """
    第 2 节：扫描的开销：不同大小的三角形，全屏扫描和包围盒差多少。

    【思路】大三角形：包围盒差不多就是它自己的两倍；细长的斜三角形：包围盒几乎全是空的。
        第 8 讲介绍更聪明的做法（层次化覆盖测试）。
    """
    console.print_header("2. 要检查多少个像素：全屏 vs 包围盒 vs 实际覆盖（画面 1920×1080）")
    w, h = 1920, 1080
    cases = [("大三角形", [[100, 100], [1800, 200], [900, 1000]]),
             ("中等三角形", [[500, 400], [800, 450], [600, 700]]),
             ("小三角形（约 10 像素）", [[900.2, 500.3], [904.7, 501.1], [901.4, 504.9]]),
             ("细长的斜三角形", [[100, 100], [1800, 1000], [1810, 990]])]
    rows = []
    for name, t in cases:
        t = np.array(t, dtype=np.float64)
        x0, x1, y0, y1 = raster2d.triangle_bbox(t, w, h)
        bbox = (x1 - x0) * (y1 - y0)
        area = raster2d.triangle_area(t)
        rows.append([name, f"{w * h:,}", f"{bbox:,}", f"{area:,.0f}", f"{area / bbox * 100:.1f}%"])
    console.print_table(["三角形", "全屏测试数", "包围盒测试数", "实际覆盖（面积）", "包围盒命中率"], rows)
    print("\n  观察：任何三角形的面积最多是包围盒的一半，所以命中率不超过 50%。")
    print("        细长的斜三角形几乎全在浪费。而现代场景里的三角形又小又多，'每个三角形的固定开销'开始比'每像素开销'更要紧。")


def section_why_triangles():
    """
    第 3 节：为什么是三角形：用数字说明四边形的两个麻烦。

    【思路】① 任意三点必共面，第 4 个点可以不在同一平面上；
        ② 四边形可以是凹的，也可以有多种切法，切法不同，着色结果就不同。
    """
    console.print_header("3. 为什么是三角形：四边形不一定是平的，也没有唯一的插值")
    quad = np.array([[0, 0, 0], [1, 0, 0], [1, 1, 0.5], [0, 1, 0]], dtype=np.float64)
    n1 = np.cross(quad[1] - quad[0], quad[2] - quad[0])
    n2 = np.cross(quad[2] - quad[0], quad[3] - quad[0])
    n3 = np.cross(quad[1] - quad[0], quad[3] - quad[0])
    n4 = np.cross(quad[2] - quad[1], quad[3] - quad[1])
    c1 = np.dot(n1, n2) / np.linalg.norm(n1) / np.linalg.norm(n2)
    c2 = np.dot(n3, n4) / np.linalg.norm(n3) / np.linalg.norm(n4)
    print(f"  四个点 {quad.tolist()}：第 4 个点不在前三点的平面上。")
    print(f"  沿对角线 AC 切开：两个三角形的法线夹角 {np.degrees(np.arccos(c1)):.1f}°；沿对角线 BD 切开：{np.degrees(np.arccos(c2)):.1f}°")
    center_ac, center_bd = (quad[0, 2] + quad[2, 2]) / 2.0, (quad[1, 2] + quad[3, 2]) / 2.0
    print(f"  正方形中心处的高度：切 AC 是 {center_ac:.2f}，切 BD 是 {center_bd:.2f}。两种切法是**不同的曲面**：一个山脊、一个山谷。")

    # 顶点颜色的插值：同一个四边形，两种切法，中心的颜色不一样
    colors = np.array([0.0, 0.0, 1.0, 0.0])              # 只有 C 是亮的
    bright_ac = (colors[0] + colors[2]) / 2.0            # 中心在对角线 AC 上，由 A、C 插值
    bright_bd = (colors[1] + colors[3]) / 2.0            # 中心在对角线 BD 上，由 B、D 插值
    print(f"\n  顶点亮度 A=0, B=0, C=1, D=0：切 AC 时中心亮度 {bright_ac:.2f}，切 BD 时中心亮度 {bright_bd:.2f}")
    print("  三角形就没有这个问题：三个顶点确定唯一的平面，内部每一点的线性插值也是唯一的。")


def supersampling_table(tri, width, height):
    """
    算一个三角形在不同采样数下的覆盖误差，打印一张表。

    【参数】tri：3×2 数组；width、height：画面大小
    【返回】(truth, masks)：精确覆盖，以及 {n: 覆盖比例}
    【边界】RMS 只在边缘像素（0 < 真实覆盖 < 1）上统计：内部和外部的像素不管怎么采样都不会错。
    """
    truth = raster2d.exact_coverage(tri, width, height)
    edge = (truth > 0) & (truth < 1)
    area = raster2d.triangle_area(tri)
    rows, masks, previous = [], {}, None
    for n in (1, 2, 4, 8, 16, 32):
        mask = raster2d.coverage_mask(tri, width, height, n)
        masks[n] = mask
        rms = float(np.sqrt(((mask - truth) ** 2).sum() / edge.sum()))
        ratio = "" if previous is None else f"{previous / rms:.2f}"
        rows.append([f"{n}×{n}", n * n, f"{mask.sum():.2f}", f"{mask.sum() - area:+.2f}", f"{rms:.4f}", ratio])
        previous = rms
    console.print_table(["每像素采样", "采样数", "覆盖总和", "和真实面积之差", "边缘 RMS 误差", "比上一行小几倍"], rows)
    print(f"  真实面积 = {area:.2f}；边缘像素 {int(edge.sum())} 个，内部全覆盖像素 {int((truth == 1).sum())} 个。")
    return truth, masks


def section_supersampling():
    """
    第 4 节：每个像素用 n×n 个采样点估计覆盖比例，和精确答案比较。

    【思路】用多边形裁剪算出的精确覆盖作为标准答案。比较两种三角形：
        ① 普通朝向的边：规则网格的误差互相抵消，每方向采样数翻倍，误差缩小 3~4 倍；
        ② 几乎水平的边：一整行子采样点同时"翻转"，误差抵消不了，翻倍只缩小约 2 倍。
    【输出】out/04_coverage.png：n=1、2、4、精确（放大 8 倍）。
    """
    console.print_header("4. 覆盖比例：采样越多越接近真实面积，但提升的速度取决于边的朝向")
    w, h = 40, 28
    print("  ① 普通朝向的三角形：")
    tri = np.array([[3.3, 4.2], [36.6, 8.8], [12.1, 25.7]])
    truth, masks = supersampling_table(tri, w, h)
    print("\n  ② 边几乎水平、几乎竖直的三角形（只差一点点没和网格对齐）：")
    supersampling_table(np.array([[3.3, 4.2], [36.3, 4.5], [36.6, 25.7]]), w, h)
    print("\n  观察：① 每方向采样数翻倍，误差缩小 3~4 倍，好于'翻倍减半'的直觉：直边上各列的误差有正有负，互相抵消了。")
    print("        ② 边几乎和采样网格平行时，整排采样点同时越过边，抵消不起来，翻倍只缩小 2 倍左右。")
    print("        这是实际硬件把采样网格旋转一个角度（rotated grid）的原因（第 8、24 讲）。")
    print("        另外误差只来自边缘像素：内部像素的额外采样全是浪费，这是 MSAA 的出发点（第 8、12 讲）。")
    panels = [image_io.upscale(1.0 - masks[n], 8) for n in (1, 2, 4)] + [image_io.upscale(1.0 - truth, 8)]
    image_io.save_png(os.path.join(course_path.out_dir(), "04_coverage.png"), image_io.image_grid(panels, cols=2, gap=10))
    print("  输出 out/04_coverage.png：左上 1×1、右上 2×2、左下 4×4、右下精确覆盖")

    print("\n  1×1 采样（只看像素中心）的字符画，这就是最基本的光栅化：\n")
    for j in range(h):
        print("   " + "".join("#" if masks[1][j, i] > 0 else "." for i in range(w)))


def main():
    section_point_in_triangle()
    section_cost()
    section_why_triangles()
    section_supersampling()


if __name__ == "__main__":
    main()
