Lighting Lab

This lab adds some sparkle to the cylinder you developed in the last lab. You'll shade the cylinder using the Blinn-Phong illumination model. Additionally, you'll get some practice reading in a file.

Read in File

Your first challenge is to load in a configuration file like this:

  "albedo": [1, 1, 0],
  "position": [0, 0, -6],
  "ambientFactor": 0.2,
  "diffuseColor": [1, 0.5, 1],
  "specularColor": [1, 1, 1],
  "shininess": 99

The format of this file is JSON (JavaScript Object Notation), which is a plain text format for describing integers, floats, booleans, strings, null, arrays, and key-value pairs. This particular JSON file describes the lighting and position properties of your cylinder. Follow these steps to pull this file into your renderer.

Save this file to your project directory.
Read in the file. JavaScript running in the browser doesn't have direct access to your computer's file system. However, thanks to Vite, you do have a web server running that is happy to send the file along. You just need to issue a fetch call. If the file is plain text, you read it with code like this:
async function readTextFromFile(file) {
  const text = await fetch(file).then(response => response.text());
  return text;

But the file is JSON, so it must be parsed into a real JavaScript object. Instead of calling the text method, you call json:

async function readObjectFromFile(file) {
  const object = await fetch(file).then(response => response.json());
  return object;

The actual fetching of the file takes place in the background. Sometimes you need the fetched content before you can do anything else. In that case, then you can effectively force the browser to block using the await keyword. Awaiting is only legal if the function is marked async.

The initialize function might read in a JSON file like this:

function initialize() {
  const configuration = await readObjectFromFile('configuration.json');
  // ...
Use the position property to translate the cylinder. Use a translation matrix, but make sure the current rotation happens first.
Show your instructor your working renderer to receive credit.

Lit Cylinder

Your second challenge is to shade the the cylinder using the Blinn-Phong illumination model. Follow these steps:

Add normals to your cylinder's vertex attributes. As with the sphere, you can derive a vertex's normal from its position. Have the vertex shader pass the normal along to the fragment shader.
Temporarily color the cylinder by its normal. Make sure you can see colors before advancing.
Add a diffuse term. Use the diffuse light color and albedo from the JSON configuration; send them along as uniforms.
Add an ambient term. Weight the ambient and diffuse terms using the ambient factor from the JSON configuration.
Add a specular term. Use the specular light color and shininess from the JSON configuration.
Show your instructor your working renderer to receive credit.