PMREMGenerator.js 22 KB

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