PMREMGenerator.js 21 KB

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