从零开始使用C ++编写Ray-Tracer
更新:HHH   时间:2023-1-7


光线追踪是一种基于光传播模拟的3D渲染技术。该技术能够产生非常高的视觉真实感。

原理很简单。它包括滑动每个像素的屏幕像素。对于每个像素,请查看从相机经过该像素的光线是否会与场景中的任何对象相交。像素采用对象的颜色。如果不相交,则像素采用背景色。实际上,像素并不会照原样呈现对象颜色,而是通过称为着色的过程计算出的颜色。着色的目的是使渲染更加真实感。
摄像机的位置以及场景中的所有物体均由3d向量表示,颜色也由3d向量表示。因此,我们需要一直操纵向量。

#ifndef Vect_h
#define Vect_h

#include <cmath>

using namespace std;

class Vec3 {
public:
    float X;
    float Y;
    float Z;
    Vec3(float x, float y, float z) : X(x), Y(y), Z(z) {}
    Vec3 operator +(Vec3 vec) {
        return Vec3(X+vec.X,Y+vec.Y,Z+vec.Z);
    }
    Vec3 operator -(Vec3 vec) {
        return Vec3(X-vec.X,Y-vec.Y,Z-vec.Z);
    }
    Vec3 operator *(float scalar) {
        return Vec3(scalar*X,scalar*Y,scalar*Z);
    }
    float dot(Vec3 vec) {
        return X*vec.X+Y*vec.Y+Z*vec.Z;
    }
    float norm() {
        return sqrt(dot(*this));
    }
    Vec3 normalize() {
        return (*this)*(1/norm());
    }

};

#endif

射线与球体的交点:

以c为中心,半径为r的球面的方程为:

射线(一条线)的方程为:

其中o代表射线的原点,d代表射线的方向,t是参数。
那么对于相交点,t必须满足:

注意:

然后 :

这是二次方程。通过添加单位向量d,我们可以:

解(如果有)是:

    bool Sphere::intersect(Ray& ray, float &t) {
        Vec3 o = ray.get_origin();
        Vec3 d = ray.get_direction();

        Vec3 v = o - Center;

        const float b = 2 * v.dot(d);
        const float c = v.dot(v) - Radius*Radius;
        float delta = b*b - 4 * c;

        if (delta < 1e-4)
            return false;

        const float t1 = (-b - sqrt(delta))/2;
        const float t2 = (-b + sqrt(delta))/2;

        t = (t1 < t2) ? t1 : t2; // get the first intersection only

        return true;
    }

着色:
在开始之前,让我们介绍一些符号。

从要着色点到摄像机的单位向量V。
在所考虑点垂直于球体的法向量N。
易得给定球面一点的法向量:


    Vec3 Sphere::get_normal(Vec3 p) {
        return (p - Center) * (-1/(Radius));
    }

因为:在考虑的点p上的每个法向矢量必须与将p连接到球体中心的半径共线。
简单着色工作很好(正面比,此着色器将返回着色法线和入射光线方向的点积的绝对值,在其他渲染器中,也称为入射。):
facing ratio = V . N
它是V和N之间的夹角的余弦。我们可以使用它来对球体进行如下着色:

Vec3 Shading(Ray ray, Sphere sphere) { 
  Vec3 color(0, 0, 0);
  float t;
  if (sphere.intersect(ray, t)) {
    Vec3 V = ray.get_direction();
    Vec3 P = ray.get_origin() +  V * t;
    Vec3 N = sphere.get_normal(P);

    float facing_ratio = N.dot(V);

    color = sphere.get_color() * (facing_ratio * 0.5);
  }
  return color;
}

结果如下:

返回游戏开发教程...