Ray casting and ray tracing in MATLAB games

The MATLAB One-Button Game Mini Hack is coming to a close. It's been an exciting ride, with so many amazing games submitted by over 80 participants. At the same time, it's been an incredibly rewarding learning experience, with participants gradually refining their entries and experimenting with more intricate graphics along the way. In this article, I'd like to share some of the techniques I've used for ray casting and ray tracing in MATLAB, from the scenery in Canyon Swift to the reflections in Pool 3D.
Ray casting in 2.5D
Ray casting finds which surface is visible in each pixel's direction from the camera. A ray starts at the camera and extends into the scene, with its nearest opaque surface supplying the visible material. When the scene has a regular structure, we can share much of this calculation between neighboring pixels.
Canyon Swift represents its landscape as a height field: each horizontal position has one terrain height. That height can describe a low riverbed, a canyon wall or a tall pillar, but it cannot describe an opening beneath an overhang. Such terrain renderers are often described as 2.5D (or pseudo-3D). Canyon Swift draws the bridges separately, using the terrain's depth to determine which parts remain visible.
Consider one vertical column of the image. All of its viewing directions have the same horizontal bearing, so we can sample the terrain along that horizontal path once, at increasing depths ahead of the camera. Projecting the height of each sample returns the screen row where its top appears. For a level camera, the vertical projection has the following form:
screenRow = horizonRow + focalLength * (cameraHeight - terrainHeight) ./ depth;
Here, screen rows increase downward and focalLength is measured in image pixels. The sample's depth is its forward displacement in the renderer's coordinates, rather than distance along the sloping ray. Terrain above the camera projects above the horizon, and increasing the depth moves its projection closer to the horizon. Canyon Swift turns the view by shifting the horizontal sampling path and banks it by adding a shear to the screen rows.
The game calculates an RGB array with 150 rows and 200 columns. At its default settings, it samples 110 depths for each column, with the samples spaced more closely near the camera. These are shared terrain samples for the whole column, rather than a separate search through the landscape for each of its 150 pixels. An image object created during initialization displays the array; each rendered frame replaces its CData with the newly calculated colors.
In the figure below, the vertical line marks one column of the game's image. Its projected terrain tops are plotted in magenta, ordered by depth from near to far, while the cyan line shows the smallest screen-row value reached so far. The two panels have the same screen-row scale. Each yellow guide connects a marked pixel to the first sample covering it, at the corresponding step in the cyan line:
MATLAB's cummin is used to calculate the running minimum. A farther sample whose top falls below it is hidden by terrain, as the magenta points under the flat end of the cyan line show. A sample that rises above it exposes a new strip of the column. The same front-to-back visibility idea is illustrated in the VoxelSpace reconstruction, where a height map is drawn by updating the uncovered part of each column.
We still need to know which sample colors each pixel. Suppose five terrain samples project to rows 9, 7, 8, 4, 6 in a small image. Their running minima are 9, 7, 7, 4, 4. At screen row 6, the first covering sample is sample 4. From that point onward, every running minimum is at or above row 6, even if a later terrain top falls below it. There are therefore two qualifying minima: the ones for samples 4 and 5. With five samples in total, the first covering sample is 5 + 1 - 2 = 4. More generally, if the count is positive, its index is sampleCount + 1 - count. A count of zero means that no terrain sample reaches the pixel, so it shows the sky. Counting the original tops would result in forgetting which sample arrived first. At row 7, for example, three original tops qualify, giving the incorrect index 5 + 1 - 3 = 3; sample 3 actually projects to row 8. Counting the running minima gives four and correctly selects sample 2.
We can calculate the counts for all rows simultaneously, by taking the ceiling of each running minimum to find the first integer row it covers, counting how many minima arrive at each row, and then accumulating those counts down the screen:
projectedRows = [9; 7; 8; 4; 6];
screenHeight = 10;
sampleCount = numel(projectedRows);
skyline = cummin(projectedRows);
firstRow = min(max(ceil(skyline), 1), screenHeight + 1);
events = accumarray(firstRow, 1, [screenHeight + 1, 1]);
count = cumsum(events(1:screenHeight));
visible = count > 0;
sampleIndex = zeros(screenHeight, 1);
sampleIndex(visible) = sampleCount + 1 - count(visible);
accumarray forms the histogram of first covered rows, and cumsum counts all the minima that have reached each row. The extra bin at screenHeight + 1 holds samples below the image; excluding it keeps those samples from producing a false hit on the bottom row. Tops above the image are assigned to row 1 as they cover the column from its first pixel onward. The visible mask keeps the zero-valued sky entries out of subsequent terrain lookups.
Canyon Swift uses arrays to perform the same calculation for all columns. For each terrain pixel, the selected sample returns its depth. Rearranging the level-camera projection recovers the height of the point seen at that pixel:
worldHeight = cameraHeight - (screenRow - horizonRow) .* depth / focalLength;
For the banked view, the renderer removes the screen-row shear before this calculation. The recovered height varies down a cliff even when several pixels select the same terrain sample: the terrain sample describes the top, while each pixel looks at a different point below it. The rock's horizontal strata are colored using that recovered height, while the sample's terrain values supply its material and shading, and the distance adds atmospheric haze.
Rendering water, scenery, and wraparound landscapes
In Stone Skipping, the lake reflects the mountains and rock stacks that surround it. The landscape is drawn using the same projected-height and running-minimum construction, and its colors are reused for the water, with waves and expanding rings from the skipping stone displacing the reflection:
For each water pixel, the renderer looks up a row above the shoreline and displaces that lookup with waves and rings from the skipping stone. The shoreline is found separately for each column. An additional shoreline calculation omits the rock stacks, allowing their reflections to end and reveal the farther shore behind them.
As the camera travels over the lake, the samples' forward depths change to keep their positions along the lake aligned with the fixed grids. The 100 samples are divided into zones with spacings of 2, 4, 8 and 16 game units. Each sample has a nominal forward depth, baseDepth, and its zone's spacing, step. The camera's progress within the current grid cell is subtracted from that nominal depth:
depth = baseDepth - mod(cameraZ, step);
worldZ = cameraZ + depth;
For example, the first sample in the zone with spacing 4 has a nominal depth of 77. At camera positions 10 and 11, its forward depths become 75 and 74, so both views sample world position 85. When the camera reaches 12, the sample moves to world position 89, the next grid point. This keeps the terrain sampling positions fixed between grid crossings. The renderer samples the terrain at shorter intervals near the camera and at longer intervals farther away.
The camera's position along the lake also sets the time of day in a repeating cycle. Each of four keyframes, for day, sunset, night and dawn, stores a zenith color, a haze color and a light color in one row of a table. interp1 is used to linearly interpolate them between the rows as the cycle wraps around and the keyframes repeat. The sky is blended from the zenith color at the top of the image to the haze color at the horizon, with a weight that grows quadratically with the screen row. The terrain is blended toward the haze color using a weight that increases with depth according to a power law. The light color multiplies the terrain's shading, colors the sun and the clouds, and tints the water and the stone. The water's reflection lookup reads the image after the sky has been drawn, and the sun, the moon and the Aurora Borealis are reflected along with the terrain:
The clouds, the crepuscular rays, the Aurora Borealis and the dawn mist take their variation from a noise tile generated during initialization. rand is used to fill a 256-by-256 array with white noise, and conv2 is used to filter it with a separable Gaussian kernel with a standard deviation of 3 cells, truncated at 8 cells on each side. repmat is used to tile three-by-three copies of the array before filtering, and keeping the central copy makes the result periodic, so lookups can wrap around the tile using mod without visible seams. rescale is then used to map the values to the range 0 to 1:
kernel = exp(-(-8:8).^2/18);
filtered = conv2(kernel, kernel, repmat(rand(256), 3), "same");
noiseTile = rescale(filtered(257:512, 257:512));
Each of these features reads the tile at its own coordinates. Where the tile exceeds 0.5, the clouds shift the sky color toward the light color in proportion to the excess, at a lookup position that drifts with time. For the sun's crepuscular rays, both lookup coordinates are the polar angle around the sun calculated using atan2, scaled so that one turn spans about 256 cells, with an offset that grows with time added to one coordinate and subtracted from the other. The noise is therefore constant along each radius. As the angle varies, the lookup follows a diagonal through the tile, and the offset moves that diagonal perpendicular to itself, so that the rays change in place instead of rotating. Their brightness is multiplied by the positive half of a sine wave with the period of the cycle, which peaks at sunset. The lower part of the Aurora Borealis is a tilted line displaced by two sine waves traveling in opposite directions. Above that, the brightness decays exponentially and is modulated by two columns of the tile scrolling in opposite directions, while the color is interpolated from green at the edge to purple above it. At dawn, the negative half of the same sine wave scales a mist weight: a Gaussian function of each terrain pixel's recovered height, centered on the water level and modulated by the tile and by depth. The terrain is blended toward the haze color with the larger of the mist and haze weights. The sun and the moon are the sum of a narrow and a wide Gaussian, and a logistic step across an offset circle cuts the moon's narrow Gaussian to a crescent. The stars are a separate array, max(0, 60*rand(150, 200) - 59), which lights about one pixel in 60 with a uniformly distributed brightness, and it moves with the view direction using circshift.
Chase the Light! uses a height field wrapped around the inside of a cylinder. Its map coordinates are an angle around the cylinder and a distance along its axis, with one inward terrain height at each map location. The base cylinder has radius 60 game units; the terrain height reduces that radius, raising the land toward the viewer. The camera travels at radius 50, with land continuing around both sides and overhead:
The color and height maps are generated during initialization. In this view, the same patch of the initialized map is shown flat and wrapped onto the inside of the cylinder. The matching circles identify the same hill in both views. The upper part is omitted from the diagram so that the interior remains visible; the game itself closes the landscape overhead.
Here the renderer works along directions radiating from the vanishing point rather than down vertical columns. For each direction, it finds the distance from the camera to the base cylinder in its cross section. The terrain raises the wall inward, so that distance must then be shortened. The game estimates the change by multiplying the terrain height at the base-cylinder intersection by the rate at which this distance changes with the cylinder radius. Subtracting that correction gives a first-order estimate of the distance to the raised wall.
This cross-sectional distance is separate from the forward depth along the cylinder's axis. At each sampled forward depth, the local terrain height gives a corrected cross-sectional distance, which projects to a radial edge in the image in place of the canyon's projected top row. A running minimum and histogram recover the first sample covering each pixel, filling the image inward from its outer regions toward the vanishing point.
The first covering sample identifies the depth interval in which the ray reaches the wall. Within that interval, the renderer approximates the wall profile by a straight segment relating cross-sectional distance to forward depth. It intersects the pixel's ray with that segment and clamps the resulting depth to the interval's endpoints. The refined position supplies the angle and axial coordinate used to look up the terrain color, and the wheels of spokes are drawn separately at their own depths.
Simulating freefall
I've Got Some Falling to Do combines maps of the ground and clouds with a camera that follows the skydiver's descent. The skydiver starts at an altitude of 4,000 m. Gravity accelerates the fall while quadratic drag opposes the motion, gradually reducing the forward speed and bringing the downward speed toward the 217 km/h terminal speed. The trajectory is calculated during initialization in 0.1-second steps, with the positions and velocities stored in a table. During play, the game interpolates this table at the elapsed jump time and adds the sideways motion used to steer through the rings:
The camera initially turns from the airplane door toward the direction of the fall. Its pitch then follows the forward and vertical velocity components, while steering turns and banks the view. A wide-angle stereographic projection supplies a unit-length direction for each pixel, and the camera's orientation transforms these directions into the world. The ray origins follow the skydiver's position, bringing the ground closer and shifting it across the image as the skydiver descends and steers.
The fields, woods, river and roads below are drawn from procedurally generated color maps. Each downward ray meets a horizontal ground plane, and the intersection's coordinates determine which part of the map it sees. The renderer estimates each pixel's footprint on the ground to select a map resolution, using finer maps for nearby ground and evaluating close airfield detail directly. A precalculated map supplies cloud shadows, while distance adds atmospheric haze and the water mixes in color from the sky.
Clouds can partially obscure the scenery below, so the same rays also need to collect cloud color while transmitting some of the background. I've Got Some Falling to Do estimates each ray's segment within the cloud layer between 1,800 and 2,400 m altitude, limiting the search to 14 km from the camera. That segment is split into four sampling intervals. Downward rays use a fixed per-pixel shift within those intervals; upward rays use their midpoints.
At each sample, a precalculated map supplies the cloud's local thickness and lighting. The thickness determines the fraction of the interval inside the cloud, from which the renderer estimates an opacity. Intervals with a greater horizontal extent use more blurred thickness values. Together, the four samples estimate the cloud's transparency along the viewing ray.
Suppose the four sample opacities for one ray are 0.25, 0.5, 0, 0.2, ordered from near to far. Each sample transmits the fraction 1 - alpha of the light arriving from behind it. Multiplying those fractions returns the transmittance through successive sampling intervals:
alpha = [0.25 0.5 0 0.2];
transmission = cumprod(1 - alpha, 2);
weights = [alpha(:,1), transmission(:,1:3) .* alpha(:,2:4)];
Each row represents one ray, so the same operations can be applied to many pixels at once. The nearest sample contributes with a weight of 0.25. The second has 0.5 opacity, but only 0.75 of its light gets through the first sample, resulting in a weight of 0.375. The third sample has 0 opacity, and the fourth results in a weight of 0.075 after transmission through the earlier samples. The sample colors are multiplied by those weights and summed, and the remaining 0.3 of the background color is then added. The weights and remaining transmission add up to 1, accounting for the whole pixel.
Below, the grayscale view shows the total cloud opacity, 1 - transmission(:,4), calculated from the same camera position and ray directions as the frame beside it. The cloud ahead of the skydiver appears as a bright central patch, with darker regions around it where the ground is visible.
The simulated trajectory and steering therefore change both the ground positions reached by the camera rays and the parts of the cloud layer the rays pass through. Below the layer, downward rays reach the land directly, while the continuing descent brings the finer maps and airfield detail into view.
Ray casting in 3D
I've Got Some Falling to Do finds the ground by intersecting downward viewing rays with a plane. In Space Racer 3D, we also need intersections with the curved course and the racing vehicles (anti-gravity Machines). Circular cross sections describe the road as it bends through space and curves upward into a tube, while the Machines are assembled from convex solids. The renderer tests each ray against both kinds of geometry:
The course is defined by circular cross sections along its forward coordinate. At each section, let p be the horizontal displacement from the bottom of the section, q its vertical displacement, and radius the circle's radius. The expression
value = p.^2 + q.^2 - 2*radius.*q;
is zero on the circle, negative inside it and positive outside. Completing the square gives p.^2 + (q-radius).^2 - radius.^2, so the circle's center lies one radius above its bottom. A radius of 100,000 makes the narrow arc used for the open road almost flat, while a radius of 37 defines the inside of the tube.
The camera ray has a direction of the form [x, y, 1], where x and y are the pixel's horizontal and vertical slopes. Its parameter therefore measures forward depth. At each sampled depth, the renderer accounts for the course's bends and evaluates the cross section there. It keeps the first sampled transition from inside to outside, then bisects the interval twice in reciprocal depth: each new test uses the midpoint between the reciprocals of the current endpoint depths. The forward depth is linearly interpolated to estimate where the ray intersects the course surface, and the result is clamped to the refined interval. The course-depth image below uses a logarithmic color scale to make small depth differences along the nearby road easier to distinguish:
Each Machine is built from six convex pieces, with eight bounding planes per piece. A plane's normal points perpendicular to its face. The normal and offset describe the allowed side through dot(normal, point) <= offset. Substituting a point on the ray, origin + t*direction, turns that spatial condition into a bound on t:
dot(normal, direction) * t <= offset - dot(normal, origin)
Dividing by a negative coefficient reverses the inequality, giving a lower bound on t: for example, -2*t <= -12 requires t >= 6. A positive coefficient gives an upper bound, such as 3*t <= 27, or t <= 9. For a ray that is not parallel to any face, we take the largest lower bound as the entry depth and the smallest upper bound as the exit. Lower bounds of 4, 6, 5 and upper bounds of 11, 9, 10, for instance, leave the interval from 6 to 9. The camera is outside the Machines, so the game looks for a nonnegative entry; it rejects a piece if that entry is negative or reaches or exceeds the exit.
Before testing a Machine, the renderer transforms the ray's origin and direction into the Machine's coordinates and leaves the direction unnormalized. Its parameter therefore remains the forward camera depth, matching the course calculation:
The model view uses the game's actual shape, pose and colors. The marked pixel supplies the ray for the interval diagram. The numbered rows show the depths allowed by each plane, and the bottom row is their common interval. In the game, the nearest accepted piece supplies the Machine's surface color, and its depth is compared with the course.
Ray tracing in 3D
Pool 3D uses ray tracing to render reflections on the billiard balls. As the balls separate after a shot, the reflected images of their neighbors move across their surfaces:
The water in Stone Skipping looked up another row of an existing image. Here, the reflected view is calculated from the point on the ball where the camera ray arrives. We first intersect the sphere, find its surface normal at that point, and reflect the viewing direction about the normal. Ray tracing continues from that surface, following the reflected ray to find what appears in the reflection.
A ray can be written as origin + distance*direction. For the sphere calculation below, direction has unit length, so distance measures distance along the ray. Let center and radius describe the sphere. Substituting the ray into the sphere equation gives a quadratic. A negative discriminant means that the ray's line misses the sphere, and a valid intersection must lie in front of the origin. For a camera outside the sphere we use the nearer positive root; a ray starting inside needs the farther positive root. The sphere-intersection derivation in PBRT develops the general quadratic.
For a small numerical example, take a unit sphere at the origin and a camera ray starting at [0.5, 0, 3], pointing along the negative z direction. The ray is offset from the center, so it meets a sloping part of the surface:
origin = [0.5 0 3];
direction = [0 0 -1];
center = [0 0 0];
radius = 1;
offset = origin - center;
b = dot(direction, offset);
discriminant = b^2 - dot(offset, offset) + radius^2;
distance = -b - sqrt(discriminant);
point = origin + distance * direction;
normal = (point - center) / radius;
The distance is 3 - sqrt(3)/2, and the hit point is [0.5, 0, sqrt(3)/2]. Because this sphere has radius 1 and is centered at the origin, the normal has the same coordinates as the hit point. At any true surface hit, the normal is the outward vector from the center to the hit, divided by the radius.
With the unit normal above, reflection reverses the direction's component along the normal while preserving its tangential component:
reflected = direction - 2 * dot(direction, normal) * normal;
For our offset ray, this gives [sqrt(3)/2, 0, 0.5]: it travels sideways and back upward from the hit. The same reflection formula is applied to the ball pixels in Pool 3D.
In the enlarged image below, the reflection of the red ball gives the right edge of the striped ball a pink tint. The schematic shows the balls from the same camera view, with the arrows drawn in the plane of reflection so we can see the angles at P. The camera ray D reaches the striped ball at P, where the radius from the ball's center gives the direction of the outward normal N. The reflected ray R leaves at the same angle to the normal as the incoming ray and reaches the red ball at Q:
The reflected ray repeats the sphere-intersection calculation from P, using R as its direction. Pool 3D tests up to four other balls, chosen by the nearest centers in the table plane, and keeps the nearest valid hit among them. The second ball contributes its color, stripe and simplified lighting. If the reflected ray misses those balls, upward directions see square ceiling lights or the dark room, while downward directions receive the cloth color with a darker region near the ball's foot. These simple environment surfaces fill the remaining reflected directions without intersecting a complete model of the room.
The reflected color is mixed with the ball's locally shaded color using the chosen weight 0.3 + 0.7*(1 + dot(direction, normal))^5. At the point facing the camera, the dot product is near -1 and the reflected fraction is near 0.3. Toward the silhouette, the dot product approaches zero and the reflected fraction approaches 1, making the surroundings more prominent near the ball's edge.
Optimizing ray tracing for speed
With its camera and table fixed, Pool 3D can ray trace the table once and reuse its image during play. During initialization, the renderer takes four subpixel samples for each output pixel and averages each two-by-two group, producing the cached image of the wood, cloth, rail markings and pockets.
During play, each ball is ray traced within a separate 30-by-30 image window, which is positioned over the table using the projected ball center. The images are layered by center depth, with the numbers and soft shadows drawn separately.
The image's alpha mask softens the ball's silhouette. Pool 3D compares the ray's closest distance to the sphere's center with the radius to estimate pixel coverage, keeping a partially covered pixel even when its center ray just misses. That coverage estimate blends the ball image with the layers behind it; it is separate from the true surface hit used in the reflection example.
The ball images are retained between frames. A ball is retraced when its position or orientation changes, when its depth order changes, or when a moving ball is close enough to affect its reflection. The proximity test is limited, so a small reflection of a more distant moving ball can lag behind a full retrace. Even if all 16 balls need to be redrawn, the renderer casts 14,400 camera rays across their windows, compared with 480,000 pixels in the full 800-by-600 view. The renderer can update the balls and their changing reflections while reusing the table image.
And that's all for this article! The MATLAB One-Button Game Mini Hack has been a great opportunity to create and share games, but the fun doesn't have to end with the contest. I hope these examples encourage you to experiment with ray casting and ray tracing in your own MATLAB games moving forward. I'm looking forward to seeing what other games everyone makes in the future!