PMREMGenerator.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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 ) {
  14. if ( sourceTexture instanceof THREE.CubeTexture ) {
  15. if ( sourceTexture.images[ 0 ] === undefined )
  16. console.error( "sourceTexture Not Initialized" );
  17. if(sourceTexture.images[ 0 ] instanceof THREE.DataTexture) {
  18. this.resolution = sourceTexture.images[ 0 ].image.width;
  19. }
  20. else {
  21. this.resolution = sourceTexture.images[ 0 ].width;
  22. }
  23. }
  24. else if ( sourceTexture instanceof THREE.WebGLRenderTargetCube ) {
  25. if ( sourceTexture === undefined ) console.error( "Render Target Not Initialized" );
  26. this.resolution = sourceTexture.width;
  27. }
  28. else {
  29. console.error( "Wrong Input to PMREMGenerator" );
  30. }
  31. this.sourceTexture = sourceTexture;
  32. var monotonicEncoding = ( sourceTexture.encoding === THREE.LinearEncoding ) ||
  33. ( sourceTexture.encoding === THREE.GammaEncoding ) || ( sourceTexture.encoding === THREE.sRGBEncoding );
  34. this.sourceTexture.minFilter = ( monotonicEncoding ) ? THREE.LinearFilter : THREE.NearestFilter;
  35. this.sourceTexture.magFilter = ( monotonicEncoding ) ? THREE.LinearFilter : THREE.NearestFilter;
  36. this.sourceTexture.generateMipmaps = this.sourceTexture.generateMipmaps && monotonicEncoding;
  37. this.cubeLods = [];
  38. var size = this.resolution;
  39. var params = { format: this.sourceTexture.format, magFilter: this.sourceTexture.magFilter, minFilter: this.sourceTexture.minFilter, type: this.sourceTexture.type };
  40. // how many LODs fit in the given CubeUV Texture.
  41. this.numLods = Math.log2( size ) - 2;
  42. for ( var i = 0; i < this.numLods; i ++ ) {
  43. var renderTarget = new THREE.WebGLRenderTargetCube( size, size, params );
  44. renderTarget.texture.generateMipmaps = this.sourceTexture.generateMipmaps;
  45. renderTarget.texture.anisotropy = this.sourceTexture.anisotropy;
  46. renderTarget.texture.encoding = this.sourceTexture.encoding;
  47. renderTarget.texture.minFilter = this.sourceTexture.minFilter;
  48. renderTarget.texture.magFilter = this.sourceTexture.magFilter;
  49. this.cubeLods.push( renderTarget );
  50. size = Math.max( 16, size / 2 );
  51. }
  52. this.camera = new THREE.OrthographicCamera( - 1, 1, 1, - 1, 0.0, 1000 );
  53. this.shader = this.getShader();
  54. this.planeMesh = new THREE.Mesh( new THREE.PlaneGeometry( 2, 2, 0 ), this.shader );
  55. this.planeMesh.material.side = THREE.DoubleSide;
  56. this.scene = new THREE.Scene();
  57. this.scene.add( this.planeMesh );
  58. this.scene.add( this.camera );
  59. this.shader.uniforms[ "envMap" ].value = this.sourceTexture;
  60. this.shader.envMap = this.sourceTexture;
  61. };
  62. THREE.PMREMGenerator.prototype = {
  63. constructor : THREE.PMREMGenerator,
  64. /*
  65. * Prashant Sharma / spidersharma03: More thought and work is needed here.
  66. * Right now it's a kind of a hack to use the previously convolved map to convolve the current one.
  67. * I tried to use the original map to convolve all the lods, but for many textures(specially the high frequency)
  68. * even a high number of samples(1024) dosen't lead to satisfactory results.
  69. * By using the previous convolved maps, a lower number of samples are generally sufficient(right now 32, which
  70. * gives okay results unless we see the reflection very carefully, or zoom in too much), however the math
  71. * goes wrong as the distribution function tries to sample a larger area than what it should be. So I simply scaled
  72. * the roughness by 0.9(totally empirical) to try to visually match the original result.
  73. * The condition "if(i <5)" is also an attemt to make the result match the original result.
  74. * This method requires the most amount of thinking I guess. Here is a paper which we could try to implement in future::
  75. * http://http.developer.nvidia.com/GPUGems3/gpugems3_ch20.html
  76. */
  77. update: function( renderer ) {
  78. this.shader.uniforms[ "envMap" ].value = this.sourceTexture;
  79. this.shader.envMap = this.sourceTexture;
  80. var gammaInput = renderer.gammaInput;
  81. var gammaOutput = renderer.gammaOutput;
  82. renderer.gammaInput = false;
  83. renderer.gammaOutput = false;
  84. for ( var i = 0; i < this.numLods; i ++ ) {
  85. var r = i / ( this.numLods - 1 );
  86. this.shader.uniforms[ "roughness" ].value = r * 0.9; // see comment above, pragmatic choice
  87. var size = this.cubeLods[ i ].width;
  88. this.shader.uniforms[ "mapSize" ].value = size;
  89. this.renderToCubeMapTarget( renderer, this.cubeLods[ i ] );
  90. if ( i < 5 )
  91. this.shader.uniforms[ "envMap" ].value = this.cubeLods[ i ];
  92. }
  93. renderer.gammaInput = renderer.gammaInput;
  94. renderer.gammaOutput = renderer.gammaOutput;
  95. },
  96. renderToCubeMapTarget: function( renderer, renderTarget ) {
  97. for ( var i = 0; i < 6; i ++ ) {
  98. this.renderToCubeMapTargetFace( renderer, renderTarget, i )
  99. }
  100. },
  101. renderToCubeMapTargetFace: function( renderer, renderTarget, faceIndex ) {
  102. renderTarget.activeCubeFace = faceIndex;
  103. this.shader.uniforms[ "faceIndex" ].value = faceIndex;
  104. renderer.render( this.scene, this.camera, renderTarget, true );
  105. },
  106. getShader: function() {
  107. return new THREE.ShaderMaterial( {
  108. uniforms: {
  109. "faceIndex": { type: 'i', value: 0 },
  110. "roughness": { type: 'f', value: 0.5 },
  111. "mapSize": { type: 'f', value: 0.5 },
  112. "envMap": { type: 't', value: null },
  113. "testColor": { type: 'v3', 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. "varying vec2 vUv;\n\
  123. uniform int faceIndex;\n\
  124. uniform float roughness;\n\
  125. uniform samplerCube envMap;\n\
  126. uniform float mapSize;\n\
  127. uniform vec3 testColor;\n\
  128. \n\
  129. float rnd(vec2 uv) {\n\
  130. return fract(sin(dot(uv, vec2(12.9898, 78.233) * 2.0)) * 43758.5453);\n\
  131. }\n\
  132. float GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\
  133. float a = ggxRoughness + 0.0001;\n\
  134. a *= a;\n\
  135. return ( 2.0 / a - 2.0 );\n\
  136. }\n\
  137. const float PI = 3.14159265358979;\n\
  138. vec3 ImportanceSamplePhong(vec2 uv, mat3 vecSpace, float specPow) {\n\
  139. float phi = uv.y * 2.0 * PI;\n\
  140. float cosTheta = pow(1.0 - uv.x, 1.0 / (specPow + 1.0));\n\
  141. float sinTheta = sqrt(1.0 - cosTheta * cosTheta);\n\
  142. vec3 sampleDir = vec3(cos(phi) * sinTheta, sin(phi) * sinTheta, cosTheta);\n\
  143. return vecSpace * sampleDir;\n\
  144. }\n\
  145. vec3 ImportanceSampleGGX( vec2 uv, mat3 vecSpace, float Roughness )\n\
  146. {\n\
  147. float a = Roughness * Roughness;\n\
  148. float Phi = 2.0 * PI * uv.x;\n\
  149. float CosTheta = sqrt( (1.0 - uv.y) / ( 1.0 + (a*a - 1.0) * uv.y ) );\n\
  150. float SinTheta = sqrt( 1.0 - CosTheta * CosTheta );\n\
  151. return vecSpace * vec3(SinTheta * cos( Phi ), SinTheta * sin( Phi ), CosTheta);\n\
  152. }\n\
  153. mat3 matrixFromVector(vec3 n) {\n\
  154. float a = 1.0 / (1.0 + n.z);\n\
  155. float b = -n.x * n.y * a;\n\
  156. vec3 b1 = vec3(1.0 - n.x * n.x * a, b, -n.x);\n\
  157. vec3 b2 = vec3(b, 1.0 - n.y * n.y * a, -n.y);\n\
  158. return mat3(b1, b2, n);\n\
  159. }\n\
  160. \n\
  161. vec4 testColorMap(float Roughness) {\n\
  162. vec4 color;\n\
  163. if(faceIndex == 0)\n\
  164. color = vec4(1.0,0.0,0.0,1.0);\n\
  165. else if(faceIndex == 1)\n\
  166. color = vec4(0.0,1.0,0.0,1.0);\n\
  167. else if(faceIndex == 2)\n\
  168. color = vec4(0.0,0.0,1.0,1.0);\n\
  169. else if(faceIndex == 3)\n\
  170. color = vec4(1.0,1.0,0.0,1.0);\n\
  171. else if(faceIndex == 4)\n\
  172. color = vec4(0.0,1.0,1.0,1.0);\n\
  173. else\n\
  174. color = vec4(1.0,0.0,1.0,1.0);\n\
  175. color *= ( 1.0 - Roughness );\n\
  176. return color;\n\
  177. }\n\
  178. void main() {\n\
  179. vec3 sampleDirection;\n\
  180. vec2 uv = vUv*2.0 - 1.0;\n\
  181. float offset = -1.0/mapSize;\n\
  182. const float a = -1.0;\n\
  183. const float b = 1.0;\n\
  184. float c = -1.0 + offset;\n\
  185. float d = 1.0 - offset;\n\
  186. float bminusa = b - a;\n\
  187. uv.x = (uv.x - a)/bminusa * d - (uv.x - b)/bminusa * c;\n\
  188. uv.y = (uv.y - a)/bminusa * d - (uv.y - b)/bminusa * c;\n\
  189. if (faceIndex==0) {\n\
  190. sampleDirection = vec3(1.0, -uv.y, -uv.x);\n\
  191. }\n\
  192. else if (faceIndex==1) {\n\
  193. sampleDirection = vec3(-1.0, -uv.y, uv.x);\n\
  194. } else if (faceIndex==2) {\n\
  195. sampleDirection = vec3(uv.x, 1.0, uv.y);\n\
  196. } else if (faceIndex==3) {\n\
  197. sampleDirection = vec3(uv.x, -1.0, -uv.y);\n\
  198. } else if (faceIndex==4) {\n\
  199. sampleDirection = vec3(uv.x, -uv.y, 1.0);\n\
  200. } else {\n\
  201. sampleDirection = vec3(-uv.x, -uv.y, -1.0);\n\
  202. }\n\
  203. mat3 vecSpace = matrixFromVector(normalize(sampleDirection));\n\
  204. vec3 rgbColor = vec3(0.0);\n\
  205. const int NumSamples = 1024;\n\
  206. vec3 vect;\n\
  207. float weight = 0.0;\n\
  208. for(int i=0; i<NumSamples; i++) {\n\
  209. float sini = sin(float(i));\n\
  210. float cosi = cos(float(i));\n\
  211. float rand = rnd(vec2(sini, cosi));\n\
  212. vect = ImportanceSampleGGX(vec2(float(i) / float(NumSamples), rand), vecSpace, roughness);\n\
  213. float dotProd = dot(vect, normalize(sampleDirection));\n\
  214. weight += dotProd;\n\
  215. vec3 color = envMapTexelToLinear(textureCube(envMap,vect)).rgb;\n\
  216. rgbColor.rgb += color;\n\
  217. }\n\
  218. rgbColor /= float(NumSamples);\n\
  219. //rgbColor = testColorMap( roughness ).rgb;\n\
  220. gl_FragColor = linearToOutputTexel( vec4( rgbColor, 1.0 ) );\n\
  221. }",
  222. blending: THREE.CustomBlending,
  223. blendSrc: THREE.OneFactor,
  224. blendDst: THREE.ZeroFactor,
  225. blendSrcAlpha: THREE.OneFactor,
  226. blendDstAlpha: THREE.ZeroFactor,
  227. blendEquation: THREE.AddEquation
  228. }
  229. );
  230. }
  231. };