[{"content":"Introduction Where did the player click? Did the bullet hit? Can the light reach this point? What does the camera see through this pixel? All of these are the same question: does this ray hit that shape, and where? This post puts the previous posts in the series to work to answer it:\nWhat a ray is, written with vectors How to test a ray against a circle (or a sphere) using a dot product and Pythagoras A tiny ray tracer: a picture made by firing one ray per pixel What Is a Ray? A ray is a half-line: it starts at a point, the origin, and goes on forever in one direction. With vectors, every point on it can be written as:\npoint(t) = origin + t × direction where t is how far along the ray you are (with a unit-length direction, t is the actual distance). t = 0 is the origin, t = 2 is two units along, and negative t would be behind the start, which doesn\u0026rsquo;t count. Asking \u0026ldquo;where does the ray hit the shape?\u0026rdquo; means finding the smallest positive t where point(t) is on the shape.\nHitting a Circle Here\u0026rsquo;s a neat way to test a ray against a circle with centre C and radius r, using only things from earlier posts. Drag the ray\u0026rsquo;s origin, its direction and the circle.\nTesting a ray against a circle\nShow the closest point Circle radius: The method:\nHow far along the ray is the centre? Take the vector from the origin to the centre and dot it with the (unit) direction. That\u0026rsquo;s the projection from the dot product post. Call it along. How close does the ray come to the centre? The point along units down the ray is the closest point to the centre (purple). Measure the distance from it to the centre (vector length). If it\u0026rsquo;s more than the radius, the ray misses. Where does it cross the edge? If it\u0026rsquo;s closer than the radius, the closest point, the centre and the hit point make a right-angled triangle. Pythagoras gives the distance from the closest point to the edge: √(r² − distance²). The ray enters at along minus that, and leaves at along plus it. The same steps work for a sphere in 3D without changing a thing: the vectors just have three numbers instead of two. Spheres are the classic first shape in every ray tracer for exactly this reason.\nOther shapes have their own tests. A ray against a flat plane, like a floor, is a single division, and a ray against a triangle is a plane test followed by the \u0026ldquo;which side of each edge\u0026rdquo; test from the cross product post.\nA Tiny Ray Tracer Now for the fun part. Put a camera somewhere, and fire one ray for each pixel of a (very small, one-row) picture, fanned out across its field of view. For each ray, find the nearest ball it hits and colour that pixel with the ball\u0026rsquo;s colour. Shade it darker where the ray strikes the surface at a glancing angle, using the dot product of the surface normal and the ray, just like Basic Lighting. The strip at the bottom is the result.\nA one-row ray tracer: one ray per pixel\nRays (pixels): Field of view: Drag a ball in front of another and it hides it in the picture, because each pixel takes the nearest hit. That\u0026rsquo;s a ray tracer\u0026rsquo;s version of the depth buffer. Raise the number of rays and the picture sharpens: more pixels, more rays.\nThis is the opposite of how the rest of this site draws things. Rasterisation starts from each triangle and asks \u0026ldquo;which pixels do you cover?\u0026rdquo;; ray tracing starts from each pixel and asks \u0026ldquo;what do you see?\u0026rdquo;. Ray tracing makes reflections and shadows natural (fire another ray towards the light: if it hits something first, the point is in shadow), but it\u0026rsquo;s far more work, which is why games long relied on rasterisation and now use ray tracing hardware for selected effects.\nUnder the hood Testing every ray against every triangle in a scene would be hopelessly slow: millions of rays times millions of triangles. Real ray tracers first group triangles into a tree of nested boxes, called a bounding volume hierarchy (BVH). A ray first tests the big boxes and only looks inside the ones it actually passes through, so it usually only has to test a handful of triangles. Modern graphics cards have dedicated ray tracing units that walk these trees and perform ray-box and ray-triangle tests in hardware, which is what made real-time ray traced reflections and shadows practical in games.\nWhere You\u0026rsquo;ll Use This Mouse picking: turn the clicked pixel into a ray from the camera (Cameras) and find what it hits. Games: bullets, line-of-sight checks, and keeping characters standing on the ground are all ray casts. Shadows and reflections in ray tracing; the shadow map is rasterisation\u0026rsquo;s answer to the same \u0026ldquo;can the light see it?\u0026rdquo; question. Ray marching, which steps along a ray using a distance function to find shapes made of pure maths (Signed Distance Fields). Summary A ray is origin + t × direction, for t ≥ 0. Ray hits circle or sphere: project the centre onto the ray (dot product), measure how close the ray comes, then use Pythagoras to find where it crosses the edge. The nearest positive t is the first hit. Ray tracing fires a ray per pixel and keeps the nearest hit: the reverse of rasterisation. That\u0026rsquo;s the end of Maths for Graphics, for now! These six ideas (vectors, dot and cross products, sine and cosine, lerp and rays) underpin almost everything else on the site.\nFurther Reading Peter Shirley and others, Ray Tracing in One Weekend: a famous free book that builds a real ray tracer step by step, starting with rays and spheres. Scratchapixel, A Minimal Ray-Tracer: ray-sphere intersection explained in detail. Jacco Bikker, How to build a BVH: how real ray tracers find hits quickly. ","permalink":"https://fragmentshack.com/posts/rays-intersections/","summary":"A ray is a starting point and a direction. Asking where it hits something powers mouse picking, bullets, shadows and ray tracing. Build a ray-circle test from what you already know, then trace a tiny picture.","title":"🎯 Rays and Intersections: Does This Line Hit That Shape?"},{"content":"Introduction So much of graphics is about blending: fading one colour into another, sliding an object from here to there, mixing four texels into one, smoothing an edge. Nearly all of it is built from one tiny formula called lerp, plus a few friends that reshape it. This post covers:\nLerp: blending between two values Inverse lerp and remapping: the same idea run backwards Clamp: keeping a value within limits Smoothstep and easing curves: making blends look natural Lerp: Blending Between Two Values Lerp is short for linear interpolation: finding a value part of the way between two others. You give it a start value a, an end value b, and an amount t from 0 to 1:\nlerp(a, b, t) = a + (b − a) × t At t = 0 you get a, at t = 1 you get b, at t = 0.5 you get exactly halfway, and so on in a straight line (\u0026ldquo;linear\u0026rdquo;). For example, lerp(10, 20, 0.25) = 10 + 10 × 0.25 = 12.5. In shader code it\u0026rsquo;s called mix.\nIt works on anything made of numbers. For a colour or a position, just lerp each number separately. Drag the orange point, or move the t slider, below.\nLerp between two numbers and between two colours\nt: a: b: Colour A Colour B (Blending colours like this is only physically correct on linear light values; sRGB and Gamma explains why, and why the middle of a red-to-green blend can look muddy.)\nYou\u0026rsquo;ve already met lerp many times on this site, under other names. Bilinear filtering is three lerps. Trilinear filtering is seven. The barycentric weights that blend values across a triangle (Fragment Shaders) are a three-way version of the same idea, and alpha blending is a lerp between the old colour and the new one, with α as t.\nInverse Lerp and Remapping Sometimes you need the opposite question: given a value, how far between a and b is it? That\u0026rsquo;s the inverse lerp:\nt = (value − a) ÷ (b − a) If a fog effect starts at 10 metres and is thickest at 50, an object at 20 metres is (20 − 10) ÷ (50 − 10) = 0.25 of the way in.\nPutting the two together gives remapping: converting a value from one range to another. Inverse-lerp it out of the first range to get t, then lerp into the second. \u0026ldquo;Turn a temperature from −10 to 40 into a colour from blue to red\u0026rdquo; is a remap; so is the step in coordinate spaces that turns −1 to +1 into 0 to 1280 pixels.\nClamp: Staying Within Limits Feed lerp a t below 0 or above 1 and it happily carries on past a or b (that\u0026rsquo;s called extrapolating). Often that\u0026rsquo;s wrong: you don\u0026rsquo;t want fog thicker than \u0026ldquo;fully foggy\u0026rdquo;. Clamping limits a value to a range: clamp(t, 0.0, 1.0) (the value, then the lowest and highest allowed) turns anything below 0 into 0 and anything above 1 into 1. Shaders do this constantly (HLSL calls the 0-to-1 version saturate).\nSmoothstep and Easing A plain lerp moves at a constant speed: it starts instantly, and stops dead. For animation and many visual effects that looks mechanical. Real things speed up and slow down. The fix is to reshape t before using it: feed t into a curve, and use the curve\u0026rsquo;s output as the amount to lerp by. These curves are called easing functions.\nThe most famous is smoothstep: t × t × (3 − 2t). It starts slowly, speeds up in the middle and slows down again at the end, and it\u0026rsquo;s built into every shading language (smoothstep(edge0, edge1, x) takes a value x and two edges: it gives 0 when x is at or below edge0, 1 at or above edge1, and the smooth curve in between; inside, it does an inverse lerp and clamp first, then applies the curve). Compare the curves below. The graph shows the curve, with time t going across and the eased amount going up, and its formula in the corner. The two balls race from left to right, one at constant speed and one eased. Drag the Time t slider, or drag across the graph or the plain ball\u0026rsquo;s track, to step through by hand: the readout shows the formula worked out with the numbers filled in.\nEasing curves, and a ball moving with each\nCurve Linear (no easing) Smoothstep Ease in Ease out Overshoot Bounce ▶ Play Time t: Ease in (t × t) starts slow and finishes fast, like something falling. Ease out starts fast and settles gently, like something sliding to a stop. User interfaces use this a lot. Overshoot goes slightly past the end and springs back. Its formula, 1 + 2.70158 × (t − 1)³ + 1.70158 × (t − 1)², looks fearsome but is just a curve built from (t − 1) multiplied by itself two and three times. At t = 1, (t − 1) is 0, so the curve ends exactly at 1. Just before that, the squared part (which is always positive) wins over the cubed part (which is negative there), pushing the value above 1 before it settles back. The number 1.70158 is chosen to make it overshoot by about 10%; bigger numbers overshoot further. Bounce imitates a ball landing. It\u0026rsquo;s made of four parabolas: the curved path anything takes when it\u0026rsquo;s thrown and falls under gravity. Each piece has the form 7.5625 × (t − centre)² + top: the first is a plain fall from 0 to 1 (the ball dropping), and each of the next three is a smaller, shorter dip that starts and ends at 1, falling back 0.25, then 0.0625, then about 0.016 below it (the ball bouncing back up, each time a quarter as high). Step the time slider through it and watch the readout say which bounce you\u0026rsquo;re in. In shaders, smoothstep is also the standard way to make a soft edge instead of a hard one: smoothstep(0.5, 0.52, distance), where distance is how far the pixel is from, say, the centre of a circle of radius 0.5, fades from 0 to 1 between 0.5 and 0.52 instead of jumping at 0.5. The fwidth and Signed Distance Fields posts use exactly this to anti-alias shapes.\nUnder the hood Lerp, written as a + (b − a) × t, is one subtraction and one fused multiply-add on a graphics card: about as cheap as maths gets. The interpolation of values across triangles is the same operation done in bulk, and blending, texture filtering and anti-aliasing all lean on dedicated hardware that performs lerps without your shader asking. One subtle point: for very large or very small numbers, a + (b − a) × t may not give exactly b at t = 1 because of rounding, so some libraries use the equivalent a × (1 − t) + b × t, which does.\nWhere You\u0026rsquo;ll Use This Colours and gradients: fades, skies, heat maps (Pixels and Colour). Texture filtering: bilinear and trilinear are lerps of texels (Texture Filtering, Mipmaps). Across triangles: barycentric interpolation is a three-way lerp (Fragment Shaders). Blending: transparency is a lerp with alpha (Alpha Blending). Animation: moving objects, cameras and user interfaces with easing; blending between animations. Soft edges: smoothstep for anti-aliasing shapes and fading effects in and out. Questions You Might Have Can you lerp rotations and directions? Lerping two unit directions gives a shorter-than-1 arrow in the middle and an uneven speed. For directions and rotations, slerp (spherical linear interpolation) moves round the circle at a constant speed instead. A plain lerp followed by normalize is a cheap, common approximation.\nSummary Lerp, a + (b − a) × t, blends from a (t = 0) to b (t = 1); shaders call it mix. Inverse lerp finds t for a value; remapping moves a value from one range to another. Clamp keeps values within limits. Easing curves such as smoothstep reshape t so blends start and stop smoothly. Further Reading Freya Holmér, The Beauty of Bézier Curves: how curves are built from repeated lerps. Andrey Sitnik and Ivan Solovev, easings.net: a gallery of easing curves, with formulas. The Book of Shaders, Shaping functions: smoothstep, mix and friends in shaders. Inigo Quilez, Remapping functions: more useful curves for shaders. ","permalink":"https://fragmentshack.com/posts/interpolation-lerp-smoothstep/","summary":"Blending smoothly from one value to another is everywhere in graphics: colours, positions, textures, animation. Meet lerp, its reverse, remapping, smoothstep and easing curves.","title":"🎚️ Interpolation: Lerp, Smoothstep and Easing"},{"content":"Introduction \u0026ldquo;Sine\u0026rdquo; and \u0026ldquo;cosine\u0026rdquo; sound like scary school maths, but in graphics they have a very friendly meaning: they\u0026rsquo;re the x and y of a point going round a circle. Whenever something rotates, orbits, bobs, waves or pulses, they\u0026rsquo;re doing the work. This post covers:\nMeasuring angles, in degrees and in radians What sine and cosine actually are, using a circle How they make rotation work How they make smooth waves for animation It builds on Coordinates and Vectors.\nAngles: Degrees and Radians You\u0026rsquo;re probably used to measuring angles in degrees: 90° is a right angle, 180° is a half turn, 360° is a full turn.\nMaths libraries and shaders almost always use radians instead. One radian is the angle you get when you walk around a circle a distance equal to its radius. A full turn is 2π radians (π, \u0026ldquo;pi\u0026rdquo;, is about 3.14159, so a full turn is about 6.28 radians). So:\n360° = 2π radians ≈ 6.28 180° = π radians ≈ 3.14 90° = π ÷ 2 radians ≈ 1.57 To convert, multiply degrees by π ÷ 180. Radians are used because they make the maths underneath simpler; for us, the only thing to remember is to convert before calling sin or cos, which expect radians.\nSine and Cosine: A Point on a Circle Imagine a circle with a radius of exactly 1, centred on the origin (called the unit circle). Start at the point (1, 0) on its right-hand edge, and walk anticlockwise round the circle by some angle. Where do you end up?\nYour x coordinate is the cosine of the angle, written cos(angle). Your y coordinate is the sine of the angle, written sin(angle). That\u0026rsquo;s the whole definition. The point below spins by itself. Drag it round the circle (or select it and use the arrow keys), or drag along the wave graph to pick an angle by its position; either one pauses the spin.\nA point going round the unit circle, and the sine wave it traces\n▶ Play Also show the cosine wave Some things to notice:\nAt 0°, the point is at (1, 0): cos is 1 and sin is 0. At 90°, it\u0026rsquo;s at the top, (0, 1). At 180°, (−1, 0). At 270°, the bottom, (0, −1). Both values always stay between −1 and 1, because the circle has radius 1. Because the point is always 1 from the centre, Pythagoras (vectors) says cos² + sin² = 1, always. As the point goes round and round, its height (sine) rises and falls smoothly, tracing the famous sine wave. Cosine traces exactly the same wave, just a quarter turn ahead. This also explains a puzzle from the dot product post: the dot product of two unit vectors is the cosine of the angle between them. Turn one of them so it lies along the x axis, and the dot product just picks out the other one\u0026rsquo;s x coordinate, which is the cosine of the angle.\nRotation To place something at a given angle and distance from a centre, use: (distance × cos(angle), distance × sin(angle)). That\u0026rsquo;s how objects are arranged in a ring, how a camera orbits a target, and how a clock hand works.\nRotating a whole shape uses the same idea. In Transformation Matrices, rotating sent the x axis to (cos θ, sin θ) and the y axis to (−sin θ, cos θ) (θ, \u0026ldquo;theta\u0026rdquo;, is a common name for an angle): those are just the points a quarter turn apart on the unit circle. The rotation matrix is two points on the unit circle, written in a grid.\nWaves Because sine goes up and down smoothly forever, it\u0026rsquo;s the perfect building block for anything that moves back and forth: bobbing, breathing, swaying, pulsing lights, water. Four numbers shape a wave:\nAmplitude: how tall it is (multiply the result) Frequency: how many waves fit in a given distance (multiply what goes in) Speed: how fast it travels (add time × speed to what goes in) Phase: where it starts (add a fixed angle) Shape the wave below. Across the picture, x goes from 0 at the left to 2π at the right: one full turn of the circle in radians. So with a frequency of 1, exactly one wave fits across; with 3, three waves. The grass at the bottom bends using the same formula.\nShaping a sine wave, and grass bending with it\n▶ Play Amplitude: Frequency: Speed: Phase: This is exactly the Wave preset in the Vertex Shaders editor: p.y += amount * sin(p.x * 4.0 + uTime * 2.0), where p is the vertex\u0026rsquo;s position, amount is the wave\u0026rsquo;s height (the amplitude), 4.0 is the frequency, and uTime is the time in seconds, so 2.0 is the speed. Adding a few sine waves of different sizes and speeds together gives convincing water.\nUnder the hood Graphics cards compute sin and cos with special hardware units that give a fast, slightly approximate answer, typically in one instruction (or a few) rather than the long calculation a maths library on the CPU might do. That\u0026rsquo;s accurate enough for animation and shading, but it\u0026rsquo;s why very large inputs (for example, a time value that has been counting up for days) can make waves go jittery: the angle loses precision as the number grows. Games usually keep time values small by wrapping them round.\nWhere You\u0026rsquo;ll Use This Rotation: rotation matrices are built from sin and cos (Transformation Matrices). Cameras: orbiting a target (Cameras) and field of view, which uses a related function called tangent. Animation in shaders: waves, wind, bobbing and pulsing (Vertex Shaders, Fragment Shaders). Lighting: the dot products in Basic Lighting are cosines of angles. Circles and patterns: anything round, spiral or radial in a shader (Signed Distance Fields). Questions You Might Have What about tan? Tangent is sine divided by cosine: the slope of the line from the centre to the point (how far up per step across). Graphics uses it less than sine and cosine, mostly to turn a field-of-view angle into a size, as the perspective matrix does.\nSummary Angles can be measured in degrees (360 per turn) or radians (2π ≈ 6.28 per turn); code usually wants radians. On a circle of radius 1, a point at an angle is at (cos, sin). Both stay between −1 and 1, and cos² + sin² = 1. Sine and cosine give rotation, orbits and smooth waves. Further Reading Maths Is Fun, Sine, Cosine and Tangent and Radians: clear introductions with diagrams. Freya Holmér, Math for Game Devs: a free lecture series on her channel on exactly this kind of maths, with game examples. The Book of Shaders, Shaping functions: using sin and friends to shape patterns in shaders. ","permalink":"https://fragmentshack.com/posts/sine-cosine-angles/","summary":"Sine and cosine are just the x and y of a point going round a circle. That simple idea gives you rotation, smooth waves, orbits and animation. Spin the point and shape a wave.","title":"〰️ Angles, Sine and Cosine: Going Round in Circles"},{"content":"Introduction The dot product turned two vectors into a single number. The cross product turns two vectors into a new vector: one that points at right angles to both of them. In 3D graphics that\u0026rsquo;s exactly what you need to work out which way a triangle faces, and it turns up in a surprising number of other places too. This post covers:\nWhat the cross product gives you, and the right-hand rule for which way it points What its length means (an area!) The simple 2D version, which tells you which side of a line a point is on Where graphics uses both Two Arrows In, One Arrow Out Take two arrows, a and b, that start at the same point. Unless they\u0026rsquo;re parallel, they lie in a flat surface together, like two pencils lying on a table. There\u0026rsquo;s exactly one direction that\u0026rsquo;s at right angles to both: straight up out of the table (or straight down into it). The cross product, written a × b, gives you an arrow in that direction.\nDrag the scene to look around it in 3D, and change the arrows with the sliders.\nTwo vectors (orange and purple) and their cross product (blue)\nSwap the order Show the parallelogram Angle between them: Tilt purple up: Orange length: Purple length: Things to try:\nTurn the scene so you\u0026rsquo;re looking straight down the blue arrow: the orange and purple arrows are both flat across your view, at right angles to it. Set the angle to 0° or 180°. The arrows are parallel, they don\u0026rsquo;t define a flat surface any more, and the cross product shrinks to nothing. Press Swap the order. b × a points the opposite way to a × b. Unlike ordinary multiplication, the order matters. Which way does it point? The right-hand rule \u0026ldquo;At right angles to both\u0026rdquo; leaves two choices: up or down. The convention is the right-hand rule: point the fingers of your right hand along a, curl them towards b, and your thumb points along a × b. Swap a and b and you have to curl the other way, so your thumb flips over. (In a left-handed coordinate system, as Matrix Conventions explains, the arrow still comes out of the same calculation, but it looks as if it follows your left hand instead.)\nIts length is an area The two arrows make a slanted rectangle called a parallelogram (shown in green). The cross product\u0026rsquo;s length equals that shape\u0026rsquo;s area. When the arrows are at right angles it\u0026rsquo;s as big as it can be; as they swing towards each other the parallelogram squashes flat and the area, and the arrow, shrink to zero. Half of it is the area of the triangle the two arrows make, which is useful in its own right.\nThe calculation For completeness, here\u0026rsquo;s how it\u0026rsquo;s worked out from the numbers. You don\u0026rsquo;t need to memorise it; every maths library and shading language has it built in (cross in GLSL):\na × b = (aybz − azby, \u0026nbsp;azbx − axbz, \u0026nbsp;axby − aybx) Each part uses the other two axes: the x part only involves y and z, and so on. Six multiplications and three subtractions.\nIn 2D: Which Side of the Line? In 2D there\u0026rsquo;s no third direction to point in, but the last part of that formula, axby − aybx, is still very useful on its own. Its sign tells you which way you turn to get from a to b: positive for anticlockwise (to the left), negative for clockwise (to the right), zero if they\u0026rsquo;re in a straight line.\nThat means it can tell you which side of a line a point is on. Take the line\u0026rsquo;s direction as one vector and the direction from the line\u0026rsquo;s start to the point as the other. Drag the edge\u0026rsquo;s ends and the point below.\nThe 2D cross product: which side of an edge is a point on?\nThis little test is the edge function that graphics cards use billions of times a second to decide which pixels a triangle covers: a pixel is inside if it\u0026rsquo;s on the inner side of all three edges (Rasterisation). Test the third corner of a triangle against its first edge and you get the triangle\u0026rsquo;s winding order, which decides whether it faces you (Vertices, Triangles and Meshes).\nUnder the hood Graphics cards don\u0026rsquo;t have a special cross product instruction. The compiler turns cross into a handful of multiply-and-subtract steps, which is cheap enough to do per pixel. The 2D version, though, is effectively built into the hardware: the rasteriser evaluates three of them, one per triangle edge, for every pixel it considers. Because the answer changes by a fixed amount from one pixel to the next, the hardware can step across the screen with just additions.\nWhere You\u0026rsquo;ll Use This Surface normals: the cross product of two edges of a triangle points straight out of it. Normalise it (vectors) and you have the triangle\u0026rsquo;s normal, ready for lighting. The flat shading trick does exactly this, per pixel. Camera axes: a \u0026ldquo;look-at\u0026rdquo; camera finds its right and up directions with two cross products (Cameras). Tangent space: the third axis of a normal map\u0026rsquo;s frame comes from a cross product (Normal Mapping). Inside or outside, and winding: the 2D version decides which pixels a triangle covers and which way it faces. Physics: spinning and turning forces (torque) are cross products. Questions You Might Have Is there a cross product in 2D or 4D? The arrow-producing cross product is special to 3D (a similar one exists only in 7D). In 2D, the version shown in this post gives a single number instead, which is still very useful for telling left from right.\nSummary The cross product a × b is a vector at right angles to both a and b. The right-hand rule gives its direction; swapping a and b flips it. Its length is the area of the parallelogram a and b make (zero if they\u0026rsquo;re parallel). In 2D, axby − aybx tells you which side of a line a point is on. Further Reading 3Blue1Brown, Cross products: an animated explanation of why the length is an area. Maths Is Fun, Cross Product: worked examples and the right-hand rule. Fletcher Dunn and Ian Parberry, 3D Math Primer: Vector Multiplication: cross products in games, in depth. ","permalink":"https://fragmentshack.com/posts/cross-product/","summary":"Give the cross product two directions and it hands back a third, at right angles to both. It\u0026rsquo;s how graphics finds which way a triangle faces, which side of a line a point is on, and how cameras get their axes.","title":"✖️ The Cross Product: Finding the Direction at Right Angles"},{"content":"Introduction If graphics programming had a favourite calculation, it would be the dot product. It takes two vectors (the previous post) and gives back a single number that says how much they point the same way. Lighting, shadows, cameras, game AI and physics all lean on it. This post covers:\nHow to calculate a dot product (it\u0026rsquo;s easy) What the answer means, especially for unit vectors The projection: \u0026ldquo;how far does this arrow go in that direction?\u0026rdquo; A practical example: can a guard see the player? How to Calculate It The dot product of two vectors is written with a dot: a · b. To work it out, multiply the matching numbers together and add up the results:\na · b = ax × bx + ay × by \u0026nbsp;\u0026nbsp;(and + az × bz in 3D) For example, (3, 1) · (2, 4) = 3 × 2 + 1 × 4 = 6 + 4 = 10. The answer is a single number, not a vector. That\u0026rsquo;s all the arithmetic there is. In shader code it\u0026rsquo;s the dot function.\nWhat It Means The magic is in what that number tells you. Drag the tips of a and b below.\nThe dot product of two vectors, and b’s “shadow” along a\nMake both unit vectors (length 1) Watch the sign of the answer:\nPositive when the arrows point roughly the same way (less than 90° apart). Zero when they\u0026rsquo;re exactly at right angles. Negative when they point roughly opposite ways (more than 90° apart). That sign alone answers questions like \u0026ldquo;is this surface facing the light?\u0026rdquo; and \u0026ldquo;is that object in front of me or behind me?\u0026rdquo;.\nFor unit vectors, it\u0026rsquo;s the angle Tick Make both unit vectors. Now the answer always lies between −1 and 1: exactly 1 when they point the same way, 0 at right angles, −1 when opposite, and smoothly in between. This number is called the cosine of the angle between them (the next-but-one post explains cosines properly), but you don\u0026rsquo;t need to know that to use it: think of it as an \u0026ldquo;agreement score\u0026rdquo; from −1 to 1.\nThat\u0026rsquo;s why graphics normalises directions so often: with unit vectors, one dot product gives you a ready-made measure of how closely two directions line up, with no angles involved.\nThe projection: \u0026ldquo;how far along?\u0026rdquo; Untick the box and look at the green arrow. It shows b\u0026rsquo;s shadow along a\u0026rsquo;s direction, as if a light were shining straight down onto the line through a. Its length is how far b reaches in the direction of a. When a is a unit vector, that length is exactly a · b. (Otherwise, divide by the length of a.)\nThis is one of the most useful tricks in geometry. \u0026ldquo;How fast is the car moving forwards?\u0026rdquo; is the car\u0026rsquo;s velocity projected onto its forward direction. \u0026ldquo;How high above the floor is this point?\u0026rdquo; is the point projected onto the floor\u0026rsquo;s upward direction.\nA Practical Example: Can the Guard See You? A guard is looking in a direction (the blue arrow; drag its tip), with a field of view: a cone in which it can see. Drag yourself (the circle) around, or drag the guard itself.\nA field-of-view check using one dot product\nField of view: The test is: make a unit vector for the way the guard faces, and a unit vector from the guard towards you, then take their dot product. If it\u0026rsquo;s bigger than a threshold (worked out once from the field of view), you\u0026rsquo;re in the cone. No angles, no trigonometry: three multiplications, two additions and a comparison, which a game can afford to do for hundreds of guards every frame.\nUnder the hood Dot products are so common that graphics cards are built to do them fast: a dot product is just a chain of multiply-and-add steps, which every shader core can do in a single instruction each. A typical fragment shader for lighting might do a dozen of them per pixel. The same operation is at the heart of matrix multiplication: each number in the result of matrix × vector is the dot product of one row of the matrix with the vector (Transformation Matrices). It\u0026rsquo;s also the core operation of modern AI chips, which do enormous numbers of dot products every second.\nWhere You\u0026rsquo;ll Use This Lighting: how much light a surface receives is N · L, the dot product of its normal with the direction to the light (Basic Lighting); shiny highlights use another one. Facing and culling: whether a surface faces towards or away from the camera. Shadows and edges: shadow mapping bias is often scaled by a dot product; outline effects use one to find edges facing sideways to the camera. Matrices: every number in a matrix multiplication is a dot product (Transformation Matrices). Games: field-of-view checks, \u0026ldquo;is the target in front of me?\u0026rdquo;, splitting a velocity into forwards and sideways parts. Questions You Might Have Does the order matter in a dot product? No: a · b = b · a, because it just multiplies matching parts and adds them up, and multiplication doesn\u0026rsquo;t care about order. (The cross product is different: swapping its order flips the answer.)\nSummary To find a · b, multiply matching numbers and add: axbx + ayby + azbz. Positive = same-ish direction, zero = right angles, negative = opposite-ish. For unit vectors, it\u0026rsquo;s an agreement score from −1 to 1 (the cosine of the angle). With a unit vector, a · b is how far b reaches in a\u0026rsquo;s direction (the projection). Next: the cross product, which finds the direction at right angles to two others.\nFurther Reading 3Blue1Brown, Dot products and duality: the deeper reason the dot product works. Maths Is Fun, Dot Product: worked examples, step by step. Fletcher Dunn and Ian Parberry, 3D Math Primer: Vector Multiplication: the dot and cross products for games, in depth. ","permalink":"https://fragmentshack.com/posts/dot-product/","summary":"One tiny calculation, three multiplications and two additions, answers \u0026lsquo;do these point the same way?\u0026rsquo;. It\u0026rsquo;s behind lighting, field-of-view checks and much more. Drag two arrows and see.","title":"⚫ The Dot Product: How Much Do Two Directions Agree?"},{"content":"Introduction Almost every number a graphics card works with describes either where something is or which way something points: the corner of a triangle, the direction of the sun, the way a surface faces. The maths for both is the same, and it\u0026rsquo;s surprisingly gentle. This post, the first in the Maths for Graphics series, covers:\nCoordinates: describing a position with a few numbers Vectors: the same numbers thought of as a movement or direction The four things you\u0026rsquo;ll do with vectors constantly: add, subtract, scale and measure them Unit vectors: arrows exactly 1 long, which graphics uses everywhere for directions You don\u0026rsquo;t need any maths beyond adding and multiplying. The series can be read on its own, or alongside Graphics Fundamentals, which uses all of this.\nCoordinates: Where Is It? Picture a sheet of graph paper with two lines drawn through the middle: one going across, called the x axis, and one going up, called the y axis. The point where they cross is the origin. Any point on the paper can be described by two numbers: how far across from the origin (x) and how far up (y). We write them in brackets, x first: (3, 2) means 3 across and 2 up. Negative numbers go the other way: (−1, −2) is 1 to the left and 2 down.\nThose two numbers are the point\u0026rsquo;s coordinates. Drag the orange point and watch them change.\nA point and its coordinates\nShow the arrow from the origin 3D works exactly the same way with one more axis, z, for forwards and backwards, so a point needs three numbers: (x, y, z). Every corner of every triangle in a game is stored like this (Vertices, Triangles and Meshes).\nVectors: Which Way, and How Far? Now look at the dashed arrow from the origin to the point. It describes a movement: \u0026ldquo;go 3 across and 2 up\u0026rdquo;. An arrow like this is called a vector, and it\u0026rsquo;s written with exactly the same numbers: (3, 2).\nThe difference between a point and a vector is only in how you think about them:\nA point is a place: \u0026ldquo;the tree is at (3, 2)\u0026rdquo;. A vector is a movement or direction: \u0026ldquo;walk 3 across and 2 up\u0026rdquo;, from wherever you are. You can slide the arrow anywhere on the paper and it\u0026rsquo;s still the same vector. Graphics uses vectors for directions (which way the light shines, which way a surface faces), for movements (how far a character walks this frame), and for the difference between two points (the arrow from the camera to an object).\nDoing Things with Vectors Choose an operation below and drag the tips of the arrows a (orange) and b (purple).\nAdding, subtracting, scaling and measuring vectors\nOperation Add: a + b Subtract: b − a Scale: k × a Length, and unit vector Scale k: Adding To add two vectors, add their matching numbers: (3, 1) + (1, 2.5) = (4, 3.5). In pictures, it means doing one movement and then the other: put the tail of b on the tip of a, and the sum goes from the start to wherever you end up. Moving an object is exactly this: its new position = its old position + the movement.\nSubtracting b − a is the arrow that goes from a to b. That\u0026rsquo;s one of the most useful facts in graphics. The direction from a surface to a light is \u0026ldquo;light position − surface position\u0026rdquo;. The arrow from the camera to an object is \u0026ldquo;object − camera\u0026rdquo;. One edge of a triangle is \u0026ldquo;one corner − another corner\u0026rdquo;.\nScaling Multiplying a vector by a single number (graphics programmers call a single number a scalar) multiplies each of its numbers: 2 × (3, 1) = (6, 2). The arrow keeps its direction but gets longer or shorter. A negative number turns it round.\nLength How long is the arrow (3, 4)? It\u0026rsquo;s the long side of a right-angled triangle whose other sides are 3 and 4, so Pythagoras\u0026rsquo; theorem gives the answer: square the numbers, add them, and take the square root. √(3² + 4²) = √(9 + 16) = √25 = 5. In 3D, just add the third number in too: length = √(x² + y² + z²). The distance between two points is the length of the vector between them.\nUnit vectors A unit vector is one whose length is exactly 1. To turn any vector into one, divide it by its own length; this is called normalising it, and in shader code it\u0026rsquo;s the normalize function. Choose Length, and unit vector in the demo: however you drag a, its unit vector always ends on the dashed circle of radius 1.\nWhy bother? Because often only the direction matters, not the length. If every direction has length 1, maths that compares directions becomes much simpler, as the next post shows. All the lighting directions in Basic Lighting, and every normal (Normal Mapping), are unit vectors.\nUnder the hood Graphics cards are built around vectors. A shading language has vector types (vec2, vec3, vec4 in GLSL), and adding two vec4s is written as a single +. Much hardware historically worked on four numbers at once for exactly this reason. Modern graphics cards mostly work one number at a time but on many pixels in parallel (How GPUs Run Shaders), and the compiler splits vector maths up for you. Square roots are relatively slow, so the hardware has a fast instruction for \u0026ldquo;1 ÷ square root\u0026rdquo;, which is exactly what normalize needs: multiply the vector by 1 ÷ its length.\nWhere You\u0026rsquo;ll Use This Every vertex is a point: (x, y, z) (Vertices, Triangles and Meshes). Moving and placing objects is adding vectors; transformation matrices package it up with rotating and scaling. Directions for lighting, the camera and surfaces are unit vectors made by subtracting points and normalising (Basic Lighting, Cameras). Distances (how far is the player from the enemy? which object is nearest?) are vector lengths. Physics, animation and AI in games all use the same vectors for positions, velocities and forces. Questions You Might Have Does the order of adding vectors matter? No: a + b gives the same answer as b + a, just like adding numbers. Walking 3 right then 2 up ends in the same place as 2 up then 3 right. Subtracting is different: a − b points the opposite way to b − a.\nSummary Coordinates describe a position: (x, y) in 2D, (x, y, z) in 3D. A vector is the same numbers as a movement or direction; it can sit anywhere. Add and subtract number by number; b − a is the arrow from a to b. Scaling multiplies every number; length comes from Pythagoras: √(x² + y² + z²). A unit vector has length 1; dividing by the length (normalising) makes one. Further Reading 3Blue1Brown, Vectors, what even are they?: a beautifully animated introduction. Maths Is Fun, Vectors: a friendly explanation with worked examples. LearnOpenGL, Transformations: Vectors: vectors from a graphics programmer\u0026rsquo;s point of view. Fletcher Dunn and Ian Parberry, 3D Math Primer for Graphics and Game Development: a whole free book on this series\u0026rsquo; topics. ","permalink":"https://fragmentshack.com/posts/vectors-coordinates/","summary":"Nearly every number in graphics is a position or a direction. Learn what coordinates and vectors are, and how to add, subtract, scale and measure them, by dragging arrows around.","title":"🧭 Coordinates and Vectors: Arrows That Describe Space"},{"content":" Introduction In ddx and ddy Explained we saw that the graphics card works out ddx and ddy by running fragment shaders (Direct3D’s pixel shaders) in 2×2 groups of neighbouring pixels and subtracting their values, and parts 2 and 3 of those posts, in the Shader Techniques series, showed what that makes possible. This post covers the catch: a few rules you need to follow, and the hidden extra work the 2×2 groups cause, called helper pixels. The demo at the end shows where helper pixels run, using your own graphics card.\nThings to Watch Out For Careful inside if statements. All four pixels in a group must reach ddx together, because they need each other’s values. If an if (or a loop) sends some pixels of a group one way and the rest another, the result is undefined: it may be garbage, and some compilers refuse to compile it. This applies to normal texture reads too, because they use ddx and ddy behind the scenes. Work out ddx and ddy (and do your texture reads) before the if, or use SampleGrad/textureGrad or SampleLevel/textureLod inside it. They’re measured in pixels of the image being drawn. The same object gives different answers at a different resolution or distance. That’s usually exactly what you want, but remember it when you compare against fixed numbers. Mainly in fragment shaders. Vertex shaders don’t run in 2×2 groups, so ddx and ddy aren’t available there. (DirectX 12 with Shader Model 6.6, and Vulkan with an extension, also allow them in compute shaders (general-purpose programs that run on the graphics card without drawing anything), which then arrange their threads into 2×2 groups.) Answers are shared. As the demos in part 1 showed, both pixels in a pair get the same answer, and a coarse derivative can share one answer across all four. They’re an estimate, not an exact per-pixel value, and they can miss or misplace sudden changes, as the edge demos showed. The 2×2 groups cost extra work. The graphics card often has to run the fragment shader for pixels that are never drawn, so that the drawn ones have neighbours to subtract from. These are called helper pixels, and the next section covers them. Helper Pixels Because fragment shaders always run in 2×2 groups, the graphics card has a problem whenever only some of a group’s four pixels need drawing. The other pixels are still needed, because ddx and ddy need their values to subtract, so the graphics card runs the fragment shader for them anyway. These extra copies are called helper pixels (HLSL calls them helper lanes, and GLSL calls them helper invocations). A helper pixel runs the shader’s instructions like any other pixel, but everything it produces is thrown away: it never changes the image, and any writes it makes to memory are ignored.\nHelper pixels turn up in more places than you might expect:\nAlong every edge of every triangle. Any 2×2 group that a triangle’s edge cuts through is only partly covered, and the uncovered pixels in it run as helpers. This happens for big triangles too, but a big triangle also has lots of fully covered groups in its middle, so the extra work is small in comparison. The smaller or thinner a triangle is, the more of its groups sit on an edge. A triangle that covers a single pixel runs the shader four times, three of them as helpers. Where triangles meet. A mesh is made of triangles that share edges, and the graphics card handles each triangle separately. A 2×2 group split by a shared edge runs once for each triangle that touches it, so its four pixels can cost eight or more runs of the shader, and many of those are helpers. Where a triangle is partly hidden. Graphics cards normally test depth before running the fragment shader (an early depth test), so pixels hidden behind something already drawn can be skipped. But if a group has some visible and some hidden pixels, the hidden ones still run, as helpers for the visible ones. (If a shader writes its own depth value, and in some cases if it uses discard, the depth test has to wait until after the shader, and hidden pixels then run in full.) After discard. A shader can throw away its pixel part-way through with discard (or clip in HLSL), for example to cut out the see-through parts of a leaf texture. In DirectX, a discarded pixel carries on running as a helper, so that its neighbours’ ddx and ddy still work. Vulkan, and OpenGL with an extension, offer the same thing as demote. In plain OpenGL and WebGL, don’t rely on ddx and ddy after some pixels in a group have discarded. Helper pixels take real time on the graphics card, which is one reason why lots of tiny or long, thin triangles are slow to draw. A shader can check whether it’s running as a helper with IsHelperLane() in HLSL (added in Shader Model 6.6), or gl_HelperInvocation in GLSL (OpenGL 4.5, OpenGL ES 3.1 and Vulkan). WebGL2 is based on OpenGL ES 3.0, so it has neither.\nSeeing Helper Pixels WebGL doesn’t let you look at helper pixels directly: everything they produce is thrown away, and a WebGL2 shader can’t ask “am I a helper?”. So the demo below works them out in two steps.\nIt draws some triangles on your graphics card at a tiny 32×20 resolution, then reads back which pixels each triangle actually drew, after the depth test. Each triangle’s drawn pixels are shown in its own colour. Every other pixel in a 2×2 group that a triangle drew into must have run as a helper for that triangle. Those pixels are striped, and on wider screens a number shows how many times each one ran as a helper. A striped pixel can also have a colour: it was drawn by one triangle and ran as a helper for another. For proof, tick Show proof. Every copy of this demo’s shader, drawn pixel or helper, also works out whether its own pixel centre is inside its triangle: 1 if it is, 0 if it isn’t. A drawn pixel is always inside, so if its ddx or ddy of that number isn’t 0, the 0 must have come from a pixel in its group that is outside the triangle and really did run: a helper pixel. Those drawn pixels get a dot. If your graphics card uses coarse derivatives, a whole group shares one answer, so dots appear on whole groups. The proof can’t see helpers caused by the depth test, because those pixels are inside their triangle. Where helper pixels run, worked out on your graphics card\nScene One big triangle A mesh of triangles Long, thin triangles A triangle partly hidden Mesh triangle size: Outline the 2×2 groups Show triangle edges Show proof Things to try:\nOne big triangle. Helpers run all the way along its edges, even though the triangle is large. A mesh of triangles. Shrink the triangles with the slider and watch the extra work climb. Pixels along shared edges are drawn by one triangle and run as helpers for its neighbours. Long, thin triangles. Almost every group they touch sits on an edge, so they’re very wasteful for the few pixels they draw. A triangle partly hidden. The small front triangle is drawn first. When the big triangle behind it is drawn, its pixels hidden behind the front triangle are skipped, except in groups that also have visible pixels: those hidden pixels run as helpers, along the front triangle’s edges. The demo assumes each triangle’s 2×2 groups are handled separately, which is the standard way graphics cards are described as working. Some graphics cards have tricks to cut down the waste, so real numbers can be lower.\nUnder the hood Each helper pixel takes up a lane in a group of 32 or 64 shader copies, exactly like a real pixel (How GPUs Run Shaders), so a group full of partly covered 2×2 groups does much less useful work than its size suggests. Games keep an eye on this: Unreal Engine, for example, has a Quad Overdraw view that colours the screen by how many times each 2×2 group was shaded. It’s also one reason games swap distant objects for simpler versions with fewer, larger triangles (levels of detail): bigger triangles fill more of their 2×2 groups.\nQuestions You Might Have Can I switch helper pixels off? No. Graphics cards always shade pixels in 2×2 groups, because that’s how they work out ddx, ddy and the mipmap level for every texture read. What you can control is how many are wasted: fewer, larger triangles mean fewer partly covered groups.\nSummary Work out ddx, ddy and ordinary texture reads before any if that could split a 2×2 group, or use the versions that take your own derivatives or mip level. Derivatives are measured in pixels of the image being drawn, are mainly available in fragment shaders, and are shared estimates rather than exact per-pixel values. Helper pixels are extra fragment shader runs for the uncovered pixels of partly covered 2×2 groups. Their results are thrown away. They appear along triangle edges, where triangles meet, where a triangle is partly hidden and after discard, so small and thin triangles cost the most. Further Reading Fabian Giesen, A trip through the Graphics Pipeline, part 8: how graphics cards really run fragment shaders in 2×2 groups, and why small triangles are expensive. Microsoft, ddx: the HLSL reference page. Khronos, gl_HelperInvocation: the GLSL reference page for checking whether a shader is running as a helper. ","permalink":"https://fragmentshack.com/posts/helper-pixels-ddx-ddy/","summary":"The rules for using ddx and ddy safely, and helper pixels: the extra, invisible fragment shader runs that 2×2 groups need. See them on your own GPU.","title":"👻 Helper Pixels: The Hidden Cost of ddx and ddy"},{"content":" Introduction Part 2 used ddx and ddy to pick mip levels and smooth edges. This post uses them on a pixel’s position to work out which way its triangle faces, giving flat shading with no extra data in the mesh, then rounds up a few more uses. It helps to have read Basic Lighting and The Cross Product.\nMaking a Normal from ddx and ddy Lighting needs a normal: a direction pointing straight out of the surface. Usually a normal is stored with each corner (vertex) of the mesh and blended across each triangle, which makes the surface look smooth.\nYou can also make one from ddx and ddy. Pass the 3D position of each vertex (for example in world space) from the vertex shader to the fragment shader, so each pixel knows its own position on the triangle. ddx(position) is how that position changes one pixel to the right, and ddy(position) is how it changes one pixel down. All four pixels of a group are worked out on the same flat triangle, so both of those directions lie flat along the triangle. (Where a group hangs over the triangle’s edge, the pixels outside it are worked out as if the triangle carried on; these are the helper pixels covered in their own post.) The cross product of two directions (a standard maths function in every shading language) gives a direction at right angles to both, which is the triangle’s own normal, in the same space as the position:\nfloat3 flatNormal = normalize(cross(ddx(position), ddy(position))); Depending on your coordinate conventions, this can point into the surface instead of out of it. If it does, swap the two arguments or negate the result. The demo below simply flips it whenever it points away from the camera.\nThis gives a faceted, low-poly look with no extra data in the mesh at all. Try it below, and change the detail to see how it behaves with more or fewer triangles. The last two options show the direction of ddx and ddy of the position as colours. Each colour changes only slightly across a triangle (because of perspective, the direction of a one-pixel step varies a little across the triangle), but both directions always lie flat along the triangle, so the normal made from them is the same everywhere on it.\nSmooth normals compared with flat normals made from ddx and ddy\nSmooth normalsFlat, from ddx/ddy Show Side by side Smooth normals Flat normals from ddx/ddy ddx(position) as colour ddy(position) as colour ▶ Play Detail: Other Uses Bump mapping without tangents: ddx and ddy of a height read from a texture, together with ddx and ddy of the position, are enough to tilt the normal and fake bumps, without the extra tangent directions (see Normal Mapping) normally stored in the mesh. Cheap edge detection: a large ddx or ddy of depth or colour suggests an edge. Because of the fixed pairs, this only sees edges between the two pixels of a pair, so proper outlines usually use a separate pass instead. Fading out detail: when ddx and ddy of a pattern’s coordinates are large, its details are smaller than a pixel, so you can fade them out before they shimmer. Under the hood There’s another way to get flat shading. GLSL’s flat qualifier (nointerpolation in HLSL) switches off blending for an output, so every pixel of a triangle gets the value from just one of its corners, the provoking vertex. But that needs a normal stored per face, so corners shared by several faces must be stored several times, making the mesh bigger. The ddx/ddy version needs no mesh changes and costs two derivatives and a cross product per pixel, which is cheap on modern graphics cards.\nQuestions You Might Have Why would a game want flat shading? Mostly for style: the faceted, low-poly look is popular in stylised games. It’s also handy for debugging, because it shows exactly where the triangles are, and for meshes that are generated on the fly, such as terrain, where computing smooth normals would take extra work.\nSummary ddx and ddy of the position are two directions lying flat along the triangle. Their cross product is the triangle’s own normal, giving flat, faceted lighting with no extra mesh data. Derivatives also help with bump mapping, edge detection and fading out detail before it shimmers. All of these uses rely on the graphics card running fragment shaders in 2×2 groups, and that has a cost. Helper Pixels, in the GPU Performance series, covers the things that can catch you out and the hidden extra work involved.\nFurther Reading Khronos, dFdx and dFdy: the GLSL reference page. Microsoft, Struct type (HLSL): includes the table of interpolation modifiers, such as nointerpolation. Inigo Quilez, Filtering procedural textures: using derivatives to stop maths-generated patterns from shimmering. ","permalink":"https://fragmentshack.com/posts/flat-shading-ddx-ddy/","summary":"Build each triangle\u0026rsquo;s normal in the fragment shader from ddx and ddy of its position: a faceted, low-poly look with no extra mesh data. Plus more uses for derivatives.","title":"💎 Flat Shading with ddx and ddy: Normals from Nowhere"},{"content":" Introduction Part 1 showed that ddx and ddy tell you how much a value changes from one pixel to the next. This post covers the two uses you’re most likely to meet: picking mipmap levels and smooth edges with fwidth. Part 3 adds flat shading and a few more.\nPicking the Right Texture Size (Mipmaps) This is the most common use. Every time a shader reads a texture with texture() in GLSL or Texture.Sample() in HLSL, the graphics card quietly works out ddx and ddy of the texture coordinate.\nAs Mipmaps and Trilinear Filtering showed, a distant texture shimmers unless the graphics card reads a smaller, pre-averaged copy of it (a mip level: level 0 is full size, each level after it half the width and height). To pick the level, it needs to know how many texels one pixel covers, and that’s what ddx and ddy of the texture coordinate tell it, once they’re multiplied by the texture’s size in texels.\nIt takes whichever is longer: the distance through the texture for one pixel step to the right (from ddx) or for one pixel step down (from ddy). If that distance is 1 texel or less, it uses level 0. Every time the distance doubles, it goes up one level: 2 texels gives level 1, and 4 texels gives level 2, a copy a quarter of the width and height, where one pixel step covers about one texel again. In-between distances give in-between levels such as 1.5, and trilinear filtering blends the two nearest levels. (This is the standard rule from the OpenGL specification. Graphics cards may approximate it slightly, and anisotropic filtering refines it for surfaces seen at a steep angle.)\nIn the demo below, the left half ignores ddx and ddy and always reads level 0. The right half reads the texture normally, with trilinear filtering. Watch the far distance, then hover over or tap the floor to see the numbers. Change Show to Mip level colours to see which level is used where (worked out in the shader with the rule above): red is level 0, each colour after it the next level, and colours in between a blend of two.\nThe mip level a texture read picks, with and without ddx and ddy\nIgnoring ddx/ddyUsing ddx/ddy (normal) Show Side by side Ignoring ddx/ddy (always full size) Using ddx/ddy (normal) Mip level colours ▶ Play Camera tilt: Texture repeats: Mip level: 0 (256×256) 1 (128) 2 (64) 3 (32) 4 (16) 5 (8) 6 (4) 7 and 8 (2 and 1) Tilt the camera down and you see more of the floor close to the camera, where each pixel covers fewer texels, so more of the picture uses level 0. Add more texture repeats and each pixel covers more texels, so higher levels are used. To take control yourself, HLSL’s SampleGrad and GLSL’s textureGrad take your own ddx and ddy values, and HLSL’s SampleLevel and GLSL’s textureLod take a mip level directly.\nSmooth Edges at Any Size with fwidth Shaders often draw shapes with maths rather than textures: circles, lines, grids, text and user interface elements. A common technique works out the distance from the pixel’s centre to the shape’s edge, negative inside and positive outside (a signed distance; see Signed Distance Fields). The test “is the distance less than 0?” gives each pixel a yes-or-no answer, so edges come out jagged.\nTo make them smooth, you want to blend across the edge over about one pixel. But how much does the distance change over one pixel? That depends on how far you’re zoomed in, and it’s what ddx and ddy of the distance tell you. There’s a built-in helper for this called fwidth:\n// What fwidth works out: a quick estimate of how much d changes over one pixel. fwidth(d) == abs(ddx(d)) + abs(ddy(d)) // How much of the shape's colour to use for this pixel: 1 well inside, 0 well outside, // and a blend across about one pixel at the edge. float alpha = saturate(0.5 - d / fwidth(d)); // saturate keeps it between 0 and 1 (HLSL; in GLSL use clamp(…, 0.0, 1.0)) Adding the two together is quick but overestimates on diagonal edges, by up to about 1.4 times. length(float2(ddx(d), ddy(d))) gives a more exact answer for a little more work. Also make sure fwidth(d) can’t be 0 where you divide by it, for example with max(fwidth(d), 0.0001), or flat areas can give invalid results.\nThe demo draws a disc, a thin ring and a grid of thin lines. Turn up Pixel size to magnify the pixels, change the zoom, and compare the modes. A fixed blur looks fine at one zoom level only. The fwidth version stays crisp but smooth at every zoom, and lines thinner than a pixel stay unbroken instead of breaking up into dashes. They do look too bold when zoomed far out, because with this simple formula a pixel whose centre is on the line always gets at least half of the line’s colour, however thin the line is; the grid shader article in Further Reading shows how to fix that too.\nHard edges, a fixed blur and fwidth, at any zoom\nHard edgefwidth Edges Side by side Hard edge Fixed blur Using fwidth ▶ Play Zoom: Pixel size: Under the hood When a shader reads a texture, the texture unit (the hardware that fetches and filters texels) is handed the texture coordinates of all four pixels in the 2×2 group at once. It works out the derivatives itself from their differences and picks the mip level, often once for the whole group. That’s why even a shader that never calls ddx still has to run in 2×2 groups: every normal texture read needs the neighbours. Reading with an explicit level, such as textureLod, doesn’t.\nQuestions You Might Have Why not just use fwidth for every edge? For shapes worked out in the shader, it’s usually the right tool. Edges of triangles are a different case: their pixels come from rasterisation, not from a distance the shader knows, so they need anti-aliasing instead.\nSummary Every ordinary texture read uses ddx and ddy of the texture coordinate to choose a mip level: the more texels one pixel step crosses, the smaller the copy it reads. fwidth(d) is abs(ddx(d)) + abs(ddy(d)): roughly how much a value changes over one pixel. Dividing a signed distance by fwidth blends edges over about one pixel, so shapes stay smooth at any zoom. Next, part 3 builds a surface’s normal from ddx and ddy of its position: flat shading with no extra data.\nFurther Reading Ben Golus, The Best Darn Grid Shader (Yet): a deep dive into drawing perfect lines with derivatives. Inigo Quilez, Filtering procedural textures: using derivatives to stop maths-generated patterns from shimmering. Microsoft, SampleGrad: the HLSL reference page for reading a texture with your own ddx and ddy. ","permalink":"https://fragmentshack.com/posts/ddx-ddy-mipmaps-fwidth/","summary":"The two uses of ddx and ddy you\u0026rsquo;ll meet most: choosing a texture\u0026rsquo;s mipmap level, and smooth edges at any zoom with fwidth. With live WebGL demos.","title":"🧰 Using ddx and ddy: Mipmaps and Smooth Edges"},{"content":" Introduction ddx and ddy turn up all over shader code, in anti-aliasing, lighting and more, and every ordinary texture read uses them behind the scenes. The documentation calls them “partial derivatives” (“partial” because each looks in only one direction), which sounds daunting, but the idea is simple. This post, the first of three, covers:\nWhat ddx and ddy actually give you How the graphics card works them out (it’s just a subtraction) The difference between fine and coarse derivatives Parts 2 and 3 show what they’re used for, and the Helper Pixels post covers the things that can catch you out. You don’t need any maths beyond subtraction.\nddx and ddy are the names in HLSL, Direct3D’s shading language. GLSL (used by OpenGL, WebGL and often Vulkan) calls them dFdx and dFdy, and Metal calls them dfdx and dfdy. This post uses ddx and ddy throughout. Everything here applies to all three, except which way “down” is (see the cheat sheet at the end).\nWhat They Measure This post builds on the fragment shader (Direct3D calls it a pixel shader): the small program that works out the colour of each pixel a triangle covers. The Graphics Pipeline shows where it runs, and Fragment Shaders shows what it does. Each copy normally knows only about its own pixel.\nA derivative is the maths word for how fast something changes. ddx and ddy estimate it in the simplest way possible: they take a step of one pixel and measure how much a value changed.\nddx(value) is how much value changes when you move one pixel to the right. ddy(value) is how much value changes when you move one pixel down (one pixel up in OpenGL and WebGL; the cheat sheet explains why). You can pass in anything your shader has worked out: a texture coordinate, a position, a brightness, a distance.\nThe Idea: Compare with the Pixel Next Door Here is a row of 16 pixels. Each has worked out a value between 0 (black) and 1 (white), shown as its colour and as a grey bar. The bars underneath show ddx, orange when the value goes up and blue when it goes down. This demo does its sums in JavaScript, the same way a graphics card does.\nTry each pattern, move the Steepness slider, and hover over or tap a pixel to see the sum. Notice that:\nA flat pattern gives a ddx of 0 everywhere, because nothing changes. A steady ramp gives the same ddx everywhere, and steeper ramps give bigger numbers. A curve gives a ddx that grows as the curve gets steeper. A wave gives positive numbers where it rises and negative numbers where it falls. A sudden edge gives 0 everywhere except at the one pair of pixels that sits across the edge. ddx along a row of 16 pixels, worked out in pairs\nPattern Flat Steady ramp Curve Wave Sudden edge Steepness: The brackets under the pixels mark fixed pairs (pixels 0 and 1, 2 and 3, and so on). The graphics card subtracts the left pixel’s value from the right one’s and gives that one answer to both pixels, which is why the ddx bars come in matching twos. The next section explains why.\nHow the Graphics Card Works Them Out How can a fragment shader know what’s happening next door? The graphics card never runs one on its own: it always runs them in 2×2 groups of four neighbouring pixels (usually called quads), lined up on a fixed grid across the image, and the four step through the shader together, one instruction at a time. When the shader reaches ddx(value), each pixel can read the values its three neighbours in the group have just worked out, and subtract:\nddx = the right pixel’s value − the left pixel’s value, in the same row of the group ddy = the bottom pixel’s value − the top pixel’s value, in the same column of the group The demo below runs on your own graphics card and shows a tiny image, 16 pixels wide and 10 tall, drawn large, with thick lines marking the 2×2 groups. Hover over or tap any pixel (or select the grid and use the arrow keys) to see its group and the two subtractions. Switch Show to ddx or ddy to colour every pixel by its answer: orange for positive, blue for negative and grey for zero.\nddx and ddy worked out by your graphics card, in 2×2 groups\nPattern Ramp across Ramp down Diagonal ramp Curve across Circle (distance from the centre) Wave Sudden edge (a disc) Show Value ddx ddy Steepness: Outline the 2×2 groups Some things worth trying:\nRamp across with Show: ddy. The value doesn’t change going down, so ddy is 0 everywhere. Diagonal ramp. Now both ddx and ddy are the same non-zero number. Circle with Show: ddx. Left of the centre the distance shrinks as you move right (blue); right of the centre it grows (orange). Sudden edge with Show: ddx. ddx is only non-zero for a pair with one pixel inside the disc and one outside. A pair entirely inside or outside sees no change at all, even right next to the edge: a side effect of working in fixed 2×2 groups. So far, each row of a group works out its own ddx, and each column its own ddy: a fine derivative. Graphics cards may instead save effort by doing the subtraction for only one row (or column) and giving that answer to all four pixels: a coarse derivative. The demo tells you which your graphics card did. HLSL’s ddx_fine and ddx_coarse, and GLSL’s dFdxFine and dFdxCoarse, ask for one or the other. Plain ddx and dFdx promise neither, and even the coarse versions only allow the shortcut.\nCheat Sheet What it does HLSL GLSL Metal Change one pixel to the right ddx dFdx dfdx Change one pixel down* ddy dFdy dfdy abs(ddx) + abs(ddy) fwidth fwidth fwidth Fine: each row (or column) of a group gets its own answer ddx_fine, ddy_fine dFdxFine, dFdyFine Not available Coarse: one answer may be shared by the whole group ddx_coarse, ddy_coarse dFdxCoarse, dFdyCoarse Not available Read a texture with your own ddx/ddy SampleGrad textureGrad sample with gradient2d * OpenGL and WebGL count pixel rows from the bottom by default, so there dFdy measures the change one pixel up. Direct3D, Metal and Vulkan count from the top. The fine and coarse GLSL versions need OpenGL 4.5 (or the ARB_derivative_control extension) or Vulkan; WebGL doesn’t have them.\nUnder the hood Fragment shaders run in groups of 32 or 64 copies that execute each instruction together (How GPUs Run Shaders), with a quad’s four pixels side by side in the same group. Each copy keeps its values in registers, the processor’s fastest storage, and special instructions let a copy read a register from another copy in its quad. So a derivative needs no trip to memory: read the neighbour’s register and subtract. Newer shader languages let programmers use the same mechanism directly, for example HLSL’s QuadReadAcrossX (Shader Model 6.0) and Vulkan GLSL’s subgroupQuadSwapHorizontal.\nQuestions You Might Have Can I use ddx and ddy in a vertex shader? No. Only fragment shaders run in 2×2 groups of neighbouring pixels, so only they have neighbours to compare with. (Some newer APIs also allow derivatives in compute shaders, by arranging threads into the same 2×2 groups.)\nAre ddx and ddy expensive? The subtraction itself is about as cheap as an instruction gets. The real cost is that the graphics card must always shade whole 2×2 groups, even where a triangle covers only one pixel of a group. Helper Pixels measures that cost.\nSummary ddx and ddy tell you how much a value changes from one pixel to the next, to the right and down (up in OpenGL and WebGL). The graphics card works them out by running fragment shaders in 2×2 groups and subtracting neighbours’ values, so each answer is shared by a pair of pixels. Fine derivatives give each row or column of a group its own answer; coarse ones may share one answer across the group. Next, part 2 puts them to work: picking mipmap levels, and smooth edges at any size with fwidth.\nFurther Reading Microsoft, ddx, ddy and fwidth: the HLSL reference pages. Khronos, dFdx and dFdy: the GLSL reference page, including the fine and coarse versions. Fabian Giesen, A trip through the Graphics Pipeline, part 8: how graphics cards really run fragment shaders (Direct3D’s pixel shaders) in 2×2 groups. ","permalink":"https://fragmentshack.com/posts/ddx-ddy-shader-derivatives-explained/","summary":"What ddx and ddy (dFdx and dFdy in GLSL) tell a shader, and how the graphics card works them out by comparing neighbouring pixels in 2×2 groups, with interactive WebGL demos.","title":"📐 ddx and ddy Explained: Shader Derivatives, Pixel by Pixel"},{"content":"Last updated: 22 November 2026\nThe short version Fragment Shack has no accounts, no adverts and no cookies. A few settings (like which posts you\u0026rsquo;ve ticked off) are saved in your own browser. They never leave your device. Our web host keeps standard server logs to keep the site running and secure. We count visits with cookie-free analytics that can\u0026rsquo;t identify you (details below). We never sell your data or share it for marketing. Who we are Fragment Shack (https://fragmentshack.com) is run by Alexander Houghton, who is the \u0026ldquo;data controller\u0026rdquo; responsible for your information under UK data protection law (the UK GDPR and the Data Protection Act 2018).\nFor any privacy question or request, email privacy@fragmentshack.com.\nWhat\u0026rsquo;s saved in your browser The site saves these small settings using your browser\u0026rsquo;s local storage. They are not cookies, they stay on your device, and they are never sent to us or anyone else:\nName What it remembers When it\u0026rsquo;s saved fs-progress Which posts you\u0026rsquo;ve marked as done When you tick \u0026ldquo;Mark this post as done\u0026rdquo; pref-theme Light or dark mode When you press the light/dark button menu-scroll-position How far you scrolled the top menu on a small screen When you scroll that menu These only exist because you asked for the feature, so the law doesn\u0026rsquo;t require us to ask for consent first. You can delete them at any time by clearing this site\u0026rsquo;s data in your browser settings. Unticking every post or switching the theme back also changes them.\nServer logs Like almost every website, our hosting provider (GoDaddy) automatically records each request made to the server: your IP address, the date and time, the page or file requested, the page that linked you here, and your browser\u0026rsquo;s identifier (its \u0026ldquo;user agent\u0026rdquo;). These logs are used only to keep the site working and secure, for example to fix errors and block attacks. We don\u0026rsquo;t use them to identify or profile visitors.\nOur lawful basis is legitimate interests: running a secure, working website. The logs are kept only as long as our host retains them for these purposes, and are then deleted.\nAnalytics We count visits so we can see which pages are read. We do this without cookies, without storing anything on your device and without building a profile of you. We never see your name or email, and we can't identify you from these numbers.\nCloudflare Web Analytics. A small script from Cloudflare records the page you visited, the page that linked you here, your browser and device type, your approximate country (worked out from your IP address) and how quickly the page loaded. Cloudflare states that it does not use cookies or local storage for this, does not fingerprint visitors, and does not use your IP address to track you. Cloudflare processes this data for us as our service provider (a \"processor\"). See Cloudflare's privacy policy.\nOur lawful basis is legitimate interests: understanding, in aggregate, how the site is used so we can improve it, in a way that has minimal impact on your privacy. If you block the script with a browser setting or extension, the site works exactly the same.\nIf you email us If you email us, we use your email address and message only to reply to you, and keep them only as long as needed to deal with your message. Our lawful basis is legitimate interests (answering your question).\nWho else sees your data Our hosting provider (GoDaddy), which stores the site and its server logs on our behalf. Our analytics provider, if one is listed above, which processes visit statistics on our behalf. Both act only on our instructions. Some of them may process data outside the UK. When that happens they rely on legal safeguards approved under UK law, such as adequacy regulations or the International Data Transfer Agreement. We don\u0026rsquo;t sell, rent or trade personal data, and we don\u0026rsquo;t use it for advertising.\nLinks to other websites Posts link to other websites for further reading. We\u0026rsquo;re not responsible for their content or privacy practices, so please check their own privacy policies.\nChildren Fragment Shack is suitable for all ages and collects no more information from children than from anyone else. Nothing on the site asks for personal details.\nYour rights Under UK data protection law, you have the right to:\nAccess the personal data we hold about you Have inaccurate data corrected Have your data deleted Restrict or object to how we use it Receive your data in a portable format (data portability) To use any of these rights, email privacy@fragmentshack.com. We\u0026rsquo;ll reply within one month. In practice we usually hold nothing that identifies you, because we don\u0026rsquo;t collect names, emails (unless you write to us) or accounts.\nIf you\u0026rsquo;re unhappy with how we\u0026rsquo;ve handled your data, you can complain to the UK\u0026rsquo;s data protection regulator, the Information Commissioner\u0026rsquo;s Office (ICO), at ico.org.uk or on 0303 123 1113. We\u0026rsquo;d appreciate the chance to put things right first, so please contact us before going to the ICO.\nChanges to this policy If the way we handle data changes, for example if we add a new service, we\u0026rsquo;ll update this page and the \u0026ldquo;last updated\u0026rdquo; date at the top.\n","permalink":"https://fragmentshack.com/privacy/","summary":"\u003cp\u003e\u003cstrong\u003eLast updated: 22 November 2026\u003c/strong\u003e\u003c/p\u003e\n\u003ch2 id=\"the-short-version\"\u003eThe short version\u003c/h2\u003e\n\u003cul\u003e\n\u003cli\u003eFragment Shack has \u003cstrong\u003eno accounts, no adverts and no cookies\u003c/strong\u003e.\u003c/li\u003e\n\u003cli\u003eA few settings (like which posts you\u0026rsquo;ve ticked off) are saved \u003cstrong\u003ein your own browser\u003c/strong\u003e. They never leave your device.\u003c/li\u003e\n\u003cli\u003eOur web host keeps standard \u003cstrong\u003eserver logs\u003c/strong\u003e to keep the site running and secure.\u003c/li\u003e\n\u003cli\u003eWe count visits with \u003cstrong\u003ecookie-free analytics\u003c/strong\u003e that can\u0026rsquo;t identify you (details below).\u003c/li\u003e\n\u003cli\u003eWe \u003cstrong\u003enever sell\u003c/strong\u003e your data or share it for marketing.\u003c/li\u003e\n\u003c/ul\u003e\n\u003ch2 id=\"who-we-are\"\u003eWho we are\u003c/h2\u003e\n\u003cp\u003eFragment Shack (\u003ca href=\"https://fragmentshack.com\"\u003ehttps://fragmentshack.com\u003c/a\u003e) is run by \u003cstrong\u003eAlexander Houghton\u003c/strong\u003e, who is the \u0026ldquo;data controller\u0026rdquo; responsible for your information under UK data protection law (the UK GDPR and the Data Protection Act 2018).\u003c/p\u003e","title":"Privacy Policy"},{"content":"Introduction In a typical 3D scene, objects hide each other: a wall in front of a room, characters in front of buildings. Every time a pixel\u0026rsquo;s fragment shader runs for a surface that ends up hidden behind something else, that work is thrown away. Shading the same pixel more than once is called overdraw, and because fragment shaders are usually the most expensive part of drawing a frame (fragment shaders), it\u0026rsquo;s a big deal for performance. This post covers:\nWhat overdraw is, seen as a heat map counted on your own graphics card The early depth test, which lets the hardware skip hidden fragments Why draw order matters, even with a depth buffer The depth pre-pass, which gets overdraw down to almost nothing Counting Shader Runs The demo below draws a crowd of 70 boxes. In heat map view, each pixel is coloured by how many times its fragment shader ran: blue for once, green for twice, yellow for about four times and red for eight or more. (It counts by having every shaded fragment add 1 to a render target with additive blending, then reads the totals back.) Drag to look around, and try the options.\nA heat map of how many times each pixel’s fragment shader runs\nShow Heat map The scene Draw order Unsorted Back to front Front to back Depth test Depth pre-pass Things to try:\nTurn the depth test off. Every fragment of every box is shaded, so the middle of the crowd glows red. (And the scene is wrong: whichever box is drawn last appears on top, as in the depth buffer post.) Turn it back on, with Back to front order. The picture is now correct, but it\u0026rsquo;s still mostly green and yellow: each box is drawn over the ones behind it, so pixels are shaded again and again before the nearest surface finally wins. Switch to Front to back. The nearest boxes are drawn first and fill the depth buffer, so later boxes behind them fail the depth test before their shader runs. The heat map turns mostly blue. Tick Depth pre-pass. Now every pixel is shaded exactly once, whatever the order. The Early Depth Test In the pipeline, the depth test was described as part of output merging, after the fragment shader. But running a shader only to throw its result away is pure waste, so graphics cards try to do the depth test early: right after rasterisation, before the fragment shader. A fragment that\u0026rsquo;s already hidden is rejected and its shader never runs. The demo\u0026rsquo;s count models exactly this: it counts the fragments that pass the depth test at the moment they\u0026rsquo;re drawn.\nEarly depth testing only helps if the hidden surface is drawn after the surface that hides it. That\u0026rsquo;s why engines sort their solid objects roughly front to back: not for correctness (the depth buffer handles that), but for speed. (Transparent objects are the exception: they must be drawn back to front, which is why they overdraw so much.)\nSome things force the hardware to fall back to testing after the shader, because the shader itself decides the final depth or whether the fragment exists: writing its own depth value, and, depending on the hardware, using discard (fragment shaders). That\u0026rsquo;s one reason alpha-tested foliage can be expensive.\nThe Depth Pre-Pass Sorting is approximate: objects overlap in complicated ways, and sorting individual triangles isn\u0026rsquo;t practical. A depth pre-pass (or z-prepass) gets it right every time. The scene is drawn twice:\nFirst with colour writes turned off and the simplest possible fragment shader, filling in only the depth buffer. This is very cheap per pixel. Then again, normally, with the depth test set to \u0026ldquo;equal\u0026rdquo;. Only the fragment that matches the nearest depth passes, so each pixel\u0026rsquo;s expensive shader runs exactly once. The cost is drawing every triangle twice. When fragment shaders are expensive (complex lighting, many textures), that trade is often well worth it. When there\u0026rsquo;s lots of geometry and simple shading, it may not be.\nUnder the hood Beyond testing individual fragments early, graphics cards keep a coarse summary of the depth buffer, often called hierarchical Z or Hi-Z: for each small tile of the screen, the furthest depth stored in it. The rasteriser can compare a whole tile of a new triangle against that summary and reject all of its pixels at once if they\u0026rsquo;re behind everything there, without touching the full depth buffer. Some hardware goes further. Most mobile graphics cards are tile-based: they collect all the triangles for a small tile of the screen before drawing it. Some, notably Apple\u0026rsquo;s and Imagination\u0026rsquo;s PowerVR designs (tile-based deferred renderers), then work out which surface is visible at each pixel before running any fragment shaders, removing most overdraw from solid objects whatever the draw order. Others, such as Arm\u0026rsquo;s Mali, use their own hidden-surface removal tricks that achieve much of the same.\nQuestions You Might Have Is overdraw always bad? No: transparent effects like smoke, glass and particles need it, because they have to blend over what\u0026rsquo;s behind. It becomes a problem when there are many layers of an expensive shader, such as a screen full of overlapping smoke particles.\nSummary Overdraw is running a pixel\u0026rsquo;s fragment shader more than once; the hidden results are wasted. The early depth test rejects hidden fragments before their shader runs, but only for surfaces drawn after whatever hides them. Drawing solid objects front to back makes early rejection effective. A depth pre-pass fills the depth buffer first, so each pixel is shaded exactly once, at the cost of drawing geometry twice. Writing depth in the shader, and sometimes discard, can disable early testing. Further Reading Fabian Giesen, A trip through the Graphics Pipeline, part 7: early and hierarchical depth testing in hardware. Khronos OpenGL Wiki, Early Fragment Test: exactly when early testing can and can\u0026rsquo;t happen. Arm, Mali GPU best practices: hidden surface removal: how tile-based mobile GPUs remove overdraw. RenderDoc: a free frame debugger whose \u0026ldquo;quad overdraw\u0026rdquo; overlay shows a heat map like this demo\u0026rsquo;s, for real games. ","permalink":"https://fragmentshack.com/posts/overdraw-early-depth/","summary":"In a busy scene, many pixels get shaded several times before the final colour wins. See a heat map of how often each pixel\u0026rsquo;s shader runs, and how draw order and a depth pre-pass cut the waste.","title":"🖌️ Overdraw: The Cost of Painting the Same Pixel Twice"},{"content":"Introduction Rasterisation decides whether a pixel is covered by testing a single point, its centre. That yes-or-no answer is why slanted edges turn into staircases and thin objects break into dashes. These problems are called aliasing, and the \u0026ldquo;anti-aliasing\u0026rdquo; option in a game\u0026rsquo;s settings is about fixing them. This post compares the three classic approaches:\nSupersampling (SSAA): draw everything at a higher resolution, then shrink it Multisampling (MSAA): test coverage at several points, but run the shader only once Post-process anti-aliasing such as FXAA: find edges in the finished image and blur along them More Samples per Pixel The underlying problem is that one sample per pixel can only say \u0026ldquo;fully covered\u0026rdquo; or \u0026ldquo;not covered\u0026rdquo;. A pixel that a triangle\u0026rsquo;s edge cuts through should really be a blend of the triangle and the background, in proportion to how much of the pixel each covers.\nThe diagram below shows one pixel, magnified, with a triangle\u0026rsquo;s edge passing through it (drag the edge\u0026rsquo;s ends). The dots are the points where coverage is tested. Compare one sample with four and eight.\nOne pixel, a triangle edge, and the points where coverage is tested\nSamples per pixel 1 (no anti-aliasing) 4 8 With four samples, the pixel can be 0%, 25%, 50%, 75% or 100% covered, so an edge gets in-between shades that smooth out the staircase. The positions aren\u0026rsquo;t a neat grid: they\u0026rsquo;re deliberately scattered (these are Direct3D\u0026rsquo;s standard patterns), so that nearly horizontal and nearly vertical edges, the ones where staircases are most visible, cross the samples at different points and still get several distinct shades.\nComparing the Methods The demo below draws a fan of thin spokes at a deliberately low resolution (enlarged so you can see each pixel), using each method for real on your graphics card. It spins by itself, so you can see how the aliasing crawls when things move (press Pause to study a still frame): that crawling is often more distracting than the staircases themselves.\nThe same scene with no anti-aliasing, supersampling, multisampling and an FXAA-style filter\nAnti-aliasing None Supersampling (SSAA 4×) Multisampling (MSAA 4×) FXAA-style post-process ▶ Play Enlarge pixels: Supersampling (SSAA) The brute-force method: draw the whole frame at twice the width and height (four times the pixels), then average each 2 × 2 block down to one pixel. It fixes every kind of aliasing, including inside textures and shaders, but it multiplies everything by four: fragment shader runs, memory and memory traffic. It\u0026rsquo;s rarely used in games except as a high-end option, though its idea lives on in rendering at a higher resolution and downscaling.\nMultisampling (MSAA) The graphics card\u0026rsquo;s built-in solution, and a very clever one. Aliasing mostly happens at the edges of triangles, and it\u0026rsquo;s the coverage test that causes it, not the shading. So MSAA tests coverage and depth at several sample points per pixel (4 here), but runs the fragment shader only once per pixel for each triangle, and stores that one colour into every sample the triangle covers. At the end, a resolve step averages each pixel\u0026rsquo;s samples. Edges come out as smooth as supersampling, for a fraction of the shading cost.\nIt has limits: it only smooths triangle edges, not aliasing inside a surface, such as shimmering textures or shiny highlights. It needs memory for every sample. And it fits poorly with deferred renderers, which most modern games use for lighting: they store surface data in several render targets and light it later, and multisampling all of those is expensive. That\u0026rsquo;s a big reason it has become less common.\nFXAA and post-process anti-aliasing The opposite approach: draw the image normally, with no anti-aliasing, then run one extra full-screen pass (post-processing) that looks for high-contrast edges and blurs along them, not across them. FXAA (Fast Approximate Anti-Aliasing, published by Timothy Lottes at NVIDIA in 2009) is the best known; the demo uses a simplified version of the same idea. It\u0026rsquo;s extremely cheap and works with any renderer. But it only sees the finished pixels, so it can\u0026rsquo;t recover detail that was lost: thin spokes that already broke into dashes stay broken, and it slightly softens the whole image, including text and textures.\nThe steps the demo's FXAA-style filter takes For every pixel of the finished image:\nMeasure brightness of the pixel and its four diagonal neighbours, using luma: 0.299 × red + 0.587 × green + 0.114 × blue (green counts most because our eyes are most sensitive to it). Skip flat areas: if the brightest and darkest of the five differ by only a little (less than 0.05, or an eighth of the brightest), it isn\u0026rsquo;t an edge, so the pixel is left alone. This keeps the filter from blurring everything. Find the edge\u0026rsquo;s direction: compare the top pair of neighbours with the bottom pair, and the left pair with the right pair. The edge runs at right angles to the way brightness changes fastest. Blur along it: average two samples taken a little way along the edge, one either side of the pixel, and, for a wider blur, two more a bit further out. Sanity check: if the wider average comes out brighter or darker than any of the original five pixels, it reached across into something else, so the closer average is used instead. The real FXAA adds a search along the edge to find where it ends, which handles long, nearly horizontal edges much better.\nUnder the hood MSAA is efficient partly because of compression in the hardware. In the middle of a triangle, all four samples of a pixel get the same colour, so graphics cards store a flag saying \u0026ldquo;all samples identical\u0026rdquo; and only spend memory traffic on the full set of samples along edges. WebGL2 lets a program draw into a multisampled image and then resolve it, which is what the demo does; the WebGL canvas itself is also multisampled by default. Today, most games use temporal anti-aliasing (TAA) instead: each frame, the sample position inside every pixel is shifted slightly, and the results are blended with previous frames (render targets explains the ping-pong trick behind it). Over a few frames, every pixel collects many samples, at the cost of some blur, and faint trails (\u0026ldquo;ghosting\u0026rdquo;) behind moving objects. Modern upscalers build on the same idea.\nSummary Aliasing comes from testing one point per pixel; anti-aliasing uses more information. SSAA draws at a higher resolution and averages: best quality, highest cost. MSAA tests coverage at several points but shades once per pixel per triangle: smooth edges, cheaply, but only edges. FXAA-style filters blur along edges in the finished image: very cheap, but can\u0026rsquo;t recover lost detail. Most modern games use temporal anti-aliasing, gathering samples over several frames. That completes the Render Targets \u0026amp; Post-Processing series! Next, Lighting \u0026amp; Shadows makes surfaces look detailed and solid.\nFurther Reading Matt Pettineo, A Quick Overview of MSAA: how multisampling really works, in detail. Timothy Lottes, FXAA (NVIDIA white paper, 2009): the original description of FXAA. Microsoft, D3D11_STANDARD_MULTISAMPLE_QUALITY_LEVELS: Direct3D\u0026rsquo;s standard sample patterns, with diagrams. Brian Karis, High-Quality Temporal Supersampling (SIGGRAPH 2014 Advances course): how Unreal Engine\u0026rsquo;s temporal anti-aliasing works. ","permalink":"https://fragmentshack.com/posts/anti-aliasing-msaa-fxaa/","summary":"Why edges look like staircases, and the three classic fixes: draw more pixels (SSAA), test more points but shade once (MSAA), or blur the edges afterwards (FXAA). Compare them on your own GPU.","title":"🪚 Anti-Aliasing: SSAA, MSAA and FXAA Compared"},{"content":"Introduction A graphics card can run a fragment shader for millions of pixels in a few milliseconds. It does that with a very different design from a normal processor, and that design explains a lot of shader \u0026ldquo;rules of thumb\u0026rdquo; that otherwise sound like folklore: why if statements can be slow, why texture reads don\u0026rsquo;t stall everything, and why using too many variables can hurt. This post, the first in the GPU Performance series, covers:\nSIMD execution: running one instruction on many pixels at once, in groups called warps or wavefronts Divergence: what happens when pixels in a group want to take different branches Latency hiding: how a graphics card keeps busy while waiting for memory The demos here are simulations, simplified to show the idea: real hardware is more complicated, but works on these principles.\nOne Instruction, Many Pixels A normal processor core is built to run one stream of instructions as fast as possible, with lots of clever hardware to predict branches and reorder work. A graphics card instead has thousands of simple arithmetic units, and saves hardware by making them share. A group of copies of your shader, one per pixel (or per vertex), all execute the same instruction at the same time, each on its own data. This is SIMD: single instruction, multiple data.\nThe groups have different names on different hardware: NVIDIA calls them warps (32 copies), AMD calls them wavefronts (64 copies on its older designs; newer ones can use 32 or 64), Apple calls them SIMD groups (32), and the graphics APIs call them subgroups or waves. For a fragment shader, the copies in a group are usually neighbouring pixels on screen, made up of the 2×2 quads described in the ddx and ddy posts.\nSharing one instruction stream between 32 copies means the hardware only has to fetch, decode and schedule each instruction once for all 32, so almost all of the chip can be spent on arithmetic. The price is that the copies must stay in lockstep.\nDivergence: When Pixels Disagree So what happens with an if?\nif (insideTheCircle) { colour = expensiveLighting(); // the \u0026#34;if\u0026#34; path } else { colour = skyColour(); // the \u0026#34;else\u0026#34; path } If every pixel in a group agrees, the group simply runs the path they all need. But if some want the if and some the else, the group can\u0026rsquo;t split up. It runs both paths, one after the other, and for each path it switches off (masks) the lanes that don\u0026rsquo;t want it. Those lanes sit idle. This is called divergence.\nThe demo below shows a 32 × 16 patch of pixels, split into groups (outlined). Orange pixels take the expensive path and blue pixels the cheap one. Each group is labelled with the number of cycles it takes (a cycle is one tick of the processor\u0026rsquo;s clock, long enough for one instruction); divergent groups are outlined in red. Click or tap a group to see its timeline: one column per lane (each copy in a group is called a lane), one row per cycle, grey where a lane is switched off.\nSimulated branch divergence in groups of shader copies\nWhich pixels take the \"if\" Inside a circle Inside a big circle Alternate columns Random All of them None of them Group size 32 (8 × 4 pixels) 64 (8 × 8 pixels) \"if\" path cost: \"else\" path cost: Things to try:\nInside a circle: only the groups along the circle\u0026rsquo;s edge diverge. Most groups are entirely inside or outside, so they run just one path. This is the normal case in real shaders, and why branches are usually fine: neighbouring pixels tend to agree. Alternate columns or Random: every group diverges, every group pays for both paths, and efficiency collapses. A branch that changes from pixel to pixel is the expensive kind. Switch to groups of 64: bigger groups are more likely to straddle an edge, so more of them diverge. So the rule of thumb isn\u0026rsquo;t \u0026ldquo;branches are slow\u0026rdquo;. It\u0026rsquo;s: branches are cheap when neighbouring pixels agree, and expensive when they don\u0026rsquo;t. A branch on a uniform value (the same for every pixel) never diverges at all.\nHiding Latency The other big difference is how a graphics card deals with memory. Reading a texture can take hundreds of cycles if the data isn\u0026rsquo;t already in a cache, a small, fast memory of recently used data. A normal processor relies on large caches and predicting what you\u0026rsquo;ll need. A graphics card mostly doesn\u0026rsquo;t wait at all: it keeps many groups loaded and ready on each of its processor cores at once, and whenever the running group has to wait for memory, it switches to another group that\u0026rsquo;s ready, in a single cycle.\nThe simulation below shows one arithmetic unit shared by several groups. Each group does a few cycles of maths, then waits for a memory read. The top row shows whether the arithmetic unit is busy (green) or idle (red).\nSimulated latency hiding: groups taking turns while others wait for memory\nGroups on the core: Memory wait: Maths between reads: With only one or two groups, the arithmetic unit is idle most of the time. Add groups until it\u0026rsquo;s always busy: their waits overlap, and the latency is hidden. More maths between memory reads helps too, because each group keeps the unit busy for longer.\nThe rules the simulation follows Each cycle, the maths unit runs one cycle of work for one group that\u0026rsquo;s ready (not waiting), taking turns in order. A group that finishes its maths sends off a memory read and waits that many cycles before it\u0026rsquo;s ready again. If no group is ready, the unit sits idle (red).\nThat gives a simple rule of thumb. Each group spends (maths + wait) cycles for every maths cycles of real work, so to keep the unit busy all the time you need about:\ngroups ≥ (maths + wait) ÷ maths = 1 + wait ÷ maths With a 30-cycle wait and 4 cycles of maths, that\u0026rsquo;s 1 + 7.5 = 8.5, so 9 groups. Real memory waits can be hundreds of cycles, which is why graphics cards keep so many groups loaded at once.\nUnder the hood: occupancy How many groups fit on a core at once is called occupancy, and it\u0026rsquo;s limited by the core\u0026rsquo;s fixed pool of fast storage for each copy\u0026rsquo;s variables, the registers. A shader that needs many registers (lots of variables alive at once) leaves room for fewer groups, so there are fewer to switch between while waiting for memory. That\u0026rsquo;s why a long, complicated shader can be slow even if most of its work is cheap, why shader compilers work hard to reduce register use, and why GPU profiling tools always report occupancy.\nSummary Graphics cards run shaders in groups (warps or wavefronts) of 32 or 64 that execute in lockstep. When copies in a group take different branches, the group runs both paths, with lanes masked: divergence. Branches are cheap when neighbouring pixels agree, and costly when they don\u0026rsquo;t. GPUs hide memory latency by switching between many resident groups; how many fit is occupancy, limited by registers. Further Reading Fabian Giesen, A trip through the Graphics Pipeline, part 8: pixel shaders, quads and how they\u0026rsquo;re scheduled. Wikipedia, Single instruction, multiple threads: the execution model, with links to each vendor\u0026rsquo;s architecture. AMD GPUOpen, Occupancy explained: registers, occupancy and latency hiding on real hardware. NVIDIA, CUDA C++ Programming Guide: SIMT Architecture: warps and divergence from the hardware maker. ","permalink":"https://fragmentshack.com/posts/gpu-shader-execution/","summary":"A graphics card runs shaders in groups of 32 or 64 that all execute the same instruction at once. See what that means for if statements, and how GPUs hide slow memory by juggling groups.","title":"⚙️ How GPUs Run Shaders: Lockstep, Divergence and Hiding Latency"},{"content":"Introduction So far this series has drawn flat shapes. Distance functions work just as well in 3D: a sphere is length(p) − r, with p a three-number (x, y, z) point measured from the centre and r the radius, and every trick from SDF part 2 works unchanged. But how do you draw a 3D distance function on a 2D screen? With ray marching, the technique behind many astonishing Shadertoy scenes. This post covers:\nThe idea: fire a ray from each pixel and find where it meets the surface Sphere tracing: using the distance to take big, safe steps Getting normals, lighting and shadows from the same function The costs and uses of the technique It builds on Rays and Intersections.\nMarching Along a Ray For each pixel, imagine a ray from the camera out through that pixel. We want the first point where it touches the scene: where the distance function is zero. A single sphere has a formula for that, but a scene of blended, repeated, twisted shapes doesn\u0026rsquo;t. So instead, we march: step along the ray until we arrive.\nHow big should each step be? Too small and it takes forever; too big and we might jump through a thin object. Here distance functions shine: at any point, they give the distance to the nearest surface in any direction. Nothing is within that distance, so we can safely jump exactly that far along the ray, then measure and jump again. Near a surface the steps get tiny; once the distance is almost zero, we\u0026rsquo;ve arrived. This is sphere tracing (the safe areas are circles in 2D, spheres in 3D).\nDrag the ray\u0026rsquo;s start and aim point below. Each orange circle is the distance measured at that step; the ray jumps to its edge.\nSphere tracing in 2D: each step jumps as far as the distance allows\nMaximum steps: Show distance contours The marching loop for this ray, with the current numbers filled in:\nIn the code, ro (ray origin) is where the ray starts and rd (ray direction) the way it points, as a unit vector. A point t units along the ray is ro + rd * t, as in Rays and Intersections. scene is the distance to all the shapes together: the min of their distances, as in SDF part 2. The d values show the steps shrinking as the ray closes in.\nThings to notice:\nIn open space the ray takes huge steps; near a surface the circles shrink until they\u0026rsquo;re tiny. Aim the ray to skim just past a shape. The steps become tiny as it passes close by, and it may run out of steps, which is why real ray marchers always set a maximum number of steps and distance. Set Maximum steps to 1, 2, 3… to watch it step by step. A Real 3D Scene The demo below draws a whole 3D scene this way, in one fragment shader: a checkered floor, a turning rounded box and a bobbing ball, smoothly blended. There isn\u0026rsquo;t a single triangle (apart from the one covering the screen to run the shader). Drag to look around.\nA ray-marched 3D scene: no triangles, just one distance function\n▶ Play Show Lit scene Number of steps per pixel Blend between box and ball: The whole scene is one function giving the distance to the nearest thing: the min of the floor and the smooth union of the box and ball. Everything else comes from it:\nThe surface point: march each pixel\u0026rsquo;s ray until the distance is tiny. The normal (Basic Lighting): the direction in which the distance grows fastest, found by measuring the distance a tiny step either side of the point along x, y and z. Lighting: the usual N · L with that normal (the dot product). Shadows: march a second ray from the surface towards the light. If it hits something, the point is in shadow; if it only passes close to something, the point is partly shadowed, giving beautiful soft shadows almost for free. The scene's distance function and normal, as the shader writes them Slightly simplified from the demo’s shader (which also animates the box and ball):\nfloat scene(vec3 p) { float ground = p.y + 1.0; // height above a floor at y = −1 float box = sdBox(p - boxCentre, vec3(0.55)) - 0.08; // a cube, rounded by 0.08 float ball = sdSphere(p - ballCentre, 0.5); // a ball of radius 0.5 return min(ground, smoothUnion(box, ball, k)); // floor, plus box and ball melted together } Here p is a 3D point (x, y, z). The floor is flat at a height of −1, so the distance to it is the point\u0026rsquo;s height above it, p.y + 1. boxCentre and ballCentre are where the shapes are, and k is the blend slider. sdBox and sdSphere are the 3D versions of SDF part 1\u0026rsquo;s box and circle, and smoothUnion is the smooth union from SDF part 2.\nThe normal compares the distance a tiny step e (0.001 units) either side of the point, along each axis:\nvec3 normal = normalize(vec3( scene(p + vec3(e, 0, 0)) - scene(p - vec3(e, 0, 0)), // how fast distance grows along x scene(p + vec3(0, e, 0)) - scene(p - vec3(0, e, 0)), // along y scene(p + vec3(0, 0, e)) - scene(p - vec3(0, 0, e)) // along z )); Distance grows fastest straight away from the surface, so together these differences point straight out of it: the normal.\nHow the soft shadow is worked out The shadow ray marches from the surface towards the light like the main ray. At each step it knows d, how close the nearest shape is, and t, how far it has travelled. If d reaches (almost) 0, the ray has hit something: full shadow. Otherwise the demo keeps the smallest value of:\nk × d ÷ t seen along the way, and uses it (limited to 0 to 1) as the amount of light. A ray passing close to an object (small d) gets a small value: partly shadowed. Dividing by t makes a near miss far from the surface darken less than one close by, so the shadow is sharp where an object meets the ground and blurrier further away, like real soft shadows. The number k sets the softness; this demo uses 10, and bigger values give harder shadows. (This is Inigo Quilez\u0026rsquo;s technique, linked below.)\nChoose Number of steps per pixel. Most pixels take only a few steps, but rays that skim past the shapes\u0026rsquo; edges or graze the distant floor take many more, just as in 2D.\nUnder the hood Ray marching is a stern test of a graphics card. Every pixel runs a loop, and neighbouring pixels can need very different numbers of steps, so groups that run in lockstep (How GPUs Run Shaders) wait for their slowest member. The scene function runs dozens of times per pixel (more for normals and shadows), so complex scenes get expensive quickly; this demo renders at slightly reduced resolution for that reason. Games use ray marching selectively: for clouds, fog and smoke, for soft shadows and reflections against simplified distance fields of the scene, and for water and terrain, while the main scene is still drawn with triangles.\nQuestions You Might Have Is ray marching the same as ray tracing? They\u0026rsquo;re cousins: both fire rays through pixels. Ray tracing usually means finding exactly where a ray hits triangles, helped by special data structures and hardware. Ray marching steps along the ray using a distance function, so it needs no triangles at all.\nSummary Ray marching finds where each pixel\u0026rsquo;s ray meets a surface by stepping along it. Sphere tracing steps by the distance function\u0026rsquo;s value: always safe, and big in open space. One distance function gives the surface, the normal (how the distance changes), lighting and soft shadows. It\u0026rsquo;s elegant but costly per pixel; games use it for clouds, fog, shadows and special effects. That completes the signed distance fields series: from a circle to a whole 3D world, built from distances.\nFurther Reading Jamie Wong, Ray Marching and Signed Distance Functions: a gentle, illustrated introduction. Inigo Quilez, 3D distance functions and Soft shadows: shapes, operators and the soft shadow trick. John C. Hart, Sphere tracing (The Visual Computer, 1996): the paper that introduced the technique. Shadertoy: thousands of ray-marched scenes to learn from. ","permalink":"https://fragmentshack.com/posts/sdf-ray-marching/","summary":"With a 3D distance function, a fragment shader can draw a whole scene without a single triangle: march a ray from each pixel, jumping as far as the distance allows. Watch the jumps, then explore a live scene. Part 4 of the signed distance fields series.","title":"🌀 Ray Marching: Drawing 3D Worlds with Distance Functions"},{"content":"Introduction SDF parts 1 and 2 described shapes with formulas. But some shapes, like the letters of a font, are far too complicated to write as a formula. This post shows how games get the benefits of distance fields anyway, by storing the distances in a texture. It covers:\nWhy ordinary text textures look blurry when magnified Storing a distance field texture instead, and why that works so well How such a texture is made The effects it makes easy: outlines, glows, shadows and bolder or thinner text The Problem with Letter Textures Games draw text by copying letters from a texture onto little rectangles. If the texture stores the letter itself (how much of each texel the letter covers), that works at its original size. Magnify it, though, and bilinear filtering blends neighbouring texels into a soft, blurry blob with wobbly edges. You could store a bigger texture, but games need text at every size, and a huge texture for every letter of every font is a lot of memory.\nStore the Distance Instead In 2007, Valve published a neat fix that\u0026rsquo;s now used everywhere: in each texel, store the signed distance from that texel to the letter\u0026rsquo;s edge instead. The letter\u0026rsquo;s edge is wherever the distance is zero.\nBoth modes below use a texture of exactly the same size: just 48 × 48 texels for one letter. Zoom in.\nThe same 48 × 48 texture size, storing coverage or distance\nTexture stores The letter (coverage) Distance to the edge The raw distance texture Zoom: Weight (threshold): Outline Glow Drop shadow The fragment shader's code for this view, with the current numbers filled in:\nChoose The raw distance texture to see what\u0026rsquo;s actually stored: each texel drawn as a flat grey square, with no blending. Hover over or tap a texel to read its number. In the code, uv is the position on the texture, from 0 to 1 across (Textures and UVs), texture(uTex, uv).r reads the red channel (the only one this texture has) with bilinear filtering, and v is the value read. smoothstep is from Interpolation.\nWhy it works Bilinear filtering blends neighbouring texels in straight lines (lerp). Blending colours that way smears an edge into a gradient. But think about how the distance to an edge changes as you move across it: if the edge is fairly straight, the distance changes at a steady rate, in a straight line. So blending distances in straight lines gives almost exactly the right distance in between. The shader then draws the edge where the distance crosses zero, blended over about one screen pixel using fwidth (SDF part 1), so it\u0026rsquo;s crisp at any zoom.\nThe weak spots are sharp corners. Near a corner, the distance doesn\u0026rsquo;t change in a straight line (the distance field turns into curves, as SDF part 1\u0026rsquo;s box showed), so magnified corners come out slightly rounded. Zoom right in on the tips of the S to see it.\nMaking the Texture A distance field texture is made ahead of time, from a high-resolution drawing of each letter:\nDraw the letter large (this demo draws it at 512 × 512 when the page loads). Find the pixels on its edge. For each texel of the small texture, find the distance to the nearest edge pixel, negative if the texel is inside the letter. Store it as a number from 0 to 1, where 0.5 means \u0026ldquo;on the edge\u0026rdquo;, smaller is outside and larger is inside. Only distances up to a set spread (here about 4 texels) are stored; anything further is clamped, so 8 bits per texel is plenty. A whole font\u0026rsquo;s letters are packed into one texture, called an atlas, along with a note of where each letter is.\nEffects for Free Because every texel knows how far it is from the edge, many effects become simple comparisons:\nWeight: drawing the edge at 0.5 gives the normal letter. Move the Weight slider to draw it at a different value and the letter gets bolder or thinner, from the same texture. Games use this for emphasis, and to make text readable at small sizes. Outline: colour everything between the edge and a little further out. Tick Outline. Glow: fade a colour in as the distance outside the letter shrinks. Tick Glow. Drop shadow: read the texture again at a small offset and draw a soft dark shape underneath. Tick Drop shadow. With a normal letter texture, each of these would need a separate pre-made image or an expensive blur.\nUnder the hood A refinement called multi-channel SDF (MSDF) uses the red, green and blue channels of the texture to store three slightly different distance fields, and takes the middle value of the three in the shader. Cleverly arranged, this preserves sharp corners, fixing the main weakness of the basic technique. Many game engines and user interface libraries now draw all their text with SDFs or MSDFs, from a single small texture per font. The same idea is used for icons, decals and even the edges of clouds of particles, anywhere a shape needs to look sharp at many sizes.\nQuestions You Might Have Do I have to make the distance textures myself? No. Tools generate them from ordinary font files, along with the atlas layout; Valve\u0026rsquo;s original paper describes the process, and open-source generators such as msdfgen also make the multi-channel version that keeps sharp corners.\nSummary Ordinary letter textures blur when magnified. A distance field texture stores the distance to the edge, which filters almost perfectly, so edges stay crisp. Sharp corners are slightly rounded; MSDF fixes that with three channels. Outlines, glows, shadows and bold or thin text are just comparisons on the distance. Next: ray marching, where distance functions draw entire 3D worlds.\nFurther Reading Chris Green (Valve), Improved Alpha-Tested Magnification for Vector Textures and Special Effects (SIGGRAPH 2007): the paper behind SDF text. Viktor Chlumský, msdfgen: the multi-channel distance field generator, with an explanation of the technique. ","permalink":"https://fragmentshack.com/posts/sdf-text/","summary":"Store the distance to a letter\u0026rsquo;s edge in a texture instead of the letter itself, and it stays razor sharp when magnified, with outlines, glows and bold text for free. Part 3 of the signed distance fields series.","title":"🔤 SDF Text: Crisp Letters from Tiny Textures"},{"content":"Introduction SDF part 1 showed how single shapes are described by their distance functions. The real power of SDFs is how easily they combine. This post covers:\nUnion, intersection and subtraction with min and max The famous smooth union, which melts shapes together like clay Bending space: repeating, mirroring and twisting shapes by changing the point before measuring When the results stop being true distances, and why that matters Joining and Cutting Shapes Say a and b are the distances from a point to two shapes. Then:\nUnion (either shape): min(a, b). The nearer of the two edges is the one that counts. Intersection (only where both overlap): max(a, b). A point is inside only if it\u0026rsquo;s inside both, meaning both distances are negative. Subtraction (cut a out of b): max(b, -a). Flipping the sign of a turns its inside into its outside, then intersecting keeps \u0026ldquo;inside b but outside a\u0026rdquo;. Drag the circle and the box by their centres and try each one. Hover over or tap to measure the distance.\nA circle and a box combined with distance functions\nCombine Union (min) Intersection (max) Box minus circle Smooth union Show Shape Distance field Smoothness: Box corner rounding: The shader code for this picture, with the current numbers filled in:\nSmooth union A plain union leaves a sharp crease where the two shapes meet, because min switches suddenly from one distance to the other. Smooth union blends between them near the crease. Where the two distances are very different, it behaves just like min. Where they\u0026rsquo;re close (near the join), it takes a little less than either, which pulls the surface outwards and fills the crease with a smooth curve:\nfloat smoothUnion(float a, float b, float k) { float h = clamp(0.5 + 0.5 * (b - a) / k, 0.0, 1.0); // how much to favour a over b return mix(b, a, h) - k * h * (1.0 - h); // blend, then bulge outwards a little } Here a and b are the two distances, as before, and k is how wide the blend is, in distance units. The value h is a number from 0 to 1 saying how much to favour a: 1 where a is much smaller than b, 0 where b is much smaller, and in between only near the join (where a and b are within k of each other). mix(b, a, h) is the lerp from Interpolation. The last part, k × h × (1 − h), is zero away from the join and biggest (k ÷ 4) right in the middle of it, where h = 0.5: that\u0026rsquo;s what pulls the surface outwards and fills the crease. Choose Smooth union and drag the shapes towards each other: they reach out and merge like drops of liquid. It\u0026rsquo;s used for organic shapes, blobby characters and lava lamps, and there are smooth versions of intersection and subtraction too.\nAre these still true distances? Switch to Distance field and look closely. For a union, the distances outside are still exact. But inside an intersection or subtraction, and near a smooth union\u0026rsquo;s blend, the contours aren\u0026rsquo;t quite evenly spaced: the numbers there are no longer the true distance to the edge, only a value that\u0026rsquo;s guaranteed never to be more than it. The edge itself is still in exactly the right place, so for drawing a shape it doesn\u0026rsquo;t matter. It does matter for effects that rely on the exact distance, like outlines of a fixed width, or for ray marching, where a too-big distance would make a ray jump through a surface.\nBending Space SDF part 1 moved shapes by changing the point before measuring. The same idea gets much more powerful when the change isn\u0026rsquo;t just a shift. Choose a mode below.\nChanging the point before measuring: repeat, mirror, copy round a circle, wobble\nSpace trick None Repeat Mirror Copies round a circle Wobble Show Shape Distance field ▶ Play Cell size: Copies: The shader code for this picture, with the current numbers filled in:\nHover over or tap the picture: the pink dot is your point, and the pink ring is where the code moves it to before measuring the one real shape.\nIn all of these, p is the point being measured, (x, y), and p.x and p.y are its two numbers.\nRepeat: p - size * round(p / size), where size is the width of one cell and round rounds to the nearest whole number, moves every point into the middle cell, by subtracting a whole number of cell widths. Every cell then measures the same single shape, so you get an endless grid of copies for the cost of one. As they animate, they all turn together, because they\u0026rsquo;re really the same shape. Mirror: p.x = abs(p.x) makes every point on the left behave like its mirror image on the right. Characters, logos and buildings are often symmetrical, so this halves the work. Copies round a circle: turn each point\u0026rsquo;s angle into an angle within one slice (using the angles from Sine and Cosine; atan(p.y, p.x) is the function that gives a point\u0026rsquo;s angle from its x and y), keeping its distance from the centre the same, then measure once: a flower, a gear or a clock face. Wobble: shift each point sideways by a sine wave before measuring, and the shape wobbles. Twisting, bending and stretching work the same way. These are called domain operations, because they change the space the shape is measured in rather than the shape itself. Repetition and mirroring keep the distances exact (as long as the shape fits inside its cell). Wobbling, twisting and stretching don\u0026rsquo;t: they squash and stretch space, so distances get distorted, and ray marchers have to take smaller steps to stay safe.\nUnder the hood Domain repetition is one of the reasons the demoscene (programmers who make astonishing animations in tiny programs) loves SDFs: a single round instruction turns one column into an endless temple, at almost no cost. The graphics card doesn\u0026rsquo;t know or care that there are \u0026ldquo;copies\u0026rdquo;; each pixel just does a little arithmetic on its own coordinates and measures one shape. Compare that with triangles, where a thousand copies means a thousand times the vertex work (or a technique called instancing to reduce it).\nQuestions You Might Have Can the shapes be 3D? Yes. Every operation here (min, max, smooth union, repeating, mirroring) works the same with 3D points and 3D distance functions such as spheres and boxes. SDF part 4 builds a 3D scene exactly this way.\nSummary Union = min(a, b), intersection = max(a, b), subtraction = max(b, -a). Smooth union blends near the join, melting shapes together; k sets how far. Combining can make the inside values approximate, though the edge stays exact. Domain operations change the point before measuring: repeat, mirror, copy round a circle, wobble. Next: crisp text from tiny textures.\nFurther Reading Inigo Quilez, Smooth minimum: several versions of smooth union, explained and compared. Inigo Quilez, Domain repetition: repeating shapes correctly, including the pitfalls. Mercury, hg_sdf: a well-known library of SDF shapes and operators from the demoscene. ","permalink":"https://fragmentshack.com/posts/sdf-combining-shapes/","summary":"Two lines of maths join, cut and melt shapes together, and a few more repeat, mirror and twist them, endlessly, for free. Part 2 of the signed distance fields series.","title":"🫠 Combining SDFs: Unions, Smooth Blends and Bending Space"},{"content":"Introduction Most of this site draws shapes with triangles. There\u0026rsquo;s a completely different way, much loved by shader programmers: describe a shape with a function that tells you, for any point, how far it is from the shape\u0026rsquo;s edge. A shape described this way is a signed distance field, or SDF. This post, the first of four, covers:\nWhat a signed distance is How the distance functions for circles, boxes, lines and polygons actually work Drawing them with perfectly smooth edges Moving, turning, scaling, rounding and hollowing a shape with a line of code each The next part combines shapes and bends space; SDF part 3 uses SDFs for crisp text; SDF part 4 draws whole 3D scenes with them. It helps to have read Fragment Shaders and the vectors and dot product posts.\nWhat Is a Signed Distance? For any point, a signed distance function (also called an SDF) returns the distance to the nearest edge of the shape, as a number that is:\nPositive outside the shape Negative inside it Zero exactly on the edge \u0026ldquo;Signed\u0026rdquo; just means the number has a plus or minus sign that says which side you\u0026rsquo;re on. The collection of these distances, one for every point, is the distance field.\nA fragment shader can call the function for every pixel and colour the pixel by the sign: negative means inside, so paint it. That\u0026rsquo;s a complete shape, with no triangles.\nA Gallery of Shapes Choose a shape below. Switch to Distance field to see the distance at every point as contour lines (orange outside, blue inside, a line every 0.1 units, white on the edge itself). Hover over or tap anywhere to measure: the pink circle around the point has a radius equal to the distance, so it always just touches the nearest edge. Drag the shape by its centre.\nShapes described by signed distance functions\nShape Circle Box Line segment Hexagon Triangle Show Shape Distance field Raw distances (grey) Turn: Scale: Rounding: Hollow (onion): The shader code for this picture, with the current numbers filled in:\nThe code under the demo is what the fragment shader runs for every pixel; the lines that move, turn, scale, round and hollow the shape are explained further down. Try Raw distances (grey): each pixel\u0026rsquo;s distance is shown directly as a shade, mid grey on the edge, darker inside and lighter outside. That\u0026rsquo;s exactly what a distance field looks like when it\u0026rsquo;s saved as a texture, as SDF part 3 does for text.\nThe circle The simplest possible SDF. The distance from a point to a circle\u0026rsquo;s edge is its distance to the centre, minus the radius:\nfloat sdCircle(vec2 p, float r) { return length(p) - r; } In words: p is the point being measured, as an (x, y) position measured from the circle\u0026rsquo;s centre; r is the circle\u0026rsquo;s radius; length(p) is how far p is from the centre (Pythagoras, from the vectors post). float and vec2 just say what kind of value each one is: a single number, or a pair of numbers.\nA point 0.8 from the centre of a circle of radius 0.5 is 0.3 outside; a point 0.2 from the centre is 0.3 inside (−0.3).\nThe box: using symmetry A box centred on the origin looks the same in all four corners, so the function first folds every point into the top-right quarter with abs(p). Then abs(p) − b says how far the point sticks out past the box, in x and in y:\nfloat sdBox(vec2 p, vec2 b) { vec2 q = abs(p) - b; // how far past the edges, in x and y return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0); // outside part + inside part } Here p is the point, measured from the box\u0026rsquo;s centre, and b holds the box\u0026rsquo;s half-width and half-height (b.x and b.y), so a box 1.2 wide and 0.7 tall has b = (0.6, 0.35). abs(p) makes both of p\u0026rsquo;s numbers positive, which is the folding; q is how far past the edges the folded point is, in x and in y (negative means not past that edge). On a pair of numbers, max(q, 0.0) works on each number separately, turning the negative ones into 0.\nIf the point sticks out in both x and y, it\u0026rsquo;s beyond a corner, and the distance is the length of that diagonal (length(max(q, 0.0))). If it sticks out in only one direction, that\u0026rsquo;s the distance to the nearest edge. Inside the box, both parts of q are negative, and the second term picks the nearest edge as a negative distance. Look at the distance field: outside, the contours turn into quarter-circles around each corner.\nThe line segment: projection The distance to a line segment from a to b is the distance to the nearest point on it. That nearest point comes from the dot product: project the point onto the line, then clamp (lerp, clamp and friends) so it can\u0026rsquo;t go past either end. A line has no inside, so its distance is never negative. Add some rounding to it in the demo and it becomes a solid capsule: every point within that distance of the segment.\nPolygons The hexagon and triangle use the same trick as the box, cleverly: fold the point using the shape\u0026rsquo;s symmetry until only one edge needs measuring. Inigo Quilez has worked out exact distance functions for dozens of shapes; see Further Reading.\nDrawing Them Smoothly The test \u0026ldquo;is the distance below 0?\u0026rdquo; gives hard, jagged edges, as with any yes-or-no test (Rasterisation). But because we know the actual distance, we can do better: fade from inside to outside over about one pixel. The function fwidth(d) tells us how much the distance changes from one pixel to the next (the fwidth post), so:\nfloat d = sdBox(p, vec2(0.6, 0.35)); float w = fwidth(d); float inside = 1.0 - smoothstep(-w, w, d); // 1 inside, 0 outside, blended across one pixel This edge stays perfectly smooth at any zoom, which is one of the main reasons SDFs are so popular for user interfaces, icons and text.\nMoving, Turning, Scaling, Rounding and Hollowing Here\u0026rsquo;s the clever bit. To move a shape, you don\u0026rsquo;t change the shape: you change the point before measuring, in the opposite direction. To draw a circle centred at (0.3, 0.2), measure sdCircle(p − vec2(0.3, 0.2), r). To turn the shape by 30°, turn the point by −30° first. To scale it by 2, measure the point divided by 2, then multiply the answer by 2 so it\u0026rsquo;s still a true distance. It\u0026rsquo;s the same idea as the view matrix moving the world instead of the camera.\nTwo more operators work on the distance itself:\nRounding: subtract a number, d − r, where d is the distance the shape\u0026rsquo;s function gave and r is how much to round by. Every edge moves outwards by r, and sharp corners become round. Try it on the box and the triangle. Hollowing, often called onion: abs(d) − thickness, where thickness is half the width of the shell you want. Taking abs makes both sides of the edge positive, so you\u0026rsquo;re left with a thin shell around the original edge. Apply it twice for two shells. Under the hood These functions are cheap: a few multiplications, an abs, a max and a square root, all things graphics cards do in an instruction or two. A fragment shader can easily evaluate dozens of shapes per pixel at full frame rate. The catch is that the cost is paid for every pixel the shader covers, whether the shape is there or not, so large SDF scenes are usually drawn only inside a rectangle around each shape, or with the distances pre-computed into a texture (as SDF part 3 does).\nQuestions You Might Have Are SDFs actually used in games? Yes, widely: for crisp text and icons (SDF part 3), user interface shapes, decals, and effects. Unreal Engine, for example, stores simplified distance fields of the scene for soft shadows and ambient occlusion.\nSummary A signed distance function gives the distance to a shape\u0026rsquo;s edge: positive outside, negative inside, zero on it. Circle: length(p) − r. Box and polygons use symmetry (abs) to fold the point. Segments use a clamped projection. fwidth and smoothstep turn a distance into a smooth, one-pixel edge at any size. Move, turn and scale by changing the point the opposite way; round with d − r; hollow with abs(d) − t. Next: combining shapes and bending space.\nFurther Reading Inigo Quilez, 2D distance functions: the definitive collection of exact 2D SDFs, with live examples. The Book of Shaders, Shapes: drawing shapes with distance functions, step by step. ","permalink":"https://fragmentshack.com/posts/signed-distance-fields/","summary":"Describe a shape by how far every point is from its edge, and you get crisp edges at any size, easy outlines and much more. See how circles, boxes, lines and polygons are written as distance functions.","title":"🔵 Signed Distance Fields: Shapes Made of Distances"},{"content":"Introduction The lighting in Basic Lighting has a big gap: it works out how much each surface faces the light, but never checks whether anything is in the way. Everything is lit, even the ground under a table. Shadows are one of the most important clues our eyes use to understand a 3D scene, and the most common way games draw them is shadow mapping. This post covers:\nThe idea: a point is in shadow if the light can\u0026rsquo;t see it The two passes: drawing a shadow map from the light, then comparing against it The three classic problems: shadow acne, jagged edges and hard edges, with their fixes It combines render targets, the depth buffer and cameras.\nThe Idea: What Can the Light See? Stand where the light is and look at the scene. Every surface you can see is lit. Every surface hidden behind something else is in shadow. So to find shadows, we need to know, for any point, whether it\u0026rsquo;s the nearest thing to the light in that direction.\nThat\u0026rsquo;s exactly what a depth buffer records: the distance to the nearest surface at every pixel. So shadow mapping draws the scene twice:\nFrom the light. Put a camera at the light, pointing the way the light shines, and draw the scene\u0026rsquo;s depth only into a render target. This depth texture is the shadow map: for every direction, how far the light reaches before hitting something. A directional light like the sun uses an orthographic camera (cameras), since its rays are parallel. From the camera. Draw the scene normally. For each pixel, also work out where that point lands in the light\u0026rsquo;s view and how far it is from the light, then look up the shadow map there. If the shadow map holds a nearer depth, something is between this point and the light: it\u0026rsquo;s in shadow. In the fragment shader, the test is a single comparison:\nvec3 p = lightSpacePosition.xyz / lightSpacePosition.w * 0.5 + 0.5; // 0..1 in the shadow map float closest = texture(uShadowMap, p.xy).r; // nearest surface to the light, in this direction float shadow = p.z - bias \u0026gt; closest ? 1.0 : 0.0; // something nearer? then we\u0026#39;re in shadow Here lightSpacePosition is this pixel\u0026rsquo;s position as the light\u0026rsquo;s camera sees it (the world position multiplied by the light\u0026rsquo;s view and projection matrices). The variable p is the same position turned into shadow-map terms: p.xy says where to look in the shadow map, and p.z is this point\u0026rsquo;s depth from the light. The value closest is the depth stored in the shadow map there, and bias is a tiny allowance explained below. The first line does the divide by w from part 5 of the fundamentals, then turns −1 to 1 into 0 to 1, the range used to read a texture. The last line uses a ? b : c (\u0026ldquo;if a, then b, otherwise c\u0026rdquo;).\nTry It The inset in the corner is the shadow map itself: the scene\u0026rsquo;s depth as seen from the light (darker is nearer). Move the light around and watch the shadows and the shadow map change together. Drag the main view to look around.\nShadow mapping, with the light’s depth map shown in the corner\n▶ Play Light direction: Light height: Shadow map size 64 × 64 128 × 128 256 × 256 512 × 512 1024 × 1024 2048 × 2048 Bias: Soften edges (PCF) Show the shadow map The Classic Problems Shadow acne Drag the bias to 0. Lit surfaces break out in stripes and blotches of shadow, called shadow acne. Each shadow map texel covers a small patch of surface but stores just one depth. Across that patch, the real surface is sometimes slightly in front of the stored depth and sometimes slightly behind it, so it shadows itself in a pattern. Lower the light to make it worse: at a shallow angle, the depth changes more across each texel.\nThe fix is the bias: subtract a little from the depth before comparing, so a surface never shadows itself. Too much bias causes the opposite problem, peter-panning: the shadow detaches from the base of the object, so it seems to float. (Raise the bias right up and look at the bottom of the box.) Real engines scale the bias with the surface\u0026rsquo;s angle to the light, to need as little as possible.\nJagged edges Set the shadow map size to 64 × 64. The shadow edges turn into big blocky staircases: each shadow map texel now covers about 15 cm of the floor (if one unit is a metre), and every pixel in that patch gets the same answer. Larger shadow maps help but cost memory and time, and big outdoor scenes need shadows near the camera to be sharp and shadows far away to exist at all. Most games solve that with cascaded shadow maps: several shadow maps, each covering a bigger area further from the camera.\nHard edges Real shadows have soft edges, because real lights aren\u0026rsquo;t single points. Tick Soften edges (PCF). Percentage-closer filtering makes the comparison at nine nearby points of the shadow map and averages the results, giving a soft transition. (Averaging the depths first wouldn\u0026rsquo;t work: you\u0026rsquo;d get a meaningless in-between depth, not a softer shadow.)\nUnder the hood Graphics cards have hardware support for exactly this comparison. A depth texture can be given a compare mode: the texture unit then does the depth comparison itself and returns 0 or 1 instead of a depth. Better still, with linear filtering turned on, it compares the four nearest texels and blends the four results bilinearly, so you get a little PCF for the price of a single texture read. Drawing the shadow map is also cheap per pixel, because it writes only depth and needs no fragment shader work at all, so the graphics card can run it at full speed. Its cost is in drawing all the scene\u0026rsquo;s triangles one extra time per light, per cascade.\nSummary A point is in shadow if something is nearer to the light in its direction. Pass 1 draws the scene\u0026rsquo;s depth from the light into a shadow map; pass 2 compares each pixel against it. Bias prevents shadow acne, but too much causes peter-panning. Shadow map resolution sets how sharp shadows can be; cascades cover large scenes. PCF averages several comparisons to soften the edges. Further Reading Lance Williams, Casting curved shadows on curved surfaces (SIGGRAPH 1978): the paper that introduced shadow mapping. LearnOpenGL, Shadow Mapping: the technique in code, with acne, bias and PCF. Microsoft, Common Techniques to Improve Shadow Depth Maps: a detailed guide to the problems and fixes. Microsoft, Cascaded Shadow Maps: how large outdoor scenes get sharp shadows. ","permalink":"https://fragmentshack.com/posts/shadow-mapping/","summary":"How games draw shadows: render the scene\u0026rsquo;s depth from the light\u0026rsquo;s point of view, then check every pixel against it. See the shadow map itself, and the acne, jaggies and blur that come with it.","title":"🌑 Shadow Mapping: Seeing the Scene from the Light"},{"content":"Introduction Modelling every brick, rivet, scratch and wrinkle with real triangles would take millions of them. Instead, games use a trick that makes flat surfaces look bumpy by changing how they\u0026rsquo;re lit. It\u0026rsquo;s called normal mapping, and it\u0026rsquo;s on almost every surface in modern games. This post covers:\nWhy changing the normal is enough to fake bumps What a normal map is, and why it\u0026rsquo;s mostly blue Tangent space: the local frame that makes normal maps reusable The limits of the trick It builds on Basic Lighting and Textures and UV Coordinates.\nLighting Only Sees the Normal In Basic Lighting, the brightness of a surface depended almost entirely on its normal, the direction it faces, compared with the direction to the light. The lighting maths never looks at the actual shape of the triangles. So if each pixel of a flat surface uses a slightly different normal, tilted the way a bump would be tilted, it will be lit as if the bump were really there: bright on the side facing the light, dark on the side facing away, with highlights in the right places.\nA normal map is a texture that stores, for every texel, which way the surface should face there.\nTry It The wall below is a single flat square: two triangles. The cube is 12. The light moves by itself (press Pause to stop it, or drag to turn the view); toggle the normal map.\nA flat surface lit with and without a normal map\nNormal map Shape Flat wall (2 triangles) Cube (12 triangles) Show Lit result The normal map texture The height map it was made from The final normals, as colours ▶ Play Bump strength: Things to notice:\nWith the normal map, the bricks look raised and the mortar looks sunken, and the shading changes correctly as the light moves. Turn it off and the illusion vanishes. Turn the camera so you\u0026rsquo;re looking along the wall at a grazing angle. The edge is still perfectly straight, and the bricks never hide the mortar behind them. A normal map changes lighting, not shape. Choose Show: The normal map texture. It\u0026rsquo;s mostly a pale blue-purple, with pink and green tints on the slopes. The next section explains why. Why Normal Maps Are Blue A normal is a direction: three numbers (x, y, z), each between −1 and +1. A texture stores colours from 0 to 1. So each component is squeezed into the colour range with colour = normal × 0.5 + 0.5, and the shader undoes it with normal = colour × 2 − 1.\nA normal pointing straight out of a flat surface is (0, 0, 1). Encoded, that\u0026rsquo;s the colour (0.5, 0.5, 1.0): a light blue-purple. Most of a surface is mostly flat, so most of the map is that colour. Where the surface slopes towards +x, the red channel goes up (pinkish); towards +y, green goes up. That\u0026rsquo;s the familiar look of every normal map.\nNormal maps are usually generated automatically, either from a height map like the one in the demo (by measuring how steeply the height changes in each direction), or by \u0026ldquo;baking\u0026rdquo; the detail from a very high-detail sculpted model onto a simpler game model.\nHow the demo makes its normal map from the height map For each texel, it measures the slope of the height map: the height of the texel to the right minus the one to the left (how steeply it rises going across, dh/du), and the one above minus the one below (how steeply it rises going up, dh/dv). These are multiplied by a strength (6 here) to exaggerate the bumps. Then:\nnormal = normalize(−dh/du, −dh/dv, 1) A flat area has no slope, giving (0, 0, 1): straight out. Where the height rises to the right, the normal tips the opposite way, to the left, just as the side of a hill that rises to the right faces left. The function normalize rescales it to length 1 (Vectors). Finally each part, from −1 to 1, is stored as a colour from 0 to 1 by halving it and adding 0.5, as described above.\nTangent Space There\u0026rsquo;s a catch. The normal map says \u0026ldquo;tilt towards +x\u0026rdquo;, but +x of what? The wall faces the camera and the cube\u0026rsquo;s faces point in six different directions, yet they share the same normal map.\nThe answer is that normal maps are stored in tangent space: a little coordinate frame that sits on the surface at each point, lined up with the texture:\nT, the tangent: the direction across the surface in which the texture\u0026rsquo;s u increases B, the bitangent: the direction in which v increases N, the surface\u0026rsquo;s own normal, pointing out Map x means \u0026ldquo;along T\u0026rdquo;, y means \u0026ldquo;along B\u0026rdquo; and z means \u0026ldquo;along N\u0026rdquo;. So the same map works on any surface, at any angle, and even on surfaces that bend and animate. The tangents are calculated from each triangle\u0026rsquo;s positions and UVs and stored with the vertices, alongside the normals. In the shader, converting the map\u0026rsquo;s normal into world space is a small matrix multiplication:\nvec3 m = texture(uNormalMap, vUV).rgb * 2.0 - 1.0; // decode: 0..1 to -1..1 vec3 n = normalize(T * m.x + B * m.y + N * m.z); // tangent space to world space // ...then light with n instead of N (Here uNormalMap is the normal map texture and vUV this pixel\u0026rsquo;s texture coordinate; m is the normal read from the map, in tangent space; n is the result in world space. .rgb picks out the red, green and blue channels of the colour read from the texture; * 2.0 - 1.0 turns 0 to 1 back into −1 to 1.)\nChoose Show: The final normals, as colours to see the result in world space, and compare the cube\u0026rsquo;s faces: the same map gives different world-space normals on each.\nUnder the hood Since a normal has length 1, its z can always be worked out from x and y (using Pythagoras\u0026rsquo; theorem: z = √(1 − x² − y²)). So games usually store only two channels and rebuild z in the shader, using special compressed two-channel formats, which keep normals far more accurate than a general colour format would. And because normal maps are data, not colours, they must never be stored as sRGB textures (sRGB and gamma): decoding them as colours would bend every normal.\nThe Limits of the Trick Normal mapping changes only the lighting, so it breaks down where the real shape would show:\nSilhouettes stay flat, as you saw at grazing angles. Bumps can\u0026rsquo;t hide each other or cast shadows onto each other. Very deep detail looks unconvincing up close. Related techniques go further, at more cost: parallax mapping shifts the texture coordinates per pixel to fake depth, and displacement mapping with tessellation actually moves vertices to create real geometry.\nQuestions You Might Have Why do some normal maps look upside down? There are two conventions for which way the map\u0026rsquo;s green channel (y) points, often called OpenGL style (+y up) and DirectX style (+y down). Using a map made for the other one makes bumps look like dents in one direction; flipping the green channel fixes it.\nSummary Lighting depends on the normal, so tilting the normal per pixel fakes bumps. A normal map stores those normals in a texture as colour = normal × 0.5 + 0.5: mostly blue. Normals are stored in tangent space (tangent, bitangent, normal), so one map works on any surface. It changes lighting, not shape: silhouettes stay flat. Further Reading LearnOpenGL, Normal Mapping: tangent space and the TBN matrix in code. LearnOpenGL, Parallax Mapping: the next step towards real depth. Christian Schüler, Normal Mapping Without Precomputed Tangents: building the tangent frame in the shader with ddx and ddy. Morten Mikkelsen, mikktspace.com: the tangent-space standard most tools now use, so maps look right in every engine. ","permalink":"https://fragmentshack.com/posts/normal-mapping/","summary":"A flat square can look like a bumpy brick wall if each pixel lies about which way it faces. See how normal maps store those directions, and why they\u0026rsquo;re always blue.","title":"🧱 Normal Mapping: Detail Without Triangles"},{"content":"Introduction A screen can only show brightness from 0 (black) to 1 (its brightest white). Real light doesn\u0026rsquo;t stop at 1: the sun is millions of times brighter than a dim room, and even a light bulb is far brighter than a white sheet of paper. If a game simply cut everything off at 1, every bright light, sky and reflection would flatten into the same dull white. This post covers how games handle that:\nHigh dynamic range (HDR) rendering: keeping brightness above 1 while drawing Exposure and tone mapping: squeezing it onto the screen at the end Bloom: the glow around bright lights, made with the blur from the previous post Keeping the Full Range The first step is to stop throwing brightness away. Instead of drawing into a normal 8-bit render target, which can only store 0 to 1 in 256 steps, the scene is drawn into a floating-point render target, usually 16 bits per channel (\u0026ldquo;half floats\u0026rdquo;), which can store values far above 1 with plenty of precision. A glowing lamp can be 20, the sky 5 and a shadowed wall 0.05, all at once. All the lighting is done in linear light (sRGB and gamma), so these numbers really are proportional to the amount of light.\nOnly at the very end of the frame is this HDR image converted to something the screen can show.\nExposure and Tone Mapping A camera has to solve the same problem, and the first tool is the same: exposure. Multiplying the whole image by a number makes it brighter or darker, like opening up a camera\u0026rsquo;s aperture (the hole that lets the light in). Exposure is often measured in stops (EV), where each stop doubles or halves the light. Games often adjust it automatically, which is why stepping out of a dark cave makes the world briefly blinding.\nBut exposure alone can\u0026rsquo;t fit a scene with both deep shadows and bright lights into 0 to 1. Tone mapping is a curve that squeezes any brightness, however large, into that range, compressing bright values more and more so they never quite reach 1, while leaving dark and middle values nearly untouched. The demo below compares a few, after drawing a dark room lit by three glowing balls in HDR. Drag to look around.\nAn HDR scene with exposure, tone mapping and bloom\nTone mapping None (clamp at 1) Reinhard Filmic (ACES fit) Bloom Show Final image Bloom only ▶ Play Exposure: Glow brightness: Bloom threshold: Bloom strength: Things to try:\nTurn bloom off and set tone mapping to None. The glowing balls are flat discs of colour, and the orange one turns a pale yellow, because its red and green channels both hit the limit of 1 and lose their difference. This is what happens without tone mapping. Switch to Reinhard, which divides each value by one plus itself: x ÷ (1 + x). Brightness of 1 becomes 0.5, 10 becomes 0.91, 100 becomes 0.99, so nothing is ever cut off, and the balls get shape again. But mid-tones are dimmed too, and the image looks washed out. Switch to Filmic, a curve designed to imitate the response of camera film. It keeps rich contrast in the shadows and mid-tones and rolls the highlights off gently. It\u0026rsquo;s a fitted approximation of the curve used by ACES, a standard from the film industry, and similar curves are used by many games. Raise and lower the exposure: tone mapping keeps the image looking natural across a much wider range than simply cutting everything off at 1 (called clamping). The second demo plots the three curves: drag across it (or use the slider) to compare them at any brightness. Notice that with no tone mapping, every brightness above 1 looks exactly the same.\nThe formulas behind the three curves For a scene brightness x (applied to red, green and blue separately):\nNone (clamp): min(x, 1): anything above 1 becomes 1. Reinhard: x ÷ (1 + x). Filmic (ACES fit): (x × (2.51x + 0.03)) ÷ (x × (2.43x + 0.59) + 0.14), then clamped to 1. It\u0026rsquo;s a ratio of two simple curves, with numbers chosen by Krzysztof Narkowicz to closely match the much more complicated ACES curve. Near 0 it rises slowly (deeper shadows), in the middle it\u0026rsquo;s steep (more contrast), and for very large x it creeps towards 2.51 ÷ 2.43 ≈ 1.03, which the clamp trims to 1. Exposure simply multiplies x before any of these, like letting more light into a camera.\nTone mapping curves: scene brightness in, screen brightness out\nScene brightness: Bloom When you look at a bright light, through your eyes or a camera lens, it seems to glow and spill over its surroundings. That\u0026rsquo;s caused by light scattering inside the eye or lens. A screen can\u0026rsquo;t actually be bright enough to cause it, so games fake it with bloom:\nBright pass: copy only the parts of the HDR image brighter than a threshold into a smaller render target (a quarter of the resolution here). Blur it heavily, using the separable Gaussian blur from the previous post, several times over. Add the blurred result back on top of the HDR image, before tone mapping. Choose Show: Bloom only to see what gets added. Lower the threshold and more of the scene glows; raise the strength for a dreamier look. It\u0026rsquo;s an effect that\u0026rsquo;s easy to overdo, which many games of the late 2000s famously did.\nWhat the bright pass does, exactly For each pixel, the demo takes its brightness as its largest channel, b = max(red, green, blue), and keeps only the part above the threshold: the colour is multiplied by (b − threshold) ÷ b, or by 0 if b is below the threshold. So with a threshold of 1, a pixel of brightness 3 keeps two thirds of its colour, one of brightness 1.2 keeps a sixth, and anything up to 1 adds no glow at all. Scaling all three channels by the same amount keeps the glow the same colour as the light.\nUnder the hood A 16-bit float render target takes twice the memory, and twice the memory traffic, of an 8-bit one, which matters at 4K. Engines sometimes use cleverly packed formats that squeeze red, green and blue floats into 32 bits per pixel (dropping alpha) to keep the range for less. Bloom is usually built from a chain of downscaled images, each half the size of the last, blurred and added back up the chain; blurring at low resolution is cheap, and combining several sizes gives a glow with a bright core and a wide, soft halo. Finally, \u0026ldquo;HDR rendering\u0026rdquo; is a different thing from an \u0026ldquo;HDR display\u0026rdquo;: HDR rendering is about calculating with a wide range internally; an HDR display can show brighter whites than 1, so the tone mapping step for it maps to a wider output range instead.\nQuestions You Might Have Which tone mapping curve do games use? It\u0026rsquo;s an artistic choice. Filmic curves like the ACES fit here are very common; newer ones such as AgX and engine-specific curves aim to handle very bright, saturated colours more gracefully. Many games let artists adjust the curve per scene.\nSummary HDR rendering stores linear light above 1 in floating-point render targets. Exposure scales the whole image; tone mapping squeezes any brightness into 0 to 1 without cutting it off. Filmic curves keep contrast and roll off highlights smoothly; Reinhard is simpler but flatter. Bloom = bright pass + heavy blur + add back, to imitate glare around bright lights. Next, the last part of the series: anti-aliasing, smoothing jagged edges, with some of the techniques running as post-processing passes like the ones in this series.\nFurther Reading LearnOpenGL, HDR and Bloom: both effects step by step in OpenGL. Krzysztof Narkowicz, ACES Filmic Tone Mapping Curve: the fitted curve used in this demo. Erik Reinhard and others, Photographic Tone Reproduction for Digital Images (SIGGRAPH 2002): the paper behind the Reinhard curve. LearnOpenGL, Physically Based Bloom: the downscale-and-upscale bloom chain used by modern engines. ","permalink":"https://fragmentshack.com/posts/hdr-tone-mapping-bloom/","summary":"Real light ranges from starlight to the sun, but a screen only goes from 0 to 1. See how games keep the full range, squeeze it onto the screen with tone mapping, and fake glare with bloom.","title":"☀️ HDR, Tone Mapping and Bloom: Making Bright Things Look Bright"},{"content":"Introduction Render targets let a fragment shader read a whole finished image. That opens up image processing: effects that change each pixel based on the pixels around it. The most fundamental of these is convolution, and once you understand it, blurring, sharpening, finding edges, glows around bright lights and camera-style focus blur all fall into place. This post covers:\nConvolution kernels: a small grid of weights that defines an effect The classic kernels: blur, sharpen, edge detection and emboss The Gaussian blur, the workhorse of post-processing Separable filters: how splitting a blur into two passes makes it dramatically cheaper Kernels: A Weighted Sum of Neighbours A kernel is a small grid of numbers, for example 3 × 3. To apply it to a pixel, place the kernel\u0026rsquo;s centre over that pixel, multiply each of the nine pixels underneath by the weight on top of it, and add them all up. Then divide by the total of the weights, so the overall brightness stays the same. (If the weights add up to zero, as for edge detection below, there\u0026rsquo;s nothing to divide by: the sum is used as it is.) Do that for every pixel and you\u0026rsquo;ve convolved the image with the kernel.\nIn a fragment shader, that\u0026rsquo;s a short piece of code that repeats nine times (a loop), reading the nine texels around the current one. Edit the weights below, or pick a preset. Sample spacing spreads the nine samples further apart, which exaggerates the effect so it\u0026rsquo;s easier to see on a high-resolution screen.\nApplying a 3 × 3 convolution kernel to an image\nPreset Identity (no change) Box blur Gaussian blur Sharpen Edge detection Emboss Sample spacing: Show original What each preset does:\nBox blur gives all nine pixels the same weight: each pixel becomes the average of its neighbourhood, smoothing out detail. Watch the fine stripes turn grey. Gaussian blur weights the centre most and the corners least, which blurs more smoothly (more on this below). Sharpen gives the centre a big positive weight and the neighbours negative ones. Where a pixel differs from its neighbours, the difference is exaggerated, so edges get crisper. Edge detection has weights that add up to zero. In a flat area, the centre\u0026rsquo;s +8 cancels the eight neighbours\u0026rsquo; −1s exactly, giving black; only where brightness changes does anything survive. This kind of filter is used for outlines and cartoon effects. Emboss is lopsided: it brightens edges on one side and darkens them on the other, which looks like light hitting raised shapes. Try your own: a single 1 in a corner and zeros elsewhere just shifts the image by one sample.\nThe Gaussian Blur A box blur has a problem: every pixel inside the box counts equally and every pixel outside counts not at all, so a bright point blurs into a visible square. A Gaussian blur uses weights that follow the bell-shaped Gaussian curve, strongest in the middle and fading smoothly to nothing. A bright point blurs into a soft, round glow, which looks natural, like an out-of-focus camera. It\u0026rsquo;s used everywhere in post-processing: for glows around bright lights, out-of-focus backgrounds, frosted glass, soft shadows and blurring the background behind menus.\nA nice blur needs a large kernel, though, not 3 × 3. A radius of 10 pixels means a 21 × 21 kernel: 441 texture reads for every single pixel. At 1920 × 1080, that\u0026rsquo;s over 900 million reads for one blur.\nSeparable Filters: Two Passes Instead of One The Gaussian has a beautiful property: blurring horizontally and then blurring the result vertically gives exactly the same result as one big 2D blur. A filter that can be split like this is called separable. So instead of one pass of 21 × 21 = 441 reads, you do one pass of 21 reads across, into a render target, then a second pass of 21 reads down: 42 reads per pixel, more than ten times fewer, for an identical image. The bigger the blur, the bigger the saving.\nA Gaussian blur done in one 2D pass, or as two 1D passes\nMethod One pass, 2D kernel Two passes, horizontal then vertical Horizontal pass only Blur radius: Switch between the two methods at the same radius: the pictures are the same, but the number of reads isn\u0026rsquo;t. Choose Horizontal pass only to see the halfway point, where each row has been smeared sideways on its own. (The 2D method is capped at a radius of 24 here; much larger and it could make your browser stutter.)\nThe box blur is separable too, but many kernels aren\u0026rsquo;t: sharpen, edge detection and emboss above can\u0026rsquo;t be split into a horizontal and a vertical pass.\nHow the Gaussian weights are worked out The weight for a texel x steps from the centre is:\nweight = e−x² ÷ (2σ²) Here e is a mathematical constant (about 2.718), and raising it to a negative power gives a number that starts at 1 when x = 0 and falls smoothly towards 0: the bell curve. σ (\u0026ldquo;sigma\u0026rdquo;) sets how wide the bell is; this demo uses σ = radius ÷ 2.5, so at the edge of the radius the weight has faded to about 4% of the centre weight. In 2D, the weight uses x² + y², the squared distance from the centre.\nFinally each weight is divided by the total of all the weights, so they add up to 1 and the brightness doesn\u0026rsquo;t change. The separable trick works because e−(x² + y²) ÷ (2σ²) is exactly e−x² ÷ (2σ²) × e−y² ÷ (2σ²): every 2D weight is a horizontal weight times a vertical one.\nUnder the hood Real blur shaders cut the cost even further with a trick using bilinear filtering (part 2 of Textures). If you sample exactly between two texels, the texture unit returns their average for the price of one read; sample at just the right point between them and it returns any weighted blend you like. So one carefully placed bilinear sample can do the work of two kernel weights, nearly halving the reads again. Large blurs are also usually done on downscaled copies of the image (half, quarter or smaller), because a blur removes fine detail anyway: blurring a quarter-resolution image by 5 pixels looks almost identical to blurring the full image by 20, at a tiny fraction of the cost.\nQuestions You Might Have What happens at the edges of the image, where some neighbours are missing? Something has to be chosen. A common choice, used here, is to clamp: reading past the edge gives the nearest edge pixel again. Other choices are wrapping round to the opposite side or treating missing pixels as black.\nSummary Convolution replaces each pixel with a weighted sum of its neighbours; the weights form a kernel. Different kernels blur, sharpen, detect edges or emboss. The Gaussian blur looks natural, but large kernels are expensive. It\u0026rsquo;s separable: a horizontal pass then a vertical pass gives the same result for far fewer reads. Next: HDR, tone mapping and bloom, where blur makes bright lights glow.\nFurther Reading Victor Powell, Image Kernels Explained Visually: a lovely interactive explanation of kernels. Daniel Rákos, Efficient Gaussian blur with linear sampling: the bilinear trick in detail. LearnOpenGL, Framebuffers: Kernel effects: kernels as post-processing in OpenGL. Wikipedia, Kernel (image processing) and Gaussian blur: more kernels and the maths of separability. ","permalink":"https://fragmentshack.com/posts/blur-convolution/","summary":"Blur, sharpen, edge detection and emboss are all the same trick: a weighted sum of neighbouring pixels. Edit a kernel live, then see why games blur in two passes instead of one.","title":"🌫️ Blur and Convolution: Post-Processing with Kernels"},{"content":"Introduction Glass, water, smoke, fire, ghosts, user interfaces: games are full of things you can partly see through. The depth buffer handles solid objects beautifully, letting them be drawn in any order. See-through objects break that, and they\u0026rsquo;re one of the classic headaches of real-time graphics. This post covers:\nAlpha and the blend equation the graphics card uses to mix colours The common blend modes: normal, additive, multiply and premultiplied alpha Why transparent objects must be sorted and drawn back to front Alpha and the Blend Equation Alongside red, green and blue, a colour can carry a fourth number, alpha (α), which usually means opacity: 1 is fully solid, 0 is invisible, 0.5 lets half the background through.\nWhen blending is turned on, the graphics card doesn\u0026rsquo;t simply overwrite the pixel in the framebuffer. In the output merging stage (the pipeline), it combines the new fragment\u0026rsquo;s colour, the source, with the colour already there, the destination, using a formula you choose. For a normal see-through surface it\u0026rsquo;s:\nresult = source × α + destination × (1 − α) At α = 0.3, the result is 30% the new surface and 70% whatever was behind it. A program chooses this formula with a single setting: which number to multiply the source by (here α), and which to multiply the destination by (here 1 − α).\nNotice that blending reads the destination: the colour already in the framebuffer. So the result depends on what has been drawn before.\nBlend Modes By changing the two multipliers, the same hardware gives several useful effects. Try them below, with the opacity slider.\nThree overlapping discs drawn with different blend modes\nBlend mode Normal (alpha) Premultiplied alpha Additive Multiply Opacity (α): Normal alpha blending is a see-through layer. Where the discs overlap, whichever was drawn last (blue) looks to be on top. Additive adds light. Overlaps get brighter, red and green make yellow, and all three make white, just like the coloured lights in Pixels and Colour. It\u0026rsquo;s used for fire, sparks, lasers and glows. Notice it barely shows over the light background but shines over the dark band. It also doesn\u0026rsquo;t care about order: addition gives the same result either way round. Multiply can only darken, like layers of tinted glass or the coloured filters used on stage lights. It\u0026rsquo;s used for stains, shadows and decals. It doesn\u0026rsquo;t care about order either. Premultiplied alpha looks identical to normal alpha here. The difference is where the multiplication by α happens: the colour is stored already multiplied by its own alpha, so the blend becomes source + destination × (1 − α), where source is the (already multiplied) colour being drawn, destination is the colour already on screen, and α is the source\u0026rsquo;s alpha. Why premultiplied alpha? If it looks the same, why bother? Because colours stored without premultiplying go wrong when they\u0026rsquo;re filtered or blended in stages. Imagine a texture of a leaf, whose transparent texels are stored as invisible black. When bilinear filtering (part 2 of Textures) blends a green edge texel with a transparent black one, the result is a half-transparent dark green, and the leaf gets a dark fringe. With premultiplied alpha, a transparent texel is (0, 0, 0, 0) and contributes nothing, so filtering just works. It also makes it possible to blend several layers together first and combine the result with the scene later, and lets one blend mode do both normal and additive blending (an α of 0 with a non-zero colour adds light). For these reasons, many engines store and blend premultiplied colours throughout.\nWhy Order Matters Here\u0026rsquo;s the big problem. Solid objects use the depth buffer to sort themselves out, but a transparent surface can\u0026rsquo;t simply hide what\u0026rsquo;s behind it: it has to blend with it. So whatever is behind it must already be in the framebuffer when the transparent surface is drawn. That means transparent objects must be drawn after all the solid ones, and in order from back to front.\nThe demo below has four see-through panes in front of and behind a solid ball. Drag to look around from different angles, and try the options.\nFour transparent panes: draw order and depth writes\nDraw the panes Sorted, far to near In a fixed order Sorted, near to far Panes write to the depth buffer With a fixed order and depth writes on, turn the camera round: from some angles, panes vanish where they overlap. A pane drawn early writes its depth, so a pane behind it drawn later fails the depth test and is never blended in. Turning off depth writes stops things vanishing, but the colours still change with the order. Only sorted, far to near looks right from every angle. (The usual recipe is to sort, and keep the depth test on but depth writes off for transparent objects, so they\u0026rsquo;re still hidden correctly behind solid ones.)\nSorting has limits though. Engines sort whole objects by distance, not individual triangles, so an object that overlaps itself, or two that pass through each other, can still go wrong, and no single order is correct for every pixel. That\u0026rsquo;s why games sometimes use alpha testing instead (each pixel is either fully solid or discarded, so the depth buffer works again; it\u0026rsquo;s common for foliage and fences), or more advanced order-independent transparency techniques.\nUnder the hood Blending is done by fixed-function hardware next to the framebuffer, often called the ROPs (render output units). It needs to read the existing colour and write a new one, so every blended pixel costs extra memory traffic. Transparent effects like smoke are usually many large, overlapping layers, each blended over every pixel it covers: a big cloud can blend dozens of times per pixel. This overdraw is why particle effects (smoke, sparks and dust made of many small overlapping images) are a common performance problem, and why they\u0026rsquo;re often drawn into a lower-resolution render target and then scaled up. The Overdraw post explores the cost.\nSummary Alpha stores opacity; the blend equation mixes the new colour (source) with what\u0026rsquo;s already there (destination). Normal, additive and multiply blending use the same hardware with different multipliers. Premultiplied alpha stores colour × α, which filters and composites correctly. Transparent objects must be drawn after solid ones, sorted back to front, usually without writing depth. Further Reading LearnOpenGL, Blending: blend functions, alpha testing and sorting in OpenGL. Tom Forsyth, Premultiplied alpha: the classic argument for premultiplying everything. Thomas Porter and Tom Duff, Compositing Digital Images (SIGGRAPH 1984): the paper that defined alpha compositing. Morgan McGuire and Louis Bavoil, Weighted Blended Order-Independent Transparency (JCGT 2013): a popular way to avoid sorting. ","permalink":"https://fragmentshack.com/posts/alpha-blending-transparency/","summary":"How the graphics card mixes a see-through surface with what\u0026rsquo;s behind it, the blend modes games use, and why transparent objects must be drawn in the right order.","title":"🫧 Alpha Blending: Why Transparency Is Hard"},{"content":"Introduction So far, every demo on this site has drawn straight to the screen. But the graphics card is just as happy to draw into a texture, which can then be used, like any other texture, in a later draw. That one idea, called rendering to a texture, is behind an enormous number of effects. This post, the first in the Render Targets \u0026amp; Post-Processing series, covers:\nWhat a render target is The simplest use: a live video screen inside a scene Multiple passes, where one pass\u0026rsquo;s output is the next pass\u0026rsquo;s input Ping-ponging between two render targets to build up effects over time What Is a Render Target? In part 1 of the fundamentals, the graphics card wrote its pixels into a framebuffer, the block of memory that becomes the picture on screen. A render target is simply another block of memory you can tell it to draw into instead. It\u0026rsquo;s usually a texture, so after you\u0026rsquo;ve drawn into it, you can sample it in a shader exactly like an image loaded from a file. It can also have its own depth buffer (part 11), so 3D scenes drawn into it work properly.\nIn WebGL, a program makes a render target by creating an empty texture and attaching it to a framebuffer object. While that framebuffer is selected, everything drawn lands in the texture instead of on screen; selecting the normal framebuffer again goes back to drawing on screen.\nA Screen Inside the Scene The demo below draws each frame in two passes. First, it draws the scene from the red security camera into a small render target. Then it draws the scene again from your viewpoint, to the screen, using that render target as the texture on the TV. Drag to look around.\nA live security camera feed, drawn into a render target and shown on a TV\n▶ Play Render target width: Security camera angle: Bilinear filtering on the TV Things to try:\nLower the render target width to 16 or so: the TV picture becomes blocky, because the render target has fewer pixels. Its resolution has nothing to do with the screen\u0026rsquo;s. Games use this freely: reflections, distant views and effects are often drawn at half or quarter resolution to save time. Tick Bilinear filtering: the render target is now sampled like any texture (texture filtering), so the blocks blend smoothly. The security camera\u0026rsquo;s picture doesn\u0026rsquo;t include the TV. If it did, drawing the TV into the render target would mean reading the render target while drawing into it. That\u0026rsquo;s called a feedback loop: it isn\u0026rsquo;t allowed, and WebGL reports an error. Games that need it (a TV showing itself, or two facing mirrors) use the previous frame\u0026rsquo;s picture instead. Passes and Post-Processing Each \u0026ldquo;draw everything into one target\u0026rdquo; step is called a pass. Real games use many passes per frame. A typical modern frame might draw the scene from each light\u0026rsquo;s point of view to work out shadows (Shadow Mapping), then the scene itself, then the lighting, then see-through objects, then a chain of post-processing passes that each read the previous result and write a changed version: blurs, a glow around bright lights, colour adjustments, smoothing of jagged edges and so on. The final pass writes to the screen. The rest of this series looks at some of those passes.\nA post-processing pass usually draws just a single triangle (or rectangle) that covers the whole render target, with a fragment shader that reads the previous pass\u0026rsquo;s texture. Its fragment shader runs once for every pixel, which is exactly what you want for an effect that changes the whole image.\nPing-Pong: Building Up Effects over Time What if an effect needs to read last frame\u0026rsquo;s result, for example to leave trails? A pass can\u0026rsquo;t read and write the same texture, so the trick is to use two render targets and swap them every frame: read from A and write to B, then read from B and write to A. This is called ping-ponging.\nThe demo below does exactly that. Each frame reads the previous frame, draws it slightly zoomed, turned and faded, then paints a new blob of colour on top. Move your pointer over it (or tap and drag) to paint.\nPing-pong feedback: each frame is built from the last one\n▶ Play Fade: Zoom: Turn per frame: The same idea, used far more subtly, powers modern techniques for smoothing jagged edges and sharpening upscaled pictures, which blend each new frame with carefully lined-up previous ones, and many simulations of water, smoke and fire that run entirely on the graphics card.\nUnder the hood Switching render targets isn\u0026rsquo;t free. Most mobile graphics cards, and many desktop ones to some degree, are tile-based: they split the target into small tiles and keep each tile in a small, very fast memory inside the chip while drawing it, writing it out to main memory only once it\u0026rsquo;s finished. Every time you switch to a new render target, the finished tiles of the old one have to be written out, and if you later read it back as a texture, it has to come back in from main memory. That memory traffic often costs more than the drawing itself. That\u0026rsquo;s why graphics APIs let a program say whether a target\u0026rsquo;s old contents need to be loaded and whether its results need to be kept, so the driver can skip unnecessary copies, and why engines try to combine passes where they can.\nQuestions You Might Have Is the screen a render target too? Yes. The picture that ends up on screen is drawn into the default framebuffer, which the browser or operating system provides. Your own render targets work just like it, except you can read them afterwards as textures.\nSummary A render target is a texture (plus optional depth buffer) that the graphics card draws into instead of the screen. It can then be sampled like any texture, in a later pass. Its resolution is independent of the screen\u0026rsquo;s. A pass can\u0026rsquo;t read the target it\u0026rsquo;s writing; ping-ponging between two targets lets effects build up over time. Modern frames are chains of many passes, ending with post-processing. Next: alpha blending and transparency, and why see-through objects are surprisingly hard.\nFurther Reading LearnOpenGL, Framebuffers: render targets and simple post-processing in OpenGL. WebGL2 Fundamentals, Rendering to a Texture: the same in WebGL2, step by step. Adrian Courrèges, GTA V: Graphics Study: a frame of a real game taken apart pass by pass. Wikipedia, Tiled rendering: how tile-based graphics cards work, and why render target switches matter on them. ","permalink":"https://fragmentshack.com/posts/render-targets/","summary":"The graphics card doesn\u0026rsquo;t have to draw to the screen. Draw into a texture instead, and you get security cameras, mirrors, shadows and every post-processing effect in modern games.","title":"🖼️ Render Targets: Drawing into Textures"},{"content":"Introduction Part 1 of the fundamentals said that colours are stored as numbers from 0 to 255, and warned that 128 isn\u0026rsquo;t half as bright as 255. This post explains that warning properly, because it affects almost every texture, every blend and every lighting calculation a game does:\nWhy images store brightness unevenly, using a curve called sRGB The difference between encoded values and linear light What goes wrong when you do maths on encoded values How graphics cards convert between the two for free Find the Real Half The left swatch below is a fine checkerboard of pure black and pure white pixels: exactly half the pixels are fully lit, so it gives off exactly 50% of white\u0026rsquo;s light. The right swatch has the value 128, \u0026ldquo;half\u0026rdquo; of 255. The middle one is yours to adjust.\nStep back from your screen, or squint, until the checkerboard blurs into a flat grey. Then move the slider until the middle swatch matches it.\nA checkerboard (exactly 50% light), your grey, and the value 128\nMiddle swatch value: Below: 16 steps evenly spaced in stored value (top), and 16 steps evenly spaced in light (bottom).\nOn most screens, the match is around 188, not 128. Value 128 gives off only about 22% of white\u0026rsquo;s light.\nNow look at the ramps. The top ramp\u0026rsquo;s values go up in even steps, and it looks even. The bottom ramp\u0026rsquo;s light goes up in even steps, but it looks lopsided: it rushes towards white, with hardly any dark shades. That\u0026rsquo;s the key: our eyes don\u0026rsquo;t see light evenly. We\u0026rsquo;re far more sensitive to differences between dark shades than between bright ones.\nWhy Images Are Stored This Way An 8-bit channel only has 256 values to spend. If they were spread evenly in light, many would be wasted on bright shades we can barely tell apart, and too few would be left for the dark shades, which would show visible bands. So images spend their values to match our eyes: more of them on dark shades, fewer on bright.\nThe standard that defines exactly how is called sRGB. To turn a stored value into an amount of light, it uses a curve that\u0026rsquo;s close to raising the value (from 0 to 1) to the power of 2.2, roughly \u0026ldquo;multiplying it by itself 2.2 times\u0026rdquo;. Raising a number between 0 and 1 to a power makes it smaller, and small numbers shrink fastest, so dark values end up much darker in light. (A short straight section near black avoids problems at zero.)\nThe exact sRGB formula For a stored value c from 0 to 1, the amount of light is:\nIf c ≤ 0.04045: light = c ÷ 12.92 (the short straight section) Otherwise: light = ((c + 0.055) ÷ 1.055)2.4 The power is 2.4, not 2.2, but the shift by 0.055 and the straight section make the overall curve follow a power of 2.2 very closely. Going the other way, light to stored value, uses the reverse: 12.92 × light near black, and 1.055 × light1 ÷ 2.4 − 0.055 above that. For example, a stored value of 128 (0.502) gives off about 21.6% of white\u0026rsquo;s light, not 50%.\nlight ≈ value2.2 \u0026nbsp;\u0026nbsp;so\u0026nbsp;\u0026nbsp; 0.52.2 ≈ 0.22 That\u0026rsquo;s the \u0026ldquo;gamma\u0026rdquo; in \u0026ldquo;gamma correction\u0026rdquo;. (It dates back to old CRT (cathode-ray tube) televisions and monitors, whose brightness responded to the electrical signal in roughly this way, so storing images like this was convenient then too.)\nSo there are two ways to describe a colour:\nEncoded (or \u0026ldquo;gamma\u0026rdquo;) values: what\u0026rsquo;s stored in image files, textures and the framebuffer. Even steps look even. Linear values: proportional to the actual amount of light. Doubling the number doubles the light. Maths Needs Linear Light Light adds up physically: two lamps give twice the light of one. So any calculation that adds, averages or scales light, such as lighting, blending, blurring and mipmap averaging, is only correct on linear values. Do it on encoded values and the results come out too dark, too bright or the wrong colour.\nThe demo shows the same two calculations both ways. The top half blends between two colours; the bottom adds together three coloured spotlights.\nBlending and adding light: on encoded values versus on linear light\nMaths on encoded values (wrong) Maths on linear light (right) Colour A Colour B With red and green, the left gradient goes through a dark, muddy olive in the middle: averaging the stored values gives (128, 128, 0), which is far too little light. The right one passes through a bright yellow, as real red and green light do when mixed. Try other colours: blue to yellow, or black to white. In the spotlights, the left version\u0026rsquo;s overlaps are too bright and harsh, because it adds the stored values of the lights rather than the lights themselves.\nThe same mistake makes mipmaps and blurs too dark around bright details, makes anti-aliased edges look thin or chunky, and makes lighting falloff look harsh. The rule is simple: decode to linear, do your maths, encode at the end.\nUnder the hood Graphics cards do the conversions for free in hardware. A texture created with an sRGB format (every API has one) is decoded to linear automatically every time it\u0026rsquo;s sampled, before filtering, so even bilinear blends and mipmap lookups are done on linear values. In the other direction, an sRGB render target (an image the graphics card draws into, covered in the next series) encodes the shader\u0026rsquo;s linear output automatically when it\u0026rsquo;s written, and blending then happens in linear space too. The only rule is to use sRGB formats for colour images (photos, painted textures) and plain formats for data that isn\u0026rsquo;t colour, such as normal maps and how rough each part of a surface is, which should never be decoded.\nQuestions You Might Have Does WebGL convert for me? It can for textures: one created with an sRGB format such as SRGB8_ALPHA8 is converted to linear automatically every time it\u0026rsquo;s read. Output to the canvas isn\u0026rsquo;t converted automatically, so shaders usually convert back to sRGB at the end themselves.\nSummary Stored colour values are encoded with the sRGB curve, so even steps of value look even. The actual light is roughly value2.2: 128 gives about 22% of the light, and 50% light is about 188. Blending, lighting, blurring and averaging must happen on linear values. sRGB texture and render target formats convert automatically, in hardware. That completes the Textures \u0026amp; Sampling series! Next, the Render Targets \u0026amp; Post-Processing series starts drawing into textures instead of the screen.\nFurther Reading John Novak, What every coder should know about gamma: a thorough, well-illustrated explanation with many examples. LearnOpenGL, Gamma Correction: sRGB textures and framebuffers in OpenGL. Alexander Houghton, Visualising sRGB \u0026amp; Gamma Correction: more interactive demos on the same topic. Wikipedia, sRGB: the exact curves and the history of the standard. ","permalink":"https://fragmentshack.com/posts/srgb-gamma/","summary":"The numbers in an image aren\u0026rsquo;t amounts of light. Find the grey that really is half as bright, then see what goes wrong when blending and lighting ignore it.","title":"🌗 sRGB and Gamma: Why 50% Grey Isn’t Half as Bright"},{"content":"Introduction Mipmaps stop distant textures from shimmering, but they leave a problem: floors, roads and walls seen at a shallow angle turn into a smeary blur long before they should. If you\u0026rsquo;ve ever turned on anisotropic filtering in a game\u0026rsquo;s settings and watched the ground suddenly sharpen, this post explains what changed:\nWhy a pixel\u0026rsquo;s footprint on a texture gets stretched when you look at a surface at an angle Why trilinear filtering has to choose between blurry and shimmery in that case How anisotropic filtering takes several samples along the footprint to get both right \u0026ldquo;Anisotropic\u0026rdquo; means \u0026ldquo;not the same in every direction\u0026rdquo;, and that\u0026rsquo;s exactly the problem.\nSide by Side Both halves of the demo below show the same floor and the same texture. The left uses trilinear filtering only; the right adds anisotropic filtering. Lower the camera to make the viewing angle shallower.\nTrilinear (left) and trilinear plus anisotropic filtering (right)\nTrilinear onlyWith anisotropic filtering Anisotropic level 1× (off) 2× 4× 8× 16× Texture Words and lines Colour grid Camera height: On the left, the words become unreadable only a short way into the distance, and the lines running away from you dissolve. On the right, they stay sharp much further. Raise the camera to look straight down and the two halves look almost identical: anisotropic filtering only matters at shallow angles.\nWhy Trilinear Gets Blurry Imagine a single square pixel projected onto the floor. Looking straight down, it covers a square patch of texture. But looking along the floor at a shallow angle, the same pixel covers a long, thin patch, stretched away from you: perhaps 1 texel wide but 8 texels long. That patch is the pixel\u0026rsquo;s footprint.\nMipmapping assumes the footprint is square. It has to pick a single level, and the graphics card picks it from the longest side of the footprint (measured by comparing neighbouring pixels\u0026rsquo; UVs), because choosing from the short side would leave 8 texels along the long side unaccounted for, and the shimmering would come back. So for our 1 × 8 footprint it reads level 3, where each texel is 8 texels across. That\u0026rsquo;s right along the footprint\u0026rsquo;s length but 8 times too blurry across its width.\nHow Anisotropic Filtering Fixes It Anisotropic filtering takes several samples along the long side of the footprint instead of one. For a 1 × 8 footprint, it can take 8 samples spaced along it, each from a sharper level that suits the short side, and average them. The result is filtered correctly in both directions.\nThe diagram below shows a pixel\u0026rsquo;s footprint (orange) on a grid of level-0 texels, and the area each method samples (blue).\nOne pixel’s footprint on the texture, and what each method samples\nViewing angle above the surface: Maximum level 2× 4× 8× 16× The anisotropic level setting (2×, 4×, 8×, 16×) is the maximum number of samples per pixel. Footprints more stretched than that are given the maximum and slightly blurred, as trilinear would. Most graphics cards support up to 16×, which covers all but the most extreme angles.\nHow the diagram works out its numbers Imagine a pixel as a small square window looking down at the floor. Looking straight down (90°), it sees a square patch of texture. Tilt the view to a lower angle and the same window sees a patch stretched away from you, roughly 1 ÷ sin(angle) times longer than it is wide: about 2× at 30°, 5.8× at 10° and 14× at 4°. (Angles, Sine and Cosine explains sin.) The diagram assumes the short side is one texel and caps the long side at 16.\nTrilinear picks its mipmap level from the long side: level = log₂(long side), meaning the power of 2 that gives the long side. A footprint 8 texels long gets level 3 (2³ = 8), where one texel covers 8 level-0 texels in both directions. Anisotropic takes N = (long side ÷ short side), rounded up, samples, but never more than the maximum you chose. Each sample covers long side ÷ N, so it uses level log₂(long side ÷ N): level 0, full sharpness, whenever the maximum is big enough. The real hardware rule isn\u0026rsquo;t fixed by the standard, but it follows this idea.\nUnder the hood The extra samples are taken by the texture unit itself, not your shader: the shader still makes one texture() call. Each sample is a full trilinear lookup, so 16× can mean up to 16 times the texture reads for those pixels. In practice it\u0026rsquo;s much cheaper than that sounds: the number of samples adapts per pixel, so surfaces facing the camera use just one; neighbouring pixels read overlapping texels that are already in the texture cache; and hardware vendors use clever approximations to cut the work further. That\u0026rsquo;s why modern games often turn it on by default with only a small performance cost. The exact method isn\u0026rsquo;t standardised: the OpenGL and WebGL description suggests an approach (take up to N samples along the long side, choosing the mip level from the long side divided by N, roughly as in the diagram) but lets hardware approximate it.\nIn WebGL, anisotropic filtering is an optional extra feature (an extension) that nearly every browser supports. A program switches it on for each texture, choosing the maximum level.\nSummary At shallow viewing angles, a pixel\u0026rsquo;s footprint on a texture becomes long and thin. Trilinear filtering chooses its mip level from the long side, so it\u0026rsquo;s too blurry across the short side. Anisotropic filtering takes several samples along the long side from a sharper level. The setting (2× to 16×) is the maximum number of samples; the cost is usually modest. Next: sRGB and gamma, the reason a texture\u0026rsquo;s numbers don\u0026rsquo;t mean what you\u0026rsquo;d expect.\nFurther Reading Khronos, EXT_texture_filter_anisotropic: the extension specification, including the suggested sampling method. MDN, EXT_texture_filter_anisotropic: using it in WebGL. Wikipedia, Anisotropic filtering: history and comparison images. Paul Heckbert, Fundamentals of Texture Mapping and Image Warping (1989): the classic thesis on texture footprints and filtering. ","permalink":"https://fragmentshack.com/posts/anisotropic-filtering/","summary":"Trilinear filtering turns floors and roads seen at a low angle into blur. Anisotropic filtering fixes it by sampling along the pixel\u0026rsquo;s stretched footprint. Compare them side by side.","title":"🛤️ Anisotropic Filtering: Sharp Textures at Steep Angles"},{"content":"Introduction Part 2 ended with a problem: when a texture is far away, each screen pixel covers many texels, but bilinear filtering only reads the four nearest the pixel\u0026rsquo;s centre. The rest are ignored, so the colour depends on exactly where the centre lands, and distant textures shimmer as the camera moves. This post covers the standard fix:\nMipmaps: a chain of smaller, pre-averaged copies of the texture How the graphics card picks which copy to use Trilinear filtering, which blends between copies The LOD bias setting Later, the ddx and ddy post on mipmaps shows exactly how the graphics card measures how many texels a pixel covers. This post focuses on the mipmaps themselves.\nThe Idea: Average in Advance The right colour for a pixel that covers, say, a 4 × 4 patch of texels is the average of all 16. Reading 16 texels for every pixel would be slow, and a pixel could cover thousands. So instead, the averaging is done once, in advance.\nA mipmap chain (from the Latin multum in parvo, \u0026ldquo;much in little\u0026rdquo;) stores the texture at a series of sizes. Level 0 is the full texture. Level 1 is half the width and half the height, each texel the average of a 2 × 2 block of level 0. Level 2 halves it again, and so on, down to a single texel holding the average colour of the whole texture.\nA 256 × 256 texture and its mip chain, made by averaging 2 × 2 blocks\nTexture Bricks Fine stripes Small checkerboard Show every level at the same size Tick Show every level at the same size to see each level magnified. Each one is a blurrier version of the one before. With Fine stripes, the stripes survive a few levels, then suddenly every texel is half black and half white, and the level becomes flat grey. That\u0026rsquo;s correct: from far enough away, fine stripes really should look grey.\nThe cost is surprisingly small. Each level has a quarter as many texels as the one before, so the whole chain adds 1/4 + 1/16 + 1/64 + … which comes to only one third more memory than the texture alone.\nChoosing a Level For each pixel, the graphics card estimates how many texels the pixel covers, by comparing its UV with its neighbouring pixels\u0026rsquo; UVs: if the UV jumps a long way from one pixel to the next, each pixel must cover many texels. If one pixel step covers about one texel, it uses level 0. If it covers about 2 texels, level 1, where texels are twice as big; 4 texels, level 2; 8 texels, level 3; and so on. In general, the level is how many times you\u0026rsquo;d have to halve the number of texels per pixel to get down to 1 (mathematicians call this the base-2 logarithm). This number is called the level of detail, or LOD.\nThe LOD is usually a fraction, like 2.4, and there are two ways to handle that:\nNearest level: round to the nearest level and use bilinear filtering within it. Trilinear filtering: use bilinear filtering in both neighbouring levels (2 and 3 here) and blend the two results, 60% level 2 and 40% level 3. That\u0026rsquo;s eight texels in all, blended in three directions: hence tri-linear. Try It The floor below repeats a texture many times into the distance. It scrolls by itself (press Pause to stop it): compare the filtering modes, and try the different textures.\nA textured floor with different minification filters\nFiltering No mipmaps Mipmaps, nearest level Trilinear Show mip levels as colours Texture Bricks Fine stripes Small checkerboard ▶ Play LOD bias: Things to notice:\nNo mipmaps looks sharp in a still picture, but the distance is full of noise and swirling patterns (moiré), and they crawl as it moves. Mipmaps, nearest level is calm, but you can see lines across the floor where it suddenly switches level. They move with the camera, which is very distracting in a game. Trilinear hides the switches completely. Choose Show mip levels as colours to see the bands that the blending smooths over. The LOD bias adds a fixed amount to every pixel\u0026rsquo;s level. A negative bias sharpens textures, but brings the shimmering back; a positive bias blurs them. Games sometimes use a small negative bias when they render at a lower resolution and then upscale. Trilinear filtering\u0026rsquo;s one weakness is that distant surfaces seen at a steep angle, like the far end of this floor, look too blurry. That\u0026rsquo;s because the level is chosen from the longest side of the pixel\u0026rsquo;s footprint: the patch of texture it covers. Anisotropic filtering, the next part, fixes that.\nUnder the hood Mipmaps are usually generated offline, by the tools that prepare a game\u0026rsquo;s textures, using better filters than a simple 2 × 2 average, then stored compressed. They can also be generated when the game loads, with a single call in most graphics APIs, which the driver usually implements by running its own small shader on the graphics card. Mipmaps also make rendering faster: a distant surface that reads small levels touches far less memory, and neighbouring pixels read neighbouring texels, so the texture cache works much better. Without mipmaps, every pixel of a distant surface jumps to a different, far-apart spot in a large texture.\nSummary A mipmap chain stores the texture at half, quarter, eighth size and so on, each pre-averaged, for only ⅓ more memory. The graphics card picks a level from how many texels a pixel covers, measured by comparing neighbouring pixels\u0026rsquo; UVs. Trilinear filtering blends the two nearest levels, hiding the switch from one to the next. Without mipmaps, distant textures shimmer; with them, they\u0026rsquo;re stable, faster and slightly blurry. Further Reading Lance Williams, Pyramidal Parametrics (SIGGRAPH 1983): the paper that introduced mipmapping. LearnOpenGL, Textures: Mipmaps: mipmap filtering modes in OpenGL. Wikipedia, Mipmap and Trilinear filtering: the history and the details. Khronos, The OpenGL 4.6 specification, section 8.14 \u0026ldquo;Texture Minification\u0026rdquo;: the exact rules for choosing and blending mip levels. ","permalink":"https://fragmentshack.com/posts/mipmaps-trilinear-filtering/","summary":"Distant textures sparkle and swirl because each pixel covers many texels. Mipmaps fix it with pre-shrunk copies of the texture. Build a mip chain, then drive over a floor with and without one.","title":"🪆 Mipmaps and Trilinear Filtering: Stopping Distant Textures from Shimmering"},{"content":"Introduction Part 1 gave every pixel a UV coordinate saying where to read the texture. But a texture is a grid of texels, and a UV like (0.42, 0.58) almost never lands exactly on the centre of one. So which colour should the pixel get? Choosing it is called texture filtering. This post covers:\nWhere texels actually sit in UV space Nearest filtering, the blocky one Bilinear filtering, which blends the four nearest texels Magnification versus minification: why filtering a texture that\u0026rsquo;s smaller on screen is a much harder problem Where Are the Texels? A texture 8 texels wide covers UVs from 0 to 1, so each texel is 1/8 = 0.125 wide. Texel 0 covers 0 to 0.125, texel 1 covers 0.125 to 0.25, and so on. The centre of texel i is at (i + 0.5) ÷ 8: 0.0625, 0.1875 and so on. Exactly as with pixels and pixel centres in rasterisation, the half matters.\nNearest Filtering The simplest answer is to use whichever texel the UV falls inside. This is nearest filtering (also called point sampling). It\u0026rsquo;s fast, as it reads only one texel, but when a texture is stretched over a large area of the screen, each texel becomes a visible square block, and the colour jumps abruptly at the edge of each one.\nBilinear Filtering Bilinear filtering instead finds the four texel centres that surround the UV and blends them, weighted by how close the UV is to each. It\u0026rsquo;s two rounds of the linear blending (\u0026ldquo;lerp\u0026rdquo;, see Interpolation) from fragment shaders, hence bi-linear: first blend the two bottom texels and the two top texels horizontally, then blend those two results vertically. The colour changes smoothly from one texel centre to the next, with no visible blocks.\nThe demo below shows a tiny 8 × 8 texture stretched over a large square. Move the pink point over it (hover, tap or drag, or select it and use the arrow keys). The panel on the right zooms in on the four texels around the point, showing each one\u0026rsquo;s share of the result.\nAn 8 × 8 texture, magnified with nearest or bilinear filtering\nThe texture on screen The four nearest texels Filter Nearest Bilinear Size on screen: Mark texel centres How the four percentages are worked out First, the UV is turned into texel units: multiply by the texture\u0026rsquo;s size (8 here) and subtract 0.5, because texel centres sit half a texel in from the edges. The whole-number part says which four texels surround the point; the leftover fraction says how far between their centres it is: fx across and fy up, each from 0 to 1.\nEach texel\u0026rsquo;s share is then how close the point is to it, across times up:\nBottom-left: (1 − fx) × (1 − fy) Bottom-right: fx × (1 − fy) Top-left: (1 − fx) × fy Top-right: fx × fy The four shares always add up to 1 (100%). For example, a point a quarter of the way across and halfway up (fx = 0.25, fy = 0.5) gets 37.5% from each left texel and 12.5% from each right one. Multiplying each texel\u0026rsquo;s colour by its share and adding them up gives exactly the same answer as the \u0026ldquo;two rounds of lerp\u0026rdquo; described above.\nThings to try:\nWith Bilinear, put the point exactly on a texel centre (a white dot): that texel gets 100%. Halfway between two centres, they get 50% each. In the middle of four, 25% each. Switch to Nearest and move slowly across a texel boundary: the result jumps instantly from one colour to the other. With Bilinear, notice the edges of the picture. Pixel art looks blurry when it\u0026rsquo;s magnified with bilinear filtering, which is why games with a pixel-art style deliberately use nearest filtering. Shrink the size on screen right down, until the whole texture is only a few pixels across. Now each screen pixel covers several texels, and neither filter looks right: bits of the picture vanish and reappear as you change the size. That\u0026rsquo;s the problem the next post solves. Magnification and Minification When a texture is drawn bigger than its own resolution, each texel covers several screen pixels. This is magnification, and bilinear filtering handles it well: it just has to fill in smoothly between texels.\nWhen a texture is drawn smaller than its resolution, for example on a distant wall, each pixel covers many texels. This is minification, and it\u0026rsquo;s far harder. Bilinear filtering still only reads the four texels nearest the pixel\u0026rsquo;s centre and ignores all the others under the pixel, so the result depends on exactly where the centre lands. As the camera moves, it lands on different texels each frame, and the texture shimmers and sparkles. The fix, mipmapping, is the subject of part 3.\nGraphics APIs let you choose the filter separately for each case. In WebGL it\u0026rsquo;s one setting each (LINEAR means bilinear; you don\u0026rsquo;t need to follow the code, just notice there are two settings):\ngl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); // magnification: bilinear gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR); // minification: trilinear (part 3) Under the hood Bilinear filtering is done by the graphics card\u0026rsquo;s texture units in dedicated fixed-function hardware, not by your shader. The four texels are fetched together (in a tiled texture layout they\u0026rsquo;re usually in the same small block of memory) and blended in one go, so on modern hardware a bilinear sample typically costs about the same as a nearest one. The blend weights are kept to a limited precision: many graphics cards store the position between two texels with only 8 bits, so a bilinear blend can only take 256 distinct steps between them. That\u0026rsquo;s far more than enough for normal textures, and only shows up if you magnify a texture enormously.\nQuestions You Might Have Does bilinear filtering add detail? No. It can only blend the texels that are there, so a magnified texture looks smooth but soft. Sharp detail up close needs a bigger texture, or tricks such as detail textures or distance fields (SDF Text).\nSummary Texel centres sit at (i + 0.5) ÷ size in UV space. Nearest filtering reads the one texel the UV falls in: fast, but blocky when magnified. Bilinear filtering blends the four nearest texels: smooth when magnified. Magnification is easy; minification, where a pixel covers many texels, makes textures shimmer, and needs mipmaps. Further Reading LearnOpenGL, Textures: Texture Filtering: nearest and linear filtering with side-by-side images. Wikipedia, Bilinear filtering and Bilinear interpolation: the maths in more detail. Inigo Quilez, Texture repetition and Improved texture interpolation: creative tricks built on top of bilinear filtering. Microsoft, Texture filtering: the filter modes as Direct3D describes them. ","permalink":"https://fragmentshack.com/posts/texture-filtering-nearest-bilinear/","summary":"A pixel\u0026rsquo;s UV almost never lands exactly on a texel. Nearest filtering picks one; bilinear blends four. Zoom into a tiny texture and see exactly which texels are mixed, and by how much.","title":"🔍 Texture Filtering: Nearest and Bilinear"},{"content":"Introduction Look closely at a brick wall in a game and you\u0026rsquo;ll usually find it\u0026rsquo;s a flat rectangle made of two triangles, with a picture of bricks on it. That picture is a texture, and it\u0026rsquo;s one of the oldest and most important tricks in real-time graphics: it adds detail without adding triangles. This post, the first in the Textures \u0026amp; Sampling series, covers:\nWhat a texture is, and what a texel is UV coordinates: how each vertex says which part of the texture it shows Wrap modes: what happens when UV coordinates go beyond the edge of the texture It builds on the Graphics Fundamentals series, especially interpolation.\nTextures and Texels A texture is an image stored in the graphics card\u0026rsquo;s memory, ready to be read by shaders. It\u0026rsquo;s a grid of coloured cells, just like the screen\u0026rsquo;s grid of pixels from part 1 of the fundamentals. To avoid confusion, the cells of a texture are called texels (texture elements), and \u0026ldquo;pixels\u0026rdquo; is kept for the screen.\nTextures aren\u0026rsquo;t only pictures. The same mechanism stores surface bumps (normal maps), shininess, transparency, pre-calculated lighting and much more: any data that varies across a surface. And reading a texture, called sampling, has dedicated hardware on the graphics card, as the rest of this series shows.\nUV Coordinates To put a texture on a triangle, each vertex needs to say which point of the texture it should show. That\u0026rsquo;s its texture coordinate, usually called its UV: two numbers, u across the texture and v up it (the letters x and y were already taken by positions).\nCrucially, UVs are measured as fractions of the texture, from 0 to 1, not in texels. (0, 0) is one corner, (1, 1) is the opposite corner, and (0.5, 0.5) is the middle, whatever the texture\u0026rsquo;s resolution. That means you can swap a 256 × 256 texture for a 4096 × 4096 one without changing the mesh at all.\nThe UVs are interpolated across the triangle like any other varying, so each pixel gets its own UV, and the fragment shader reads the texture there. In GLSL, sampler2D is the type for a texture, vec2 is a pair of numbers (the UV), and the built-in function texture reads a colour from the texture at a UV:\nin vec2 vUV; // interpolated from the three vertices uniform sampler2D uTexture; // the texture out vec4 outColor; void main() { outColor = texture(uTexture, vUV); // \u0026#34;sample\u0026#34; the texture at this UV } Try It: Moving the UVs On the left is the texture in UV space, with the 0 to 1 square outlined. Its four letters mark the corners of a square on the right, which is drawn by your graphics card with those UVs. Drag the corner points A to D on the left (or select it, press 1 to 4 to pick a corner, and use the arrow keys), or try a preset.\nA square's UV coordinates on the texture (left), and the result (right)\nUV space: the texture On screen: a square using those UVs Wrap mode Repeat Clamp to edge Mirrored repeat Whole texture Zoom in Repeat 3 × 3 Mirror Rotate Slant Some things to notice:\nZoom in uses UVs from 0.25 to 0.75: the square shows only the middle of the texture, magnified. Mirror swaps the left and right UVs, and Rotate turns the UV square, so the picture flips or turns even though the square on screen hasn\u0026rsquo;t moved. Slant moves only the top two UVs. The texture bends along the square\u0026rsquo;s diagonal, because the square is two triangles, and each triangle interpolates its own three UVs. UV unwrapping For a real 3D model, an artist decides each vertex\u0026rsquo;s UV by unwrapping the model: cutting its surface along chosen seams and flattening it out onto the texture, like flattening a cardboard box. Where the surface is cut, a vertex needs two different UVs, one for each side of the seam, so it has to be stored twice. That\u0026rsquo;s the same reason a cube needs 24 vertices rather than 8, as Vertices, Triangles and Meshes explained.\nWrap Modes: Going Past the Edge UVs aren\u0026rsquo;t limited to 0 to 1. What should the texture look like at u = 1.3? That\u0026rsquo;s controlled by the texture\u0026rsquo;s wrap mode (also called the address mode):\nRepeat ignores the whole number and keeps the fraction, so 1.3 reads the same texel as 0.3. The texture tiles endlessly. It\u0026rsquo;s how a small brick texture covers a whole wall: give the wall UVs from 0 to 20, and the bricks repeat 20 times. Clamp to edge limits the UV to the range 0 to 1, so anything past the edge reads the texel at the edge, smeared outwards. It\u0026rsquo;s used for things that mustn\u0026rsquo;t tile, like a character\u0026rsquo;s face or a user interface element. Mirrored repeat tiles the texture but flips every other copy, so the edges always match up and there are no visible seams. Choose Repeat 3 × 3 in the demo and try each mode: the left side shows what the texture \u0026ldquo;looks like\u0026rdquo; beyond the edges in each mode.\nWhich way is up? In Direct3D, Vulkan and Metal, UV (0, 0) is the top-left of the image. OpenGL and WebGL treat (0, 0) as the first row of texels in memory, which they consider the bottom. Image files store their top row first, so OpenGL programs often flip images when loading them (the demos on this site do, so v points up). If a texture appears upside down after moving between APIs, this is usually why.\nUnder the hood Graphics cards have dedicated texture units next to their shader cores. The shader just asks for \u0026ldquo;the colour at this UV\u0026rdquo;; the texture unit works out which texels to fetch, applies the wrap mode, fetches them through a dedicated texture cache (a small, fast memory of recently read texels) and blends them (the next post covers that blending). To make the cache effective, textures aren\u0026rsquo;t stored row by row in memory: texels are rearranged into small square tiles, so texels that are close together on screen are close together in memory too. Most game textures are also compressed in special formats that the hardware decodes as it reads them, typically to between a quarter and an eighth of the uncompressed size.\nSummary A texture is an image in GPU memory, made of texels; reading it is called sampling. Each vertex has a UV coordinate, measured from 0 to 1 across the texture, independent of its resolution. UVs are interpolated across each triangle, and the fragment shader samples the texture there. Wrap modes (repeat, clamp, mirror) decide what happens outside 0 to 1. But a pixel\u0026rsquo;s UV almost never lands exactly on a texel. What colour should it get then? That\u0026rsquo;s texture filtering, the next part.\nFurther Reading LearnOpenGL, Textures: loading and using textures, with wrap modes, in OpenGL. WebGL2 Fundamentals, Textures: texture coordinates and parameters in WebGL2. Fabian Giesen, A trip through the Graphics Pipeline, part 4: how texture units, caches and tiled layouts work. Nathan Reed, Understanding BCn Texture Compression Formats: how compressed textures work. ","permalink":"https://fragmentshack.com/posts/textures-uv-coordinates/","summary":"How a flat image gets wrapped onto a 3D surface. Drag a shape\u0026rsquo;s UV coordinates around a texture, and see what happens when they go past the edge.","title":"🧵 Textures and UV Coordinates: Wrapping Images onto Shapes"},{"content":"Introduction So far this series has been about getting the right shapes onto the right pixels. But a flat-coloured sphere looks like a flat circle: lighting is what makes a 3D object look 3D. Real light bounces around in incredibly complicated ways, so games use simplified models that look convincing and are cheap to calculate. This post covers the classic model, which is built from three parts, and where to run it:\nDiffuse light, which makes surfaces facing the light brighter, using Lambert\u0026rsquo;s cosine law Specular light, the shiny highlight, using the Blinn-Phong model Ambient light, a cheap stand-in for light bouncing around the room The difference between lighting per vertex and per pixel It brings together nearly everything from the series: normals from part 3, spaces from part 5, and both kinds of shader.\nWhat You Need: Normals and Directions Lighting at a point on a surface depends on a few directions. Each is a vector (three numbers, like a position) that points somewhere and has a length of exactly 1, called a unit vector. Keeping the length at 1 means only the direction matters:\nN, the normal: which way the surface faces at this point. It\u0026rsquo;s stored with each vertex and interpolated across the triangle. L: the direction from the point towards the light. For a far-away light like the sun, it\u0026rsquo;s the same everywhere. V: the direction from the point towards the camera. The key tool for comparing two directions is the dot product, written A · B: multiply the matching numbers of the two vectors and add the results, AxBx + AyBy + AzBz. For two unit vectors, it measures how closely they line up: 1 when they point the same way, 0 at right angles, and negative when they point apart, down to −1 when opposite. (It\u0026rsquo;s the cosine of the angle between them.) It\u0026rsquo;s just three multiplications and two additions, so lighting code is full of them. (The Dot Product explores it with demos.)\nDiffuse: Lambert\u0026rsquo;s Cosine Law Think of sunlight as a stream of parallel rays. A beam hitting a surface head-on lands on a small patch, concentrating its energy. Tilt the surface and the same beam spreads over a bigger area, so each bit receives less light: exactly how closely the normal and light direction line up, N · L. This is Lambert\u0026rsquo;s cosine law, and it gives a matte look, like chalk or unpolished wood. The light scatters equally in all directions, so it looks the same from any viewpoint.\nDrag the sun around and tilt the surface below.\nThe same beam of light spreading over a tilted surface\nTilt the surface: In a shader, diffuse lighting is a single line:\nfloat diffuse = max(dot(N, L), 0.0); // 0 when facing away from the light vec3 colour = diffuse * surfaceColour * lightColour; Here N is the surface\u0026rsquo;s normal and L the direction from the surface towards the light, both one unit long; surfaceColour and lightColour are the surface\u0026rsquo;s and light\u0026rsquo;s colours. max(a, b) gives whichever is bigger, so surfaces facing away from the light don\u0026rsquo;t go negative, which would remove light.\nSpecular: Shiny Highlights Shiny materials like plastic, metal and wet surfaces also reflect light like a mirror, making a bright highlight where it heads straight towards your eye. Unlike diffuse light, the highlight moves with the camera.\nThe Blinn-Phong model (Jim Blinn\u0026rsquo;s 1977 refinement of Bui Tuong Phong\u0026rsquo;s 1975 model) estimates it with the half vector, H: the direction exactly halfway between L and V. If the surface\u0026rsquo;s normal lines up with H, the surface is angled to reflect the light straight at the camera, and the highlight is brightest:\nvec3 H = normalize(L + V); float specular = pow(max(dot(N, H), 0.0), shininess); V is the direction from the surface towards the camera (the viewer). normalize scales a vector to length 1, and pow(x, n) raises x to the power n (multiplies it by itself n times). As N · H is at most 1, a big power makes it fall away fast as the surface turns from the perfect angle. That power, the shininess, sets the highlight\u0026rsquo;s size: large for a tight sparkle like polished plastic, small for a broad sheen.\nAmbient: Faking Bounced Light In a real room, surfaces facing away from the light aren\u0026rsquo;t pitch black, because light bounces off everything. Calculating that is expensive, so the classic model adds a small constant amount everywhere, ambient light. It\u0026rsquo;s crude (real bounced light varies), and modern games use much better techniques, but it stops shadowed sides from being completely black.\nPutting It Together The final colour is the sum of the three terms. Turn them on and off below, change the shininess, and watch the highlight as the light moves (press Pause to hold it still). Drag the object to look at it from different sides and watch the highlight follow you.\nAmbient, diffuse and specular lighting on a 3D object\nAmbient Diffuse Specular ▶ Play Shape Sphere Doughnut Cube Work out lighting Per pixel Per vertex (Show normals instead) Shininess: Light height: Detail: Per Vertex or Per Pixel? The lighting maths can run in either shader. Early 3D hardware ran it once per vertex and blended the resulting colours across each triangle. This Gouraud shading is cheap, as there are far fewer vertices than pixels, but it can\u0026rsquo;t show a highlight smaller than a triangle: if one falls mid-triangle, no corner is bright, and it disappears.\nSet Work out lighting to Per vertex and lower the Detail: the highlight turns blotchy and star-shaped, crawls across the triangles, and can vanish. Running the maths in the fragment shader, blending the normal instead of the colour, gives a smooth result at any detail. This is often called Phong shading (not the Phong lighting model), and almost every game does it today.\nUnder the hood Two details are easy to get wrong. First, an interpolated normal is no longer exactly length 1 (blending two unit vectors gives a shorter one), so the fragment shader must normalize it again, or the lighting dims towards the middle of each triangle. Second, normals can\u0026rsquo;t always be transformed by the same matrix as positions: if an object is stretched unevenly, its normals would tilt the wrong way. They use the normal matrix, made by inverting (part 6) and transposing (part 8) the top-left 3×3 corner of the model matrix, passed in as a uniform. And lighting maths should use linear light values, converted to the screen\u0026rsquo;s sRGB encoding at the end: the demo\u0026rsquo;s shader ends with pow(c, 1.0 / 2.2), where c is the finished colour in linear light and the power 1 ÷ 2.2 approximates sRGB. The sRGB and gamma post explains why.\nBeyond Blinn-Phong This model has been used in countless games, but it isn\u0026rsquo;t based on real physics: the highlight can reflect more light than arrived, and the settings don\u0026rsquo;t match real materials. Modern games use physically based rendering (PBR), which describes materials by properties like roughness and metalness and conserves energy. It\u0026rsquo;s built from the same ingredients: N, L, V, H and dot products.\nQuestions You Might Have What about more than one light? Work out the diffuse and specular light from each light separately and add them together (ambient is usually added once). Light simply adds up, which is also why the sums are done in linear light (sRGB and Gamma).\nSummary Lighting uses directions: the normal N, the direction to the light L and to the camera V. Diffuse light follows Lambert\u0026rsquo;s cosine law: brightness = max(N · L, 0). Specular highlights in Blinn-Phong use the half vector: pow(max(N · H, 0), shininess). Ambient adds a constant to fake bounced light. Lighting per pixel looks far better than per vertex, because it doesn\u0026rsquo;t miss highlights inside triangles. That\u0026rsquo;s the end of Graphics Fundamentals! You now know the whole journey from triangles to lit pixels. From here, the Textures \u0026amp; Sampling series looks at how images are wrapped onto these surfaces.\nFurther Reading LearnOpenGL, Basic Lighting and Advanced Lighting: Phong and Blinn-Phong in GLSL, step by step. Wikipedia, Blinn–Phong reflection model and Lambert\u0026rsquo;s cosine law: the history and the maths. Jim Blinn, Models of light reflection for computer synthesized pictures (SIGGRAPH 1977): the paper that introduced the half vector. LearnOpenGL, PBR Theory: where to go next for physically based lighting. ","permalink":"https://fragmentshack.com/posts/basic-lighting/","summary":"How a shader fakes light with three simple terms: ambient, diffuse and specular. Learn Lambert\u0026rsquo;s cosine law, the Blinn-Phong highlight, and why lighting per pixel beats lighting per vertex.","title":"💡 Basic Lighting: Ambient, Diffuse and Specular"},{"content":"Introduction So far, every triangle has gone through the pipeline on its own. But in a real scene many triangles cover the same pixel, such as a wall in front of a mountain, and only the nearest should show. This post covers:\nWhy simply drawing things in order doesn\u0026rsquo;t work The depth buffer and the depth test, which solve it What\u0026rsquo;s actually stored in the depth buffer, and why it\u0026rsquo;s so uneven Z-fighting: the flickering you get when the depth buffer runs out of precision Drawing in Order Isn\u0026rsquo;t Enough The obvious solution is the one painters use: paint the distant background first, then nearer things over the top. This painter\u0026rsquo;s algorithm works for simple scenes, but sorting thousands of objects by distance every frame takes time. And sometimes there\u0026rsquo;s no right order at all: when two objects pass through each other, each is partly in front of the other.\nThe Depth Buffer The graphics card\u0026rsquo;s solution is a second image the size of the framebuffer, the depth buffer (or z-buffer). Each of its pixels stores a depth: how far away the surface drawn there is. Before each frame, it\u0026rsquo;s cleared to the furthest possible value. Then, for every fragment:\nCompare the fragment\u0026rsquo;s depth with the value already in the depth buffer at that pixel (the depth test) If the fragment is nearer, write its colour to the framebuffer and its depth to the depth buffer If not, throw it away Objects can now be drawn in any order, and each pixel shows the nearest surface. In the demo, the ring passes through the box, which no drawing order can handle. Turn the depth test off and change the order, then switch the view to see inside the depth buffer. Drag to look around.\nDrawing order, the depth test, and the depth buffer's contents\nDepth test Drawing order Ball, box, ring Ring, box, ball Box, ring, ball Show Colours Stored depth values Distance from the camera With the depth test off, whatever is drawn last wins, which looks wrong as soon as you turn the camera. With it on, order doesn\u0026rsquo;t matter.\nUnder the hood Running a fragment shader only to throw its result away is wasteful, so graphics cards do the depth test before the fragment shader whenever they can: the early depth test (or \u0026ldquo;early z\u0026rdquo;). Many also keep a low-resolution summary of the depth buffer, to reject whole hidden tiles of a triangle at once. That\u0026rsquo;s why games often draw nearby objects first: everything behind them then fails cheaply. Early testing is switched off if the fragment shader writes its own depth, and restricted if it can discard fragments, because then the shader decides what the depth buffer ends up holding.\nWhat\u0026rsquo;s Stored: Depth Isn\u0026rsquo;t Spread Evenly The depth buffer doesn\u0026rsquo;t store the distance directly. It stores the z that comes out of the projection matrix and the divide by w (part 5), squeezed into 0 (the near plane) to 1 (the far plane). Because of the divide, it changes in step with 1 ÷ distance, not with the distance itself.\nSwitch the demo\u0026rsquo;s view to Stored depth values: almost everything is very pale, close to 1, though nothing is near the far plane. Distance from the camera shows an even spread for comparison. Most of the range is used up just in front of the camera.\nThat\u0026rsquo;s useful: nearby objects, where small errors would show most, get the most precision. But distant objects get very little.\nZ-Fighting A depth buffer usually stores each depth as a 24-bit number: about 16.8 million values between the near and far planes. That sounds like a lot, but they\u0026rsquo;re bunched up near the camera, so far away the steps between them get large. When two surfaces are closer together than one step, rounding decides which is in front, differently from pixel to pixel and frame to frame, and they flicker through each other: z-fighting.\nThe demo below shows six pairs of walls, 5, 10, 20, 40, 80 and 160 units away, sized to look the same on screen. In each pair, an orange wall sits a small gap in front of a blue one, so every wall should look orange. The chart compares the smallest gap the depth buffer can resolve at each distance (blue curve) with the actual gap (orange dashed line): where the curve rises above the line, the walls fight. The camera sways slightly so you can watch them flicker (press Pause to stop it). (The demo rounds each depth to what a 16- or 24-bit buffer could store, because some browsers quietly use a more precise one.)\nPairs of walls a tiny gap apart, and the depth buffer’s precision with distance\n▶ Play Depth buffer 16 bits 24 bits Near plane (log scale): Gap between the walls: (The near plane slider is logarithmic: each step of 1 multiplies the distance by ten, so −2 means 0.01 units, 0 means 1 and 1 means 10.)\nThe near plane matters enormously: moving it from 0.01 to 1 makes distant depth a hundred times more precise, while the far plane barely matters. Hence the advice in part 6 to push the near plane out as far as possible.\nHow the demo works out the blue curve For a surface z units from the camera, with the near plane at n and the far plane at f, the value the depth buffer stores is:\nstored depth = f ÷ (f − n) × (1 − n ÷ z) Check the ends: at z = n, the bracket is 1 − 1 = 0, and at z = f it works out to exactly 1. The n ÷ z part is the \u0026ldquo;1 ÷ distance\u0026rdquo; from earlier.\nA 24-bit buffer stores 2²⁴ different values, so one step is 1 ÷ 2²⁴ of the range (1 ÷ 2¹⁶ for 16 bits). The blue curve is how far apart two surfaces must be for their stored depths to differ by at least one step, which works out as very nearly:\nsmallest gap ≈ step × (f − n) × z² ÷ (f × n) The gap grows with z²: twice as far away needs four times the gap. And it\u0026rsquo;s divided by n: a near plane ten times further out makes everything ten times more precise. The far plane hardly matters, because (f − n) ÷ f is close to 1 when f is much bigger than n. Setting stored depth to 0.5 and solving for z gives the readout\u0026rsquo;s \u0026ldquo;half of all the values\u0026rdquo; distance, 2 × n × f ÷ (f + n): just 0.02 units when n = 0.01.\nOther common fixes:\nDon\u0026rsquo;t put surfaces almost on top of each other. Decals (pictures stuck onto surfaces, like posters or bullet holes) are a classic cause, and are usually pulled slightly towards the camera with a setting called depth bias. Reverse-Z: store 1 at the near plane and 0 at the far plane, in a 32-bit floating-point depth buffer. Floating-point numbers are most precise near 0, which cancels out most of the bunching; many modern games use it. Questions You Might Have Do 2D games need a depth buffer? Often not: they usually draw sprites back to front by layer, so the order does the job. A depth buffer still helps if solid sprites are drawn in any order.\nWhat's a stencil buffer? Another per-pixel buffer, usually stored alongside depth (24 bits of depth plus 8 of stencil is common). It holds small whole numbers that later drawing can test against: handy for masks, outlines and portals.\nSummary The depth buffer stores the depth of the nearest surface at each pixel, and the depth test keeps only fragments nearer than that. Objects can then be drawn in any order, even when they intersect. Stored depth follows 1 ÷ distance, so precision is concentrated near the camera. When two surfaces are closer than the precision allows, they z-fight. A larger near plane helps most. Next, the last part of this series puts everything together to light a 3D object: basic lighting.\nFurther Reading Nathan Reed, Depth Precision Visualized: beautiful charts of how depth precision is distributed, and why reverse-Z works. LearnOpenGL, Depth testing: depth functions, values and z-fighting in OpenGL. Fabian Giesen, A trip through the Graphics Pipeline, part 7: early and hierarchical depth testing in hardware. Microsoft, Depth bias: how Direct3D\u0026rsquo;s depth bias is calculated. ","permalink":"https://fragmentshack.com/posts/depth-buffer/","summary":"When two surfaces cover the same pixel, the depth buffer decides which one you see. Watch it work, look inside it, and find out why distant surfaces flicker through each other.","title":"🗂️ The Depth Buffer: Deciding What’s in Front"},{"content":"Introduction Part 9 worked out which pixels each triangle covers. Each covered pixel becomes a fragment, which now needs a colour: the job of the fragment shader (a pixel shader in Direct3D), where most of the visual magic in games happens. This post covers:\nInterpolation: how the corners\u0026rsquo; values are blended across the triangle What a fragment shader receives and produces, with a live editor to play in Perspective-correct interpolation: the subtle fix that keeps textures from warping Blending Across a Triangle A vertex shader only runs at the three corners, but a triangle can cover thousands of pixels. Every value it outputs (a varying, as part 7 called them), such as a colour or a texture coordinate, must be filled in for each pixel in between. The rasteriser does this by interpolating: blending the three corner values by how close the pixel is to each corner.\nThe amounts of each corner are called barycentric weights (from barycentre, a centre of balance). They\u0026rsquo;re part 9\u0026rsquo;s edge function values divided by the triangle\u0026rsquo;s area: a pixel on a corner gets 100% of that corner, a pixel on the opposite edge gets 0% of it, and the three always add up to exactly 1.\nMove the pink point around the triangle below, and drag its corners: each corner\u0026rsquo;s line thickens as its weight grows.\nBlending three corner colours with barycentric weights\nEvery varying is blended this way: colours, texture coordinates, normals and positions. To stop blending, for example for an ID number, GLSL lets you mark a varying flat: every pixel then gets one corner\u0026rsquo;s value.\nThe Fragment Shader Then the fragment shader runs, once per fragment. It receives:\nThe interpolated varyings for this fragment The same kind of uniforms as the vertex shader (time, colours, light positions, textures) Built-in values such as gl_FragCoord, the fragment\u0026rsquo;s position on screen in pixels It produces a colour (and optionally a depth, how far away it is: see part 11), or it can discard the fragment so nothing is written, which is how cut-out shapes like leaves and fences are often made. Each run knows nothing of the pixels around it (apart from the ddx and ddy trick).\nHere\u0026rsquo;s a fragment shader drawing one rectangle that covers the whole picture, so it runs once for every pixel. Pick a preset, then edit the code: the picture updates as you type.\nEdit the fragment shader and watch every pixel change\nPreset Solid colour Gradient from coordinates A circle Moving stripes Checkerboard Rings Sunset ▶ Play Reset this preset The presets use a few GLSL functions beyond those in part 7. vUV is this pixel\u0026rsquo;s position, from (0, 0) at the bottom left to (1, 1) at the top right, and uTime is the time in seconds.\nfloor(x) rounds down to a whole number, and fract(x) keeps only the part after the decimal point, so fract(x * 10.0) counts from 0 to 1 ten times as x goes from 0 to 1: handy for repeats. mod(a, 2.0) is the remainder after dividing by 2: 0 for even numbers, 1 for odd ones. step(edge, x) is 0 when x is below edge and 1 above it, a hard switch. smoothstep changes smoothly over a short range instead. mix(a, b, t) blends from a to b as t goes from 0 to 1 (see Interpolation). atan(y, x) gives a direction\u0026rsquo;s angle, for circular patterns. a ? b : c means \u0026ldquo;if a is true, use b, otherwise use c\u0026rdquo;. Some things to try:\nIn Gradient from coordinates, change vUV.x to 1.0 - vUV.x, or the 0.0 to 0.5 + 0.5 * sin(uTime), and watch it change over time. In A circle, change 0.3 to resize it. The edge is hard and jagged, because each pixel is either in or out; the fwidth post shows how to smooth it. Sunset uses no images at all, just maths on vUV, like many game effects. The fragment shader is usually the most expensive part of drawing: it runs for every covered pixel (several times where objects overlap), so its cost grows with resolution. A 4K screen has over 8 million pixels, so at 60 frames per second a full-screen effect runs it about half a billion times a second.\nPerspective-Correct Interpolation There\u0026rsquo;s a catch with blending in screen space. A road\u0026rsquo;s white lines are evenly spaced on the ground but bunch up on screen in the distance: equal steps on screen are not equal steps across the surface. Blending texture coordinates evenly on screen would stretch distant textures and squeeze near ones.\nSo graphics cards do perspective-correct interpolation, using each corner\u0026rsquo;s w (its depth, from part 5). Instead of blending each value directly, they blend the value divided by w, and 1 ÷ w, then divide one by the other for each pixel. The result is exactly what blending evenly across the real 3D surface would give.\nThe demo below shows a checkerboard floor of just two triangles. Switch to Affine (blended evenly across the screen) to turn the correction off: the shader undoes it with the same trick in reverse.\nA floor of two triangles, with and without perspective correction\nInterpolation Perspective-correct Affine (no correction) Camera height: Turn: Without the correction, the checkerboard bends along the diagonal where the triangles meet, and distant squares are far too big; lowering the camera makes it worse. The original PlayStation lacked this correction, so textures in its games warp as the camera moves (they split surfaces into many small triangles to hide it).\nUnder the hood Fragment shaders always run in 2×2 groups of pixels, so neighbouring pixels can be compared, which smooth texture reading needs (see the ddx and ddy posts). On many modern graphics cards, interpolation isn\u0026rsquo;t a fixed-function step: the rasteriser hands each group its barycentric weights, and the shader blends with a few multiply-add instructions at its start. So passing lots of varyings has a real cost.\nQuestions You Might Have Can a fragment shader move its pixel somewhere else? No. Each copy works on one fixed position and decides its colour (it can also discard the fragment, or change its depth). Where things go on screen is the vertex shader\u0026rsquo;s job.\nSummary Values output by the vertex shader are interpolated across each triangle using barycentric weights, which always add up to 1. The fragment shader runs once per fragment and outputs its colour (or discards it). It\u0026rsquo;s usually the most expensive stage, because it runs for every covered pixel. Perspective-correct interpolation uses each corner\u0026rsquo;s depth so that textures don\u0026rsquo;t warp. Next, part 11 solves a problem we\u0026rsquo;ve been ignoring: when two triangles cover the same pixel, which one wins?\nFurther Reading Patricio Gonzalez Vivo and Jen Lowe, The Book of Shaders: a gentle, beautiful introduction to fragment shaders, with live editors. Inigo Quilez and Pol Jeremias, Shadertoy: thousands of fragment shaders to read and remix, from simple to astonishing. Scratchapixel, Perspective Correct Interpolation: the maths behind the correction, step by step. ","permalink":"https://fragmentshack.com/posts/fragment-shaders-interpolation/","summary":"How values are blended smoothly across a triangle, how a fragment shader turns them into a colour, and why perspective needs special care. Includes a live fragment shader editor.","title":"🎨 Fragment Shaders: Colouring Every Pixel"},{"content":"Introduction After the vertex shader, the graphics card knows exactly where each triangle\u0026rsquo;s three corners land on screen. But the screen is a grid of pixels, and triangles don\u0026rsquo;t line up with it. Rasterisation is the step that decides which pixels each triangle covers, turning a smooth mathematical shape into a set of squares. (\u0026ldquo;Raster\u0026rdquo; is the old word for a grid of lines on a screen.) This post covers:\nThe simple rule for deciding whether a pixel is covered Edge functions: the three tests that apply that rule Fill rules: what happens when a pixel lands exactly on an edge How real hardware makes all this fast The Rule: Test the Pixel\u0026rsquo;s Centre A triangle\u0026rsquo;s edge can cut straight through a pixel, covering some of it and not the rest. But a pixel can only have one colour, so the rasteriser needs a yes-or-no answer. The standard rule is simple: a pixel is covered if its centre is inside the triangle. Pixel centres sit halfway across each pixel, at coordinates like (0.5, 0.5), (1.5, 0.5) and so on.\nDrag the triangle\u0026rsquo;s corners below (or select the grid, press 1, 2 or 3 to pick a corner, and use the arrow keys). The orange pixels are the ones whose centres are inside. Hover over or tap a pixel to see the maths for it.\nRasterising a triangle onto a grid of pixels\nPixels across: Show pixel centres Show edge tests Things to notice:\nA thin sliver of a triangle can miss every pixel centre and draw nothing at all, even though it\u0026rsquo;s visibly there. Squash the triangle flat and watch it vanish. The covered pixels form staircases along slanted edges. Raise Pixels across and the steps get smaller, but they never quite go away. This is aliasing, and the fix, anti-aliasing, has its own post. Some pixels that are almost half covered stay empty, while others that are barely more than half covered are filled. A yes-or-no test can\u0026rsquo;t do better. Edge Functions: Three Tests per Pixel How does the graphics card know whether a point is inside a triangle? Each edge of a triangle is a straight line, and every line splits the screen into two halves. A point is inside the triangle if it\u0026rsquo;s on the inner side of all three edges.\nTo test which side a point is on, the rasteriser uses an edge function. For an edge from corner A to corner B, and a pixel centre P:\nE(P) = (Px − Ax) × (By − Ay) − (Py − Ay) × (Bx − Ax) Here Px means P\u0026rsquo;s x coordinate, Ay means A\u0026rsquo;s y coordinate, and so on: it\u0026rsquo;s just two multiplications and a subtraction. The answer is positive on one side of the line, negative on the other and exactly zero on the line itself. (It\u0026rsquo;s a 2D version of the cross product.) Tick Show edge tests in the demo: pixels outside the triangle are shaded more darkly the more tests they pass, so you can see the three \u0026ldquo;inner sides\u0026rdquo; overlapping. Only pixels that pass all three are covered.\nThis is a lovely method for hardware, for two reasons. Each pixel can be tested independently, so thousands can be tested in parallel. And the edge function changes by a fixed amount from one pixel to the next, so stepping across the screen needs only an addition, not a multiplication.\nThe same three numbers, divided by the triangle\u0026rsquo;s total area, also tell you how close the pixel is to each corner. Those are the weights used to blend vertex values across the triangle, which is the subject of part 10.\nFill Rules: When a Centre Lands Exactly on an Edge Meshes are made of triangles that share edges. What if a pixel\u0026rsquo;s centre sits exactly on a shared edge? If both triangles claimed it, it would be drawn twice: harmless for a solid surface, but a see-through surface would be blended twice there and show a visible seam. If neither claimed it, there\u0026rsquo;d be a gap. Each such pixel must be drawn by exactly one of the two triangles.\nIn the demo below, the shared edge runs at exactly 45° through a line of pixel centres. Try each rule.\nTwo triangles sharing an edge that passes exactly through pixel centres\nWhen a centre is exactly on an edge Always count it as inside Always count it as outside Use the top-left rule The top-left rule solves it. A pixel centre exactly on an edge counts as inside only if that edge is a top edge (perfectly horizontal, with the triangle below it) or a left edge (with the triangle to its right). Any edge shared by two triangles is a left edge for one of them and a right edge for the other (or top for one and bottom for the other), so exactly one of them claims the pixel.\nDirect3D specifies the top-left rule exactly. OpenGL and Vulkan only require that a pixel on an edge shared by two triangles is drawn by exactly one of them, and in practice hardware uses a rule like this one.\nUnder the hood Real rasterisers don\u0026rsquo;t test every pixel on the screen for every triangle. They first work out the triangle\u0026rsquo;s bounding box (the smallest rectangle that contains it), then test whole tiles of pixels (for example 8×8) at once, using the edge functions at the tile\u0026rsquo;s corners to reject tiles that are completely outside and accept tiles that are completely inside without testing each pixel. Only tiles that an edge passes through are tested pixel by pixel. Vertex positions are also rounded to a fine grid (in Direct3D 11, steps of 1/256 of a pixel), so the edge tests can use exact whole-number arithmetic, with no rounding errors. That makes the \u0026ldquo;exactly on the edge\u0026rdquo; case well defined, and guarantees two triangles sharing an edge compute the same edge, with no cracks between them. Finally, covered pixels are handed on to the fragment shader in 2×2 groups, for reasons covered later in the ddx and ddy posts.\nQuestions You Might Have What happens to a triangle smaller than a pixel? If it doesn\u0026rsquo;t cover any pixel centre, it produces no fragments at all and simply vanishes. Huge numbers of tiny triangles are also slow, because the hardware works on pixels in small groups (Helper Pixels).\nSummary Rasterisation decides which pixels a triangle covers: a pixel is covered if its centre is inside. Inside means passing three edge function tests, one per edge, which are cheap and fully parallel. The yes-or-no test causes aliasing: staircase edges and vanishing slivers. Fill rules like the top-left rule make sure pixels on shared edges are drawn exactly once. Next, part 10 looks at what happens to each covered pixel: how values are blended across the triangle, and how the fragment shader colours it.\nFurther Reading Juan Pineda, A Parallel Algorithm for Polygon Rasterization (SIGGRAPH 1988): the original paper on edge functions. Fabian Giesen, Triangle rasterization in practice: edge functions, fill rules and fixed-point precision explained in depth. Scratchapixel, Rasterization: a Practical Implementation: building a rasteriser in code. Microsoft, Rasterization rules: Direct3D\u0026rsquo;s official top-left rule, with diagrams. ","permalink":"https://fragmentshack.com/posts/rasterisation/","summary":"How the graphics card decides which pixels a triangle covers, using three simple edge tests per pixel, and how it makes sure triangles that share an edge never overlap or leave gaps.","title":"🔳 Rasterisation: Which Pixels Does a Triangle Cover?"},{"content":"Optional on a first read New to graphics? You can skip this post for now and go straight to part 9, Rasterisation: nothing later in the series depends on it. Come back when you move between engines or graphics APIs, or when something appears mirrored, upside down or out of place.\nIntroduction The maths in part 4, part 5 and part 6 is the same everywhere, but the way it\u0026rsquo;s written down isn\u0026rsquo;t. Books, engines and graphics APIs make different choices, and mixing them up gives objects in the wrong place, mirrored scenes or nothing at all. This post separates the four choices that cause the most confusion. (A point going into a matrix multiplication is usually called a vector: just a list of numbers, such as (x, y, z).)\nRow vectors or column vectors: which side of the matrix the point goes on Row-major or column-major storage: what order the 16 numbers sit in memory Left-handed or right-handed coordinates: which way z points The NDC conventions: the depth range and which way is up The key idea to take away: these are independent choices. Each one is easy on its own; the trouble comes from assuming two of them always go together.\nChoice 1: Row Vectors or Column Vectors So far this series has written points as columns on the right of the matrix: p′ = M × p. The translation then sits in the last column, and in a chain of matrices the one on the right happens first.\nYou can equally write points as rows on the left: p′ = p × M. For the same answer, the matrix must be flipped along its diagonal, or transposed: rows become columns. The translation then sits in the bottom row, and the chain reads left to right: p × S × R × T means scale, then rotate, then translate.\nNeither is more correct. OpenGL\u0026rsquo;s documentation, GLSL (the language OpenGL and WebGL shaders are written in, covered in part 7) and most maths textbooks use column vectors. Microsoft\u0026rsquo;s maths library for Direct3D uses row vectors, as did older Direct3D documentation. HLSL, the shader language for Direct3D, lets you use either.\nChoice 2: Row-Major or Column-Major Storage Memory is one long line of numbers, so a 4×4 matrix is laid out as 16 numbers in a row (as floats, short for floating-point numbers: how computers store numbers with a decimal point). Row-major storage writes the first row, then the second, and so on; column-major writes the first column, then the second.\nThis is a separate choice from choice 1: how numbers are stored, not how the maths is written. It matters because when your program hands 16 numbers to a shader, the shader must know their order. GLSL (and so WebGL) and HLSL both read matrices column-major by default, though both can be told otherwise.\nThe demo below shows a transformation (turn and move a crate) written both ways, stored both ways, and then uploaded to your graphics card exactly as stored, to be used by a shader that does matrix × vector, the standard GLSL way.\nThe same transform under different conventions, and what WebGL makes of the 16 floats\nWritten on paper:\nIn memory, in the order they're uploaded (float 0 first):\nVectors Column vectors (M × v) Row vectors (v × M) Storage Column-major Row-major Move x: Move z: Turn: Colours show what each number means: red, green and blue for where the x, y and z axes go, and orange for the translation. Try all four combinations. You\u0026rsquo;ll find:\nColumn vectors + column-major works: the translation lands in floats 12, 13 and 14. Row vectors + row-major also works, and produces exactly the same 16 floats. The matrix on paper is transposed, but it\u0026rsquo;s stored row by row, so the two flips cancel out. The other two combinations put the translation in floats 3, 7 and 11, and the crate breaks. That\u0026rsquo;s why a matrix built by a row-vector maths library often goes straight into a shader that does matrix × vector unchanged: the memory is already right. It\u0026rsquo;s also why \u0026ldquo;I\u0026rsquo;ll transpose it\u0026rdquo; fixes so many bugs, and why the fix is so confusing when you don\u0026rsquo;t know which choice actually differed.\nUnder the hood The graphics card has no idea what a \u0026ldquo;matrix\u0026rdquo; is. To it, a matrix handed to a shader is just 16 floats in memory, and the shader\u0026rsquo;s multiplication becomes a handful of multiply-and-add steps reading those floats in the order the shading language\u0026rsquo;s rules say. So the convention is a setting of the shading language and API: GLSL and HLSL both have keywords to choose row-major or column-major, and OpenGL can transpose a matrix as it\u0026rsquo;s uploaded.\nChoice 3: Left-Handed or Right-Handed Take x to the right and y up. Should z point towards you, out of the screen, or away from you, into it? Hold up your right hand with the thumb along x and index finger along y: your middle finger points towards you. That\u0026rsquo;s a right-handed system. Do the same with your left hand and it points away: left-handed.\nHandedness also decides which way a positive rotation turns: in a right-handed system, curl your right fingers round an axis with the thumb along it, and positive rotations turn the way they curl.\nThe same numbers in a right-handed and a left-handed system\nSystem Right-handed Left-handed ▶ Play Switching systems mirrors the picture: same coordinates, same rotation matrix, but z and the direction of turning are flipped. So putting a model from a left-handed modelling program into a right-handed engine without converting gives a mirror image, and back-face culling (part 3) culls the wrong side, because mirroring flips the winding order.\nThis one varies too: OpenGL\u0026rsquo;s tradition (and this site\u0026rsquo;s demos) is right-handed in world and view space; Direct3D\u0026rsquo;s older helper libraries offered both but leaned left-handed; the Unity engine is left-handed with y up; the Blender modelling program is right-handed with z up. Using z for \u0026ldquo;up\u0026rdquo; instead of y is yet another independent choice.\nChoice 4: NDC Depth Range and Which Way Is Up Finally, the graphics APIs themselves disagree about the box that clip space maps to (part 5). WebGPU, in the table, is the newer graphics API for web browsers. \u0026ldquo;Pixel row 0\u0026rdquo; is which end of the picture the API counts rows from.\nNDC depth (z) NDC y Pixel row 0 OpenGL, WebGL −1 to +1 up bottom Direct3D 0 to 1 up top Vulkan 0 to 1 down top Metal, WebGPU 0 to 1 up top So a projection matrix built for OpenGL is slightly wrong for Direct3D: it squeezes depth into the wrong range. That\u0026rsquo;s why maths libraries offer separate projection functions, and why moving drawing code between APIs usually involves a \u0026ldquo;flip y\u0026rdquo; somewhere. (Recent versions of OpenGL can also be switched to the 0 to 1 depth range, which helps depth precision, as part 11 explains.)\nA Checklist for New Code When you meet an unfamiliar engine, library or tutorial, ask:\nAre points rows or columns? (Where\u0026rsquo;s the translation: bottom row or last column?) How are matrices stored in memory, and how does the shader read them? Is the coordinate system left- or right-handed, and which axis is up? Which NDC depth range and y direction does the API use? Questions You Might Have Which conventions should I use? Whichever your maths library, engine or existing code already uses, consistently everywhere. Neither choice is more correct; problems only come from mixing them.\nSummary Row vs column vectors is about how the maths is written; it transposes the matrix. Row-major vs column-major is about how numbers are stored; it\u0026rsquo;s a separate choice. Column vectors + column-major and row vectors + row-major give the same 16 floats. Handedness decides which way z points and which way rotations turn; mixing them mirrors the scene. APIs differ in NDC depth range and y direction. Next, part 9 follows the transformed triangles into the rasteriser, which decides exactly which pixels they cover.\nFurther Reading Fabian Giesen, Row major vs. column major, row vectors vs. column vectors: why these are two separate choices. Microsoft, Matrix ordering in HLSL and DirectXMath getting started: HLSL\u0026rsquo;s packing rules and DirectXMath\u0026rsquo;s row-vector convention. Khronos, Data Type (GLSL): how GLSL stores and multiplies matrices. Matthew Wellings, Vulkan\u0026rsquo;s coordinate system: what changed from OpenGL, and how to adapt a projection matrix. ","permalink":"https://fragmentshack.com/posts/matrix-conventions/","summary":"Row or column vectors? Row-major or column-major memory? Left- or right-handed? Depth from 0 or −1? Untangle the conventions that trip up everyone, and see which combinations really work.","title":"🧮 Matrix Conventions: Rows, Columns, Handedness and Depth"},{"content":"Introduction Part 2 introduced the vertex shader as the first programmable stage of the pipeline, and parts 4 to 7 built the matrices it uses. Now it\u0026rsquo;s time to write one. This post covers:\nWhat goes in to a vertex shader and what comes out The one job every vertex shader must do What else vertex shaders are used for, such as waves, wind and animation What a vertex shader can\u0026rsquo;t do The demo is a live editor: change the code and the shape on screen updates as you type.\nWhat Goes In, What Comes Out A vertex shader is a small function that the graphics card runs once for each vertex in a draw call, thousands or millions of times, in parallel. Each run handles one vertex, on its own. It\u0026rsquo;s written in a shading language: GLSL for OpenGL and WebGL (used here), HLSL for Direct3D, and MSL (Metal Shading Language) for Metal. They all look much like the C programming language, but you don\u0026rsquo;t need to know C: this post explains everything the examples use.\nIt receives three kinds of input:\nAttributes: the data stored with this particular vertex, such as its position, normal and texture coordinate (part 3). Each run gets different values. Uniforms: values that are the same for every vertex in the draw call, such as the model, view and projection matrices, or the current time. They\u0026rsquo;re set by the CPU before drawing. Built-in values provided by the graphics card, such as gl_VertexID, the vertex\u0026rsquo;s number in the list of vertices. And it produces two kinds of output:\nThe position, in clip space (part 5). In GLSL it\u0026rsquo;s written to a built-in variable called gl_Position. This is the one job every vertex shader must do. Varyings: any other values you want to pass on, such as a colour, a normal or a texture coordinate. They\u0026rsquo;re blended across each triangle and handed to the fragment shader, as part 10 explains. The most common vertex shader in the world looks something like this:\n#version 300 es layout(location = 0) in vec3 aPosition; // attribute uniform mat4 uModelViewProj; // uniform: P × V × M void main() { gl_Position = uModelViewProj * vec4(aPosition, 1.0); } Line by line:\n#version 300 es says which version of GLSL this is (the one WebGL2 uses). layout(location = 0) in vec3 aPosition; declares an input (in) called aPosition, of type vec3: a group of three numbers, the vertex\u0026rsquo;s x, y and z. layout(location = 0) just says which slot of the vertex data it comes from. The semicolon ends the statement. uniform mat4 uModelViewProj; declares a uniform of type mat4, a 4×4 matrix: the model, view and projection matrices from part 5 multiplied together. Everything after // on a line is a comment: a note for humans, ignored by the computer. void main() { … } is the function the graphics card runs for each vertex. The code inside the curly brackets is its body. vec4(aPosition, 1.0) makes a group of four numbers: the position plus the extra w = 1 coordinate from part 4. * means multiply, so the line multiplies it by the matrix, moving the vertex from local space to clip space in one step, and stores the answer (=) in gl_Position. Reading shader code A few more pieces of GLSL appear in the editor below:\nTypes. Every variable has a type: float is a single decimal number, vec2, vec3 and vec4 are groups of 2, 3 or 4 numbers, and mat2 and mat4 are 2×2 and 4×4 matrices. vec3 p = aPosition; makes a new variable p holding a copy of the position. Parts of a vector. p.x, p.y and p.z are the separate numbers inside p. p.xz means the x and z parts together, as a vec2. Changing a value. p.y += 0.5; adds 0.5 to p.y. (-= subtracts and *= multiplies.) Numbers in GLSL are written with a decimal point, like 4.0, to show they\u0026rsquo;re decimals. Functions. sin(x) (Angles, Sine and Cosine) gives a smooth wave that goes up and down between −1 and 1 as x increases, which is perfect for animation. length(v) is the length of a vector, cos is another wave (the same shape, shifted along), and normalize and mix are explained where they\u0026rsquo;re used. Try It: A Live Vertex Shader The top part of the shader (the inputs, uniforms and outputs) is fixed and shown in grey. It uses uViewProj rather than the uModelViewProj above: just the view and projection matrices. That\u0026rsquo;s because this demo\u0026rsquo;s mesh sits at the centre of the world without being moved, so it has no model matrix (its model space and world space are the same). It also has two outputs, vWorld and vColor, which pass the moved position and a colour on to the fragment shader. Edit the body of main() below it. Pick a preset to start from, then change the numbers and see what happens. Drag the shape to turn it.\nEdit the vertex shader and watch the mesh change\nPreset Pass-through (no change) Wave Ripples Twist Inflate along normals Colour by vertex number Fix the mistake Shape Flat grid Sphere ▶ Play Amount (uAmount): Wireframe Reset this preset Things to try:\nIn Wave, change 4.0 to 12.0 for shorter waves, or swap p.x for p.z to change direction. Games move water, flags and grass this way, with no extra work for the CPU.\nTwist does nothing to the flat grid, because the amount of twist depends on height and the grid is flat. Switch the shape to Sphere: the same code works on any mesh, because it only ever looks at one vertex at a time.\nColour by vertex number gives every vertex a random colour based on gl_VertexID. Each triangle shows a blend of its three corners\u0026rsquo; colours: proof that the colours really are worked out per vertex.\nFix the mistake won\u0026rsquo;t compile (be translated into instructions the graphics card can run). While it\u0026rsquo;s broken, the picture greys out and keeps showing the last shader that worked. Read the error and the plain-English note under it, then fix the line. When it works, a hill rises out of the middle of the grid.\nShow answer vec3(…) turns the number inside it into a vec3 (three numbers), but p.y holds just one number, so they don\u0026rsquo;t fit. Delete vec3( and its matching ), so the line adds a single number: p.y += uAmount * 0.6 * cos(length(p.xz) * 2.5);\nWith the wireframe on, notice that the shape can only bend at vertices. Between them, the triangles stay flat. A vertex shader can only move the vertices that exist.\n(The lighting is worked out in the fragment shader from the moved positions, using a trick explained later in Flat Shading with ddx and ddy, so you don\u0026rsquo;t need to update the normals yourself here.)\nWhat Vertex Shaders Are Used For Besides transforming positions with matrices, real games use vertex shaders for:\nSkinning: bending a character\u0026rsquo;s mesh to follow its skeleton. Each vertex stores which bones affect it, and by how much, and the shader blends those bones\u0026rsquo; matrices. Morph targets: blending between several versions of a mesh, such as facial expressions. Wind and water: moving grass, leaves, flags and waves with formulas like the ones above. Billboards: turning flat cards, such as the little images used for smoke and sparks, or distant trees, to always face the camera. Passing data along: computing values once per vertex, such as fog amount or a world-space position, for the fragment shader to use. What Vertex Shaders Can\u0026rsquo;t Do They can\u0026rsquo;t see other vertices. Each run only knows about its own vertex. That\u0026rsquo;s what lets thousands run in parallel, in any order. They can\u0026rsquo;t create or delete vertices. One vertex goes in, one comes out. (Some optional extra pipeline stages can add geometry, but WebGL doesn\u0026rsquo;t have them.) They don\u0026rsquo;t decide colours on screen. They can pass colours along, but which pixels get which colour is decided later, by rasterisation and the fragment shader. Under the hood A graphics card doesn\u0026rsquo;t run one vertex at a time. It gathers vertices into groups, typically 32 or 64, and runs the shader on the whole group at once, with every vertex in the group executing the same instruction at the same moment on different data. This is called SIMD (single instruction, multiple data), and it\u0026rsquo;s why a graphics card can afford thousands of tiny processors: they share the work of reading and understanding each instruction. It also explains why shaders are written so that every run does the same thing in the same order. How GPUs Run Shaders covers this in detail.\nSummary A vertex shader runs once per vertex, in parallel, each run on its own. Its inputs are attributes (per vertex), uniforms (per draw) and built-ins; its outputs are the clip-space position and varyings. Its one essential job is writing the position, usually P × V × M × position. It can move vertices for animation and effects, but can\u0026rsquo;t see neighbours or add vertices. Next, part 8 untangles something that trips up everyone who moves between engines and APIs: matrix conventions. It\u0026rsquo;s optional on a first read, so if you\u0026rsquo;d rather keep going, skip to part 9, which follows the transformed triangles into the rasteriser to decide exactly which pixels they cover.\nFurther Reading The Khronos Group, Vertex Shader: inputs, outputs and built-in variables in detail. LearnOpenGL, Shaders: GLSL from the beginning, with uniforms and varyings. WebGL2 Fundamentals, Shaders and GLSL: attributes, uniforms and varyings in WebGL2. Microsoft, Vertex shader stage: the same stage in Direct3D and HLSL. ","permalink":"https://fragmentshack.com/posts/vertex-shaders/","summary":"The vertex shader runs once for every vertex, placing it on screen and passing data along. Edit one live: make waves, twist shapes and see exactly what it can and can\u0026rsquo;t do.","title":"📍 Vertex Shaders: A Tiny Program for Every Corner"},{"content":"Introduction There\u0026rsquo;s no camera object inside a graphics card. What a game calls \u0026ldquo;the camera\u0026rdquo; is really two of the matrices from part 5: the view matrix, which says where the camera is and which way it\u0026rsquo;s looking, and the projection matrix, which says what kind of lens it has. This post covers:\nHow the view matrix is built, and why it\u0026rsquo;s the inverse of the camera\u0026rsquo;s position The frustum: the shape of space a camera can see Field of view, aspect ratio and the near and far planes The difference between perspective and orthographic projection The View Matrix: Moving the World, Not the Camera Placing a camera is just like placing any other object: it has a position and a direction, so we could build a model matrix for it from a rotation and a translation. Call that the camera\u0026rsquo;s world matrix: it takes points from the camera\u0026rsquo;s own space into world space.\nBut we need the opposite. We want to take every point in the world and express it relative to the camera. A matrix that undoes another matrix is called its inverse, so:\nview matrix = inverse of the camera's world matrix If the camera moves 5 units to the right, the view matrix moves the whole world 5 units to the left. If the camera turns left, the view matrix turns the world right. Everything ends up arranged around a camera sitting at the origin, which is view space.\nIn practice, most engines build the view matrix directly with a look-at function: give it the camera\u0026rsquo;s position (the eye), a point to look at (the target) and which way is roughly up, and it works out the camera\u0026rsquo;s three axes with a little vector maths (mainly the cross product, which finds the direction at right angles to two others). The rows of the rotation part of the resulting matrix are exactly those three axes: right, up and backwards (backwards because, in OpenGL\u0026rsquo;s convention, the camera looks down −z). You can see it in the demo below.\nThe Frustum A camera can\u0026rsquo;t see everything. It sees a region shaped like a pyramid lying on its side, with the camera at the tip, cut off near the tip and again further away. That shape is called the view frustum (\u0026ldquo;frustum\u0026rdquo; is the word for a cone or pyramid with its top sliced off). Anything outside it isn\u0026rsquo;t drawn.\nThe demo shows the scene from outside on one side, with the camera (orange) and its frustum outlined, and what that camera actually sees on the other. Drag the overview to look around it.\nA camera's frustum, and what it sees\nLeft: the scene from outsideRight: what the camera sees Projection Perspective Orthographic Dolly zoom Field of view: Box height: Camera distance: Camera direction: Near: Far: View matrix (rows 1 to 3 of the rotation part are the camera’s right, up and back directions):\nProjection matrix:\nField of view The field of view (FOV) is the angle between the top and bottom of the frustum (some engines measure side to side instead). A wide angle sees more of the scene, but each object takes up less of the picture, and objects near the edges of the picture look stretched outwards. (Straight lines still stay straight, unlike with a real fish-eye lens, which bends them.) A narrow angle is like a telephoto lens: it magnifies, and flattens the sense of depth. The width of the frustum comes from the height multiplied by the aspect ratio, the image\u0026rsquo;s width divided by its height, so the picture isn\u0026rsquo;t stretched.\nPress Dolly zoom to see the famous film trick: the camera moves back while the field of view narrows, keeping the ball the same size. The ball doesn\u0026rsquo;t change, but the pillars behind it seem to swing towards it, because the strength of the perspective is changing.\nNear and far planes The frustum is cut off at a near plane and a far plane (in maths, a plane is a flat surface that goes on forever). Nothing closer than the near plane or further than the far plane is drawn. Drag the near slider up until it slices through the ball, or pull the far slider in until the distant pillars vanish.\nWhy not make the near plane tiny and the far plane enormous? (It can never be exactly 0: the projection divides by distance, and dividing by zero breaks the maths.) The depth buffer (part 11) stores depth with limited precision, spread very unevenly between near and far. A near plane that\u0026rsquo;s too close wastes most of that precision right in front of the camera, and distant surfaces start to flicker through each other. The usual advice is to push the near plane out as far as you can get away with.\nPerspective and Orthographic Projection A perspective projection makes things smaller the further away they are, using the divide by w from part 5. It\u0026rsquo;s how our eyes and real cameras work, and most 3D games use it.\nAn orthographic projection doesn\u0026rsquo;t shrink distant objects at all. The frustum becomes a plain box, and parallel lines stay parallel on screen. Switch the demo to Orthographic and look at the pillars: the far ones are exactly as big as the near ones. It\u0026rsquo;s used for 2D games, strategy and \u0026ldquo;isometric-looking\u0026rdquo; games, technical drawings, user interfaces, and for the light\u0026rsquo;s point of view when drawing shadows (Shadow Mapping). In the projection matrix, you can see the difference in the bottom row: for perspective it\u0026rsquo;s (0, 0, −1, 0), which copies the depth into w; for orthographic it\u0026rsquo;s (0, 0, 0, 1), so w stays 1 and the divide does nothing.\nUnder the hood Engines usually skip drawing objects that are completely outside the frustum before sending them to the graphics card at all. This is frustum culling: the CPU tests a simple box or sphere that surrounds each object against the frustum\u0026rsquo;s six sides, which can be read straight out of the view and projection matrices multiplied together. It\u0026rsquo;s often the single biggest saving in a game\u0026rsquo;s drawing code, because most of a large world is behind or beside the camera. Anything that slips through is still safe: the hardware clips triangles to the frustum after the vertex shader, as described in part 5.\nSummary A camera is two matrices: the view matrix (where it is) and the projection matrix (its lens). The view matrix is the inverse of the camera\u0026rsquo;s world matrix, usually built with look-at. The camera sees a frustum, shaped by the field of view, aspect ratio, near and far planes. Perspective shrinks distant things; orthographic doesn\u0026rsquo;t. Keep the near plane as far out as you can, for depth precision. Next, part 7 looks at the program that applies all these matrices to every vertex: the vertex shader.\nFurther Reading LearnOpenGL, Camera: building a look-at camera and moving it with the keyboard and mouse. WebGL2 Fundamentals, 3D Cameras and Visualizing the Camera: the view matrix as an inverse, with a frustum visualiser. Song Ho Ahn, OpenGL Projection Matrix: the perspective and orthographic matrices derived from scratch. Gil Gribb and Klaus Hartmann, Fast Extraction of Viewing Frustum Planes from the World-View-Projection Matrix: the classic trick for frustum culling. ","permalink":"https://fragmentshack.com/posts/cameras-view-projection/","summary":"A game camera is just two matrices. See how the view matrix moves the world, how field of view, near and far shape the frustum, and how perspective differs from orthographic.","title":"🎥 Cameras: How the View and Projection Matrices Work"},{"content":"Introduction Part 4 showed how a matrix can move, rotate and scale a mesh. In a real game, every vertex goes through not one but a whole chain of transformations on its way to the screen, and each step moves it into a new coordinate space. This post covers:\nWhat a coordinate space is, and why graphics uses several of them The five spaces every vertex passes through: local, world, view, clip (and NDC) and screen The model, view and projection matrices that connect them Where the famous divide by w fits in (w is the extra coordinate from part 4), which is how perspective happens The demo lets you watch an entire scene move through each space, so you can see what each matrix actually does.\nWhat Is a Coordinate Space? A coordinate is only meaningful once you know what it\u0026rsquo;s measured from. \u0026ldquo;Three steps forward\u0026rdquo; means something different depending on where you\u0026rsquo;re standing and which way you\u0026rsquo;re facing. A coordinate space is a choice of origin (the point (0, 0, 0)) and of directions for the x, y and z axes. The same point in the world has different coordinates in different spaces, just as your house has a different \u0026ldquo;address\u0026rdquo; in a street map, a country map and a satellite photo.\nGraphics uses several spaces because each one makes a particular job easy:\nModelling a chair is easiest when the chair\u0026rsquo;s own centre is the origin Placing chairs around a room is easiest with one shared origin for the whole room Working out what the camera sees is easiest when the camera is the origin Working out which pixel a point lands on is easiest in a space that matches the screen The matrices from part 4 are how we get from one space to the next.\nThe Journey Use the buttons (or Next) to move the scene from one space to the next, and drag the picture to look around (or select it and use the arrow keys). You\u0026rsquo;re watching from outside, as an observer: the outlined box is what the scene\u0026rsquo;s camera can see. The table underneath follows a single point, the pink corner of the roof, through every space. The field of view slider changes how wide an angle the camera sees, like zooming a camera lens out or in.\nOne scene in each coordinate space\n« Previous Next » Look from behind the camera Turn the house: Camera field of view: 1. Local space Each mesh is built in its own local space (also called object or model space), usually with the origin at its centre or at its base. The house\u0026rsquo;s vertices are stored like this. Local space doesn\u0026rsquo;t know or care where the house will end up.\n2. World space The model matrix moves each object from its local space into world space: one shared space for the whole scene. It\u0026rsquo;s built from the scale, rotation and translation of part 4. Try Turn the house while in world space: only the model matrix changes, so only the house moves. Every object has its own model matrix; the two crates use the same mesh with different model matrices.\n3. View space Next, the view matrix moves everything so that the camera ends up at the origin, looking straight down an axis. This is view space (also called camera or eye space). It might seem odd to move the whole world rather than the camera, but the result on screen is identical, and it makes the next step much simpler. If you\u0026rsquo;ve ever felt like a train next to yours was moving when it was really your own train, it\u0026rsquo;s the same idea. Part 6, Cameras, covers how the view matrix is built.\nBy convention in OpenGL and WebGL, the camera looks down the negative z axis in view space, with x to the right and y up. Other engines choose differently, which is the subject of part 8.\n4. Clip space and NDC The projection matrix is where the 3D view gets turned into something that can become a 2D image. It maps the camera\u0026rsquo;s viewing volume, called the frustum (a pyramid with its top cut off), onto a simple box. The result is clip space, and the vertex shader\u0026rsquo;s job is to output each vertex\u0026rsquo;s position in clip space.\nClip space coordinates have four numbers, (x, y, z, w), and this is where the extra coordinate from part 4 earns its keep. A perspective projection matrix copies each point\u0026rsquo;s depth (how far it is in front of the camera) into w. The graphics card then divides x, y and z by w. Dividing by the depth makes far-away things smaller, which is exactly what perspective is. The result is called normalised device coordinates, or NDC: everything the camera can see ends up inside a cube from −1 to +1 on each axis (in OpenGL and WebGL; Direct3D, Vulkan and Metal use 0 to 1 for z).\nStep from View to Clip → NDC in the demo and watch the frustum become a cube. The far end of the box shrinks the most, so distant objects are squashed smaller, while nearby objects are stretched bigger. Widen the field of view and the squashing gets stronger. Compare the clip and NDC rows in the table: NDC is just clip divided by w.\nUnder the hood The divide by w isn\u0026rsquo;t done by your shader. Your vertex shader outputs a clip-space position, and the fixed-function hardware takes it from there. Before dividing, it clips triangles against the edges of the visible volume: in OpenGL\u0026rsquo;s convention, a point is inside if each of x, y and z is between −w and +w. That\u0026rsquo;s why it\u0026rsquo;s called clip space. Doing this before the divide matters: a point behind the camera has a negative w, and dividing by it would flip it to the wrong side of the screen. Then it divides by w, and finally applies the viewport transform.\n5. Screen space The last step, the viewport transform, stretches NDC to the size of the canvas in pixels: −1 to +1 in x becomes 0 to 1280, for example. The z value is kept (scaled to 0 to 1 by default) for the depth test in part 11. This is screen space (or window space), and it\u0026rsquo;s where rasterisation happens. Notice in the table that screen y is measured from the top here, as most screen and image coordinates are. OpenGL\u0026rsquo;s own window coordinates actually count from the bottom; part 8 covers this kind of difference.\nPutting It Together: Model, View, Projection So a vertex\u0026rsquo;s journey is:\nlocal → model matrix → world → view matrix → view → projection matrix → clip → ÷ w → NDC → viewport → screen The first three steps are matrices, so they can be multiplied into a single model-view-projection matrix, often called the MVP:\nclip = P × V × M × local A typical vertex shader does little more than this multiplication. The CPU builds the matrices once per object per frame, and the graphics card applies them to every vertex. The divide by w and the viewport transform are done by the hardware afterwards.\nSome calculations are easier in particular spaces, so shaders often keep intermediate results too. Lighting is commonly done in world space or view space, for example, because distances and angles there are the same as in the real scene. In clip space and NDC they\u0026rsquo;ve been squashed by perspective.\nQuestions You Might Have Which way is up? It depends on the convention. This site, like most WebGL code, uses y up. Some tools and engines, such as Blender and Unreal Engine, use z up instead, which is one of the things to watch for when moving models between programs (Matrix Conventions).\nSummary A coordinate space is a choice of origin and axes; the same point has different coordinates in each. Local → world uses the model matrix, world → view uses the view matrix, view → clip uses the projection matrix. The vertex shader outputs clip space. The hardware clips, divides by w (giving perspective and NDC), and maps to screen space pixels. P × V × M combines the three matrices into one. Next, part 6 builds the view and projection matrices properly: cameras.\nFurther Reading LearnOpenGL, Coordinate Systems: the same five spaces, with the code to set them up. Song Ho Ahn, OpenGL Transformation and OpenGL Projection Matrix: clear diagrams of each space, and the projection matrix derived step by step. WebGL2 Fundamentals, 3D Perspective: how the divide by w produces perspective, built up gradually. MDN, WebGL model view projection: a walkthrough of clip space and the MVP matrix in WebGL. ","permalink":"https://fragmentshack.com/posts/coordinate-spaces-transform-chain/","summary":"Every vertex travels through local, world, view, clip and screen space on its way to a pixel. Watch a whole scene morph through each space, and follow one point\u0026rsquo;s coordinates.","title":"🌍 Coordinate Spaces: The Journey from Model to Screen"},{"content":"Introduction A mesh is built once, in its own coordinates, but a game shows it in many places: a hundred trees, each in a different spot, turned a different way and a slightly different size. Instead of changing every vertex by hand, graphics programs describe each change as a transformation matrix: a small grid of numbers that moves, rotates and scales every vertex in one go. This post covers:\nWhat a matrix does to a point, and how to read a matrix just by looking at it The three basic transformations: scale, rotate and translate (move) Why 3D graphics uses 4×4 matrices, even though space only has three dimensions Why the order you combine transformations in changes the result To keep the pictures simple, the demos are in 2D, but everything here works the same way in 3D with one more row and column.\nA Matrix Moves Points (Coordinates and Vectors gently introduces this section.) A point in 2D is a pair of numbers, (x, y): how far it is along the x axis (horizontal) and the y axis (vertical). The axes cross at the origin, the point (0, 0).\nA matrix is a grid of numbers. A 2D transformation matrix has two rows and two columns (2×2), and \u0026ldquo;multiplying\u0026rdquo; a point by it follows a fixed recipe that gives a new point. Writing a·x to mean \u0026ldquo;a times x\u0026rdquo;, the recipe is:\nabcd × xy = a·x + b·yc·x + d·y Each new number is a mix of the old ones: the new x is a lots of the old x plus b lots of the old y, and the new y is c lots of x plus d lots of y. But there\u0026rsquo;s a much more useful way to think about it.\nThe columns are where the axes go Put the point (1, 0), one step along the x axis, through the rule above, and you get (a, c): the first column of the matrix. Put in (0, 1), one step up the y axis, and you get (b, d): the second column. So:\nThe first column says where the x axis ends up The second column says where the y axis ends up Every other point comes along for the ride, because (2, 3) just means \u0026ldquo;2 steps along x plus 3 steps along y\u0026rdquo;, and those steps follow the axes. This is the most useful fact about transformation matrices: you can read what a matrix does from its columns.\nTry It The demo below builds a matrix from sliders: move (translate), rotate and scale. The house is drawn with the matrix applied, the red and green arrows show where its x and y axes have gone, and the matrix is shown underneath in the same colours. Then switch to Drag the axes and move the arrow tips to make any matrix, including ones the sliders can\u0026rsquo;t, like a slant (a shear) or a mirror image.\nA 2D transformation and its matrix\nMode Use the sliders Drag the axes Move x: Move y: Rotate: Scale x: Scale y: Some things to try:\nRotate only. As the angle grows, the red arrow\u0026rsquo;s tip travels round a circle and the green one stays at right angles to it. Both keep their length, so the house turns without changing shape. (In trigonometry terms, the columns are (cos θ, sin θ) and (−sin θ, cos θ) for an angle θ; Angles, Sine and Cosine explains them.) Scale x to 2. The first column doubles and the house stretches sideways. Scale to a negative number and the house flips over: a mirror image. In Drag the axes mode, drag the green tip sideways without moving the red one. That\u0026rsquo;s a shear. Drag one tip on top of the other and the house is squashed flat: no 2D picture is left to undo, so this matrix can\u0026rsquo;t be reversed. Moving Needs an Extra Dimension The matrix in the demo is 3×3, not 2×2, because a 2×2 matrix can\u0026rsquo;t move anything: whatever its numbers, (0, 0) always comes out as (0, 0). Rotation and scaling keep the origin fixed, but moving (translation) doesn\u0026rsquo;t.\nThe trick is to give every point an extra coordinate, always set to 1: (x, y) becomes (x, y, 1). These are called homogeneous coordinates. Now a 3×3 matrix can add a fixed amount to each coordinate, using its third column:\nabtxcdty001 × xy1 = a·x + b·y + txc·x + d·y + ty1 The third column is exactly how far the origin moves. 3D graphics does the same thing one size up: points are (x, y, z, 1), and transformations are 4×4 matrices, with the x, y and z axes in the first three columns and the translation in the fourth.\nA nice side effect: set the extra coordinate to 0 instead of 1 and translation has no effect. That\u0026rsquo;s just right for a direction, like \u0026ldquo;the way this surface faces\u0026rdquo;, which should turn with the object but not move with it. The extra coordinate returns, doing something much cleverer, for perspective in part 5.\nCombining Transformations To scale, rotate and move a mesh, you could apply three matrices to every vertex in turn. But multiplying two matrices gives one matrix that does both jobs, so games multiply all of an object\u0026rsquo;s transformations together once and apply that single matrix to every vertex. A whole chain costs the same per vertex as one.\nBut the order matters. In the demo below, both houses get the same two steps: rotate by 45°, and move 3 to the right. It plays once by itself; press Play to watch again.\nSame two steps, different order\n▶ Play Progress: Rotation and scaling always happen around the origin. If the object has already been moved away from the origin, rotating swings it around in a big arc instead of turning it on the spot. That\u0026rsquo;s why the usual order for placing an object is scale, then rotate, then translate.\nWhen matrices are written as a multiplication, the one nearest the point happens first. So \u0026ldquo;scale, then rotate, then translate\u0026rdquo; is written:\nM = T × R × S, \u0026nbsp; and then \u0026nbsp; p′ = M × p Here p is a point, p′ (say \u0026ldquo;p dash\u0026rdquo;) is where it ends up, and the formula reads right to left: S happens first. If that feels backwards, you\u0026rsquo;re not alone, and some game engines (the software games are built on, such as Unity or Unreal) write it the other way round. That\u0026rsquo;s the topic of part 8, Matrix Conventions.\nUnder the hood Multiplying a 4×4 matrix by a point (x, y, z, 1) is 16 multiplications and 12 additions. Graphics cards are built for exactly this: each of their thousands of small processors does a multiplication and an addition in a single step, all at once, so transforming millions of vertices every frame is routine. Combining matrices is usually done once per object on the main processor (the CPU), and the result is handed to the vertex shader as a uniform: a value that\u0026rsquo;s the same for every vertex in a draw call.\nQuestions You Might Have Do I have to build these matrices by hand? No. Maths libraries (glMatrix for WebGL, GLM, DirectXMath, or the one in your game engine) have functions like translate, rotate and perspective that build them for you. Knowing what\u0026rsquo;s inside is what helps when something ends up in the wrong place.\nSummary A matrix transforms points; each new coordinate is a mix of the old ones. The columns of a matrix are where the axes end up, so you can read a matrix by looking at it. Homogeneous coordinates add a 1 to every point, so one matrix can also translate. That\u0026rsquo;s why 3D uses 4×4 matrices. Matrices combine by multiplying, and order matters: usually scale, then rotate, then translate. Next: coordinate spaces and the transform chain, where a series of these matrices carries every vertex from its model all the way to the screen.\nFurther Reading 3Blue1Brown, Essence of Linear Algebra: beautifully animated videos on what matrices really do. Chapters 3 and 4 match this post. LearnOpenGL, Transformations: the same ideas in 3D, with the code to use them in shaders. WebGL2 Fundamentals, 2D Matrices: building up 2D transformations step by step. Wikipedia, Transformation matrix: a reference for rotation, shear, reflection and more. ","permalink":"https://fragmentshack.com/posts/transformation-matrices/","summary":"How a small grid of numbers can move, turn, stretch and mirror a whole mesh at once, why its columns tell you where the axes go, and why the order you combine them in matters.","title":"🔄 Transformation Matrices: Moving, Rotating and Scaling with Grids of Numbers"},{"content":"Introduction Part 2 showed that the graphics pipeline starts with a list of vertices. This post looks at that input properly:\nWhat a vertex is and what it stores Why graphics cards draw everything with triangles How vertices and triangles make up a mesh, and how an index buffer saves memory Winding order: how the order of a triangle\u0026rsquo;s corners tells the graphics card which side is the front Vertices: More Than Just Corners A vertex (plural: vertices) is a corner of a shape. At minimum it has a position: three numbers saying how far it is along each of three directions, called x (left and right), y (up and down) and z (forwards and backwards). A position like (2, 0, −1) means 2 steps along x, none along y and 1 step backwards along z. But a vertex usually carries other information too, called vertex attributes. Common ones are:\nA normal: a direction pointing straight out of the surface at that point, used for lighting (part 12 covers this) A texture coordinate, or UV: which point of an image (a texture) should be stretched onto this corner, so a picture can be wrapped over the surface (the Textures \u0026amp; Sampling series covers this) A colour For animated characters, which bones the vertex follows and by how much The graphics card doesn\u0026rsquo;t care what the numbers mean. It just passes them to the vertex shader, which uses them however it likes.\nWhy Triangles? Graphics cards can draw points and lines, but every solid surface is drawn as triangles. That\u0026rsquo;s because a triangle has some very useful properties:\nIt\u0026rsquo;s always flat. Any three points lie on a single flat plane. Four points don\u0026rsquo;t have to: a \u0026ldquo;square\u0026rdquo; whose corners have been pulled about can bend, and then it\u0026rsquo;s not clear what its surface should look like in between. It\u0026rsquo;s always convex. A triangle has no dents, so a straight line crosses its edge at most twice. That makes working out which pixels are inside it fast and simple, as part 9 shows. It\u0026rsquo;s simple to blend across. Any point inside a triangle can be described as a mix of its three corners. That\u0026rsquo;s how values like colours and texture coordinates are smoothly spread across the surface (part 10). Any other flat shape with straight edges (a polygon) can be split into triangles, so nothing is lost. Curved surfaces are approximated with lots of small triangles: the more you use, the smoother the curve looks.\nMeshes A mesh is a collection of triangles that together make up the surface of an object. In the demo below, drag the shape to turn it (or select it and use the arrow keys), change the detail, and switch to wireframe (just the triangles\u0026rsquo; edges) or vertices to see what it\u0026rsquo;s made of.\nMeshes made of triangles, and the memory they take\nShape Sphere Doughnut Flat grid Cube Show Shaded Wireframe Vertices Detail: Notice how a low-detail sphere looks like a cut gem, and how its outline only becomes smooth with many triangles. Notice also that a cube has 24 vertices, not 8. Each corner of a cube belongs to three faces that point in different directions, so it needs three different normals, and a vertex can only hold one of each attribute. Wherever a surface has a hard edge or a seam in its texture, its vertices have to be split into copies.\nVertex buffers and index buffers A mesh is uploaded to the graphics card\u0026rsquo;s memory as a vertex buffer: one long list of vertices, one after another. The simplest way to describe triangles is to list three vertices for each one. But most vertices are shared: on a smooth sphere, most vertices are corners of six triangles (and the ones at the poles, of many more), so that would store the same vertex six times or more.\nInstead, each vertex is stored once, and a second list, the index buffer, describes each triangle with three small numbers: the positions of its corners in the vertex buffer. For example, 0, 1, 2, 2, 1, 3 makes two triangles that share vertices 1 and 2. An index is usually 2 bytes, while a vertex can easily be 32 bytes or more, so this saves a lot of memory, as the readout above shows. It saves work too, as the graphics card can often reuse the vertex shader\u0026rsquo;s result for a vertex it has just processed, instead of running it again.\nWhich Way Is the Front? Winding Order A triangle has two sides. For a closed object like a sphere, you only ever see the outside of each triangle; the inside faces are hidden. If the graphics card could tell which triangles face away from the camera, it could skip them, which roughly halves the work for a closed object.\nIt tells them apart using the order of the corners. Look at the triangle on screen and follow its corners in the order they\u0026rsquo;re listed: they go round either clockwise or anticlockwise (also called counter-clockwise, which is where WebGL\u0026rsquo;s setting name gl.CCW comes from). That\u0026rsquo;s the triangle\u0026rsquo;s winding order. Models are built so that every triangle\u0026rsquo;s corners go round anticlockwise when seen from the outside (or clockwise; it\u0026rsquo;s a convention that you choose). When a triangle is turned to face away, the same corners appear to go round the other way. Skipping triangles that wind the \u0026ldquo;wrong\u0026rdquo; way is called back-face culling.\nDrag the corners below, and try to make them go round the other way.\nWinding order and back-face culling\nCull back faces As soon as you drag one corner across the line between the other two, the order flips from anticlockwise to clockwise and the triangle disappears. When a 3D object turns away from the camera, exactly this happens to its triangles on screen.\nUnder the hood The graphics card doesn\u0026rsquo;t \u0026ldquo;look\u0026rdquo; at the triangle. After the vertex shader, it knows the three corners\u0026rsquo; positions on screen, and it works out the triangle\u0026rsquo;s signed area with a single formula. The sign (positive or negative) gives the winding order directly. In OpenGL and WebGL, anticlockwise triangles are front faces by default, and culling is switched off until a program turns it on. Direct3D defaults to treating clockwise triangles as front faces and culls back faces by default. Either way it\u0026rsquo;s a setting, so what matters is that your models and your settings agree.\nQuestions You Might Have Where do meshes come from? Artists build them in modelling programs such as Blender, Maya or 3ds Max, and save them in files (such as .obj, .fbx or .gltf) that the game loads into vertex and index buffers. Some, like this demo\u0026rsquo;s sphere, are generated by code.\nIs a vertex the same as a pixel? No. A vertex is a corner of a triangle, with a position and any other data attached (colour, normal, texture coordinates). Pixels only appear later, when the triangles are filled in (Rasterisation).\nSummary A vertex is a corner with a position plus attributes such as a normal, texture coordinate or colour. Everything solid is drawn with triangles, because they\u0026rsquo;re always flat, convex and easy to blend across. A mesh is many triangles. Hard edges and texture seams need duplicated vertices. An index buffer lets triangles share vertices, saving memory and vertex shader work. Winding order tells front faces from back faces, so hidden back faces can be culled. Next we\u0026rsquo;ll learn how to move, turn and resize meshes with transformation matrices.\nFurther Reading Khronos OpenGL Wiki, Face Culling: winding order and culling in detail. LearnOpenGL, Hello Triangle: vertex buffers, index (element) buffers and drawing them, in code. Microsoft, Rasterizer state: Direct3D 11\u0026rsquo;s culling and front-face settings and their defaults. Wikipedia, Polygon mesh: other ways of storing meshes, and the trade-offs. ","permalink":"https://fragmentshack.com/posts/vertices-triangles-meshes/","summary":"Why every 3D object is built from triangles, what a vertex stores, how index buffers save memory, and how the order of a triangle\u0026rsquo;s corners decides which side is the front.","title":"🔺 Vertices, Triangles and Meshes: The Shapes Games Are Made Of"},{"content":"Introduction In part 1 we saw that the graphics card\u0026rsquo;s job is to fill a grid of pixels with colours. But a game doesn\u0026rsquo;t hand it a grid of colours; it hands it a 3D world made of triangles. The series of steps that turns one into the other is called the graphics pipeline, and it\u0026rsquo;s the backbone of everything else on this site. This post covers:\nThe six main stages of the pipeline, and what each one does Which stages you program yourself (shaders) and which are built into the hardware How often each shader actually runs, measured on your own graphics card Every later post in this series zooms in on one of these stages, so think of this as the map.\nWhy a Pipeline? A factory production line splits a big job into small steps, with each worker doing one step over and over. While one car is being painted, the next is having its wheels fitted. A graphics card works the same way: each stage takes the output of the stage before it, and all stages work at once on different pieces of the frame.\nEach stage also works on many things in parallel. A graphics card has thousands of small processors, and the work is arranged so that each vertex, and each pixel, can be handled independently of the others. That\u0026rsquo;s why a graphics card can colour millions of pixels in a few milliseconds when a normal processor would take far longer.\nThe Six Stages Step through the stages below, using the buttons or Next. The image is a tiny 24 × 14 pixels so you can see every one, and it contains two triangles: an orange one in front and a blue one behind.\nTwo triangles going through the graphics pipeline, one stage at a time\n« Previous Next » Here is each stage in a little more detail.\nVertex data. The game uploads its 3D models, called meshes, to the graphics card\u0026rsquo;s memory. A mesh is stored as a list of vertices: the corners of its triangles. Each vertex carries a position and usually more, such as a colour, or which point of an image should be stretched onto that corner. The next part, Vertices, Triangles and Meshes, covers this in detail. Vertex shader. A small program, written by the game\u0026rsquo;s developers, that runs once for each vertex. Its main job is to work out where the vertex ends up on screen, which usually involves some grids of numbers called matrices that move, turn and project things; parts 4 to 7 of this series explain them. It can also move vertices around to animate them. Primitive assembly. The vertices are joined up into triangles. Triangles completely outside the view are thrown away, triangles crossing the edge of the view are trimmed where necessary (clipped), and triangles facing away from the camera can be skipped too (culling). Rasterisation. For each triangle, the hardware works out which pixels it covers. Each covered pixel becomes a fragment: a candidate for that pixel, carrying values blended from the triangle\u0026rsquo;s three vertices. Fragment shader. Another small program written by the developers, which runs once for each fragment and works out its colour. This is where texturing and lighting usually happen. (Some graphics systems, such as Microsoft\u0026rsquo;s Direct3D, call it a pixel shader.) Output merging. Each fragment\u0026rsquo;s colour is tested and combined with what\u0026rsquo;s already in the framebuffer. The depth test throws away fragments hidden behind something nearer, and blending mixes colours for see-through surfaces. A shader is just a program that runs on the graphics card as one of these stages. The name is historical: the first ones only worked out shading (light and dark), but today they do far more.\nProgrammable and fixed stages Only the vertex and fragment shaders are programs you write. Rasterisation, clipping and the depth test are fixed-function stages: built into the hardware, and only configurable through settings like \u0026ldquo;turn the depth test on\u0026rdquo;. Modern graphics cards also have a few optional extra programmable stages, which this series doesn\u0026rsquo;t need: the six stages above are the core that everything else builds on.\nWho Tells the Graphics Card What to Do? The game runs on the computer\u0026rsquo;s main processor (the CPU). To draw something, it calls a graphics API (application programming interface): a set of functions provided for programs to use, such as Direct3D, Vulkan, Metal, OpenGL or, in a web browser, WebGL. It sets up which shaders, meshes and textures to use, then issues a draw call: \u0026ldquo;draw these triangles\u0026rdquo;.\nThe graphics card\u0026rsquo;s driver, software supplied by its manufacturer, translates those calls into commands the hardware understands and queues them up. The graphics card works through the queue on its own, which leaves the CPU free to get on with the game. A typical frame of a modern game might make thousands of draw calls.\nHow Often Does Each Shader Run? The vertex shader runs once per vertex, and the fragment shader runs once per fragment, roughly once per covered pixel. Those can be wildly different numbers. The demo below draws a sphere on your graphics card, then reads the image back to count exactly how many pixels it covers.\nCounting vertex shader and fragment shader runs for a sphere\nDetail: Distance: Resolution: ▶ Play Try these:\nMove the sphere further away. The number of fragments drops quickly (it shrinks with the area on screen), but the vertex count doesn\u0026rsquo;t change at all: the vertex shader still has to process every vertex, however small the sphere looks. Turn up the detail while the sphere is small. The vertex shader now does more work than the fragment shader, which is why games swap distant objects for simpler versions, called levels of detail. Lower the resolution. Fragment work falls with the number of pixels. This is why lowering the resolution is the classic way to make a game run faster, and why games often draw at a lower resolution and then stretch the picture up to full size (upscaling). Under the hood The counts in the demo are close, but not exact. Vertices shared by several triangles are normally processed once and the result reused, but the graphics card only remembers a small number of recent results, so some vertices can run more than once. Fragment shaders always run in little 2×2 squares of pixels, so pixels along a triangle\u0026rsquo;s edge often cost a few extra \u0026ldquo;helper\u0026rdquo; runs. And in a scene where objects overlap, a pixel can be coloured several times over before the nearest object wins, which is called overdraw. Graphics cards reduce that by checking, before running the fragment shader, whether the fragment is hidden behind something already drawn. The Helper Pixels post shows the 2×2 groups in action.\nQuestions You Might Have Why triangles, and not squares or circles? A triangle\u0026rsquo;s three corners always lie on one flat surface, so it can never be bent or twisted, and any shape can be built from enough of them. That keeps the hardware\u0026rsquo;s job of filling them in simple and very fast. Squares and circles are drawn as triangles too.\nSummary The graphics pipeline turns vertices into pixels in stages: vertex data, vertex shader, primitive assembly, rasterisation, fragment shader and output merging. The vertex shader runs once per vertex and places it on screen; the fragment shader runs once per covered pixel and colours it. The CPU drives it all with draw calls through a graphics API, and the driver turns them into hardware commands. Vertex work depends on mesh detail; fragment work depends on screen area and resolution. Next, we\u0026rsquo;ll look at what goes in at the very start of the pipeline: vertices, triangles and meshes.\nFurther Reading Fabian Giesen, A trip through the Graphics Pipeline 2011: the classic deep dive into what really happens at each stage, from the driver to the pixels. LearnOpenGL, Hello Triangle: the pipeline from a programmer\u0026rsquo;s point of view, with the code to draw your first triangle. WebGL2 Fundamentals, How It Works: how WebGL feeds vertex and fragment shaders. Microsoft, Graphics pipeline: Direct3D 11\u0026rsquo;s version of the pipeline, including the optional stages. ","permalink":"https://fragmentshack.com/posts/graphics-pipeline/","summary":"The six steps every graphics card follows to turn a list of triangles into a finished image. Step through each one, then count how often each shader really runs.","title":"🏭 The Graphics Pipeline: How Triangles Become Pixels"},{"content":"Introduction Before we can talk about how a graphics card (also called a GPU, for graphics processing unit) draws a 3D world, we need to know what it\u0026rsquo;s actually drawing into. Every frame of every game ends up as the same thing: a grid of tiny coloured squares. This post covers:\nWhat a pixel is, and how a screen makes colours from red, green and blue light How colours are stored as numbers, both in memory and in shaders The framebuffer: the block of memory where the picture lives while it\u0026rsquo;s being drawn The first demo runs on your own graphics card using WebGL, the browser\u0026rsquo;s built-in way for a web page to use the graphics card, like most demos on this site.\nA Picture Is a Grid of Pixels Look closely enough at any screen and you\u0026rsquo;ll find a grid of tiny squares, each showing a single colour. Each is a pixel, short for \u0026ldquo;picture element\u0026rdquo;. A Full HD screen has 1920 columns and 1080 rows of them, just over two million; a 4K screen has four times as many.\nEverything you see on screen, from text to faces to explosions, is just lots of single-coloured squares close together, which your eye blends into smooth shapes.\nIn the demo below, the graphics card draws a small landscape at the resolution you choose (the number of pixels across and down), then stretches it to fill the box without smoothing, so you can see every pixel. Drag the slider down to make the pixels huge, then hover over or tap a pixel (or select the image and use the arrow keys) to read its colour straight back from the graphics card.\nThe same picture at different resolutions\nPixels across: Outline pixels Some things to notice:\nAt 8 or 16 pixels across, the shapes are barely recognisable, and the edges of the sun and hills turn into staircases. Those steps are called aliasing, or \u0026ldquo;jaggies\u0026rdquo;, and fighting them is a big topic later in the site. As the resolution increases, each pixel covers less of the scene and the picture gets sharper. But doubling the width and height needs four times as many pixels. Each pixel\u0026rsquo;s colour is just three numbers. Keep reading to see what they mean. Mixing Colours from Red, Green and Blue Most screens can\u0026rsquo;t actually show \u0026ldquo;yellow\u0026rdquo; or \u0026ldquo;purple\u0026rdquo; directly. Instead, each pixel is made of three even smaller lights called sub-pixels: one red, one green and one blue. By setting how brightly each glows, the screen fools your eyes into seeing almost any colour: red and green together look yellow, all three at full brightness look white, and all three off is black. This is additive colour mixing, because the lights add together, unlike paint, which gets darker as you mix it.\nUse the sliders to mix a colour. The left side shows what you\u0026rsquo;d see from a normal distance; the right side shows a few pixels close up, as if under a magnifying glass.\nMixing a colour from red, green and blue light\nRed: Green: Blue: Yellow Cyan Magenta White Grey Black Real screens arrange their sub-pixels in different patterns (some phone screens share sub-pixels between neighbouring pixels, for example), but the idea is always the same: every colour is a mix of red, green and blue light.\nColours Are Just Numbers To a computer, each pixel\u0026rsquo;s colour is three numbers: how much red, green and blue. Computers store everything as bits, single on-or-off values written as 1 or 0, and the most common colour format uses 8 bits for each of red, green and blue. Eight bits can be set in 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 = 256 ways, giving 256 levels for each colour, from 0 (off) to 255 (full brightness). A group of 8 bits is a byte, so each channel takes one byte.\nThat\u0026rsquo;s also where colour codes like #E8743B come from: the three numbers written in hexadecimal (counting in sixteens, using 0 to 9 and then A to F for ten to fifteen), two digits each for red (E8 = 232), green (74 = 116) and blue (3B = 59). You don\u0026rsquo;t need to read hexadecimal for this site.\nOften there\u0026rsquo;s a fourth number, alpha, which usually stores how see-through a colour is. Red, green, blue and alpha together make 4 bytes per pixel, which is why the first demo multiplied the number of pixels by 4.\nShaders, the small programs that colour pixels (more on those later in the series), see colours differently. Inside a shader, each channel is a decimal number from 0.0 to 1.0, and a colour is a group of three numbers like vec3(0.91, 0.45, 0.23) (vec3 means \u0026ldquo;a group, or vector, of three numbers\u0026rdquo;: here red, green and blue). When the result is stored, the graphics card converts it back: 1.0 becomes 255, 0.5 about 128. Working with 0 to 1 keeps the maths simple: multiplying by 0.5 halves the value, whatever format the screen uses.\nA quick warning about \"half brightness\" A value of 128 doesn\u0026rsquo;t actually produce half as much light as 255. Most images use a standard called sRGB, which spends more of the 256 levels on dark shades, because our eyes are better at telling dark shades apart. In sRGB, 128 gives only about a fifth of the light of 255. It\u0026rsquo;s a surprisingly important detail for lighting maths, and it gets its own post in the Textures \u0026amp; Sampling series.\nThe Framebuffer: Where the Picture Lives When a graphics card draws a frame, it doesn\u0026rsquo;t paint directly onto the glass of your screen. It writes pixel colours into a block of its own memory called a framebuffer: one slot for every pixel, in rows, with 4 bytes per pixel. A 1920 × 1080 framebuffer is 1920 × 1080 × 4 = 8,294,400 bytes, a little over 8 megabytes.\nIf the screen showed the framebuffer while the graphics card was still drawing into it, you\u0026rsquo;d see half-finished frames. So games use (at least) two framebuffers:\nThe front buffer, which the screen is currently showing The back buffer, which the graphics card is drawing the next frame into When the frame is finished, the two swap roles: double buffering. A screen refreshing 60 times a second gives the graphics card about 16.7 milliseconds per frame, in which, at Full HD, it must colour over two million pixels, and usually many more, because parts of the scene get drawn on top of each other.\nUnder the hood A part of the graphics card called the display controller reads the front buffer row by row, from the top of the screen to the bottom, and sends the colours down the cable (HDMI or DisplayPort) to the screen, over and over, every refresh. If the buffers swap while it\u0026rsquo;s halfway down the image, the top of the screen shows the old frame and the bottom shows the new one, with a visible line between them. That\u0026rsquo;s called screen tearing. V-sync avoids it by waiting to swap until the display controller has finished sending the current frame.\nQuestions You Might Have Why red, green and blue, and not red, yellow and blue like paint? Screens add light together. Our eyes have three kinds of colour-sensing cells, and mixing red, green and blue light in different amounts can stimulate them in almost every combination we can see. Paints work the other way: each one absorbs some light, which is why mixing paints follows different rules.\nSummary A screen image is a grid of pixels, each a single colour. Each pixel\u0026rsquo;s colour is a mix of red, green and blue light, made by tiny sub-pixels. Colours are stored as numbers, usually 0 to 255 per channel in memory and 0.0 to 1.0 in shaders. The graphics card draws into a framebuffer in memory, and swaps finished frames to the screen. Next: how the graphics card draws, through the graphics pipeline, the series of steps that turns triangles into pixels.\nFurther Reading Wikipedia, RGB color model: how red, green and blue light combine into every colour a screen shows, and how the numbers are stored. Wikipedia, Pixel and Subpixel rendering: pixel layouts and the different sub-pixel patterns real screens use. Wikipedia, Multiple buffering: double and triple buffering, and why they exist. Wikipedia, sRGB: the colour standard most images and screens use. ","permalink":"https://fragmentshack.com/posts/pixels-and-colour/","summary":"Every image on your screen is a grid of coloured squares made from red, green and blue light. Zoom into one, mix colours, and see where the image lives in memory.","title":"🟥 Pixels and Colour: What Your Screen Is Really Showing"},{"content":" Every frame of every video game is built by your graphics card from millions of tiny calculations: triangles are positioned, pixels are coloured, textures are read and light is faked in clever ways. Fragment Shack is a place to learn how all of that works, one idea at a time, by playing with it.\nWho it\u0026rsquo;s for Fragment Shack is written for beginners. If you\u0026rsquo;ve played a video game and wondered how the picture gets on the screen, you\u0026rsquo;re in the right place. You don\u0026rsquo;t need to be a programmer, and you don\u0026rsquo;t need much maths: where a post needs some, it explains it from scratch.\nIf you already write shaders or game engines, you should still find something new, especially in the parts that explain what the hardware and drivers are doing behind the scenes.\nHow the posts work Every post is built around interactive demos. Most run live on your own graphics card, using WebGL (the browser\u0026rsquo;s built-in way of letting a web page use the graphics card); a few, such as the maths diagrams and the simulations of what happens inside the hardware, are drawn by ordinary JavaScript in the browser. You\u0026rsquo;ll find sliders, menus and buttons to tweak, and things you can drag around. The text explains the idea; the demos let you see it, test it and break it. Reading that distant textures can shimmer is one thing; switching off the fix and watching a floor sparkle in front of you is another.\nEach post:\nTeaches one main idea, and takes about 10 minutes to read and play with (the estimate at the top of each post allows 200 words a minute for reading, plus a minute and a half for each demo) Has at least one interactive demo, with a short explanation of what it shows and what to try Includes \u0026ldquo;Under the hood\u0026rdquo; boxes explaining what the graphics card and its driver are actually doing Ends with further reading, so you can go deeper Under the hood Boxes like this one appear throughout the site. They're optional, but they explain what's happening inside the hardware, which is where a lot of the \"why\" lives. Where to start Posts are grouped into series: short learning paths meant to be read in order.\nNew to graphics? Start with Graphics Fundamentals. It goes from \u0026ldquo;what is a pixel?\u0026rdquo; all the way to lighting a 3D object, and every later post builds on it. When a post links to a maths post, open it then: Maths for Graphics explains vectors, angles, blending and rays gently, with demos, exactly when you need them. Know the basics? Jump into whichever series catches your eye, or search for a specific technique. You can also browse by tag or see every post.\nWhat you need A modern web browser on a computer, tablet or phone. The demos use WebGL2, which every current major browser supports. Animated demos only run while they\u0026rsquo;re on screen, and don\u0026rsquo;t start by themselves if your device is set to reduce motion.\nThe demos run on whatever graphics hardware you have, so a few of them can show slightly different results on different devices. Where that happens, the post explains why, because those differences are often interesting in their own right.\nIf the demos don\u0026rsquo;t appear If a demo shows a \u0026ldquo;needs WebGL2\u0026rdquo; message instead of running, try these in order:\nUpdate your browser to the latest version. Turn on hardware acceleration. In Chrome and Edge it\u0026rsquo;s in Settings, under System, called \u0026ldquo;Use graphics acceleration when available\u0026rdquo;. In Firefox it\u0026rsquo;s in Settings, under General, then Performance. Restart the browser afterwards. Try a different browser. Current versions of Chrome, Edge, Firefox and Safari all support WebGL2. Check your device at get.webgl.org/webgl2, which tells you whether WebGL2 works there at all. Some older or locked-down computers, and some remote desktops, switch it off. Each demo shows a still picture in its place while it can\u0026rsquo;t run, so the text around it still makes sense.\nWhy \u0026ldquo;Fragment Shack\u0026rdquo;? In graphics, a fragment is a candidate pixel: when the graphics card draws a triangle, it produces a fragment for each pixel the triangle covers, and runs a small program called a fragment shader to decide its colour. Fragments are where triangles become pictures, and that\u0026rsquo;s what this site is about. The shack is just where we keep them.\nWelcome in, and have fun breaking things.\nStart at part 1 Browse the series ","permalink":"https://fragmentshack.com/welcome/","summary":"What Fragment Shack is, who it\u0026rsquo;s for, and how to get the most out of it.","title":"Welcome to Fragment Shack"}]