PMREMGenerator.js 24 KB

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