{
  "id": "shader",
  "title": "Shader",
  "lang": "en",
  "source_lang": "en",
  "summary": "A shader is a program that controls a programmable graphics-processing stage or performs parallel computation through a graphics-oriented programming interface.",
  "category": "computer-science",
  "subcategory": "software",
  "type": "concept",
  "aliases": [
    "Shader program"
  ],
  "generated_at": "2026-11-03",
  "model": "pro/gpt-6.1-sol",
  "url": "https://aiwiki.page/en/shader/",
  "translations": {
    "zh-Hans": {
      "url": "https://aiwiki.page/zh/shader/",
      "json": "https://aiwiki.page/zh/shader.json"
    }
  },
  "sections": [
    {
      "heading": "",
      "text": "A shader is a program executed within a programmable rendering or graphics-computation system. Shaders determine how geometric data are transformed, how surfaces interact with light, how image samples are produced, and, in modern systems, how many kinds of parallel computation are performed. They usually run on a graphics processing unit (GPU), although software renderers and offline rendering systems can execute shaders on other processors. The name originated in calculations of surface appearance, but contemporary shaders also manipulate geometry, trace rays, simulate physical systems, and process data without producing an image.\n\nShaders are central to computer graphics because they separate the description of visual behavior from the fixed capabilities of a rendering device. A rendering application supplies programs, resources, and commands; the graphics implementation executes those programs for large numbers of vertices, fragments, rays, or work items. The result depends not only on shader code but also on the surrounding pipeline, numerical representations, resource bindings, and synchronization rules.\n\nThe term describes a role rather than one particular language or file format. A short fragment shader that colors a triangle, an offline material program that describes layered glass, and a compute shader that filters a photograph may all be called shaders, although their inputs, execution models, and outputs differ substantially."
    },
    {
      "heading": "Historical development and the move to programmable graphics",
      "text": "Early interactive graphics hardware performed most rendering through fixed-function circuits. Applications could select predefined operations, supply transformation matrices and lighting parameters, and configure texture-combination modes, but could not freely replace the underlying calculations. Surface appearance was consequently constrained by the operations implemented in the hardware. Software rendering offered greater flexibility, but often at a much higher computational cost.\n\nProgrammable shading developed prominently in film production and research before becoming standard in consumer graphics hardware. Robert L. Cook’s 1984 paper Shade Trees described a compositional approach to shading calculations. The RenderMan Interface Specification, introduced by Pixar in 1988, helped establish a programmable model in which specialized programs described surfaces, lights, displacement, and atmospheric effects. Such programs could evaluate procedural patterns and material responses without requiring every appearance to be represented by a stored image. Their execution environment was an offline renderer rather than necessarily a GPU.\n\nConsumer graphics hardware became progressively programmable around the turn of the twenty-first century. Microsoft’s DirectX 8, released in 2000, exposed programmable vertex and pixel shader models. NVIDIA’s GeForce 3, introduced in 2001, was an influential implementation of this generation. Early hardware programs had tight limits on instruction counts, temporary registers, texture access, and control flow. Vertex processors and pixel processors also had different capabilities, so a calculation available in one stage might not be possible in another.\n\nHigher-level programming languages subsequently reduced dependence on hardware-specific assembly. NVIDIA introduced Cg in 2002, and Microsoft’s DirectX 9, released that year, included the High-Level Shader Language. OpenGL 2.0 incorporated the OpenGL Shading Language in 2004. These developments allowed programmers to express arithmetic, functions, and increasingly complex control flow in forms closer to conventional application code, while a compiler translated the programs for the target graphics system.\n\nHardware organization changed alongside the languages. Older GPUs commonly divided resources into dedicated vertex and pixel processors. Unified shader architectures instead used broadly shared execution resources for different shader stages, allowing the hardware to distribute capacity according to workload. Direct3D 10-era desktop GPUs made this approach widely established in 2006–2007. “Unified” did not eliminate the logical stages: a vertex shader and a fragment shader retained different interfaces even when the same arithmetic units could execute both.\n\nLater extensions expanded programmability beyond surface shading. Geometry processing, tessellation, compute workloads, mesh generation, and hardware-assisted ray tracing acquired programmable interfaces. The historical progression therefore involved both greater freedom within existing stages and the introduction of new stages with fundamentally different responsibilities."
    },
    {
      "heading": "Shader stages in the rasterization pipeline",
      "text": "A graphics pipeline converts a scene description into image data through a sequence of operations. In a rasterization pipeline, geometric primitives such as triangles are projected onto an image plane and converted into covered samples. Some operations are programmable, while others remain fixed-function or configurable. A shader is defined partly by its position in this pipeline: the stage determines which data it receives, what it can write, and how its invocations relate to the underlying geometry.\n\nA vertex shader processes vertex attributes such as position, surface normal, color, and texture coordinates. A common task is to transform an object-space position into homogeneous clip coordinates:\n\n\\[\\mathbf{p}_{\\mathrm{clip}} = \\mathbf{P}\\mathbf{V}\\mathbf{M}\\mathbf{p}_{\\mathrm{object}},\\]\n\nwhere \\(\\mathbf{M}\\), \\(\\mathbf{V}\\), and \\(\\mathbf{P}\\) are model, view, and projection transformations. These are usually represented using matrices. Vertex shaders also perform skeletal deformation, morph-target blending, and other per-vertex calculations. Their outputs include data that can later be interpolated across a primitive. An invocation is a logical processing event, not a guarantee that every submitted vertex will be independently recomputed: implementations can reuse suitable results.\n\nOptional stages modify or generate geometry. Tessellation control and evaluation stages subdivide patches and evaluate positions on the resulting domain; Direct3D calls these the hull and domain stages. A geometry shader receives a primitive and can emit a limited sequence of new primitives. More recent mesh-shader pipelines organize geometry generation around groups of cooperating invocations. They can combine tasks such as fetching vertex data, rejecting invisible geometry, and assembling primitives without following the traditional vertex-input path.\n\nFollowing clipping, perspective division, and viewport transformation, rasterization determines sample coverage. A fragment shader, called a pixel shader in Direct3D terminology, computes values associated with rasterized fragments. A fragment is not identical to a final pixel: multiple primitives may contribute fragments at the same location, and multisampling may represent several coverage samples within a pixel. Fragment inputs often include interpolated texture coordinates and normals. Outputs commonly include one or more color values and, optionally, depth.\n\nThe interpolation rules matter. Perspective-correct interpolation accounts for the projective transformation, whereas flat interpolation takes a value from a designated vertex. Some interfaces also offer interpolation without perspective correction and controls related to sample positions. Incorrect interpolation can make a texture appear to slide or distort even when the fragment shader’s arithmetic is otherwise correct.\n\nDepth tests, stencil tests, blending, and output-format conversion determine whether and how shader outputs affect an attachment. These operations are not simply part of the fragment shader. Implementations may perform some tests early when permitted, but shader side effects, depth writes, and discard behavior constrain such optimizations. Consequently, the pipeline’s observable behavior cannot be inferred from shader code alone."
    },
    {
      "heading": "Surface appearance, illumination, and procedural materials",
      "text": "A surface shader evaluates an appearance model using geometric information, material parameters, light information, and often sampled images. The calculation can be as simple as returning a constant color or as complex as describing multiple scattering layers. A useful distinction separates a material description, which states properties such as roughness and absorption, from a lighting calculation, which estimates how those properties interact with illumination. Rendering systems may combine these responsibilities in one program or distribute them across several passes.\n\nDiffuse illumination is often introduced through Lambert’s cosine law. For a simple directional light, a corresponding shader expression is\n\n\\[\\mathbf{L}_{o} = \\frac{\\boldsymbol{\\rho}}{\\pi} \\odot \\mathbf{L}_{i} \\max(0,\\mathbf{n}\\cdot\\mathbf{l}),\\]\n\nwhere \\(\\boldsymbol{\\rho}\\) is diffuse reflectance, \\(\\mathbf{n}\\) is the unit surface normal, \\(\\mathbf{l}\\) is the unit direction toward the light, and \\(\\odot\\) denotes componentwise multiplication. The factor \\(1/\\pi\\) belongs to the Lambertian reflectance function. Practical lighting interfaces sometimes absorb normalization factors into their parameter conventions, so superficially similar code can use different numerical scales.\n\nMore general reflectance is described by a bidirectional reflectance distribution function (BRDF). For a non-emissive reflecting surface, outgoing radiance is expressed by the surface rendering equation:\n\n\\[L_o(\\mathbf{x},\\omega_o) = \\int_{\\Omega^+} f_r(\\mathbf{x},\\omega_i,\\omega_o) L_i(\\mathbf{x},\\omega_i) \\max(0,\\mathbf{n}\\cdot\\omega_i)\\,d\\omega_i.\\]\n\nA shader may evaluate the BRDF, approximate this integral, or provide parameters used by a renderer that performs the integration. These are different responsibilities. A physically motivated material function alone does not supply accurate global illumination.\n\nModern real-time physically based rendering commonly uses microfacet models for specular reflection. Such models describe a surface as a statistical distribution of tiny reflecting facets and combine a normal-distribution term, Fresnel reflection, and geometric masking and shadowing. Metallic-roughness workflows expose a compact set of artist-facing parameters, but their precise interpretation depends on the rendering system. Roughness is not a universal physical quantity with one mandatory mapping to every microfacet distribution.\n\nTexture maps and procedural functions supply spatial variation. A texture map may store base color, roughness, a normal perturbation, or another parameter. Normal mapping alters the normal used in shading without necessarily changing the geometric silhouette; displacement changes the actual surface position when the pipeline supports it. Procedural noise, coordinate transformations, and mathematical patterns can generate wood grain, clouds, terrain, or wear without storing every detail explicitly.\n\nAppearance also depends on color representation. Lighting arithmetic generally operates on linear-light values; display-encoded color values must be interpreted appropriately before use. High-dynamic-range illumination can exceed the displayable range and requires a later display mapping. Treating a color texture as linear when it is encoded nonlinearly, or applying a display conversion twice, changes brightness and material response independently of the lighting model."
    },
    {
      "heading": "Resources, memory, and data interfaces",
      "text": "Shaders operate on data supplied through an application programming interface (API). Resources include images, buffers, acceleration structures, and small blocks of parameters. The application establishes which resources a program may access, while the shader declares compatible interfaces. Unlike ordinary application functions, shader invocations generally do not receive unrestricted access to the host process’s address space. Available memory operations depend on the graphics API, stage, hardware capabilities, and enabled features.\n\nUniform or constant data hold parameters shared across many invocations, such as a transformation matrix, camera position, or light count. Vertex inputs provide attributes associated with geometry. Storage buffers support larger indexed data structures and, where permitted, writes. Small immediate parameter mechanisms, such as Vulkan push constants, provide another way to communicate frequently changing values. These categories describe access and binding conventions rather than guaranteeing one particular physical memory technology.\n\nTextures combine image storage with specialized access operations. Sampling may involve coordinate addressing, filtering, format conversion, and level-of-detail selection. A sampler specifies behavior such as wrapping or clamping coordinates and selecting nearest-neighbor or linear filtering. An integer-coordinate image fetch is conceptually different from a filtered sample: the former requests a particular texel, while the latter evaluates a sampling operation over an image representation.\n\nMipmapping stores progressively smaller versions of a texture to reduce aliasing and improve access locality when the texture occupies little screen space. Fragment shaders can often use implicit coordinate derivatives to estimate the appropriate level of detail. These derivatives are typically formed using neighboring invocations arranged in small pixel groups. Sampling from stages without such implicit derivatives generally requires another mechanism, such as an explicit level of detail or explicit gradients. Filtering reduces sampling artifacts but does not reconstruct detail absent from the stored signal.\n\nResource layouts are a major source of interoperability errors. A structure written by the host must have the offsets, alignment, stride, and scalar representations expected by the shader. A three-component vector, for example, does not imply that the next member begins immediately after three tightly packed scalars under every layout convention. Different APIs and shader languages offer different layout rules, and a cross-platform system must preserve their intended correspondence.\n\nWrites introduce visibility and ordering questions. A shader that writes an image or buffer does not automatically make those writes available to every subsequent consumer under every execution circumstance. The application may need pipeline barriers, resource transitions, or other synchronization operations. Within a cooperating group, shader-level barriers can coordinate participating invocations. Resource access is therefore both a data-description problem and a memory-model problem: correct addresses and types are insufficient if the required ordering has not been established."
    },
    {
      "heading": "Parallel execution and performance characteristics",
      "text": "Shader execution is a form of parallel computing designed to expose many similar operations at once. A renderer may launch work for millions of fragments or vertices, while a compute dispatch supplies a grid of work items. Hardware schedules this work across execution units and typically groups invocations into subgroups, often called warps or wavefronts. Their size and exact behavior depend on the architecture and programming interface; portable code cannot assume one universal subgroup width.\n\nMany GPUs use a single-instruction, multiple-thread style of execution. Neighboring invocations can maintain distinct values while executing a common instruction stream. When an ordinary branch sends invocations in different directions, the hardware may execute the paths with different active-lane masks. This divergence can reduce useful throughput. A branch shared by all active invocations may be inexpensive, however, and skipping costly work can be beneficial even when some divergence occurs. Branch count alone is therefore a poor performance measure.\n\nRegister use affects how much work can remain resident on a processing unit. A large number of live temporary values may reduce the number of simultaneously active invocations or cause register spilling into other storage. Resident work helps hide instruction and memory latency, but maximum occupancy is not synonymous with maximum speed. A program with fewer resident groups may still run faster if it performs less work, uses resources more efficiently, or avoids unnecessary memory traffic.\n\nMemory behavior is equally important. Nearby invocations accessing suitably arranged nearby addresses can often be served efficiently, whereas scattered access may require more transactions. Texture caches exploit locality in sampling workloads. Reusing data in shared memory can reduce repeated external accesses in compute shaders, although loading the shared data and coordinating its use also have costs. The relevant bottleneck may be bandwidth, instruction throughput, latency, resource dependencies, or fixed-function capacity rather than one universal limit.\n\nFragment workloads add effects that do not appear directly in the source program. Overdraw occurs when multiple surfaces generate work for the same screen region. Some invocations execute as helpers so that neighboring fragments can obtain derivatives, even though those helper invocations do not contribute ordinary final outputs. Small or thin triangles may use fragment-processing groups inefficiently. Thus, reducing the number of visible pixels does not necessarily reduce shader execution proportionally.\n\nNumerical choices also affect performance and results. Some devices provide efficient reduced-precision arithmetic, while others execute particular precision classes similarly. Floating-point reassociation, fused operations, denormal handling, and approximate mathematical instructions can produce differences between implementations. Performance analysis consequently relies on measurements of representative workloads and GPU timing or profiling tools rather than on the length of shader source code."
    },
    {
      "heading": "Languages, compilation, and portability",
      "text": "Shader languages describe both calculations and execution interfaces. The OpenGL Shading Language (GLSL) is associated with OpenGL and has related forms used in other environments. HLSL originated with Microsoft’s Direct3D ecosystem. Metal Shading Language serves Apple’s Metal API. WebGL uses versions of GLSL ES, while WebGPU defines the WebGPU Shading Language, WGSL, as its standard shader language. These languages share familiar arithmetic and control-flow constructs, but differ in types, resource declarations, stage annotations, and validation requirements.\n\nCompilation frequently involves several representations. A source compiler may first produce an intermediate module that is later translated into device-specific machine instructions. SPIR-V, standardized by the Khronos Group, is an intermediate representation used prominently with Vulkan. Microsoft’s DirectX Intermediate Language, DXIL, serves a related role in modern Direct3D toolchains. Neither format should be confused with a universal GPU instruction set: the final executable instructions depend on the target hardware and implementation.\n\nCompilation also includes interface checking. The system must establish that a shader’s declared inputs, outputs, resource types, and capabilities are compatible with the intended pipeline. In systems using explicit pipeline objects, shaders are combined with relevant fixed-function configuration to create executable pipeline state. Implementations can optimize on the basis of this combined information. Specialization constants and related mechanisms allow selected parameters to become fixed during a later compilation step without requiring an entirely separate handwritten source program.\n\nCompilation costs can become visible to users. A game may contain many shader variants corresponding to combinations of material features, rendering passes, quality settings, and hardware capabilities. If every combination is generated, the number can grow multiplicatively. Some variants are compiled during development or installation; others are created when a particular pipeline is first needed. Unexpected compilation during rendering can cause frame-time spikes. Pipeline caches can reduce repeated work, but their reuse and compatibility rules are implementation-dependent.\n\nPortability has several layers. Translating the syntax does not automatically reconcile coordinate conventions, buffer layouts, interpolation rules, supported texture formats, or numerical behavior. For example, clip-space depth conventions and image-coordinate conventions differ among APIs or are configurable. A shader translated mechanically from one environment may compile while producing an inverted image, incorrect depth, or misaligned data. Cross-compilation systems therefore need semantic mappings, not just replacements for keywords.\n\nHigher-level authoring systems add another layer. Node-based material editors and domain-specific languages generate shader code from graphs or structured descriptions. They can centralize conventions and remove repetitive low-level work, but they do not remove the constraints of the target execution model. The generated program still consumes registers, accesses memory, depends on resource layouts, and must obey the target API’s validation and synchronization rules."
    },
    {
      "heading": "Compute shaders and non-rendering workloads",
      "text": "A compute shader runs through a graphics or compute API without being tied to the vertex-to-fragment rasterization sequence. The application dispatches a grid of workgroups, each containing a defined arrangement of local invocations. Programs can derive indices from workgroup and local identifiers to determine which elements they process. This organization supports both independent operations and cooperation among nearby invocations.\n\nAn image filter illustrates the model. A dispatch can assign one invocation to each output pixel, read a neighborhood of input pixels, and write the filtered result. If the image dimensions are not exact multiples of the workgroup dimensions, additional invocations may fall outside the valid image and need appropriate bounds handling. In-place filtering requires particular care because one invocation must not accidentally read values that another has already overwritten when the algorithm expects the original image.\n\nWorkgroup-local storage enables tiled algorithms. For a convolution, a group can cooperatively load an image tile and its surrounding border into shared memory, synchronize, and reuse those values for several output calculations. Similar techniques support matrix operations, particle simulations, histograms, and portions of sorting algorithms. Shader-level barriers must satisfy the language’s participation and control-flow rules. A barrier encountered by only an inappropriate subset of a workgroup can make the program invalid or produce undefined behavior.\n\nCoordination across an entire dispatch is more restricted. Portable programs generally cannot assume that all workgroups are resident or that an ordinary workgroup barrier synchronizes the whole grid. Algorithms requiring global phases commonly use multiple dispatches with API-level synchronization between them. Atomic operations coordinate accesses to selected memory locations, but an atomic increment is not automatically a complete synchronization mechanism for all surrounding data. Its ordering and visibility guarantees depend on the applicable memory model.\n\nCompute shaders are widely used for image processing, visibility determination, animation, particle systems, lighting preparation, and post-processing. They can also generate data later consumed by a rendering command, such as indirect draw parameters or compacted lists of visible objects. Keeping intermediate data on the GPU avoids some transfers to and from the central processing unit, although dependencies between compute and graphics work still require scheduling and synchronization.\n\nThe distinction between a compute shader and another GPU kernel is largely one of interface and ecosystem. CUDA and other compute systems expose their own programming models, libraries, and device capabilities. Compute shaders are attractive when computation is closely integrated with graphics resources or must operate through a particular cross-platform API. They do not inherently outperform specialized compute frameworks, and a workload’s suitability depends on parallelism, memory behavior, supported operations, and transfer costs."
    },
    {
      "heading": "Ray-tracing shaders and offline shading systems",
      "text": "Ray-tracing systems ask which scene objects intersect a ray and then use those results to evaluate visibility or light transport. Programmable ray-tracing pipelines divide responsibilities into stages that differ from rasterization stages. In APIs such as Direct3D Raytracing and Vulkan’s ray-tracing extensions, a ray-generation shader initiates tracing. A miss shader handles a ray that finds no accepted intersection, while hit-related shaders process candidate or selected intersections.\n\nA closest-hit shader commonly evaluates the material at the nearest accepted hit. An any-hit shader can examine candidate intersections and reject them, for example when a cutout texture indicates that part of a triangle is transparent. An intersection shader can implement intersection tests for procedural geometry represented through bounding volumes. Callable shaders provide another form of programmable organization. These interfaces are not interchangeable with ordinary function calls: the ray-tracing implementation manages traversal and dispatch according to the API’s rules.\n\nAcceleration structures reduce the number of geometric tests. A bounding volume hierarchy groups objects within nested bounds so that a ray can reject large portions of the scene. Hardware acceleration may assist traversal and triangle intersection, while shaders remain responsible for material behavior, procedural intersection logic, and ray-generation policy. Dynamic scenes introduce additional costs because their acceleration structures may need to be built, updated, or replaced.\n\nNot every ray-tracing operation requires a dedicated ray-tracing pipeline. Ray-query facilities allow suitable shaders to request and inspect traversal results within another stage, such as a compute or fragment shader. This supports hybrid renderers: rasterization can establish primary surface visibility, while selected rays estimate shadows, reflections, or ambient occlusion. The division of work is an implementation choice rather than a requirement that all rendering use one method.\n\nIn path tracing, shaders typically participate in repeatedly sampling scattering directions and updating a path’s contribution. The renderer must account for sampling probabilities, emission, visibility, and the accumulation of many noisy estimates. Material programs may return closures or structured descriptions of scattering rather than immediately calculating a final color. This allows the rendering system to choose how to sample and integrate the material.\n\nOffline shading languages consequently emphasize a different abstraction from many real-time fragment programs. Open Shading Language (OSL), developed at Sony Pictures Imageworks, supports renderer-oriented material descriptions and scattering closures. A closure describes a kind of light-scattering behavior that the renderer evaluates and samples. This separates artistic material construction from parts of the light-transport algorithm, although supported features and execution back ends still depend on the renderer."
    },
    {
      "heading": "Production workflows, correctness, and security",
      "text": "In production software, a shader is one component of a larger rendering system. Artists and technical directors may construct materials through node graphs; engine programmers define lighting models and resource conventions; tools generate variants and compile pipeline objects. A single visible material can require different programs for depth rendering, shadow maps, motion vectors, transparent rendering, and the main lighting pass. Consistency across these passes is essential: a deformed object whose shadow pass omits the deformation produces an incorrect shadow even if each individual shader compiles successfully.\n\nDebugging is complicated by massive parallelism and by the dependence on surrounding pipeline state. A black surface may result from a shader arithmetic error, an unbound resource, an incorrect vertex attribute, a failed depth test, or a format mismatch. Frame-capture tools expose draw calls, resource contents, and pipeline state; shader debuggers can inspect selected invocations where supported. Diagnostic outputs, such as displaying a normal as color or writing an invocation index, help isolate whether the failure lies in geometry, interpolation, resources, or lighting.\n\nNumerical correctness requires attention to exceptional inputs. Normalizing a zero-length vector, dividing by a vanishing value, or evaluating a function outside its intended domain can produce infinities or not-a-number values. Such values can spread through later image-processing passes. Visual correctness also has a temporal dimension: unstable sampling, discontinuous level-of-detail changes, or inconsistent motion information can cause flicker even when individual frames appear plausible. Automated tests may compare reference images with tolerances rather than demand identical bits across all hardware.\n\nShader workloads also create security concerns because applications can submit substantial programs to complex compiler and driver stacks. Web-facing graphics interfaces must treat these programs and their resource accesses as untrusted. Language validation, bounds-related rules, resource isolation, and sandboxing help limit what submitted code can do. Requirements vary by API; a guarantee provided by a web graphics environment should not be assumed for every native graphics interface.\n\nVery long-running or otherwise pathological workloads can interfere with display responsiveness or shared GPU use. Operating systems and device drivers therefore use scheduling, fault handling, and, in some environments, timeout-and-recovery mechanisms. Recovery may terminate a workload or invalidate a graphics device context rather than preserve normal application execution. These mechanisms are distinct from proving that a shader terminates or that its output is mathematically correct.\n\nReproducibility depends on retaining more than source text. Relevant information includes compiler versions, compilation options, generated intermediate modules, pipeline configuration, resource formats, and representative input data. A compiler update can alter instruction selection or expose assumptions in previously accepted code. Production build systems therefore track shader dependencies and compilation artifacts alongside ordinary application code, treating shader programs as executable software rather than merely as visual assets."
    }
  ],
  "links": [
    "graphics-processing-unit",
    "computer-graphics",
    "programming-language",
    "compiler",
    "ray-tracing",
    "rasterization",
    "matrix",
    "pixel",
    "bidirectional-reflectance-distribution-function",
    "physically-based-rendering",
    "application-programming-interface",
    "parallel-computing",
    "shared-memory",
    "image-processing",
    "central-processing-unit",
    "cuda",
    "sandbox-computer-security",
    "operating-system",
    "device-driver"
  ],
  "sources": [],
  "license": "https://creativecommons.org/licenses/by/4.0/"
}