Ray Tracing Basics
π‘ Ray Tracing Fundamentals & Implementation
This document explores the foundational concepts and practical implementation of a ray tracer within a game engine environment. It covers camera setup, object intersection (spheres and triangles), lighting models (diffuse and specular reflections), random number generation for physically based rendering, and advanced effects like depth of field.
πΈ Camera Setup & Ray Generation
To accurately render a scene, the ray tracer must simulate the perspective of a virtual camera. This involves calculating the projection plane and generating rays that originate from the camera and pass through each pixel.
π Projection Plane Calculation
The dimensions of the projection plane are crucial for mapping screen pixels to world space.
The height of the projection plane is calculated using the camera's field of view (FOV) and basic trigonometry.
The width is then derived from the height and the aspect ratio of the display.
β‘οΈ Visualizing Rays
A grid of points is generated on this projection plane. Each point is transformed according to the camera's position and orientation.
Ray directions are calculated from the camera's position towards each of these transformed points.
These directions can be visualized as arrows originating from the camera, representing the paths light would take to reach the sensor.
π Ray Tracing vs. Reality
In reality, light originates from sources, bounces off objects, and enters the camera. This is highly inefficient to simulate directly because most light rays miss the camera.
Ray tracing (or "ancient Greek style") reverses this: rays are "shot" out of the camera into the scene. Only rays that eventually hit a light source contribute to the final image, making the process much more efficient.
π» GPU Implementation & Shader Basics
Ray tracing involves sending out millions of rays, a task perfectly suited for parallel processing on the GPU. A Ray Tracing Manager script handles sending camera information to a custom shader and drawing the results.
π¨ Shader Operations
A shader is a program that runs on the GPU, executing code for every pixel on the screen.
Returning a color, e.g.,
red, fills the entire screen with that color.Accessing pixel coordinates (e.g.,
xory) allows for creating gradients, where values range from 0 (left/bottom) to 1 (right/top).
π Calculating Pixel Position
The position of the current pixel on the camera's projection plane is calculated using its coordinates and the camera's information. This often involves matrix multiplication.
A
Raystructure is defined, containing anOrigin(the camera's position) and aDirection(calculated as described above).
π Visualizing Ray Directions
The
Directionvector can be visualized as a color, where X, Y, and Z components map to Red, Green, and Blue, respectively.Looking along the positive X-axis shows more red, positive Y shows more green, and positive Z shows more blue.
Areas where all axes are negative (e.g., behind the camera) appear black.
π Object Intersection: Spheres
For simple shapes like spheres, a pure mathematical representation is more accurate and efficient than using triangles.
π§ͺ Sphere Equation
The equation for a sphere centered at the origin is x2+y2+z2=r2, where r is the radius.
To handle spheres at different positions, the ray can be conceptually moved away from the sphere, keeping the sphere centered at zero for the calculation.
π― Ray-Sphere Intersection
A ray starts at an
originand moves along adirectionfor somedistance.Intersection occurs when the squared length of the ray's position equals the sphere's squared radius.
Solving for
distanceresults in a quadratic equation.If the discriminant (part under the square root) is negative, there are no real solutions, and the ray misses the sphere.
If it's zero, the ray touches the sphere at one point (tangent).
If it's positive, the ray intersects the sphere at two points.
π Hit Information
A HitInfo structure stores details about an intersection:
didHit: A boolean indicating if an intersection occurred.distance: The distance from the ray origin to the intersection point.position: The 3D coordinates of the intersection point.normalVector: The vector perpendicular to the surface at the intersection point, crucial for lighting and reflections.
π¦ Handling Multiple Spheres
RayTracingMaterial: Stores properties like the object'scolor,emissionColor,emissionStrength,smoothness, andspecularProbability.Spherestructure: Holdsposition,radius, andmaterial.RayCollisionfunction:Loops through all spheres in the scene.
Performs an intersection test for each sphere.
If a hit occurs, it checks if this is the **closest hit so far**.
Updates the `HitInfo` with the closest intersection details and the `material` of the hit object.
This allows for rendering multiple spheres with different colors and ensures depth sorting (nearby objects appear in front of distant ones).
β¨ Diffuse Lighting & Random Numbers
Making objects look interesting requires simulating how light interacts with their surfaces. Diffuse reflection is a common type of light scattering.
π‘ Diffuse Reflection
When light hits a rough material, it scatters in random directions. This is known as diffuse reflection.
For ray tracing, this means when a ray hits a surface, it should bounce off in a completely random direction.
π² Random Number Generation (RNG)
Generating pseudo-random numbers on the GPU for each pixel is essential for diffuse lighting.
A pixel index (a unique value from 0 to the total number of pixels) serves as a seed for the random number generator.
A
randomValuefunction takes this seed and transforms it to produce a pseudo-random number between 0 and 1.To generate multiple random values per pixel, the seed is modified within the
randomValuefunction, ensuring subsequent calls yield different results.
π Generating Random Directions
Generating random directions is equivalent to generating random points on the surface of a sphere.
Rejection Sampling (Cube Method):
Generate three random values (X, Y, Z) between -1 and 1, creating a point inside a cube.
Keep generating points until one falls *inside* a unit sphere.
Normalize this point to get a random direction on the sphere's surface.
*Caveat*: This method can be inefficient and prone to infinite loops if not carefully implemented with loop limits. Points can also clump near cube edges if not properly normalized.
Normal Distribution Method:
Generate random numbers using a **normal (Gaussian) distribution** instead of a uniform distribution.
Using these values to generate a point results in a **uniform random distribution** of points over the sphere's surface (due to complex mathematical reasons involving probability). This method is generally faster for GPUs.
π Random Directions in a Hemisphere
When a ray hits a surface, we want it to bounce randomly within a hemisphere oriented around the surface's normal vector.
To ensure the random direction is within the correct hemisphere:
Calculate the **dot product** between the surface normal and the generated random direction.
If the dot product is **negative** (meaning the angle is greater than 90 degrees, pointing away from the hemisphere), **invert** the random direction.
πΆββοΈ Ray Path Tracing & Light Accumulation
The core of the ray tracer involves tracing the path of a ray as it bounces through the scene, accumulating light along its journey.
π€οΈ Trace Function
This function takes an incoming ray and simulates its path:
Collision Detection: Uses the
RayCollisionfunction to find what the ray hits.Bounce: If it hits something:
The ray's
originis moved to the intersection point.A random direction is picked for the ray to bounce off in (diffuse reflection).
Looping: This process repeats until:
A maximum bounce limit is reached.
The ray misses everything and shoots into empty space.
π‘ Light Accumulation
rayColor: Starts as pure white. Whenever the ray hits an object,rayColoris multiplied by the object'smaterial.color. This simulates how light is absorbed or reflected by objects (e.g., a black object absorbs all light, makingrayColorzero).incomingLight: Starts at zero.When a ray hits an object, the object's emitted light (
material.emissionColor * material.emissionStrength) is calculated.This emitted light is added to
incomingLight, tinted by the currentrayColor(representing the colors of all objects the ray has encountered so far).
The
Tracefunction returns the totalincomingLightaccumulated along the path.
π₯οΈ Shader Integration
The main shader code calculates a random seed for the current pixel.
It creates a ray originating from the camera.
It calls the
Tracefunction to determine the pixel's color.
π Environment Lighting
When a ray misses all objects, instead of returning black, it can gather background environment lighting.
A simple function can blend between ground and sky colors based on the ray's vertical direction, and add a sun disc based on a light direction.
βοΈ Cosine Weighting for Diffuse Surfaces
When light hits a surface at an angle, it spreads out more, resulting in weaker illumination per point. This is accounted for by multiplying the light strength by the cosine of the angle between the surface normal and the light direction.
Alternatively, this
light strengthcalculation can be removed if the random bounce directions are generated with a cosine-weighted distribution instead of a uniform distribution. This means more rays are sent in directions that contribute more light, achieving the same physical accuracy more efficiently.
πΌοΈ Addressing Noise & Performance
A common problem in ray tracing, especially with diffuse lighting, is noise in the image, which arises from sending out too few rays.
π Single Ray per Pixel
Initially, only a single ray is sent out per pixel. This leads to extremely noisy images, especially with random bounces.
β¬οΈ Multiple Rays per Pixel (Sampling)
To reduce noise, the shader can loop multiple times per pixel, sending out many rays.
Each ray follows a different random path.
The
incomingLightfrom all these rays is summed up, and the average is output as the pixel's color.While this improves quality, it significantly impacts performance.
ποΈ Averaging Over Multiple Frames (Temporal Accumulation)
To improve quality over time without a massive immediate performance hit, the results from the current frame can be averaged with the previous frame's render.
This requires the random number seed to change with each frame (e.g., by adding the current frame number to the pixel index) to ensure rays bounce differently.
Caveat: This approach is unsuitable for scenes with moving objects, as it leads to "smudgy" trails.
πΊ Object Intersection: Triangles
While spheres are simple, most complex 3D models are built from triangles.
π§© Triangle Representation
A buffer in the shader holds all the triangles in the scene.
Another buffer stores information about each mesh, indicating where its triangles start in the main triangle list and how many it contains.
π Ray-Triangle Intersection
The
RayCollisionfunction is extended to handle triangles.It iterates through the triangles of each mesh.
For each triangle, it performs an intersection test.
Before checking individual triangles, an optimization is used: testing if the ray intersects the object's bounding box. If it doesn't, all triangles within that object can be skipped.
ποΈ Cornell Box Example
A classic test scene, the Cornell Box, is used: a simple room with colored walls (red, blue, green, white).
This helps visualize bounce lighting: light from a white light source will pick up the color of the walls as it reflects, creating subtle color tints on other surfaces.
π Specular Reflections & Materials
Beyond diffuse scattering, surfaces can also exhibit specular reflections, like mirrors.
πͺ Specular Reflection
On a smooth surface, light bounces off perfectly, with the angle of incidence equaling the angle of reflection.
The reflection direction can be calculated using the surface's
normalVectorand theincomingDirectionof the ray.A
smoothnessproperty is added to the material, ranging from 0 (fully diffuse) to 1 (perfectly specular). The ray's new direction is a blend between the diffuse and specular directions based on thissmoothness.Higher
smoothnessvalues result in crisp, mirror-like reflections, while lower values produce blurry reflections.
βΎοΈ Infinite Reflections
When two fully reflective surfaces face each other, they create infinite reflections, where each surface reflects the other, and that reflection contains a reflection of the first, and so on. This is naturally handled by the recursive nature of ray tracing.
π Specular Tinting (Fresnel Effect)
Real-world objects like tomatoes (or varnished wood) have a transparent protective coating.
When light hits this coating, some of it is specularly reflected (untinted, reflecting the light source's color), while some passes through to be diffusely scattered by the object's underlying color.
To simulate this:
A
specularProbabilityis added to the material.A random value is compared against this probability to decide if the current bounce is specular or diffuse.
If it's a specular bounce, the ray's color is multiplied by the material's
specularColor(often white); otherwise, it's multiplied by theregular color.This allows for untinted specular highlights on colored objects, making them appear more realistic.
π«οΈ Depth of Field (DoF)
Depth of field creates a photographic effect where objects at a certain distance appear in focus, while objects closer or farther away are blurred.
π― Basic Idea
Instead of all rays for a pixel starting from the exact same camera position and going in the exact same direction, they are made to diverge slightly.
This divergence is achieved by randomly nudging the ray's origin within a small circle around the original viewpoint.
β Generating Random Points in a Circle
A function generates a random point inside a circle:
Calculates a random angle.
Uses sine and cosine to convert the angle to a point on the **unit circle**.
Scales this point down by the **square root** of another random value to distribute points uniformly *inside* the circle (without the square root, points would cluster towards the center).
This random vector is scaled by a
defocusStrengthsetting.This new, randomly offset viewpoint is used to calculate the ray's direction.
π«οΈ Blurring & Anti-Aliasing
Increasing the
defocusStrengthmakes everything blurry.Setting
defocusStrengthto an extremely low value can help smooth out jagged edges (aliasing) by making the rays diverge just enough to sample slightly different sub-pixel areas.
π Focusing at a Distance
To achieve a specific focal distance, instead of randomly offsetting the viewpoint, the ray origin is randomly offset.
These offset rays are then directed to converge at a specific point on a "focal plane."
Objects on this focal plane will appear sharp, as all rays for a pixel will hit the same point on the object.
Objects in front of or behind the focal plane will appear blurry, as the diverging/converging rays will hit different points on them.
The focus distance is controlled by the Z-component of the camera's view parameters.
π Future Enhancements
The current ray tracer provides a solid foundation, but many advanced features and optimizations can be explored:
Glass objects: Implementing refraction and transparency.
Volumetric effects: Simulating fog, smoke, or clouds.
Performance improvements: Optimizing intersection tests (e.g., using spatial data structures like BVH or Octrees) to handle more complex scenes in real-time.
Atmosphere rendering: Integrating more sophisticated sky and sun models for realistic sunsets and environmental lighting.

Ask anything
We've read this whole study set, so questions about it get the best answers.