PMREMGenerator.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  1. /**
  2. * @author Emmett Lalish / elalish
  3. *
  4. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  5. * (PMREM) from a cubeMap environment texture. This allows different levels of
  6. * blur to be quickly accessed based on material roughness. It is packed into a
  7. * special CubeUV format that allows us to perform custom interpolation so that
  8. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  10. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  11. * higher roughness levels. In this way we maintain resolution to smoothly
  12. * interpolate diffuse lighting while limiting sampling computation.
  13. */
  14. THREE.PMREMGenerator = ( function () {
  15. var LOD_MIN = 4;
  16. var LOD_MAX = 8;
  17. var SIZE_MAX = Math.pow( 2, LOD_MAX );
  18. // The standard deviations (radians) associated with the extra mips. These are
  19. // chosen to approximate a Trowbridge-Reitz distribution function times the
  20. // geometric shadowing function. These sigma values squared must match the
  21. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  22. var EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  23. var TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  24. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  25. // samples and exit early, but not recompile the shader.
  26. var MAX_SAMPLES = 20;
  27. var ENCODINGS = {
  28. [ THREE.LinearEncoding ]: 0,
  29. [ THREE.sRGBEncoding ]: 1,
  30. [ THREE.RGBEEncoding ]: 2,
  31. [ THREE.RGBM7Encoding ]: 3,
  32. [ THREE.RGBM16Encoding ]: 4,
  33. [ THREE.RGBDEncoding ]: 5,
  34. [ THREE.GammaEncoding ]: 6
  35. };
  36. var _flatCamera = new THREE.OrthographicCamera();
  37. var _blurMaterial = _getBlurShader( MAX_SAMPLES );
  38. var _equirectShader = null;
  39. var _cubemapShader = null;
  40. var { _lodPlanes, _sizeLods, _sigmas } = _createPlanes();
  41. var _pingPongRenderTarget = null;
  42. var _renderer = null;
  43. // Golden Ratio
  44. var PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  45. var INV_PHI = 1 / PHI;
  46. // Vertices of a dodecahedron (except the opposites, which represent the
  47. // same axis), used as axis directions evenly spread on a sphere.
  48. var _axisDirections = [
  49. new THREE.Vector3( 1, 1, 1 ),
  50. new THREE.Vector3( - 1, 1, 1 ),
  51. new THREE.Vector3( 1, 1, - 1 ),
  52. new THREE.Vector3( - 1, 1, - 1 ),
  53. new THREE.Vector3( 0, PHI, INV_PHI ),
  54. new THREE.Vector3( 0, PHI, - INV_PHI ),
  55. new THREE.Vector3( INV_PHI, 0, PHI ),
  56. new THREE.Vector3( - INV_PHI, 0, PHI ),
  57. new THREE.Vector3( PHI, INV_PHI, 0 ),
  58. new THREE.Vector3( - PHI, INV_PHI, 0 ) ];
  59. var PMREMGenerator = function ( renderer ) {
  60. _renderer = renderer;
  61. _compileMaterial( _blurMaterial );
  62. };
  63. PMREMGenerator.prototype = {
  64. constructor: PMREMGenerator,
  65. /**
  66. * Generates a PMREM from a supplied Scene, which can be faster than using an
  67. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  68. * in radians to be applied to the scene before PMREM generation. Optional near
  69. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  70. * is placed at the origin).
  71. */
  72. fromScene: function ( scene, sigma = 0, near = 0.1, far = 100 ) {
  73. var cubeUVRenderTarget = _allocateTargets();
  74. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  75. if ( sigma > 0 ) {
  76. _blur( cubeUVRenderTarget, 0, 0, sigma );
  77. }
  78. _applyPMREM( cubeUVRenderTarget );
  79. _cleanup();
  80. cubeUVRenderTarget.scissorTest = false;
  81. return cubeUVRenderTarget;
  82. },
  83. /**
  84. * Generates a PMREM from an equirectangular texture, which can be either LDR
  85. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  86. * as this matches best with the 256 x 256 cubemap output.
  87. */
  88. fromEquirectangular: function ( equirectangular ) {
  89. equirectangular.magFilter = THREE.NearestFilter;
  90. equirectangular.minFilter = THREE.NearestFilter;
  91. equirectangular.generateMipmaps = false;
  92. return this.fromCubemap( equirectangular );
  93. },
  94. /**
  95. * Generates a PMREM from an cubemap texture, which can be either LDR
  96. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  97. * as this matches best with the 256 x 256 cubemap output.
  98. */
  99. fromCubemap: function ( cubemap ) {
  100. var cubeUVRenderTarget = _allocateTargets( cubemap );
  101. _textureToCubeUV( cubemap, cubeUVRenderTarget );
  102. _applyPMREM( cubeUVRenderTarget );
  103. _cleanup();
  104. cubeUVRenderTarget.scissorTest = false;
  105. return cubeUVRenderTarget;
  106. },
  107. /**
  108. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  109. * your texture's network fetch for increased concurrency.
  110. */
  111. compileCubemapShader: function () {
  112. if ( _cubemapShader == null ) {
  113. _cubemapShader = _getCubemapShader();
  114. _compileMaterial( _cubemapShader );
  115. }
  116. },
  117. /**
  118. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  119. * your texture's network fetch for increased concurrency.
  120. */
  121. compileEquirectangularShader: function () {
  122. if ( _equirectShader == null ) {
  123. _equirectShader = _getEquirectShader();
  124. _compileMaterial( _equirectShader );
  125. }
  126. },
  127. /**
  128. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  129. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  130. * one of them will cause any others to also become unusable.
  131. */
  132. dispose: function () {
  133. _blurMaterial.dispose();
  134. if ( _cubemapShader != null ) _cubemapShader.dispose();
  135. if ( _equirectShader != null ) _equirectShader.dispose();
  136. var plane;
  137. for ( plane of _lodPlanes ) {
  138. plane.dispose();
  139. }
  140. },
  141. };
  142. function _createPlanes() {
  143. var _lodPlanes = [];
  144. var _sizeLods = [];
  145. var _sigmas = [];
  146. var lod = LOD_MAX;
  147. for ( var i = 0; i < TOTAL_LODS; i ++ ) {
  148. var sizeLod = Math.pow( 2, lod );
  149. _sizeLods.push( sizeLod );
  150. var sigma = 1.0 / sizeLod;
  151. if ( i > LOD_MAX - LOD_MIN ) {
  152. sigma = EXTRA_LOD_SIGMA[ i - LOD_MAX + LOD_MIN - 1 ];
  153. } else if ( i == 0 ) {
  154. sigma = 0;
  155. }
  156. _sigmas.push( sigma );
  157. var texelSize = 1.0 / ( sizeLod - 1 );
  158. var min = - texelSize / 2;
  159. var max = 1 + texelSize / 2;
  160. var uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  161. var cubeFaces = 6;
  162. var vertices = 6;
  163. var positionSize = 3;
  164. var uvSize = 2;
  165. var faceIndexSize = 1;
  166. var position = new Float32Array( positionSize * vertices * cubeFaces );
  167. var uv = new Float32Array( uvSize * vertices * cubeFaces );
  168. var faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  169. for ( var face = 0; face < cubeFaces; face ++ ) {
  170. var x = ( face % 3 ) * 2 / 3 - 1;
  171. var y = face > 2 ? 0 : - 1;
  172. var coordinates = [
  173. [ x, y, 0 ],
  174. [ x + 2 / 3, y, 0 ],
  175. [ x + 2 / 3, y + 1, 0 ],
  176. [ x, y, 0 ],
  177. [ x + 2 / 3, y + 1, 0 ],
  178. [ x, y + 1, 0 ]
  179. ];
  180. position.set( [].concat( ...coordinates ),
  181. positionSize * vertices * face );
  182. uv.set( uv1, uvSize * vertices * face );
  183. var fill = [ face, face, face, face, face, face ];
  184. faceIndex.set( fill, faceIndexSize * vertices * face );
  185. }
  186. var planes = new THREE.BufferGeometry();
  187. planes.setAttribute(
  188. 'position', new THREE.BufferAttribute( position, positionSize ) );
  189. planes.setAttribute( 'uv', new THREE.BufferAttribute( uv, uvSize ) );
  190. planes.setAttribute(
  191. 'faceIndex', new THREE.BufferAttribute( faceIndex, faceIndexSize ) );
  192. _lodPlanes.push( planes );
  193. if ( lod > LOD_MIN ) {
  194. lod --;
  195. }
  196. }
  197. return { _lodPlanes, _sizeLods, _sigmas };
  198. }
  199. function _allocateTargets( equirectangular ) {
  200. var params = {
  201. magFilter: THREE.NearestFilter,
  202. minFilter: THREE.NearestFilter,
  203. generateMipmaps: false,
  204. type: equirectangular ? equirectangular.type : THREE.UnsignedByteType,
  205. format: equirectangular ? equirectangular.format : THREE.RGBEFormat,
  206. encoding: equirectangular ? equirectangular.encoding : THREE.RGBEEncoding,
  207. depthBuffer: false,
  208. stencilBuffer: false
  209. };
  210. var cubeUVRenderTarget = _createRenderTarget(
  211. { ...params, depthBuffer: ( equirectangular ? false : true ) } );
  212. _pingPongRenderTarget = _createRenderTarget( params );
  213. return cubeUVRenderTarget;
  214. }
  215. function _cleanup() {
  216. _pingPongRenderTarget.dispose();
  217. _renderer.setRenderTarget( null );
  218. var size = _renderer.getSize( new THREE.Vector2() );
  219. _renderer.setViewport( 0, 0, size.x, size.y );
  220. }
  221. function _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  222. var fov = 90;
  223. var aspect = 1;
  224. var cubeCamera = new THREE.PerspectiveCamera( fov, aspect, near, far );
  225. var upSign = [ 1, 1, 1, 1, - 1, 1 ];
  226. var forwardSign = [ 1, 1, - 1, - 1, - 1, 1 ];
  227. var outputEncoding = _renderer.outputEncoding;
  228. var toneMapping = _renderer.toneMapping;
  229. var toneMappingExposure = _renderer.toneMappingExposure;
  230. var clearColor = _renderer.getClearColor();
  231. var clearAlpha = _renderer.getClearAlpha();
  232. _renderer.toneMapping = THREE.LinearToneMapping;
  233. _renderer.toneMappingExposure = 1.0;
  234. _renderer.outputEncoding = THREE.LinearEncoding;
  235. scene.scale.z *= - 1;
  236. var background = scene.background;
  237. if ( background && background.isColor ) {
  238. background.convertSRGBToLinear();
  239. // Convert linear to RGBE
  240. var maxComponent = Math.max( background.r, background.g, background.b );
  241. var fExp = Math.min( Math.max( Math.ceil( Math.log2( maxComponent ) ), - 128.0 ), 127.0 );
  242. background = background.multiplyScalar( Math.pow( 2.0, - fExp ) );
  243. var alpha = ( fExp + 128.0 ) / 255.0;
  244. _renderer.setClearColor( background, alpha );
  245. scene.background = null;
  246. }
  247. _renderer.setRenderTarget( cubeUVRenderTarget );
  248. for ( var i = 0; i < 6; i ++ ) {
  249. var col = i % 3;
  250. if ( col == 0 ) {
  251. cubeCamera.up.set( 0, upSign[ i ], 0 );
  252. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  253. } else if ( col == 1 ) {
  254. cubeCamera.up.set( 0, 0, upSign[ i ] );
  255. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  256. } else {
  257. cubeCamera.up.set( 0, upSign[ i ], 0 );
  258. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  259. }
  260. _setViewport(
  261. col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX );
  262. _renderer.render( scene, cubeCamera );
  263. }
  264. _renderer.toneMapping = toneMapping;
  265. _renderer.toneMappingExposure = toneMappingExposure;
  266. _renderer.outputEncoding = outputEncoding;
  267. _renderer.setClearColor( clearColor, clearAlpha );
  268. scene.scale.z *= - 1;
  269. }
  270. function _textureToCubeUV( texture, cubeUVRenderTarget ) {
  271. var scene = new THREE.Scene();
  272. if ( texture.isCubeTexture ) {
  273. if ( _cubemapShader == null ) {
  274. _cubemapShader = _getCubemapShader();
  275. }
  276. } else {
  277. if ( _equirectShader == null ) {
  278. _equirectShader = _getEquirectShader();
  279. }
  280. }
  281. var material = texture.isCubeTexture ? _cubemapShader : _equirectShader;
  282. scene.add( new THREE.Mesh( _lodPlanes[ 0 ], material ) );
  283. var uniforms = material.uniforms;
  284. uniforms[ 'envMap' ].value = texture;
  285. if ( ! texture.isCubeTexture ) {
  286. uniforms[ 'texelSize' ].value.set( 1.0 / texture.image.width, 1.0 / texture.image.height );
  287. }
  288. uniforms[ 'inputEncoding' ].value = ENCODINGS[ texture.encoding ];
  289. uniforms[ 'outputEncoding' ].value = ENCODINGS[ texture.encoding ];
  290. _renderer.setRenderTarget( cubeUVRenderTarget );
  291. _setViewport( 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX );
  292. _renderer.render( scene, _flatCamera );
  293. }
  294. function _compileMaterial( material ) {
  295. var tmpScene = new THREE.Scene();
  296. tmpScene.add( new THREE.Mesh( _lodPlanes[ 0 ], material ) );
  297. _renderer.compile( tmpScene, _flatCamera );
  298. }
  299. function _createRenderTarget( params ) {
  300. var cubeUVRenderTarget =
  301. new THREE.WebGLRenderTarget( 3 * SIZE_MAX, 3 * SIZE_MAX, params );
  302. cubeUVRenderTarget.texture.mapping = THREE.CubeUVReflectionMapping;
  303. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  304. cubeUVRenderTarget.scissorTest = true;
  305. return cubeUVRenderTarget;
  306. }
  307. function _setViewport( x, y, width, height ) {
  308. var invDpr = 1.0 / _renderer.getPixelRatio();
  309. x *= invDpr;
  310. y *= invDpr;
  311. width *= invDpr;
  312. height *= invDpr;
  313. _renderer.setViewport( x, y, width, height );
  314. _renderer.setScissor( x, y, width, height );
  315. }
  316. function _applyPMREM( cubeUVRenderTarget ) {
  317. var autoClear = _renderer.autoClear;
  318. _renderer.autoClear = false;
  319. for ( var i = 1; i < TOTAL_LODS; i ++ ) {
  320. var sigma = Math.sqrt(
  321. _sigmas[ i ] * _sigmas[ i ] -
  322. _sigmas[ i - 1 ] * _sigmas[ i - 1 ] );
  323. var poleAxis =
  324. _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  325. _blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  326. }
  327. _renderer.autoClear = autoClear;
  328. }
  329. /**
  330. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  331. * vertically and horizontally, but this breaks down on a cube. Here we apply
  332. * the blur latitudinally (around the poles), and then longitudinally (towards
  333. * the poles) to approximate the orthogonally-separable blur. It is least
  334. * accurate at the poles, but still does a decent job.
  335. */
  336. function _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  337. _halfBlur(
  338. cubeUVRenderTarget,
  339. _pingPongRenderTarget,
  340. lodIn,
  341. lodOut,
  342. sigma,
  343. 'latitudinal',
  344. poleAxis );
  345. _halfBlur(
  346. _pingPongRenderTarget,
  347. cubeUVRenderTarget,
  348. lodOut,
  349. lodOut,
  350. sigma,
  351. 'longitudinal',
  352. poleAxis );
  353. }
  354. function _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  355. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  356. console.error(
  357. 'blur direction must be either latitudinal or longitudinal!' );
  358. }
  359. // Number of standard deviations at which to cut off the discrete approximation.
  360. var STANDARD_DEVIATIONS = 3;
  361. var blurScene = new THREE.Scene();
  362. blurScene.add( new THREE.Mesh( _lodPlanes[ lodOut ], _blurMaterial ) );
  363. var blurUniforms = _blurMaterial.uniforms;
  364. var pixels = _sizeLods[ lodIn ] - 1;
  365. var radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  366. var sigmaPixels = sigmaRadians / radiansPerPixel;
  367. var samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  368. if ( samples > MAX_SAMPLES ) {
  369. console.warn( `sigmaRadians, ${
  370. sigmaRadians}, is too large and will clip, as it requested ${
  371. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  372. }
  373. var weights = [];
  374. var sum = 0;
  375. for ( var i = 0; i < MAX_SAMPLES; ++ i ) {
  376. var x = i / sigmaPixels;
  377. var weight = Math.exp( - x * x / 2 );
  378. weights.push( weight );
  379. if ( i == 0 ) {
  380. sum += weight;
  381. } else if ( i < samples ) {
  382. sum += 2 * weight;
  383. }
  384. }
  385. weights = weights.map( w => w / sum );
  386. blurUniforms[ 'envMap' ].value = targetIn.texture;
  387. blurUniforms[ 'samples' ].value = samples;
  388. blurUniforms[ 'weights' ].value = weights;
  389. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  390. if ( poleAxis ) {
  391. blurUniforms[ 'poleAxis' ].value = poleAxis;
  392. }
  393. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  394. blurUniforms[ 'mipInt' ].value = LOD_MAX - lodIn;
  395. blurUniforms[ 'inputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ];
  396. blurUniforms[ 'outputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ];
  397. var outputSize = _sizeLods[ lodOut ];
  398. var x = 3 * Math.max( 0, SIZE_MAX - 2 * outputSize );
  399. var y = ( lodOut === 0 ? 0 : 2 * SIZE_MAX ) +
  400. 2 * outputSize *
  401. ( lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0 );
  402. _renderer.setRenderTarget( targetOut );
  403. _setViewport( x, y, 3 * outputSize, 2 * outputSize );
  404. _renderer.render( blurScene, _flatCamera );
  405. }
  406. function _getBlurShader( maxSamples ) {
  407. var weights = new Float32Array( maxSamples );
  408. var poleAxis = new THREE.Vector3( 0, 1, 0 );
  409. var shaderMaterial = new THREE.RawShaderMaterial( {
  410. defines: { 'n': maxSamples },
  411. uniforms: {
  412. 'envMap': { value: null },
  413. 'samples': { value: 1 },
  414. 'weights': { value: weights },
  415. 'latitudinal': { value: false },
  416. 'dTheta': { value: 0 },
  417. 'mipInt': { value: 0 },
  418. 'poleAxis': { value: poleAxis },
  419. 'inputEncoding': { value: ENCODINGS[ THREE.LinearEncoding ] },
  420. 'outputEncoding': { value: ENCODINGS[ THREE.LinearEncoding ] }
  421. },
  422. vertexShader: _getCommonVertexShader(),
  423. fragmentShader: `
  424. precision mediump float;
  425. precision mediump int;
  426. varying vec3 vOutputDirection;
  427. uniform sampler2D envMap;
  428. uniform int samples;
  429. uniform float weights[n];
  430. uniform bool latitudinal;
  431. uniform float dTheta;
  432. uniform float mipInt;
  433. uniform vec3 poleAxis;
  434. ${_getEncodings()}
  435. #define ENVMAP_TYPE_CUBE_UV
  436. #include <cube_uv_reflection_fragment>
  437. void main() {
  438. gl_FragColor = vec4(0.0);
  439. for (int i = 0; i < n; i++) {
  440. if (i >= samples)
  441. break;
  442. for (int dir = -1; dir < 2; dir += 2) {
  443. if (i == 0 && dir == 1)
  444. continue;
  445. vec3 axis = latitudinal ? poleAxis : cross(poleAxis, vOutputDirection);
  446. if (all(equal(axis, vec3(0.0))))
  447. axis = cross(vec3(0.0, 1.0, 0.0), vOutputDirection);
  448. axis = normalize(axis);
  449. float theta = dTheta * float(dir * i);
  450. float cosTheta = cos(theta);
  451. // Rodrigues' axis-angle rotation
  452. vec3 sampleDirection = vOutputDirection * cosTheta
  453. + cross(axis, vOutputDirection) * sin(theta)
  454. + axis * dot(axis, vOutputDirection) * (1.0 - cosTheta);
  455. gl_FragColor.rgb +=
  456. weights[i] * bilinearCubeUV(envMap, sampleDirection, mipInt);
  457. }
  458. }
  459. gl_FragColor = linearToOutputTexel(gl_FragColor);
  460. }
  461. `,
  462. blending: THREE.NoBlending,
  463. depthTest: false,
  464. depthWrite: false
  465. } );
  466. shaderMaterial.type = 'SphericalGaussianBlur';
  467. return shaderMaterial;
  468. }
  469. function _getEquirectShader() {
  470. var texelSize = new THREE.Vector2( 1, 1 );
  471. var shaderMaterial = new THREE.RawShaderMaterial( {
  472. uniforms: {
  473. 'envMap': { value: null },
  474. 'texelSize': { value: texelSize },
  475. 'inputEncoding': { value: ENCODINGS[ THREE.LinearEncoding ] },
  476. 'outputEncoding': { value: ENCODINGS[ THREE.LinearEncoding ] }
  477. },
  478. vertexShader: _getCommonVertexShader(),
  479. fragmentShader: `
  480. precision mediump float;
  481. precision mediump int;
  482. varying vec3 vOutputDirection;
  483. uniform sampler2D envMap;
  484. uniform vec2 texelSize;
  485. ${_getEncodings()}
  486. #define RECIPROCAL_PI 0.31830988618
  487. #define RECIPROCAL_PI2 0.15915494
  488. void main() {
  489. gl_FragColor = vec4(0.0);
  490. vec3 outputDirection = normalize(vOutputDirection);
  491. vec2 uv;
  492. uv.y = asin(clamp(outputDirection.y, -1.0, 1.0)) * RECIPROCAL_PI + 0.5;
  493. uv.x = atan(outputDirection.z, outputDirection.x) * RECIPROCAL_PI2 + 0.5;
  494. vec2 f = fract(uv / texelSize - 0.5);
  495. uv -= f * texelSize;
  496. vec3 tl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;
  497. uv.x += texelSize.x;
  498. vec3 tr = envMapTexelToLinear(texture2D(envMap, uv)).rgb;
  499. uv.y += texelSize.y;
  500. vec3 br = envMapTexelToLinear(texture2D(envMap, uv)).rgb;
  501. uv.x -= texelSize.x;
  502. vec3 bl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;
  503. vec3 tm = mix(tl, tr, f.x);
  504. vec3 bm = mix(bl, br, f.x);
  505. gl_FragColor.rgb = mix(tm, bm, f.y);
  506. gl_FragColor = linearToOutputTexel(gl_FragColor);
  507. }
  508. `,
  509. blending: THREE.NoBlending,
  510. depthTest: false,
  511. depthWrite: false
  512. } );
  513. shaderMaterial.type = 'EquirectangularToCubeUV';
  514. return shaderMaterial;
  515. }
  516. function _getCubemapShader() {
  517. var shaderMaterial = new THREE.RawShaderMaterial( {
  518. uniforms: {
  519. 'envMap': { value: null },
  520. 'inputEncoding': { value: ENCODINGS[ THREE.LinearEncoding ] },
  521. 'outputEncoding': { value: ENCODINGS[ THREE.LinearEncoding ] }
  522. },
  523. vertexShader: _getCommonVertexShader(),
  524. fragmentShader: `
  525. precision mediump float;
  526. precision mediump int;
  527. varying vec3 vOutputDirection;
  528. uniform samplerCube envMap;
  529. ${_getEncodings()}
  530. void main() {
  531. gl_FragColor = vec4(0.0);
  532. gl_FragColor.rgb = envMapTexelToLinear(textureCube(envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ))).rgb;
  533. gl_FragColor = linearToOutputTexel(gl_FragColor);
  534. }
  535. `,
  536. blending: THREE.NoBlending,
  537. depthTest: false,
  538. depthWrite: false
  539. } );
  540. shaderMaterial.type = 'CubemapToCubeUV';
  541. return shaderMaterial;
  542. }
  543. function _getCommonVertexShader() {
  544. return `
  545. precision mediump float;
  546. precision mediump int;
  547. attribute vec3 position;
  548. attribute vec2 uv;
  549. attribute float faceIndex;
  550. varying vec3 vOutputDirection;
  551. vec3 getDirection(vec2 uv, float face) {
  552. uv = 2.0 * uv - 1.0;
  553. vec3 direction = vec3(uv, 1.0);
  554. if (face == 0.0) {
  555. direction = direction.zyx;
  556. direction.z *= -1.0;
  557. } else if (face == 1.0) {
  558. direction = direction.xzy;
  559. direction.z *= -1.0;
  560. } else if (face == 3.0) {
  561. direction = direction.zyx;
  562. direction.x *= -1.0;
  563. } else if (face == 4.0) {
  564. direction = direction.xzy;
  565. direction.y *= -1.0;
  566. } else if (face == 5.0) {
  567. direction.xz *= -1.0;
  568. }
  569. return direction;
  570. }
  571. void main() {
  572. vOutputDirection = getDirection(uv, faceIndex);
  573. gl_Position = vec4( position, 1.0 );
  574. }
  575. `;
  576. }
  577. function _getEncodings() {
  578. return `
  579. uniform int inputEncoding;
  580. uniform int outputEncoding;
  581. #include <encodings_pars_fragment>
  582. vec4 inputTexelToLinear(vec4 value){
  583. if(inputEncoding == 0){
  584. return value;
  585. }else if(inputEncoding == 1){
  586. return sRGBToLinear(value);
  587. }else if(inputEncoding == 2){
  588. return RGBEToLinear(value);
  589. }else if(inputEncoding == 3){
  590. return RGBMToLinear(value, 7.0);
  591. }else if(inputEncoding == 4){
  592. return RGBMToLinear(value, 16.0);
  593. }else if(inputEncoding == 5){
  594. return RGBDToLinear(value, 256.0);
  595. }else{
  596. return GammaToLinear(value, 2.2);
  597. }
  598. }
  599. vec4 linearToOutputTexel(vec4 value){
  600. if(outputEncoding == 0){
  601. return value;
  602. }else if(outputEncoding == 1){
  603. return LinearTosRGB(value);
  604. }else if(outputEncoding == 2){
  605. return LinearToRGBE(value);
  606. }else if(outputEncoding == 3){
  607. return LinearToRGBM(value, 7.0);
  608. }else if(outputEncoding == 4){
  609. return LinearToRGBM(value, 16.0);
  610. }else if(outputEncoding == 5){
  611. return LinearToRGBD(value, 256.0);
  612. }else{
  613. return LinearToGamma(value, 2.2);
  614. }
  615. }
  616. vec4 envMapTexelToLinear(vec4 color) {
  617. return inputTexelToLinear(color);
  618. }
  619. `;
  620. }
  621. return PMREMGenerator;
  622. } )();