How to combine lights in a GLSL shader


Create a shader that takes in multiple lights as uniforms. Then, add up their properties to determine the combined final result.
In order to combine, or mix lights, in GLSL you must write a shader that takes in the lights as uniforms and determines the visual outcome by adding up the properties of the lights in the fragment shader.
An example solution of a shader that renders a point light and a spotlight can be found can be found on the tutorial/three-js/light-shaders branch of our Open Source React, Typescript & ViteJS Starter Project.
To clone this project, paste the code found below in Terminal.
git clone git@github.com:delasign/reactjs-3js-vitejs-starter-project.git
Step One: Create shaders for individual lights

Use our guide below to create the necessary functionality for ambient lights, directional lights, point lights and spotlights.
Step Two: Write the Shader

Create a vertex.glsl and fragment.glsl file for your shader.
This shader should make use of the functionality created in Step One and add up the properties of the lights that are passed in as uniforms.
If you wish to have multiple lights of the same type, we recommend that you pass them in as an array and add them up using a for loop.
We recommend that you place these files under a folder within a shaders folder.
Step Three: Create a Scene

Create a scene that makes use of the vertex and fragment shader that you created in Step Two.
Step Four: Test

Run the code and make sure that everything works as expected.
If you wish to include dat.gui sliders like we have, consult the tutorials below.
Looking to learn more about ReactJS and ThreeJS ?
Search our blog to find educational content on learning how to use ReactJS and ThreeJS.