/* =============================================================================
 * Lecture 4 · 程序 09：把第 1 讲的管线用 C++ 重写一遍（讲义 §11）
 * =============================================================================
 *
 * 【这个程序要回答的问题】
 *   这一讲学的类、模板、const、引用、RAII、虚函数放在一起是什么样子？
 *   同一条管线，从 Python 换到 C++，能快多少？结果一样吗？
 *
 * 【运行】make && ./out/09_mini_rasterizer                （渲染并打印统计）
 *        ./out/09_mini_rasterizer 1280 800               （指定分辨率）
 *        ./out/09_mini_rasterizer 640 400 repeat=50      （重复渲染，用于计时）
 *        python3 compare_render.py                       （和 Python 版本逐像素比较）
 *
 * 【思路】逐阶段照抄 mini_pipeline.py，几何数据的生成顺序也完全相同，所以每个阶段的统计数字都应该一样：
 *     顶点着色 → 图元装配 → 平凡拒绝 → 近平面裁剪 → 透视除法 → 背面剔除 → 光栅化 → 片元着色 → 深度测试
 *     这是一个很好的检验：如果数字对不上，就说明某处写错了。
 *
 * 【和 Python 版本的不同】
 *     Python 版本批量处理片元（numpy）；这里逐个片元处理，每个片元调用一次虚函数 shade()。
 *     这正好体现了本讲 §8 讨论的代价。
 *
 * 【边界】这不是 Scotty3D 的代码，也不是它的答案。只有最基本的功能，和 mini_pipeline.py 相同的那些简化。
 * -------------------------------------------------------------------------- */
#include <array>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <limits>
#include <memory>
#include <string>
#include <vector>

#include "gfx_common.h"
#include "png_writer.h"
#include "vec3.h"

namespace mini {

using Real = double;                // 和 Python 版本一样用双精度，这样才能逐像素比较
using Vec3 = gfx::Vec3T<Real>;
constexpr Real PI = 3.14159265358979323846;

/* -----------------------------------------------------------------------------
 * Mat4：4×4 矩阵，行优先存放。
 * 【C++ 小知识】std::array<Real, 16> 是固定大小的数组，不做堆分配，所以 Mat4 可以放心地按值传递。
 * -------------------------------------------------------------------------- */
struct Mat4 {
    std::array<Real, 16> m{};

    static Mat4 identity() {
        Mat4 r;
        r.m[0] = r.m[5] = r.m[10] = r.m[15] = 1.0;
        return r;
    }
    static Mat4 translate(Real x, Real y, Real z) {
        Mat4 r = identity();
        r.m[3] = x;
        r.m[7] = y;
        r.m[11] = z;
        return r;
    }
    static Mat4 rotate_y(Real degrees) {
        Real c = std::cos(degrees * PI / 180.0), s = std::sin(degrees * PI / 180.0);
        Mat4 r = identity();
        r.m[0] = c;
        r.m[2] = s;
        r.m[8] = -s;
        r.m[10] = c;
        return r;
    }
    static Mat4 look_at(const Vec3& eye, const Vec3& target, const Vec3& up) {
        Vec3 z = (eye - target).unit();
        Vec3 x = up.cross(z).unit();
        Vec3 y = z.cross(x);
        Mat4 r = identity();
        r.m[0] = x.x; r.m[1] = x.y; r.m[2] = x.z; r.m[3] = -x.dot(eye);
        r.m[4] = y.x; r.m[5] = y.y; r.m[6] = y.z; r.m[7] = -y.dot(eye);
        r.m[8] = z.x; r.m[9] = z.y; r.m[10] = z.z; r.m[11] = -z.dot(eye);
        return r;
    }
    static Mat4 perspective(Real fovy_deg, Real aspect, Real near_plane, Real far_plane) {
        Real f = 1.0 / std::tan(fovy_deg * PI / 180.0 / 2.0);
        Mat4 r;
        r.m[0] = f / aspect;
        r.m[5] = f;
        r.m[10] = (far_plane + near_plane) / (near_plane - far_plane);
        r.m[11] = 2.0 * far_plane * near_plane / (near_plane - far_plane);
        r.m[14] = -1.0;
        return r;
    }

    Mat4 operator*(const Mat4& o) const {
        Mat4 r;
        for (int i = 0; i < 4; i++)
            for (int j = 0; j < 4; j++) {
                Real s = 0.0;
                for (int k = 0; k < 4; k++) s += m[size_t(i * 4 + k)] * o.m[size_t(k * 4 + j)];
                r.m[size_t(i * 4 + j)] = s;
            }
        return r;
    }

    /* 把点 (x, y, z, 1) 变换后写进 out[4]。 */
    void apply(const Vec3& p, Real out[4]) const {
        for (int i = 0; i < 4; i++) out[i] = m[size_t(i * 4)] * p.x + m[size_t(i * 4 + 1)] * p.y + m[size_t(i * 4 + 2)] * p.z + m[size_t(i * 4 + 3)];
    }

    /* 只变换方向：只用左上角 3×3。这个场景只有旋转和平移，所以它就是法线矩阵（逆转置等于自身）。 */
    Vec3 apply_direction(const Vec3& v) const {
        return Vec3(m[0] * v.x + m[1] * v.y + m[2] * v.z, m[4] * v.x + m[5] * v.y + m[6] * v.z, m[8] * v.x + m[9] * v.y + m[10] * v.z);
    }
};

/* 网格：和 meshes.py 的数据结构相同。 */
struct Mesh {
    std::vector<Vec3> positions, normals;
    std::vector<std::array<int, 3>> faces;
};

/* 下面 4 个函数和 meshes.py 里的同名函数逐行对应，顶点和面的顺序完全相同。 */
static Mesh make_cube(Real size) {
    Mesh out;
    Real s = size / 2.0;
    const Real quads[6][4][3] = {
        {{+s, -s, +s}, {+s, -s, -s}, {+s, +s, -s}, {+s, +s, +s}},
        {{-s, -s, -s}, {-s, -s, +s}, {-s, +s, +s}, {-s, +s, -s}},
        {{-s, +s, +s}, {+s, +s, +s}, {+s, +s, -s}, {-s, +s, -s}},
        {{-s, -s, -s}, {+s, -s, -s}, {+s, -s, +s}, {-s, -s, +s}},
        {{-s, -s, +s}, {+s, -s, +s}, {+s, +s, +s}, {-s, +s, +s}},
        {{+s, -s, -s}, {-s, -s, -s}, {-s, +s, -s}, {+s, +s, -s}},
    };
    for (int i = 0; i < 6; i++) {
        Vec3 a(quads[i][0][0], quads[i][0][1], quads[i][0][2]);
        Vec3 b(quads[i][1][0], quads[i][1][1], quads[i][1][2]);
        Vec3 c(quads[i][2][0], quads[i][2][1], quads[i][2][2]);
        Vec3 n = (b - a).cross(c - a).unit();
        for (int k = 0; k < 4; k++) {
            out.positions.emplace_back(quads[i][k][0], quads[i][k][1], quads[i][k][2]);
            out.normals.push_back(n);
        }
        int base = 4 * i;
        out.faces.push_back({base, base + 1, base + 2});
        out.faces.push_back({base, base + 2, base + 3});
    }
    return out;
}

static Mesh make_sphere(int rows, int cols, Real radius) {
    Mesh out;
    for (int r = 0; r <= rows; r++) {
        for (int c = 0; c <= cols; c++) {
            Real theta = Real(r) / rows * PI, phi = Real(c) / cols * 2.0 * PI;
            Vec3 n(std::sin(theta) * std::sin(phi), std::cos(theta), std::sin(theta) * std::cos(phi));
            out.positions.push_back(n * radius);
            out.normals.push_back(n);
        }
    }
    for (int r = 0; r < rows; r++) {
        for (int c = 0; c < cols; c++) {
            int a = r * (cols + 1) + c, b = (r + 1) * (cols + 1) + c, d = (r + 1) * (cols + 1) + c + 1, e = r * (cols + 1) + c + 1;
            if (r != 0) out.faces.push_back({a, b, e});
            if (r != rows - 1) out.faces.push_back({b, d, e});
        }
    }
    return out;
}

static Mesh make_torus(Real major, Real minor, int rows, int cols) {
    Mesh out;
    for (int r = 0; r <= rows; r++) {
        for (int c = 0; c <= cols; c++) {
            Real phi = Real(c) / cols * 2.0 * PI, psi = Real(r) / rows * 2.0 * PI;
            Vec3 center(std::sin(phi), 0.0, std::cos(phi));
            Vec3 n = center * std::cos(psi) + Vec3(0.0, 1.0, 0.0) * std::sin(psi);
            out.positions.push_back(center * major + n * minor);
            out.normals.push_back(n);
        }
    }
    for (int r = 0; r < rows; r++) {
        for (int c = 0; c < cols; c++) {
            int a = r * (cols + 1) + c, b = a + cols + 1, d = a + cols + 2, e = a + 1;
            out.faces.push_back({a, e, b});
            out.faces.push_back({b, e, d});
        }
    }
    return out;
}

static Mesh make_ground(Real s) {
    Mesh out;
    out.positions = {Vec3(-s, 0, s), Vec3(s, 0, s), Vec3(s, 0, -s), Vec3(-s, 0, -s)};
    out.normals.assign(4, Vec3(0, 1, 0));
    out.faces = {{0, 1, 2}, {0, 2, 3}};
    return out;
}

/* -----------------------------------------------------------------------------
 * Shader：片元着色器的接口（抽象基类）。
 *
 * 【思路】每种材质是一个派生类，实现自己的 shade()。渲染器只认识 Shader&，不关心具体是哪种。
 *     这是虚函数最典型的用途。Python 版本里，着色器就是一个普通的函数对象，这里是一个类。
 * 【参数】world：片元的世界坐标；normal：插值后的法线（还没有归一化）
 * 【返回】线性颜色
 * -------------------------------------------------------------------------- */
class Shader {
public:
    virtual Vec3 shade(const Vec3& world, const Vec3& normal) const = 0;
    virtual ~Shader() = default;      // 通过基类指针 delete 时，要能调用到派生类的析构函数
};

class LambertShader : public Shader {
public:
    LambertShader(const Vec3& albedo, const Vec3& light_dir, Real ambient = 0.12)
        : albedo_(albedo), light_(light_dir.unit()), ambient_(ambient) {}

    Vec3 shade(const Vec3&, const Vec3& normal) const override { return albedo_ * lighting(normal); }

protected:
    /* 光照量：派生类也要用，所以放在 protected。 */
    Real lighting(const Vec3& normal) const {
        Real d = normal.unit().dot(light_);
        d = d < 0.0 ? 0.0 : (d > 1.0 ? 1.0 : d);
        return ambient_ + (1.0 - ambient_) * d;
    }

private:
    Vec3 albedo_, light_;
    Real ambient_;
};

class CheckerShader final : public LambertShader {
public:
    explicit CheckerShader(const Vec3& light_dir) : LambertShader(Vec3(1, 1, 1), light_dir) {}

    Vec3 shade(const Vec3& world, const Vec3& normal) const override {
        Real p = std::fmod(std::fmod(std::floor(world.x) + std::floor(world.z), 2.0) + 2.0, 2.0);
        Vec3 base = p < 0.5 ? Vec3(0.85, 0.85, 0.82) : Vec3(0.25, 0.25, 0.28);
        return base * lighting(normal);
    }
};

/* 一次绘制：网格 + 模型矩阵 + 着色器。unique_ptr 表示这个 Draw 拥有它的着色器。 */
struct Draw {
    Mesh mesh;
    Mat4 model;
    std::unique_ptr<Shader> shader;
};

struct Stats {
    long vertices = 0, primitives = 0, rejected = 0, near_clipped = 0, backfacing = 0, rasterized = 0;
    long edge_tests = 0, fragments = 0, shaded = 0, depth_passed = 0, pixels = 0;
};

/* 帧缓冲。std::vector 自动管理内存：Framebuffer 销毁时内存自动释放，这就是 RAII。 */
class Framebuffer {
public:
    Framebuffer(int w, int h, const Vec3& clear)
        : width(w), height(h), color(size_t(w) * h, clear), depth(size_t(w) * h, std::numeric_limits<Real>::infinity()), id(size_t(w) * h, -1) {}

    const int width, height;
    std::vector<Vec3> color;
    std::vector<Real> depth;
    std::vector<int> id;
};

/* 裁剪坐标 + 属性：一个顶点流过管线时携带的全部数据。 */
struct ClipVertex {
    Real clip[4];
    Vec3 world, normal;
};

static ClipVertex lerp_vertex(const ClipVertex& a, const ClipVertex& b, Real t) {
    ClipVertex out;
    for (int i = 0; i < 4; i++) out.clip[i] = a.clip[i] + t * (b.clip[i] - a.clip[i]);
    out.world = a.world + (b.world - a.world) * t;
    out.normal = a.normal + (b.normal - a.normal) * t;
    return out;
}

/* -----------------------------------------------------------------------------
 * raster_triangle：透视除法 → 视口 → 背面剔除 → 光栅化 → 着色 → 深度测试。
 *
 * 【思路】和 mini_pipeline._raster_triangle 逐行对应。这里的重心坐标写成增量形式：
 *     edge 函数是 (x, y) 的线性函数，所以 x 每走一格只需加一个常数（第 1 讲 §6.2）。
 * 【参数】fb：帧缓冲（引用，要写）；tri：3 个顶点（const，只读）；shader：着色器；prim_id：图元编号；stats：统计
 * 【边界】面积为 0 的三角形直接返回。
 * -------------------------------------------------------------------------- */
static void raster_triangle(Framebuffer& fb, const ClipVertex tri[3], const Shader& shader, int prim_id, Stats& stats) {
    const int W = fb.width, H = fb.height;
    Real sx[3], sy[3], sz[3], inv_w[3];
    for (int i = 0; i < 3; i++) {
        Real w = tri[i].clip[3];
        inv_w[i] = 1.0 / w;
        sx[i] = (tri[i].clip[0] / w * 0.5 + 0.5) * W;
        sy[i] = (0.5 - tri[i].clip[1] / w * 0.5) * H;
        sz[i] = tri[i].clip[2] / w;
    }
    Real area2 = (sx[1] - sx[0]) * (sy[2] - sy[0]) - (sy[1] - sy[0]) * (sx[2] - sx[0]);
    if (area2 == 0.0) return;
    if (area2 > 0.0) {             // 图像的 y 向下，所以从外面看逆时针的正面，这里是负数
        stats.backfacing++;
        return;
    }
    int x0 = std::max(int(std::floor(std::min({sx[0], sx[1], sx[2]}))), 0);
    int x1 = std::min(int(std::ceil(std::max({sx[0], sx[1], sx[2]}))), W);
    int y0 = std::max(int(std::floor(std::min({sy[0], sy[1], sy[2]}))), 0);
    int y1 = std::min(int(std::ceil(std::max({sy[0], sy[1], sy[2]}))), H);
    if (x1 <= x0 || y1 <= y0) return;
    stats.rasterized++;
    stats.edge_tests += long(x1 - x0) * (y1 - y0);

    for (int y = y0; y < y1; y++) {
        Real py = y + 0.5;
        for (int x = x0; x < x1; x++) {
            Real px = x + 0.5;
            Real b0 = ((sx[2] - sx[1]) * (py - sy[1]) - (sy[2] - sy[1]) * (px - sx[1])) / area2;
            Real b1 = ((sx[0] - sx[2]) * (py - sy[2]) - (sy[0] - sy[2]) * (px - sx[2])) / area2;
            Real b2 = ((sx[1] - sx[0]) * (py - sy[0]) - (sy[1] - sy[0]) * (px - sx[0])) / area2;
            if (b0 < 0.0 || b1 < 0.0 || b2 < 0.0) continue;
            Real z = b0 * sz[0] + b1 * sz[1] + b2 * sz[2];
            if (z < -1.0 || z > 1.0) continue;
            stats.fragments++;
            size_t index = size_t(y) * W + x;
            if (!(z < fb.depth[index])) continue;      // 提前深度测试
            Real l0 = b0 * inv_w[0], l1 = b1 * inv_w[1], l2 = b2 * inv_w[2];
            Real scale = 1.0 / (l0 + l1 + l2);
            l0 *= scale;
            l1 *= scale;
            l2 *= scale;
            Vec3 world = tri[0].world * l0 + tri[1].world * l1 + tri[2].world * l2;
            Vec3 normal = tri[0].normal * l0 + tri[1].normal * l1 + tri[2].normal * l2;
            fb.color[index] = shader.shade(world, normal);      // 这里有一次虚函数调用
            fb.depth[index] = z;
            fb.id[index] = prim_id;
            stats.shaded++;
            stats.depth_passed++;
        }
    }
}

/* -----------------------------------------------------------------------------
 * render：主循环。和 mini_pipeline.render 对应。
 * 【参数】draws：绘制列表（const&：不复制也不修改）；vp：投影 × 视图；fb：帧缓冲
 * 【返回】统计
 * -------------------------------------------------------------------------- */
static Stats render(const std::vector<Draw>& draws, const Mat4& vp, Framebuffer& fb) {
    Stats stats;
    int prim_id = 0;
    std::vector<ClipVertex> verts;       // 放在循环外面，重复使用同一块内存，不用每次都分配
    for (const Draw& draw : draws) {
        // ---- 顶点着色器 ----
        const Mesh& mesh = draw.mesh;
        verts.resize(mesh.positions.size());
        for (size_t i = 0; i < verts.size(); i++) {
            Real w[4];
            draw.model.apply(mesh.positions[i], w);
            verts[i].world = Vec3(w[0], w[1], w[2]);
            vp.apply(verts[i].world, verts[i].clip);
            verts[i].normal = draw.model.apply_direction(mesh.normals[i]);
        }
        stats.vertices += long(verts.size());

        // ---- 图元装配 ----
        for (const auto& f : mesh.faces) {
            stats.primitives++;
            const ClipVertex tri[3] = {verts[size_t(f[0])], verts[size_t(f[1])], verts[size_t(f[2])]};
            bool reject = false;
            for (int axis = 0; axis < 2; axis++) {
                bool all_above = true, all_below = true;
                for (int k = 0; k < 3; k++) {
                    all_above = all_above && tri[k].clip[axis] > tri[k].clip[3];
                    all_below = all_below && tri[k].clip[axis] < -tri[k].clip[3];
                }
                reject = reject || all_above || all_below;
            }
            bool all_far = true, all_near = true;
            for (int k = 0; k < 3; k++) {
                all_far = all_far && tri[k].clip[2] > tri[k].clip[3];
                all_near = all_near && (tri[k].clip[2] + tri[k].clip[3]) < 0.0;
            }
            if (reject || all_far || all_near) {
                stats.rejected++;
                prim_id++;
                continue;
            }
            // ---- 近平面裁剪（Sutherland–Hodgman）----
            Real d[3];
            bool inside = true;
            for (int k = 0; k < 3; k++) {
                d[k] = tri[k].clip[2] + tri[k].clip[3];
                inside = inside && d[k] >= 0.0;
            }
            if (inside) {
                raster_triangle(fb, tri, *draw.shader, prim_id, stats);
            } else {
                stats.near_clipped++;
                ClipVertex poly[4];
                int count = 0;
                for (int i = 0; i < 3; i++) {
                    int j = (i + 1) % 3;
                    if (d[i] >= 0.0) poly[count++] = tri[i];
                    if ((d[i] >= 0.0) != (d[j] >= 0.0)) poly[count++] = lerp_vertex(tri[i], tri[j], d[i] / (d[i] - d[j]));
                }
                for (int k = 1; k + 1 < count; k++) {
                    const ClipVertex fan[3] = {poly[0], poly[k], poly[k + 1]};
                    raster_triangle(fb, fan, *draw.shader, prim_id, stats);
                }
            }
            prim_id++;
        }
    }
    for (int v : fb.id) stats.pixels += v >= 0;
    return stats;
}

static Real srgb_encode(Real x) {
    x = x < 0.0 ? 0.0 : (x > 1.0 ? 1.0 : x);
    return x <= 0.0031308 ? 12.92 * x : 1.055 * std::pow(x, 1.0 / 2.4) - 0.055;
}

}  // namespace mini

int main(int argc, char** argv) {
    using namespace mini;      // 这个函数里可以省略 mini:: 前缀
    int width = argc > 1 ? std::atoi(argv[1]) : 640;
    int height = argc > 2 ? std::atoi(argv[2]) : 400;
    int repeat = 1;
    std::string out_path = "out/09_cpp_render.png";
    for (int i = 3; i < argc; i++) {
        std::string a = argv[i];
        if (a.rfind("repeat=", 0) == 0) repeat = std::atoi(a.c_str() + 7);
        if (a.rfind("out=", 0) == 0) out_path = a.substr(4);
    }

    const Vec3 light(0.45, 0.8, 0.4);
    std::vector<Draw> draws;
    draws.push_back(Draw{make_ground(12.0), Mat4::identity(), std::make_unique<CheckerShader>(light)});
    draws.push_back(Draw{make_cube(1.2), Mat4::translate(-1.5, 0.6, -0.2) * Mat4::rotate_y(28.0),
                         std::make_unique<LambertShader>(Vec3(0.80, 0.16, 0.14), light)});
    draws.push_back(Draw{make_sphere(24, 48, 0.8), Mat4::translate(0.9, 0.8, -0.5),
                         std::make_unique<LambertShader>(Vec3(0.10, 0.62, 0.66), light)});
    draws.push_back(Draw{make_torus(0.62, 0.22, 16, 32), Mat4::translate(-0.25, 0.22, 1.35),
                         std::make_unique<LambertShader>(Vec3(0.88, 0.60, 0.12), light)});

    Mat4 view = Mat4::look_at(Vec3(3.2, 2.6, 5.4), Vec3(-0.1, 0.45, 0.1), Vec3(0, 1, 0));
    Mat4 proj = Mat4::perspective(38.0, Real(width) / height, 0.1, 100.0);
    Mat4 vp = proj * view;

    const Vec3 clear(0.62, 0.74, 0.86);
    Stats stats;
    std::vector<uint8_t> rgb(size_t(width) * height * 3);
    double best = 1e30;
    for (int r = 0; r < repeat; r++) {
        Framebuffer fb(width, height, clear);
        double t0 = gfx::now();
        stats = render(draws, vp, fb);
        double dt = gfx::now() - t0;
        best = dt < best ? dt : best;
        if (r + 1 == repeat) {
            for (size_t i = 0; i < fb.color.size(); i++) {
                const Vec3& c = fb.color[i];
                rgb[3 * i] = uint8_t(srgb_encode(c.x) * 255.0 + 0.5);
                rgb[3 * i + 1] = uint8_t(srgb_encode(c.y) * 255.0 + 0.5);
                rgb[3 * i + 2] = uint8_t(srgb_encode(c.z) * 255.0 + 0.5);
            }
        }
    }
    if (!gfx::write_png(out_path, width, height, rgb)) {
        std::fprintf(stderr, "写文件失败：%s（out/ 目录存在吗？）\n", out_path.c_str());
        return 1;
    }
    std::printf("vertices %ld\nprimitives %ld\nrejected %ld\nnear_clipped %ld\nbackfacing %ld\nrasterized %ld\n"
                "edge_tests %ld\nfragments %ld\nshaded %ld\ndepth_passed %ld\npixels %ld\nseconds %.6f\n",
                stats.vertices, stats.primitives, stats.rejected, stats.near_clipped, stats.backfacing, stats.rasterized,
                stats.edge_tests, stats.fragments, stats.shaded, stats.depth_passed, stats.pixels, best);
    return 0;
}
