Now that we’ve learned about lighting, materials, and projectors, let’s combine these effects. We show the effect of lighting objects in different positions with several point lights under sunlight and a spot light.

To define multiple light sources, we need to define different structures. At the same time, we separate the different light calculation to make the code clearer. GLSL definition method is similar to C, but need to declare first, then define, as follows:

void calc(); Void calc(); void calc();Copy the code

We first define directional light, and the structure is defined as:

Struct DirLight {vec3 direction; vec3 ambient; vec3 diffuse; vec3 specular; }; uniform DirLight dirLight;Copy the code

Call calcDirLight in the main function to get the result:

... vec3 calcDirLight(DirLight light, vec3 viewDir); voidmain() { vec3 viewDir = normalize(-fragPos); Vec3 result = calcDirLight(dirLight, viewDir); Gl_FragColor = vec4 (result, 1.0); Vec3 calcDirLight(DirLight, vec3 viewDir) {... / / the resultreturn (ambient + diffuse + specular);
  }
Copy the code

The calculation of directional light can be referred to the previous chapter and will not be described here.

For the definition of point light source, here we use an array to store the data of four point light sources, and also use the for loop to calculate them separately, and then add the results:

Struct PointLight {... };#define NR_POINT_LIGHTS 4uniform PointLight pointLights[NR_POINT_LIGHTS]; ... vec3 calcPointLight(PointLight light, vec3 viewDir); voidmain() { vec3 viewDir = normalize(-fragPos); Vec3 result = calcDirLight(dirLight, viewDir); // Calculate the point light sourcefor(int i = 0; i < NR_POINT_LIGHTS; i++){ result += calcPointLight(pointLights[i], viewDir); } gl_FragColor = vec4(result, 1.0); Vec3 calcPointLight(PointLight, vec3 viewDir){... / / the resultreturn (ambient + diffuse + specular);
  }
Copy the code

Note that when passing in point light data, the parameter name should start with: pointLights[index].

Finally, the effect of concentrating light:

Struct SpotLight {... }; uniform SpotLight spotLight; ... vec3 calcSpotLight(SpotLight light, vec3 viewDir); voidmain() { vec3 viewDir = normalize(-fragPos); Vec3 result = calcDirLight(dirLight, viewDir); // Calculate the point light sourcefor(int i = 0; i < NR_POINT_LIGHTS; i++){ result += calcPointLight(pointLights[i], viewDir); } result += calcSpotLight(spotLight, viewDir); Gl_FragColor = vec4 (result, 1.0); }... Vec3 calcSpotLight(SpotLight light, vec3 viewDir){... / / the resultreturn (ambient + diffuse + specular);
  }
Copy the code

Finally, pass in the object and light data we defined. The effect picture is as follows: