PMREMGenerator.js 21 KB

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