Creating a fully featured ray tracer in C++ in under 400 lines is a challenge, but a basic version can be achieved. Below is a simplified ray tracing program written in less than 400 lines. This demonstration deals with spheres and a single light source. There is no advanced material, texture, or reflection/refraction in this example for brevity.
To compile and run this program, you will need a modern C++ compiler that supports C++11 or later. This program uses the file "lodepng.h" to handle PNG creation, which can be downloaded from the LodePNG website (https://lodev.org/lodepng/). Place "lodepng.h" and "lodepng.cpp" in the same directory as your raytracer.cpp before compiling.
// raytracer.cpp
#include <iostream>
#include <vector>
#include <cmath>
#include <limits>
#include <memory>
#include "lodepng.h"
const float kInfinity = std::numeric_limits<float>::max();
const float kEpsilon = 1e-4;
struct Vec3 {
float x, y, z;
Vec3() : x(0), y(0), z(0) {}
Vec3(float x, float y, float z) : x(x), y(y), z(z) {}
Vec3 operator - () const { return Vec3(-x, -y, -z); }
Vec3 operator + (const Vec3& v) const { return Vec3(x+v.x, y+v.y, z+v.z); }
Vec3 operator - (const Vec3& v) const { return Vec3(x-v.x, y-v.y, z-v.z); }
Vec3 operator * (const float& a) const { return Vec3(x*a, y*a, z*a); }
Vec3 operator * (const Vec3& v) const { return Vec3(x*v.x, y*v.y, z*v.z); }
Vec3& operator += (const Vec3 &v) { x += v.x, y += v.y, z += v.z; return *this; }
Vec3& normalize() {
float norm2 = length2();
if (norm2 > 0) {
float invNorm = 1 / sqrtf(norm2);
x *= invNorm, y *= invNorm, z *= invNorm;
}
return *this;
}
float dot(const Vec3 &v) const { return x*v.x + y*v.y + z*v.z; }
Vec3 cross(const Vec3 &v) const { return Vec3(y*v.z - z*v.y, z*v.x - x*v.z, x*v.y - y*v.x); }
float length2() const { return x*x + y*y + z*z; }
float length() const { return sqrtf(length2()); }
};
struct Ray {
Vec3 orig, dir;
Ray(const Vec3& orig, const Vec3& dir) : orig(orig), dir(dir) {}
};
class Object {
public:
virtual bool intersect(const Ray& r, float& t) const = 0;
virtual Vec3 getNormal(const Vec3& p) const = 0;
};
typedef std::vector<std::shared_ptr<Object>> VecObjects;
class Sphere : public Object {
public:
Vec3 center;
float radius, radius2;
Sphere(const Vec3& c, const float& r) : center(c), radius(r), radius2(r*r) {}
bool intersect(const Ray& r, float& t) const override {
Vec3 L = center - r.orig;
float tca = L.dot(r.dir);
float d2 = L.dot(L) - tca*tca;
if (d2 > radius2) return false;
float thc = sqrtf(radius2 - d2);
float t0 = tca - thc;
float t1 = tca + thc;
if (t0 < 0) t0 = t1;
if (t0 < 0) return false;
t = t0;
return true;
}
Vec3 getNormal(const Vec3& p) const override {
return (p - center).normalize();
}
};
bool trace(
const Ray &ray,
const VecObjects &objects,
float &tNear,
const Object *&hitObject
) {
tNear = kInfinity;
std::vector<std::shared_ptr<Object>>::const_iterator iter = objects.begin();
for (; iter != objects.end(); ++iter) {
float t = kInfinity;
if ((*iter)->intersect(ray, t) && t < tNear) {
hitObject = iter->get();
tNear = t;
}
}
return (hitObject != nullptr);
}
Vec3 castRay(
const Ray &ray,
const VecObjects &objects,
const Vec3 &lightDir,
const Vec3 &lightColor,
const Vec3 &backgroundColor
) {
Vec3 hitColor = backgroundColor;
const Object *hitObject = nullptr;
float t;
if (trace(ray, objects, t, hitObject)) {
Vec3 hitPoint = ray.orig + ray.dir * t;
Vec3 hitNormal = hitObject->getNormal(hitPoint);
float lightPower = std::max(float(0), hitNormal.dot(-lightDir));
hitColor = lightColor * lightPower;
}
return hitColor;
}
void render(
const VecObjects &objects,
const Vec3 &lightDir,
const Vec3 &lightColor,
const Vec3 &backgroundColor,
const unsigned width,
const unsigned height,
const std::string &filename
) {
std::vector<unsigned char> image;
image.reserve(width * height * 4);
float invWidth = 1 / float(width), invHeight = 1 / float(height);
float fov = 30, aspectratio = width / float(height);
float angle = tan(M_PI * 0.5 * fov / 180.);
for (unsigned y = 0; y < height; ++y) {
for (unsigned x = 0; x < width; ++x) {
float xx = (2 * ((x + 0.5) * invWidth) - 1) * angle * aspectratio;
float yy = (1 - 2 * ((y + 0.5) * invHeight)) * angle;
Ray ray(Vec3(), Vec3(xx, yy, -1).normalize());
Vec3 color = castRay(ray, objects, lightDir, lightColor, backgroundColor);
image.push_back(std::min(float(1), color.x) * 255);
image.push_back(std::min(float(1), color.y) * 255);
image.push_back(std::min(float(1), color.z) * 255);
image.push_back(255);
}
}
unsigned error = lodepng::encode(filename, image, width, height);
if (error) std::cout << "encoder error " << error << ": " << lodepng_error_text(error) << std::endl;
}
int main() {
std::string filename = "rendered.png";
unsigned width = 800, height = 600;
Vec3 lightDir(0, -1, -1);
lightDir.normalize();
Vec3 lightColor(1, 1, 1);
Vec3 backgroundColor(0.1f, 0.1f, 0.1f);
VecObjects objects;
objects.push_back(std::make_shared<Sphere>(Vec3(0, 0, -20), 4));
objects.push_back(std::make_shared<Sphere>(Vec3(5, -1, -15), 2));
objects.push_back(std::make_shared<Sphere>(Vec3(-3, 1, -10), 1));
render(objects, lightDir, lightColor, backgroundColor, width, height, filename);
return 0;
}
This code traces rays through the scene and checks for intersections with simple spheres. If an intersection is found, it calculates simple shaded color by using lambertian reflection from a light source. The resulting image is saved as "rendered.png".
Please remember that a more complex scene would require additional code and likely would surpass the 400-line limit. This program does not handle shadows, reflections, refractions, or textures, and it uses a very rudimentary lighting model. Also, for the production of high-quality images, a more advanced library and substantial additional code would be required.