PMREMGenerator.js 24 KB

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