Shaders From Zero · Episode 03

UVs Are Everything

UVs Are Everything is Episode 03 of Shaders From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.

Part of the MasterAllArts Creative 3D Roadmap .

Episode 03 · Shaders From Zero

UVs are normally for sampling textures. But they're really just a built-in coordinate system handed to your fragment shader, free of charge. Once you stop seeing them as "texture coords" and start seeing them as "where am I on this surface," you unlock about 80% of the fragment-shader effects you've ever admired on Shadertoy.

This episode is a single mental shift. By the end, you'll think in UVs before you think in pixels. Every demo from here on will look like: take the UV, do something interesting with it, output a color. Centering, tiling, polar, grids, stripes — all of it lives inside the unit square.

0 fps
ShaderMaterial · UVs
vUv as red+green. The shader-programmer's first sanity check.

What UVs actually are

Every Three.js geometry has a built-in vec2 uv attribute on each vertex. The values run from 0.0 to 1.0 across the surface, and the GPU interpolates them per pixel for you. That's it. That's the whole feature. The word "UV" is a historical artifact — "U" and "V" were the letters Pixar's RenderMan used because "X" and "Y" were taken by world coordinates.

For a flat plane, the layout is:

(0, 1) ┌──────────────────┐ (1, 1) │ │ │ vUv │ │ ranges 0..1 │ │ on both axes │ │ │ (0, 0) └──────────────────┘ (1, 0)

The pattern is the same one we used in Episode 1 for the gradient stage: declare a varying, write to it in the vertex shader, read it in the fragment shader.

// VERTEX SHADER
varying vec2 vUv;

void main() {
  vUv = uv;        // uv is auto-declared by ShaderMaterial
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}

// FRAGMENT SHADER
varying vec2 vUv;

void main() {
  gl_FragColor = vec4(vUv, 0.0, 1.0);
}

Stage 1 in the demo. The bottom-left corner is black (vUv = (0, 0), no red, no green). The bottom-right is red (vUv.x = 1). The top-left is green (vUv.y = 1). The top-right is yellow (both at 1). Memorize this image. The first thing you do when an effect looks wrong is render the raw UV and check that it points the way you expect.

Takeaway: UVs are a free per-pixel coordinate system in [0, 1] × [0, 1]. Use them as input to every fragment effect.

Centering the origin

The native UV range [0, 1] is fine for asymmetric effects — a left-to-right wipe, a top-down scanline — but it's annoying for anything symmetric. If you want a circle in the middle of the surface, you don't want its origin at the corner. The standard move:

vec2 p = vUv - 0.5;        // p is now in [−0.5, 0.5] × [−0.5, 0.5]

Now (0, 0) is the center of the surface. p.x is negative on the left, positive on the right. p.y is negative on the bottom, positive on top. The convention is to call this variable p ("point") or uv (shadowing the varying), but please don't shadow the varying — it leads to confusion when you need both.

The single most useful function on centered UVs is length(p):

float d = length(p);     // distance from center, 0.0 at middle, ~0.707 at corners

Now you can write things like "color this pixel red if it's within 0.3 of the center" — a circle, in two lines. We'll do that in Episode 6 when we get to SDFs. For now, just notice: Stage 2 in the demo renders abs(p) * 2.0 as RGB, which makes the center black and the corners bright. Distance from center, drawn on each axis independently.

Takeaway: Subtract 0.5 to center. length(p) is then "how far from the middle am I."

Fixing aspect ratio

There's a trap waiting in centered UVs. If your surface isn't square — say, a 16:10 plane or a fullscreen quad — then a "circle" drawn from length(vUv - 0.5) will look like an oval. UVs are [0, 1] in both axes regardless of the physical aspect ratio of the mesh on screen.

Fix: multiply one axis by aspect:

uniform float uAspect;       // width / height, passed in from JS

void main() {
  vec2 p = vUv - 0.5;
  p.x *= uAspect;            // stretch x so 1 unit of p.x equals 1 unit of p.y on screen
  float d = length(p);
  // ...
}

From the JS side, set uAspect whenever your container resizes:

material.uniforms.uAspect.value = mount.clientWidth / mount.clientHeight;

Without this fix, every "circle" effect you build looks fine in the editor and squished the moment someone resizes the browser.

Power-user note: for a full-screen quad rendered with a post-process pass, you don't have UVs — you have gl_FragCoord.xy, which is pixel coordinates. The fullscreen idiom is vec2 p = gl_FragCoord.xy / uResolution.xy - 0.5; p.x *= uResolution.x / uResolution.y;. Same shape, different inputs. We'll use this when we get to post-processing.

Takeaway: Multiply p.x by aspect ratio before you do radial math, or your circles will be ovals.

Scaling and tiling with fract

One of the most beautiful tricks in shading is the fract tile. fract(x) returns the fractional part of x — drops the integer, keeps everything after the decimal point. Apply it to a scaled UV and you get a brand-new [0, 1] coordinate system, per tile:

vec2 tileUv = fract(vUv * 8.0);     // 8 tiles per axis = 64 mini-UV-squares
gl_FragColor = vec4(tileUv, 0.0, 1.0);

Stage 3 in the demo. The single Stage-1 gradient becomes 64 copies of itself. Each tile is independent. You can think of fract as the GLSL equivalent of "repeat this pattern infinitely without authoring more geometry."

Two practical uses come up constantly:

  • Repeated patterns. Stripes, polka dots, checker, hex tiles — author one cell, multiply UV by N, fract, repeat.
  • Animation cells. Multiply UV by N, fract, then offset by time. A flowing river of stripes is six lines of GLSL.

One gotcha: fract(x) always returns the fractional part as a positive value, which is exactly what you want. The wraparound is seamless, so a value of 0.99 jumps to 0.0 at the boundary. That jump is a hard discontinuity — patterns that aren't periodic across that boundary will show a visible seam. We'll discuss this in pitfalls below.

Takeaway: fract(vUv * N) tiles your UV N×N times. Each tile is its own fresh coordinate system in [0, 1].

Polar coordinates — UVs on a wheel

For anything with rotational symmetry — a sun with rays, a vortex, a radial gradient, a clock — polar coordinates are way easier than Cartesian. Two functions get you there:

vec2 p = vUv - 0.5;

float angle  = atan(p.y, p.x);    // in [−π, π]; counter-clockwise from +x
float radius = length(p);         // distance from center

That's the whole conversion. Now any effect that "rotates around a point" is expressible as a function of angle. Any effect that "depends on distance" is a function of radius. Stage 4 in the demo uses angle to drive hue and radius to drive brightness — a quick rainbow disc:

vec2 p = vUv - 0.5;
float a = atan(p.y, p.x);
float r = length(p) * 2.0;

// IQ cosine palette — same one we'll cover properly in Episode 04
vec3 col = 0.5 + 0.5 * cos(a + vec3(0.0, 2.094, 4.189));

gl_FragColor = vec4(col * (1.0 - r), 1.0);

Note the atan(p.y, p.x) argument order. GLSL collapses what most languages call atan2(y, x) into a two-argument overload of plain atan. Y comes first, X second. Reverse them and your wheel reflects. More on that in pitfalls.

2.094 and 4.189 are 2π/3 and 4π/3 — one-third and two-thirds of a full turn. They shift the cosine by 120° and 240°, which is how a single cosine becomes a smooth RGB rainbow. We unpack this in Episode 04.

Takeaway: atan(p.y, p.x) for angle, length(p) for radius. Together they convert UVs into polar coordinates in two lines.

Combining: stripes, grids, checkerboards

Now we have the pieces to build the classic UV demos in one or two lines each.

Stripes

float stripes = step(0.5, fract(vUv.x * 6.0));
gl_FragColor = vec4(vec3(stripes), 1.0);

Six vertical bands. fract(vUv.x * 6.0) repeats 0..1 six times across the surface; step(0.5, ...) turns the lower half black and the upper half white. Change the 0.5 to control bar thickness, change the 6.0 to control density.

Grid lines

vec2 g = abs(fract(vUv * 8.0) - 0.5);
float line = step(0.45, max(g.x, g.y));
gl_FragColor = vec4(vec3(line), 1.0);

This is Stage 5 in the demo. The trick: fract(vUv * 8.0) runs 0→1 inside every tile. Subtract 0.5 and take abs — now each tile runs 0.5 → 0 → 0.5, peaking at the edges. Take the max of the two axes and threshold at 0.45 — you get a line right at the boundary. Change 0.45 to control line thickness.

Checkerboard

GLSL has no != operator on floats and no boolean XOR, so the obvious "this row XOR this column" trick doesn't work directly. The standard idiom is to use mod on the sum of integer parts:

float checker = mod(floor(vUv.x * 4.0) + floor(vUv.y * 4.0), 2.0);
gl_FragColor = vec4(vec3(checker), 1.0);

Walk it: floor(vUv.x * 4.0) gives 0, 1, 2, 3 in horizontal strips. Same for y. Add them — diagonals get the same value. mod 2.0 alternates them between 0 and 1. Classic checkerboard, four lines.

Takeaway: step + fract is your tile primitive. floor + mod 2.0 is your checker primitive. These two patterns generate most of the procedural patterns you'll ever need.

Common first-day pitfalls

  • Forgot to subtract 0.5 for centered effects. You wrote length(vUv) and your "circle in the middle" is actually a quarter-arc stuck in the corner. Always subtract 0.5 before radial math.
  • Aspect ratio not corrected. Your circle is an oval, your square is a rectangle, and you change the browser size to verify it's still wrong. Multiply p.x by aspect, every time, for every radial effect.
  • atan(y, x) argument order. Most languages have atan2(y, x); GLSL folds the two-arg form into plain atan with y first. Write atan(p.x, p.y) and your polar wheel will rotate the wrong way and start from the wrong axis. Memorize: y then x.
  • Visible seam at the tile boundary. Your fract(vUv * 8.0) pattern has a hard cliff every 1/8 of the surface. If your per-tile effect doesn't go back to 0 at the edges, you'll see the seam. The classic seamless pattern is sin(vUv.x * 6.2832), which returns to 0 exactly once per UV period because 2π is one full sine cycle.
  • floor on the wrong side of fract. fract(floor(x)) is always 0. floor(fract(x)) is 0 too. You wanted one or the other on its own — usually fract for the "position inside the tile" and floor for the "which tile am I."
  • Negative UVs from animation offset. You wrote fract(vUv.x * 8.0 - uTime) to make stripes move left. That works in GLSL because fract handles negatives correctly (returns a positive fractional part), but the older textbook formula x - floor(x) would not. Trust fract; don't trust hand-rolled equivalents.

Exercises

  1. Modify Stage 3 (the tiled UV) so the tile count comes from a uniform uTiles and a slider in the controls panel. Watch the tile count animate smoothly as you drag — and notice that non-integer values produce a visibly broken pattern at the edge of the surface. Why? (Hint: the surface ends at vUv = 1 regardless.)
  2. Take Stage 4's polar wheel and animate the rotation. Add uTime to the angle before feeding it to the cosine palette. Then make the radius pulse with sin(uTime * 2.0). Two characters of change for a real-looking spinning disc.
  3. Build a "barber pole" by combining stripes with rotation. Compute angle and radius from centered UVs, then make stripes at step(0.5, fract(radius * 8.0 + angle)). The diagonal stripes of a real barber pole, parameterized in polar. Try animating the offset with uTime.

What's next

Episode 04 — Color & Gradients. We've been outputting vec3s of RGB and calling them done. Time to be more deliberate. We'll cover HSV (and why you almost never want raw HSV in a final shader), Inigo Quilez's cosine palette formula (the cos(a + vec3(0.0, 2.094, 4.189)) we used in Stage 4 of this episode), and the gamma-correction trap that makes 95% of shader gradients look subtly wrong. After Episode 04 your gradients will look like a designer made them.