Lensflare.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. import {
  2. AdditiveBlending,
  3. Box2,
  4. BufferGeometry,
  5. Color,
  6. FramebufferTexture,
  7. InterleavedBuffer,
  8. InterleavedBufferAttribute,
  9. Mesh,
  10. MeshBasicMaterial,
  11. RawShaderMaterial,
  12. UnsignedByteType,
  13. Vector2,
  14. Vector3,
  15. Vector4
  16. } from 'three';
  17. /**
  18. * Creates a simulated lens flare that tracks a light.
  19. *
  20. * Note that this class can only be used with {@link WebGLRenderer}.
  21. * When using {@link WebGPURenderer}, use {@link LensflareMesh}.
  22. *
  23. * ```js
  24. * const light = new THREE.PointLight( 0xffffff, 1.5, 2000 );
  25. *
  26. * const lensflare = new Lensflare();
  27. * lensflare.addElement( new LensflareElement( textureFlare0, 512, 0 ) );
  28. * lensflare.addElement( new LensflareElement( textureFlare1, 512, 0 ) );
  29. * lensflare.addElement( new LensflareElement( textureFlare2, 60, 0.6 ) );
  30. *
  31. * light.add( lensflare );
  32. * ```
  33. *
  34. * @augments Mesh
  35. */
  36. class Lensflare extends Mesh {
  37. /**
  38. * Constructs a new lensflare.
  39. */
  40. constructor() {
  41. super( Lensflare.Geometry, new MeshBasicMaterial( { opacity: 0, transparent: true } ) );
  42. /**
  43. * This flag can be used for type testing.
  44. *
  45. * @type {boolean}
  46. * @readonly
  47. * @default true
  48. */
  49. this.isLensflare = true;
  50. this.type = 'Lensflare';
  51. /**
  52. * Overwritten to disable view-frustum culling by default.
  53. *
  54. * @type {boolean}
  55. * @default false
  56. */
  57. this.frustumCulled = false;
  58. /**
  59. * Overwritten to make sure lensflares a rendered last.
  60. *
  61. * @type {number}
  62. * @default Infinity
  63. */
  64. this.renderOrder = Infinity;
  65. //
  66. const positionScreen = new Vector3();
  67. const positionView = new Vector3();
  68. // textures
  69. const tempMap = new FramebufferTexture( 16, 16 );
  70. const occlusionMap = new FramebufferTexture( 16, 16 );
  71. let currentType = UnsignedByteType;
  72. // material
  73. const geometry = Lensflare.Geometry;
  74. const material1a = new RawShaderMaterial( {
  75. uniforms: {
  76. 'scale': { value: null },
  77. 'screenPosition': { value: null }
  78. },
  79. vertexShader: /* glsl */`
  80. precision highp float;
  81. uniform vec3 screenPosition;
  82. uniform vec2 scale;
  83. attribute vec3 position;
  84. void main() {
  85. gl_Position = vec4( position.xy * scale + screenPosition.xy, screenPosition.z, 1.0 );
  86. }`,
  87. fragmentShader: /* glsl */`
  88. precision highp float;
  89. void main() {
  90. gl_FragColor = vec4( 1.0, 0.0, 1.0, 1.0 );
  91. }`,
  92. depthTest: true,
  93. depthWrite: false,
  94. transparent: false
  95. } );
  96. const material1b = new RawShaderMaterial( {
  97. uniforms: {
  98. 'map': { value: tempMap },
  99. 'scale': { value: null },
  100. 'screenPosition': { value: null }
  101. },
  102. vertexShader: /* glsl */`
  103. precision highp float;
  104. uniform vec3 screenPosition;
  105. uniform vec2 scale;
  106. attribute vec3 position;
  107. attribute vec2 uv;
  108. varying vec2 vUV;
  109. void main() {
  110. vUV = uv;
  111. gl_Position = vec4( position.xy * scale + screenPosition.xy, screenPosition.z, 1.0 );
  112. }`,
  113. fragmentShader: /* glsl */`
  114. precision highp float;
  115. uniform sampler2D map;
  116. varying vec2 vUV;
  117. void main() {
  118. gl_FragColor = texture2D( map, vUV );
  119. }`,
  120. depthTest: false,
  121. depthWrite: false,
  122. transparent: false
  123. } );
  124. // the following object is used for occlusionMap generation
  125. const mesh1 = new Mesh( geometry, material1a );
  126. //
  127. const elements = [];
  128. const shader = LensflareElement.Shader;
  129. const material2 = new RawShaderMaterial( {
  130. name: shader.name,
  131. uniforms: {
  132. 'map': { value: null },
  133. 'occlusionMap': { value: occlusionMap },
  134. 'color': { value: new Color( 0xffffff ) },
  135. 'scale': { value: new Vector2() },
  136. 'screenPosition': { value: new Vector3() }
  137. },
  138. vertexShader: shader.vertexShader,
  139. fragmentShader: shader.fragmentShader,
  140. blending: AdditiveBlending,
  141. transparent: true,
  142. depthWrite: false
  143. } );
  144. const mesh2 = new Mesh( geometry, material2 );
  145. /**
  146. * Adds the given lensflare element to this instance.
  147. *
  148. * @param {LensflareElement} element - The element to add.
  149. */
  150. this.addElement = function ( element ) {
  151. elements.push( element );
  152. };
  153. //
  154. const scale = new Vector2();
  155. const screenPositionPixels = new Vector2();
  156. const validArea = new Box2();
  157. const viewport = new Vector4();
  158. this.onBeforeRender = function ( renderer, scene, camera ) {
  159. renderer.getCurrentViewport( viewport );
  160. const renderTarget = renderer.getRenderTarget();
  161. const type = ( renderTarget !== null ) ? renderTarget.texture.type : UnsignedByteType;
  162. if ( currentType !== type ) {
  163. tempMap.dispose();
  164. occlusionMap.dispose();
  165. tempMap.type = occlusionMap.type = type;
  166. currentType = type;
  167. }
  168. const invAspect = viewport.w / viewport.z;
  169. const halfViewportWidth = viewport.z / 2.0;
  170. const halfViewportHeight = viewport.w / 2.0;
  171. let size = 16 / viewport.w;
  172. scale.set( size * invAspect, size );
  173. validArea.min.set( viewport.x, viewport.y );
  174. validArea.max.set( viewport.x + ( viewport.z - 16 ), viewport.y + ( viewport.w - 16 ) );
  175. // calculate position in screen space
  176. positionView.setFromMatrixPosition( this.matrixWorld );
  177. positionView.applyMatrix4( camera.matrixWorldInverse );
  178. if ( positionView.z > 0 ) return; // lensflare is behind the camera
  179. positionScreen.copy( positionView ).applyMatrix4( camera.projectionMatrix );
  180. // horizontal and vertical coordinate of the lower left corner of the pixels to copy
  181. screenPositionPixels.x = viewport.x + ( positionScreen.x * halfViewportWidth ) + halfViewportWidth - 8;
  182. screenPositionPixels.y = viewport.y + ( positionScreen.y * halfViewportHeight ) + halfViewportHeight - 8;
  183. // screen cull
  184. if ( validArea.containsPoint( screenPositionPixels ) ) {
  185. // save current RGB to temp texture
  186. renderer.copyFramebufferToTexture( tempMap, screenPositionPixels );
  187. // render pink quad
  188. let uniforms = material1a.uniforms;
  189. uniforms[ 'scale' ].value = scale;
  190. uniforms[ 'screenPosition' ].value = positionScreen;
  191. renderer.renderBufferDirect( camera, null, geometry, material1a, mesh1, null );
  192. // copy result to occlusionMap
  193. renderer.copyFramebufferToTexture( occlusionMap, screenPositionPixels );
  194. // restore graphics
  195. uniforms = material1b.uniforms;
  196. uniforms[ 'scale' ].value = scale;
  197. uniforms[ 'screenPosition' ].value = positionScreen;
  198. renderer.renderBufferDirect( camera, null, geometry, material1b, mesh1, null );
  199. // render elements
  200. const vecX = - positionScreen.x * 2;
  201. const vecY = - positionScreen.y * 2;
  202. for ( let i = 0, l = elements.length; i < l; i ++ ) {
  203. const element = elements[ i ];
  204. const uniforms = material2.uniforms;
  205. uniforms[ 'color' ].value.copy( element.color );
  206. uniforms[ 'map' ].value = element.texture;
  207. uniforms[ 'screenPosition' ].value.x = positionScreen.x + vecX * element.distance;
  208. uniforms[ 'screenPosition' ].value.y = positionScreen.y + vecY * element.distance;
  209. size = element.size / viewport.w;
  210. const invAspect = viewport.w / viewport.z;
  211. uniforms[ 'scale' ].value.set( size * invAspect, size );
  212. material2.uniformsNeedUpdate = true;
  213. renderer.renderBufferDirect( camera, null, geometry, material2, mesh2, null );
  214. }
  215. }
  216. };
  217. /**
  218. * Frees the GPU-related resources allocated by this instance. Call this
  219. * method whenever this instance is no longer used in your app.
  220. */
  221. this.dispose = function () {
  222. material1a.dispose();
  223. material1b.dispose();
  224. material2.dispose();
  225. tempMap.dispose();
  226. occlusionMap.dispose();
  227. for ( let i = 0, l = elements.length; i < l; i ++ ) {
  228. elements[ i ].texture.dispose();
  229. }
  230. };
  231. }
  232. }
  233. /**
  234. * Represents a single flare that can be added to a {@link Lensflare} container.
  235. */
  236. class LensflareElement {
  237. /**
  238. * Constructs a new lensflare element.
  239. *
  240. * @param {Texture} texture - The flare's texture.
  241. * @param {number} [size=1] - The size in pixels.
  242. * @param {number} [distance=0] - The normalized distance (`[0,1]`) from the light source.
  243. * A value of `0` means the flare is located at light source.
  244. * @param {Color} [color] - The flare's color
  245. */
  246. constructor( texture, size = 1, distance = 0, color = new Color( 0xffffff ) ) {
  247. /**
  248. * The flare's texture.
  249. *
  250. * @type {Texture}
  251. */
  252. this.texture = texture;
  253. /**
  254. * The size in pixels.
  255. *
  256. * @type {number}
  257. * @default 1
  258. */
  259. this.size = size;
  260. /**
  261. * The normalized distance (`[0,1]`) from the light source.
  262. * A value of `0` means the flare is located at light source.
  263. *
  264. * @type {number}
  265. * @default 0
  266. */
  267. this.distance = distance;
  268. /**
  269. * The flare's color
  270. *
  271. * @type {Color}
  272. * @default (1,1,1)
  273. */
  274. this.color = color;
  275. }
  276. }
  277. LensflareElement.Shader = {
  278. name: 'LensflareElementShader',
  279. uniforms: {
  280. 'map': { value: null },
  281. 'occlusionMap': { value: null },
  282. 'color': { value: null },
  283. 'scale': { value: null },
  284. 'screenPosition': { value: null }
  285. },
  286. vertexShader: /* glsl */`
  287. precision highp float;
  288. uniform vec3 screenPosition;
  289. uniform vec2 scale;
  290. uniform sampler2D occlusionMap;
  291. attribute vec3 position;
  292. attribute vec2 uv;
  293. varying vec2 vUV;
  294. varying float vVisibility;
  295. void main() {
  296. vUV = uv;
  297. vec2 pos = position.xy;
  298. vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );
  299. visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );
  300. visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );
  301. visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );
  302. visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );
  303. visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );
  304. visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );
  305. visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );
  306. visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );
  307. vVisibility = visibility.r / 9.0;
  308. vVisibility *= 1.0 - visibility.g / 9.0;
  309. vVisibility *= visibility.b / 9.0;
  310. gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );
  311. }`,
  312. fragmentShader: /* glsl */`
  313. precision highp float;
  314. uniform sampler2D map;
  315. uniform vec3 color;
  316. varying vec2 vUV;
  317. varying float vVisibility;
  318. void main() {
  319. vec4 texture = texture2D( map, vUV );
  320. texture.a *= vVisibility;
  321. gl_FragColor = texture;
  322. gl_FragColor.rgb *= color;
  323. }`
  324. };
  325. Lensflare.Geometry = ( function () {
  326. const geometry = new BufferGeometry();
  327. const float32Array = new Float32Array( [
  328. - 1, - 1, 0, 0, 0,
  329. 1, - 1, 0, 1, 0,
  330. 1, 1, 0, 1, 1,
  331. - 1, 1, 0, 0, 1
  332. ] );
  333. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  334. geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  335. geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  336. geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  337. return geometry;
  338. } )();
  339. export { Lensflare, LensflareElement };
粤ICP备19079148号