1 /* 2 * Copyright 2017 Google Inc. 3 * 4 * Use of this source code is governed by a BSD-style license that can be 5 * found in the LICENSE file. 6 */ 7 8 #include "GrCCCoverageProcessor.h" 9 10 #include "GrMesh.h" 11 #include "glsl/GrGLSLVertexGeoBuilder.h" 12 13 using InputType = GrGLSLGeometryBuilder::InputType; 14 using OutputType = GrGLSLGeometryBuilder::OutputType; 15 16 /** 17 * This class and its subclasses implement the coverage processor with geometry shaders. 18 */ 19 class GrCCCoverageProcessor::GSImpl : public GrGLSLGeometryProcessor { 20 protected: 21 GSImpl(std::unique_ptr<Shader> shader) : fShader(std::move(shader)) {} 22 23 virtual bool hasCoverage() const { return false; } 24 25 void setData(const GrGLSLProgramDataManager& pdman, const GrPrimitiveProcessor&, 26 FPCoordTransformIter&& transformIter) final { 27 this->setTransformDataHelper(SkMatrix::I(), pdman, &transformIter); 28 } 29 30 void onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) final { 31 const GrCCCoverageProcessor& proc = args.fGP.cast<GrCCCoverageProcessor>(); 32 33 // The vertex shader simply forwards transposed x or y values to the geometry shader. 34 SkASSERT(1 == proc.numVertexAttributes()); 35 gpArgs->fPositionVar = proc.fVertexAttribute.asShaderVar(); 36 37 // Geometry shader. 38 GrGLSLVaryingHandler* varyingHandler = args.fVaryingHandler; 39 this->emitGeometryShader(proc, varyingHandler, args.fGeomBuilder, args.fRTAdjustName); 40 varyingHandler->emitAttributes(proc); 41 varyingHandler->setNoPerspective(); 42 SkASSERT(!args.fFPCoordTransformHandler->nextCoordTransform()); 43 44 // Fragment shader. 45 fShader->emitFragmentCode(proc, args.fFragBuilder, args.fOutputColor, args.fOutputCoverage); 46 } 47 48 void emitGeometryShader(const GrCCCoverageProcessor& proc, 49 GrGLSLVaryingHandler* varyingHandler, GrGLSLGeometryBuilder* g, 50 const char* rtAdjust) const { 51 int numInputPoints = proc.numInputPoints(); 52 SkASSERT(3 == numInputPoints || 4 == numInputPoints); 53 54 int inputWidth = (4 == numInputPoints || proc.hasInputWeight()) ? 4 : 3; 55 const char* posValues = (4 == inputWidth) ? "sk_Position" : "sk_Position.xyz"; 56 g->codeAppendf("float%ix2 pts = transpose(float2x%i(sk_in[0].%s, sk_in[1].%s));", 57 inputWidth, inputWidth, posValues, posValues); 58 59 GrShaderVar wind("wind", kHalf_GrSLType); 60 g->declareGlobal(wind); 61 Shader::CalcWind(proc, g, "pts", wind.c_str()); 62 if (PrimitiveType::kWeightedTriangles == proc.fPrimitiveType) { 63 SkASSERT(3 == numInputPoints); 64 SkASSERT(kFloat4_GrVertexAttribType == proc.fVertexAttribute.cpuType()); 65 g->codeAppendf("%s *= sk_in[0].sk_Position.w;", wind.c_str()); 66 } 67 68 SkString emitVertexFn; 69 SkSTArray<2, GrShaderVar> emitArgs; 70 const char* corner = emitArgs.emplace_back("corner", kFloat2_GrSLType).c_str(); 71 const char* bloatdir = emitArgs.emplace_back("bloatdir", kFloat2_GrSLType).c_str(); 72 const char* coverage = nullptr; 73 if (this->hasCoverage()) { 74 coverage = emitArgs.emplace_back("coverage", kHalf_GrSLType).c_str(); 75 } 76 const char* cornerCoverage = nullptr; 77 if (GSSubpass::kCorners == proc.fGSSubpass) { 78 cornerCoverage = emitArgs.emplace_back("corner_coverage", kHalf2_GrSLType).c_str(); 79 } 80 g->emitFunction(kVoid_GrSLType, "emitVertex", emitArgs.count(), emitArgs.begin(), [&]() { 81 SkString fnBody; 82 if (coverage) { 83 fnBody.appendf("%s *= %s;", coverage, wind.c_str()); 84 } 85 if (cornerCoverage) { 86 fnBody.appendf("%s.x *= %s;", cornerCoverage, wind.c_str()); 87 } 88 fnBody.appendf("float2 vertexpos = fma(%s, float2(bloat), %s);", bloatdir, corner); 89 fShader->emitVaryings(varyingHandler, GrGLSLVarying::Scope::kGeoToFrag, &fnBody, 90 "vertexpos", coverage ? coverage : wind.c_str(), cornerCoverage); 91 g->emitVertex(&fnBody, "vertexpos", rtAdjust); 92 return fnBody; 93 }().c_str(), &emitVertexFn); 94 95 float bloat = kAABloatRadius; 96 #ifdef SK_DEBUG 97 if (proc.debugBloatEnabled()) { 98 bloat *= proc.debugBloat(); 99 } 100 #endif 101 g->defineConstant("bloat", bloat); 102 103 this->onEmitGeometryShader(proc, g, wind, emitVertexFn.c_str()); 104 } 105 106 virtual void onEmitGeometryShader(const GrCCCoverageProcessor&, GrGLSLGeometryBuilder*, 107 const GrShaderVar& wind, const char* emitVertexFn) const = 0; 108 109 virtual ~GSImpl() {} 110 111 const std::unique_ptr<Shader> fShader; 112 113 typedef GrGLSLGeometryProcessor INHERITED; 114 }; 115 116 /** 117 * Generates conservative rasters around a triangle and its edges, and calculates coverage ramps. 118 * 119 * Triangle rough outlines are drawn in two steps: (1) draw a conservative raster of the entire 120 * triangle, with a coverage of +1, and (2) draw conservative rasters around each edge, with a 121 * coverage ramp from -1 to 0. These edge coverage values convert jagged conservative raster edges 122 * into smooth, antialiased ones. 123 * 124 * The final corners get touched up in a later step by GSTriangleCornerImpl. 125 */ 126 class GrCCCoverageProcessor::GSTriangleHullImpl : public GrCCCoverageProcessor::GSImpl { 127 public: 128 GSTriangleHullImpl(std::unique_ptr<Shader> shader) : GSImpl(std::move(shader)) {} 129 130 bool hasCoverage() const override { return true; } 131 132 void onEmitGeometryShader(const GrCCCoverageProcessor&, GrGLSLGeometryBuilder* g, 133 const GrShaderVar& wind, const char* emitVertexFn) const override { 134 fShader->emitSetupCode(g, "pts", wind.c_str()); 135 136 // Visualize the input triangle as upright and equilateral, with a flat base. Paying special 137 // attention to wind, we can identify the points as top, bottom-left, and bottom-right. 138 // 139 // NOTE: We generate the rasters in 5 independent invocations, so each invocation designates 140 // the corner it will begin with as the top. 141 g->codeAppendf("int i = (%s > 0 ? sk_InvocationID : 4 - sk_InvocationID) %% 3;", 142 wind.c_str()); 143 g->codeAppend ("float2 top = pts[i];"); 144 g->codeAppendf("float2 right = pts[(i + (%s > 0 ? 1 : 2)) %% 3];", wind.c_str()); 145 g->codeAppendf("float2 left = pts[(i + (%s > 0 ? 2 : 1)) %% 3];", wind.c_str()); 146 147 // Determine which direction to outset the conservative raster from each of the three edges. 148 g->codeAppend ("float2 leftbloat = sign(top - left);"); 149 g->codeAppend ("leftbloat = float2(0 != leftbloat.y ? leftbloat.y : leftbloat.x, " 150 "0 != leftbloat.x ? -leftbloat.x : -leftbloat.y);"); 151 152 g->codeAppend ("float2 rightbloat = sign(right - top);"); 153 g->codeAppend ("rightbloat = float2(0 != rightbloat.y ? rightbloat.y : rightbloat.x, " 154 "0 != rightbloat.x ? -rightbloat.x : -rightbloat.y);"); 155 156 g->codeAppend ("float2 downbloat = sign(left - right);"); 157 g->codeAppend ("downbloat = float2(0 != downbloat.y ? downbloat.y : downbloat.x, " 158 "0 != downbloat.x ? -downbloat.x : -downbloat.y);"); 159 160 // The triangle's conservative raster has a coverage of +1 all around. 161 g->codeAppend ("half4 coverages = half4(+1);"); 162 163 // Edges have coverage ramps. 164 g->codeAppend ("if (sk_InvocationID >= 2) {"); // Are we an edge? 165 Shader::CalcEdgeCoverageAtBloatVertex(g, "top", "right", 166 "float2(+rightbloat.y, -rightbloat.x)", 167 "coverages[0]"); 168 g->codeAppend ( "coverages.yzw = half3(-1, 0, -1 - coverages[0]);"); 169 // Reassign bloats to characterize a conservative raster around a single edge, rather than 170 // the entire triangle. 171 g->codeAppend ( "leftbloat = downbloat = -rightbloat;"); 172 g->codeAppend ("}"); 173 174 // Here we generate the conservative raster geometry. The triangle's conservative raster is 175 // the convex hull of 3 pixel-size boxes centered on the input points. This translates to a 176 // convex polygon with either one, two, or three vertices at each input point (depending on 177 // how sharp the corner is) that we split between two invocations. Edge conservative rasters 178 // are convex hulls of 2 pixel-size boxes, one at each endpoint. For more details on 179 // conservative raster, see: 180 // https://developer.nvidia.com/gpugems/GPUGems2/gpugems2_chapter42.html 181 g->codeAppendf("bool2 left_right_notequal = notEqual(leftbloat, rightbloat);"); 182 g->codeAppend ("if (all(left_right_notequal)) {"); 183 // The top corner will have three conservative raster vertices. Emit the 184 // middle one first to the triangle strip. 185 g->codeAppendf( "%s(top, float2(-leftbloat.y, +leftbloat.x), coverages[0]);", 186 emitVertexFn); 187 g->codeAppend ("}"); 188 g->codeAppend ("if (any(left_right_notequal)) {"); 189 // Second conservative raster vertex for the top corner. 190 g->codeAppendf( "%s(top, rightbloat, coverages[1]);", emitVertexFn); 191 g->codeAppend ("}"); 192 193 // Main interior body. 194 g->codeAppendf("%s(top, leftbloat, coverages[2]);", emitVertexFn); 195 g->codeAppendf("%s(right, rightbloat, coverages[1]);", emitVertexFn); 196 197 // Here the invocations diverge slightly. We can't symmetrically divide three triangle 198 // points between two invocations, so each does the following: 199 // 200 // sk_InvocationID=0: Finishes the main interior body of the triangle hull. 201 // sk_InvocationID=1: Remaining two conservative raster vertices for the third hull corner. 202 // sk_InvocationID=2..4: Finish the opposite endpoint of their corresponding edge. 203 g->codeAppendf("bool2 right_down_notequal = notEqual(rightbloat, downbloat);"); 204 g->codeAppend ("if (any(right_down_notequal) || 0 == sk_InvocationID) {"); 205 g->codeAppendf( "%s((0 == sk_InvocationID) ? left : right, " 206 "(0 == sk_InvocationID) ? leftbloat : downbloat, " 207 "coverages[2]);", emitVertexFn); 208 g->codeAppend ("}"); 209 g->codeAppend ("if (all(right_down_notequal) && 0 != sk_InvocationID) {"); 210 g->codeAppendf( "%s(right, float2(-rightbloat.y, +rightbloat.x), coverages[3]);", 211 emitVertexFn); 212 g->codeAppend ("}"); 213 214 // 5 invocations: 2 triangle hull invocations and 3 edges. 215 g->configure(InputType::kLines, OutputType::kTriangleStrip, 6, 5); 216 } 217 }; 218 219 /** 220 * Generates a conservative raster around a convex quadrilateral that encloses a cubic or quadratic. 221 */ 222 class GrCCCoverageProcessor::GSCurveHullImpl : public GrCCCoverageProcessor::GSImpl { 223 public: 224 GSCurveHullImpl(std::unique_ptr<Shader> shader) : GSImpl(std::move(shader)) {} 225 226 void onEmitGeometryShader(const GrCCCoverageProcessor&, GrGLSLGeometryBuilder* g, 227 const GrShaderVar& wind, const char* emitVertexFn) const override { 228 const char* hullPts = "pts"; 229 fShader->emitSetupCode(g, "pts", wind.c_str(), &hullPts); 230 231 // Visualize the input (convex) quadrilateral as a square. Paying special attention to wind, 232 // we can identify the points by their corresponding corner. 233 // 234 // NOTE: We split the square down the diagonal from top-right to bottom-left, and generate 235 // the hull in two independent invocations. Each invocation designates the corner it will 236 // begin with as top-left. 237 g->codeAppend ("int i = sk_InvocationID * 2;"); 238 g->codeAppendf("float2 topleft = %s[i];", hullPts); 239 g->codeAppendf("float2 topright = %s[%s > 0 ? i + 1 : 3 - i];", hullPts, wind.c_str()); 240 g->codeAppendf("float2 bottomleft = %s[%s > 0 ? 3 - i : i + 1];", hullPts, wind.c_str()); 241 g->codeAppendf("float2 bottomright = %s[2 - i];", hullPts); 242 243 // Determine how much to outset the conservative raster hull from the relevant edges. 244 g->codeAppend ("float2 leftbloat = float2(topleft.y > bottomleft.y ? +1 : -1, " 245 "topleft.x > bottomleft.x ? -1 : +1);"); 246 g->codeAppend ("float2 upbloat = float2(topright.y > topleft.y ? +1 : -1, " 247 "topright.x > topleft.x ? -1 : +1);"); 248 g->codeAppend ("float2 rightbloat = float2(bottomright.y > topright.y ? +1 : -1, " 249 "bottomright.x > topright.x ? -1 : +1);"); 250 251 // Here we generate the conservative raster geometry. It is the convex hull of 4 pixel-size 252 // boxes centered on the input points, split evenly between two invocations. This translates 253 // to a polygon with either one, two, or three vertices at each input point, depending on 254 // how sharp the corner is. For more details on conservative raster, see: 255 // https://developer.nvidia.com/gpugems/GPUGems2/gpugems2_chapter42.html 256 g->codeAppendf("bool2 left_up_notequal = notEqual(leftbloat, upbloat);"); 257 g->codeAppend ("if (all(left_up_notequal)) {"); 258 // The top-left corner will have three conservative raster vertices. 259 // Emit the middle one first to the triangle strip. 260 g->codeAppendf( "%s(topleft, float2(-leftbloat.y, leftbloat.x));", emitVertexFn); 261 g->codeAppend ("}"); 262 g->codeAppend ("if (any(left_up_notequal)) {"); 263 // Second conservative raster vertex for the top-left corner. 264 g->codeAppendf( "%s(topleft, leftbloat);", emitVertexFn); 265 g->codeAppend ("}"); 266 267 // Main interior body of this invocation's half of the hull. 268 g->codeAppendf("%s(topleft, upbloat);", emitVertexFn); 269 g->codeAppendf("%s(bottomleft, leftbloat);", emitVertexFn); 270 g->codeAppendf("%s(topright, upbloat);", emitVertexFn); 271 272 // Remaining two conservative raster vertices for the top-right corner. 273 g->codeAppendf("bool2 up_right_notequal = notEqual(upbloat, rightbloat);"); 274 g->codeAppend ("if (any(up_right_notequal)) {"); 275 g->codeAppendf( "%s(topright, rightbloat);", emitVertexFn); 276 g->codeAppend ("}"); 277 g->codeAppend ("if (all(up_right_notequal)) {"); 278 g->codeAppendf( "%s(topright, float2(-upbloat.y, upbloat.x));", emitVertexFn); 279 g->codeAppend ("}"); 280 281 g->configure(InputType::kLines, OutputType::kTriangleStrip, 7, 2); 282 } 283 }; 284 285 /** 286 * Generates conservative rasters around corners (aka pixel-size boxes) and calculates 287 * coverage and attenuation ramps to fix up the coverage values written by the hulls. 288 */ 289 class GrCCCoverageProcessor::GSCornerImpl : public GrCCCoverageProcessor::GSImpl { 290 public: 291 GSCornerImpl(std::unique_ptr<Shader> shader) : GSImpl(std::move(shader)) {} 292 293 bool hasCoverage() const override { return true; } 294 295 void onEmitGeometryShader(const GrCCCoverageProcessor& proc, GrGLSLGeometryBuilder* g, 296 const GrShaderVar& wind, const char* emitVertexFn) const override { 297 fShader->emitSetupCode(g, "pts", wind.c_str()); 298 299 g->codeAppendf("int corneridx = sk_InvocationID;"); 300 if (!proc.isTriangles()) { 301 g->codeAppendf("corneridx *= %i;", proc.numInputPoints() - 1); 302 } 303 304 g->codeAppendf("float2 corner = pts[corneridx];"); 305 g->codeAppendf("float2 left = pts[(corneridx + (%s > 0 ? %i : 1)) %% %i];", 306 wind.c_str(), proc.numInputPoints() - 1, proc.numInputPoints()); 307 g->codeAppendf("float2 right = pts[(corneridx + (%s > 0 ? 1 : %i)) %% %i];", 308 wind.c_str(), proc.numInputPoints() - 1, proc.numInputPoints()); 309 310 g->codeAppend ("float2 leftdir = corner - left;"); 311 g->codeAppend ("leftdir = (float2(0) != leftdir) ? normalize(leftdir) : float2(1, 0);"); 312 313 g->codeAppend ("float2 rightdir = right - corner;"); 314 g->codeAppend ("rightdir = (float2(0) != rightdir) ? normalize(rightdir) : float2(1, 0);"); 315 316 // Find "outbloat" and "crossbloat" at our corner. The outbloat points diagonally out of the 317 // triangle, in the direction that should ramp to zero coverage with attenuation. The 318 // crossbloat runs perpindicular to outbloat. 319 g->codeAppend ("float2 outbloat = float2(leftdir.x > rightdir.x ? +1 : -1, " 320 "leftdir.y > rightdir.y ? +1 : -1);"); 321 g->codeAppend ("float2 crossbloat = float2(-outbloat.y, +outbloat.x);"); 322 323 g->codeAppend ("half attenuation; {"); 324 Shader::CalcCornerAttenuation(g, "leftdir", "rightdir", "attenuation"); 325 g->codeAppend ("}"); 326 327 if (proc.isTriangles()) { 328 g->codeAppend ("half2 left_coverages; {"); 329 Shader::CalcEdgeCoveragesAtBloatVertices(g, "left", "corner", "-outbloat", 330 "-crossbloat", "left_coverages"); 331 g->codeAppend ("}"); 332 333 g->codeAppend ("half2 right_coverages; {"); 334 Shader::CalcEdgeCoveragesAtBloatVertices(g, "corner", "right", "-outbloat", 335 "crossbloat", "right_coverages"); 336 g->codeAppend ("}"); 337 338 // Emit a corner box. The first coverage argument erases the values that were written 339 // previously by the hull and edge geometry. The second pair are multiplied together by 340 // the fragment shader. They ramp to 0 with attenuation in the direction of outbloat, 341 // and linearly from left-edge coverage to right-edge coverage in the direction of 342 // crossbloat. 343 // 344 // NOTE: Since this is not a linear mapping, it is important that the box's diagonal 345 // shared edge points in the direction of outbloat. 346 g->codeAppendf("%s(corner, -crossbloat, right_coverages[1] - left_coverages[1]," 347 "half2(1 + left_coverages[1], 1));", 348 emitVertexFn); 349 350 g->codeAppendf("%s(corner, outbloat, 1 + left_coverages[0] + right_coverages[0], " 351 "half2(0, attenuation));", 352 emitVertexFn); 353 354 g->codeAppendf("%s(corner, -outbloat, -1 - left_coverages[0] - right_coverages[0], " 355 "half2(1 + left_coverages[0] + right_coverages[0], 1));", 356 emitVertexFn); 357 358 g->codeAppendf("%s(corner, crossbloat, left_coverages[1] - right_coverages[1]," 359 "half2(1 + right_coverages[1], 1));", 360 emitVertexFn); 361 } else { 362 // Curves are simpler. The first coverage value of -1 means "wind = -wind", and causes 363 // the Shader to erase what it had written previously for the hull. Then, at each vertex 364 // of the corner box, the Shader will calculate the curve's local coverage value, 365 // interpolate it alongside our attenuation parameter, and multiply the two together for 366 // a final coverage value. 367 g->codeAppendf("%s(corner, -crossbloat, -1, half2(1));", emitVertexFn); 368 g->codeAppendf("%s(corner, outbloat, -1, half2(0, attenuation));", 369 emitVertexFn); 370 g->codeAppendf("%s(corner, -outbloat, -1, half2(1));", emitVertexFn); 371 g->codeAppendf("%s(corner, crossbloat, -1, half2(1));", emitVertexFn); 372 } 373 374 g->configure(InputType::kLines, OutputType::kTriangleStrip, 4, proc.isTriangles() ? 3 : 2); 375 } 376 }; 377 378 void GrCCCoverageProcessor::initGS() { 379 SkASSERT(Impl::kGeometryShader == fImpl); 380 if (4 == this->numInputPoints() || this->hasInputWeight()) { 381 fVertexAttribute = 382 {"x_or_y_values", kFloat4_GrVertexAttribType, kFloat4_GrSLType}; 383 GR_STATIC_ASSERT(sizeof(QuadPointInstance) == 384 2 * GrVertexAttribTypeSize(kFloat4_GrVertexAttribType)); 385 GR_STATIC_ASSERT(offsetof(QuadPointInstance, fY) == 386 GrVertexAttribTypeSize(kFloat4_GrVertexAttribType)); 387 } else { 388 fVertexAttribute = 389 {"x_or_y_values", kFloat3_GrVertexAttribType, kFloat3_GrSLType}; 390 GR_STATIC_ASSERT(sizeof(TriPointInstance) == 391 2 * GrVertexAttribTypeSize(kFloat3_GrVertexAttribType)); 392 GR_STATIC_ASSERT(offsetof(TriPointInstance, fY) == 393 GrVertexAttribTypeSize(kFloat3_GrVertexAttribType)); 394 } 395 this->setVertexAttributes(&fVertexAttribute, 1); 396 this->setWillUseGeoShader(); 397 } 398 399 void GrCCCoverageProcessor::appendGSMesh(sk_sp<const GrBuffer> instanceBuffer, int instanceCount, 400 int baseInstance, SkTArray<GrMesh>* out) const { 401 // GSImpl doesn't actually make instanced draw calls. Instead, we feed transposed x,y point 402 // values to the GPU in a regular vertex array and draw kLines (see initGS). Then, each vertex 403 // invocation receives either the shape's x or y values as inputs, which it forwards to the 404 // geometry shader. 405 SkASSERT(Impl::kGeometryShader == fImpl); 406 GrMesh& mesh = out->emplace_back(GrPrimitiveType::kLines); 407 mesh.setNonIndexedNonInstanced(instanceCount * 2); 408 mesh.setVertexData(std::move(instanceBuffer), baseInstance * 2); 409 } 410 411 GrGLSLPrimitiveProcessor* GrCCCoverageProcessor::createGSImpl(std::unique_ptr<Shader> shadr) const { 412 if (GSSubpass::kHulls == fGSSubpass) { 413 return this->isTriangles() 414 ? (GSImpl*) new GSTriangleHullImpl(std::move(shadr)) 415 : (GSImpl*) new GSCurveHullImpl(std::move(shadr)); 416 } 417 SkASSERT(GSSubpass::kCorners == fGSSubpass); 418 return new GSCornerImpl(std::move(shadr)); 419 } 420