PMREMGenerator.js 22 KB

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