Core Module
Basic data types and utility functions for the ray tracer.
vec3
3D vector class with common operations.
cpp
struct vec3 {
float x, y, z;
__host__ __device__ vec3 operator+(const vec3& v) const;
__host__ __device__ vec3 operator-(const vec3& v) const;
__host__ __device__ vec3 operator*(float t) const;
__host__ __device__ float dot(const vec3& v) const;
__host__ __device__ vec3 cross(const vec3& v) const;
__host__ __device__ float length() const;
__host__ __device__ vec3 normalize() const;
};Common Operations:
| Operation | Description |
|---|---|
dot(a, b) | Dot product: $a \cdot b$ |
cross(a, b) | Cross product: $a \times b$ |
reflect(v, n) | Reflection: $v - 2(v \cdot n)n$ |
normalize(v) | Unit vector: $v / |v|$ |
ray
Ray class with origin and direction.
cpp
struct ray {
vec3 origin; // Ray starting point
vec3 direction; // Normalized direction
float t_min; // Minimum intersection distance
float t_max; // Maximum intersection distance
__host__ __device__ vec3 at(float t) const {
return origin + direction * t;
}
};Random Utilities
CUDA random number utilities using cuRAND.
cpp
// Initialize random state per pixel
__device__ void init_random(curandState* state, int seed);
// Generate uniform [0, 1)
__device__ float random_float(curandState* state);
// Generate uniform [min, max)
__device__ float random_float(curandState* state, float min, float max);
// Cosine-weighted hemisphere sampling
__device__ vec3 random_cosine_direction(curandState* state);
// Uniform sphere sampling
__device__ vec3 random_in_unit_sphere(curandState* state);CUDA Helper Macro
cpp
// CUDA error checking
#define CUDA_CHECK(call) \
do { \
cudaError_t err = call; \
if (err != cudaSuccess) { \
fprintf(stderr, "CUDA Error at %s:%d: %s\n", \
__FILE__, __LINE__, cudaGetErrorString(err)); \
exit(1); \
} \
} while (0)Constants
cpp
namespace constants {
constexpr float PI = 3.14159265358979323846f;
constexpr float EPSILON = 1e-6f;
constexpr float INFINITY = 1e30f;
constexpr int MAX_DEPTH = 64; // BVH max depth
}Usage Example
cpp
// Vector operations
vec3 a(1.0f, 2.0f, 3.0f);
vec3 b(4.0f, 5.0f, 6.0f);
vec3 c = a + b; // (5, 7, 9)
float d = dot(a, b); // 32
vec3 e = cross(a, b); // (-3, 6, -3)
// Ray operations
Ray r(vec3(0, 0, 0), normalize(vec3(1, 1, 0)));
vec3 p = r.at(5.0f); // Point at t=5