PMREMGenerator.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  1. import {
  2. CubeReflectionMapping,
  3. CubeRefractionMapping,
  4. CubeUVReflectionMapping,
  5. LinearEncoding,
  6. LinearFilter,
  7. NoToneMapping,
  8. NoBlending,
  9. RGBAFormat,
  10. HalfFloatType
  11. } from '../constants.js';
  12. import { BufferAttribute } from '../core/BufferAttribute.js';
  13. import { BufferGeometry } from '../core/BufferGeometry.js';
  14. import { Mesh } from '../objects/Mesh.js';
  15. import { OrthographicCamera } from '../cameras/OrthographicCamera.js';
  16. import { PerspectiveCamera } from '../cameras/PerspectiveCamera.js';
  17. import { RawShaderMaterial } from '../materials/RawShaderMaterial.js';
  18. import { Vector2 } from '../math/Vector2.js';
  19. import { Vector3 } from '../math/Vector3.js';
  20. import { Color } from '../math/Color.js';
  21. import { WebGLRenderTarget } from '../renderers/WebGLRenderTarget.js';
  22. import { MeshBasicMaterial } from '../materials/MeshBasicMaterial.js';
  23. import { BoxGeometry } from '../geometries/BoxGeometry.js';
  24. import { BackSide } from '../constants.js';
  25. const LOD_MIN = 4;
  26. const LOD_MAX = 8;
  27. const SIZE_MAX = Math.pow( 2, LOD_MAX );
  28. // The standard deviations (radians) associated with the extra mips. These are
  29. // chosen to approximate a Trowbridge-Reitz distribution function times the
  30. // geometric shadowing function. These sigma values squared must match the
  31. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  32. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  33. const TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  34. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  35. // samples and exit early, but not recompile the shader.
  36. const MAX_SAMPLES = 20;
  37. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  38. const { _lodPlanes, _sizeLods, _sigmas } = /*@__PURE__*/ _createPlanes();
  39. const _clearColor = /*@__PURE__*/ new Color();
  40. let _oldTarget = null;
  41. // Golden Ratio
  42. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  43. const 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. const _axisDirections = [
  47. /*@__PURE__*/ new Vector3( 1, 1, 1 ),
  48. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  49. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  50. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  51. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  52. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  53. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  54. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  55. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  56. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ];
  57. /**
  58. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  59. * (PMREM) from a cubeMap environment texture. This allows different levels of
  60. * blur to be quickly accessed based on material roughness. It is packed into a
  61. * special CubeUV format that allows us to perform custom interpolation so that
  62. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  63. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  64. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  65. * higher roughness levels. In this way we maintain resolution to smoothly
  66. * interpolate diffuse lighting while limiting sampling computation.
  67. *
  68. * Paper: Fast, Accurate Image-Based Lighting
  69. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  70. */
  71. class PMREMGenerator {
  72. constructor( renderer ) {
  73. this._renderer = renderer;
  74. this._pingPongRenderTarget = null;
  75. this._blurMaterial = _getBlurShader( MAX_SAMPLES );
  76. this._equirectShader = null;
  77. this._cubemapShader = null;
  78. this._compileMaterial( this._blurMaterial );
  79. }
  80. /**
  81. * Generates a PMREM from a supplied Scene, which can be faster than using an
  82. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  83. * in radians to be applied to the scene before PMREM generation. Optional near
  84. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  85. * is placed at the origin).
  86. */
  87. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  88. _oldTarget = this._renderer.getRenderTarget();
  89. const cubeUVRenderTarget = this._allocateTargets();
  90. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  91. if ( sigma > 0 ) {
  92. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  93. }
  94. this._applyPMREM( cubeUVRenderTarget );
  95. this._cleanup( cubeUVRenderTarget );
  96. return cubeUVRenderTarget;
  97. }
  98. /**
  99. * Generates a PMREM from an equirectangular texture, which can be either LDR
  100. * or HDR. The ideal input image size is 1k (1024 x 512),
  101. * as this matches best with the 256 x 256 cubemap output.
  102. */
  103. fromEquirectangular( equirectangular ) {
  104. return this._fromTexture( equirectangular );
  105. }
  106. /**
  107. * Generates a PMREM from an cubemap texture, which can be either LDR
  108. * or HDR. The ideal input cube size is 256 x 256,
  109. * as this matches best with the 256 x 256 cubemap output.
  110. */
  111. fromCubemap( cubemap ) {
  112. return this._fromTexture( cubemap );
  113. }
  114. /**
  115. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  116. * your texture's network fetch for increased concurrency.
  117. */
  118. compileCubemapShader() {
  119. if ( this._cubemapShader === null ) {
  120. this._cubemapShader = _getCubemapShader();
  121. this._compileMaterial( this._cubemapShader );
  122. }
  123. }
  124. /**
  125. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  126. * your texture's network fetch for increased concurrency.
  127. */
  128. compileEquirectangularShader() {
  129. if ( this._equirectShader === null ) {
  130. this._equirectShader = _getEquirectShader();
  131. this._compileMaterial( this._equirectShader );
  132. }
  133. }
  134. /**
  135. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  136. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  137. * one of them will cause any others to also become unusable.
  138. */
  139. dispose() {
  140. this._blurMaterial.dispose();
  141. if ( this._cubemapShader !== null ) this._cubemapShader.dispose();
  142. if ( this._equirectShader !== null ) this._equirectShader.dispose();
  143. for ( let i = 0; i < _lodPlanes.length; i ++ ) {
  144. _lodPlanes[ i ].dispose();
  145. }
  146. }
  147. // private interface
  148. _cleanup( outputTarget ) {
  149. this._pingPongRenderTarget.dispose();
  150. this._renderer.setRenderTarget( _oldTarget );
  151. outputTarget.scissorTest = false;
  152. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  153. }
  154. _fromTexture( texture ) {
  155. _oldTarget = this._renderer.getRenderTarget();
  156. const cubeUVRenderTarget = this._allocateTargets( texture );
  157. this._textureToCubeUV( texture, cubeUVRenderTarget );
  158. this._applyPMREM( cubeUVRenderTarget );
  159. this._cleanup( cubeUVRenderTarget );
  160. return cubeUVRenderTarget;
  161. }
  162. _allocateTargets( texture ) { // warning: null texture is valid
  163. const params = {
  164. magFilter: LinearFilter,
  165. minFilter: LinearFilter,
  166. generateMipmaps: false,
  167. type: HalfFloatType,
  168. format: RGBAFormat,
  169. encoding: LinearEncoding,
  170. depthBuffer: false
  171. };
  172. const cubeUVRenderTarget = _createRenderTarget( params );
  173. cubeUVRenderTarget.depthBuffer = texture ? false : true;
  174. this._pingPongRenderTarget = _createRenderTarget( params );
  175. return cubeUVRenderTarget;
  176. }
  177. _compileMaterial( material ) {
  178. const tmpMesh = new Mesh( _lodPlanes[ 0 ], material );
  179. this._renderer.compile( tmpMesh, _flatCamera );
  180. }
  181. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  182. const fov = 90;
  183. const aspect = 1;
  184. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  185. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  186. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  187. const renderer = this._renderer;
  188. const originalAutoClear = renderer.autoClear;
  189. const toneMapping = renderer.toneMapping;
  190. renderer.getClearColor( _clearColor );
  191. renderer.toneMapping = NoToneMapping;
  192. renderer.autoClear = false;
  193. const backgroundMaterial = new MeshBasicMaterial( {
  194. name: 'PMREM.Background',
  195. side: BackSide,
  196. depthWrite: false,
  197. depthTest: false,
  198. } );
  199. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  200. let useSolidColor = false;
  201. const background = scene.background;
  202. if ( background ) {
  203. if ( background.isColor ) {
  204. backgroundMaterial.color.copy( background );
  205. scene.background = null;
  206. useSolidColor = true;
  207. }
  208. } else {
  209. backgroundMaterial.color.copy( _clearColor );
  210. useSolidColor = true;
  211. }
  212. for ( let i = 0; i < 6; i ++ ) {
  213. const col = i % 3;
  214. if ( col == 0 ) {
  215. cubeCamera.up.set( 0, upSign[ i ], 0 );
  216. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  217. } else if ( col == 1 ) {
  218. cubeCamera.up.set( 0, 0, upSign[ i ] );
  219. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  220. } else {
  221. cubeCamera.up.set( 0, upSign[ i ], 0 );
  222. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  223. }
  224. _setViewport( cubeUVRenderTarget,
  225. col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX );
  226. renderer.setRenderTarget( cubeUVRenderTarget );
  227. if ( useSolidColor ) {
  228. renderer.render( backgroundBox, cubeCamera );
  229. }
  230. renderer.render( scene, cubeCamera );
  231. }
  232. backgroundBox.geometry.dispose();
  233. backgroundBox.material.dispose();
  234. renderer.toneMapping = toneMapping;
  235. renderer.autoClear = originalAutoClear;
  236. scene.background = background;
  237. }
  238. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  239. const renderer = this._renderer;
  240. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  241. if ( isCubeTexture ) {
  242. if ( this._cubemapShader == null ) {
  243. this._cubemapShader = _getCubemapShader();
  244. }
  245. } else {
  246. if ( this._equirectShader == null ) {
  247. this._equirectShader = _getEquirectShader();
  248. }
  249. }
  250. const material = isCubeTexture ? this._cubemapShader : this._equirectShader;
  251. const mesh = new Mesh( _lodPlanes[ 0 ], material );
  252. const uniforms = material.uniforms;
  253. uniforms[ 'envMap' ].value = texture;
  254. if ( ! isCubeTexture ) {
  255. uniforms[ 'texelSize' ].value.set( 1.0 / texture.image.width, 1.0 / texture.image.height );
  256. }
  257. _setViewport( cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX );
  258. renderer.setRenderTarget( cubeUVRenderTarget );
  259. renderer.render( mesh, _flatCamera );
  260. }
  261. _applyPMREM( cubeUVRenderTarget ) {
  262. const renderer = this._renderer;
  263. const autoClear = renderer.autoClear;
  264. renderer.autoClear = false;
  265. for ( let i = 1; i < TOTAL_LODS; i ++ ) {
  266. const sigma = Math.sqrt( _sigmas[ i ] * _sigmas[ i ] - _sigmas[ i - 1 ] * _sigmas[ i - 1 ] );
  267. const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  268. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  269. }
  270. renderer.autoClear = autoClear;
  271. }
  272. /**
  273. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  274. * vertically and horizontally, but this breaks down on a cube. Here we apply
  275. * the blur latitudinally (around the poles), and then longitudinally (towards
  276. * the poles) to approximate the orthogonally-separable blur. It is least
  277. * accurate at the poles, but still does a decent job.
  278. */
  279. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  280. const pingPongRenderTarget = this._pingPongRenderTarget;
  281. this._halfBlur(
  282. cubeUVRenderTarget,
  283. pingPongRenderTarget,
  284. lodIn,
  285. lodOut,
  286. sigma,
  287. 'latitudinal',
  288. poleAxis );
  289. this._halfBlur(
  290. pingPongRenderTarget,
  291. cubeUVRenderTarget,
  292. lodOut,
  293. lodOut,
  294. sigma,
  295. 'longitudinal',
  296. poleAxis );
  297. }
  298. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  299. const renderer = this._renderer;
  300. const blurMaterial = this._blurMaterial;
  301. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  302. console.error(
  303. 'blur direction must be either latitudinal or longitudinal!' );
  304. }
  305. // Number of standard deviations at which to cut off the discrete approximation.
  306. const STANDARD_DEVIATIONS = 3;
  307. const blurMesh = new Mesh( _lodPlanes[ lodOut ], blurMaterial );
  308. const blurUniforms = blurMaterial.uniforms;
  309. const pixels = _sizeLods[ lodIn ] - 1;
  310. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  311. const sigmaPixels = sigmaRadians / radiansPerPixel;
  312. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  313. if ( samples > MAX_SAMPLES ) {
  314. console.warn( `sigmaRadians, ${
  315. sigmaRadians}, is too large and will clip, as it requested ${
  316. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  317. }
  318. const weights = [];
  319. let sum = 0;
  320. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  321. const x = i / sigmaPixels;
  322. const weight = Math.exp( - x * x / 2 );
  323. weights.push( weight );
  324. if ( i == 0 ) {
  325. sum += weight;
  326. } else if ( i < samples ) {
  327. sum += 2 * weight;
  328. }
  329. }
  330. for ( let i = 0; i < weights.length; i ++ ) {
  331. weights[ i ] = weights[ i ] / sum;
  332. }
  333. blurUniforms[ 'envMap' ].value = targetIn.texture;
  334. blurUniforms[ 'samples' ].value = samples;
  335. blurUniforms[ 'weights' ].value = weights;
  336. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  337. if ( poleAxis ) {
  338. blurUniforms[ 'poleAxis' ].value = poleAxis;
  339. }
  340. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  341. blurUniforms[ 'mipInt' ].value = LOD_MAX - lodIn;
  342. const outputSize = _sizeLods[ lodOut ];
  343. const x = 3 * Math.max( 0, SIZE_MAX - 2 * outputSize );
  344. const y = ( lodOut === 0 ? 0 : 2 * SIZE_MAX ) + 2 * outputSize * ( lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0 );
  345. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  346. renderer.setRenderTarget( targetOut );
  347. renderer.render( blurMesh, _flatCamera );
  348. }
  349. }
  350. function _createPlanes() {
  351. const _lodPlanes = [];
  352. const _sizeLods = [];
  353. const _sigmas = [];
  354. let lod = LOD_MAX;
  355. for ( let i = 0; i < TOTAL_LODS; i ++ ) {
  356. const sizeLod = Math.pow( 2, lod );
  357. _sizeLods.push( sizeLod );
  358. let sigma = 1.0 / sizeLod;
  359. if ( i > LOD_MAX - LOD_MIN ) {
  360. sigma = EXTRA_LOD_SIGMA[ i - LOD_MAX + LOD_MIN - 1 ];
  361. } else if ( i == 0 ) {
  362. sigma = 0;
  363. }
  364. _sigmas.push( sigma );
  365. const texelSize = 1.0 / ( sizeLod - 1 );
  366. const min = - texelSize / 2;
  367. const max = 1 + texelSize / 2;
  368. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  369. const cubeFaces = 6;
  370. const vertices = 6;
  371. const positionSize = 3;
  372. const uvSize = 2;
  373. const faceIndexSize = 1;
  374. const position = new Float32Array( positionSize * vertices * cubeFaces );
  375. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  376. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  377. for ( let face = 0; face < cubeFaces; face ++ ) {
  378. const x = ( face % 3 ) * 2 / 3 - 1;
  379. const y = face > 2 ? 0 : - 1;
  380. const coordinates = [
  381. x, y, 0,
  382. x + 2 / 3, y, 0,
  383. x + 2 / 3, y + 1, 0,
  384. x, y, 0,
  385. x + 2 / 3, y + 1, 0,
  386. x, y + 1, 0
  387. ];
  388. position.set( coordinates, positionSize * vertices * face );
  389. uv.set( uv1, uvSize * vertices * face );
  390. const fill = [ face, face, face, face, face, face ];
  391. faceIndex.set( fill, faceIndexSize * vertices * face );
  392. }
  393. const planes = new BufferGeometry();
  394. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  395. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  396. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  397. _lodPlanes.push( planes );
  398. if ( lod > LOD_MIN ) {
  399. lod --;
  400. }
  401. }
  402. return { _lodPlanes, _sizeLods, _sigmas };
  403. }
  404. function _createRenderTarget( params ) {
  405. const cubeUVRenderTarget = new WebGLRenderTarget( 3 * SIZE_MAX, 3 * SIZE_MAX, params );
  406. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  407. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  408. cubeUVRenderTarget.scissorTest = true;
  409. return cubeUVRenderTarget;
  410. }
  411. function _setViewport( target, x, y, width, height ) {
  412. target.viewport.set( x, y, width, height );
  413. target.scissor.set( x, y, width, height );
  414. }
  415. function _getBlurShader( maxSamples ) {
  416. const weights = new Float32Array( maxSamples );
  417. const poleAxis = new Vector3( 0, 1, 0 );
  418. const shaderMaterial = new RawShaderMaterial( {
  419. name: 'SphericalGaussianBlur',
  420. defines: { 'n': maxSamples },
  421. uniforms: {
  422. 'envMap': { value: null },
  423. 'samples': { value: 1 },
  424. 'weights': { value: weights },
  425. 'latitudinal': { value: false },
  426. 'dTheta': { value: 0 },
  427. 'mipInt': { value: 0 },
  428. 'poleAxis': { value: poleAxis }
  429. },
  430. vertexShader: _getCommonVertexShader(),
  431. fragmentShader: /* glsl */`
  432. precision mediump float;
  433. precision mediump int;
  434. varying vec3 vOutputDirection;
  435. uniform sampler2D envMap;
  436. uniform int samples;
  437. uniform float weights[ n ];
  438. uniform bool latitudinal;
  439. uniform float dTheta;
  440. uniform float mipInt;
  441. uniform vec3 poleAxis;
  442. #define ENVMAP_TYPE_CUBE_UV
  443. #include <cube_uv_reflection_fragment>
  444. vec3 getSample( float theta, vec3 axis ) {
  445. float cosTheta = cos( theta );
  446. // Rodrigues' axis-angle rotation
  447. vec3 sampleDirection = vOutputDirection * cosTheta
  448. + cross( axis, vOutputDirection ) * sin( theta )
  449. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  450. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  451. }
  452. void main() {
  453. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  454. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  455. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  456. }
  457. axis = normalize( axis );
  458. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  459. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  460. for ( int i = 1; i < n; i++ ) {
  461. if ( i >= samples ) {
  462. break;
  463. }
  464. float theta = dTheta * float( i );
  465. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  466. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  467. }
  468. }
  469. `,
  470. blending: NoBlending,
  471. depthTest: false,
  472. depthWrite: false
  473. } );
  474. return shaderMaterial;
  475. }
  476. function _getEquirectShader() {
  477. const texelSize = new Vector2( 1, 1 );
  478. const shaderMaterial = new RawShaderMaterial( {
  479. name: 'EquirectangularToCubeUV',
  480. uniforms: {
  481. 'envMap': { value: null },
  482. 'texelSize': { value: texelSize }
  483. },
  484. vertexShader: _getCommonVertexShader(),
  485. fragmentShader: /* glsl */`
  486. precision mediump float;
  487. precision mediump int;
  488. varying vec3 vOutputDirection;
  489. uniform sampler2D envMap;
  490. uniform vec2 texelSize;
  491. #include <common>
  492. void main() {
  493. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  494. vec3 outputDirection = normalize( vOutputDirection );
  495. vec2 uv = equirectUv( outputDirection );
  496. vec2 f = fract( uv / texelSize - 0.5 );
  497. uv -= f * texelSize;
  498. vec3 tl = texture2D ( envMap, uv ).rgb;
  499. uv.x += texelSize.x;
  500. vec3 tr = texture2D ( envMap, uv ).rgb;
  501. uv.y += texelSize.y;
  502. vec3 br = texture2D ( envMap, uv ).rgb;
  503. uv.x -= texelSize.x;
  504. vec3 bl = texture2D ( envMap, uv ).rgb;
  505. vec3 tm = mix( tl, tr, f.x );
  506. vec3 bm = mix( bl, br, f.x );
  507. gl_FragColor.rgb = mix( tm, bm, f.y );
  508. }
  509. `,
  510. blending: NoBlending,
  511. depthTest: false,
  512. depthWrite: false
  513. } );
  514. return shaderMaterial;
  515. }
  516. function _getCubemapShader() {
  517. const shaderMaterial = new RawShaderMaterial( {
  518. name: 'CubemapToCubeUV',
  519. uniforms: {
  520. 'envMap': { value: null }
  521. },
  522. vertexShader: _getCommonVertexShader(),
  523. fragmentShader: /* glsl */`
  524. precision mediump float;
  525. precision mediump int;
  526. varying vec3 vOutputDirection;
  527. uniform samplerCube envMap;
  528. void main() {
  529. gl_FragColor = textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) );
  530. }
  531. `,
  532. blending: NoBlending,
  533. depthTest: false,
  534. depthWrite: false
  535. } );
  536. return shaderMaterial;
  537. }
  538. function _getCommonVertexShader() {
  539. return /* glsl */`
  540. precision mediump float;
  541. precision mediump int;
  542. attribute vec3 position;
  543. attribute vec2 uv;
  544. attribute float faceIndex;
  545. varying vec3 vOutputDirection;
  546. // RH coordinate system; PMREM face-indexing convention
  547. vec3 getDirection( vec2 uv, float face ) {
  548. uv = 2.0 * uv - 1.0;
  549. vec3 direction = vec3( uv, 1.0 );
  550. if ( face == 0.0 ) {
  551. direction = direction.zyx; // ( 1, v, u ) pos x
  552. } else if ( face == 1.0 ) {
  553. direction = direction.xzy;
  554. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  555. } else if ( face == 2.0 ) {
  556. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  557. } else if ( face == 3.0 ) {
  558. direction = direction.zyx;
  559. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  560. } else if ( face == 4.0 ) {
  561. direction = direction.xzy;
  562. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  563. } else if ( face == 5.0 ) {
  564. direction.z *= -1.0; // ( u, v, -1 ) neg z
  565. }
  566. return direction;
  567. }
  568. void main() {
  569. vOutputDirection = getDirection( uv, faceIndex );
  570. gl_Position = vec4( position, 1.0 );
  571. }
  572. `;
  573. }
  574. export { PMREMGenerator };