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 #ifndef GrCCCoverageProcessor_DEFINED
9 #define GrCCCoverageProcessor_DEFINED
10 
11 #include "GrCaps.h"
12 #include "GrGeometryProcessor.h"
13 #include "GrPipeline.h"
14 #include "GrShaderCaps.h"
15 #include "SkNx.h"
16 #include "glsl/GrGLSLGeometryProcessor.h"
17 #include "glsl/GrGLSLVarying.h"
18 
19 class GrGLSLFPFragmentBuilder;
20 class GrGLSLVertexGeoBuilder;
21 class GrMesh;
22 class GrOpFlushState;
23 
24 /**
25  * This is the geometry processor for the simple convex primitive shapes (triangles and closed,
26  * convex bezier curves) from which ccpr paths are composed. The output is a single-channel alpha
27  * value, positive for clockwise shapes and negative for counter-clockwise, that indicates coverage.
28  *
29  * The caller is responsible to draw all primitives as produced by GrCCGeometry into a cleared,
30  * floating point, alpha-only render target using SkBlendMode::kPlus. Once all of a path's
31  * primitives have been drawn, the render target contains a composite coverage count that can then
32  * be used to draw the path (see GrCCPathProcessor).
33  *
34  * To draw primitives, use appendMesh() and draw() (defined below).
35  */
36 class GrCCCoverageProcessor : public GrGeometryProcessor {
37 public:
38     enum class PrimitiveType {
39         kTriangles,
40         kWeightedTriangles, // Triangles (from the tessellator) whose winding magnitude > 1.
41         kQuadratics,
42         kCubics,
43         kConics
44     };
45     static const char* PrimitiveTypeName(PrimitiveType);
46 
47     // Defines a single primitive shape with 3 input points (i.e. Triangles and Quadratics).
48     // X,Y point values are transposed.
49     struct TriPointInstance {
50         float fX[3];
51         float fY[3];
52 
53         void set(const SkPoint[3], const Sk2f& trans);
54         void set(const SkPoint&, const SkPoint&, const SkPoint&, const Sk2f& trans);
55         void set(const Sk2f& P0, const Sk2f& P1, const Sk2f& P2, const Sk2f& trans);
56     };
57 
58     // Defines a single primitive shape with 4 input points, or 3 input points plus a "weight"
59     // parameter duplicated in both lanes of the 4th input (i.e. Cubics, Conics, and Triangles with
60     // a weighted winding number). X,Y point values are transposed.
61     struct QuadPointInstance {
62         float fX[4];
63         float fY[4];
64 
65         void set(const SkPoint[4], float dx, float dy);
66         void setW(const SkPoint[3], const Sk2f& trans, float w);
67         void setW(const SkPoint&, const SkPoint&, const SkPoint&, const Sk2f& trans, float w);
68         void setW(const Sk2f& P0, const Sk2f& P1, const Sk2f& P2, const Sk2f& trans, float w);
69     };
70 
GrCCCoverageProcessor(GrResourceProvider * rp,PrimitiveType type)71     GrCCCoverageProcessor(GrResourceProvider* rp, PrimitiveType type)
72             : INHERITED(kGrCCCoverageProcessor_ClassID)
73             , fPrimitiveType(type)
74             , fImpl(rp->caps()->shaderCaps()->geometryShaderSupport() ? Impl::kGeometryShader
75                                                                       : Impl::kVertexShader) {
76         if (Impl::kGeometryShader == fImpl) {
77             this->initGS();
78         } else {
79             this->initVS(rp);
80         }
81     }
82 
83     // GrPrimitiveProcessor overrides.
name()84     const char* name() const override { return PrimitiveTypeName(fPrimitiveType); }
85 #ifdef SK_DEBUG
dumpInfo()86     SkString dumpInfo() const override {
87         return SkStringPrintf("%s\n%s", this->name(), this->INHERITED::dumpInfo().c_str());
88     }
89 #endif
90     void getGLSLProcessorKey(const GrShaderCaps&, GrProcessorKeyBuilder*) const override;
91     GrGLSLPrimitiveProcessor* createGLSLInstance(const GrShaderCaps&) const override;
92 
93 #ifdef SK_DEBUG
94     // Increases the 1/2 pixel AA bloat by a factor of debugBloat.
enableDebugBloat(float debugBloat)95     void enableDebugBloat(float debugBloat) { fDebugBloat = debugBloat; }
debugBloatEnabled()96     bool debugBloatEnabled() const { return fDebugBloat > 0; }
debugBloat()97     float debugBloat() const { SkASSERT(this->debugBloatEnabled()); return fDebugBloat; }
98 #endif
99 
100     // Appends a GrMesh that will draw the provided instances. The instanceBuffer must be an array
101     // of either TriPointInstance or QuadPointInstance, depending on this processor's RendererPass,
102     // with coordinates in the desired shape's final atlas-space position.
appendMesh(sk_sp<GrBuffer> instanceBuffer,int instanceCount,int baseInstance,SkTArray<GrMesh> * out)103     void appendMesh(sk_sp<GrBuffer> instanceBuffer, int instanceCount, int baseInstance,
104                     SkTArray<GrMesh>* out) const {
105         if (Impl::kGeometryShader == fImpl) {
106             this->appendGSMesh(std::move(instanceBuffer), instanceCount, baseInstance, out);
107         } else {
108             this->appendVSMesh(std::move(instanceBuffer), instanceCount, baseInstance, out);
109         }
110     }
111 
112     void draw(GrOpFlushState*, const GrPipeline&, const SkIRect scissorRects[], const GrMesh[],
113               int meshCount, const SkRect& drawBounds) const;
114 
115     // The Shader provides code to calculate each pixel's coverage in a RenderPass. It also
116     // provides details about shape-specific geometry.
117     class Shader {
118     public:
119         // Called before generating geometry. Subclasses may set up internal member variables during
120         // this time that will be needed during onEmitVaryings (e.g. transformation matrices).
121         //
122         // If the 'outHull4' parameter is provided, and there are not 4 input points, the subclass
123         // is required to fill it with the name of a 4-point hull around which the Impl can generate
124         // its geometry. If it is left unchanged, the Impl will use the regular input points.
125         virtual void emitSetupCode(GrGLSLVertexGeoBuilder*, const char* pts, const char* wind,
126                                    const char** outHull4 = nullptr) const {
127             SkASSERT(!outHull4);
128         }
129 
emitVaryings(GrGLSLVaryingHandler * varyingHandler,GrGLSLVarying::Scope scope,SkString * code,const char * position,const char * coverage,const char * cornerCoverage)130         void emitVaryings(GrGLSLVaryingHandler* varyingHandler, GrGLSLVarying::Scope scope,
131                           SkString* code, const char* position, const char* coverage,
132                           const char* cornerCoverage) {
133             SkASSERT(GrGLSLVarying::Scope::kVertToGeo != scope);
134             this->onEmitVaryings(varyingHandler, scope, code, position, coverage, cornerCoverage);
135         }
136 
137         void emitFragmentCode(const GrCCCoverageProcessor&, GrGLSLFPFragmentBuilder*,
138                               const char* skOutputColor, const char* skOutputCoverage) const;
139 
140         // Calculates the winding direction of the input points (+1, -1, or 0). Wind for extremely
141         // thin triangles gets rounded to zero.
142         static void CalcWind(const GrCCCoverageProcessor&, GrGLSLVertexGeoBuilder*, const char* pts,
143                              const char* outputWind);
144 
145         // Defines an equation ("dot(float3(pt, 1), distance_equation)") that is -1 on the outside
146         // border of a conservative raster edge and 0 on the inside. 'leftPt' and 'rightPt' must be
147         // ordered clockwise.
148         static void EmitEdgeDistanceEquation(GrGLSLVertexGeoBuilder*, const char* leftPt,
149                                              const char* rightPt,
150                                              const char* outputDistanceEquation);
151 
152         // Calculates an edge's coverage at a conservative raster vertex. The edge is defined by two
153         // clockwise-ordered points, 'leftPt' and 'rightPt'. 'rasterVertexDir' is a pair of +/-1
154         // values that point in the direction of conservative raster bloat, starting from an
155         // endpoint.
156         //
157         // Coverage values ramp from -1 (completely outside the edge) to 0 (completely inside).
158         static void CalcEdgeCoverageAtBloatVertex(GrGLSLVertexGeoBuilder*, const char* leftPt,
159                                                   const char* rightPt, const char* rasterVertexDir,
160                                                   const char* outputCoverage);
161 
162         // Calculates an edge's coverage at two conservative raster vertices.
163         // (See CalcEdgeCoverageAtBloatVertex).
164         static void CalcEdgeCoveragesAtBloatVertices(GrGLSLVertexGeoBuilder*, const char* leftPt,
165                                                      const char* rightPt, const char* bloatDir1,
166                                                      const char* bloatDir2,
167                                                      const char* outputCoverages);
168 
169         // Corner boxes require an additional "attenuation" varying that is multiplied by the
170         // regular (linearly-interpolated) coverage. This function calculates the attenuation value
171         // to use in the single, outermost vertex. The remaining three vertices of the corner box
172         // all use an attenuation value of 1.
173         static void CalcCornerAttenuation(GrGLSLVertexGeoBuilder*, const char* leftDir,
174                                           const char* rightDir, const char* outputAttenuation);
175 
~Shader()176         virtual ~Shader() {}
177 
178     protected:
179         // Here the subclass adds its internal varyings to the handler and produces code to
180         // initialize those varyings from a given position and coverage values.
181         //
182         // NOTE: the coverage values are signed appropriately for wind.
183         //       'coverage' will only be +1 or -1 on curves.
184         virtual void onEmitVaryings(GrGLSLVaryingHandler*, GrGLSLVarying::Scope, SkString* code,
185                                     const char* position, const char* coverage,
186                                     const char* cornerCoverage) = 0;
187 
188         // Emits the fragment code that calculates a pixel's signed coverage value.
189         virtual void onEmitFragmentCode(GrGLSLFPFragmentBuilder*,
190                                         const char* outputCoverage) const = 0;
191 
192         // Returns the name of a Shader's internal varying at the point where where its value is
193         // assigned. This is intended to work whether called for a vertex or a geometry shader.
OutName(const GrGLSLVarying & varying)194         const char* OutName(const GrGLSLVarying& varying) const {
195             using Scope = GrGLSLVarying::Scope;
196             SkASSERT(Scope::kVertToGeo != varying.scope());
197             return Scope::kGeoToFrag == varying.scope() ? varying.gsOut() : varying.vsOut();
198         }
199 
200         // Our friendship with GrGLSLShaderBuilder does not propogate to subclasses.
AccessCodeString(GrGLSLShaderBuilder * s)201         inline static SkString& AccessCodeString(GrGLSLShaderBuilder* s) { return s->code(); }
202     };
203 
204 private:
205     class GSImpl;
206     class GSTriangleHullImpl;
207     class GSCurveHullImpl;
208     class GSCornerImpl;
209     class VSImpl;
210     class TriangleShader;
211 
212     // Slightly undershoot a bloat radius of 0.5 so vertices that fall on integer boundaries don't
213     // accidentally bleed into neighbor pixels.
214     static constexpr float kAABloatRadius = 0.491111f;
215 
216     // Number of bezier points for curves, or 3 for triangles.
numInputPoints()217     int numInputPoints() const { return PrimitiveType::kCubics == fPrimitiveType ? 4 : 3; }
218 
isTriangles()219     bool isTriangles() const {
220         return PrimitiveType::kTriangles == fPrimitiveType ||
221                PrimitiveType::kWeightedTriangles == fPrimitiveType;
222     }
223 
hasInputWeight()224     int hasInputWeight() const {
225         return PrimitiveType::kWeightedTriangles == fPrimitiveType ||
226                PrimitiveType::kConics == fPrimitiveType;
227     }
228 
229     enum class Impl : bool {
230         kGeometryShader,
231         kVertexShader
232     };
233 
234     // Geometry shader backend draws primitives in two subpasses.
235     enum class GSSubpass : bool {
236         kHulls,
237         kCorners
238     };
239 
GrCCCoverageProcessor(const GrCCCoverageProcessor & proc,GSSubpass subpass)240     GrCCCoverageProcessor(const GrCCCoverageProcessor& proc, GSSubpass subpass)
241             : INHERITED(kGrCCCoverageProcessor_ClassID)
242             , fPrimitiveType(proc.fPrimitiveType)
243             , fImpl(Impl::kGeometryShader)
244             SkDEBUGCODE(, fDebugBloat(proc.fDebugBloat))
245             , fGSSubpass(subpass) {
246         SkASSERT(Impl::kGeometryShader == proc.fImpl);
247         this->initGS();
248     }
249 
250     void initGS();
251     void initVS(GrResourceProvider*);
252 
253     void appendGSMesh(sk_sp<const GrBuffer> instanceBuffer, int instanceCount, int baseInstance,
254                       SkTArray<GrMesh>* out) const;
255     void appendVSMesh(sk_sp<const GrBuffer> instanceBuffer, int instanceCount, int baseInstance,
256                       SkTArray<GrMesh>* out) const;
257 
258     GrGLSLPrimitiveProcessor* createGSImpl(std::unique_ptr<Shader>) const;
259     GrGLSLPrimitiveProcessor* createVSImpl(std::unique_ptr<Shader>) const;
260     // The type and meaning of this attribute depends on whether we're using VSImpl or GSImpl.
261     Attribute fVertexAttribute;
262 
263     const PrimitiveType fPrimitiveType;
264     const Impl fImpl;
265     SkDEBUGCODE(float fDebugBloat = 0);
266 
267     // Used by GSImpl.
268     const GSSubpass fGSSubpass = GSSubpass::kHulls;
269 
270     // Used by VSImpl.
271     Attribute fInstanceAttributes[2];
272     sk_sp<const GrBuffer> fVSVertexBuffer;
273     sk_sp<const GrBuffer> fVSIndexBuffer;
274     int fVSNumIndicesPerInstance;
275     GrPrimitiveType fVSTriangleType;
276 
277     typedef GrGeometryProcessor INHERITED;
278 };
279 
PrimitiveTypeName(PrimitiveType type)280 inline const char* GrCCCoverageProcessor::PrimitiveTypeName(PrimitiveType type) {
281     switch (type) {
282         case PrimitiveType::kTriangles: return "kTriangles";
283         case PrimitiveType::kWeightedTriangles: return "kWeightedTriangles";
284         case PrimitiveType::kQuadratics: return "kQuadratics";
285         case PrimitiveType::kCubics: return "kCubics";
286         case PrimitiveType::kConics: return "kConics";
287     }
288     SK_ABORT("Invalid PrimitiveType");
289     return "";
290 }
291 
set(const SkPoint p[3],const Sk2f & trans)292 inline void GrCCCoverageProcessor::TriPointInstance::set(const SkPoint p[3], const Sk2f& trans) {
293     this->set(p[0], p[1], p[2], trans);
294 }
295 
set(const SkPoint & p0,const SkPoint & p1,const SkPoint & p2,const Sk2f & trans)296 inline void GrCCCoverageProcessor::TriPointInstance::set(const SkPoint& p0, const SkPoint& p1,
297                                                          const SkPoint& p2, const Sk2f& trans) {
298     Sk2f P0 = Sk2f::Load(&p0);
299     Sk2f P1 = Sk2f::Load(&p1);
300     Sk2f P2 = Sk2f::Load(&p2);
301     this->set(P0, P1, P2, trans);
302 }
303 
set(const Sk2f & P0,const Sk2f & P1,const Sk2f & P2,const Sk2f & trans)304 inline void GrCCCoverageProcessor::TriPointInstance::set(const Sk2f& P0, const Sk2f& P1,
305                                                          const Sk2f& P2, const Sk2f& trans) {
306     Sk2f::Store3(this, P0 + trans, P1 + trans, P2 + trans);
307 }
308 
set(const SkPoint p[4],float dx,float dy)309 inline void GrCCCoverageProcessor::QuadPointInstance::set(const SkPoint p[4], float dx, float dy) {
310     Sk4f X,Y;
311     Sk4f::Load2(p, &X, &Y);
312     (X + dx).store(&fX);
313     (Y + dy).store(&fY);
314 }
315 
setW(const SkPoint p[3],const Sk2f & trans,float w)316 inline void GrCCCoverageProcessor::QuadPointInstance::setW(const SkPoint p[3], const Sk2f& trans,
317                                                            float w) {
318     this->setW(p[0], p[1], p[2], trans, w);
319 }
320 
setW(const SkPoint & p0,const SkPoint & p1,const SkPoint & p2,const Sk2f & trans,float w)321 inline void GrCCCoverageProcessor::QuadPointInstance::setW(const SkPoint& p0, const SkPoint& p1,
322                                                            const SkPoint& p2, const Sk2f& trans,
323                                                            float w) {
324     Sk2f P0 = Sk2f::Load(&p0);
325     Sk2f P1 = Sk2f::Load(&p1);
326     Sk2f P2 = Sk2f::Load(&p2);
327     this->setW(P0, P1, P2, trans, w);
328 }
329 
setW(const Sk2f & P0,const Sk2f & P1,const Sk2f & P2,const Sk2f & trans,float w)330 inline void GrCCCoverageProcessor::QuadPointInstance::setW(const Sk2f& P0, const Sk2f& P1,
331                                                            const Sk2f& P2, const Sk2f& trans,
332                                                            float w) {
333     Sk2f W = Sk2f(w);
334     Sk2f::Store4(this, P0 + trans, P1 + trans, P2 + trans, W);
335 }
336 
337 #endif
338