PMREMGenerator.js 23 KB

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