Lensflare.js 11 KB

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