Welcome back! This time, we'll look into what is perhaps the "poster boy" feature introduced with the d3d11/shader 5.x hardware generation: tessellation. this one is interesting both because it's a fun topic, and because it marks the first time in a long while that a significant user-visible component has been added to the graphics pipeline that's not programmable.
Unlike geometry shaders, which are conceptually quite easy (it's just a shader that sees whole primitives as opposed to individual vertices), the topic of "tessellation" requires some more explanation. there's tons of ways to Tessellate geometry-to name just the most popular ones, there's spline patches in dozens of flavors, various types of subdivision surfaces, and Displacement mapping-so from the bullet point "tessellation" alone it's not at all obvious what services the GPU provides us with, and how they are implemented.
To describe how hardware tessellation works, it's probably easiest to start in the middle-with the actual primitive tessellation step, and the various requirements that apply to it. i'll get to the new Shader types (Hull shaders and domain shaders in d3d11 parlance, tessellation control shader and tessellation evaluation shader in OpenGL 4.0 lingo) later.
Tessellation-not quite like you 'd got CT
Tessellation as implemented by shader 5.x class HW is of the "patch-based" variety. patch types in the CG literature are mostly named by what kind of function is used to construct the tessellated points from the control points (B-spline patches, béz triangles, etc .). but we'll ignore that part for now, since it's handled in the new Shader types. the actual fixed-function tessellation unit deals only with the topology of the output mesh (I. e. how many vertices there are and how they're connected to each other); and it turns out that from this perspective, there's basically only two different types of patches: quad-based patches, which are defined on a parameter domain with two orthogonal coordinate axes (which I'll call u and v here, both are in [0, 1]) and usually constructed as a tensor product of two one-parameter basis functions, and triangle-based patches, which use a redundant representation with three coordinates (U, V, W) based on barycentric coordinates (I. e. u, V, W \ GE 0, U + V + W = 1 ). in d3d11 parlance, these are the "QUAD" and "tri" domains, respectively. there's also an "isoline" domain which instead of a 2D surface produces one or multiple 1D curves; i'll treat it the same way as I did lines and point primitives throughout this series: I acknowledge its existence but won't go into further detail.
Tessellated primitives can be drawn naturally in their respective domain coordinate systems. for quads, the obvious choice of drawing the domain is as a unit square, so that's what I'll use; for triangles, I'll use an equilateral triangle to visualize things. here's the coordinate systems I'll be using in this post with both the vertices and Edges labeled:
Anyway, both triangles and quads have what I wocould consider a "natural" way to Tessellate them, depicted below. but it turns out that's not actually the mesh topology you get. here's
ActualMeshes that the tessellator will produce for the given input parameters: For quads, this is (roughly) What we're re expecting-since T for some flipped diagonals, which I'll get to in a minute. but the triangle is a completely different beast. it's got a very different Topology from the "natural" tessellation I showed above, including a different number of vertices (12 instead of 10 ). clearly, there's something funny going on here-and that something happens to be related to the way transitions between different tessellation levels are handled.
Making ends meetThe elephant in the room is handling transitions between patches. tessellating a single triangle (or quad) is easy, but we want to be able to determine tessellation factors per-patch, because we only want to spend triangles where we need them-and not waste tons of triangles on some distant (and possibly backface-Culled) parts of the mesh. additionally, we want to be able to do this quickly and ideally without extra memory usage; that means a global fix-up post-pass or something of that caliber is out of the question.
The solution-which you 've already encountered if you 've written a hull or domain shader-is to make all of the actual tessellation work purely local and push the burden of ensuring watertightness for resulting mesh down to the shaders. this is a topic all by itself and requires, among other things, great care in the domain shader code; I'll skip all the details about expression evaluation in shaders and stick with the basics. the basic mechanism is that each patch has multiple tessellation factors (TFS), which are computed in the hull shader: one or two for the actual inside of the patch, plus one for each edge. the TFS for the inside of the patch can be chosen freely; but if two patches share an edge, they 'd better compute the exact same TFs along that edge, or there will be cracks. the hardware doesn' t care-it will process each patch by itself. if you do everything correctly, you'll get a nice watertight mesh, otherwise-well, that's your problem. all the HW needs to make sure is that it's
PossibleTo get watertight meshes, preferably with reasonable efficiency. That by itself turns out to be tricky in some places; I'll get to that later.
So, here are some new reference patches-this time with different TFs along each edge so we can see how that works: I 've colored the areas influenced by the different edge tessellation factors; the uncolored center part in the middle only depends on the inside TFs. in these images, the u = 0 (yellow) edge has a TF of 2, the V = 0 (green) edge has a TF of 3, the U = 1/W = 0 (pink) edge has a TF of 4, and the V = 1 (quad only, Cyan) edge has a TF of 5-exactly the number of vertices along the corresponding outer edge. as shoshould be obvious from these two images, the basic building block for topology is just a nice way to stitch two subdivided edges with different number of vertices to each other. the details of this are somewhat tricky, but not special interesting, so I won't go into it.
As for the inside TFS, quads are fairly easy: the quad above has an inside TF of 3 along u and 4 along v. the geometry is basically that of a regular grid of that size, should T with the first and last rows/columns replaced by the respective stitching triangles (if any edge has a TF of 1, the resulting mesh will have the same structure as if the inside TFs for u/V were both 2, even if they're smaller Than That ). triangles are a bit more complicated. odd TFs we 've already seen-for a TF of, they produce a mesh consisting of concentric rings, the innermost of which is a single triangle. for even TFS, we get concentric rings with a center vertex instead of a center triangle. below is an image of the simplest even case, which consists just of edge stitches plus the center vertex. finally, whe N triangulating quads, the diagonal is generally chosen to point away from the center of the patch (in the domain coordinate space), with a consistent tie-breaking rule. this is simply to ensure maximum rotational algorithms of the resulting meshes-if there's extra degrees of freedom, might as well use them!
Fractional tessellation factors and overall pipeline flowSo far, I 've only talked about integer TFs. in two of the so-called "partitioning types", namely "integer" and "pow2", that's all the tessellator sees. if the shader generates a non-INTEGER (or, respectively, non-power-of-2) TF, it will simply get rounded up to the next acceptable value. more interesting are the remaining two partitioning types: fractional-odd and Fractional-even tessellation. instead of jumping from tessellation factor to tessellation factor (which wocould cause visible pops ), new vertices start out at the same position as an existing vertex in the mesh and then gradually move to their new positions as the TF increases.
For example, with Fractional-odd tessellation, if you were to use an inner TF of 3.001 for the above triangle, the resulting mesh wocould look very much like the mesh for a TF of 3-But topologically, it 'd be the same as if the TF was 5, I. e. it's a patch with 3 concentric rings, even though the middle ring is very narrow. then as the TF gets closer to 5, the middle ring expands until it is eventually at its final position for TF 5. once you raise the TF past 5, the mesh will be topologically the same as is the TF was 7, but again with a number of almost-degenerate triangles in the middle, and so forth. fractional-even tessellation uses the same principle, just with even TFs.
The output of the tessellator then consists of two things: first, the positions of the tessellated vertices in domain coordinates, and second, the corresponding connectivity information-basically an index buffer.
Now, with the basic function of the fixed-function tessellator Unit explained, let's step back and see what we need to do to actually church n out primitives: first, we need to input a bunch of input control points comprising a patch into the hull shader. the HS then computes output control points and "patch constants" (both of which get passed down to the domain shader), plus all tessellation factors (which are essential just more patch constants ). then we run the fixed-function tessellator, which gives us a bunch of domain positions to run the domain shader at, plus the associated indices. after we 've run the DS, we then do another round of primitive assembly, and then send the primitives either down to the GS pipeline (if it's active) or viewport transform, clip and cull (if not ). so let's look a bit into the HS stage.
Hull shader executionLike geometry shaders, hull shaders work on full (patch) primitives as input-with all the input buffering headaches that causes. how much of a headache entirely depends on the type of input patch. if the patch type is something like a cubic bézr patch, we need 4 × 4 = 16 Input Points
Per patchAnd might just produce a single quad of output (or even none at all, if the patch is culled); clearly, that's a somewhat awkward amount of data to work, and doesn't lend itself to very efficient shading. on the other hand, if tessellation takes plain triangles as input (which a lot of people do), input buffering is pretty tame and not likely to be a source of problems or bottlenecks.
More importantly, unlike geometry shaders (which run for every primitive), hull shaders don't run all that often-they run once
Per patch, And as long as there's any actual tessellation going on (even at modest TFs), we have way less patches than we have output triangles. in other words, even when HS input is somewhat inefficient, it's less of an issue than in the GS case simply because we don't hit that often.
The other nice attribute of hull shaders is that, unlike geometry shaders, they don't have a variable amount of output data; they produce a fixed amount of control points, each which a fixed amount of associated attributes, plus a fixed amount of patch constants. all of this is statically known at compile time; no dynamic run-time buffer management necessary. if we hull shade 16 hulls at a time, we know exactly where the data for each hull will end up before we even start executing the shader. that's definitely an advantage over geometry shaders; for lots of geometry shaders, it's possible to know statically how many output vertices will be generated (for example because all the control flow leading to emit/cut instructions can be statically evaluated at compile time ), and for all of them, there's a guaranteed maximum number of output vertices, but for HS, we have a guaranteed fixed amount of output data, no additional analysis required. in short, there's no problems with output buffer management, other than the fact that, again depending on the primitive type, we might need lots of output buffer space which limits the amount of parallelism we can achieve (due to memory/register constraints ).
Finally, hull shaders are somewhat special in the way they are compiled in d3d11; all other Shader types basically consist of one block of code (with some subroutines maybe ), but hull shaders are generated factored into multiple phases, each of which can consist of multiple (independent) threads of execution. the details are mainly of interest to driver and shader compiler programmers, but suffice it to say that your average HS comes packaged in a form that exposes lots of latent parallelism, if there is any. it certainly seems like Microsoft was really keen to avoid the bottlenecks that plague ry shaders this time around.
Anyway, hull shaders produce a bunch of output per patch; most of it is just kept around until the corresponding domain shaders run, could t for the TFS, which get sent to the tessellator unit. if any of the TFS are less than or equal to zero (or Nan), the patch is culled, and the corresponding control points and patch constants silently get thrown away. otherwise, the tessellator (which implements the functionality described abve) kicks in, reads the just-shaded patches, and starts Ning chilout domain point positions and triangle indices, and we need to get ready for DS execution.
Domain shadersJust like for vertex shading way back, we want to gather multiple domain vertices into one batch that we shade together and then pass on the PA. the fixed-function tessellator can take care of this: "just" handle it along with producing vertex positions and indices (I put the "just" in quotes here because this does involve some amount of bookkeeping ).
In terms of input and output, domain shaders are very simple indeed: the only input they get that actually varies per vertex is the domain Point U and V coordinates (W, when used, doesn't need to be computed or passed in by the tesselator; since, it can be computed ). everything else is either patch constants, control points (all of which are the same authentication ss a patch) or constant buffers. and output is basically the same as for vertex shaders.
In short, once we get to the DS, life is good; the data flow is almost as simple as for vs, which is a path we know how to run efficiently. this is perhaps the biggest advantage of the d3d11 tessellation pipeline over geometry shaders: the actual triangle amplification doesn't happen in a shader, where we waste precious ALU cycles and need to keep buffer space for a worst-case estimate of vertices, But in a localized element (the tessellator) that is basically a state machine, gets very little input (a few TFs) and produces very compact output (effectively an index buffer, plus a 2D coordinate per output vertex ). because of this, we need way less memory for buffering, and can keep our shader units busy with actual shading work instead of housekeeping. and that's it for this post-Next up: c Ompute shaders, aka the final part in my original outline for this series! Until then.
Final remarksAs usual, I cut a few corners. there's the "isoline" patch type, which I didn't go into at all (if there's any demand for this, I can write it up ). the tessellator has all kinds of algorithms ry and precision requirements; as far as vertex domain positions are concerned, you can basically perform CT bit-Exact results between the different HW vendors, because the d3d11 spec really nails this bit down. what's intentionally not nailed down is the order in which vertices or triangles are produced-an implementation can do what it wants there, provided it does so consistently (I. e. the same input has to produce the same output, always ). there's a bunch of subtle constraints that go into this too-for example, all domain positions written by the tessellator need to have both U and 1-u (and also V and 1-V) exactly representable as float; there's a bunch of necessary conditions like this so that domain shaders can then produce watertight meshes (this rule in particle is important so that a shared edge AB between two patches, which is AB to one patch and Ba to the other, can get tessellated the same way for both patches ).
Writing domain shaders so they actually can't produce cracks is tricky and requires great care; I intentionally sidestep the topic because it's outside the scope of this series. another much more trivial issue that I didn't mention is the winding order of triangles generated by the tessellator (answer: It's up to the app-both clockwise and counterclockwise are supported ).
The description of input/output buffering for hull and domain shaders is somewhat terse, but it's very similar to stages we 've ve already seen, so I 'd rather keep it short and avoid extra clutter; re-read the posts on vertex shaders and geometry shaders if this was too fast.
Finally, because the tesselation pipeline can feed into the GS, there's the question of whether it can generate adjacency information. for the "Inside" of patches this wocould be conceivable (just more indices for the tessellator unit to write), but it gets uugly fast once you reach patch edges, since cross-patch adjacency needs exactly the kind of global "mesh Awareness" that the tessellation pipeline design tries so hard to avoid. so, long story short, no, the tessellator will not produce adjacency information for the GS, just plain triangles.