PBR --- Specular IBL
PBR(Physically Based Rendering),是一系列基于物理的渲染技术的统称,这些渲染技术都在不同程度上基于相同的更符合物理世界规律的基础理论。
In the previous chapter we’ve set up PBR in combination with image based lighting by pre-computing an irradiance map as the lighting’s indirect diffuse portion. In this chapter we’ll focus on the specular part of the reflectance equation:
在上一章中,我们通过预计算辐照度图(irradiance map)作为光照的间接漫反射部分,把 PBR 与基于图像的光照(IBL)结合了起来。本章我们将聚焦于反射方程中的镜面反射部分:
\[L_o{\small(p,\omega_o)} = \int\limits_{\Omega} \big( k_d\frac{c}{\pi} + k_s\frac{DFG}{4 \big( \omega_o \cdot n \big) \big( \omega_i \cdot n \big)} \big) L_i{\small(p,\omega_i)} \big( n \cdot \omega_i \big) d\omega_i\]注意:$L_i{\small(p,\omega_i)}$ 是函数,这里面的括号指明函数的参数,表示 $L_i$ 是关于参数 $p$ 和 $\omega_i$ 的函数。而 $\big( n \cdot \omega_i \big)$ 是代数表达式,这里面的括号作用是指明运算优先级,优先进行 $n$ 和 $\omega_i$ 的点积运算。注意认识函数和代数表达式,防止因括号造成混淆误解。$L_i{\small(p,\omega_i)} \big( n \cdot \omega_i \big)$ 是上述二者的数乘。
You’ll notice that the Cook-Torrance specular portion (multiplied by $k_s$) isn’t constant over the integral and is dependent on the incoming light direction, but also the incoming view direction. Trying to solve the integral for all incoming light directions including all possible view directions is a combinatorial overload and way too expensive to calculate on a real-time basis. Epic Games proposed a solution where they were able to pre-convolute the specular part for real time purposes, given a few compromises, known as the split sum approximation.
你会注意到,Cook-Torrance 镜面反射部分(乘以 $k_s$ 的那一项)在积分区间内并不是常数,它不仅依赖于入射光方向 $\omega_i$,还依赖于观察方向 $\omega_o$。若要对「所有入射光方向 × 所有可能的观察方向」这一组合集合求解积分,组合数量会急剧膨胀,在实时渲染中完全不可行。Epic Games 提出了一种方案:在做出若干妥协的前提下,预先卷积镜面反射部分以满足实时需求,这就是所谓的拆分求和近似(split sum approximation)。
The split sum approximation splits the specular part of the reflectance equation into two separate parts that we can individually convolute and later combine in the PBR shader for specular indirect image based lighting. Similar to how we pre-convoluted the irradiance map, the split sum approximation requires an HDR environment map as its convolution input. To understand the split sum approximation we’ll again look at the reflectance equation, but this time focus on the specular part:
拆分求和近似把反射方程的镜面反射部分拆成两个独立的部分,二者可以分别卷积,之后再在 PBR 着色器中组合,用于基于图像的镜面反射间接光照。与预卷积辐照度图一样,拆分求和近似同样需要一张 HDR 环境贴图作为卷积输入。为理解拆分求和近似,我们再次审视反射方程,不过这次只关注其中的镜面反射部分:
\[L_o{\small(p,\omega_o)} = \int\limits_{\Omega} k_s\frac{DFG}{4 \big( \omega_o \cdot n \big) \big( \omega_i \cdot n \big)} L_i{\small(p,\omega_i)} \big( n \cdot \omega_i \big) d\omega_i = \int\limits_{\Omega} f_r {\small(p, \omega_i, \omega_o)} L_i{\small(p,\omega_i)} \big( n \cdot \omega_i \big) d\omega_i\]For the same (performance) reasons as the irradiance convolution, we can’t solve the specular part of the integral in real time and expect a reasonable performance. So preferably we’d pre-compute this integral to get something like a specular IBL map, sample this map with the fragment’s normal, and be done with it. However, this is where it gets a bit tricky. We were able to pre-compute the irradiance map as the integral only depended on $\omega_i$ and we could move the constant diffuse albedo terms out of the integral. This time, the integral depends on more than just $\omega_i$ as evident from the BRDF:
出于与辐照度卷积完全相同的(性能)原因,我们无法在实时条件下求解镜面反射部分的积分,并期望得到可接受的帧率。因此更理想的做法是把这个积分预计算成一张类似「镜面 IBL 贴图」的结果,渲染时只需用片段的法线采样一次即可。然而问题正是在这里变得棘手:我们之所以能预计算辐照度图,是因为那个积分只依赖于 $\omega_i$,并且可以把漫反射反照率等常数项提到积分号外面;而这一次,从 BRDF 的表达式就能看出,积分所依赖的变量不止 $\omega_i$:
\[f_r{\small(p, \omega_i, \omega_o)} = \frac{DFG}{4 \big( \omega_o \cdot n \big) \big( \omega_i \cdot n \big)}\]The integral also depends on $\omega_o$, and we can’t really sample a pre-computed cubemap with two direction vectors. The position $p$ is irrelevant here as described in the previous chapter. Pre-computing this integral for every possible combination of $\omega_i$ and $\omega_o$ isn’t practical in a real-time setting.
积分同样依赖于 $\omega_o$,而我们无法用两个方向向量去采样一张预计算的立方体贴图(立方体贴图采样只接受一个方向向量)。如上一章所述,位置 $p$ 在这里同样可以忽略。因此,为 $\omega_i$ 与 $\omega_o$ 的每一种可能组合都预计算这个积分,在实时渲染场景中并不现实。
Epic Games’ split sum approximation solves the issue by splitting the pre-computation into 2 individual parts that we can later combine to get the resulting pre-computed result we’re after. The split sum approximation splits the specular integral into two separate integrals:
Epic Games 的拆分求和近似正是为解决这一矛盾而提出:它把预计算拆成两个独立部分,之后再组合起来得到所需的结果。具体来说,拆分求和近似把镜面反射积分拆成两个积分:
\[L_o{\small(p,\omega_o)} = \int\limits_{\Omega} L_i{\small(p,\omega_i)} d\omega_i \cdot \int\limits_{\Omega} f_r{\small(p, \omega_i, \omega_o)} \big( n \cdot \omega_i \big) d\omega_i\]注意:被积函数中的余弦因子 $n \cdot \omega_i$ 并不能严格地这样一分为二,这里的拆分是一种近似:第一项把环境辐射率 $L_i$ 当作「按余弦加权的平均辐射率」来处理——预滤波阶段以 $N \cdot L$ 作为累加权重、最后再除以权重总和,正是把余弦因子归并进了这一项;第二项则只保留 BRDF 自身的响应。两项相乘后,整体结果在能量与亮度分布上都与真实积分非常接近,这正是该近似能在工业界广泛使用的原因。
The first part (when convoluted) is known as the pre-filtered environment map which is (similar to the irradiance map) a pre-computed environment convolution map, but this time taking roughness into account. For increasing roughness levels, the environment map is convoluted with more scattered sample vectors, creating blurrier reflections. For each roughness level we convolute, we store the sequentially blurrier results in the pre-filtered map’s mipmap levels. For instance, a pre-filtered environment map storing the pre-convoluted result of 5 different roughness values in its 5 mipmap levels looks as follows:
第一项卷积之后称为预滤波环境贴图(pre-filtered environment map)。它和辐照度图一样是一张预计算的环境卷积贴图,区别在于这次把粗糙度纳入了计算:粗糙度越高,卷积时使用的采样向量越分散,得到的反射也就越模糊。对每一个粗糙度级别我们都做一次卷积,并把逐步变模糊的结果依次存入预滤波贴图的各级 mipmap。例如,下图这张预滤波环境贴图就在它的 5 个 mipmap 层级中分别存有 5 个不同粗糙度值的预卷积结果:
We generate the sample vectors and their scattering amount using the normal distribution function (NDF) of the Cook-Torrance BRDF that takes as input both a normal and view direction. As we don’t know beforehand the view direction when convoluting the environment map, Epic Games makes a further approximation by assuming the view direction (and thus the specular reflection direction) to be equal to the output sample direction $\omega_o$. This translates itself to the following code:
采样向量的方向与分散程度由 Cook-Torrance BRDF 的法线分布函数(NDF)决定,而 NDF 的输入是法线方向与观察方向。但在卷积环境贴图时,我们事先并不知道观察方向,于是 Epic Games 又做了一层近似:假设观察方向(以及由它决定的镜面反射方向)就等于当前的输出采样方向 $\omega_o$。落到代码上就是:
1
2
3
vec3 N = normalize(w_o);
vec3 R = N;
vec3 V = R;
This way, the pre-filtered environment convolution doesn’t need to be aware of the view direction. This does mean we don’t get nice grazing specular reflections when looking at specular surface reflections from an angle as seen in the image below (courtesy of the Moving Frostbite to PBR article); this is however generally considered an acceptable compromise:
这样一来,预滤波的环境卷积就完全不需要感知观察方向了。代价是:当我们从斜角观察镜面表面时,得不到漂亮的掠射角镜面反射(如下图所示,图片出自 Moving Frostbite to PBR)。不过这一般被认为是可以接受的折中——掠射角区域的反射细节本就不是视觉上最敏感的部分,而换来的好处是任意粗糙度的环境反射都只需一次纹理采样。
The second part of the split sum equation equals the BRDF part of the specular integral. If we pretend the incoming radiance is completely white for every direction (thus $L(p, x) = 1.0$) we can pre-calculate the BRDF’s response given an input roughness and an input angle between the normal $n$ and light direction $\omega_i$, or $n \cdot \omega_i$. Epic Games stores the pre-computed BRDF’s response to each normal and light direction combination on varying roughness values in a 2D lookup texture (LUT) known as the BRDF integration map. The 2D lookup texture outputs a scale (red) and a bias value (green) to the surface’s Fresnel response giving us the second part of the split specular integral:
拆分求和方程的第二项对应镜面反射积分中的 BRDF 部分。如果我们假定每个方向上的入射辐射率都是纯白(即 $L(p, x) = 1.0$),就可以预先算出「给定粗糙度、给定法线 $n$ 与光照方向 $\omega_i$ 夹角($n \cdot \omega_i$)」时 BRDF 的响应。Epic Games 把不同粗糙度下、每一组法线与光照方向所对应的预计算 BRDF 响应,存入一张二维查找纹理(LUT),称为 BRDF 积分图(BRDF integration map)。这张查找纹理输出两个值,共同作用于表面的菲涅尔响应:红色通道是缩放系数(scale),绿色通道是偏移量(bias),二者构成拆分后镜面反射积分的第二项:
We generate the lookup texture by treating the horizontal texture coordinate (ranged between 0.0 and 1.0) of a plane as the BRDF’s input $n \cdot \omega_i$, and its vertical texture coordinate as the input roughness value. With this BRDF integration map and the pre-filtered environment map we can combine both to get the result of the specular integral:
生成这张查找纹理时,我们把一个平面纹理坐标的水平分量(范围 0.0~1.0)当作 BRDF 的输入 $n \cdot \omega_i$,垂直分量当作输入的粗糙度值。有了 BRDF 积分图与预滤波环境贴图,把两者组合起来就能得到镜面反射积分的结果:
1
2
3
4
float lod = getMipLevelFromRoughness(roughness);
vec3 prefilteredColor = textureCubeLod(PrefilteredEnvMap, refVec, lod);
vec2 envBRDF = texture2D(BRDFIntegrationMap, vec2(NdotV, roughness)).xy;
vec3 indirectSpecular = prefilteredColor * (F * envBRDF.x + envBRDF.y)
注意:
F * envBRDF.x + envBRDF.y这一步,本质上是把菲涅尔项 $F_0 + (1 - F_0)\alpha$ 重排成 $F_0 \cdot A + B$ 的形式:$F_0$ 被提到了积分之外,而 $A$、$B$ 作为对整个半球积分得到的系数,只与 $n \cdot \omega_o$ 和粗糙度有关,因此可以预先制表,运行时连乘加即可。
This should give you a bit of an overview on how Epic Games’ split sum approximation roughly approaches the indirect specular part of the reflectance equation. Let’s now try and build the pre-convoluted parts ourselves.
以上内容大致勾勒出 Epic Games 的拆分求和近似是如何处理反射方程中的间接镜面反射部分的。接下来,我们动手把这些预卷积的部分实现出来。
Pre-filtering an HDR environment map
Pre-filtering an environment map is quite similar to how we convoluted an irradiance map. The difference being that we now account for roughness and store sequentially rougher reflections in the pre-filtered map’s mip levels.
预滤波环境贴图与卷积辐照度图非常相似,区别在于现在要把粗糙度纳入计算,并把逐步变粗糙的反射结果存入预滤波贴图的各级 mip 层级中。
First, we need to generate a new cubemap to hold the pre-filtered environment map data. To make sure we allocate enough memory for its mip levels we call glGenerateMipmap as an easy way to allocate the required amount of memory:
首先需要生成一张新的立方体贴图来存放预滤波环境贴图数据。为了确保为各级 mipmap 分配了足够的内存,我们调用 glGenerateMipmap,这是一种便捷的内存分配方式:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
unsigned int prefilterMap;
glGenTextures(1, &prefilterMap);
glBindTexture(GL_TEXTURE_CUBE_MAP, prefilterMap);
for (unsigned int i = 0; i < 6; ++i)
{
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB16F, 128, 128, 0, GL_RGB, GL_FLOAT, nullptr);
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glGenerateMipmap(GL_TEXTURE_CUBE_MAP);
Note that because we plan to sample prefilterMap’s mipmaps you’ll need to make sure its minification filter is set to GL_LINEAR_MIPMAP_LINEAR to enable trilinear filtering. We store the pre-filtered specular reflections in a per-face resolution of 128 by 128 at its base mip level. This is likely to be enough for most reflections, but if you have a large number of smooth materials (think of car reflections) you may want to increase the resolution.
注意,由于后面要采样 prefilterMap 的 mipmap,其缩小过滤方式必须设为 GL_LINEAR_MIPMAP_LINEAR 以启用三线性过滤,否则在较粗的 mip 层级之间会出现明显的跳变。预滤波的镜面反射在基础 mip 层级上按每面 128×128 的分辨率存储,这对大多数反射已经足够;但如果场景中存在大量光滑材质(比如车漆反射),就需要适当提高这个分辨率。
In the previous chapter we convoluted the environment map by generating sample vectors uniformly spread over the hemisphere $\Omega$ using spherical coordinates. While this works just fine for irradiance, for specular reflections it’s less efficient. When it comes to specular reflections, based on the roughness of a surface, the light reflects closely or roughly around a reflection vector $r$ over a normal $n$, but (unless the surface is extremely rough) around the reflection vector nonetheless:
上一章我们通过球面坐标在半球 $\Omega$ 上均匀生成采样向量来卷积环境贴图。这种做法用于辐照度毫无问题,但对镜面反射而言效率很低。就镜面反射来说,根据表面粗糙度的不同,光线会紧密或松散地围绕法线 $n$ 上的反射向量 $r$ 分布——除非表面粗糙到极点,否则总体仍围绕反射向量展开:
The general shape of possible outgoing light reflections is known as the specular lobe. As roughness increases, the specular lobe’s size increases; and the shape of the specular lobe changes on varying incoming light directions. The shape of the specular lobe is thus highly dependent on the material.
这些可能出射方向的整体形状被称为镜面波瓣(specular lobe)。粗糙度增大时,波瓣随之变大;入射光方向改变时,波瓣形状也会变化。可见镜面波瓣的形状与材质特性高度相关。
When it comes to the microsurface model, we can imagine the specular lobe as the reflection orientation about the microfacet halfway vectors given some incoming light direction. Seeing as most light rays end up in a specular lobe reflected around the microfacet halfway vectors, it makes sense to generate the sample vectors in a similar fashion as most would otherwise be wasted. This process is known as importance sampling.
在微表面模型中,可以把镜面波瓣理解为:给定入射光方向时,出射方向围绕微表面半程向量(halfway vector)的分布。既然绝大多数光线最终都落在围绕半程向量的镜面波瓣内,那么按照同样的分布去生成采样向量就非常合理——否则绝大多数采样都会落在波瓣之外,被白白浪费掉。这一过程就是重要性采样(importance sampling)。
Monte Carlo integration and importance sampling
To fully get a grasp of importance sampling it’s relevant we first delve into the mathematical construct known as Monte Carlo integration. Monte Carlo integration revolves mostly around a combination of statistics and probability theory. Monte Carlo helps us in discretely solving the problem of figuring out some statistic or value of a population without having to take all of the population into consideration.
要彻底理解重要性采样,有必要先了解被称为蒙特卡洛积分(Monte Carlo integration)的数学工具。它本质上是统计学与概率论的结合:当无法(或不愿)遍历总体中的全部个体时,它可以只用一个足够小的随机子集来估计总体的某项统计量或数值。
For instance, let’s say you want to count the average height of all citizens of a country. To get your result, you could measure every citizen and average their height which will give you the exact answer you’re looking for. However, since most countries have a considerable population this isn’t a realistic approach: it would take too much effort and time. A different approach is to pick a much smaller completely random (unbiased) subset of this population, measure their height, and average the result. This population could be as small as a 100 people. While not as accurate as the exact answer, you’ll get an answer that is relatively close to the ground truth. This is known as the law of large numbers. The idea is that if you measure a smaller set of size $N$ of truly random samples from the total population, the result will be relatively close to the true answer and gets closer as the number of samples $N$ increases.
举一个直观的例子:假设要统计某个国家全体公民的平均身高。你可以测量每一位公民再求平均,这会给出精确答案,但面对庞大的人口显然不现实——太费时费力。另一种做法是从总体中随意抽取一个规模小得多的完全随机(无偏)子集,测量他们的身高再求平均,哪怕只有 100 人。结果虽不精确,却会相当接近真实值。这就是大数定律(law of large numbers):只要子集是从总体中真正随机抽取的,样本量 $N$ 越大,结果就越接近真实答案。
Monte Carlo integration builds on this law of large numbers and takes the same approach in solving an integral. Rather than solving an integral for all possible (theoretically infinite) sample values $x$, simply generate $N$ sample values randomly picked from the total population and average. As $N$ increases, we’re guaranteed to get a result closer to the exact answer of the integral:
蒙特卡洛积分建立在大数定律之上,用同样的思路求解积分:与其对全部(理论上无穷多)的采样值 $x$ 求积分,不如从总体中随机抽取 $N$ 个采样值再求平均。随着 $N$ 增大,结果必然越来越接近积分的精确解:
\[O = \int\limits_{a}^{b} f(x) dx = \frac{1}{N} \sum_{i=0}^{N-1} \frac{f(x_i)}{pdf(x_i)}\]To solve the integral, we take $N$ random samples over the population $a$ to $b$, add them together, and divide by the total number of samples to average them. The $pdf$ stands for the probability density function that tells us the probability a specific sample occurs over the total sample set. For instance, the pdf of the height of a population would look a bit like this:
具体做法是:在区间 $[a, b]$ 上随机取 $N$ 个样本,累加后除以样本总数求平均。式中的 $pdf$ 表示概率密度函数(probability density function),它描述某个特定样本在整个样本集合中出现的概率。例如,人口身高的概率密度函数大致如下图所示:
From this graph we can see that if we take any random sample of the population, there is a higher chance of picking a sample of someone of height 1.70, compared to the lower probability of the sample being of height 1.50.
从图中可以看出,随机取值时抽到身高 1.70 的样本的概率,要高于抽到身高 1.50 的样本的概率。
When it comes to Monte Carlo integration, some samples may have a higher probability of being generated than others. This is why for any general Monte Carlo estimation we divide or multiply the sampled value by the sample probability according to a pdf. So far, in each of our cases of estimating an integral, the samples we’ve generated were uniform, having the exact same chance of being generated. Our estimations so far were unbiased, meaning that given an ever-increasing amount of samples we will eventually converge to the exact solution of the integral.
在蒙特卡洛积分中,不同样本被生成的概率可能并不相同,因此对一般的蒙特卡洛估计,都要依据 pdf 把采样值除以(或乘以)该样本的概率密度,这一步就是重要性权重修正。此前我们处理过的所有积分估计中,样本都是均匀生成的——每个样本被抽到的机会完全相同,因此估计是无偏的:随着采样数不断增加,最终会收敛到积分的精确解。
However, some Monte Carlo estimators are biased, meaning that the generated samples aren’t completely random, but focused towards a specific value or direction. These biased Monte Carlo estimators have a faster rate of convergence, meaning they can converge to the exact solution at a much faster rate, but due to their biased nature it’s likely they won’t ever converge to the exact solution. This is generally an acceptable tradeoff, especially in computer graphics, as the exact solution isn’t too important as long as the results are visually acceptable. As we’ll soon see with importance sampling (which uses a biased estimator), the generated samples are biased towards specific directions in which case we account for this by multiplying or dividing each sample by its corresponding pdf.
然而,也可以让估计器有偏:生成的样本并不完全随机,而是集中偏向某个数值或方向。这类有偏估计器的收敛速度更快,能以更高的速率逼近精确解;但正因为有偏,它很可能永远无法真正收敛到精确解。这通常是可接受的权衡——尤其在计算机图形学中,只要视觉上令人信服,精确解并不那么重要。接下来要讲的重要性采样使用的正是有偏估计器:样本被偏向特定方向,我们再通过除以(或乘以)对应的 pdf 来补偿这一偏差。
Monte Carlo integration is quite prevalent in computer graphics as it’s a fairly intuitive way to approximate continuous integrals in a discrete and efficient fashion: take any area/volume to sample over (like the hemisphere $\Omega$), generate $N$ amount of random samples within the area/volume, and sum and weigh every sample contribution to the final result.
蒙特卡洛积分在计算机图形学中极为常见,因为它以离散、高效且直观的方式近似连续积分:任选一片待采样的区域/体积(例如半球 $\Omega$),在其中随机生成 $N$ 个样本,再把每个样本的贡献加权求和,得到最终结果。
Monte Carlo integration is an extensive mathematical topic and I won’t delve much further into the specifics, but we’ll mention that there are multiple ways of generating the random samples. By default, each sample is completely (pseudo)random as we’re used to, but by utilizing certain properties of semi-random sequences we can generate sample vectors that are still random, but have interesting properties. For instance, we can do Monte Carlo integration on something called low-discrepancy sequences which still generate random samples, but each sample is more evenly distributed (image courtesy of James Heald):
蒙特卡洛积分是个内容广博的数学话题,这里不再深入细节,但需要指出:随机样本的生成方式有多种。默认情况下,每个样本都是我们熟悉的完全(伪)随机值;而利用某些半随机序列的性质,可以生成仍然随机、却具备优良分布的采样向量。例如,可以对所谓的低差异序列(low-discrepancy sequence)做蒙特卡洛积分——它依然产生随机样本,但样本分布更加均匀(图片由 James Heald 提供):
When using a low-discrepancy sequence for generating the Monte Carlo sample vectors, the process is known as Quasi-Monte Carlo integration. Quasi-Monte Carlo methods have a faster rate of convergence which makes them interesting for performance heavy applications.
用低差异序列生成蒙特卡洛采样向量时,这一过程被称为准蒙特卡洛积分(Quasi-Monte Carlo integration)。准蒙特卡洛方法收敛更快,因此在性能敏感的场合极具吸引力。
Given our newly obtained knowledge of Monte Carlo and Quasi-Monte Carlo integration, there is an interesting property we can use for an even faster rate of convergence known as importance sampling. We’ve mentioned it before in this chapter, but when it comes to specular reflections of light, the reflected light vectors are constrained in a specular lobe with its size determined by the roughness of the surface. Seeing as any (quasi-)randomly generated sample outside the specular lobe isn’t relevant to the specular integral it makes sense to focus the sample generation to within the specular lobe, at the cost of making the Monte Carlo estimator biased.
在掌握蒙特卡洛与准蒙特卡洛积分之后,还有一个能进一步加快收敛的性质可用,那就是重要性采样。前面已经提到:光的镜面反射向量被限制在由表面粗糙度决定的镜面波瓣内。既然任何落在波瓣之外的(准)随机样本对镜面反射积分都没有实质贡献,那么把采样集中在波瓣内部就是明智的,代价只是让估计器变成有偏的。
This is in essence what importance sampling is about: generate sample vectors in some region constrained by the roughness oriented around the microfacet’s halfway vector. By combining Quasi-Monte Carlo sampling with a low-discrepancy sequence and biasing the sample vectors using importance sampling, we get a high rate of convergence. Because we reach the solution at a faster rate, we’ll need significantly fewer samples to reach an approximation that is sufficient enough.
这便是重要性采样的本质:在由粗糙度约束、围绕微表面半程向量的区域内生成采样向量。把准蒙特卡洛采样、低差异序列与重要性采样三者结合起来,就能获得很高的收敛速度;收敛更快意味着达到足够好的近似所需的样本数大幅减少。
A low-discrepancy sequence
In this chapter we’ll pre-compute the specular portion of the indirect reflectance equation using importance sampling given a random low-discrepancy sequence based on the Quasi-Monte Carlo method. The sequence we’ll be using is known as the Hammersley Sequence as carefully described by Holger Dammertz. The Hammersley sequence is based on the Van Der Corput sequence which mirrors a decimal binary representation around its decimal point.
本章我们将基于准蒙特卡洛方法、使用低差异序列,通过重要性采样预计算间接反射方程的镜面反射部分。所用序列是 Hammersley 序列,其详细说明可参见 Holger Dammertz 的文章。Hammersley 序列建立在 Van Der Corput 序列之上——后者把整数的二进制表示以小数点为轴做镜像翻转(radical inverse),得到一个分布在 $[0,1)$ 内的小数。
Given some neat bit tricks, we can quite efficiently generate the Van Der Corput sequence in a shader program which we’ll use to get a Hammersley sequence sample $i$ over N total samples:
借助若干巧妙的位运算技巧,我们可以在着色器中相当高效地生成 Van Der Corput 序列,从而得到总样本数为 N 时第 i 个 Hammersley 样本:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
float RadicalInverse_VdC(uint bits)
{
bits = (bits << 16u) | (bits >> 16u);
bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);
bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);
bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);
bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);
return float(bits) * 2.3283064365386963e-10; // / 0x100000000
}
// ----------------------------------------------------------------------------
vec2 Hammersley(uint i, uint N)
{
return vec2(float(i)/float(N), RadicalInverse_VdC(i));
}
The GLSL Hammersley function gives us the low-discrepancy sample $i$ of the total sample set of size $N$.
Hammersley 函数返回规模为 N 的样本集合中的第 i 个低差异样本:横坐标是均匀铺开的 i / N,纵坐标是第 i 个数的 Van Der Corput 序列值。横向的等间距保证了覆盖率,纵向的镜像二进制小数则不断填充前者留下的空隙,二者组合在单位正方形内的分布远比纯随机均匀。
Hammersley sequence without bit operator support
Not all OpenGL related drivers support bit operators (WebGL and OpenGL ES 2.0 for instance) in which case you may want to use an alternative version of the Van Der Corput Sequence that doesn’t rely on bit operators:
不支持位运算符时的 Hammersley 序列
并非所有与 OpenGL 相关的驱动都支持位运算符(例如 WebGL 与 OpenGL ES 2.0),此时可以改用不依赖位运算符的 Van Der Corput 序列版本:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
float VanDerCorput(uint n, uint base)
{
float invBase = 1.0 / float(base);
float denom = 1.0;
float result = 0.0;
for(uint i = 0u; i < 32u; ++i)
{
if(n > 0u)
{
denom = mod(float(n), 2.0);
result += denom * invBase;
invBase = invBase / 2.0;
n = uint(float(n) / 2.0);
}
}
return result;
}
// ----------------------------------------------------------------------------
vec2 HammersleyNoBitOps(uint i, uint N)
{
return vec2(float(i)/float(N), VanDerCorput(i, 2u));
}
Note that due to GLSL loop restrictions in older hardware, the sequence loops over all possible 32 bits. This version is less performant, but does work on all hardware if you ever find yourself without bit operators.
注意,由于老硬件对 GLSL 循环的限制,这个版本固定遍历全部 32 个二进制位(而不是在 n 变成 0 时提前退出)。它的性能较差,但当目标硬件确实缺少位运算支持时,它是可用的兜底方案。
GGX Importance sampling
Instead of uniformly or randomly (Monte Carlo) generating sample vectors over the integral’s hemisphere $\Omega$, we’ll generate sample vectors biased towards the general reflection orientation of the microsurface halfway vector based on the surface’s roughness. The sampling process will be similar to what we’ve seen before: begin a large loop, generate a random (low-discrepancy) sequence value, take the sequence value to generate a sample vector in tangent space, transform to world space, and sample the scene’s radiance. What’s different is that we now use a low-discrepancy sequence value as input to generate a sample vector:
我们不再在积分的半球 $\Omega$ 上均匀或随机(蒙特卡洛)地生成采样向量,而是依据表面粗糙度,让采样向量偏向微表面半程向量所指示的反射方向。采样流程与之前类似:开一个大循环,取一个(低差异)随机序列值,用它生成切线空间中的采样向量,再变换到世界空间并采样场景辐射率。不同之处在于,生成采样向量的输入换成了低差异序列值:
1
2
3
4
const uint SAMPLE_COUNT = 4096u;
for(uint i = 0u; i < SAMPLE_COUNT; ++i)
{
vec2 Xi = Hammersley(i, SAMPLE_COUNT);
Additionally, to build a sample vector, we need some way of orienting and biasing the sample vector towards the specular lobe of some surface roughness. We can take the NDF as described in the theory chapter and combine the GGX NDF in the spherical sample vector process as described by Epic Games:
此外,为了构造采样向量,还需要有办法让它朝向并偏向给定粗糙度对应的镜面波瓣。这里采用理论章节介绍过的法线分布函数(NDF),并按照 Epic Games 的做法,把 GGX 形式的 NDF 融入球面采样向量的生成过程:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
vec3 ImportanceSampleGGX(vec2 Xi, vec3 N, float roughness)
{
float a = roughness*roughness;
float phi = 2.0 * PI * Xi.x;
float cosTheta = sqrt((1.0 - Xi.y) / (1.0 + (a*a - 1.0) * Xi.y));
float sinTheta = sqrt(1.0 - cosTheta*cosTheta);
// from spherical coordinates to cartesian coordinates
vec3 H;
H.x = cos(phi) * sinTheta;
H.y = sin(phi) * sinTheta;
H.z = cosTheta;
// from tangent-space vector to world-space sample vector
vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);
vec3 tangent = normalize(cross(up, N));
vec3 bitangent = cross(N, tangent);
vec3 sampleVec = tangent * H.x + bitangent * H.y + N * H.z;
return normalize(sampleVec);
}
注意:
cosTheta那一行是对 GGX 法线分布做逆变换采样的结果——以 $D(h)\cos\theta_h$ 作为概率密度函数,积分得到累积分布函数后反解,即得 $\cos\theta = \sqrt{\frac{1-\xi}{1+(a^2-1)\xi}}$。倾斜角越小(越接近法线)的半程向量被抽到的概率越大,采样点自然集中到镜面波瓣内部。而up的选取是一个健壮性处理:当 $N$ 接近 $(0,0,1)$ 时改用 $(1,0,0)$,避免叉乘得到零向量而无法构造切线空间。
This gives us a sample vector somewhat oriented around the expected microsurface’s halfway vector based on some input roughness and the low-discrepancy sequence value Xi. Note that Epic Games uses the squared roughness for better visual results as based on Disney’s original PBR research.
这样,给定输入粗糙度与低差异序列值 Xi,我们就得到一个大致朝向预期微表面半程向量的采样向量。注意 Epic Games 在这里使用的是粗糙度的平方(a = roughness * roughness),这是沿用 Disney 最初 PBR 研究的做法,能获得更好的视觉效果。
With the low-discrepancy Hammersley sequence and sample generation defined, we can finalize the pre-filter convolution shader:
定义了低差异 Hammersley 序列与采样函数之后,我们就可以写出完整的预滤波卷积着色器了:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#version 330 core
out vec4 FragColor;
in vec3 localPos;
uniform samplerCube environmentMap;
uniform float roughness;
const float PI = 3.14159265359;
float RadicalInverse_VdC(uint bits);
vec2 Hammersley(uint i, uint N);
vec3 ImportanceSampleGGX(vec2 Xi, vec3 N, float roughness);
void main()
{
vec3 N = normalize(localPos);
vec3 R = N;
vec3 V = R;
const uint SAMPLE_COUNT = 1024u;
float totalWeight = 0.0;
vec3 prefilteredColor = vec3(0.0);
for(uint i = 0u; i < SAMPLE_COUNT; ++i)
{
vec2 Xi = Hammersley(i, SAMPLE_COUNT);
vec3 H = ImportanceSampleGGX(Xi, N, roughness);
vec3 L = normalize(2.0 * dot(V, H) * H - V);
float NdotL = max(dot(N, L), 0.0);
if(NdotL > 0.0)
{
prefilteredColor += texture(environmentMap, L).rgb * NdotL;
totalWeight += NdotL;
}
}
prefilteredColor = prefilteredColor / totalWeight;
FragColor = vec4(prefilteredColor, 1.0);
}
We pre-filter the environment, based on some input roughness that varies over each mipmap level of the pre-filter cubemap (from 0.0 to 1.0), and store the result in prefilteredColor. The resulting prefilteredColor is divided by the total sample weight, where samples with less influence on the final result (for small NdotL) contribute less to the final weight.
我们按传入的粗糙度对环境做预滤波——该粗糙度在预滤波立方体贴图的各 mip 层级上从 0.0 渐变到 1.0——并把结果累加到 prefilteredColor。最后除以权重总和:对最终结果影响更小的样本(NdotL 较小)在总权重中占的份额也更小。这里的 L 是由半程向量 H 关于 V 反射得到的入射方向(L = 2(V·H)H - V),而 V = R = N 正是前面提到的近似。
Capturing pre-filter mipmap levels
What’s left to do is let OpenGL pre-filter the environment map with different roughness values over multiple mipmap levels. This is actually fairly easy to do with the original setup of the irradiance chapter:
剩下的工作是让 OpenGL 在多个 mipmap 层级上以不同粗糙度对环境贴图做预滤波。借助辐照度章节搭建的那套框架,这其实相当容易:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
prefilterShader.use();
prefilterShader.setInt("environmentMap", 0);
prefilterShader.setMat4("projection", captureProjection);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_CUBE_MAP, envCubemap);
glBindFramebuffer(GL_FRAMEBUFFER, captureFBO);
unsigned int maxMipLevels = 5;
for (unsigned int mip = 0; mip < maxMipLevels; ++mip)
{
// reisze framebuffer according to mip-level size.
unsigned int mipWidth = 128 * std::pow(0.5, mip);
unsigned int mipHeight = 128 * std::pow(0.5, mip);
glBindRenderbuffer(GL_RENDERBUFFER, captureRBO);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, mipWidth, mipHeight);
glViewport(0, 0, mipWidth, mipHeight);
float roughness = (float)mip / (float)(maxMipLevels - 1);
prefilterShader.setFloat("roughness", roughness);
for (unsigned int i = 0; i < 6; ++i)
{
prefilterShader.setMat4("view", captureViews[i]);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, prefilterMap, mip);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
renderCube();
}
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
The process is similar to the irradiance map convolution, but this time we scale the framebuffer’s dimensions to the appropriate mipmap scale, each mip level reducing the dimensions by a scale of 2. Additionally, we specify the mip level we’re rendering into in glFramebufferTexture2D’s last parameter and pass the roughness we’re pre-filtering for to the pre-filter shader.
该过程与辐照度图卷积类似,但这次把帧缓冲尺寸缩放到对应的 mip 尺寸,每升高一级 mip 尺寸减半;同时在 glFramebufferTexture2D 的最后一个参数中指定要渲染到的 mip 层级,并把当前预滤波的粗糙度传给着色器。maxMipLevels = 5 时,5 个层级对应的粗糙度依次为 0.0、0.25、0.5、0.75、1.0。
This should give us a properly pre-filtered environment map that returns blurrier reflections the higher mip level we access it from. If we use the pre-filtered environment cubemap in the skybox shader and forcefully sample somewhat above its first mip level like so:
这样我们就得到了正确预滤波的环境贴图:访问的 mip 层级越高,返回的反射就越模糊。如果在天空盒着色器中改用这张预滤波立方体贴图,并强制采样第 1 层 mip 略偏上的位置:
1
vec3 envColor = textureLod(environmentMap, WorldPos, 1.2).rgb;
We get a result that indeed looks like a blurrier version of the original environment:
我们会得到看起来确实像是原环境模糊版本的结果:
If it looks somewhat similar you’ve successfully pre-filtered the HDR environment map. Play around with different mipmap levels to see the pre-filter map gradually change from sharp to blurry reflections on increasing mip levels.
如果效果大致相似,说明你已成功对 HDR 环境贴图完成了预滤波。不妨切换不同 mip 层级,观察预滤波贴图如何随 mip 升高,从清晰的反射逐步变为模糊的反射。
Pre-filter convolution artifacts
While the current pre-filter map works fine for most purposes, sooner or later you’ll come across several render artifacts that are directly related to the pre-filter convolution. I’ll list the most common here including how to fix them.
目前的预滤波贴图在多数情形下都能正常工作,但你迟早会遇到几种与预滤波卷积直接相关的渲染瑕疵。下面列出最常见的几种,以及各自的修复方法。
Cubemap seams at high roughness
Sampling the pre-filter map on surfaces with a rough surface means sampling the pre-filter map on some of its lower mip levels. When sampling cubemaps, OpenGL by default doesn’t linearly interpolate across cubemap faces. Because the lower mip levels are both of a lower resolution and the pre-filter map is convoluted with a much larger sample lobe, the lack of between-cube-face filtering becomes quite apparent:
在粗糙表面上采样预滤波贴图,实际采样的是它较低的若干 mip 层级。而采样立方体贴图时,OpenGL 默认不会在立方体贴图的面与面之间做线性插值。低 mip 层级的分辨率本就更低,加上预滤波时使用了大得多的采样波瓣,”面间不过滤”的问题就会非常明显:
Luckily for us, OpenGL gives us the option to properly filter across cubemap faces by enabling GL_TEXTURE_CUBE_MAP_SEAMLESS:
好在 OpenGL 提供了跨面过滤的开关——启用 GL_TEXTURE_CUBE_MAP_SEAMLESS 即可:
1
glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
Simply enable this property somewhere at the start of your application and the seams will be gone.
只需在应用程序启动时启用一次,接缝就会消失。
Bright dots in the pre-filter convolution
Due to high frequency details and wildly varying light intensities in specular reflections, convoluting the specular reflections requires a large number of samples to properly account for the wildly varying nature of HDR environmental reflections. We already take a very large number of samples, but on some environments it may still not be enough at some of the rougher mip levels in which case you’ll start seeing dotted patterns emerge around bright areas:
镜面反射中含有大量高频细节,且 HDR 环境中的光强变化极为剧烈,因此卷积镜面反射需要足够多的样本才能正确反映这种变化。我们取的样本数已经很多,但在某些环境、某些较粗糙的 mip 层级上仍然不够,这时亮区周围就会出现点状图案:
One option is to further increase the sample count, but this won’t be enough for all environments. As described by Chetan Jags we can reduce this artifact by (during the pre-filter convolution) not directly sampling the environment map, but sampling a mip level of the environment map based on the integral’s PDF and the roughness:
一种办法是继续增加采样数,但这并不能对所有环境奏效。正如 Chetan Jags 所述,我们可以这样减轻该瑕疵:预滤波时不再直接采样环境贴图的第 0 层,而是依据积分的概率密度函数(PDF)与粗糙度,采样环境贴图的某个 mip 层级:
1
2
3
4
5
6
7
8
float D = DistributionGGX(NdotH, roughness);
float pdf = (D * NdotH / (4.0 * HdotV)) + 0.0001;
float resolution = 512.0; // resolution of source cubemap (per face)
float saTexel = 4.0 * PI / (6.0 * resolution * resolution);
float saSample = 1.0 / (float(SAMPLE_COUNT) * pdf + 0.0001);
float mipLevel = roughness == 0.0 ? 0.0 : 0.5 * log2(saSample / saTexel);
注意:这段代码的思路是让采样足迹与纹素覆盖率相匹配。
saTexel是源立方体贴图每个纹素所张的立体角(整个球面为 $4\pi$,6 个面共 $6 \times resolution^2$ 个纹素);saSample则是由 PDF 推算出的单个样本所代表的立体角。二者之比取以 2 为底的对数再乘 0.5,正好换算出「用哪一级 mip 上的纹素去近似这个样本的足迹」——于是单点采样变成了对预先平均过的纹素采样,也就不容易漏掉亮斑了。
Don’t forget to enable trilinear filtering on the environment map you want to sample its mip levels from:
别忘了为需要采样 mip 层级的那张环境贴图启用三线性过滤:
1
2
glBindTexture(GL_TEXTURE_CUBE_MAP, envCubemap);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
And let OpenGL generate the mipmaps after the cubemap’s base texture is set:
并且要在立方体贴图的基础层级设置完成之后,再让 OpenGL 生成 mipmap:
1
2
3
4
5
// convert HDR equirectangular environment map to cubemap equivalent
[...]
// then generate mipmaps
glBindTexture(GL_TEXTURE_CUBE_MAP, envCubemap);
glGenerateMipmap(GL_TEXTURE_CUBE_MAP);
This works surprisingly well and should remove most, if not all, dots in your pre-filter map on rougher surfaces.
这一招效果出奇地好,基本能消除预滤波贴图在粗糙表面上的全部白点。
Pre-computing the BRDF
With the pre-filtered environment up and running, we can focus on the second part of the split-sum approximation: the BRDF. Let’s briefly review the specular split sum approximation again:
预滤波环境贴图已经就绪,现在可以专注于拆分求和近似的第二部分:BRDF。让我们简要回顾一下镜面反射的拆分求和近似:
\[L_o{\small(p,\omega_o)} = \int\limits_{\Omega} L_i{\small(p,\omega_i)} d\omega_i \cdot \int\limits_{\Omega} f_r{\small(p, \omega_i, \omega_o)} \big( n \cdot \omega_i \big) d\omega_i\]We’ve pre-computed the left part of the split sum approximation in the pre-filter map over different roughness levels. The right side requires us to convolute the BRDF equation over the angle $n \cdot \omega_o$, the surface roughness, and Fresnel’s $F_0$. This is similar to integrating the specular BRDF with a solid-white environment or a constant radiance $L_i$ of 1.0. Convoluting the BRDF over 3 variables is a bit much, but we can try to move $F_0$ out of the specular BRDF equation:
拆分求和近似的左半部分,我们已经按不同粗糙度级别预计算进预滤波贴图了。右侧则需要把 BRDF 方程对 $n \cdot \omega_o$ 的夹角、表面粗糙度以及菲涅尔的 $F_0$ 三者做卷积。这相当于在纯白环境(恒定辐射率 $L_i = 1.0$)下对镜面 BRDF 求积分。对 3 个变量做卷积负担确实偏重,不过我们可以尝试把 $F_0$ 提到积分号外面:
\[\int\limits_{\Omega} f_r{\small(p, \omega_i, \omega_o)} \big( n \cdot \omega_i \big) d\omega_i = \int\limits_{\Omega} f_r{\small(p, \omega_i, \omega_o)} \frac{F{\small(\omega_o, h)}}{F{\small(\omega_o, h)}} \big( n \cdot \omega_i \big) d\omega_i\]With $F$ being the Fresnel equation. Moving the Fresnel denominator to the BRDF gives us the following equivalent equation:
其中 $F$ 是菲涅尔方程。把作为分母的菲涅尔项并入 BRDF,就得到下面这个等价的式子:
\[\int\limits_{\Omega} \frac{f_r{\small(p, \omega_i, \omega_o)}}{F{\small(\omega_o, h)}} F{\small(\omega_o, h)} \big( n \cdot \omega_i \big) d\omega_i\]Substituting the right-most $F$ with the Fresnel-Schlick approximation gives us:
把最右侧的 $F$ 用菲涅尔-施利克近似代入:
\[\int\limits_{\Omega} \frac{f_r{\small(p, \omega_i, \omega_o)}}{F{\small(\omega_o, h)}} \big( F_0 + (1 - F_0){\small(1 - \omega_o \cdot h)}^5 \big) \big( n \cdot \omega_i \big) d\omega_i\]Let’s replace ${(1 - \omega_o \cdot h)}^5$ by $\alpha$ to make it easier to solve for $F_0$:
为了更容易地把 $F_0$ 分离出来,我们用 $\alpha$ 代替 ${\small(1 - \omega_o \cdot h)}^5$:
\[\int\limits_{\Omega} \frac{f_r{\small(p, \omega_i, \omega_o)}}{F{\small(\omega_o, h)}} \big( F_0 + (1 - F_0)\alpha \big) \big( n \cdot \omega_i \big) d\omega_i\] \[\int\limits_{\Omega} \frac{f_r{\small(p, \omega_i, \omega_o)}}{F{\small(\omega_o, h)}} \big( F_0 + \alpha - F_0 \alpha \big) \big( n \cdot \omega_i \big) d\omega_i\] \[\int\limits_{\Omega} \frac{f_r{\small(p, \omega_i, \omega_o)}}{F{\small(\omega_o, h)}} \big( F_0 (1 - \alpha) + \alpha \big) \big( n \cdot \omega_i \big) d\omega_i\]Then we split the Fresnel function $F$ over two integrals:
于是把菲涅尔函数 $F$ 拆到两个积分中:
\[\int\limits_{\Omega} \frac{f_r{\small(p, \omega_i, \omega_o)}}{F{\small(\omega_o, h)}} \big( F_0 (1 - \alpha) \big) \big( n \cdot \omega_i \big) d\omega_i + \int\limits_{\Omega} \frac{f_r{\small(p, \omega_i, \omega_o)}}{F{\small(\omega_o, h)}} \alpha \big( n \cdot \omega_i \big) d\omega_i\]This way, $F_0$ is constant over the integral and we can take $F_0$ out of the integral. Next, we substitute $\alpha$ back to its original form giving us the final split sum BRDF equation:
这样 $F_0$ 在积分内就是常数,可以提到积分号外。接下来把 $\alpha$ 换回原来的形式,就得到最终的拆分求和 BRDF 方程:
\[F_0 \int\limits_{\Omega} f_r{\small(p, \omega_i, \omega_o)} \big( 1 - {\small(1 - \omega_o \cdot h)}^5 \big) \big( n \cdot \omega_i \big) d\omega_i + \int\limits_{\Omega} f_r{\small(p, \omega_i, \omega_o)} {\small(1 - \omega_o \cdot h)}^5 \big( n \cdot \omega_i \big) d\omega_i\]The two resulting integrals represent a scale and a bias to $F_0$ respectively. Note that as $f_r(p, \omega_i, \omega_o)$ already contains a term for $F$ they both cancel out, removing $F$ from $f_r$.
得到的两个积分分别代表对 $F_0$ 的缩放系数与偏移量。注意,由于 $f_r{\small(p, \omega_i, \omega_o)}$ 本身已经含有菲涅尔项 $F$,二者正好相互抵消,因此 $f_r$ 中的 $F$ 被消去了——这也是为什么最终结果只与 $n \cdot \omega_o$ 和粗糙度有关。
In a similar fashion to the earlier convoluted environment maps, we can convolute the BRDF equations on their inputs: the angle between $n$ and $\omega_o$, and the roughness. We store the convoluted results in a 2D lookup texture (LUT) known as a BRDF integration map that we later use in our PBR lighting shader to get the final convoluted indirect specular result.
与之前卷积环境贴图的方式类似,我们可以针对 BRDF 方程的输入——$n$ 与 $\omega_o$ 之间的夹角、以及表面粗糙度——做卷积。卷积结果存储在二维查找纹理(LUT)中,也就是 BRDF 积分图,随后在 PBR 光照着色器中用它得到最终的间接镜面反射卷积结果。
The BRDF convolution shader operates on a 2D plane, using its 2D texture coordinates directly as inputs to the BRDF convolution (NdotV and roughness). The convolution code is largely similar to the pre-filter convolution, except that it now processes the sample vector according to our BRDF’s geometry function and Fresnel-Schlick’s approximation:
BRDF 卷积着色器作用于一个二维平面,直接使用二维纹理坐标作为 BRDF 卷积的输入(NdotV 与粗糙度)。卷积代码与预滤波卷积大体相似,区别在于它按照 BRDF 的几何函数与菲涅尔-施利克近似来处理采样向量:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
vec2 IntegrateBRDF(float NdotV, float roughness)
{
vec3 V;
V.x = sqrt(1.0 - NdotV*NdotV);
V.y = 0.0;
V.z = NdotV;
float A = 0.0;
float B = 0.0;
vec3 N = vec3(0.0, 0.0, 1.0);
const uint SAMPLE_COUNT = 1024u;
for(uint i = 0u; i < SAMPLE_COUNT; ++i)
{
vec2 Xi = Hammersley(i, SAMPLE_COUNT);
vec3 H = ImportanceSampleGGX(Xi, N, roughness);
vec3 L = normalize(2.0 * dot(V, H) * H - V);
float NdotL = max(L.z, 0.0);
float NdotH = max(H.z, 0.0);
float VdotH = max(dot(V, H), 0.0);
if(NdotL > 0.0)
{
float G = GeometrySmith(N, V, L, roughness);
float G_Vis = (G * VdotH) / (NdotH * NdotV);
float Fc = pow(1.0 - VdotH, 5.0);
A += (1.0 - Fc) * G_Vis;
B += Fc * G_Vis;
}
}
A /= float(SAMPLE_COUNT);
B /= float(SAMPLE_COUNT);
return vec2(A, B);
}
// ----------------------------------------------------------------------------
void main()
{
vec2 integratedBRDF = IntegrateBRDF(TexCoords.x, TexCoords.y);
FragColor = integratedBRDF;
}
As you can see, the BRDF convolution is a direct translation from the mathematics to code. We take both the angle $\theta$ and the roughness as input, generate a sample vector with importance sampling, process it over the geometry and the derived Fresnel term of the BRDF, and output both a scale and a bias to $F_0$ for each sample, averaging them in the end.
可以看到,BRDF 卷积就是数学公式到代码的直接翻译:以夹角 $\theta$ 与粗糙度作为输入,用重要性采样生成采样向量,再用 BRDF 的几何项和推导出的菲涅尔项处理它,为每个样本累加出对 $F_0$ 的缩放系数与偏移量,最后求平均。这里 N 固定为 $(0,0,1)$,V 由 NdotV 反解得出(位于 $xz$ 平面内),因此整个积分在切线空间中完成,无需额外的基向量变换。
You may recall from the theory chapter that the geometry term of the BRDF is slightly different when used alongside IBL as its $k$ variable has a slightly different interpretation:
你可能还记得理论章节中提到过:当 BRDF 的几何项与 IBL 一起使用时,其形式会略有不同,因为其中 $k$ 变量的含义有所变化:
\[k_{direct} = \frac{(\alpha + 1)^2}{8}, \qquad k_{IBL} = \frac{\alpha^2}{2}\]Since the BRDF convolution is part of the specular IBL integral we’ll use $k_{IBL}$ for the Schlick-GGX geometry function:
由于 BRDF 卷积属于镜面 IBL 积分的一部分,在 Schlick-GGX 几何函数中我们要使用 $k_{IBL}$:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
float GeometrySchlickGGX(float NdotV, float roughness)
{
float a = roughness;
float k = (a * a) / 2.0;
float nom = NdotV;
float denom = NdotV * (1.0 - k) + k;
return nom / denom;
}
// ----------------------------------------------------------------------------
float GeometrySmith(vec3 N, vec3 V, vec3 L, float roughness)
{
float NdotV = max(dot(N, V), 0.0);
float NdotL = max(dot(N, L), 0.0);
float ggx2 = GeometrySchlickGGX(NdotV, roughness);
float ggx1 = GeometrySchlickGGX(NdotL, roughness);
return ggx1 * ggx2;
}
Note that while $k$ takes $a$ as its parameter we didn’t square roughness as $a$ as we originally did for other interpretations of $a$; likely as $a$ is squared here already. I’m not sure whether this is an inconsistency on Epic Games’ part or the original Disney paper, but directly translating roughness to $a$ gives the BRDF integration map that is identical to Epic Games’ version.
注意,虽然 $k$ 以 $a$ 为参数,但这里并没有像处理其他 $a$ 时那样再对 roughness 求平方——原因大概是这里的 $a$ 本身已经是平方后的结果(k = a*a / 2.0,相当于 $roughness^2/2$,与 $k_{IBL} = \alpha^2/2$ 一致)。这一点在 Epic Games 或原始 Disney 论文中是否算作不一致,我无法确定,但直接把 roughness 赋给 $a$,得到的 BRDF 积分图与 Epic Games 的版本完全一致。
Finally, to store the BRDF convolution result we’ll generate a 2D texture of a 512 by 512 resolution:
最后,为了存储 BRDF 卷积结果,我们生成一张分辨率为 512×512 的二维纹理:
1
2
3
4
5
6
7
8
9
10
unsigned int brdfLUTTexture;
glGenTextures(1, &brdfLUTTexture);
// pre-allocate enough memory for the LUT texture.
glBindTexture(GL_TEXTURE_2D, brdfLUTTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RG16F, 512, 512, 0, GL_RG, GL_FLOAT, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
Note that we use a 16-bit precision floating format as recommended by Epic Games. Be sure to set the wrapping mode to GL_CLAMP_TO_EDGE to prevent edge sampling artifacts.
注意,我们按 Epic Games 的建议使用了 16 位精度的浮点格式(GL_RG16F),两个通道分别存放 scale 与 bias。务必把环绕方式设为 GL_CLAMP_TO_EDGE,以避免边缘采样产生的瑕疵。
Then, we re-use the same framebuffer object and run this shader over an NDC screen-space quad:
然后复用同一个帧缓冲对象,在 NDC 屏幕空间的一个四边形上运行这个着色器:
1
2
3
4
5
6
7
8
9
10
11
glBindFramebuffer(GL_FRAMEBUFFER, captureFBO);
glBindRenderbuffer(GL_RENDERBUFFER, captureRBO);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, 512, 512);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, brdfLUTTexture, 0);
glViewport(0, 0, 512, 512);
brdfShader.use();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
RenderQuad();
glBindFramebuffer(GL_FRAMEBUFFER, 0);
The convoluted BRDF part of the split sum integral should give you the following result:
拆分求和积分中经过卷积的 BRDF 部分,应当给出如下结果:
With both the pre-filtered environment map and the BRDF 2D LUT we can re-construct the indirect specular integral according to the split sum approximation. The combined result then acts as the indirect or ambient specular light.
有了预滤波环境贴图与 BRDF 二维 LUT,我们就可以按照拆分求和近似重构间接镜面反射积分。组合后的结果即作为间接(环境)镜面反射光。
Completing the IBL reflectance
To get the indirect specular part of the reflectance equation up and running we need to stitch both parts of the split sum approximation together. Let’s start by adding the pre-computed lighting data to the top of our PBR shader:
要让反射方程中的间接镜面反射部分真正工作起来,需要把拆分求和近似的两个部分缝合在一起。首先,在 PBR 着色器顶部加入预计算得到的光照数据:
1
2
uniform samplerCube prefilterMap;
uniform sampler2D brdfLUT;
First, we get the indirect specular reflections of the surface by sampling the pre-filtered environment map using the reflection vector. Note that we sample the appropriate mip level based on the surface roughness, giving rougher surfaces blurrier specular reflections:
先用反射向量采样预滤波环境贴图,得到表面的间接镜面反射。注意要依据表面粗糙度采样合适的 mip 层级,从而让越粗糙的表面得到越模糊的镜面反射:
1
2
3
4
5
6
7
8
9
void main()
{
[...]
vec3 R = reflect(-V, N);
const float MAX_REFLECTION_LOD = 4.0;
vec3 prefilteredColor = textureLod(prefilterMap, R, roughness * MAX_REFLECTION_LOD).rgb;
[...]
}
In the pre-filter step we only convoluted the environment map up to a maximum of 5 mip levels (0 to 4), which we denote here as MAX_REFLECTION_LOD to ensure we don’t sample a mip level where there’s no (relevant) data.
在预滤波阶段,我们最多只对环境贴图卷积了 5 个 mip 层级(0 到 4),这里用 MAX_REFLECTION_LOD 表示,以确保不会采样到没有(有效)数据的层级。粗糙度 0.0~1.0 线性映射到 LOD 0~4。
Then we sample from the BRDF lookup texture given the material’s roughness and the angle between the normal and view vector:
接着,依据材质的粗糙度以及法线与视线向量之间的夹角,对 BRDF 查找纹理进行采样:
1
2
3
vec3 F = FresnelSchlickRoughness(max(dot(N, V), 0.0), F0, roughness);
vec2 envBRDF = texture(brdfLUT, vec2(max(dot(N, V), 0.0), roughness)).rg;
vec3 specular = prefilteredColor * (F * envBRDF.x + envBRDF.y);
Given the scale and bias to $F_0$ (here we’re directly using the indirect Fresnel result $F$) from the BRDF lookup texture, we combine this with the left pre-filter portion of the IBL reflectance equation and re-construct the approximated integral result as specular.
BRDF 查找纹理给出了对 $F_0$ 的缩放系数与偏移量(这里我们直接使用了间接光照的菲涅尔结果 $F$,它已经包含粗糙度修正),把它与 IBL 反射方程左侧的预滤波部分相乘再相加,即可重构出近似的积分结果,作为 specular。
This gives us the indirect specular part of the reflectance equation. Now, combine this with the diffuse IBL part of the reflectance equation from the last chapter and we get the full PBR IBL result:
至此我们得到了反射方程中的间接镜面反射部分。现在把它与上一章得到的 IBL 漫反射部分结合,就得到了完整的 PBR IBL 结果:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
vec3 F = FresnelSchlickRoughness(max(dot(N, V), 0.0), F0, roughness);
vec3 kS = F;
vec3 kD = 1.0 - kS;
kD *= 1.0 - metallic;
vec3 irradiance = texture(irradianceMap, N).rgb;
vec3 diffuse = irradiance * albedo;
const float MAX_REFLECTION_LOD = 4.0;
vec3 prefilteredColor = textureLod(prefilterMap, R, roughness * MAX_REFLECTION_LOD).rgb;
vec2 envBRDF = texture(brdfLUT, vec2(max(dot(N, V), 0.0), roughness)).rg;
vec3 specular = prefilteredColor * (F * envBRDF.x + envBRDF.y);
vec3 ambient = (kD * diffuse + specular) * ao;
Note that we don’t multiply specular by $k_s$ as we already have a Fresnel multiplication in there.
注意,这里没有再把 specular 乘以 $k_s$(即 kS),因为该项中已经包含了一次菲涅尔乘法。另外,漫反射部分乘上了 1.0 - metallic:金属没有漫反射,这一项保证了金属表面的间接漫反射被完全去除。
Now, running this exact code on the series of spheres that differ by their roughness and metallic properties, we finally get to see their true colors in the final PBR renderer:
现在,把这套代码原样作用在那组按粗糙度与金属度变化的球体上,我们终于能在最终的 PBR 渲染器中看到它们真正的样子:
We could even go wild, and use some cool textured PBR materials:
我们甚至可以更进一步,使用一些效果酷炫的带纹理 PBR 材质:
Or load this awesome free 3D PBR model by Andrew Maximov:
或者加载 这个由 Andrew Maximov 提供的免费 3D PBR 模型:
I’m sure we can all agree that our lighting now looks a lot more convincing. What’s even better, is that our lighting looks physically correct regardless of which environment map we use. Below you’ll see several different pre-computed HDR maps, completely changing the lighting dynamics, but still looking physically correct without changing a single lighting variable!
相信大家都会同意,现在画面的光照真实得多。更妙的是,无论使用哪张环境贴图,光照都保持物理正确。下面你会看到几张不同的预计算 HDR 贴图,它们彻底改变了光照氛围,却没有改动任何一个光照参数,画面依然物理可信!
Well, this PBR adventure turned out to be quite a long journey. There are a lot of steps and thus a lot that could go wrong so carefully work your way through the sphere scene or textured scene code samples (including all shaders) if you’re stuck, or check and ask around in the comments.
好了,这段 PBR 之旅可谓漫长。步骤很多,出错的可能性也就很多——如果卡住了,请仔细研读球体场景或带纹理场景的示例代码(包含所有着色器),或者在评论区查看、提问。
What’s next?
Hopefully, by the end of this tutorial you should have a pretty clear understanding of what PBR is about, and even have an actual PBR renderer up and running. In these tutorials, we’ve pre-computed all the relevant PBR image-based lighting data at the start of our application, before the render loop. This was fine for educational purposes, but not too great for any practical use of PBR. First, the pre-computation only really has to be done once, not at every startup. And second, the moment you use multiple environment maps you’ll have to pre-compute each and every one of them at every startup which tends to build up.
希望读到教程末尾时,你对 PBR 的内涵已经有了相当清晰的理解,甚至已经跑通了一个真正的 PBR 渲染器。在这些教程中,我们在应用程序启动时、渲染循环之前预计算了所有相关的 PBR 基于图像光照数据。这对教学目的而言没有问题,但对 PBR 的实际应用并不理想:其一,预计算其实只需要做一次,而不必每次启动都做;其二,一旦使用多张环境贴图,就必须在每次启动时把它们逐一预计算,累积的开销会相当可观。
For this reason you’d generally pre-compute an environment map into an irradiance and pre-filter map just once, and then store it on disk (note that the BRDF integration map isn’t dependent on an environment map so you only need to calculate or load it once). This does mean you’ll need to come up with a custom image format to store HDR cubemaps, including their mip levels. Or, you’ll store (and load) it as one of the available formats (like .dds that supports storing mip levels).
因此通常的做法是:把一张环境贴图预计算成辐照度图与预滤波图只做一次,然后存到磁盘上(BRDF 积分图不依赖任何环境贴图,所以只需计算或加载一次即可)。这意味着你需要设计一种自定义图像格式来保存 HDR 立方体贴图及其 mip 层级;或者把它存成(并从)现有格式加载,例如支持保存 mip 层级的 .dds。
Furthermore, we’ve described the total process in these tutorials, including generating the pre-computed IBL images to help further our understanding of the PBR pipeline. But, you’ll be just as fine by using several great tools like cmftStudio or IBLBaker to generate these pre-computed maps for you.
此外,这些教程描述了完整的流程,包括生成预计算的 IBL 图像,目的是帮助加深对 PBR 管线的理解。不过在工程实践中,你完全可以借助 cmftStudio 或 IBLBaker 这类优秀工具来替你生成这些预计算贴图。
One point we’ve skipped over is pre-computed cubemaps as reflection probes: cubemap interpolation and parallax correction. This is the process of placing several reflection probes in your scene that take a cubemap snapshot of the scene at that specific location, which we can then convolute as IBL data for that part of the scene. By interpolating between several of these probes based on the camera’s vicinity we can achieve local high-detail image-based lighting that is simply limited by the amount of reflection probes we’re willing to place. This way, the image-based lighting could correctly update when moving from a bright outdoor section of a scene to a darker indoor section for instance. I’ll write a tutorial about reflection probes somewhere in the future, but for now I recommend the article by Chetan Jags below to give you a head start.
还有一个我们跳过的话题:把预计算的立方体贴图用作反射探针(reflection probe),即立方体贴图之间的插值与视差校正。做法是在场景中放置若干反射探针,在每个探针所在的特定位置对场景拍摄一张立方体贴图快照,再把它卷积成该区域的 IBL 数据。通过根据相机与各探针的距离进行插值,我们就能获得局部的高精度基于图像光照,其质量只取决于我们愿意放置多少探针。这样一来,当相机从场景中明亮的室外区域移动到较暗的室内区域时,基于图像的光照也能正确地随之变化。将来我会专门写一篇关于反射探针的教程,目前建议先阅读下面 Chetan Jags 的文章入门。












