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 "GrCCPathProcessor.h"
9
10 #include "GrGpuCommandBuffer.h"
11 #include "GrOnFlushResourceProvider.h"
12 #include "GrTexture.h"
13 #include "ccpr/GrCCPerFlushResources.h"
14 #include "glsl/GrGLSLFragmentShaderBuilder.h"
15 #include "glsl/GrGLSLGeometryProcessor.h"
16 #include "glsl/GrGLSLProgramBuilder.h"
17 #include "glsl/GrGLSLVarying.h"
18
19 // Paths are drawn as octagons. Each point on the octagon is the intersection of two lines: one edge
20 // from the path's bounding box and one edge from its 45-degree bounding box. The below inputs
21 // define a vertex by the two edges that need to be intersected. Normals point out of the octagon,
22 // and the bounding boxes are sent in as instance attribs.
23 static constexpr float kOctoEdgeNorms[8 * 4] = {
24 // bbox // bbox45
25 -1, 0, -1,+1,
26 -1, 0, -1,-1,
27 0,-1, -1,-1,
28 0,-1, +1,-1,
29 +1, 0, +1,-1,
30 +1, 0, +1,+1,
31 0,+1, +1,+1,
32 0,+1, -1,+1,
33 };
34
35 GR_DECLARE_STATIC_UNIQUE_KEY(gVertexBufferKey);
36
FindVertexBuffer(GrOnFlushResourceProvider * onFlushRP)37 sk_sp<const GrBuffer> GrCCPathProcessor::FindVertexBuffer(GrOnFlushResourceProvider* onFlushRP) {
38 GR_DEFINE_STATIC_UNIQUE_KEY(gVertexBufferKey);
39 return onFlushRP->findOrMakeStaticBuffer(kVertex_GrBufferType, sizeof(kOctoEdgeNorms),
40 kOctoEdgeNorms, gVertexBufferKey);
41 }
42
43 static constexpr uint16_t kRestartStrip = 0xffff;
44
45 static constexpr uint16_t kOctoIndicesAsStrips[] = {
46 1, 0, 2, 4, 3, kRestartStrip, // First half.
47 5, 4, 6, 0, 7 // Second half.
48 };
49
50 static constexpr uint16_t kOctoIndicesAsTris[] = {
51 // First half.
52 1, 0, 2,
53 0, 4, 2,
54 2, 4, 3,
55
56 // Second half.
57 5, 4, 6,
58 4, 0, 6,
59 6, 0, 7,
60 };
61
62 GR_DECLARE_STATIC_UNIQUE_KEY(gIndexBufferKey);
63
64 constexpr GrPrimitiveProcessor::Attribute GrCCPathProcessor::kInstanceAttribs[];
65 constexpr GrPrimitiveProcessor::Attribute GrCCPathProcessor::kEdgeNormsAttrib;
66
FindIndexBuffer(GrOnFlushResourceProvider * onFlushRP)67 sk_sp<const GrBuffer> GrCCPathProcessor::FindIndexBuffer(GrOnFlushResourceProvider* onFlushRP) {
68 GR_DEFINE_STATIC_UNIQUE_KEY(gIndexBufferKey);
69 if (onFlushRP->caps()->usePrimitiveRestart()) {
70 return onFlushRP->findOrMakeStaticBuffer(kIndex_GrBufferType, sizeof(kOctoIndicesAsStrips),
71 kOctoIndicesAsStrips, gIndexBufferKey);
72 } else {
73 return onFlushRP->findOrMakeStaticBuffer(kIndex_GrBufferType, sizeof(kOctoIndicesAsTris),
74 kOctoIndicesAsTris, gIndexBufferKey);
75 }
76 }
77
GrCCPathProcessor(const GrTextureProxy * atlas,const SkMatrix & viewMatrixIfUsingLocalCoords)78 GrCCPathProcessor::GrCCPathProcessor(const GrTextureProxy* atlas,
79 const SkMatrix& viewMatrixIfUsingLocalCoords)
80 : INHERITED(kGrCCPathProcessor_ClassID)
81 , fAtlasAccess(atlas->textureType(), atlas->config(), GrSamplerState::Filter::kNearest,
82 GrSamplerState::WrapMode::kClamp)
83 , fAtlasSize(atlas->isize())
84 , fAtlasOrigin(atlas->origin()) {
85 // TODO: Can we just assert that atlas has GrCCAtlas::kTextureOrigin and remove fAtlasOrigin?
86 this->setInstanceAttributes(kInstanceAttribs, kNumInstanceAttribs);
87 SkASSERT(this->instanceStride() == sizeof(Instance));
88
89 this->setVertexAttributes(&kEdgeNormsAttrib, 1);
90 this->setTextureSamplerCnt(1);
91
92 if (!viewMatrixIfUsingLocalCoords.invert(&fLocalMatrix)) {
93 fLocalMatrix.setIdentity();
94 }
95 }
96
97 class GLSLPathProcessor : public GrGLSLGeometryProcessor {
98 public:
99 void onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) override;
100
101 private:
setData(const GrGLSLProgramDataManager & pdman,const GrPrimitiveProcessor & primProc,FPCoordTransformIter && transformIter)102 void setData(const GrGLSLProgramDataManager& pdman, const GrPrimitiveProcessor& primProc,
103 FPCoordTransformIter&& transformIter) override {
104 const GrCCPathProcessor& proc = primProc.cast<GrCCPathProcessor>();
105 pdman.set2f(fAtlasAdjustUniform, 1.0f / proc.atlasSize().fWidth,
106 1.0f / proc.atlasSize().fHeight);
107 this->setTransformDataHelper(proc.localMatrix(), pdman, &transformIter);
108 }
109
110 GrGLSLUniformHandler::UniformHandle fAtlasAdjustUniform;
111
112 typedef GrGLSLGeometryProcessor INHERITED;
113 };
114
createGLSLInstance(const GrShaderCaps &) const115 GrGLSLPrimitiveProcessor* GrCCPathProcessor::createGLSLInstance(const GrShaderCaps&) const {
116 return new GLSLPathProcessor();
117 }
118
drawPaths(GrOpFlushState * flushState,const GrPipeline & pipeline,const GrPipeline::FixedDynamicState * fixedDynamicState,const GrCCPerFlushResources & resources,int baseInstance,int endInstance,const SkRect & bounds) const119 void GrCCPathProcessor::drawPaths(GrOpFlushState* flushState, const GrPipeline& pipeline,
120 const GrPipeline::FixedDynamicState* fixedDynamicState,
121 const GrCCPerFlushResources& resources, int baseInstance,
122 int endInstance, const SkRect& bounds) const {
123 const GrCaps& caps = flushState->caps();
124 GrPrimitiveType primitiveType = caps.usePrimitiveRestart()
125 ? GrPrimitiveType::kTriangleStrip
126 : GrPrimitiveType::kTriangles;
127 int numIndicesPerInstance = caps.usePrimitiveRestart()
128 ? SK_ARRAY_COUNT(kOctoIndicesAsStrips)
129 : SK_ARRAY_COUNT(kOctoIndicesAsTris);
130 GrMesh mesh(primitiveType);
131 auto enablePrimitiveRestart = GrPrimitiveRestart(flushState->caps().usePrimitiveRestart());
132
133 mesh.setIndexedInstanced(resources.refIndexBuffer(), numIndicesPerInstance,
134 resources.refInstanceBuffer(), endInstance - baseInstance,
135 baseInstance, enablePrimitiveRestart);
136 mesh.setVertexData(resources.refVertexBuffer());
137
138 flushState->rtCommandBuffer()->draw(*this, pipeline, fixedDynamicState, nullptr, &mesh, 1,
139 bounds);
140 }
141
onEmitCode(EmitArgs & args,GrGPArgs * gpArgs)142 void GLSLPathProcessor::onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) {
143 using InstanceAttribs = GrCCPathProcessor::InstanceAttribs;
144 using Interpolation = GrGLSLVaryingHandler::Interpolation;
145
146 const GrCCPathProcessor& proc = args.fGP.cast<GrCCPathProcessor>();
147 GrGLSLUniformHandler* uniHandler = args.fUniformHandler;
148 GrGLSLVaryingHandler* varyingHandler = args.fVaryingHandler;
149
150 const char* atlasAdjust;
151 fAtlasAdjustUniform = uniHandler->addUniform(
152 kVertex_GrShaderFlag,
153 kFloat2_GrSLType, "atlas_adjust", &atlasAdjust);
154
155 varyingHandler->emitAttributes(proc);
156
157 GrGLSLVarying texcoord(kFloat3_GrSLType);
158 GrGLSLVarying color(kHalf4_GrSLType);
159 varyingHandler->addVarying("texcoord", &texcoord);
160 varyingHandler->addPassThroughAttribute(proc.getInstanceAttrib(InstanceAttribs::kColor),
161 args.fOutputColor, Interpolation::kCanBeFlat);
162
163 // The vertex shader bloats and intersects the devBounds and devBounds45 rectangles, in order to
164 // find an octagon that circumscribes the (bloated) path.
165 GrGLSLVertexBuilder* v = args.fVertBuilder;
166
167 // Each vertex is the intersection of one edge from devBounds and one from devBounds45.
168 // 'N' holds the normals to these edges as column vectors.
169 //
170 // NOTE: "float2x2(float4)" is valid and equivalent to "float2x2(float4.xy, float4.zw)",
171 // however Intel compilers crash when we use the former syntax in this shader.
172 v->codeAppendf("float2x2 N = float2x2(%s.xy, %s.zw);", proc.getEdgeNormsAttrib().name(),
173 proc.getEdgeNormsAttrib().name());
174
175 // N[0] is the normal for the edge we are intersecting from the regular bounding box, pointing
176 // out of the octagon.
177 v->codeAppendf("float4 devbounds = %s;",
178 proc.getInstanceAttrib(InstanceAttribs::kDevBounds).name());
179 v->codeAppend ("float2 refpt = (0 == sk_VertexID >> 2)"
180 "? float2(min(devbounds.x, devbounds.z), devbounds.y)"
181 ": float2(max(devbounds.x, devbounds.z), devbounds.w);");
182
183 // N[1] is the normal for the edge we are intersecting from the 45-degree bounding box, pointing
184 // out of the octagon.
185 v->codeAppendf("float2 refpt45 = (0 == ((sk_VertexID + 1) & (1 << 2))) ? %s.xy : %s.zw;",
186 proc.getInstanceAttrib(InstanceAttribs::kDevBounds45).name(),
187 proc.getInstanceAttrib(InstanceAttribs::kDevBounds45).name());
188 v->codeAppendf("refpt45 *= float2x2(.5,.5,-.5,.5);"); // transform back to device space.
189
190 v->codeAppend ("float2 K = float2(dot(N[0], refpt), dot(N[1], refpt45));");
191 v->codeAppendf("float2 octocoord = K * inverse(N);");
192
193 // Round the octagon out to ensure we rasterize every pixel the path might touch. (Positive
194 // bloatdir means we should take the "ceil" and negative means to take the "floor".)
195 //
196 // NOTE: If we were just drawing a rect, ceil/floor would be enough. But since there are also
197 // diagonals in the octagon that cross through pixel centers, we need to outset by another
198 // quarter px to ensure those pixels get rasterized.
199 v->codeAppend ("float2 bloatdir = (0 != N[0].x) "
200 "? half2(N[0].x, N[1].y) : half2(N[1].x, N[0].y);");
201 v->codeAppend ("octocoord = (ceil(octocoord * bloatdir - 1e-4) + 0.25) * bloatdir;");
202
203 gpArgs->fPositionVar.set(kFloat2_GrSLType, "octocoord");
204
205 // Convert to atlas coordinates in order to do our texture lookup.
206 v->codeAppendf("float2 atlascoord = octocoord + float2(%s);",
207 proc.getInstanceAttrib(InstanceAttribs::kDevToAtlasOffset).name());
208 if (kTopLeft_GrSurfaceOrigin == proc.atlasOrigin()) {
209 v->codeAppendf("%s.xy = atlascoord * %s;", texcoord.vsOut(), atlasAdjust);
210 } else {
211 SkASSERT(kBottomLeft_GrSurfaceOrigin == proc.atlasOrigin());
212 v->codeAppendf("%s.xy = float2(atlascoord.x * %s.x, 1 - atlascoord.y * %s.y);",
213 texcoord.vsOut(), atlasAdjust, atlasAdjust);
214 }
215 // The third texture coordinate is -.5 for even-odd paths and +.5 for winding ones.
216 // ("right < left" indicates even-odd fill type.)
217 v->codeAppendf("%s.z = sign(devbounds.z - devbounds.x) * .5;", texcoord.vsOut());
218
219 this->emitTransforms(v, varyingHandler, uniHandler, GrShaderVar("octocoord", kFloat2_GrSLType),
220 proc.localMatrix(), args.fFPCoordTransformHandler);
221
222 // Fragment shader.
223 GrGLSLFPFragmentBuilder* f = args.fFragBuilder;
224
225 // Look up coverage count in the atlas.
226 f->codeAppend ("half coverage = ");
227 f->appendTextureLookup(args.fTexSamplers[0], SkStringPrintf("%s.xy", texcoord.fsIn()).c_str(),
228 kFloat2_GrSLType);
229 f->codeAppend (".a;");
230
231 // Scale coverage count by .5. Make it negative for even-odd paths and positive for winding
232 // ones. Clamp winding coverage counts at 1.0 (i.e. min(coverage/2, .5)).
233 f->codeAppendf("coverage = min(abs(coverage) * %s.z, .5);", texcoord.fsIn());
234
235 // For negative values, this finishes the even-odd sawtooth function. Since positive (winding)
236 // values were clamped at "coverage/2 = .5", this only undoes the previous multiply by .5.
237 f->codeAppend ("coverage = 1 - abs(fract(coverage) * 2 - 1);");
238
239 f->codeAppendf("%s = half4(coverage);", args.fOutputCoverage);
240 }
241