/* =============================================================================
 * Lecture 4 · 程序 06：虚函数：运行时才决定调用谁（讲义 §8）
 * =============================================================================
 *
 * 【这个程序要回答的问题】
 *   1. 基类指针指向派生类对象时，调用的是谁的函数？（有 virtual 和没有 virtual，结果不同）
 *   2. 虚函数是怎么实现的？（每个对象多一个指针，指向一张函数表）
 *   3. 它有多贵？（比普通调用慢多少？为什么数据的排列顺序影响这么大？）
 *   4. 图形程序里什么时候该用，什么时候不该用？
 *
 * 【运行】make && ./out/06_virtual        （约 3 秒）
 *
 * 【图形学联系】渲染器要处理球、平面、三角形……用虚函数写最自然，每种形状实现自己的 hit()。
 *     但光线追踪每秒要调用几亿次 hit()，所以这个"自然"的写法有多贵，是实实在在的工程问题。
 * -------------------------------------------------------------------------- */
#include <cmath>
#include <cstdio>
#include <memory>
#include <vector>

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

using gfx::Vec3f;

/* ---- 第 1 节：virtual 决定调用谁 ---- */
struct Action {
    virtual const char* undo() { return "Action::undo"; }     // 虚函数：调用谁，看对象实际的类型
    const char* redo() { return "Action::redo"; }             // 普通函数：调用谁，看指针的类型
    virtual ~Action() = default;                              // 有虚函数的类，析构函数也要是虚的（§9 解释）
};

struct MeshEdit : Action {
    const char* undo() override { return "MeshEdit::undo"; }  // override：明确说这是在重写，写错了编译器会报错
    const char* redo() { return "MeshEdit::redo"; }           // 这只是一个同名的新函数，并没有重写
};

/* ---- 第 2 节：几种形状 ----
 *
 * Shape 是抽象类：= 0 表示这个函数没有实现，派生类必须提供，Shape 本身不能创建对象。
 * 所有形状都接受同样的光线，返回交点的距离（没碰到返回 −1）。
 */
struct Ray {
    Vec3f o, d;      // 起点、单位方向
};

struct Shape {
    virtual float hit(const Ray& r) const = 0;
    virtual ~Shape() = default;
};

struct Sphere final : Shape {          // final：不会再有派生类，给编译器更多优化机会
    Vec3f c;
    float radius;
    Sphere(Vec3f c_, float r_) : c(c_), radius(r_) {}
    float hit(const Ray& r) const override {
        Vec3f oc = r.o - c;
        float b = oc.dot(r.d);
        float disc = b * b - (oc.dot(oc) - radius * radius);
        return disc > 0.0f ? -b - std::sqrt(disc) : -1.0f;
    }
};

struct Plane final : Shape {
    Vec3f n;
    float d;
    Plane(Vec3f n_, float d_) : n(n_), d(d_) {}
    float hit(const Ray& r) const override {
        float denom = n.dot(r.d);
        return std::fabs(denom) > 1e-6f ? (d - n.dot(r.o)) / denom : -1.0f;
    }
};

struct Disk final : Shape {
    Vec3f c, n;
    float radius;
    Disk(Vec3f c_, Vec3f n_, float r_) : c(c_), n(n_), radius(r_) {}
    float hit(const Ray& r) const override {
        float denom = n.dot(r.d);
        if (std::fabs(denom) <= 1e-6f) return -1.0f;
        float t = (c - r.o).dot(n) / denom;
        Vec3f p = r.o + r.d * t - c;
        return p.dot(p) <= radius * radius ? t : -1.0f;
    }
};

/* 不用虚函数的对照组：所有形状放在一个结构里，用一个整数标记类型（tagged union 的简化版）。 */
struct TaggedShape {
    int kind;                 // 0 球，1 平面，2 圆盘
    Vec3f a, b;
    float value;
    float hit(const Ray& r) const {
        switch (kind) {
            case 0: {
                Vec3f oc = r.o - a;
                float h = oc.dot(r.d);
                float disc = h * h - (oc.dot(oc) - value * value);
                return disc > 0.0f ? -h - std::sqrt(disc) : -1.0f;
            }
            case 1: {
                float denom = a.dot(r.d);
                return std::fabs(denom) > 1e-6f ? (value - a.dot(r.o)) / denom : -1.0f;
            }
            default: {
                float denom = b.dot(r.d);
                if (std::fabs(denom) <= 1e-6f) return -1.0f;
                float t = (a - r.o).dot(b) / denom;
                Vec3f p = r.o + r.d * t - a;
                return p.dot(p) <= value * value ? t : -1.0f;
            }
        }
    }
};

/* -----------------------------------------------------------------------------
 * measure：把光线和所有形状都测一遍，返回每次调用的纳秒数。
 *
 * 【思路】形状少时一遍太短，量不准，而且程序刚启动时可能还跑在小核上、频率也没升上来。
 *     所以一轮要重复足够多遍（总共约 400 万次调用），再取 7 轮里最快的一轮。
 * 【参数】n：形状个数；ray：光线；get(i)：返回第 i 个形状的引用；hits_out：碰到的次数（防止被优化掉）
 * 【返回】每次调用的纳秒数
 * -------------------------------------------------------------------------- */
template <class Getter>
static double measure(size_t n, const Ray& ray, Getter&& get, long& hits_out) {
    size_t passes = 4'000'000 / n + 1;
    double best = gfx::best_of(7, [&] {
        long hits = 0;
        for (size_t p = 0; p < passes; p++) {
            for (size_t i = 0; i < n; i++) hits += get(i).hit(ray) > 0.0f;
        }
        hits_out = hits;
        gfx::keep(hits);
    });
    return best / double(n * passes) * 1e9;
}

/* 直接调用的对照组：同一种类型，放在连续的数组里，编译器可以把 hit 内联进循环。 */
struct PlainSphere {
    Vec3f c;
    float radius;
    float hit(const Ray& r) const {
        Vec3f oc = r.o - c;
        float b = oc.dot(r.d);
        float disc = b * b - (oc.dot(oc) - radius * radius);
        return disc > 0.0f ? -b - std::sqrt(disc) : -1.0f;
    }
};

int main() {
    std::printf("\n=== 1. virtual 决定调用谁 ===\n");
    MeshEdit edit;
    Action* action = &edit;           // 基类指针指向派生类对象
    gfx::opaque(action);
    std::printf("  action->undo() 调用了 %s（virtual：看对象实际的类型）\n", action->undo());
    std::printf("  action->redo() 调用了 %s（非 virtual：看指针的类型）\n", action->redo());

    std::printf("\n=== 2. 虚函数的内存开销 ===\n");
    struct NoVirtual { float x; float hit() const { return x; } };
    std::printf("  sizeof(没有虚函数、只有 1 个 float) = %zu\n", sizeof(NoVirtual));
    std::printf("  sizeof(Sphere：Vec3f + float + 虚表指针) = %zu（4 个 float 是 16 字节，多了 8 字节指针）\n", sizeof(Sphere));
    std::printf("  sizeof(Plane) = %zu，sizeof(Disk) = %zu；sizeof(TaggedShape) = %zu（所有形状一样大）\n", sizeof(Plane), sizeof(Disk), sizeof(TaggedShape));

    // 对象切片：把派生类对象按值赋给基类变量，派生部分被切掉了
    Action sliced = edit;
    std::printf("  对象切片：Action a = meshEdit; a.undo() 调用了 %s（派生部分被复制时切掉了）\n", sliced.undo());
    std::printf("  所以多态对象总是通过指针或引用使用，按值使用是一个常见的 bug\n");

    std::printf("\n=== 3. 虚函数有多贵（真实计时，每次调用的纳秒数）===\n");
    Ray ray{Vec3f(0.1f, 0.2f, -5.0f), Vec3f(0.0f, 0.0f, 1.0f)};
    gfx::opaque(ray);
    std::printf("  下面每一列都是把光线和所有形状各测一次，形状的参数分布相同：\n");
    std::printf("    A 直接调用：同一种类型的连续数组，没有虚函数\n");
    std::printf("    B 虚函数：同一种类型\n");
    std::printf("    C 虚函数：三种类型，按类型排好\n");
    std::printf("    D 虚函数：三种类型随机交错\n");
    std::printf("    E 虚函数：随机交错 + 访问顺序在内存里也是乱的\n");
    std::printf("    F switch：三种类型随机交错，放在连续数组里，用整数标记类型\n\n");
    std::printf("  %-10s %10s %10s %10s %10s %10s %10s\n", "形状个数", "A", "B", "C", "D", "E", "F");
    for (size_t n : {size_t(1000), size_t(100000), size_t(1000000)}) {
        gfx::Lcg rng(n);
        auto make = [&](int kind) -> std::unique_ptr<Shape> {
            float a = rng.uniform() * 4.0f - 2.0f, b = rng.uniform() * 4.0f - 2.0f, r = 0.2f + rng.uniform();
            if (kind == 0) return std::make_unique<Sphere>(Vec3f(a, b, 0.0f), r);
            if (kind == 1) return std::make_unique<Plane>(Vec3f(a, b, 1.0f).unit(), r);
            return std::make_unique<Disk>(Vec3f(a, b, 1.0f), Vec3f(0.0f, 0.0f, -1.0f), r);
        };
        // 所有对象按 球…平面…圆盘… 的顺序分配（内存里基本连续）
        std::vector<std::unique_ptr<Shape>> owned;
        std::vector<int> kinds;
        owned.reserve(n);
        for (size_t i = 0; i < n; i++) {
            int kind = int(i * 3 / n);
            owned.push_back(make(kind));
            kinds.push_back(kind);
        }
        std::vector<Shape*> sorted(n), shuffled_types(n), spheres_only;
        for (size_t i = 0; i < n; i++) sorted[i] = owned[i].get();
        // 只有一种类型：另外分配 n 个球
        std::vector<std::unique_ptr<Shape>> owned_spheres;
        for (size_t i = 0; i < n; i++) {
            owned_spheres.push_back(make(0));
            spheres_only.push_back(owned_spheres.back().get());
        }
        // 三种类型随机交错，但内存里每次访问都是相邻的：按交错的顺序重新分配
        std::vector<int> mix(n);
        for (size_t i = 0; i < n; i++) mix[i] = int(i % 3);
        gfx::shuffle(mix, n, rng);
        std::vector<std::unique_ptr<Shape>> owned_mixed;
        std::vector<TaggedShape> tagged(n);
        for (size_t i = 0; i < n; i++) {
            owned_mixed.push_back(make(mix[i]));
            shuffled_types[i] = owned_mixed.back().get();
            float a = rng.uniform() * 4.0f - 2.0f, b = rng.uniform() * 4.0f - 2.0f, r = 0.2f + rng.uniform();
            if (mix[i] == 0) tagged[i] = TaggedShape{0, Vec3f(a, b, 0.0f), Vec3f(), r};
            else if (mix[i] == 1) tagged[i] = TaggedShape{1, Vec3f(a, b, 1.0f).unit(), Vec3f(), r};
            else tagged[i] = TaggedShape{2, Vec3f(a, b, 1.0f), Vec3f(0.0f, 0.0f, -1.0f), r};
        }
        // 再把指针数组打乱：既有类型的随机，也有内存访问的随机
        std::vector<Shape*> shuffled_memory = shuffled_types;
        gfx::shuffle(shuffled_memory, n, rng);

        long hits = 0;
        std::vector<PlainSphere> plain(n);
        for (size_t i = 0; i < n; i++) {
            plain[i] = PlainSphere{Vec3f(rng.uniform() * 4.0f - 2.0f, rng.uniform() * 4.0f - 2.0f, 0.0f), 0.2f + rng.uniform()};
        }
        double t_plain = measure(n, ray, [&](size_t i) -> const PlainSphere& { return plain[i]; }, hits);
        double t_same = measure(n, ray, [&](size_t i) -> const Shape& { return *spheres_only[i]; }, hits);
        double t_sorted = measure(n, ray, [&](size_t i) -> const Shape& { return *sorted[i]; }, hits);
        double t_mixed = measure(n, ray, [&](size_t i) -> const Shape& { return *shuffled_types[i]; }, hits);
        double t_scatter = measure(n, ray, [&](size_t i) -> const Shape& { return *shuffled_memory[i]; }, hits);
        double t_switch = measure(n, ray, [&](size_t i) -> const TaggedShape& { return tagged[i]; }, hits);
        std::printf("  %-10zu %7.2f ns %7.2f ns %7.2f ns %7.2f ns %7.2f ns %7.2f ns\n", n, t_plain, t_same, t_sorted, t_mixed, t_scatter, t_switch);
        gfx::keep(hits);
    }
    std::printf("  观察：A 到 B：虚函数本身的代价（读表再跳转）。B 和 C 差不多：只要类型是有规律的，跳转就能被准确预测。\n");
    std::printf("        C 到 D 才是大头：类型随机时，分支预测总是猜错。F 的 switch 同样猜错，所以它并不比虚函数好多少。\n");
    std::printf("        D 到 E：形状多到放不进缓存时，内存访问的顺序又带来一次损失。\n");
    std::printf("        所以高性能的渲染器都把光线和材质按类型分组处理：问题不在 virtual 这个关键字，而在相干性。\n");
    return 0;
}
