Introduction
This document is meant as both a quick reference as well as documentation of a few sampling techniques that can be used in path tracing. It mostly came about because I found it hard to find such a reference or the derivations themselves.
This is of course not every kind of sampling technique (for example, no stratified sampling) or distribution, just a few, but maybe someone else can use it as well.
Each Sampling method will have the algorithm and probability density functions listed first and afterwards a derivation. So if you are just looking up how to implement it, you can find it below the images. The images (for the 3D directions) show a heatmap hemisphere corresponding to a number of samples chosen with the showcased method. The heatmap values correspond to number of points per area. Regions with high values will receive more samples than regions with low values.
In general I tried to include every step in the derivation so hopefully it is easy enough to follow.
You can run and all the presented code and change parameters as you like and add points to the current heatmap.
Common helper functions
These are the two functions used to convert from spherical/polar to Cartesian coordinates:
Note: We use a right-handed spherical coordinate system with the y-axis pointing upwards, as that is common in computer graphics. You can easily transform this to a system more common in physics with z up by shifting the coordinates such that z aligns with y: .
function spherical_to_cart(theta, phi, r = 1.0) {
const st = Math.sin(theta);
const ct = Math.cos(theta);
const sp = Math.sin(phi);
const cp = Math.cos(phi);
const x = r * st * sp;
const y = r * ct;
const z = r * st * cp;
return [x, y, z];
}
function polar_to_cart(r, alpha) {
const sa = Math.sin(alpha);
const ca = Math.cos(alpha);
const x = r * ca;
const y = r * sa;
return [x, y];
}
Inverse Transform Sampling
The following sections will explore some ways to sample points/directions used for the Monte Carlo integration. The recipe for calculating the sampling formulas is called inverse transform sampling (there are, of course, other methods)
- Generate a uniform random number in the interval
- Find the cumulative distribution function (CDF) of the desired distribution
- Calculate . will be distributed with
Here we can see a visual demonstration of this method. You can see how the uniformly distributed points on the y-axis get automatically spread out over the x-axis according to the rate of change in the function.
Since we usually need two-dimensional values, we have to modify it a bit
-
Generate two uniform random numbers in the interval
-
The probability density function is dependent on , so
- Calculate the marginal distribution
- Calculate the conditional probability distribution of with respect to with the Bayes theorem:
-
Calculate the CDFs and .
-
Calculate and . and will have the desired distribution
(see for example: https://www.slac.stanford.edu/slac/sass/talks/MonteCarloSASS.pdf)