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.
| Data | Direction | Purpose |
|---|---|---|
| Interpolated varyings | Input | Normals, UVs and colors from the vertex shader |
| Uniforms and constants | Input | Light data, material parameters, time, matrices |
| Textures and samplers | Input | Albedo, normal, roughness and shadow maps |
gl_FragCoord or SV_Position | Input | Window-space position and depth of the fragment |
| Color outputs | Output | One or more render targets (MRT) |
| Depth output | Output | Optional override of the rasterized depth |
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.
| Workload | Typical operations | Relative cost |
|---|---|---|
| Texturing | UV sampling, mipmap selection, filtering | Low to moderate |
| Normal mapping | Tangent-space normal decode and transform | Low |
| PBR lighting | BRDF evaluation per light, image-based lighting | Moderate to high |
| Shadow lookup | Shadow map sampling with PCF filtering | Moderate |
| Post-processing | Bloom, tone mapping, color grading on a full-screen quad | Scales with resolution |
| Stylized shading | Cel shading ramps, outlines, dithering | Low |
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.
| Stage | Runs per | Main output | Typical use |
|---|---|---|---|
| Vertex shader | Vertex | Clip-space position and varyings | Transformation, skinning, morphing |
| Fragment shader | Rasterized fragment | Color and depth | Materials, lighting, effects |
| Compute shader | Thread in a dispatch | Arbitrary buffers and images | Simulation, culling, light lists |
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.
| Problem | Cause | Typical remedy |
|---|---|---|
| Overdraw | Many layers shade the same pixel | Front-to-back sorting, depth prepass, occlusion culling |
| Divergent branching | Lanes in a wave take different paths | Uniform branches, precomputed masks |
| Texture bandwidth | Large uncompressed or unmipped textures | Mipmapping, block compression, fewer samples |
| Disabled early-Z | Discard or depth writes in the shader | Avoid discard on opaque geometry |
| Many lights | Every light evaluated for every fragment | Deferred shading or clustered light lists |
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:
mediumpfloats 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.