PBR基本介绍

PBR代表基于物理的渲染,本质上还是

  1. gl_FragColor = Emssive + Ambient + Diffuse + Specular

可能高级一些在考虑下AO也就是环境光遮蔽就是下面的情况

  1. vec4 generalColor = Ambient + Diffuse + Specular);
  2. gl_FragColor = Emssive + mix(color, color * ao, u_OcclusionStrength)

在非PBR模式下,这种光照方式往往看着不真实,为啥呢,专家说因为能量不守恒,跟人眼在客观世界看到的不一样;然后就出现了基于物理的渲染。这种渲染模式呢,大方向模块还是以上那个。但是在各个模块计算过程中充分考虑了能量守恒,各个模块的计算式经过一系列复杂的数学推导计算出来。比如下面这个

  •  L(P,V)是经过P点反射(diffuse或specular)后进入视点V的光
  •  L(P,-V)是从-V方向射入P点的光
  •  R是对应的BRDF(双向反射分布函数)函数,会考虑各种物理现象(能量守恒Energy conservation、粗糙度Roughness、材质的次表面散射subsurface scattering、材质折射率各向异性Fresnel、绝缘度(这玩意用来调整diffuse和specular的能量分配)metallic)

最讨厌这种公式,看着就让人烦,我们这里只要记住,BRDF就是从能量守恒角度考虑的一个计算公式,这个玩意具体公式是做实验做出来的,有好多个,最常用的一个叫Cook-Torrance。一般来说PBR计算过程是比较复杂的,直接在实时渲染里面计算式很耗费时间的,所以数学家有做了一堆拆分,让某些计算因子可以提前进行预处理,放在几个纹理中。对于工程师来说,我不想了解后面具体的物理学和数学推导,我只想知道怎么用来做项目。所以,一言不合看源码(源码来自luma.gl)。

  1. vec4 pbr_filterColor(vec4 colorUnused)
  2. {
  3. // Metallic and Roughness material properties are packed together
  4. // In glTF, these factors can be specified by fixed scalar values
  5. // or from a metallic-roughness map
  6. float perceptualRoughness = u_MetallicRoughnessValues.y;
  7. float metallic = u_MetallicRoughnessValues.x;
  8. #ifdef HAS_METALROUGHNESSMAP
  9. // Roughness is stored in the 'g' channel, metallic is stored in the 'b' channel.
  10. // This layout intentionally reserves the 'r' channel for (optional) occlusion map data
  11. vec4 mrSample = texture2D(u_MetallicRoughnessSampler, pbr_vUV);
  12. perceptualRoughness = mrSample.g * perceptualRoughness;
  13. metallic = mrSample.b * metallic;
  14. #endif
  15. perceptualRoughness = clamp(perceptualRoughness, c_MinRoughness, 1.0);
  16. metallic = clamp(metallic, 0.0, 1.0);
  17. // Roughness is authored as perceptual roughness; as is convention,
  18. // convert to material roughness by squaring the perceptual roughness [2].
  19. float alphaRoughness = perceptualRoughness * perceptualRoughness;
  20.  
  21. // The albedo may be defined from a base texture or a flat color
  22. #ifdef HAS_BASECOLORMAP
  23. vec4 baseColor = SRGBtoLINEAR(texture2D(u_BaseColorSampler, pbr_vUV)) * u_BaseColorFactor;
  24. #else
  25. vec4 baseColor = u_BaseColorFactor;
  26. #endif
  27.  
  28. #ifdef ALPHA_CUTOFF
  29. if (baseColor.a < u_AlphaCutoff) {
  30. discard;
  31. }
  32. #endif
  33.  
  34. vec3 f0 = vec3(0.04);
  35. vec3 diffuseColor = baseColor.rgb * (vec3(1.0) - f0);
  36. diffuseColor *= 1.0 - metallic;
  37. vec3 specularColor = mix(f0, baseColor.rgb, metallic);
  38.  
  39. // Compute reflectance.
  40. float reflectance = max(max(specularColor.r, specularColor.g), specularColor.b);
  41.  
  42. // For typical incident reflectance range (between 4% to 100%) set the grazing
  43. // reflectance to 100% for typical fresnel effect.
  44. // For very low reflectance range on highly diffuse objects (below 4%),
  45. // incrementally reduce grazing reflecance to 0%.
  46. float reflectance90 = clamp(reflectance * 25.0, 0.0, 1.0);
  47. vec3 specularEnvironmentR0 = specularColor.rgb;
  48. vec3 specularEnvironmentR90 = vec3(1.0, 1.0, 1.0) * reflectance90;
  49.  
  50. vec3 n = getNormal(); // normal at surface point
  51. vec3 v = normalize(u_Camera - pbr_vPosition); // Vector from surface point to camera
  52.  
  53. float NdotV = clamp(abs(dot(n, v)), 0.001, 1.0);
  54. vec3 reflection = -normalize(reflect(v, n));
  55.  
  56. PBRInfo pbrInputs = PBRInfo(
  57. 0.0, // NdotL
  58. NdotV,
  59. 0.0, // NdotH
  60. 0.0, // LdotH
  61. 0.0, // VdotH
  62. perceptualRoughness,
  63. metallic,
  64. specularEnvironmentR0,
  65. specularEnvironmentR90,
  66. alphaRoughness,
  67. diffuseColor,
  68. specularColor,
  69. n,
  70. v
  71. );
  72.  
  73. vec3 color = vec3(, , );
  74.  
  75. #ifdef USE_LIGHTS
  76. // Apply ambient light
  77. PBRInfo_setAmbientLight(pbrInputs);
  78. color += calculateFinalColor(pbrInputs, lighting_uAmbientLight.color);
  79.  
  80. // Apply directional light
  81. SMART_FOR(int i = , i < MAX_LIGHTS, i < lighting_uDirectionalLightCount, i++) {
  82. if (i < lighting_uDirectionalLightCount) {
  83. PBRInfo_setDirectionalLight(pbrInputs, lighting_uDirectionalLight[i].direction);
  84. color += calculateFinalColor(pbrInputs, lighting_uDirectionalLight[i].color);
  85. }
  86. }
  87.  
  88. // Apply point light
  89. SMART_FOR(int i = , i < MAX_LIGHTS, i < lighting_uPointLightCount, i++) {
  90. if (i < lighting_uPointLightCount) {
  91. PBRInfo_setPointLight(pbrInputs, lighting_uPointLight[i]);
  92. float attenuation = getPointLightAttenuation(lighting_uPointLight[i], distance(lighting_uPointLight[i].position, pbr_vPosition));
  93. color += calculateFinalColor(pbrInputs, lighting_uPointLight[i].color / attenuation);
  94. }
  95. }
  96. #endif
  97.  
  98. // Calculate lighting contribution from image based lighting source (IBL)
  99. #ifdef USE_IBL
  100. color += getIBLContribution(pbrInputs, n, reflection);
  101. #endif
  102.  
  103. // Apply optional PBR terms for additional (optional) shading
  104. #ifdef HAS_OCCLUSIONMAP
  105. float ao = texture2D(u_OcclusionSampler, pbr_vUV).r;
  106. color = mix(color, color * ao, u_OcclusionStrength);
  107. #endif
  108.  
  109. #ifdef HAS_EMISSIVEMAP
  110. vec3 emissive = SRGBtoLINEAR(texture2D(u_EmissiveSampler, pbr_vUV)).rgb * u_EmissiveFactor;
  111. color += emissive;
  112. #endif
  113.  
  114. // This section uses mix to override final color for reference app visualization
  115. // of various parameters in the lighting equation.
  116. #ifdef PBR_DEBUG
  117. // TODO: Figure out how to debug multiple lights
  118.  
  119. // color = mix(color, F, u_ScaleFGDSpec.x);
  120. // color = mix(color, vec3(G), u_ScaleFGDSpec.y);
  121. // color = mix(color, vec3(D), u_ScaleFGDSpec.z);
  122. // color = mix(color, specContrib, u_ScaleFGDSpec.w);
  123.  
  124. // color = mix(color, diffuseContrib, u_ScaleDiffBaseMR.x);
  125. color = mix(color, baseColor.rgb, u_ScaleDiffBaseMR.y);
  126. color = mix(color, vec3(metallic), u_ScaleDiffBaseMR.z);
  127. color = mix(color, vec3(perceptualRoughness), u_ScaleDiffBaseMR.w);
  128. #endif
  129.  
  130. return vec4(pow(color,vec3(1.0/2.2)), baseColor.a);
  131. }

一堆数学计算看不懂。。。没关系,慢慢拆分

如果模型采用PBR材质,最少需要两个两张纹理:albedo和metalRoughness。Albedo对应该模型的纹理,就是我们常用的的baseColor。metalRoughness对应rgba的g和b两位,范围是[0,1],对应模型的g(roughness)和b(metallic)。这个metallic属性,用来描述该模型对应P点在绝缘体和金属之间的一个度,金属的反射率相对较高,该系数用来调整diffuse和specular的能量分配。那么这一部分,主要目的是求一个粗糙度和绝缘系数。

  1. // Metallic and Roughness material properties are packed together
  2. // In glTF, these factors can be specified by fixed scalar values
  3. // or from a metallic-roughness map
  4. float perceptualRoughness = u_MetallicRoughnessValues.y;
  5. float metallic = u_MetallicRoughnessValues.x;
  6. #ifdef HAS_METALROUGHNESSMAP
  7. // Roughness is stored in the 'g' channel, metallic is stored in the 'b' channel.
  8. // This layout intentionally reserves the 'r' channel for (optional) occlusion map data
  9. vec4 mrSample = texture2D(u_MetallicRoughnessSampler, pbr_vUV);
  10. perceptualRoughness = mrSample.g * perceptualRoughness;
  11. metallic = mrSample.b * metallic;
  12. #endif
  13. perceptualRoughness = clamp(perceptualRoughness, c_MinRoughness, 1.0);
  14. metallic = clamp(metallic, 0.0, 1.0);
  15. // Roughness is authored as perceptual roughness; as is convention,
  16. // convert to material roughness by squaring the perceptual roughness [2].
  17. float alphaRoughness = perceptualRoughness * perceptualRoughness;

上面说的albedo从下面的纹理中获取

  1. // The albedo may be defined from a base texture or a flat color
  2. #ifdef HAS_BASECOLORMAP
  3. vec4 baseColor = SRGBtoLINEAR(texture2D(u_BaseColorSampler, pbr_vUV)) * u_BaseColorFactor;
  4. #else
  5. vec4 baseColor = u_BaseColorFactor;
  6. #endif
  7.  
  8. #ifdef ALPHA_CUTOFF
  9. if (baseColor.a < u_AlphaCutoff) {
  10. discard;
  11. }
  12. #endif

下面代码是求了一个镜像反射系数,这个镜像反射系数为了满足菲涅尔效果,在不同角度下系数不一样(4%~100%)之间。下面的25就是1/0.4的值。specularEnvironmentR0 和 specularEnvironmentR90 我猜是代表视线和法线夹角在0和90的一个反射颜色。

  1. // Compute reflectance.
  2. float reflectance = max(max(specularColor.r, specularColor.g), specularColor.b);
  3.  
  4. // For typical incident reflectance range (between 4% to 100%) set the grazing
  5. // reflectance to 100% for typical fresnel effect.
  6. // For very low reflectance range on highly diffuse objects (below 4%),
  7. // incrementally reduce grazing reflecance to 0%.
  8. // 对于典型的入射反射范围(在4%到100%之间),将掠射反射率设置为100%以获得典型的菲涅耳效果。对于高度漫反射对象上的极低反射范围(低于4%),请以增量方式将掠过反射减少到0%。
  9. float reflectance90 = clamp(reflectance * 25.0, 0.0, 1.0);
  10. vec3 specularEnvironmentR0 = specularColor.rgb;
  11. vec3 specularEnvironmentR90 = vec3(1.0, 1.0, 1.0) * reflectance90;

根据法线和视线计算出夹角和反射向量。getNormal的计算过程也是涉及到法向量切变空间,这个后续在继续。同时这里要特别注意这个向量的原点在哪里,这是在视空间还是世界空间中的计算。

  1. vec3 n = getNormal(); // normal at surface point
  2. vec3 v = normalize(u_Camera - pbr_vPosition); // Vector from surface point to camera
  3.  
  4. float NdotV = clamp(abs(dot(n, v)), 0.001, 1.0);
  5. vec3 reflection = -normalize(reflect(v, n));

组装PBRInfo以及设置初始颜色值

  1. PBRInfo pbrInputs = PBRInfo(
  2. 0.0, // NdotL
  3. NdotV,
  4. 0.0, // NdotH
  5. 0.0, // LdotH
  6. 0.0, // VdotH
  7. perceptualRoughness,
  8. metallic,
  9. specularEnvironmentR0,
  10. specularEnvironmentR90,
  11. alphaRoughness,
  12. diffuseColor,
  13. specularColor,
  14. n,
  15. v
  16. );
  17.  
  18. vec3 color = vec3(0, 0, 0);

根据不同的光源类型,环境光、方向光源、点光源进行光照计算。这个跟普通的光照模式一样

  1. #ifdef USE_LIGHTS
  2. // Apply ambient light
  3. PBRInfo_setAmbientLight(pbrInputs);
  4. color += calculateFinalColor(pbrInputs, lighting_uAmbientLight.color);
  5.  
  6. // Apply directional light
  7. SMART_FOR(int i = 0, i < MAX_LIGHTS, i < lighting_uDirectionalLightCount, i++) {
  8. if (i < lighting_uDirectionalLightCount) {
  9. PBRInfo_setDirectionalLight(pbrInputs, lighting_uDirectionalLight[i].direction);
  10. color += calculateFinalColor(pbrInputs, lighting_uDirectionalLight[i].color);
  11. }
  12. }
  13.  
  14. // Apply point light
  15. SMART_FOR(int i = 0, i < MAX_LIGHTS, i < lighting_uPointLightCount, i++) {
  16. if (i < lighting_uPointLightCount) {
  17. PBRInfo_setPointLight(pbrInputs, lighting_uPointLight[i]);
  18. float attenuation = getPointLightAttenuation(lighting_uPointLight[i], distance(lighting_uPointLight[i].position, pbr_vPosition));
  19. color += calculateFinalColor(pbrInputs, lighting_uPointLight[i].color / attenuation);
  20. }
  21. }
  22. #endif

这块可以认为是除了普通的环境光之外,其他来自四面发放的光。光源在环境中经过其他各种物体反射、折射等汇集而来的光。

  1. // Calculate lighting contribution from image based lighting source (IBL)
  2. #ifdef USE_IBL
  3. color += getIBLContribution(pbrInputs, n, reflection);
  4. #endif

下面是计算环境光遮蔽的效果,这个也是提前处理在一张纹理上了。环境光遮蔽又是一个专门的话题。

文档:Cesium源码剖析---Ambient Occlusion(?..

链接:http://note.youdao.com/noteshare?id=5d3122657947fcb43010948ea5f7d627&sub=D56577007ABC43A696F84D0CA968EA27

上面这个是安哥写的文章。

  1. // Apply optional PBR terms for additional (optional) shading
  2. #ifdef HAS_OCCLUSIONMAP
  3. float ao = texture2D(u_OcclusionSampler, pbr_vUV).r;
  4. color = mix(color, color * ao, u_OcclusionStrength);
  5. #endif

处理自发光的纹理。这里纹理都是在gamma颜色空间中,要先转变成线性空间。gamma的来龙去脉也是个专题。

文档:ThreeJS 不可忽略的事情 - Gamma色彩空...

链接:http://note.youdao.com/noteshare?id=f5ab02acba1260bb2e0be26c56a9d281&sub=77FA63C5D6C24A2D8202B1D623519666

  1. #ifdef HAS_EMISSIVEMAP
  2. vec3 emissive = SRGBtoLINEAR(texture2D(u_EmissiveSampler, pbr_vUV)).rgb * u_EmissiveFactor;
  3. color += emissive;
  4. #endif

最后就是由线性空间转变成gamma空间。

  1. return vec4(pow(color,vec3(1.0/2.2)), baseColor.a);

PBR核心

看起来也很简单是不,那是因为大部分代码都封装在calculateFinalColor函数中了。

接下来看一下PBR真正的核心:

  1. vec3 calculateFinalColor(PBRInfo pbrInputs, vec3 lightColor) {
  2. // Calculate the shading terms for the microfacet specular shading model
  3. vec3 F = specularReflection(pbrInputs);
  4. float G = geometricOcclusion(pbrInputs);
  5. float D = microfacetDistribution(pbrInputs);
  6.  
  7. // Calculation of analytical lighting contribution
  8. vec3 diffuseContrib = (1.0 - F) * diffuse(pbrInputs);
  9. vec3 specContrib = F * G * D / (4.0 * pbrInputs.NdotL * pbrInputs.NdotV);
  10. // Obtain final intensity as reflectance (BRDF) scaled by the energy of the light (cosine law)
  11. return pbrInputs.NdotL * lightColor * (diffuseContrib + specContrib);
  12. }

再回到最初这个公式:

现在根据代码来重新解释下面几个部分。

  •  L(P,V)是经过P点反射(diffuse或specular)后进入视点V的光;就是return的返回值
  •  L(P,-V)是从-V方向射入P点的光,可以认为代码中的lightColor
  •  R是对应的BRDF(双向反射分布函数)函数,可以认为是代码中的(diffuseContrib + specContrib)部分
  •  N*V' 是代码中的pbrInputs.NdotL

这里的BRDF是根据下面公式来的。

diffuse采用的是Lambert模型:

,C是漫反射光的颜色Color,这里认为该点微观上是一个平面,漫反射以一个半圆180°均匀反射,所以除以π;至于这里的代码是考虑了菲涅尔效果,进行了一个调整,为啥这么搞我也不是很清楚。

  1. // Basic Lambertian diffuse
  2. // Implementation from Lambert's Photometria https://archive.org/details/lambertsphotome00lambgoog
  3. // See also [1], Equation 1
  4. vec3 diffuse(PBRInfo pbrInputs)
  5. {
  6. return pbrInputs.diffuseColor / M_PI;
  7. }

而后就是Specular部分,这个里面有FGD三个因素,分别是考虑菲涅尔反射、L光源能够到达V视角的概率、表面粗糙度。

(F)resnel reflectance;菲涅尔反射

既然是Fresnel,不难理解,该函数主要是用来计算不同介质之间光的折射,简化后的Schlick公式可以取得近似值,公式如下,在中心点时l和h为零度角,cos=1.为F(0),为该材质的base reflectivity,在45°时,还基本不变,但接近90°时,则反射率则迅速提升到1,符合之前Fresnel的变化曲线

  1. // The following equation models the Fresnel reflectance term of the spec equation (aka F())
  2. // Implementation of fresnel from [4], Equation 15
  3. vec3 specularReflection(PBRInfo pbrInputs)
  4. {
  5. return pbrInputs.reflectance0 +
  6. (pbrInputs.reflectance90 - pbrInputs.reflectance0) *
  7. pow(clamp(1.0 - pbrInputs.VdotH, 0.0, 1.0), 5.0);
  8. }

(G)eometric term

表示从L光源能够到达V视角的概率,G称为双向阴影遮挡函数,也就是v会被其他的微面元遮挡(如下图所示),这里glTF采用的是GGX,而Cesium则是Schlick模型:(不过luma的代码好像做了一些优化,具体没细研究)

最后考虑到能量守恒,需要在diffuse和specular之间添加参数,控制两者的比例,这里也有多种方式,比如前面提到的Disney给出的公式(glTF和Cesium中都采用该公式),也有论文里提到的diffuse Fresnel term:

  1. // This calculates the specular geometric attenuation (aka G()),
  2. // where rougher material will reflect less light back to the viewer.
  3. // This implementation is based on [1] Equation 4, and we adopt their modifications to
  4. // alphaRoughness as input as originally proposed in [2].
  5. float geometricOcclusion(PBRInfo pbrInputs)
  6. {
  7. float NdotL = pbrInputs.NdotL;
  8. float NdotV = pbrInputs.NdotV;
  9. float r = pbrInputs.alphaRoughness;
  10.  
  11. float attenuationL = 2.0 * NdotL / (NdotL + sqrt(r * r + (1.0 - r * r) * (NdotL * NdotL)));
  12. float attenuationV = 2.0 * NdotV / (NdotV + sqrt(r * r + (1.0 - r * r) * (NdotV * NdotV)));
  13. return attenuationL * attenuationV;
  14. }

Normal (d)istribution term

该函数用来描述材质的roughness,在能量守恒下,控制物体在反射与折射间的分配,glTF中采用的是Trowbridge-Reitz GGX公式,其中α是唯一参数,而h可以通过粗糙度α和法线n求解:

(又是一堆公式,以后遇到直接拿来用,不在公式上花费时间)

  1. // The following equation(s) model the distribution of microfacet normals across
  2. // the area being drawn (aka D())
  3. // Implementation from "Average Irregularity Representation of a Roughened Surface
  4. // for Ray Reflection" by T. S. Trowbridge, and K. P. Reitz
  5. // Follows the distribution function recommended in the SIGGRAPH 2013 course notes
  6. // from EPIC Games [1], Equation 3.
  7. float microfacetDistribution(PBRInfo pbrInputs)
  8. {
  9. float roughnessSq = pbrInputs.alphaRoughness * pbrInputs.alphaRoughness;
  10. float f = (pbrInputs.NdotH * roughnessSq - pbrInputs.NdotH) * pbrInputs.NdotH + 1.0;
  11. return roughnessSq / (M_PI * f * f);
  12. }

IBL

现在环境光、点光源、平行光的计算基本说清楚了。还有一种是来自四面八方的光照计算。

对于来自四面八方的光,就有一个求和的过程,这里,对该积分做了如下两步近似求解

因为如上的近似推导,证明我们可以通过EnvironmentMap和BRDF lookup table两张纹理,对Sum求和的过程预处理,减少real time下的计算量。(这里是直接拷贝大牛的文章,根据我的理解就是IBLContrib部分可以简化成两个部分,环境贴图和一个根据BRDF公式计算出来的一个纹理(LUT,lookup table),这个纹理里面存储了对四面八方的光的specular部分进行参数调节的两个变量)

Environment Map和BRDF lookup table。前者根据不同的Roughness,计算对应光源的平均像素值。后者根据Roughness和视角计算出对应颜色的调整系数(scale和bias)。虽然两部分的计算量比较大,但都可以预处理,通常Cube Texture都是固定的,我们可以预先获取对应的Environment Map,根据Roughness构建MipMap;后者只跟Roughness和视角V的cos有关,一旦确定了BRDF模型,计算公式是固定的,也可以预先生成U(Roughness) V(cosV)对应的 Texture:

Cook-TorranceModel对应的LUT

这样,我们可以获取环境光的计算公式如下:

finalColor += PrefilteredColor * ( SpecularColor* EnvBRDF.x + EnvBRDF.y );

(这里理论和代码不是完全一致,这里的EnvironmentMap分为了两个,u_DiffuseEnvSampler和u_SpecularEnvSampler,当然这两个都是需要提前准备的)

  1. // Calculation of the lighting contribution from an optional Image Based Light source.
  2. // Precomputed Environment Maps are required uniform inputs and are computed as outlined in [1].
  3. // See our README.md on Environment Maps [3] for additional discussion.
  4. #ifdef USE_IBL
  5. vec3 getIBLContribution(PBRInfo pbrInputs, vec3 n, vec3 reflection)
  6. {
  7. float mipCount = 9.0; // resolution of 512x512
  8. float lod = (pbrInputs.perceptualRoughness * mipCount);
  9. // retrieve a scale and bias to F0. See [1], Figure 3
  10. vec3 brdf = SRGBtoLINEAR(texture2D(u_brdfLUT,
  11. vec2(pbrInputs.NdotV, 1.0 - pbrInputs.perceptualRoughness))).rgb;
  12. vec3 diffuseLight = SRGBtoLINEAR(textureCube(u_DiffuseEnvSampler, n)).rgb;
  13.  
  14. #ifdef USE_TEX_LOD
  15. vec3 specularLight = SRGBtoLINEAR(textureCubeLodEXT(u_SpecularEnvSampler, reflection, lod)).rgb;
  16. #else
  17. vec3 specularLight = SRGBtoLINEAR(textureCube(u_SpecularEnvSampler, reflection)).rgb;
  18. #endif
  19.  
  20. vec3 diffuse = diffuseLight * pbrInputs.diffuseColor;
  21. vec3 specular = specularLight * (pbrInputs.specularColor * brdf.x + brdf.y);
  22.  
  23. // For presentation, this allows us to disable IBL terms
  24. diffuse *= u_ScaleIBLAmbient.x;
  25. specular *= u_ScaleIBLAmbient.y;
  26.  
  27. return diffuse + specular;
  28. }
  29. #endif

渲染部分基本讲完了,这里面还涉及几个辅助函数用来设置一些向量乘积变量。

  1. void PBRInfo_setAmbientLight(inout PBRInfo pbrInputs) {
  2. pbrInputs.NdotL = 1.0;
  3. pbrInputs.NdotH = 0.0;
  4. pbrInputs.LdotH = 0.0;
  5. pbrInputs.VdotH = 1.0;
  6. }
  7.  
  8. void PBRInfo_setDirectionalLight(inout PBRInfo pbrInputs, vec3 lightDirection) {
  9. vec3 n = pbrInputs.n;
  10. vec3 v = pbrInputs.v;
  11. vec3 l = normalize(lightDirection); // Vector from surface point to light
  12. vec3 h = normalize(l+v); // Half vector between both l and v
  13.  
  14. pbrInputs.NdotL = clamp(dot(n, l), 0.001, 1.0);
  15. pbrInputs.NdotH = clamp(dot(n, h), 0.0, 1.0);
  16. pbrInputs.LdotH = clamp(dot(l, h), 0.0, 1.0);
  17. pbrInputs.VdotH = clamp(dot(v, h), 0.0, 1.0);
  18. }
  19.  
  20. void PBRInfo_setPointLight(inout PBRInfo pbrInputs, PointLight pointLight) {
  21. vec3 light_direction = normalize(pointLight.position - pbr_vPosition);
  22. PBRInfo_setDirectionalLight(pbrInputs, light_direction);
  23. }

还有将gamma颜色空间转成线性空间的函数

  1. vec4 SRGBtoLINEAR(vec4 srgbIn)
  2. {
  3. #ifdef MANUAL_SRGB
  4. #ifdef SRGB_FAST_APPROXIMATION
  5. vec3 linOut = pow(srgbIn.xyz,vec3(2.2));
  6. #else //SRGB_FAST_APPROXIMATION
  7. vec3 bLess = step(vec3(0.04045),srgbIn.xyz);
  8. vec3 linOut = mix( srgbIn.xyz/vec3(12.92), pow((srgbIn.xyz+vec3(0.055))/vec3(1.055),vec3(2.4)), bLess );
  9. #endif //SRGB_FAST_APPROXIMATION
  10. return vec4(linOut,srgbIn.w);;
  11. #else //MANUAL_SRGB
  12. return srgbIn;
  13. #endif //MANUAL_SRGB
  14. }

以及获取法向量的函数,关于法向量纹理,里面涉及切向量空间,又是另外一个专题,不展开了。

  1. // Find the normal for this fragment, pulling either from a predefined normal map
  2. // or from the interpolated mesh normal and tangent attributes.
  3. vec3 getNormal()
  4. {
  5. // Retrieve the tangent space matrix
  6. #ifndef HAS_TANGENTS
  7. vec3 pos_dx = dFdx(pbr_vPosition);
  8. vec3 pos_dy = dFdy(pbr_vPosition);
  9. vec3 tex_dx = dFdx(vec3(pbr_vUV, 0.0));
  10. vec3 tex_dy = dFdy(vec3(pbr_vUV, 0.0));
  11. vec3 t = (tex_dy.t * pos_dx - tex_dx.t * pos_dy) / (tex_dx.s * tex_dy.t - tex_dy.s * tex_dx.t);
  12.  
  13. #ifdef HAS_NORMALS
  14. vec3 ng = normalize(pbr_vNormal);
  15. #else
  16. vec3 ng = cross(pos_dx, pos_dy);
  17. #endif
  18.  
  19. t = normalize(t - ng * dot(ng, t));
  20. vec3 b = normalize(cross(ng, t));
  21. mat3 tbn = mat3(t, b, ng);
  22. #else // HAS_TANGENTS
  23. mat3 tbn = pbr_vTBN;
  24. #endif
  25.  
  26. #ifdef HAS_NORMALMAP
  27. vec3 n = texture2D(u_NormalSampler, pbr_vUV).rgb;
  28. n = normalize(tbn * ((2.0 * n - 1.0) * vec3(u_NormalScale, u_NormalScale, 1.0)));
  29. #else
  30. // The tbn matrix is linearly interpolated, so we need to re-normalize
  31. vec3 n = normalize(tbn[2].xyz);
  32. #endif
  33.  
  34. return n;
  35. }

以及PBRInfo信息:

  1. // Encapsulate the various inputs used by the various functions in the shading equation
  2. // We store values in this struct to simplify the integration of alternative implementations
  3. // of the shading terms, outlined in the Readme.MD Appendix.
  4. struct PBRInfo
  5. {
  6. float NdotL; // cos angle between normal and light direction
  7. float NdotV; // cos angle between normal and view direction
  8. float NdotH; // cos angle between normal and half vector
  9. float LdotH; // cos angle between light direction and half vector
  10. float VdotH; // cos angle between view direction and half vector
  11. float perceptualRoughness; // roughness value, as authored by the model creator (input to shader)
  12. float metalness; // metallic value at the surface
  13. vec3 reflectance0; // full reflectance color (normal incidence angle)
  14. vec3 reflectance90; // reflectance color at grazing angle
  15. float alphaRoughness; // roughness mapped to a more linear change in the roughness (proposed by [2])
  16. vec3 diffuseColor; // color contribution from diffuse lighting
  17. vec3 specularColor; // color contribution from specular lighting
  18. vec3 n; // normal at surface point
  19. vec3 v; // vector from surface point to camera
  20. };

部分图和文字借用了一些大佬的文章,侵权请联系我,必删!

参考文章

https://mp.weixin.qq.com/s?__biz=MzA5MDcyOTE5Nw==&mid=2650545802&idx=1&sn=282eec1403c901cbf406141ec668a96a&scene=19#wechat_redirect

https://blog.csdn.net/qjh5606/article/details/89948573

https://mp.weixin.qq.com/s?__biz=MzA5MDcyOTE5Nw==&mid=2650545891&idx=1&sn=938f1e2d37864bf0cff5ec9e308fdae0&scene=19#wechat_redirect

https://zhuanlan.zhihu.com/p/58692781?utm_source=wechat_session

https://zhuanlan.zhihu.com/p/58641686

https://zhuanlan.zhihu.com/c_1084126907469135872

PBR(基于物理的渲染)学习笔记的更多相关文章

  1. PBR(基于物理的渲染)学习笔记2

    相关资料 https://www.cnblogs.com/dojo-lzz/p/13237686.html 文档:PBR学习笔记.note 链接:http://note.youdao.com/note ...

  2. PBR:基于物理的渲染(Physically Based Rendering)+理论相关

    一: 关于能量守恒 出射光线的能量永远不能超过入射光线的能量(发光面除外).如图示我们可以看到,随着粗糙度的上升镜面反射区域的会增加,但是镜面反射的亮度却会下降.如果不管反射轮廓的大小而让每个像素的镜 ...

  3. Canvas 数学、物理、动画学习笔记一

    Canvas 第五章 数学.物理和运动学习笔记让人映像深刻的运动,需要我们不只是简单的知道如何移动对象,还需要知道怎么按用户期望看到的方式去移动它们.这些需要基于数学知识的基本算法和物理学作用.基于点 ...

  4. 基于物理的渲染——间接光照

    在前面的文章中我们已经给出了基于物理的渲染方程: 并介绍了直接光照的实现.然而在自然界中,一个物体不会单独存在,光源会照射到其他的物体上,反射的光会有一部分反射到物体上.为了模拟这种环境光照的形式,我 ...

  5. 离屏渲染学习笔记 /iOS圆角性能问题

    离屏渲染学习笔记 一.概念理解 OpenGL中,GPU屏幕渲染有以下两种方式: On-Screen Rendering 意为当前屏幕渲染,指的是GPU的渲染操作是在当前用于显示的屏幕缓冲区中进行. O ...

  6. MVC中使用Entity Framework 基于方法的查询学习笔记 (三)

    紧接上文,我们已经学习了MVC数据上下文中两个常用的类,这两个类承载着利用函数方式进行数据查询的全部内容,我们既然已经了解了DbSet<TEntity> 是一个泛型集合,并且实现了一些接口 ...

  7. MVC中使用Entity Framework 基于方法的查询学习笔记 (一)

    EF中基于方法的查询方式不同于LINQ和以往的ADO.NET,正因为如此,有必要深入学习一下啦.闲话不多说,现在开始一个MVC项目,在项目中临床学习. 创建MVC项目 1.“文件”--“新建项目”-- ...

  8. 基于PHP的AJAX学习笔记(教程)

    本文转载自:http://www.softeng.cn/?p=107 这是本人在学习ajax过程所做的笔记,通过本笔记的学习,可以完成ajax的快速入门.本笔记前端分别使用原生态的javascript ...

  9. 基于python的接口测试学习笔记一(初出茅庐)

    第一次写博客笔记,讲一下近来学习的接口自动化测试.网上查阅了相关资料,最后决定使用python语言写接口测试,使用的是python的第三方库requests.虽然python本身标准库中的 urlli ...

随机推荐

  1. Java实现蓝桥杯快乐数

    [问题描述] 判断一个正整数是否是快乐数字? 如果一个数字能够通过有限次快乐变换成为1,则是快乐数字. 快乐变换是对一个数字的每一位的平方数求和. 例如: 对于68 68 => 62+82= 1 ...

  2. java实现第三届蓝桥杯排日程

    排日程 [编程题](满分34分) 某保密单位机要人员 A,B,C,D,E 每周需要工作5天,休息2天. 上级要求每个人每周的工作日和休息日安排必须是固定的,不能在周间变更. 此外,由于工作需要,还有如 ...

  3. 制作seata docker镜像

    seata是阿里巴巴的一款开源的分布式事务框架,官方已经支持docker了,但是因为业务的需要,需要自己定制. 制作docker镜像 官方的Dockerfile.下载seata-server-1.1. ...

  4. MYSQL SQL 语句修改字段默认值

    alter table tablename alter column drop default; (若本身存在默认值,则先删除) alter table tablename alter column ...

  5. office2016专业增强版激活密匙 (shell激活版)

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明.本文链接:https://blog.csdn.net/qq_42642945/article/d ...

  6. render props的运用

    2020-04-03 render props的运用 术语 “render prop” 是指一种在 React 组件之间使用一个值为函数的 prop 共享代码的简单技术 通常的 这个值为函数的prop ...

  7. 最全面的SourceTree账号注册教程

    前言: 作为一个国内开发者而言使用Git操作神器SoureTree最大的问题就是账号注册问题,因为注册账号的链接在不翻墙的情况下基本上是打不开的(弄过的童鞋应该都体会过),所以有的时候我们需要借助一些 ...

  8. (五)TestNG测试的并发执行详解

    原文链接:https://blog.csdn.net/taiyangdao/article/details/52159065 TestNG在执行测试时,默认suitethreadpoolsize=1, ...

  9. node-sass问题

    cnpm install node-sass@latest 或者 所以用npm install -g cnpm --registry=https://registry.npm.taobao.org , ...

  10. startActivityForResult调用另外一个Activity获取返回结果

    startActivityForResult(intent,requestCode)可以调用另外一个Activity,并返回结果. 换头像案例 activity_main.xml <?xml v ...