physical_fragment.glsl 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. //
  2. // Physically Based Shading of a microfacet surface material - Fragment Shader
  3. // Modified from reference implementation at https://github.com/KhronosGroup/glTF-WebGL-PBR
  4. //
  5. // References:
  6. // [1] Real Shading in Unreal Engine 4
  7. // http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  8. // [2] Physically Based Shading at Disney
  9. // http://blog.selfshadow.com/publications/s2012-shading-course/burley/s2012_pbs_disney_brdf_notes_v3.pdf
  10. // [3] README.md - Environment Maps
  11. // https://github.com/KhronosGroup/glTF-WebGL-PBR/#environment-maps
  12. // [4] "An Inexpensive BRDF Model for Physically based Rendering" by Christophe Schlick
  13. // https://www.cs.virginia.edu/~jdl/bib/appearance/analytic%20models/schlick94b.pdf
  14. //#extension GL_EXT_shader_texture_lod: enable
  15. //#extension GL_OES_standard_derivatives : enable
  16. precision highp float;
  17. //uniform vec3 u_LightDirection;
  18. //uniform vec3 u_LightColor;
  19. //#ifdef USE_IBL
  20. //uniform samplerCube u_DiffuseEnvSampler;
  21. //uniform samplerCube u_SpecularEnvSampler;
  22. //uniform sampler2D u_brdfLUT;
  23. //#endif
  24. #ifdef HAS_BASECOLORMAP
  25. uniform sampler2D uBaseColorSampler;
  26. #endif
  27. #ifdef HAS_METALROUGHNESSMAP
  28. uniform sampler2D uMetallicRoughnessSampler;
  29. #endif
  30. #ifdef HAS_NORMALMAP
  31. uniform sampler2D uNormalSampler;
  32. //uniform float uNormalScale;
  33. #endif
  34. #ifdef HAS_EMISSIVEMAP
  35. uniform sampler2D uEmissiveSampler;
  36. #endif
  37. #ifdef HAS_OCCLUSIONMAP
  38. uniform sampler2D uOcclusionSampler;
  39. uniform float uOcclusionStrength;
  40. #endif
  41. // Material parameters uniform array
  42. uniform vec4 Material[3];
  43. // Macros to access elements inside the Material array
  44. #define uBaseColor Material[0]
  45. #define uEmissiveColor Material[1]
  46. #define uMetallicFactor Material[2].x
  47. #define uRoughnessFactor Material[2].y
  48. #include <lights>
  49. // Inputs from vertex shader
  50. in vec3 Position; // Vertex position in camera coordinates.
  51. in vec3 Normal; // Vertex normal in camera coordinates.
  52. in vec3 CamDir; // Direction from vertex to camera
  53. in vec2 FragTexcoord;
  54. // Final fragment color
  55. out vec4 FragColor;
  56. // Encapsulate the various inputs used by the various functions in the shading equation
  57. // We store values in this struct to simplify the integration of alternative implementations
  58. // of the shading terms, outlined in the Readme.MD Appendix.
  59. struct PBRLightInfo
  60. {
  61. float NdotL; // cos angle between normal and light direction
  62. float NdotV; // cos angle between normal and view direction
  63. float NdotH; // cos angle between normal and half vector
  64. float LdotH; // cos angle between light direction and half vector
  65. float VdotH; // cos angle between view direction and half vector
  66. };
  67. struct PBRInfo
  68. {
  69. float perceptualRoughness; // roughness value, as authored by the model creator (input to shader)
  70. float metalness; // metallic value at the surface
  71. vec3 reflectance0; // full reflectance color (normal incidence angle)
  72. vec3 reflectance90; // reflectance color at grazing angle
  73. float alphaRoughness; // roughness mapped to a more linear change in the roughness (proposed by [2])
  74. vec3 diffuseColor; // color contribution from diffuse lighting
  75. vec3 specularColor; // color contribution from specular lighting
  76. };
  77. const float M_PI = 3.141592653589793;
  78. const float c_MinRoughness = 0.04;
  79. vec4 SRGBtoLINEAR(vec4 srgbIn) {
  80. //#ifdef MANUAL_SRGB
  81. // #ifdef SRGB_FAST_APPROXIMATION
  82. // vec3 linOut = pow(srgbIn.xyz,vec3(2.2));
  83. // #else //SRGB_FAST_APPROXIMATION
  84. vec3 bLess = step(vec3(0.04045),srgbIn.xyz);
  85. vec3 linOut = mix( srgbIn.xyz/vec3(12.92), pow((srgbIn.xyz+vec3(0.055))/vec3(1.055),vec3(2.4)), bLess );
  86. // #endif //SRGB_FAST_APPROXIMATION
  87. return vec4(linOut,srgbIn.w);
  88. //#else //MANUAL_SRGB
  89. // return srgbIn;
  90. //#endif //MANUAL_SRGB
  91. }
  92. // Find the normal for this fragment, pulling either from a predefined normal map
  93. // or from the interpolated mesh normal and tangent attributes.
  94. vec3 getNormal()
  95. {
  96. // Retrieve the tangent space matrix
  97. //#ifndef HAS_TANGENTS
  98. vec3 pos_dx = dFdx(Position);
  99. vec3 pos_dy = dFdy(Position);
  100. vec3 tex_dx = dFdx(vec3(FragTexcoord, 0.0));
  101. vec3 tex_dy = dFdy(vec3(FragTexcoord, 0.0));
  102. vec3 t = (tex_dy.t * pos_dx - tex_dx.t * pos_dy) / (tex_dx.s * tex_dy.t - tex_dy.s * tex_dx.t);
  103. //#ifdef HAS_NORMALS
  104. vec3 ng = normalize(Normal);
  105. //#else
  106. // vec3 ng = cross(pos_dx, pos_dy);
  107. //#endif
  108. t = normalize(t - ng * dot(ng, t));
  109. vec3 b = normalize(cross(ng, t));
  110. mat3 tbn = mat3(t, b, ng);
  111. //#else // HAS_TANGENTS
  112. // mat3 tbn = v_TBN;
  113. //#endif
  114. #ifdef HAS_NORMALMAP
  115. float uNormalScale = 1.0;
  116. vec3 n = texture2D(uNormalSampler, FragTexcoord).rgb;
  117. n = normalize(tbn * ((2.0 * n - 1.0) * vec3(uNormalScale, uNormalScale, 1.0)));
  118. #else
  119. // The tbn matrix is linearly interpolated, so we need to re-normalize
  120. vec3 n = normalize(tbn[2].xyz);
  121. #endif
  122. return n;
  123. }
  124. // Calculation of the lighting contribution from an optional Image Based Light source.
  125. // Precomputed Environment Maps are required uniform inputs and are computed as outlined in [1].
  126. // See our README.md on Environment Maps [3] for additional discussion.
  127. vec3 getIBLContribution(PBRInfo pbrInputs, PBRLightInfo pbrLight, vec3 n, vec3 reflection)
  128. {
  129. float mipCount = 9.0; // resolution of 512x512
  130. float lod = (pbrInputs.perceptualRoughness * mipCount);
  131. // retrieve a scale and bias to F0. See [1], Figure 3
  132. vec3 brdf = vec3(0.5,0.5,0.5);//SRGBtoLINEAR(texture2D(u_brdfLUT, vec2(pbrLight.NdotV, 1.0 - pbrInputs.perceptualRoughness))).rgb;
  133. vec3 diffuseLight = vec3(0.5,0.5,0.5);//SRGBtoLINEAR(textureCube(u_DiffuseEnvSampler, n)).rgb;
  134. //#ifdef USE_TEX_LOD
  135. // vec3 specularLight = SRGBtoLINEAR(textureCubeLodEXT(u_SpecularEnvSampler, reflection, lod)).rgb;
  136. //#else
  137. vec3 specularLight = vec3(0.5,0.5,0.5);//SRGBtoLINEAR(textureCube(u_SpecularEnvSampler, reflection)).rgb;
  138. //#endif
  139. vec3 diffuse = diffuseLight * pbrInputs.diffuseColor;
  140. vec3 specular = specularLight * (pbrInputs.specularColor * brdf.x + brdf.y);
  141. // For presentation, this allows us to disable IBL terms
  142. // diffuse *= u_ScaleIBLAmbient.x;
  143. // specular *= u_ScaleIBLAmbient.y;
  144. return diffuse + specular;
  145. }
  146. // Basic Lambertian diffuse
  147. // Implementation from Lambert's Photometria https://archive.org/details/lambertsphotome00lambgoog
  148. // See also [1], Equation 1
  149. vec3 diffuse(PBRInfo pbrInputs)
  150. {
  151. return pbrInputs.diffuseColor / M_PI;
  152. }
  153. // The following equation models the Fresnel reflectance term of the spec equation (aka F())
  154. // Implementation of fresnel from [4], Equation 15
  155. vec3 specularReflection(PBRInfo pbrInputs, PBRLightInfo pbrLight)
  156. {
  157. return pbrInputs.reflectance0 + (pbrInputs.reflectance90 - pbrInputs.reflectance0) * pow(clamp(1.0 - pbrLight.VdotH, 0.0, 1.0), 5.0);
  158. }
  159. // This calculates the specular geometric attenuation (aka G()),
  160. // where rougher material will reflect less light back to the viewer.
  161. // This implementation is based on [1] Equation 4, and we adopt their modifications to
  162. // alphaRoughness as input as originally proposed in [2].
  163. float geometricOcclusion(PBRInfo pbrInputs, PBRLightInfo pbrLight)
  164. {
  165. float NdotL = pbrLight.NdotL;
  166. float NdotV = pbrLight.NdotV;
  167. float r = pbrInputs.alphaRoughness;
  168. float attenuationL = 2.0 * NdotL / (NdotL + sqrt(r * r + (1.0 - r * r) * (NdotL * NdotL)));
  169. float attenuationV = 2.0 * NdotV / (NdotV + sqrt(r * r + (1.0 - r * r) * (NdotV * NdotV)));
  170. return attenuationL * attenuationV;
  171. }
  172. // The following equation(s) model the distribution of microfacet normals across the area being drawn (aka D())
  173. // Implementation from "Average Irregularity Representation of a Roughened Surface for Ray Reflection" by T. S. Trowbridge, and K. P. Reitz
  174. // Follows the distribution function recommended in the SIGGRAPH 2013 course notes from EPIC Games [1], Equation 3.
  175. float microfacetDistribution(PBRInfo pbrInputs, PBRLightInfo pbrLight)
  176. {
  177. float roughnessSq = pbrInputs.alphaRoughness * pbrInputs.alphaRoughness;
  178. float f = (pbrLight.NdotH * roughnessSq - pbrLight.NdotH) * pbrLight.NdotH + 1.0;
  179. return roughnessSq / (M_PI * f * f);
  180. }
  181. vec3 pbrModel(PBRInfo pbrInputs, vec3 lightColor, vec3 lightDir) {
  182. // vec3 lightDir = lightPos - vec3(Position);
  183. vec3 n = getNormal(); // normal at surface point
  184. vec3 v = normalize(CamDir); // Vector from surface point to camera
  185. vec3 l = normalize(lightDir); // Vector from surface point to light
  186. vec3 h = normalize(l+v); // Half vector between both l and v
  187. vec3 reflection = -normalize(reflect(v, n));
  188. float NdotL = clamp(dot(n, l), 0.001, 1.0);
  189. float NdotV = abs(dot(n, v)) + 0.001;
  190. float NdotH = clamp(dot(n, h), 0.0, 1.0);
  191. float LdotH = clamp(dot(l, h), 0.0, 1.0);
  192. float VdotH = clamp(dot(v, h), 0.0, 1.0);
  193. PBRLightInfo pbrLight = PBRLightInfo(
  194. NdotL,
  195. NdotV,
  196. NdotH,
  197. LdotH,
  198. VdotH
  199. );
  200. // Calculate the shading terms for the microfacet specular shading model
  201. vec3 F = specularReflection(pbrInputs, pbrLight);
  202. float G = geometricOcclusion(pbrInputs, pbrLight);
  203. float D = microfacetDistribution(pbrInputs, pbrLight);
  204. // Calculation of analytical lighting contribution
  205. vec3 diffuseContrib = (1.0 - F) * diffuse(pbrInputs);
  206. vec3 specContrib = F * G * D / (4.0 * NdotL * NdotV);
  207. // Obtain final intensity as reflectance (BRDF) scaled by the energy of the light (cosine law)
  208. vec3 color = NdotL * lightColor * (diffuseContrib + specContrib);
  209. return color;
  210. }
  211. void main() {
  212. float perceptualRoughness = uRoughnessFactor;
  213. float metallic = uMetallicFactor;
  214. #ifdef HAS_METALROUGHNESSMAP
  215. // Roughness is stored in the 'g' channel, metallic is stored in the 'b' channel.
  216. // This layout intentionally reserves the 'r' channel for (optional) occlusion map data
  217. vec4 mrSample = texture2D(uMetallicRoughnessSampler, FragTexcoord);
  218. perceptualRoughness = mrSample.g * perceptualRoughness;
  219. metallic = mrSample.b * metallic;
  220. #endif
  221. perceptualRoughness = clamp(perceptualRoughness, c_MinRoughness, 1.0);
  222. metallic = clamp(metallic, 0.0, 1.0);
  223. // Roughness is authored as perceptual roughness; as is convention,
  224. // convert to material roughness by squaring the perceptual roughness [2].
  225. float alphaRoughness = perceptualRoughness * perceptualRoughness;
  226. // The albedo may be defined from a base texture or a flat color
  227. #ifdef HAS_BASECOLORMAP
  228. vec4 baseColor = SRGBtoLINEAR(texture2D(uBaseColorSampler, FragTexcoord)) * uBaseColor;
  229. #else
  230. vec4 baseColor = uBaseColor;
  231. #endif
  232. vec3 f0 = vec3(0.04);
  233. vec3 diffuseColor = baseColor.rgb * (vec3(1.0) - f0);
  234. diffuseColor *= 1.0 - metallic;
  235. // vec3 AmbientLight = vec3(0.5);
  236. // diffuseColor.rgb += AmbientLight;
  237. // diffuseColor *= baseColor.rgb;
  238. // diffuseColor = max(diffuseColor, 0.0);
  239. vec3 specularColor = mix(f0, baseColor.rgb, uMetallicFactor);
  240. // Compute reflectance.
  241. float reflectance = max(max(specularColor.r, specularColor.g), specularColor.b);
  242. // For typical incident reflectance range (between 4% to 100%) set the grazing reflectance to 100% for typical fresnel effect.
  243. // For very low reflectance range on highly diffuse objects (below 4%), incrementally reduce grazing reflectance to 0%.
  244. float reflectance90 = clamp(reflectance * 25.0, 0.0, 1.0);
  245. vec3 specularEnvironmentR0 = specularColor.rgb;
  246. vec3 specularEnvironmentR90 = vec3(1.0, 1.0, 1.0) * reflectance90;
  247. PBRInfo pbrInputs = PBRInfo(
  248. perceptualRoughness,
  249. metallic,
  250. specularEnvironmentR0,
  251. specularEnvironmentR90,
  252. alphaRoughness,
  253. diffuseColor,
  254. specularColor
  255. );
  256. // vec3 normal = getNormal();
  257. vec3 color = vec3(0.0);
  258. #if AMB_LIGHTS>0
  259. // Ambient lights
  260. for (int i = 0; i < AMB_LIGHTS; i++) {
  261. color += AmbientLightColor[i] * pbrInputs.diffuseColor;
  262. }
  263. #endif
  264. #if DIR_LIGHTS>0
  265. // Directional lights
  266. for (int i = 0; i < DIR_LIGHTS; i++) {
  267. // Diffuse reflection
  268. // DirLightPosition is the direction of the current light
  269. vec3 lightDirection = normalize(DirLightPosition(i));
  270. // PBR
  271. color += pbrModel(pbrInputs, DirLightColor(i), lightDirection);
  272. }
  273. #endif
  274. #if POINT_LIGHTS>0
  275. // Point lights
  276. for (int i = 0; i < POINT_LIGHTS; i++) {
  277. // Common calculations
  278. // Calculates the direction and distance from the current vertex to this point light.
  279. vec3 lightDirection = PointLightPosition(i) - vec3(Position);
  280. float lightDistance = length(lightDirection);
  281. // Normalizes the lightDirection
  282. lightDirection = lightDirection / lightDistance;
  283. // Calculates the attenuation due to the distance of the light
  284. float attenuation = 1.0 / (1.0 + PointLightLinearDecay(i) * lightDistance +
  285. PointLightQuadraticDecay(i) * lightDistance * lightDistance);
  286. vec3 attenuatedColor = PointLightColor(i) * attenuation;
  287. // PBR
  288. color += pbrModel(pbrInputs, attenuatedColor, lightDirection);
  289. }
  290. #endif
  291. #if SPOT_LIGHTS>0
  292. // for (int i = 0; i < SPOT_LIGHTS; i++) {
  293. // // Calculates the direction and distance from the current vertex to this spot light.
  294. // vec3 lightDirection = SpotLightPosition(i) - vec3(Position);
  295. // float lightDistance = length(lightDirection);
  296. // lightDirection = lightDirection / lightDistance;
  297. //
  298. // // Calculates the attenuation due to the distance of the light
  299. // float attenuation = 1.0 / (1.0 + SpotLightLinearDecay(i) * lightDistance +
  300. // SpotLightQuadraticDecay(i) * lightDistance * lightDistance);
  301. //
  302. // // Calculates the angle between the vertex direction and spot direction
  303. // // If this angle is greater than the cutoff the spotlight will not contribute
  304. // // to the final color.
  305. // float angle = acos(dot(-lightDirection, SpotLightDirection(i)));
  306. // float cutoff = radians(clamp(SpotLightCutoffAngle(i), 0.0, 90.0));
  307. //
  308. // if (angle < cutoff) {
  309. // float spotFactor = pow(dot(-lightDirection, SpotLightDirection(i)), SpotLightAngularDecay(i));
  310. //
  311. // // Diffuse reflection
  312. // float dotNormal = max(dot(lightDirection, normal), 0.0);
  313. // color += SpotLightColor(i) * dotNormal * attenuation * spotFactor;
  314. //
  315. // // Specular reflection
  316. // vec3 ref = reflect(-lightDirection, normal);
  317. // if (dotNormal > 0.0) {
  318. // color += SpotLightColor(i) * pow(max(dot(ref, CamDir), 0.0), 5) * attenuation * spotFactor;
  319. // }
  320. // }
  321. // }
  322. // TODO
  323. for (int i = 0; i < SPOT_LIGHTS; i++) {
  324. // Calculates the direction and distance from the current vertex to this spot light.
  325. vec3 lightDirection = SpotLightPosition(i) - vec3(Position);
  326. float lightDistance = length(lightDirection);
  327. lightDirection = lightDirection / lightDistance;
  328. // Calculates the attenuation due to the distance of the light
  329. float attenuation = 1.0 / (1.0 + SpotLightLinearDecay(i) * lightDistance +
  330. SpotLightQuadraticDecay(i) * lightDistance * lightDistance);
  331. // Calculates the angle between the vertex direction and spot direction
  332. // If this angle is greater than the cutoff the spotlight will not contribute
  333. // to the final color.
  334. float angle = acos(dot(-lightDirection, SpotLightDirection(i)));
  335. float cutoff = radians(clamp(SpotLightCutoffAngle(i), 0.0, 90.0));
  336. if (angle < cutoff) {
  337. float spotFactor = pow(dot(-lightDirection, SpotLightDirection(i)), SpotLightAngularDecay(i));
  338. vec3 attenuatedColor = SpotLightColor(i) * attenuation * spotFactor;
  339. // PBR
  340. color += pbrModel(pbrInputs, attenuatedColor, lightDirection);
  341. }
  342. }
  343. #endif
  344. // Calculate lighting contribution from image based lighting source (IBL)
  345. //#ifdef USE_IBL
  346. // color += getIBLContribution(pbrInputs, n, reflection);
  347. //#endif
  348. // Apply optional PBR terms for additional (optional) shading
  349. #ifdef HAS_OCCLUSIONMAP
  350. float ao = texture2D(uOcclusionSampler, FragTexcoord).r;
  351. color = mix(color, color * ao, 1.0);//, uOcclusionStrength);
  352. #endif
  353. #ifdef HAS_EMISSIVEMAP
  354. vec3 emissive = SRGBtoLINEAR(texture2D(uEmissiveSampler, FragTexcoord)).rgb * vec3(uEmissiveColor);
  355. color += emissive;
  356. #endif
  357. // Base Color
  358. // FragColor = baseColor;
  359. // Normal
  360. // FragColor = vec4(n, 1.0);
  361. // Emissive Color
  362. // FragColor = vec4(emissive, 1.0);
  363. // F
  364. // color = F;
  365. // G
  366. // color = vec3(G);
  367. // D
  368. // color = vec3(D);
  369. // Specular
  370. // color = specContrib;
  371. // Diffuse
  372. // color = diffuseContrib;
  373. // Roughness
  374. // color = vec3(perceptualRoughness);
  375. // Metallic
  376. // color = vec3(metallic);
  377. // Final fragment color
  378. FragColor = vec4(pow(color,vec3(1.0/2.2)), baseColor.a);
  379. }