"""
=============================================================================
Lecture 1 · 脚本 08：整门课的预告片：四个组成部分各来一小段（讲义 §2、§9）
=============================================================================

【这个脚本要回答的问题】
    课程的四次大作业对应图形学的四个组成部分：光栅化、几何、渲染、动画。
    各用几十行代码做一个最小版本，让你先看到这门课要去哪里：
        A. 光栅化：05 脚本已经做了，这里直接用它的结果
        B. 几何：从 8 个三角形的八面体细分出球；用数字看"面越多，越接近真实的球"
        C. 渲染：一个极简的路径追踪器。光在场景里反弹，自动得到软阴影和颜色渗透（color bleeding）
        D. 动画：几个关键帧 + 样条插值 = 一段连续运动

【运行】python3 08_course_preview.py          （约 30 秒）
       python3 08_course_preview.py --quick  （不到 1 秒，低采样数，只确认能运行）
【输出】out/08_geometry.png、out/08_pathtrace_*.png、out/08_animation.png/.gif、out/08_course_preview.png

【边界】
    - 这里的路径追踪器只有漫反射和两种几何体（平面、球），是预告片，不是第 21–24 讲的完整实现；
    - 这些代码是 Python 教学实现，和课程作业 Scotty3D 的 C++ 框架无关，也不是它的答案。
"""

import os
import sys
import time

import numpy as np

import console
import course_path
import image_io
import meshes
import mini_pipeline as mp
import transforms as tf


# =============================================================================
# B. 几何
# =============================================================================

def section_geometry():
    """
    把八面体细分 0、1、2、4 次，比较面数、和真实球的体积差，并渲染成图。

    【思路】几何处理的最小例子：同样的算法反复用，由粗到细。
    【返回】拼好的图（后面放进总览图）
    """
    console.print_header("B. 几何：一个八面体 → 一个球（Geometry）")
    camera = mp.Camera(eye=(1.6, 1.3, 3.2), target=(0, 0, 0), fovy_deg=36.0)
    mesh = meshes.octahedron()
    level = 0
    panels, rows = [], []
    truth = 4.0 / 3.0 * np.pi
    for target in (0, 1, 2, 4):
        while level < target:
            mesh = meshes.subdivide_to_sphere(mesh)
            level += 1
        volume = meshes.signed_volume(mesh)
        rows.append([level, f"{len(mesh.positions):,}", f"{len(mesh.faces):,}", f"{volume:.4f}", f"{(volume - truth) / truth * 100:+.2f}%"])
        flat = meshes.flat_shaded(mesh)
        fb, _ = mp.render([mp.Draw(flat, np.eye(4), mp.fs_lambert, {"color": (0.75, 0.55, 0.25), "light_dir": mp.SCENE_LIGHT})],
                          camera, 200, 200, clear_color=(0.95, 0.95, 0.95))
        panels.append(image_io.to_uint8(image_io.srgb_encode(fb.color)))
    console.print_table(["细分次数", "顶点数", "三角形数", "体积", "和真实球的相对误差"], rows)
    print(f"\n  真实的单位球体积 = {truth:.4f}。每细分一次面数翻 4 倍，误差缩小到约 1/4（第 15 讲讲真正的细分曲面）。")
    sheet = image_io.image_grid(panels, cols=4)
    image_io.save_png(os.path.join(course_path.out_dir(), "08_geometry.png"), sheet)
    return sheet


# =============================================================================
# C. 渲染：极简路径追踪器
# =============================================================================
#
# 场景：一个"康奈尔盒"风格的房间，左墙红、右墙绿、其余白，天花板上有一块长方形灯，房间里有两个白球。
# 整个追踪器只有 3 个函数：nearest_hit（光线最先碰到什么）、cosine_hemisphere（往哪个方向反弹）、trace（循环反弹）。

BOX = {"x0": -1.0, "x1": 1.0, "y0": 0.0, "y1": 2.0, "z0": -1.0, "z1": 3.2}
SPHERES = np.array([[-0.45, 0.42, -0.2, 0.42], [0.48, 0.32, 0.45, 0.32]])    # 每行：cx, cy, cz, r
LIGHT_RECT = (-0.45, 0.45, -0.1, 0.8)                                         # 灯在天花板上的范围 x0, x1, z0, z1
LIGHT_POWER = 9.0
CAMERA_EYE, CAMERA_FOVY = (0.0, 1.0, 3.1), 44.0                               # 相机位置、竖直视场角
WHITE, RED, GREEN = np.array([0.75, 0.75, 0.75]), np.array([0.70, 0.12, 0.10]), np.array([0.14, 0.60, 0.16])


def nearest_hit(origins, directions):
    """
    对一批光线，找出每条光线最先碰到的表面。

    【思路】房间是 6 个轴对齐平面，房间内的光线一定会碰到其中之一；再和每个球比较，取最小的 t。
    【参数】origins、directions：N×3（directions 是单位向量）
    【返回】(points, normals, albedo, emission)：都是 N×3 数组
    【边界】
        - 轴平行时分母为 0，这一维的 t 记为 inf；
        - 法线一律朝向房间内部（平面）或球外，光线不会从球的内部出发，因为反弹点沿法线抬高了一点。
    """
    n = len(origins)
    best = np.full(n, np.inf)
    normals = np.zeros((n, 3))
    albedo = np.tile(WHITE, (n, 1))

    # ---- 房间的 6 个平面 ----
    planes = [(0, BOX["x0"], (1, 0, 0), RED), (0, BOX["x1"], (-1, 0, 0), GREEN),
              (1, BOX["y0"], (0, 1, 0), WHITE), (1, BOX["y1"], (0, -1, 0), WHITE),
              (2, BOX["z0"], (0, 0, 1), WHITE), (2, BOX["z1"], (0, 0, -1), WHITE)]
    for axis, value, normal, color in planes:
        d = directions[:, axis]
        t = np.divide(value - origins[:, axis], d, out=np.full(n, np.inf), where=d != 0.0)
        closer = (t > 1e-6) & (t < best)
        best[closer] = t[closer]
        normals[closer] = normal
        albedo[closer] = color

    # ---- 球：解 |o + t·d − c|² = r² 的一元二次方程 ----
    for cx, cy, cz, r in SPHERES:
        oc = origins - np.array([cx, cy, cz])
        half_b = (oc * directions).sum(axis=1)
        c = (oc * oc).sum(axis=1) - r * r
        disc = half_b * half_b - c
        hit = disc > 0.0
        t = np.full(n, np.inf)
        t[hit] = -half_b[hit] - np.sqrt(disc[hit])       # 取近的那个根
        closer = (t > 1e-6) & (t < best)
        best[closer] = t[closer]
        normals[closer] = (origins[closer] + t[closer, None] * directions[closer] - np.array([cx, cy, cz])) / r
        albedo[closer] = WHITE

    points = origins + best[:, None] * directions
    # 自发光：碰到天花板，且落在灯的长方形范围内，且法线朝下
    x0, x1, z0, z1 = LIGHT_RECT
    is_light = (normals[:, 1] < -0.5) & (np.abs(points[:, 1] - BOX["y1"]) < 1e-6) \
        & (points[:, 0] > x0) & (points[:, 0] < x1) & (points[:, 2] > z0) & (points[:, 2] < z1)
    emission = np.zeros((n, 3))
    emission[is_light] = LIGHT_POWER
    return points, normals, albedo, emission


def cosine_hemisphere(normals, rng):
    """
    在法线方向的半球上按余弦分布采样方向（越靠近法线的方向越容易被选中）。

    【为什么要余弦分布】漫反射的光照贡献正比于 cos θ。如果采样的概率也正比于 cos θ，
        Monte Carlo 估计里的 cos θ 就被约掉了，方差更小（第 22 讲的重要性采样）。
    【参数】normals：N×3 单位向量；rng：numpy 随机数发生器
    【返回】N×3 单位向量
    【边界】用"单位球上的随机点 + 法线再归一化"的办法，比建坐标系简单；随机点恰好等于 −n 的概率为 0。
    """
    v = rng.normal(size=normals.shape)
    v /= np.linalg.norm(v, axis=1, keepdims=True)
    d = normals + v
    return d / np.maximum(np.linalg.norm(d, axis=1, keepdims=True), 1e-12)


def trace(origins, directions, bounces, rng):
    """
    路径追踪：让每条光线在场景里反弹最多 bounces 次，把路上碰到的光加起来。

    【思路】这就是渲染方程（第 21 讲）的 Monte Carlo 解法。throughput 记录"还能传回多少比例的光"，
        每次碰到表面就乘上表面的反照率（因为按余弦分布采样，其他项都约掉了）。
    【参数】origins、directions：N×3；bounces：最多走几段路径；rng：随机数发生器
    【返回】N×3 的辐射亮度估计
    【边界】bounces 有限，所以严格说有一点偏差（比真实结果略暗）；反弹 5 次之后贡献已经很小。
        bounces=2 时只有"相机 → 表面 → 灯"这样的路径，也就是只有直接光照。
    """
    radiance = np.zeros_like(origins)
    throughput = np.ones_like(origins)
    o, d = origins, directions
    for _ in range(bounces):
        p, n, albedo, emission = nearest_hit(o, d)
        radiance += throughput * emission
        throughput = throughput * albedo
        d = cosine_hemisphere(n, rng)
        o = p + 1e-5 * n                          # 沿法线抬高一点，防止光线又立刻打中自己
    return radiance


def render_path(width, height, spp, bounces, seed, chunk=16):
    """
    渲染整张图。

    【思路】每个像素发射 spp 条光线，每条光线在像素内随机偏移（顺便得到反走样），最后取平均。
    【参数】width、height：画面大小；spp：每像素采样数；bounces：最大路径段数；seed：随机种子；chunk：一次处理多少 spp（控制内存）
    【返回】H×W×3 的线性辐射亮度
    """
    rng = np.random.default_rng(seed)
    camera = np.array(CAMERA_EYE)
    half_h = np.tan(np.radians(CAMERA_FOVY) / 2.0)
    half_w = half_h * width / height
    xx, yy = np.meshgrid(np.arange(width), np.arange(height))
    xx, yy = xx.ravel(), yy.ravel()
    total = np.zeros((width * height, 3))
    done = 0
    while done < spp:
        k = min(chunk, spp - done)
        px = np.tile(xx, k) + rng.random(k * xx.size)
        py = np.tile(yy, k) + rng.random(k * xx.size)
        d = np.stack([(px / width * 2.0 - 1.0) * half_w, (1.0 - py / height * 2.0) * half_h, -np.ones_like(px)], axis=1)
        d /= np.linalg.norm(d, axis=1, keepdims=True)
        o = np.tile(camera, (len(d), 1))
        estimate = trace(o, d, bounces, rng)
        total += estimate.reshape(k, -1, 3).sum(axis=0)
        done += k
    return (total / spp).reshape(height, width, 3)


def classify_pixels(width, height, offset_x, offset_y):
    """
    判断穿过每个像素某个位置的光线打到了什么：天花板（避开灯）、靠红墙的地面、靠绿墙的地面、其他。

    【参数】width、height：画面大小；offset_x、offset_y：在像素内的位置，0~1
    【返回】长度 width·height 的字符串数组，取值 "ceiling"、"floor_red"、"floor_green"、"other"
    【边界】"避开灯"留了 0.05 的余量，防止数值误差把灯算进来。
    """
    half_h = np.tan(np.radians(CAMERA_FOVY) / 2.0)
    half_w = half_h * width / height
    px, py = np.meshgrid(np.arange(width) + offset_x, np.arange(height) + offset_y)
    d = np.stack([(px.ravel() / width * 2.0 - 1.0) * half_w, (1.0 - py.ravel() / height * 2.0) * half_h, -np.ones(px.size)], axis=1)
    d /= np.linalg.norm(d, axis=1, keepdims=True)
    points, normals, _, emission = nearest_hit(np.tile(np.array(CAMERA_EYE), (len(d), 1)), d)
    x, z = points[:, 0], points[:, 2]
    x0, x1, z0, z1 = LIGHT_RECT
    away = (x < x0 - 0.05) | (x > x1 + 0.05) | (z < z0 - 0.05) | (z > z1 + 0.05)
    out = np.full(len(d), "other", dtype=object)
    out[(normals[:, 1] < -0.5) & (points[:, 1] > BOX["y1"] - 1e-6) & away] = "ceiling"
    is_floor = (normals[:, 1] > 0.5) & (points[:, 1] < BOX["y0"] + 1e-6)
    out[is_floor & (x < -0.7)] = "floor_red"
    out[is_floor & (x > 0.7)] = "floor_green"
    return out


def section_rendering(quick):
    """
    比较"只有直接光照"和"全局光照"，并观察噪声随采样数的下降。

    【思路】
        ① 天花板只能被反弹光照亮（灯就贴在它上面，直接光照不到），所以它的亮度是全局光照最直接的证据；
        ② 左墙红、右墙绿，它们附近的白球和白墙应该沾上颜色（颜色渗透）；
        ③ Monte Carlo 的噪声按 1/√N 下降：采样数翻 4 倍，误差才减半。
    【参数】quick：True 时用低采样数，只确认能运行
    【返回】拼好的图
    """
    console.print_header("C. 渲染：极简路径追踪器（Rendering）")
    w, h = (64, 48) if quick else (160, 120)
    ref_spp = 32 if quick else 1024
    t0 = time.perf_counter()
    reference = render_path(w, h, ref_spp, 6, seed=100)
    elapsed = time.perf_counter() - t0
    direct = render_path(w, h, ref_spp // 2, 2, seed=101)
    print(f"  {w}×{h}，参考图每像素 {ref_spp} 条路径、最多 6 段：{elapsed:.1f} 秒（这台机器上的真实耗时，每次略有不同）")

    # ---- 全局光照的证据 ----
    # 在**世界坐标**里圈定要比较的区域，这样不会误把灯、球算进去。
    # 渲染时光线在像素内随机偏移，所以一个像素必须 4 个角都落在区域内才算数，否则偏移的光线可能打到别的东西。
    corners = [classify_pixels(w, h, ox, oy) for ox, oy in [(0, 0), (1, 0), (0, 1), (1, 1)]]
    ceiling = np.logical_and.reduce([c == "ceiling" for c in corners])
    near_red = np.logical_and.reduce([c == "floor_red" for c in corners])
    near_green = np.logical_and.reduce([c == "floor_green" for c in corners])
    flat_direct, flat_full = direct.reshape(-1, 3), reference.reshape(-1, 3)
    print("\n  同一块区域的平均亮度（线性值，RGB 平均）：")
    console.print_table(["区域", "只有直接光（2 段）", "全局光照（6 段）"], [
        ["天花板（避开灯）", f"{flat_direct[ceiling].mean():.4f}", f"{flat_full[ceiling].mean():.4f}"]])
    rows = []
    for name, region in [("靠近红墙的地面", near_red), ("靠近绿墙的地面", near_green)]:
        for label, image in [("直接光", flat_direct), ("全局光", flat_full)]:
            r, g = image[region, 0].mean(), image[region, 1].mean()
            rows.append([name, label, f"{r:.3f}", f"{g:.3f}", f"{r / g:.3f}"])
    print()
    console.print_table(["区域", "光照", "R", "G", "R/G"], rows, align=["<", "<", ">", ">", ">"])
    print("\n  观察：天花板只有在全局光照下才有亮度：灯就贴在它上面，光要先经地面、墙壁反弹才能照到它，直接光照下严格为 0。")
    print("        直接光下地面的 R/G 严格等于 1（白灯照白地）；全局光下，靠近红墙的 R/G 升高，靠近绿墙的下降：颜色是从墙上'渗'过来的。")
    print("        这些效果没有一行代码专门处理：它们自动来自'光线反弹'这一条物理规律。")

    # ---- 噪声 ----
    rows, panels = [], []
    previous = None
    for spp in ((1, 4, 16) if quick else (1, 4, 16, 64, 256)):
        image = render_path(w, h, spp, 6, seed=200 + spp)
        rms = float(np.sqrt(((image - reference) ** 2).mean()))
        rows.append([spp, f"{rms:.4f}", "" if previous is None else f"{previous / rms:.2f}"])
        previous = rms
        if spp in (1, 16, 256):
            panels.append(image_io.to_uint8(image_io.srgb_encode(image)))
    print()
    console.print_table(["每像素路径数", "和参考图的 RMS 误差", "比上一行小几倍"], rows)
    print("\n  观察：采样数翻 4 倍，误差缩小约 2 倍，也就是 1/√N（参考图自己也有一点噪声，所以最后一行略小于 2）。")
    print("        想把噪声减半，要多花 4 倍的时间：这是离线渲染昂贵的根本原因。")
    print("        第 24 讲（方差缩减）的全部内容，就是怎样用更聪明的采样打败这条曲线。")

    panels.append(image_io.to_uint8(image_io.srgb_encode(direct)))
    panels.append(image_io.to_uint8(image_io.srgb_encode(reference)))
    k = 2
    sheet = image_io.image_grid([image_io.upscale(p, k) for p in panels], cols=len(panels), gap=6)
    image_io.save_png(os.path.join(course_path.out_dir(), "08_pathtrace.png"), sheet)
    print("  输出 out/08_pathtrace.png：不同采样数（噪声逐渐消失）、只有直接光照、全局光照")
    return image_io.upscale(image_io.to_uint8(image_io.srgb_encode(reference)), 2)


# =============================================================================
# D. 动画
# =============================================================================

KEY_TIMES = np.array([0.0, 1.0, 2.0, 3.0, 4.0])
KEY_POSITIONS = np.array([[-1.8, 0.6, 0.5], [-0.7, 1.7, 0.0], [0.3, 0.6, -0.3], [1.1, 1.5, 0.3], [2.0, 0.6, 0.6]])


def interpolate_linear(t):
    """
    线性插值关键帧。

    【参数】t：时间（标量）
    【返回】长度 3 的位置
    【边界】t 超出关键帧的范围时，夹到两端。
    """
    t = float(np.clip(t, KEY_TIMES[0], KEY_TIMES[-1]))
    i = min(int(t), len(KEY_TIMES) - 2)
    return KEY_POSITIONS[i] + (t - KEY_TIMES[i]) * (KEY_POSITIONS[i + 1] - KEY_POSITIONS[i])


def interpolate_catmull_rom(t):
    """
    Catmull-Rom 样条插值：每段是一条三次多项式，切线由前后相邻的关键帧决定。

    【思路】线性插值在关键帧处速度突变，看起来像机器人。三次多项式多出来的自由度，
        正好可以让每个关键帧两侧的速度相等（第 27 讲）。
    【参数】t：时间（标量）
    【返回】长度 3 的位置
    【边界】首尾两段缺少"前一个"或"后一个"关键帧，用端点本身代替（切线比较小，起止看起来有缓动）。
    """
    t = float(np.clip(t, KEY_TIMES[0], KEY_TIMES[-1]))
    n = len(KEY_TIMES)
    i = min(int(t), n - 2)
    p0 = KEY_POSITIONS[max(i - 1, 0)]
    p1, p2 = KEY_POSITIONS[i], KEY_POSITIONS[i + 1]
    p3 = KEY_POSITIONS[min(i + 2, n - 1)]
    s = t - KEY_TIMES[i]
    return 0.5 * ((2.0 * p1) + (p2 - p0) * s + (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * s * s
                  + (3.0 * p1 - p0 - 3.0 * p2 + p3) * s * s * s)


def velocity_jump(fn, at, eps=1e-5):
    """
    用数值差分算函数在时刻 at 左右两侧的速度差（速度突变的大小）。

    【参数】fn：位置函数；at：时刻；eps：差分步长
    【返回】速度差向量的长度
    """
    left = (fn(at) - fn(at - eps)) / eps
    right = (fn(at + eps) - fn(at)) / eps
    return float(np.linalg.norm(right - left))


def section_animation(quick):
    """
    5 个关键帧，用样条算出中间的每一帧，用 mini_pipeline 渲染出来。

    【参数】quick：True 时只渲染很少的帧
    【返回】胶片条图（后面放进总览图）
    """
    console.print_header("D. 动画：关键帧 + 插值（Animation）")
    rows = []
    for at in (1.0, 2.0, 3.0):
        rows.append([f"t = {at:.0f}", f"{velocity_jump(interpolate_linear, at):.3f}", f"{velocity_jump(interpolate_catmull_rom, at):.6f}"])
    console.print_table(["关键帧", "线性插值的速度突变", "Catmull-Rom 的速度突变"], rows)
    print("\n  观察：线性插值在每个关键帧处速度都突然改变，观众会看到'一顿一顿'；样条的速度是连续的（差异只剩数值误差）。")

    ball = meshes.cube(0.8)
    ground = mp.Draw(meshes.ground(12.0), np.eye(4), mp.fs_checker, {"light_dir": mp.SCENE_LIGHT, "scale": 1.0})
    camera = mp.Camera(eye=(0.0, 2.2, 6.2), target=(0.1, 0.8, 0.0), fovy_deg=38.0)
    count = 4 if quick else 24
    w, h = 120, 80
    frames = []
    for k in range(count):
        t = k / (count - 1) * KEY_TIMES[-1]
        model = tf.translate(*interpolate_catmull_rom(t)) @ tf.rotate_y(90.0 * t) @ tf.rotate_x(45.0 * t)
        draw = mp.Draw(ball, model, mp.fs_lambert, {"color": (0.82, 0.25, 0.20), "light_dir": mp.SCENE_LIGHT})
        fb, _ = mp.render([ground, draw], camera, w, h, clear_color=(0.55, 0.70, 0.86))
        frames.append(image_io.to_uint8(image_io.srgb_encode(fb.color)))
    picks = frames[:: max(len(frames) // 8, 1)][:8]
    strip = image_io.image_grid(picks, cols=4, gap=4)
    image_io.save_png(os.path.join(course_path.out_dir(), "08_animation.png"), strip)
    print(f"\n  共 {len(frames)} 帧。输出 out/08_animation.png（挑 {len(picks)} 帧的胶片条）", end="")
    try:
        from PIL import Image
        pil = [Image.fromarray(f).convert("P", palette=Image.ADAPTIVE) for f in frames]
        gif = os.path.join(course_path.out_dir(), "08_animation.gif")
        pil[0].save(gif, save_all=True, append_images=pil[1:], duration=80, loop=0)
        print("、out/08_animation.gif（循环播放）")
    except ImportError:
        print("（没有 Pillow，跳过 GIF）")
    return strip


def main():
    quick = "--quick" in sys.argv
    draws, camera = mp.demo_scene()
    fb, _ = mp.render(draws, camera, 320, 240, clear_color=(0.55, 0.70, 0.86))
    raster = image_io.to_uint8(image_io.srgb_encode(fb.color))
    geometry = section_geometry()
    rendering = section_rendering(quick)
    animation = section_animation(quick)
    top = image_io.image_grid([raster, rendering], gap=8)         # 分两行分别拼，避免列宽互相牵连，留下大片空白
    bottom = image_io.image_grid([geometry, animation], gap=8)
    image_io.save_png(os.path.join(course_path.out_dir(), "08_course_preview.png"), image_io.image_grid([top, bottom], cols=1, gap=0))
    print("\n  输出 out/08_course_preview.png：左上光栅化、右上路径追踪、左下几何、右下动画")


if __name__ == "__main__":
    main()
