PMREMGenerator.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. /**
  2. * @author Prashant Sharma / spidersharma03
  3. * @author Ben Houston / bhouston, https://clara.io
  4. *
  5. * To avoid cube map seams, I create an extra pixel around each face. This way when the cube map is
  6. * sampled by an application later(with a little care by sampling the centre of the texel), the extra 1 border
  7. * of pixels makes sure that there is no seams artifacts present. This works perfectly for cubeUV format as
  8. * well where the 6 faces can be arranged in any manner whatsoever.
  9. * Code in the beginning of fragment shader's main function does this job for a given resolution.
  10. * Run Scene_PMREM_Test.html in the examples directory to see the sampling from the cube lods generated
  11. * by this class.
  12. */
  13. THREE.PMREMGenerator = function( sourceTexture, samplesPerLevel, resolution ) {
  14. this.sourceTexture = sourceTexture;
  15. this.resolution = ( resolution !== undefined ) ? resolution : 256; // NODE: 256 is currently hard coded in the glsl code for performance reasons
  16. this.samplesPerLevel = ( samplesPerLevel !== undefined ) ? samplesPerLevel : 16;
  17. var monotonicEncoding = ( sourceTexture.encoding === THREE.LinearEncoding ) ||
  18. ( sourceTexture.encoding === THREE.GammaEncoding ) || ( sourceTexture.encoding === THREE.sRGBEncoding );
  19. this.sourceTexture.minFilter = ( monotonicEncoding ) ? THREE.LinearFilter : THREE.NearestFilter;
  20. this.sourceTexture.magFilter = ( monotonicEncoding ) ? THREE.LinearFilter : THREE.NearestFilter;
  21. this.sourceTexture.generateMipmaps = this.sourceTexture.generateMipmaps && monotonicEncoding;
  22. this.cubeLods = [];
  23. var size = this.resolution;
  24. var params = {
  25. format: this.sourceTexture.format,
  26. magFilter: this.sourceTexture.magFilter,
  27. minFilter: this.sourceTexture.minFilter,
  28. type: this.sourceTexture.type,
  29. generateMipmaps: this.sourceTexture.generateMipmaps,
  30. anisotropy: this.sourceTexture.anisotropy,
  31. encoding: this.sourceTexture.encoding
  32. };
  33. // how many LODs fit in the given CubeUV Texture.
  34. this.numLods = Math.log( size ) / Math.log( 2 ) - 2; // IE11 doesn't support Math.log2
  35. for ( var i = 0; i < this.numLods; i ++ ) {
  36. var renderTarget = new THREE.WebGLRenderTargetCube( size, size, params );
  37. renderTarget.texture.name = "PMREMGenerator.cube" + i;
  38. this.cubeLods.push( renderTarget );
  39. size = Math.max( 16, size / 2 );
  40. }
  41. this.camera = new THREE.OrthographicCamera( - 1, 1, 1, - 1, 0.0, 1000 );
  42. this.shader = this.getShader();
  43. this.shader.defines['SAMPLES_PER_LEVEL'] = this.samplesPerLevel;
  44. this.planeMesh = new THREE.Mesh( new THREE.PlaneGeometry( 2, 2, 0 ), this.shader );
  45. this.planeMesh.material.side = THREE.DoubleSide;
  46. this.scene = new THREE.Scene();
  47. this.scene.add( this.planeMesh );
  48. this.scene.add( this.camera );
  49. this.shader.uniforms[ 'envMap' ].value = this.sourceTexture;
  50. this.shader.envMap = this.sourceTexture;
  51. };
  52. THREE.PMREMGenerator.prototype = {
  53. constructor : THREE.PMREMGenerator,
  54. /*
  55. * Prashant Sharma / spidersharma03: More thought and work is needed here.
  56. * Right now it's a kind of a hack to use the previously convolved map to convolve the current one.
  57. * I tried to use the original map to convolve all the lods, but for many textures(specially the high frequency)
  58. * even a high number of samples(1024) dosen't lead to satisfactory results.
  59. * By using the previous convolved maps, a lower number of samples are generally sufficient(right now 32, which
  60. * gives okay results unless we see the reflection very carefully, or zoom in too much), however the math
  61. * goes wrong as the distribution function tries to sample a larger area than what it should be. So I simply scaled
  62. * the roughness by 0.9(totally empirical) to try to visually match the original result.
  63. * The condition "if(i <5)" is also an attemt to make the result match the original result.
  64. * This method requires the most amount of thinking I guess. Here is a paper which we could try to implement in future::
  65. * http://http.developer.nvidia.com/GPUGems3/gpugems3_ch20.html
  66. */
  67. update: function( renderer ) {
  68. this.shader.uniforms[ 'envMap' ].value = this.sourceTexture;
  69. this.shader.envMap = this.sourceTexture;
  70. var gammaInput = renderer.gammaInput;
  71. var gammaOutput = renderer.gammaOutput;
  72. var toneMapping = renderer.toneMapping;
  73. var toneMappingExposure = renderer.toneMappingExposure;
  74. renderer.toneMapping = THREE.LinearToneMapping;
  75. renderer.toneMappingExposure = 1.0;
  76. renderer.gammaInput = false;
  77. renderer.gammaOutput = false;
  78. for ( var i = 0; i < this.numLods; i ++ ) {
  79. var r = i / ( this.numLods - 1 );
  80. this.shader.uniforms[ 'roughness' ].value = r * 0.9; // see comment above, pragmatic choice
  81. this.shader.uniforms[ 'queryScale' ].value.x = ( i == 0 ) ? -1 : 1;
  82. var size = this.cubeLods[ i ].width;
  83. this.shader.uniforms[ 'mapSize' ].value = size;
  84. this.renderToCubeMapTarget( renderer, this.cubeLods[ i ] );
  85. if ( i < 5 ) this.shader.uniforms[ 'envMap' ].value = this.cubeLods[ i ].texture;
  86. }
  87. renderer.toneMapping = toneMapping;
  88. renderer.toneMappingExposure = toneMappingExposure;
  89. renderer.gammaInput = gammaInput;
  90. renderer.gammaOutput = gammaOutput;
  91. },
  92. renderToCubeMapTarget: function( renderer, renderTarget ) {
  93. for ( var i = 0; i < 6; i ++ ) {
  94. this.renderToCubeMapTargetFace( renderer, renderTarget, i )
  95. }
  96. },
  97. renderToCubeMapTargetFace: function( renderer, renderTarget, faceIndex ) {
  98. renderTarget.activeCubeFace = faceIndex;
  99. this.shader.uniforms[ 'faceIndex' ].value = faceIndex;
  100. renderer.render( this.scene, this.camera, renderTarget, true );
  101. },
  102. getShader: function() {
  103. return new THREE.ShaderMaterial( {
  104. defines: {
  105. "SAMPLES_PER_LEVEL": 20,
  106. },
  107. uniforms: {
  108. "faceIndex": { value: 0 },
  109. "roughness": { value: 0.5 },
  110. "mapSize": { value: 0.5 },
  111. "envMap": { value: null },
  112. "queryScale": { value: new THREE.Vector3( 1, 1, 1 ) },
  113. "testColor": { value: new THREE.Vector3( 1, 1, 1 ) },
  114. },
  115. vertexShader:
  116. "varying vec2 vUv;\n\
  117. void main() {\n\
  118. vUv = uv;\n\
  119. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\
  120. }",
  121. fragmentShader:
  122. "#include <common>\n\
  123. varying vec2 vUv;\n\
  124. uniform int faceIndex;\n\
  125. uniform float roughness;\n\
  126. uniform samplerCube envMap;\n\
  127. uniform float mapSize;\n\
  128. uniform vec3 testColor;\n\
  129. uniform vec3 queryScale;\n\
  130. \n\
  131. float GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\
  132. float a = ggxRoughness + 0.0001;\n\
  133. a *= a;\n\
  134. return ( 2.0 / a - 2.0 );\n\
  135. }\n\
  136. vec3 ImportanceSamplePhong(vec2 uv, mat3 vecSpace, float specPow) {\n\
  137. float phi = uv.y * 2.0 * PI;\n\
  138. float cosTheta = pow(1.0 - uv.x, 1.0 / (specPow + 1.0));\n\
  139. float sinTheta = sqrt(1.0 - cosTheta * cosTheta);\n\
  140. vec3 sampleDir = vec3(cos(phi) * sinTheta, sin(phi) * sinTheta, cosTheta);\n\
  141. return vecSpace * sampleDir;\n\
  142. }\n\
  143. vec3 ImportanceSampleGGX( vec2 uv, mat3 vecSpace, float Roughness )\n\
  144. {\n\
  145. float a = Roughness * Roughness;\n\
  146. float Phi = 2.0 * PI * uv.x;\n\
  147. float CosTheta = sqrt( (1.0 - uv.y) / ( 1.0 + (a*a - 1.0) * uv.y ) );\n\
  148. float SinTheta = sqrt( 1.0 - CosTheta * CosTheta );\n\
  149. return vecSpace * vec3(SinTheta * cos( Phi ), SinTheta * sin( Phi ), CosTheta);\n\
  150. }\n\
  151. mat3 matrixFromVector(vec3 n) {\n\
  152. float a = 1.0 / (1.0 + n.z);\n\
  153. float b = -n.x * n.y * a;\n\
  154. vec3 b1 = vec3(1.0 - n.x * n.x * a, b, -n.x);\n\
  155. vec3 b2 = vec3(b, 1.0 - n.y * n.y * a, -n.y);\n\
  156. return mat3(b1, b2, n);\n\
  157. }\n\
  158. \n\
  159. vec4 testColorMap(float Roughness) {\n\
  160. vec4 color;\n\
  161. if(faceIndex == 0)\n\
  162. color = vec4(1.0,0.0,0.0,1.0);\n\
  163. else if(faceIndex == 1)\n\
  164. color = vec4(0.0,1.0,0.0,1.0);\n\
  165. else if(faceIndex == 2)\n\
  166. color = vec4(0.0,0.0,1.0,1.0);\n\
  167. else if(faceIndex == 3)\n\
  168. color = vec4(1.0,1.0,0.0,1.0);\n\
  169. else if(faceIndex == 4)\n\
  170. color = vec4(0.0,1.0,1.0,1.0);\n\
  171. else\n\
  172. color = vec4(1.0,0.0,1.0,1.0);\n\
  173. color *= ( 1.0 - Roughness );\n\
  174. return color;\n\
  175. }\n\
  176. void main() {\n\
  177. vec3 sampleDirection;\n\
  178. vec2 uv = vUv*2.0 - 1.0;\n\
  179. float offset = -1.0/mapSize;\n\
  180. const float a = -1.0;\n\
  181. const float b = 1.0;\n\
  182. float c = -1.0 + offset;\n\
  183. float d = 1.0 - offset;\n\
  184. float bminusa = b - a;\n\
  185. uv.x = (uv.x - a)/bminusa * d - (uv.x - b)/bminusa * c;\n\
  186. uv.y = (uv.y - a)/bminusa * d - (uv.y - b)/bminusa * c;\n\
  187. if (faceIndex==0) {\n\
  188. sampleDirection = vec3(1.0, -uv.y, -uv.x);\n\
  189. } else if (faceIndex==1) {\n\
  190. sampleDirection = vec3(-1.0, -uv.y, uv.x);\n\
  191. } else if (faceIndex==2) {\n\
  192. sampleDirection = vec3(uv.x, 1.0, uv.y);\n\
  193. } else if (faceIndex==3) {\n\
  194. sampleDirection = vec3(uv.x, -1.0, -uv.y);\n\
  195. } else if (faceIndex==4) {\n\
  196. sampleDirection = vec3(uv.x, -uv.y, 1.0);\n\
  197. } else {\n\
  198. sampleDirection = vec3(-uv.x, -uv.y, -1.0);\n\
  199. }\n\
  200. mat3 vecSpace = matrixFromVector(normalize(sampleDirection * queryScale));\n\
  201. vec3 rgbColor = vec3(0.0);\n\
  202. const int NumSamples = SAMPLES_PER_LEVEL;\n\
  203. vec3 vect;\n\
  204. float weight = 0.0;\n\
  205. for( int i = 0; i < NumSamples; i ++ ) {\n\
  206. float sini = sin(float(i));\n\
  207. float cosi = cos(float(i));\n\
  208. float r = rand(vec2(sini, cosi));\n\
  209. vect = ImportanceSampleGGX(vec2(float(i) / float(NumSamples), r), vecSpace, roughness);\n\
  210. float dotProd = dot(vect, normalize(sampleDirection));\n\
  211. weight += dotProd;\n\
  212. vec3 color = envMapTexelToLinear(textureCube(envMap,vect)).rgb;\n\
  213. rgbColor.rgb += color;\n\
  214. }\n\
  215. rgbColor /= float(NumSamples);\n\
  216. //rgbColor = testColorMap( roughness ).rgb;\n\
  217. gl_FragColor = linearToOutputTexel( vec4( rgbColor, 1.0 ) );\n\
  218. }",
  219. blending: THREE.CustomBlending,
  220. blendSrc: THREE.OneFactor,
  221. blendDst: THREE.ZeroFactor,
  222. blendSrcAlpha: THREE.OneFactor,
  223. blendDstAlpha: THREE.ZeroFactor,
  224. blendEquation: THREE.AddEquation
  225. } );
  226. }
  227. };