PMREMGenerator.js 23 KB

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