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 "GrGpuCommandBuffer.h"
11 #include "GrOpFlushState.h"
12 #include "SkMakeUnique.h"
13 #include "ccpr/GrCCConicShader.h"
14 #include "ccpr/GrCCCubicShader.h"
15 #include "ccpr/GrCCQuadraticShader.h"
16 #include "glsl/GrGLSLVertexGeoBuilder.h"
17 #include "glsl/GrGLSLFragmentShaderBuilder.h"
18 #include "glsl/GrGLSLVertexGeoBuilder.h"
19 
20 class GrCCCoverageProcessor::TriangleShader : public GrCCCoverageProcessor::Shader {
onEmitVaryings(GrGLSLVaryingHandler * varyingHandler,GrGLSLVarying::Scope scope,SkString * code,const char * position,const char * coverage,const char * cornerCoverage)21     void onEmitVaryings(GrGLSLVaryingHandler* varyingHandler, GrGLSLVarying::Scope scope,
22                         SkString* code, const char* position, const char* coverage,
23                         const char* cornerCoverage) override {
24         if (!cornerCoverage) {
25             fCoverages.reset(kHalf_GrSLType, scope);
26             varyingHandler->addVarying("coverage", &fCoverages);
27             code->appendf("%s = %s;", OutName(fCoverages), coverage);
28         } else {
29             fCoverages.reset(kHalf3_GrSLType, scope);
30             varyingHandler->addVarying("coverages", &fCoverages);
31             code->appendf("%s = half3(%s, %s);", OutName(fCoverages), coverage, cornerCoverage);
32         }
33     }
34 
onEmitFragmentCode(GrGLSLFPFragmentBuilder * f,const char * outputCoverage) const35     void onEmitFragmentCode(GrGLSLFPFragmentBuilder* f, const char* outputCoverage) const override {
36         if (kHalf_GrSLType == fCoverages.type()) {
37             f->codeAppendf("%s = %s;", outputCoverage, fCoverages.fsIn());
38         } else {
39             f->codeAppendf("%s = %s.z * %s.y + %s.x;",
40                            outputCoverage, fCoverages.fsIn(), fCoverages.fsIn(), fCoverages.fsIn());
41         }
42     }
43 
44     GrGLSLVarying fCoverages;
45 };
46 
CalcWind(const GrCCCoverageProcessor & proc,GrGLSLVertexGeoBuilder * s,const char * pts,const char * outputWind)47 void GrCCCoverageProcessor::Shader::CalcWind(const GrCCCoverageProcessor& proc,
48                                              GrGLSLVertexGeoBuilder* s, const char* pts,
49                                              const char* outputWind) {
50     if (3 == proc.numInputPoints()) {
51         s->codeAppendf("float2 a = %s[0] - %s[1], "
52                               "b = %s[0] - %s[2];", pts, pts, pts, pts);
53     } else {
54         // All inputs are convex, so it's sufficient to just average the middle two input points.
55         SkASSERT(4 == proc.numInputPoints());
56         s->codeAppendf("float2 p12 = (%s[1] + %s[2]) * .5;", pts, pts);
57         s->codeAppendf("float2 a = %s[0] - p12, "
58                               "b = %s[0] - %s[3];", pts, pts, pts);
59     }
60 
61     s->codeAppend ("float area_x2 = determinant(float2x2(a, b));");
62     if (proc.isTriangles()) {
63         // We cull extremely thin triangles by zeroing wind. When a triangle gets too thin it's
64         // possible for FP round-off error to actually give us the wrong winding direction, causing
65         // rendering artifacts. The criteria we choose is "height <~ 1/1024". So we drop a triangle
66         // if the max effect it can have on any single pixel is <~ 1/1024, or 1/4 of a bit in 8888.
67         s->codeAppend ("float2 bbox_size = max(abs(a), abs(b));");
68         s->codeAppend ("float basewidth = max(bbox_size.x + bbox_size.y, 1);");
69         s->codeAppendf("%s = (abs(area_x2 * 1024) > basewidth) ? sign(area_x2) : 0;", outputWind);
70     } else {
71         // We already converted nearly-flat curves to lines on the CPU, so no need to worry about
72         // thin curve hulls at this point.
73         s->codeAppendf("%s = sign(area_x2);", outputWind);
74     }
75 }
76 
EmitEdgeDistanceEquation(GrGLSLVertexGeoBuilder * s,const char * leftPt,const char * rightPt,const char * outputDistanceEquation)77 void GrCCCoverageProcessor::Shader::EmitEdgeDistanceEquation(GrGLSLVertexGeoBuilder* s,
78                                                              const char* leftPt,
79                                                              const char* rightPt,
80                                                              const char* outputDistanceEquation) {
81     s->codeAppendf("float2 n = float2(%s.y - %s.y, %s.x - %s.x);",
82                    rightPt, leftPt, leftPt, rightPt);
83     s->codeAppend ("float nwidth = (abs(n.x) + abs(n.y)) * (bloat * 2);");
84     // When nwidth=0, wind must also be 0 (and coverage * wind = 0). So it doesn't matter what we
85     // come up with here as long as it isn't NaN or Inf.
86     s->codeAppend ("n /= (0 != nwidth) ? nwidth : 1;");
87     s->codeAppendf("%s = float3(-n, dot(n, %s) - .5);", outputDistanceEquation, leftPt);
88 }
89 
CalcEdgeCoverageAtBloatVertex(GrGLSLVertexGeoBuilder * s,const char * leftPt,const char * rightPt,const char * rasterVertexDir,const char * outputCoverage)90 void GrCCCoverageProcessor::Shader::CalcEdgeCoverageAtBloatVertex(GrGLSLVertexGeoBuilder* s,
91                                                                   const char* leftPt,
92                                                                   const char* rightPt,
93                                                                   const char* rasterVertexDir,
94                                                                   const char* outputCoverage) {
95     // Here we find an edge's coverage at one corner of a conservative raster bloat box whose center
96     // falls on the edge in question. (A bloat box is axis-aligned and the size of one pixel.) We
97     // always set up coverage so it is -1 at the outermost corner, 0 at the innermost, and -.5 at
98     // the center. Interpolated, these coverage values convert jagged conservative raster edges into
99     // smooth antialiased edges.
100     //
101     // d1 == (P + sign(n) * bloat) dot n                   (Distance at the bloat box vertex whose
102     //    == P dot n + (abs(n.x) + abs(n.y)) * bloatSize    coverage=-1, where the bloat box is
103     //                                                      centered on P.)
104     //
105     // d0 == (P - sign(n) * bloat) dot n                   (Distance at the bloat box vertex whose
106     //    == P dot n - (abs(n.x) + abs(n.y)) * bloatSize    coverage=0, where the bloat box is
107     //                                                      centered on P.)
108     //
109     // d == (P + rasterVertexDir * bloatSize) dot n        (Distance at the bloat box vertex whose
110     //   == P dot n + (rasterVertexDir dot n) * bloatSize   coverage we wish to calculate.)
111     //
112     // coverage == -(d - d0) / (d1 - d0)                   (coverage=-1 at d=d1; coverage=0 at d=d0)
113     //
114     //          == (rasterVertexDir dot n) / (abs(n.x) + abs(n.y)) * -.5 - .5
115     //
116     s->codeAppendf("float2 n = float2(%s.y - %s.y, %s.x - %s.x);",
117                    rightPt, leftPt, leftPt, rightPt);
118     s->codeAppend ("float nwidth = abs(n.x) + abs(n.y);");
119     s->codeAppendf("float t = dot(%s, n);", rasterVertexDir);
120     // The below conditional guarantees we get exactly 1 on the divide when nwidth=t (in case the
121     // GPU divides by multiplying by the reciprocal?) It also guards against NaN when nwidth=0.
122     s->codeAppendf("%s = (abs(t) != nwidth ? t / nwidth : sign(t)) * -.5 - .5;", outputCoverage);
123 }
124 
CalcEdgeCoveragesAtBloatVertices(GrGLSLVertexGeoBuilder * s,const char * leftPt,const char * rightPt,const char * bloatDir1,const char * bloatDir2,const char * outputCoverages)125 void GrCCCoverageProcessor::Shader::CalcEdgeCoveragesAtBloatVertices(GrGLSLVertexGeoBuilder* s,
126                                                                      const char* leftPt,
127                                                                      const char* rightPt,
128                                                                      const char* bloatDir1,
129                                                                      const char* bloatDir2,
130                                                                      const char* outputCoverages) {
131     // See comments in CalcEdgeCoverageAtBloatVertex.
132     s->codeAppendf("float2 n = float2(%s.y - %s.y, %s.x - %s.x);",
133                    rightPt, leftPt, leftPt, rightPt);
134     s->codeAppend ("float nwidth = abs(n.x) + abs(n.y);");
135     s->codeAppendf("float2 t = n * float2x2(%s, %s);", bloatDir1, bloatDir2);
136     s->codeAppendf("for (int i = 0; i < 2; ++i) {");
137     s->codeAppendf(    "%s[i] = (abs(t[i]) != nwidth ? t[i] / nwidth : sign(t[i])) * -.5 - .5;",
138                        outputCoverages);
139     s->codeAppendf("}");
140 }
141 
CalcCornerAttenuation(GrGLSLVertexGeoBuilder * s,const char * leftDir,const char * rightDir,const char * outputAttenuation)142 void GrCCCoverageProcessor::Shader::CalcCornerAttenuation(GrGLSLVertexGeoBuilder* s,
143                                                           const char* leftDir, const char* rightDir,
144                                                           const char* outputAttenuation) {
145     // obtuseness = cos(corner_angle)  if corner_angle > 90 degrees
146     //                              0  if corner_angle <= 90 degrees
147     //
148     // NOTE: leftDir and rightDir are normalized and point in the same direction the path was
149     // defined with, i.e., leftDir points into the corner and rightDir points away from the corner.
150     s->codeAppendf("half obtuseness = max(dot(%s, %s), 0);", leftDir, rightDir);
151 
152     // axis_alignedness = 1 - tan(angle_to_nearest_axis_from_corner_bisector)
153     //                    (i.e.,  1  when the corner bisector is aligned with the x- or y-axis
154     //                            0  when the corner bisector falls on a 45 degree angle
155     //                         0..1  when the corner bisector falls somewhere in between
156     s->codeAppendf("half2 abs_bisect_maybe_transpose = abs((0 == obtuseness) ? %s - %s : %s + %s);",
157                    leftDir, rightDir, leftDir, rightDir);
158     s->codeAppend ("half axis_alignedness = "
159                            "1 - min(abs_bisect_maybe_transpose.y, abs_bisect_maybe_transpose.x) / "
160                                "max(abs_bisect_maybe_transpose.x, abs_bisect_maybe_transpose.y);");
161 
162     // ninety_degreesness = sin^2(corner_angle)
163     // sin^2 just because... it's always positive and the results looked better than plain sine... ?
164     s->codeAppendf("half ninety_degreesness = determinant(half2x2(%s, %s));", leftDir, rightDir);
165     s->codeAppend ("ninety_degreesness = ninety_degreesness * ninety_degreesness;");
166 
167     // The below formula is not smart. It was just arrived at by considering the following
168     // observations:
169     //
170     // 1. 90-degree, axis-aligned corners have full attenuation along the bisector.
171     //    (i.e. coverage = 1 - distance_to_corner^2)
172     //    (i.e. outputAttenuation = 0)
173     //
174     // 2. 180-degree corners always have zero attenuation.
175     //    (i.e. coverage = 1 - distance_to_corner)
176     //    (i.e. outputAttenuation = 1)
177     //
178     // 3. 90-degree corners whose bisector falls on a 45 degree angle also do not attenuate.
179     //    (i.e. outputAttenuation = 1)
180     s->codeAppendf("%s = max(obtuseness, axis_alignedness * ninety_degreesness);",
181                    outputAttenuation);
182 }
183 
getGLSLProcessorKey(const GrShaderCaps &,GrProcessorKeyBuilder * b) const184 void GrCCCoverageProcessor::getGLSLProcessorKey(const GrShaderCaps&,
185                                                 GrProcessorKeyBuilder* b) const {
186     int key = (int)fPrimitiveType << 2;
187     if (GSSubpass::kCorners == fGSSubpass) {
188         key |= 2;
189     }
190     if (Impl::kVertexShader == fImpl) {
191         key |= 1;
192     }
193 #ifdef SK_DEBUG
194     uint32_t bloatBits;
195     memcpy(&bloatBits, &fDebugBloat, 4);
196     b->add32(bloatBits);
197 #endif
198     b->add32(key);
199 }
200 
createGLSLInstance(const GrShaderCaps &) const201 GrGLSLPrimitiveProcessor* GrCCCoverageProcessor::createGLSLInstance(const GrShaderCaps&) const {
202     std::unique_ptr<Shader> shader;
203     switch (fPrimitiveType) {
204         case PrimitiveType::kTriangles:
205         case PrimitiveType::kWeightedTriangles:
206             shader = skstd::make_unique<TriangleShader>();
207             break;
208         case PrimitiveType::kQuadratics:
209             shader = skstd::make_unique<GrCCQuadraticShader>();
210             break;
211         case PrimitiveType::kCubics:
212             shader = skstd::make_unique<GrCCCubicShader>();
213             break;
214         case PrimitiveType::kConics:
215             shader = skstd::make_unique<GrCCConicShader>();
216             break;
217     }
218     return Impl::kGeometryShader == fImpl ? this->createGSImpl(std::move(shader))
219                                           : this->createVSImpl(std::move(shader));
220 }
221 
emitFragmentCode(const GrCCCoverageProcessor & proc,GrGLSLFPFragmentBuilder * f,const char * skOutputColor,const char * skOutputCoverage) const222 void GrCCCoverageProcessor::Shader::emitFragmentCode(const GrCCCoverageProcessor& proc,
223                                                      GrGLSLFPFragmentBuilder* f,
224                                                      const char* skOutputColor,
225                                                      const char* skOutputCoverage) const {
226     f->codeAppendf("half coverage = 0;");
227     this->onEmitFragmentCode(f, "coverage");
228     f->codeAppendf("%s.a = coverage;", skOutputColor);
229     f->codeAppendf("%s = half4(1);", skOutputCoverage);
230 }
231 
draw(GrOpFlushState * flushState,const GrPipeline & pipeline,const SkIRect scissorRects[],const GrMesh meshes[],int meshCount,const SkRect & drawBounds) const232 void GrCCCoverageProcessor::draw(GrOpFlushState* flushState, const GrPipeline& pipeline,
233                                  const SkIRect scissorRects[], const GrMesh meshes[], int meshCount,
234                                  const SkRect& drawBounds) const {
235     GrPipeline::DynamicStateArrays dynamicStateArrays;
236     dynamicStateArrays.fScissorRects = scissorRects;
237     GrGpuRTCommandBuffer* cmdBuff = flushState->rtCommandBuffer();
238     cmdBuff->draw(*this, pipeline, nullptr, &dynamicStateArrays, meshes, meshCount, drawBounds);
239 
240     // Geometry shader backend draws primitives in two subpasses.
241     if (Impl::kGeometryShader == fImpl) {
242         SkASSERT(GSSubpass::kHulls == fGSSubpass);
243         GrCCCoverageProcessor cornerProc(*this, GSSubpass::kCorners);
244         cmdBuff->draw(cornerProc, pipeline, nullptr, &dynamicStateArrays, meshes, meshCount,
245                       drawBounds);
246     }
247 }
248