PMREMGenerator.js 19 KB

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