Fragment Shader Challenge

With the globeTexture uniform pulled in, we can now utilize GLSL's texture2D function to render pixel data onto our geometry.

texture2D takes two arguments, a sampler2D object and a UV coordinate. Recall, a UV coordinate is just another name for an XY coordinate. The X, Y, and Z coordinate names were taken by the XYZ axes to determine the position of something in 3D space, so the creators of UV mapping decided to use the next closest letters to represent X and Y coordinates: U and V.

These UV coordinates represent a specific location on an unwrapped 3D geometry. Say you have a sphere—if we were to unwrap it so it were on a 2D plane, a specific point on this unwrapped geometry would be a UV coordinate.

So given our texture2D() function, remember, it takes a sampler2D texture for its first argument and a UV coordinate (looks like vec2(0, 3)) for it's second argument:

texture2D(globeTexture, UVCoordinate);

We retrieve a UV coordinate from our vertex shader—it represents a location on our geometry if it were unwrapped onto a 2D plane. If we were to lay our texture on top of this unwrapped geometry, what would our pixel color be? texture2D obtains that pixel color and assigns it to the pixel we are looping over.

How do we obtain a UV coordinate from our vertex shader though? To do so, we need to utilize something called a varying:

varying vec2 vertexUV; // equates to a coordinate like [0, 0.24]

A varying is basically a variable that is passed from the vertex shader over to the fragment shader. You can think of it as a uniform, but rather than being passed to both shaders from a JavaScript file, it's only passed from the vertex shader to the fragment shader.

To access a varying in our fragment shader, first we must declare and assign it within our vertex shader.

Add the vertexUV varying above into the vertex shader below (it should be declared above your main function so we can use it later):

vertex.glsl

Providing the lift to launch your development career

© 2024 Chris Courses. All rights reserved.