├── static ├── .gitkeep ├── cover.jpg ├── background.exr ├── lensDirtTexture.png ├── sphere-transformed.glb └── digital_painting_golden_hour_sunset.jpg ├── .gitignore ├── package.json ├── vite.config.js ├── src ├── style.css ├── index.html ├── script.js └── LensFlare.js ├── readme.md └── LICENSE /static/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .vercel 3 | -------------------------------------------------------------------------------- /static/cover.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ektogamat/lensflare-threejs-vanilla/HEAD/static/cover.jpg -------------------------------------------------------------------------------- /static/background.exr: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ektogamat/lensflare-threejs-vanilla/HEAD/static/background.exr -------------------------------------------------------------------------------- /static/lensDirtTexture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ektogamat/lensflare-threejs-vanilla/HEAD/static/lensDirtTexture.png -------------------------------------------------------------------------------- /static/sphere-transformed.glb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ektogamat/lensflare-threejs-vanilla/HEAD/static/sphere-transformed.glb -------------------------------------------------------------------------------- /static/digital_painting_golden_hour_sunset.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ektogamat/lensflare-threejs-vanilla/HEAD/static/digital_painting_golden_hour_sunset.jpg -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "threejs-journey-exercise", 3 | "private": true, 4 | "version": "0.0.0", 5 | "type": "module", 6 | "scripts": { 7 | "dev": "vite", 8 | "build": "vite build", 9 | "deploy": "vercel --prod" 10 | }, 11 | "devDependencies": { 12 | "vite": "^4.3.9" 13 | }, 14 | "dependencies": { 15 | "lil-gui": "^0.18.1", 16 | "maath": "^0.7.0", 17 | "three": "^0.153.0", 18 | "vercel": "^31.0.4" 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /vite.config.js: -------------------------------------------------------------------------------- 1 | const isCodeSandbox = 'SANDBOX_URL' in process.env || 'CODESANDBOX_HOST' in process.env 2 | 3 | export default { 4 | root: 'src/', 5 | publicDir: '../static/', 6 | base: './', 7 | server: 8 | { 9 | host: true, 10 | open: !isCodeSandbox // Open if it's not a CodeSandbox 11 | }, 12 | build: 13 | { 14 | outDir: '../dist', 15 | emptyOutDir: true, 16 | sourcemap: true 17 | } 18 | } -------------------------------------------------------------------------------- /src/style.css: -------------------------------------------------------------------------------- 1 | @import url('https://fonts.googleapis.com/css2?family=Bebas+Neue&display=swap'); 2 | * { 3 | margin: 0; 4 | padding: 0; 5 | } 6 | 7 | html, 8 | body { 9 | overflow: hidden; 10 | user-select: none; 11 | font-family: 'Bebas Neue', sans-serif; 12 | } 13 | 14 | .webgl { 15 | position: fixed; 16 | top: 0; 17 | left: 0; 18 | outline: none; 19 | } 20 | 21 | .container { 22 | position: absolute; 23 | top: 80%; 24 | left: 50%; 25 | z-index: 1; 26 | text-align: center; 27 | pointer-events: none; 28 | transform: translate(-50%, -50%); 29 | width: 100%; 30 | line-height: 6em; 31 | color: rgba(255, 255, 255, 0.754); 32 | } 33 | 34 | h1 { 35 | font-size: 12vw; 36 | } 37 | 38 | p { 39 | font-size: 3vw; 40 | } 41 | 42 | a, 43 | small { 44 | color: rgba(255, 255, 255, 0.492); 45 | cursor: pointer; 46 | pointer-events: all; 47 | } 48 | -------------------------------------------------------------------------------- /src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Lens Flare Vanilla Threejs - By Anderson Mancini 7 | 11 | 12 | 13 | 14 | 18 | 22 | 23 | 24 | 25 | 26 | 27 | 31 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 |
46 |

LENS FLARE

47 |

FOR VANILLA THREEJS

48 | Created with 💛 by Anderson Mancini.DEV 49 |
50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # Lens Flare for Vanilla Threejs 2 | 3 |

by Anderson Mancini

4 | 5 | Lens Flare adds the optical aberration caused by the dispersion of light entering the lens through its edges. This one doesn't use any post-processing pipeline and it is very easy to use and customize. 6 | 7 | [![screenshot](/static/cover.jpg)](https://lensflare-threejs-vanilla.vercel.app/) 8 | 9 | [See the demo here](https://lensflare-threejs-vanilla.vercel.app/) 10 | 11 | [Check a simple Code Sandbox implementation here](https://codesandbox.io/s/lens-flare-vanilla-threejs-pt4fwr) 12 | 13 | # HOW TO USE? 14 | 15 | #### 1. Download the files component and save it on your project 16 | 17 | [Download the Lens Flare source code](https://gist.githubusercontent.com/ektogamat/23e31dc891bb2859cbe0e89b46e288de/raw/0dc29630f7d841920b2ddb671c34215a052062f0/LensFlare.js) and save into your project 18 | 19 | #### 2. Import the component 20 | 21 | ```js 22 | import { LensFlareEffect, LensFlareParams } from './LensFlare' 23 | ``` 24 | 25 | Then add the LensFlare to your Scene 26 | 27 | ```js 28 | const lensFlareEffect = LensFlareEffect() 29 | scene.add(lensFlareEffect) 30 | ``` 31 | 32 | That's all you need ✨ 33 | 34 | --- 35 | 36 | ### Ignoring occlusion on some objects 37 | 38 | To disable the occlusion effect, simply add `userData={{ lensflare: 'no-occlusion' }}` to your object/mesh. This feature is particularly useful for creating realistic skyboxes in demos. By utilizing this setting, the internal raycaster of Lens Flare will exclude the designated object/mesh from occlusion calculations. 39 | 40 | ### Debud interface 41 | 42 | You can add this to your project to have a debug interface to change the parameters. 43 | 44 | ```js 45 | import * as dat from 'lil-gui' 46 | ``` 47 | 48 | ```js 49 | // Debug Lens Flare 50 | const gui = new dat.GUI() 51 | gui.add(lensFlareEffect.material.uniforms.enabled, 'value').name('Enabled?') 52 | gui.add(lensFlareEffect.material.uniforms.followMouse, 'value').name('Follow Mouse?') 53 | gui.add(lensFlareEffect.material.uniforms.starPoints, 'value').name('starPoints').min(0).max(9) 54 | gui.add(lensFlareEffect.material.uniforms.glareSize, 'value').name('glareSize').min(0).max(2) 55 | gui.add(lensFlareEffect.material.uniforms.flareSize, 'value').name('flareSize').min(0).max(0.1).step(0.001) 56 | gui.add(lensFlareEffect.material.uniforms.flareSpeed, 'value').name('flareSpeed').min(0).max(1).step(0.01) 57 | gui.add(lensFlareEffect.material.uniforms.flareShape, 'value').name('flareShape').min(0).max(2).step(0.01) 58 | gui.add(lensFlareEffect.material.uniforms.haloScale, 'value').name('haloScale').min(-0.5).max(1).step(0.01) 59 | gui.add(LensFlareParams, 'opacity').name('opacity').min(0).max(1).step(0.01) 60 | gui.add(lensFlareEffect.material.uniforms.ghostScale, 'value').name('ghostScale').min(0).max(2).step(0.01) 61 | gui.add(lensFlareEffect.material.uniforms.animated, 'value').name('animated') 62 | gui.add(lensFlareEffect.material.uniforms.anamorphic, 'value').name('anamorphic') 63 | gui.add(lensFlareEffect.material.uniforms.secondaryGhosts, 'value').name('secondaryGhosts') 64 | gui.add(lensFlareEffect.material.uniforms.starBurst, 'value').name('starBurst') 65 | gui.add(lensFlareEffect.material.uniforms.aditionalStreaks, 'value').name('aditionalStreaks') 66 | gui.close() 67 | ``` 68 | 69 | ### Improving performance 70 | 71 | ⚠️ The `StarBurst` option is very intense for some GPU's to compute. If you have any issues with the performance, you can disable it. 72 | 73 | ### Compatibility 74 | 75 | `Lens Flare` is compatible with all modern browsers that support WebGL 2.0 (WebGL 1 is not supported), using three.js version r153 or later is recommended. 76 | 77 | ### Getting Started using this demo project 78 | 79 | Download and install Node.js on your computer (https://nodejs.org/en/download/). 80 | 81 | Then, open VSCODE, drag the project folder to it. Open VSCODE terminal and install dependencies (you need to do this only in the first time) 82 | 83 | ```shell 84 | npm install 85 | ``` 86 | 87 | Run this command in your terminal to open a local server at localhost:3000 88 | 89 | ```shell 90 | npm run dev 91 | ``` 92 | 93 | ### License 94 | 95 | A CC0 license is used for this project. You can do whatever you want with it, no attribution is required. However, if you do use it, I'd love to hear about it! 96 | 97 | ### Can you leave a star please? 98 | 99 | I genuinely appreciate your support! If you're willing to show your appreciation, you can give me a star on GitHub 🎉 or consider buying a coffee to support my development at https://www.buymeacoffee.com/andersonmancini. The funds received will be utilized to create more valuable content about Three.js and invest in acquiring new courses. Thank you for your consideration! 100 | 101 | ### Credits 102 | 103 | Hard to remember everything I read to achieve this, but here's a list of resources that have been helpful to me: 104 | 105 | - https://www.shadertoy.com/view/4sK3W3 106 | - https://www.shadertoy.com/view/4sX3Rs 107 | - https://www.shadertoy.com/view/dllSRX 108 | - https://www.shadertoy.com/view/Xlc3D2 109 | - https://www.shadertoy.com/view/XtKfRV 110 | - https://blog.maximeheckel.com/posts/the-study-of-shaders-with-react-three-fiber/ 111 | - https://skybox.blockadelabs.com/ 112 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Creative Commons Legal Code 2 | 3 | CC0 1.0 Universal 4 | 5 | CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE 6 | LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN 7 | ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS 8 | INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES 9 | REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS 10 | PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM 11 | THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED 12 | HEREUNDER. 13 | 14 | Statement of Purpose 15 | 16 | The laws of most jurisdictions throughout the world automatically confer 17 | exclusive Copyright and Related Rights (defined below) upon the creator 18 | and subsequent owner(s) (each and all, an "owner") of an original work of 19 | authorship and/or a database (each, a "Work"). 20 | 21 | Certain owners wish to permanently relinquish those rights to a Work for 22 | the purpose of contributing to a commons of creative, cultural and 23 | scientific works ("Commons") that the public can reliably and without fear 24 | of later claims of infringement build upon, modify, incorporate in other 25 | works, reuse and redistribute as freely as possible in any form whatsoever 26 | and for any purposes, including without limitation commercial purposes. 27 | These owners may contribute to the Commons to promote the ideal of a free 28 | culture and the further production of creative, cultural and scientific 29 | works, or to gain reputation or greater distribution for their Work in 30 | part through the use and efforts of others. 31 | 32 | For these and/or other purposes and motivations, and without any 33 | expectation of additional consideration or compensation, the person 34 | associating CC0 with a Work (the "Affirmer"), to the extent that he or she 35 | is an owner of Copyright and Related Rights in the Work, voluntarily 36 | elects to apply CC0 to the Work and publicly distribute the Work under its 37 | terms, with knowledge of his or her Copyright and Related Rights in the 38 | Work and the meaning and intended legal effect of CC0 on those rights. 39 | 40 | 1. Copyright and Related Rights. A Work made available under CC0 may be 41 | protected by copyright and related or neighboring rights ("Copyright and 42 | Related Rights"). Copyright and Related Rights include, but are not 43 | limited to, the following: 44 | 45 | i. the right to reproduce, adapt, distribute, perform, display, 46 | communicate, and translate a Work; 47 | ii. moral rights retained by the original author(s) and/or performer(s); 48 | iii. publicity and privacy rights pertaining to a person's image or 49 | likeness depicted in a Work; 50 | iv. rights protecting against unfair competition in regards to a Work, 51 | subject to the limitations in paragraph 4(a), below; 52 | v. rights protecting the extraction, dissemination, use and reuse of data 53 | in a Work; 54 | vi. database rights (such as those arising under Directive 96/9/EC of the 55 | European Parliament and of the Council of 11 March 1996 on the legal 56 | protection of databases, and under any national implementation 57 | thereof, including any amended or successor version of such 58 | directive); and 59 | vii. other similar, equivalent or corresponding rights throughout the 60 | world based on applicable law or treaty, and any national 61 | implementations thereof. 62 | 63 | 2. Waiver. To the greatest extent permitted by, but not in contravention 64 | of, applicable law, Affirmer hereby overtly, fully, permanently, 65 | irrevocably and unconditionally waives, abandons, and surrenders all of 66 | Affirmer's Copyright and Related Rights and associated claims and causes 67 | of action, whether now known or unknown (including existing as well as 68 | future claims and causes of action), in the Work (i) in all territories 69 | worldwide, (ii) for the maximum duration provided by applicable law or 70 | treaty (including future time extensions), (iii) in any current or future 71 | medium and for any number of copies, and (iv) for any purpose whatsoever, 72 | including without limitation commercial, advertising or promotional 73 | purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each 74 | member of the public at large and to the detriment of Affirmer's heirs and 75 | successors, fully intending that such Waiver shall not be subject to 76 | revocation, rescission, cancellation, termination, or any other legal or 77 | equitable action to disrupt the quiet enjoyment of the Work by the public 78 | as contemplated by Affirmer's express Statement of Purpose. 79 | 80 | 3. Public License Fallback. Should any part of the Waiver for any reason 81 | be judged legally invalid or ineffective under applicable law, then the 82 | Waiver shall be preserved to the maximum extent permitted taking into 83 | account Affirmer's express Statement of Purpose. In addition, to the 84 | extent the Waiver is so judged Affirmer hereby grants to each affected 85 | person a royalty-free, non transferable, non sublicensable, non exclusive, 86 | irrevocable and unconditional license to exercise Affirmer's Copyright and 87 | Related Rights in the Work (i) in all territories worldwide, (ii) for the 88 | maximum duration provided by applicable law or treaty (including future 89 | time extensions), (iii) in any current or future medium and for any number 90 | of copies, and (iv) for any purpose whatsoever, including without 91 | limitation commercial, advertising or promotional purposes (the 92 | "License"). The License shall be deemed effective as of the date CC0 was 93 | applied by Affirmer to the Work. Should any part of the License for any 94 | reason be judged legally invalid or ineffective under applicable law, such 95 | partial invalidity or ineffectiveness shall not invalidate the remainder 96 | of the License, and in such case Affirmer hereby affirms that he or she 97 | will not (i) exercise any of his or her remaining Copyright and Related 98 | Rights in the Work or (ii) assert any associated claims and causes of 99 | action with respect to the Work, in either case contrary to Affirmer's 100 | express Statement of Purpose. 101 | 102 | 4. Limitations and Disclaimers. 103 | 104 | a. No trademark or patent rights held by Affirmer are waived, abandoned, 105 | surrendered, licensed or otherwise affected by this document. 106 | b. Affirmer offers the Work as-is and makes no representations or 107 | warranties of any kind concerning the Work, express, implied, 108 | statutory or otherwise, including without limitation warranties of 109 | title, merchantability, fitness for a particular purpose, non 110 | infringement, or the absence of latent or other defects, accuracy, or 111 | the present or absence of errors, whether or not discoverable, all to 112 | the greatest extent permissible under applicable law. 113 | c. Affirmer disclaims responsibility for clearing rights of other persons 114 | that may apply to the Work or any use thereof, including without 115 | limitation any person's Copyright and Related Rights in the Work. 116 | Further, Affirmer disclaims responsibility for obtaining any necessary 117 | consents, permissions or other rights required for any use of the 118 | Work. 119 | d. Affirmer understands and acknowledges that Creative Commons is not a 120 | party to this document and has no duty or obligation with respect to 121 | this CC0 or use of the Work. 122 | -------------------------------------------------------------------------------- /src/script.js: -------------------------------------------------------------------------------- 1 | import * as THREE from 'three' 2 | import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js' 3 | import * as dat from 'lil-gui' 4 | import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js' 5 | import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader.js' 6 | import { EXRLoader } from 'three/examples/jsm/loaders/EXRLoader.js' 7 | import { LensFlareEffect, LensFlareParams } from './LensFlare' 8 | 9 | const dracoLoader = new DRACOLoader() 10 | const loader = new GLTFLoader() 11 | dracoLoader.setDecoderPath('https://www.gstatic.com/draco/v1/decoders/') 12 | dracoLoader.setDecoderConfig({ type: 'js' }) 13 | loader.setDRACOLoader(dracoLoader) 14 | 15 | 16 | /** 17 | * Scene 18 | */ 19 | const canvas = document.querySelector('canvas.webgl') 20 | const scene = new THREE.Scene() 21 | THREE.ColorManagement.enabled = false 22 | 23 | 24 | 25 | /** 26 | * SkyBox 27 | */ 28 | const geometry = new THREE.SphereGeometry(45, 40, 40) 29 | const texture = new THREE.TextureLoader().load('digital_painting_golden_hour_sunset.jpg') 30 | texture.flipY = true 31 | const material = new THREE.MeshBasicMaterial({ map: texture, side: THREE.BackSide, depthTest: false }) 32 | 33 | const skyBox = new THREE.Mesh(geometry, material) 34 | skyBox.userData = 'no-occlusion' 35 | scene.add(skyBox) 36 | 37 | /** 38 | * SphereTest 39 | */ 40 | let params = {enableMeshes: true} 41 | 42 | const sphereTest = new THREE.SphereGeometry(1, 40, 40) 43 | const materialTest = new THREE.MeshPhysicalMaterial({ transmission: 1, thickness: 0.3, ior: 1.64, color: 'orange', roughness: 0.2, side: THREE.DoubleSide }) 44 | const spereTestMesh = new THREE.Mesh(sphereTest, materialTest) 45 | materialTest.envMapIntensity = 3 46 | spereTestMesh.position.x = 4.5 47 | scene.add(spereTestMesh) 48 | 49 | /** 50 | * SphereTestMetal 51 | */ 52 | const sphereTestMetal = new THREE.SphereGeometry(1, 40, 40) 53 | const materialTestMetal = new THREE.MeshPhysicalMaterial({metalness: 0.9, roughness: 0.25 }) 54 | const spereTestMeshMetal = new THREE.Mesh(sphereTestMetal, materialTestMetal) 55 | materialTest.envMapIntensity = 3 56 | spereTestMeshMetal.position.x = 8.5 57 | scene.add(spereTestMeshMetal) 58 | 59 | /** 60 | * SphereTestTransparent 61 | */ 62 | const sphereTestTransparent = new THREE.SphereGeometry(1, 40, 40) 63 | // const materialTestTransparent = new THREE.MeshPhysicalMaterial({ transmission: 0, thickness: 0.3, ior: 1.9, color: 'orange', roughness: 0.2, transparent: true, opacity: 0.2, side: THREE.DoubleSide }) 64 | // const materialTestTransparent = new THREE.MeshPhysicalMaterial({ transmission: 0.8, thickness: 0.3, ior: 1.9, color: 'orange', roughness: 0.2, transparent: true, opacity: 0.87, side: THREE.DoubleSide }) 65 | // const materialTestTransparent = new THREE.MeshPhysicalMaterial({Transparent: 0.9, roughness: 0.25 }) 66 | const materialTestTransparent = new THREE.MeshPhongMaterial({ color: '#333634', transparent: true, opacity: 0.7 }) 67 | const spereTestMeshTransparent = new THREE.Mesh(sphereTestTransparent, materialTestTransparent) 68 | materialTest.envMapIntensity = 3 69 | spereTestMeshTransparent.position.x = 6.5 70 | scene.add(spereTestMeshTransparent) 71 | 72 | /** 73 | * SphereTest 74 | */ 75 | const sphereTestDenseGlass = new THREE.SphereGeometry(1, 40, 40) 76 | const materialTestDenseGlass = new THREE.MeshPhysicalMaterial({ transmission: 0.4, thickness: 0.2, clearcoat: 0.5, ior: 1.1, color: '#1c1036', roughness: 0.2, envMapIntensity: 20, side: THREE.DoubleSide }) 77 | const spereTestMeshDenseGlass = new THREE.Mesh(sphereTestDenseGlass, materialTestDenseGlass) 78 | materialTestDenseGlass.envMapIntensity = 3 79 | spereTestMeshDenseGlass.position.x = 10.5 80 | scene.add(spereTestMeshDenseGlass) 81 | 82 | 83 | /** 84 | * ScreenResolution 85 | */ 86 | const screenRes = { 87 | width: window.innerWidth, 88 | height: window.innerHeight, 89 | } 90 | 91 | window.addEventListener('resize', () => { 92 | // Update screenRes 93 | screenRes.width = window.innerWidth 94 | screenRes.height = window.innerHeight 95 | 96 | // Update camera 97 | camera.aspect = screenRes.width / screenRes.height 98 | camera.updateProjectionMatrix() 99 | 100 | // Update renderer 101 | renderer.setSize(screenRes.width, screenRes.height) 102 | renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)) 103 | }) 104 | 105 | /** 106 | * Camera 107 | */ 108 | const camera = new THREE.PerspectiveCamera(45, screenRes.width / screenRes.height, 0.1, 1000) 109 | camera.position.z = 8.5 110 | scene.add(camera) 111 | 112 | // Controls 113 | const controls = new OrbitControls(camera, canvas) 114 | controls.enableDamping = true 115 | controls.maxDistance = 20 116 | 117 | /** 118 | * Lights 119 | */ 120 | const light = new THREE.DirectionalLight() 121 | light.intensity = 1 122 | light.position.set(-20, 20, 50) 123 | scene.add(light) 124 | 125 | const ambientLight = new THREE.AmbientLight() 126 | ambientLight.intensity = 0.9 127 | scene.add(ambientLight) 128 | 129 | /** 130 | * Renderer 131 | */ 132 | const renderer = new THREE.WebGLRenderer({ 133 | canvas: canvas, 134 | }) 135 | renderer.outputColorSpace = THREE.LinearSRGBColorSpace 136 | renderer.setSize(screenRes.width, screenRes.height) 137 | renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)) 138 | 139 | let newEnvMap 140 | 141 | new EXRLoader().load('background.exr', function (texture) { 142 | const exrCubeRenderTarget = pmremGenerator.fromEquirectangular(texture) 143 | newEnvMap = exrCubeRenderTarget ? exrCubeRenderTarget.texture : null 144 | loadObjectAndAndEnvMap() 145 | texture.dispose() 146 | }) 147 | 148 | const pmremGenerator = new THREE.PMREMGenerator(renderer) 149 | pmremGenerator.compileEquirectangularShader() 150 | 151 | function loadObjectAndAndEnvMap() { 152 | scene.environment = newEnvMap 153 | } 154 | 155 | let glassDome 156 | loader.load('sphere-transformed.glb', function (gltf) { 157 | glassDome = gltf.scene 158 | 159 | const glassDomeMaterial = glassDome.children[0].material 160 | let domeMaterial = glassDome.children[1].material 161 | domeMaterial.roughness = 0.6 162 | 163 | glassDomeMaterial.iridescence = 0.7 164 | glassDomeMaterial.iridescenceIOR = 3.46 165 | glassDomeMaterial.thickness = 0.05 166 | glassDomeMaterial.ior = 1.4 167 | glassDomeMaterial.side = THREE.DoubleSide 168 | glassDomeMaterial.roughness = 0.15 169 | glassDomeMaterial.clearcoat = 1 170 | glassDomeMaterial.metalness = 0.22 171 | 172 | glassDome.scale.set(0.7, 0.7, 0.7) 173 | 174 | scene.add(glassDome) 175 | glassDome.children[0].visible = true 176 | glassDome.children[1].visible = true 177 | }) 178 | 179 | /** 180 | * Lens Flare 181 | */ 182 | const lensFlareEffect = LensFlareEffect() 183 | scene.add(lensFlareEffect) 184 | 185 | // Debug Lens Flare 186 | const gui = new dat.GUI() 187 | gui.add(lensFlareEffect.material.uniforms.enabled, 'value').name('Enabled?') 188 | gui.add(lensFlareEffect.material.uniforms.followMouse, 'value').name('Follow Mouse?') 189 | gui.add(lensFlareEffect.material.uniforms.starPoints, 'value').name('starPoints').min(0).max(9).step(1) 190 | gui.add(lensFlareEffect.material.uniforms.glareSize, 'value').name('glareSize').min(0).max(2) 191 | gui.add(lensFlareEffect.material.uniforms.flareSize, 'value').name('flareSize').min(0).max(0.1).step(0.001) 192 | gui.add(lensFlareEffect.material.uniforms.flareSpeed, 'value').name('flareSpeed').min(0).max(1).step(0.01) 193 | gui.add(lensFlareEffect.material.uniforms.flareShape, 'value').name('flareShape').min(0).max(2).step(0.01) 194 | gui.add(lensFlareEffect.material.uniforms.haloScale, 'value').name('haloScale').min(-0.5).max(1).step(0.01) 195 | gui.add(LensFlareParams, 'opacity').name('opacity').min(0).max(1).step(0.01) 196 | gui.add(lensFlareEffect.material.uniforms.ghostScale, 'value').name('ghostScale').min(0).max(2).step(0.01) 197 | gui.add(lensFlareEffect.material.uniforms.animated, 'value').name('animated') 198 | gui.add(lensFlareEffect.material.uniforms.anamorphic, 'value').name('anamorphic') 199 | gui.add(lensFlareEffect.material.uniforms.secondaryGhosts, 'value').name('secondaryGhosts') 200 | gui.add(lensFlareEffect.material.uniforms.starBurst, 'value').name('starBurst') 201 | gui.add(lensFlareEffect.material.uniforms.aditionalStreaks, 'value').name('aditionalStreaks') 202 | 203 | // Debug Meshes (Demo scene only) 204 | gui.add(params, 'enableMeshes').name('Debug meshes (demo)?').onChange(update) 205 | function update(){ 206 | spereTestMesh.visible = params.enableMeshes 207 | spereTestMeshMetal.visible = params.enableMeshes 208 | spereTestMeshTransparent.visible = params.enableMeshes 209 | spereTestMeshDenseGlass.visible = params.enableMeshes 210 | if (glassDome){ 211 | glassDome.children[0].visible = params.enableMeshes 212 | glassDome.children[1].visible = params.enableMeshes 213 | } 214 | } 215 | update() 216 | 217 | gui.close() 218 | 219 | /** 220 | * Animate 221 | */ 222 | const clock = new THREE.Clock() 223 | const tick = () => { 224 | controls.update() 225 | 226 | renderer.render(scene, camera) 227 | 228 | if (glassDome) { 229 | glassDome.rotation.y += 0.004 230 | glassDome.rotation.x += 0.002 231 | glassDome.position.y = Math.sin(clock.getElapsedTime()) / 4.3 232 | } 233 | 234 | window.requestAnimationFrame(tick) 235 | } 236 | 237 | tick() 238 | -------------------------------------------------------------------------------- /src/LensFlare.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Lens Flare by Anderson Mancini 3 | * Based on: https://github.com/ektogamat/R3F-Ultimate-Lens-Flare 4 | */ 5 | import * as THREE from 'three' 6 | import { easing } from 'maath' 7 | export let LensFlareParams = {} 8 | 9 | /** 10 | * @param {Boolean | undefined} enabled Enable or disable the effect 11 | * @param {THREE.Vector3 | undefined} lensPosition The lens position in Vector3 format 12 | * @param {Number | undefined} opacity The opacity for this effect 13 | * @param {THREE.Color | undefined} colorGain The colorGain in RGB format 14 | * @param {Number | undefined} starPoints The integer number of star points 15 | * @param {Number | undefined} glareSize The float number of glare size 16 | * @param {Number | undefined} flareSize The float number of flare size 17 | * @param {Number | undefined} flareSpeed The float number of the flare animation speed. Set 0 to disable 18 | * @param {Number | undefined} flareShape The float number to define the flare shape. Higher number sharper 19 | * @param {Number | undefined} haloScale The float number to define the halo of startBurst scale 20 | * @param {Boolean | undefined} animated Enable or disable the flare rotation animation 21 | * @param {Boolean | undefined} anamorphic Enable or disable the anamorphic flare shape 22 | * @param {Boolean | undefined} secondaryGhosts Enable or disable the secondary ghosts 23 | * @param {Boolean | undefined} starBurst Enable or disable the star burst. Disable for better performance 24 | * @param {Number | undefined} ghostScale The float number of the ghosts scale 25 | * @param {Boolean | undefined} aditionalStreaks Enable or disable the aditional streaks 26 | * @param {Boolean | undefined} followMouse Enable or disable follow mouse lens flare 27 | */ 28 | 29 | export function LensFlareEffect( 30 | enabled, 31 | lensPosition, 32 | opacity, 33 | colorGain, 34 | starPoints, 35 | glareSize, 36 | flareSize, 37 | flareSpeed, 38 | flareShape, 39 | haloScale, 40 | animated, 41 | anamorphic, 42 | secondaryGhosts, 43 | starBurst, 44 | ghostScale, 45 | aditionalStreaks, 46 | followMouse 47 | ) { 48 | LensFlareParams = { 49 | enabled: enabled != undefined ? enabled : true, 50 | lensPosition: lensPosition != undefined ? lensPosition : new THREE.Vector3(25, 2, -40), 51 | opacity: opacity != undefined ? opacity : 0.8, 52 | colorGain: colorGain != undefined ? colorGain : new THREE.Color(95, 12, 10), 53 | starPoints: starPoints != undefined ? starPoints : 5.0, 54 | glareSize: glareSize != undefined ? glareSize : 0.55, 55 | flareSize: flareSize != undefined ? flareSize : 0.004, 56 | flareSpeed: flareSpeed != undefined ? flareSpeed : 0.4, 57 | flareShape: flareShape != undefined ? flareShape : 1.2, 58 | haloScale: haloScale != undefined ? haloScale : 0.5, 59 | animated: animated != undefined ? animated : true, 60 | anamorphic: anamorphic != undefined ? anamorphic : false, 61 | secondaryGhosts: secondaryGhosts != undefined ? secondaryGhosts : true, 62 | starBurst: starBurst != undefined ? starBurst : true, 63 | ghostScale: ghostScale != undefined ? ghostScale : 0.3, 64 | aditionalStreaks: aditionalStreaks != undefined ? aditionalStreaks : true, 65 | followMouse: followMouse != undefined ? followMouse : false, 66 | } 67 | 68 | const clock = new THREE.Clock() 69 | const screenPosition = LensFlareParams.lensPosition 70 | const viewport = new THREE.Vector4() 71 | const oldOpacity = LensFlareParams.opacity 72 | 73 | let internalOpacity = oldOpacity 74 | let flarePosition = new THREE.Vector3() 75 | const raycaster = new THREE.Raycaster() 76 | 77 | const lensFlareMaterial = new THREE.ShaderMaterial({ 78 | uniforms: { 79 | iTime: { value: 0 }, 80 | iResolution: { value: new THREE.Vector2(window.innerWidth, window.innerHeight) }, 81 | lensPosition: { value: new THREE.Vector2(0, 0) }, 82 | enabled: { value: LensFlareParams.enabled }, 83 | colorGain: { value: LensFlareParams.colorGain }, 84 | starPoints: { value: LensFlareParams.starPoints }, 85 | glareSize: { value: LensFlareParams.glareSize }, 86 | flareSize: { value: LensFlareParams.flareSize }, 87 | flareSpeed: { value: LensFlareParams.flareSpeed }, 88 | flareShape: { value: LensFlareParams.flareShape }, 89 | haloScale: { value: LensFlareParams.haloScale }, 90 | opacity: { value: internalOpacity }, 91 | animated: { value: LensFlareParams.animated }, 92 | anamorphic: { value: LensFlareParams.anamorphic }, 93 | secondaryGhosts: { value: LensFlareParams.secondaryGhosts }, 94 | starBurst: { value: LensFlareParams.starBurst }, 95 | ghostScale: { value: LensFlareParams.ghostScale }, 96 | aditionalStreaks: { value: LensFlareParams.aditionalStreaks }, 97 | followMouse: { value: LensFlareParams.followMouse }, 98 | lensDirtTexture: { value: new THREE.TextureLoader().load('https://i.ibb.co/c3x4dBy/lens-Dirt-Texture.jpg') }, 99 | }, 100 | /*GLSL */ 101 | fragmentShader: ` 102 | 103 | // Based on https://www.shadertoy.com/view/4sX3Rs 104 | uniform float iTime; 105 | uniform vec2 lensPosition; 106 | uniform vec2 iResolution; 107 | uniform vec3 colorGain; 108 | uniform float starPoints; 109 | uniform float glareSize; 110 | uniform float flareSize; 111 | uniform float flareSpeed; 112 | uniform float flareShape; 113 | uniform float haloScale; 114 | uniform float opacity; 115 | uniform bool animated; 116 | uniform bool anamorphic; 117 | uniform bool enabled; 118 | uniform bool secondaryGhosts; 119 | uniform bool starBurst; 120 | uniform float ghostScale; 121 | uniform bool aditionalStreaks; 122 | uniform sampler2D lensDirtTexture; 123 | varying vec2 vUv; 124 | 125 | float uDispersal = 0.3; 126 | float uHaloWidth = 0.6; 127 | float uDistortion = 1.5; 128 | float uBrightDark = 0.5; 129 | vec2 vTexCoord; 130 | 131 | 132 | float rand(float n){return fract(sin(n) * 43758.5453123);} 133 | 134 | float noise(float p){ 135 | float fl = floor(p); 136 | float fc = fract(p); 137 | return mix(rand(fl),rand(fl + 1.0), fc); 138 | } 139 | 140 | vec3 hsv2rgb(vec3 c) 141 | { 142 | vec4 k = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); 143 | vec3 p = abs(fract(c.xxx + k.xyz) * 6.0 - k.www); 144 | return c.z * mix(k.xxx, clamp(p - k.xxx, 0.0, 1.0), c.y); 145 | } 146 | 147 | float saturate2(float x) 148 | { 149 | return clamp(x, 0.,1.); 150 | } 151 | 152 | 153 | vec2 rotateUV(vec2 uv, float rotation) 154 | { 155 | return vec2( 156 | cos(rotation) * uv.x + sin(rotation) * uv.y, 157 | cos(rotation) * uv.y - sin(rotation) * uv.x 158 | ); 159 | } 160 | 161 | // Based on https://www.shadertoy.com/view/XtKfRV 162 | vec3 drawflare(vec2 p, float intensity, float rnd, float speed, int id) 163 | { 164 | float flarehueoffset = (1. / 32.) * float(id) * 0.1; 165 | float lingrad = distance(vec2(0.), p); 166 | float expgrad = 1. / exp(lingrad * (fract(rnd) * 0.66 + 0.33)); 167 | vec3 colgrad = hsv2rgb(vec3( fract( (expgrad * 8.) + speed * flareSpeed + flarehueoffset), pow(1.-abs(expgrad*2.-1.), 0.45), 20.0 * expgrad * intensity)); //rainbow spectrum effect 168 | 169 | float internalStarPoints; 170 | 171 | if(anamorphic){ 172 | internalStarPoints = 1.0; 173 | } else{ 174 | internalStarPoints = starPoints; 175 | } 176 | 177 | float blades = length(p * flareShape * sin(internalStarPoints * atan(p.x, p.y))); //draw 6 blades 178 | 179 | float comp = pow(1.-saturate2(blades), ( anamorphic ? 100. : 12.)); 180 | comp += saturate2(expgrad-0.9) * 3.; 181 | comp = pow(comp * expgrad, 8. + (1.-intensity) * 5.); 182 | 183 | if(flareSpeed > 0.0){ 184 | return vec3(comp) * colgrad; 185 | } else{ 186 | return vec3(comp) * flareSize * 15.; 187 | } 188 | } 189 | 190 | float dist(vec3 a, vec3 b) { return abs(a.x - b.x) + abs(a.y - b.y) + abs(a.z - b.z); } 191 | 192 | float glare(vec2 uv, vec2 pos, float size) 193 | { 194 | vec2 main; 195 | 196 | if(animated){ 197 | main = rotateUV(uv-pos, iTime * 0.1); 198 | } else{ 199 | main = uv-pos; 200 | } 201 | 202 | float ang = atan(main.y, main.x) * (anamorphic ? 1.0 : starPoints); 203 | float dist = length(main); 204 | dist = pow(dist, .9); 205 | 206 | float f0 = 1.0/(length(uv-pos)*(1.0/size*16.0)+.2); 207 | 208 | return f0+f0*(sin((ang))*.2 +.3); 209 | } 210 | 211 | //https://www.shadertoy.com/view/Xd2GR3 212 | float sdHex(vec2 p){ 213 | p = abs(p); 214 | vec2 q = vec2(p.x*2.0*0.5773503, p.y + p.x*0.5773503); 215 | return dot(step(q.xy,q.yx), 1.0-q.yx); 216 | } 217 | 218 | //fakes x^n for specular effects (k is 0-1) 219 | float fpow(float x, float k){ 220 | return x > k ? pow((x-k)/(1.0-k),2.0) : 0.0; 221 | } 222 | 223 | vec3 renderhex(vec2 uv, vec2 p, float s, vec3 col){ 224 | uv -= p; 225 | if (abs(uv.x) < 0.2*s && abs(uv.y) < 0.2*s){ 226 | return mix(vec3(0),mix(vec3(0),col,0.1 + fpow(length(uv/s),0.1)*10.0),smoothstep(0.0,0.1,sdHex(uv*20.0/s))); 227 | } 228 | return vec3(0); 229 | } 230 | 231 | vec3 LensFlare(vec2 uv, vec2 pos) 232 | { 233 | vec2 main = uv-pos; 234 | vec2 uvd = uv*(length(uv)); 235 | 236 | float ang = atan(main.x,main.y); 237 | 238 | float f0 = .3/(length(uv-pos)*16.0+1.0); 239 | 240 | f0 = f0*(sin(noise(sin(ang*3.9-(animated ? iTime : 0.0) * 0.3) * starPoints))*.2 ); 241 | 242 | float f1 = max(0.01-pow(length(uv+1.2*pos),1.9),.0)*7.0; 243 | 244 | float f2 = max(.9/(10.0+32.0*pow(length(uvd+0.99*pos),2.0)),.0)*0.35; 245 | float f22 = max(.9/(11.0+32.0*pow(length(uvd+0.85*pos),2.0)),.0)*0.23; 246 | float f23 = max(.9/(12.0+32.0*pow(length(uvd+0.95*pos),2.0)),.0)*0.6; 247 | 248 | vec2 uvx = mix(uv,uvd, 0.1); 249 | 250 | float f4 = max(0.01-pow(length(uvx+0.4*pos),2.9),.0)*4.02; 251 | float f42 = max(0.0-pow(length(uvx+0.45*pos),2.9),.0)*4.1; 252 | float f43 = max(0.01-pow(length(uvx+0.5*pos),2.9),.0)*4.6; 253 | 254 | uvx = mix(uv,uvd,-.4); 255 | 256 | float f5 = max(0.01-pow(length(uvx+0.1*pos),5.5),.0)*2.0; 257 | float f52 = max(0.01-pow(length(uvx+0.2*pos),5.5),.0)*2.0; 258 | float f53 = max(0.01-pow(length(uvx+0.1*pos),5.5),.0)*2.0; 259 | 260 | uvx = mix(uv,uvd, 2.1); 261 | 262 | float f6 = max(0.01-pow(length(uvx-0.3*pos),1.61),.0)*3.159; 263 | float f62 = max(0.01-pow(length(uvx-0.325*pos),1.614),.0)*3.14; 264 | float f63 = max(0.01-pow(length(uvx-0.389*pos),1.623),.0)*3.12; 265 | 266 | vec3 c = vec3(glare(uv,pos, glareSize)); 267 | 268 | vec2 prot; 269 | 270 | if(animated){ 271 | prot = rotateUV(uv - pos, (iTime * 0.1)); 272 | } else if(anamorphic){ 273 | prot = rotateUV(uv - pos, 1.570796); 274 | } else { 275 | prot = uv - pos; 276 | } 277 | 278 | c += drawflare(prot, (anamorphic ? flareSize * 10. : flareSize), 0.1, iTime, 1); 279 | 280 | c.r+=f1+f2+f4+f5+f6; c.g+=f1+f22+f42+f52+f62; c.b+=f1+f23+f43+f53+f63; 281 | c = c*1.3 * vec3(length(uvd)+.09); // Vignette 282 | c+=vec3(f0); 283 | 284 | return c; 285 | } 286 | 287 | vec3 cc(vec3 color, float factor,float factor2) 288 | { 289 | float w = color.x+color.y+color.z; 290 | return mix(color,vec3(w)*factor,w*factor2); 291 | } 292 | 293 | float rnd(vec2 p) 294 | { 295 | float f = fract(sin(dot(p, vec2(12.1234, 72.8392) )*45123.2)); 296 | return f; 297 | } 298 | 299 | float rnd(float w) 300 | { 301 | float f = fract(sin(w)*1000.); 302 | return f; 303 | } 304 | 305 | float regShape(vec2 p, int N) 306 | { 307 | float f; 308 | 309 | float a=atan(p.x,p.y)+.2; 310 | float b=6.28319/float(N); 311 | f=smoothstep(.5,.51, cos(floor(.5+a/b)*b-a)*length(p.xy)* 2.0 -ghostScale); 312 | 313 | return f; 314 | } 315 | 316 | // Based on https://www.shadertoy.com/view/Xlc3D2 317 | vec3 circle(vec2 p, float size, float decay, vec3 color, vec3 color2, float dist, vec2 mouse) 318 | { 319 | float l = length(p + mouse*(dist*2.))+size/2.; 320 | float l2 = length(p + mouse*(dist*4.))+size/3.; 321 | 322 | float c = max(0.04-pow(length(p + mouse*dist), size*ghostScale), 0.0)*10.; 323 | float c1 = max(0.001-pow(l-0.3, 1./40.)+sin(l*20.), 0.0)*3.; 324 | float c2 = max(0.09/pow(length(p-mouse*dist/.5)*1., .95), 0.0)/20.; 325 | float s = max(0.02-pow(regShape(p*5. + mouse*dist*5. + decay, 6) , 1.), 0.0)*1.5; 326 | 327 | color = cos(vec3(colorGain)*16. + dist/8.)*0.5+.5; 328 | vec3 f = c*color; 329 | f += c1*color; 330 | f += c2*color; 331 | f += s*color; 332 | return f; 333 | } 334 | 335 | vec4 getLensColor(float x){ 336 | return vec4(vec3(mix(mix(mix(mix(mix(mix(mix(mix(mix(mix(mix(mix(mix(mix(mix(vec3(0., 0., 0.), 337 | vec3(0., 0., 0.), smoothstep(0.0, 0.063, x)), 338 | vec3(0., 0., 0.), smoothstep(0.063, 0.125, x)), 339 | vec3(0.0, 0., 0.), smoothstep(0.125, 0.188, x)), 340 | vec3(0.188, 0.131, 0.116), smoothstep(0.188, 0.227, x)), 341 | vec3(0.31, 0.204, 0.537), smoothstep(0.227, 0.251, x)), 342 | vec3(0.192, 0.106, 0.286), smoothstep(0.251, 0.314, x)), 343 | vec3(0.102, 0.008, 0.341), smoothstep(0.314, 0.392, x)), 344 | vec3(0.086, 0.0, 0.141), smoothstep(0.392, 0.502, x)), 345 | vec3(1.0, 0.31, 0.0), smoothstep(0.502, 0.604, x)), 346 | vec3(.1, 0.1, 0.1), smoothstep(0.604, 0.643, x)), 347 | vec3(1.0, 0.929, 0.0), smoothstep(0.643, 0.761, x)), 348 | vec3(1.0, 0.086, 0.424), smoothstep(0.761, 0.847, x)), 349 | vec3(1.0, 0.49, 0.0), smoothstep(0.847, 0.89, x)), 350 | vec3(0.945, 0.275, 0.475), smoothstep(0.89, 0.941, x)), 351 | vec3(0.251, 0.275, 0.796), smoothstep(0.941, 1.0, x))), 352 | 1.0); 353 | } 354 | 355 | float dirtNoise(vec2 p){ 356 | vec2 f = fract(p); 357 | f = (f * f) * (3.0 - (2.0 * f)); 358 | float n = dot(floor(p), vec2(1.0, 157.0)); 359 | vec4 a = fract(sin(vec4(n + 0.0, n + 1.0, n + 157.0, n + 158.0)) * 43758.5453123); 360 | return mix(mix(a.x, a.y, f.x), mix(a.z, a.w, f.x), f.y); 361 | } 362 | 363 | float fbm(vec2 p){ 364 | const mat2 m = mat2(0.80, -0.60, 0.60, 0.80); 365 | float f = 0.0; 366 | f += 0.5000*dirtNoise(p); p = m*p*2.02; 367 | f += 0.2500*dirtNoise(p); p = m*p*2.03; 368 | f += 0.1250*dirtNoise(p); p = m*p*2.01; 369 | f += 0.0625*dirtNoise(p); 370 | return f/0.9375; 371 | } 372 | vec4 getLensStar(vec2 p){ 373 | vec2 pp = (p - vec2(0.5)) * 2.0; 374 | float a = atan(pp.y, pp.x); 375 | vec4 cp = vec4(sin(a * 1.0), length(pp), sin(a * 13.0), sin(a * 53.0)); 376 | float d = sin(clamp(pow(length(vec2(0.5) - p) * 0.5 + haloScale /2., 5.0), 0.0, 1.0) * 3.14159); 377 | vec3 c = vec3(d) * vec3(fbm(cp.xy * 16.0) * fbm(cp.zw * 9.0) * max(max(max(max(0.5, sin(a * 1.0)), sin(a * 3.0) * 0.8), sin(a * 7.0) * 0.8), sin(a * 9.0) * 10.6)); 378 | c *= vec3(mix(2.0, (sin(length(pp.xy) * 256.0) * 0.5) + 0.5, sin((clamp((length(pp.xy) - 0.875) / 0.1, 0.0, 1.0) + 0.0) * 2.0 * 3.14159) * 1.5) + 0.5) * 0.3275; 379 | return vec4(vec3(c * 1.0), d); 380 | } 381 | 382 | vec4 getLensDirt(vec2 p){ 383 | p.xy += vec2(fbm(p.yx * 3.0), fbm(p.yx * 2.0)) * 0.0825; 384 | vec3 o = vec3(mix(0.125, 0.25, max(max(smoothstep(0.1, 0.0, length(p - vec2(0.25))), 385 | smoothstep(0.4, 0.0, length(p - vec2(0.75)))), 386 | smoothstep(0.8, 0.0, length(p - vec2(0.875, 0.125)))))); 387 | o += vec3(max(fbm(p * 1.0) - 0.5, 0.0)) * 0.5; 388 | o += vec3(max(fbm(p * 2.0) - 0.5, 0.0)) * 0.5; 389 | o += vec3(max(fbm(p * 4.0) - 0.5, 0.0)) * 0.25; 390 | o += vec3(max(fbm(p * 8.0) - 0.75, 0.0)) * 1.0; 391 | o += vec3(max(fbm(p * 16.0) - 0.75, 0.0)) * 0.75; 392 | o += vec3(max(fbm(p * 64.0) - 0.75, 0.0)) * 0.5; 393 | return vec4(clamp(o, vec3(0.15), vec3(1.0)), 1.0); 394 | } 395 | 396 | vec4 textureLimited(sampler2D tex, vec2 texCoord){ 397 | if(((texCoord.x < 0.) || (texCoord.y < 0.)) || ((texCoord.x > 1.) || (texCoord.y > 1.))){ 398 | return vec4(0.0); 399 | }else{ 400 | return texture(tex, texCoord); 401 | } 402 | } 403 | 404 | vec4 textureDistorted(sampler2D tex, vec2 texCoord, vec2 direction, vec3 distortion) { 405 | return vec4(textureLimited(tex, (texCoord + (direction * distortion.r))).r, 406 | textureLimited(tex, (texCoord + (direction * distortion.g))).g, 407 | textureLimited(tex, (texCoord + (direction * distortion.b))).b, 408 | 1.0); 409 | } 410 | 411 | vec4 getStartBurst(){ 412 | vec2 aspectTexCoord = vec2(1.0) - (((vTexCoord - vec2(0.5)) * vec2(1.0)) + vec2(0.5)); 413 | vec2 texCoord = vec2(1.0) - vTexCoord; 414 | vec2 ghostVec = (vec2(0.5) - texCoord) * uDispersal - lensPosition; 415 | vec2 ghostVecAspectNormalized = normalize(ghostVec * vec2(1.0)) * vec2(1.0); 416 | vec2 haloVec = normalize(ghostVec) * uHaloWidth; 417 | vec2 haloVecAspectNormalized = ghostVecAspectNormalized * uHaloWidth; 418 | vec2 texelSize = vec2(1.0) / vec2(iResolution.xy); 419 | vec3 distortion = vec3(-(texelSize.x * uDistortion), 0.2, texelSize.x * uDistortion); 420 | vec4 c = vec4(0.0); 421 | for (int i = 0; i < 8; i++) { 422 | vec2 offset = texCoord + (ghostVec * float(i)); 423 | c += textureDistorted(lensDirtTexture, offset, ghostVecAspectNormalized, distortion) * pow(max(0.0, 1.0 - (length(vec2(0.5) - offset) / length(vec2(0.5)))), 10.0); 424 | } 425 | vec2 haloOffset = texCoord + haloVecAspectNormalized; 426 | return (c * getLensColor((length(vec2(0.5) - aspectTexCoord) / length(vec2(haloScale))))) + 427 | (textureDistorted(lensDirtTexture, haloOffset, ghostVecAspectNormalized, distortion) * pow(max(0.0, 1.0 - (length(vec2(0.5) - haloOffset) / length(vec2(0.5)))), 10.0)); 428 | } 429 | 430 | void main() 431 | { 432 | vec2 uv = vUv; 433 | vec2 myUV = uv -0.5; 434 | myUV.y *= iResolution.y/iResolution.x; 435 | vec2 mouse = lensPosition * 0.5; 436 | mouse.y *= iResolution.y/iResolution.x; 437 | 438 | //First LensFlarePass 439 | vec3 finalColor = LensFlare(myUV, mouse) * 20.0 * colorGain / 256.; 440 | 441 | //Aditional Streaks 442 | if(aditionalStreaks){ 443 | vec3 circColor = vec3(0.9, 0.2, 0.1); 444 | vec3 circColor2 = vec3(0.3, 0.1, 0.9); 445 | 446 | for(float i=0.;i<10.;i++){ 447 | finalColor += circle(myUV, pow(rnd(i*2000.)*2.8, .1)+1.41, 0.0, circColor+i , circColor2+i, rnd(i*20.)*3.+0.2-.5, lensPosition); 448 | } 449 | } 450 | 451 | //Alternative Ghosts 452 | if(secondaryGhosts){ 453 | vec3 altGhosts = vec3(0.1); 454 | altGhosts += renderhex(myUV, -lensPosition*0.25, ghostScale * 1.4, vec3(0.03)* colorGain); 455 | altGhosts += renderhex(myUV, lensPosition*0.25, ghostScale * 0.5, vec3(0.03)* colorGain); 456 | altGhosts += renderhex(myUV, lensPosition*0.1, ghostScale * 1.6,vec3(0.03)* colorGain); 457 | altGhosts += renderhex(myUV, lensPosition*1.8, ghostScale * 2.0, vec3(0.03)* colorGain); 458 | altGhosts += renderhex(myUV, lensPosition*1.25, ghostScale * 0.8, vec3(0.03)* colorGain); 459 | altGhosts += renderhex(myUV, -lensPosition*1.25, ghostScale * 5.0, vec3(0.03)* colorGain); 460 | 461 | //Circular ghost 462 | altGhosts += fpow(1.0 - abs(distance(lensPosition*0.8,myUV) - 0.5),0.985)*vec3(.1); 463 | altGhosts += fpow(1.0 - abs(distance(lensPosition*0.4,myUV) - 0.2),0.994)*vec3(.05); 464 | finalColor += altGhosts; 465 | } 466 | 467 | 468 | //Starburst 469 | if(starBurst){ 470 | vTexCoord = myUV + 0.5; 471 | vec4 lensMod = getLensDirt(myUV); 472 | float tooBright = 1.0 - (clamp(uBrightDark, 0.0, 0.5) * 2.0); 473 | float tooDark = clamp(uBrightDark - 0.5, 0.0, 0.5) * 2.0; 474 | lensMod += mix(lensMod, pow(lensMod * 2.0, vec4(2.0)) * 0.5, tooBright); 475 | float lensStarRotationAngle = ((myUV.x + myUV.y)) * (1.0 / 6.0); 476 | vec2 lensStarTexCoord = (mat2(cos(lensStarRotationAngle), -sin(lensStarRotationAngle), sin(lensStarRotationAngle), cos(lensStarRotationAngle)) * vTexCoord); 477 | lensMod += getLensStar(lensStarTexCoord) * 2.; 478 | 479 | finalColor += clamp((lensMod.rgb * getStartBurst().rgb ), 0.01, 1.0); 480 | } 481 | 482 | //Final composed output 483 | if(enabled){ 484 | 485 | gl_FragColor = vec4(finalColor, mix(finalColor, -vec3(.15), 0.5) * opacity); 486 | 487 | #include 488 | #include 489 | } 490 | } 491 | `, 492 | 493 | /* GLSL */ 494 | vertexShader: ` 495 | varying vec2 vUv; 496 | void main() { 497 | vUv = uv; 498 | 499 | gl_Position = vec4(position, 1.0); 500 | 501 | }`, 502 | transparent: true, 503 | depthWrite: false, 504 | depthTest: false, 505 | blending: THREE.AdditiveBlending, 506 | name: 'LensFlareShader', 507 | }) 508 | 509 | lensFlareMaterial.onBeforeRender = function (renderer, scene, camera) { 510 | const elapsedTime = clock.getElapsedTime() 511 | 512 | renderer.getCurrentViewport(viewport) 513 | lensFlareContainer.lookAt(camera) 514 | 515 | lensFlareMaterial.uniforms.iResolution.value.set(viewport.z, viewport.w) 516 | 517 | if (lensFlareMaterial.uniforms.followMouse.value === true) { 518 | lensFlareMaterial.uniforms.lensPosition.value.set(mouse.x, mouse.y) 519 | } else { 520 | const projectedPosition = screenPosition.clone() 521 | projectedPosition.project(camera) 522 | 523 | flarePosition.x = projectedPosition.x 524 | flarePosition.y = projectedPosition.y 525 | flarePosition.z = projectedPosition.z 526 | 527 | if (flarePosition.z < 1) { 528 | lensFlareMaterial.uniforms.lensPosition.value.set(flarePosition.x, flarePosition.y) 529 | } 530 | 531 | raycaster.setFromCamera(projectedPosition, camera) 532 | const intersects = raycaster.intersectObjects(scene.children, true) 533 | checkTransparency(intersects) 534 | } 535 | 536 | lensFlareMaterial.uniforms.iTime.value = elapsedTime 537 | easing.damp(lensFlareMaterial.uniforms.opacity, 'value', internalOpacity, 0.007, clock.getDelta()) 538 | } 539 | 540 | /** 541 | * Transparency check 542 | */ 543 | function checkTransparency(intersects) { 544 | if (intersects[0]) { 545 | if (intersects[0].object) { 546 | if (intersects[0].object.visible) { 547 | // console.log(intersects[0].object) 548 | if (intersects[0].object.material.transmission) { 549 | if (intersects[0].object.material.transmission > 0.2) { 550 | internalOpacity = oldOpacity * (intersects[0].object.material.transmission * 0.5) 551 | } else { 552 | internalOpacity = 0 553 | } 554 | } else if (intersects[0].object.material.transmission === 0) { 555 | internalOpacity = 0 556 | } else if (intersects[0].object.material.transmission === undefined) { 557 | if (intersects[0].object.material.transparent) { 558 | if (intersects[0].object.material.opacity < 0.98) { 559 | internalOpacity = oldOpacity / (intersects[0].object.material.opacity * 10) 560 | } 561 | } else { 562 | if (intersects[0].object.userData === 'no-occlusion') { 563 | internalOpacity = oldOpacity 564 | } else { 565 | internalOpacity = 0 566 | } 567 | } 568 | } 569 | } 570 | } 571 | } else { 572 | internalOpacity = oldOpacity 573 | } 574 | } 575 | 576 | /** 577 | * Mouse 578 | */ 579 | const mouse = new THREE.Vector2() 580 | 581 | window.addEventListener('mousemove', (event) => { 582 | mouse.x = (event.clientX / window.innerWidth) * 2 - 1 583 | mouse.y = -(event.clientY / window.innerHeight) * 2 + 1 584 | }) 585 | 586 | const lensFlareContainer = new THREE.Mesh(new THREE.PlaneGeometry(2, 2, 1, 1), lensFlareMaterial) 587 | 588 | return lensFlareContainer 589 | } 590 | --------------------------------------------------------------------------------