Fragment shader

Also known as: pixel shader

On this page 7

A fragment shader is a small program that runs on the graphics processing unit (GPU) once for every fragment produced by rasterization and outputs that fragment’s final color, and optionally its depth. In Direct3D terminology the same stage is called a pixel shader. In Real-time 3D, the fragment shader is where materials, lighting, texturing and most visual effects are evaluated, which makes it the stage that decides how surfaces actually look on screen.

Within 3D graphics & animation, the fragment shader sits after the vertex shader and the rasterizer in the programmable pipeline. Because it executes millions of times per frame, its cost dominates the frame budget in many scenes, and writing efficient fragment code is a core skill for engine and technical artists.

How a fragment shader fits into the GPU pipeline

A fragment shader receives interpolated inputs from earlier stages and returns one or more output values per fragment. The vertex shader transforms vertices into clip space and emits attributes such as normals, texture coordinates and colors. The rasterizer then determines which screen samples each triangle covers and interpolates those attributes with perspective correction, producing a fragment for every covered sample.

A fragment is not yet a pixel. It is a candidate sample that still has to pass the depth test, stencil test and blending before it modifies the framebuffer. A fragment shader can also discard a fragment entirely, which is how alpha-tested foliage and cutout materials are drawn.

The table below lists the typical inputs and outputs of the stage in common shading languages.

DataDirectionPurpose
Interpolated varyingsInputNormals, UVs and colors from the vertex shader
Uniforms and constantsInputLight data, material parameters, time, matrices
Textures and samplersInputAlbedo, normal, roughness and shadow maps
gl_FragCoord or SV_PositionInputWindow-space position and depth of the fragment
Color outputsOutputOne or more render targets (MRT)
Depth outputOutputOptional override of the rasterized depth
Typical fragment shader inputs and outputs

What a fragment shader computes

The central job of a fragment shader is evaluating the material and lighting model for a single surface point. In a modern physically based rendering (PBR) workflow, the shader samples base color, normal, metallic and roughness textures, reconstructs the shading normal, and evaluates a microfacet BRDF such as Cook-Torrance with a GGX distribution for each relevant light.

Beyond lighting, fragment shaders implement a wide range of effects. The following table groups the most common workloads.

WorkloadTypical operationsRelative cost
TexturingUV sampling, mipmap selection, filteringLow to moderate
Normal mappingTangent-space normal decode and transformLow
PBR lightingBRDF evaluation per light, image-based lightingModerate to high
Shadow lookupShadow map sampling with PCF filteringModerate
Post-processingBloom, tone mapping, color grading on a full-screen quadScales with resolution
Stylized shadingCel shading ramps, outlines, ditheringLow
Common fragment shader workloads

Fragment shaders are written in GLSL for OpenGL and WebGL, HLSL for Direct3D, MSL for Metal and WGSL for WebGPU. Vulkan consumes the SPIR-V intermediate representation, which can be compiled from GLSL or HLSL. Node-based material editors in game engines generate fragment code automatically, but the underlying stage is the same.

Fragment shader compared with vertex and compute shaders

The fragment shader differs from neighboring stages mainly in what it runs on and how often. A vertex shader runs once per vertex, so a mesh with 50,000 vertices costs 50,000 invocations. A fragment shader on a 4K display can run more than eight million times for a single full-screen pass, and more when overdraw or multisampling is involved.

StageRuns perMain outputTypical use
Vertex shaderVertexClip-space position and varyingsTransformation, skinning, morphing
Fragment shaderRasterized fragmentColor and depthMaterials, lighting, effects
Compute shaderThread in a dispatchArbitrary buffers and imagesSimulation, culling, light lists
Comparison of programmable shader stages

A practical rule follows from these frequencies: move work to the vertex stage when a value varies smoothly across a triangle, and keep in the fragment stage only what must vary per sample. Compute shaders increasingly take over screen-space work, such as tiled light culling, because they offer shared memory and flexible thread groups that the fragment stage lacks.

Performance factors in fragment shading

Fragment cost is the product of shader complexity and fragment count, so both must be controlled. GPUs execute fragments in small groups, typically 2×2 quads inside wider SIMD waves of 32 or 64 lanes. Quads exist so that the hardware can compute screen-space derivatives for mipmap selection, which also means that tiny triangles waste lanes on helper invocations.

The following table summarizes the factors that most often limit fragment throughput and the usual remedies.

ProblemCauseTypical remedy
OverdrawMany layers shade the same pixelFront-to-back sorting, depth prepass, occlusion culling
Divergent branchingLanes in a wave take different pathsUniform branches, precomputed masks
Texture bandwidthLarge uncompressed or unmipped texturesMipmapping, block compression, fewer samples
Disabled early-ZDiscard or depth writes in the shaderAvoid discard on opaque geometry
Many lightsEvery light evaluated for every fragmentDeferred shading or clustered light lists
Fragment performance problems and remedies

Early depth testing is a decisive optimization. When a fragment shader neither writes depth nor discards fragments, the GPU can reject hidden fragments before running the shader. Using discard or writing gl_FragDepth can disable this hardware optimization, so alpha-tested materials should be limited to geometry that truly needs them.

Common mistakes and limitations

Several errors recur in fragment shader code, especially in projects that grow from prototypes. The list below covers the most frequent ones.

  • Lighting in the wrong color space: blending or lighting sRGB-encoded values instead of linear values produces dark, muddy gradients.
  • Unnormalized interpolated normals: interpolation shortens vectors, so normals must be renormalized per fragment.
  • Precision problems: mediump floats on mobile GPUs cause banding and visible errors in large world coordinates.
  • Derivatives inside divergent branches: texture sampling with implicit derivatives inside non-uniform control flow gives undefined results.
  • Shader permutation explosion: compiling a variant for every feature combination inflates build time and causes runtime hitches.

A fragment shader also has inherent limits. It cannot see neighboring fragments of the same draw, cannot create new geometry, and in standard pipelines cannot read the current framebuffer value it is about to overwrite. Effects that need such information use extra render passes, framebuffer fetch extensions or compute shaders.

In plain words

Picture a screen as a huge grid of tiny dots. A fragment shader is a short recipe that the graphics card runs for each dot covered by an object. The recipe answers one question: what color should this dot be?

To answer, it looks at the surface. It checks the texture, the direction the surface faces and where the lights are. Then it mixes these into one color. The graphics card runs millions of these recipes at once. That is why a simple recipe keeps a game smooth and a heavy one slows it down.

A real-world example

A small studio is building a browser-based product configurator for furniture with WebGL. The first version uses one fragment shader with full PBR lighting for every surface, including eight dynamic lights and a high-resolution environment map. On mid-range laptops at 1920×1080, the scene runs at only about 30 frames per second.

Profiling shows that the GPU is fragment-bound: overdraw from transparent fabric layers and per-fragment evaluation of all eight lights dominate the frame. The team bakes static lighting into lightmaps, keeps only two dynamic lights, replaces alpha-tested fabric with opaque geometry where possible, and moves fog calculation to the vertex shader. After these changes the configurator holds a stable 60 frames per second on the same hardware, with no visible loss of material quality.