1 /*
2 * Copyright 2019 Google LLC.
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 "src/gpu/ganesh/tessellate/GrPathTessellationShader.h"
9
10 #include "src/base/SkMathPriv.h"
11 #include "src/gpu/KeyBuilder.h"
12 #include "src/gpu/ganesh/effects/GrDisableColorXP.h"
13 #include "src/gpu/ganesh/glsl/GrGLSLFragmentShaderBuilder.h"
14 #include "src/gpu/ganesh/glsl/GrGLSLVarying.h"
15 #include "src/gpu/ganesh/glsl/GrGLSLVertexGeoBuilder.h"
16 #include "src/gpu/tessellate/FixedCountBufferUtils.h"
17 #include "src/gpu/tessellate/Tessellation.h"
18 #include "src/gpu/tessellate/WangsFormula.h"
19
20 using namespace skia_private;
21
22 namespace {
23
24 using namespace skgpu::tess;
25
26 // Draws a simple array of triangles.
27 class SimpleTriangleShader : public GrPathTessellationShader {
28 public:
SimpleTriangleShader(const SkMatrix & viewMatrix,SkPMColor4f color)29 SimpleTriangleShader(const SkMatrix& viewMatrix, SkPMColor4f color)
30 : GrPathTessellationShader(kTessellate_SimpleTriangleShader_ClassID,
31 GrPrimitiveType::kTriangles,
32 viewMatrix,
33 color,
34 PatchAttribs::kNone) {
35 constexpr static Attribute kInputPointAttrib{"inputPoint", kFloat2_GrVertexAttribType,
36 SkSLType::kFloat2};
37 this->setVertexAttributesWithImplicitOffsets(&kInputPointAttrib, 1);
38 }
39
40 private:
name() const41 const char* name() const final { return "tessellate_SimpleTriangleShader"; }
addToKey(const GrShaderCaps &,skgpu::KeyBuilder *) const42 void addToKey(const GrShaderCaps&, skgpu::KeyBuilder*) const final {}
43 std::unique_ptr<ProgramImpl> makeProgramImpl(const GrShaderCaps&) const final;
44 };
45
makeProgramImpl(const GrShaderCaps &) const46 std::unique_ptr<GrGeometryProcessor::ProgramImpl> SimpleTriangleShader::makeProgramImpl(
47 const GrShaderCaps&) const {
48 class Impl : public GrPathTessellationShader::Impl {
49 void emitVertexCode(const GrShaderCaps&,
50 const GrPathTessellationShader&,
51 GrGLSLVertexBuilder* v,
52 GrGLSLVaryingHandler*,
53 GrGPArgs* gpArgs) override {
54 v->codeAppend(
55 "float2 localcoord = inputPoint;"
56 "float2 vertexpos = AFFINE_MATRIX * localcoord + TRANSLATE;");
57 gpArgs->fLocalCoordVar.set(SkSLType::kFloat2, "localcoord");
58 gpArgs->fPositionVar.set(SkSLType::kFloat2, "vertexpos");
59 }
60 };
61 return std::make_unique<Impl>();
62 }
63
64
65 // Uses instanced draws to triangulate standalone closed curves with a "middle-out" topology.
66 // Middle-out draws a triangle with vertices at T=[0, 1/2, 1] and then recurses breadth first:
67 //
68 // depth=0: T=[0, 1/2, 1]
69 // depth=1: T=[0, 1/4, 2/4], T=[2/4, 3/4, 1]
70 // depth=2: T=[0, 1/8, 2/8], T=[2/8, 3/8, 4/8], T=[4/8, 5/8, 6/8], T=[6/8, 7/8, 1]
71 // ...
72 //
73 // The shader determines how many segments are required to render each individual curve smoothly,
74 // and emits empty triangles at any vertices whose sk_VertexIDs are higher than necessary. It is the
75 // caller's responsibility to draw enough vertices per instance for the most complex curve in the
76 // batch to render smoothly (i.e., NumTrianglesAtResolveLevel() * 3).
77 class MiddleOutShader : public GrPathTessellationShader {
78 public:
MiddleOutShader(const GrShaderCaps & shaderCaps,const SkMatrix & viewMatrix,const SkPMColor4f & color,PatchAttribs attribs)79 MiddleOutShader(const GrShaderCaps& shaderCaps, const SkMatrix& viewMatrix,
80 const SkPMColor4f& color, PatchAttribs attribs)
81 : GrPathTessellationShader(kTessellate_MiddleOutShader_ClassID,
82 GrPrimitiveType::kTriangles, viewMatrix, color, attribs) {
83 fInstanceAttribs.emplace_back("p01", kFloat4_GrVertexAttribType, SkSLType::kFloat4);
84 fInstanceAttribs.emplace_back("p23", kFloat4_GrVertexAttribType, SkSLType::kFloat4);
85 if (fAttribs & PatchAttribs::kFanPoint) {
86 fInstanceAttribs.emplace_back("fanPointAttrib",
87 kFloat2_GrVertexAttribType,
88 SkSLType::kFloat2);
89 }
90 if (fAttribs & PatchAttribs::kColor) {
91 fInstanceAttribs.emplace_back("colorAttrib",
92 (fAttribs & PatchAttribs::kWideColorIfEnabled)
93 ? kFloat4_GrVertexAttribType
94 : kUByte4_norm_GrVertexAttribType,
95 SkSLType::kHalf4);
96 }
97 if (fAttribs & PatchAttribs::kExplicitCurveType) {
98 // A conic curve is written out with p3=[w,Infinity], but GPUs that don't support
99 // infinity can't detect this. On these platforms we also write out an extra float with
100 // each patch that explicitly tells the shader what type of curve it is.
101 fInstanceAttribs.emplace_back("curveType", kFloat_GrVertexAttribType, SkSLType::kFloat);
102 }
103 this->setInstanceAttributesWithImplicitOffsets(fInstanceAttribs.data(),
104 fInstanceAttribs.size());
105 SkASSERT(fInstanceAttribs.size() <= kMaxInstanceAttribCount);
106 SkASSERT(this->instanceStride() ==
107 sizeof(SkPoint) * 4 + PatchAttribsStride(fAttribs));
108
109 constexpr static Attribute kVertexAttrib("resolveLevel_and_idx", kFloat2_GrVertexAttribType,
110 SkSLType::kFloat2);
111 this->setVertexAttributesWithImplicitOffsets(&kVertexAttrib, 1);
112 }
113
114 private:
name() const115 const char* name() const final { return "tessellate_MiddleOutShader"; }
addToKey(const GrShaderCaps &,skgpu::KeyBuilder * b) const116 void addToKey(const GrShaderCaps&, skgpu::KeyBuilder* b) const final {
117 // When color is in a uniform, it's always wide so we need to ignore kWideColorIfEnabled.
118 // When color is in an attrib, its wideness is accounted for as part of the attrib key in
119 // GrGeometryProcessor::getAttributeKey().
120 // Either way, we get the correct key by ignoring .
121 b->add32((uint32_t)(fAttribs & ~PatchAttribs::kWideColorIfEnabled));
122 }
123 std::unique_ptr<ProgramImpl> makeProgramImpl(const GrShaderCaps&) const final;
124
125 constexpr static int kMaxInstanceAttribCount = 5;
126 STArray<kMaxInstanceAttribCount, Attribute> fInstanceAttribs;
127 };
128
makeProgramImpl(const GrShaderCaps &) const129 std::unique_ptr<GrGeometryProcessor::ProgramImpl> MiddleOutShader::makeProgramImpl(
130 const GrShaderCaps&) const {
131 class Impl : public GrPathTessellationShader::Impl {
132 void emitVertexCode(const GrShaderCaps& shaderCaps,
133 const GrPathTessellationShader& shader,
134 GrGLSLVertexBuilder* v,
135 GrGLSLVaryingHandler* varyingHandler,
136 GrGPArgs* gpArgs) override {
137 const MiddleOutShader& middleOutShader = shader.cast<MiddleOutShader>();
138 v->defineConstant("PRECISION", skgpu::tess::kPrecision);
139 v->defineConstant("MAX_FIXED_RESOLVE_LEVEL",
140 (float)skgpu::tess::kMaxResolveLevel);
141 v->defineConstant("MAX_FIXED_SEGMENTS",
142 (float)(skgpu::tess::kMaxParametricSegments));
143 v->insertFunction(GrTessellationShader::WangsFormulaSkSL());
144 if (middleOutShader.fAttribs & PatchAttribs::kExplicitCurveType) {
145 v->insertFunction(SkStringPrintf(
146 "bool is_conic_curve() {"
147 "return curveType != %g;"
148 "}", skgpu::tess::kCubicCurveType).c_str());
149 v->insertFunction(SkStringPrintf(
150 "bool is_triangular_conic_curve() {"
151 "return curveType == %g;"
152 "}", skgpu::tess::kTriangularConicCurveType).c_str());
153 } else {
154 SkASSERT(shaderCaps.fInfinitySupport);
155 v->insertFunction(
156 "bool is_conic_curve() { return isinf(p23.w); }"
157 "bool is_triangular_conic_curve() { return isinf(p23.z); }");
158 }
159 if (shaderCaps.fBitManipulationSupport) {
160 v->insertFunction(
161 "float ldexp_portable(float x, float p) {"
162 "return ldexp(x, int(p));"
163 "}");
164 } else {
165 v->insertFunction(
166 "float ldexp_portable(float x, float p) {"
167 "return x * exp2(p);"
168 "}");
169 }
170 v->codeAppend(
171 "float resolveLevel = resolveLevel_and_idx.x;"
172 "float idxInResolveLevel = resolveLevel_and_idx.y;"
173 "float2 localcoord;");
174 if (middleOutShader.fAttribs & PatchAttribs::kFanPoint) {
175 v->codeAppend(
176 // A negative resolve level means this is the fan point.
177 "if (resolveLevel < 0) {"
178 "localcoord = fanPointAttrib;"
179 "} else "); // Fall through to next if (). Trailing space is important.
180 }
181 v->codeAppend(
182 "if (is_triangular_conic_curve()) {"
183 // This patch is an exact triangle.
184 "localcoord = (resolveLevel != 0) ? p01.zw"
185 ": (idxInResolveLevel != 0) ? p23.xy"
186 ": p01.xy;"
187 "} else {"
188 "float2 p0=p01.xy, p1=p01.zw, p2=p23.xy, p3=p23.zw;"
189 "float w = -1;" // w < 0 tells us to treat the instance as an integral cubic.
190 "float maxResolveLevel;"
191 "if (is_conic_curve()) {"
192 // Conics are 3 points, with the weight in p3.
193 "w = p3.x;"
194 "maxResolveLevel = wangs_formula_conic_log2(PRECISION, AFFINE_MATRIX * p0,"
195 "AFFINE_MATRIX * p1,"
196 "AFFINE_MATRIX * p2, w);"
197 "p1 *= w;" // Unproject p1.
198 "p3 = p2;" // Duplicate the endpoint for shared code that also runs on cubics.
199 "} else {"
200 // The patch is an integral cubic.
201 "maxResolveLevel = wangs_formula_cubic_log2(PRECISION, p0, p1, p2, p3,"
202 "AFFINE_MATRIX);"
203 "}"
204 "if (resolveLevel > maxResolveLevel) {"
205 // This vertex is at a higher resolve level than we need. Demote to a lower
206 // resolveLevel, which will produce a degenerate triangle.
207 "idxInResolveLevel = floor(ldexp_portable(idxInResolveLevel,"
208 "maxResolveLevel - resolveLevel));"
209 "resolveLevel = maxResolveLevel;"
210 "}"
211 // Promote our location to a discrete position in the maximum fixed resolve level.
212 // This is extra paranoia to ensure we get the exact same fp32 coordinates for
213 // colocated points from different resolve levels (e.g., the vertices T=3/4 and
214 // T=6/8 should be exactly colocated).
215 "float fixedVertexID = floor(.5 + ldexp_portable("
216 "idxInResolveLevel, MAX_FIXED_RESOLVE_LEVEL - resolveLevel));"
217 "if (0 < fixedVertexID && fixedVertexID < MAX_FIXED_SEGMENTS) {"
218 "float T = fixedVertexID * (1 / MAX_FIXED_SEGMENTS);"
219
220 // Evaluate at T. Use De Casteljau's for its accuracy and stability.
221 "float2 ab = mix(p0, p1, T);"
222 "float2 bc = mix(p1, p2, T);"
223 "float2 cd = mix(p2, p3, T);"
224 "float2 abc = mix(ab, bc, T);"
225 "float2 bcd = mix(bc, cd, T);"
226 "float2 abcd = mix(abc, bcd, T);"
227
228 // Evaluate the conic weight at T.
229 "float u = mix(1.0, w, T);"
230 "float v = w + 1 - u;" // == mix(w, 1, T)
231 "float uv = mix(u, v, T);"
232
233 "localcoord = (w < 0) ?" /*cubic*/ "abcd:" /*conic*/ "abc/uv;"
234 "} else {"
235 "localcoord = (fixedVertexID == 0) ? p0.xy : p3.xy;"
236 "}"
237 "}"
238 "float2 vertexpos = AFFINE_MATRIX * localcoord + TRANSLATE;");
239 gpArgs->fLocalCoordVar.set(SkSLType::kFloat2, "localcoord");
240 gpArgs->fPositionVar.set(SkSLType::kFloat2, "vertexpos");
241 if (middleOutShader.fAttribs & PatchAttribs::kColor) {
242 GrGLSLVarying colorVarying(SkSLType::kHalf4);
243 varyingHandler->addVarying("color",
244 &colorVarying,
245 GrGLSLVaryingHandler::Interpolation::kCanBeFlat);
246 v->codeAppendf("%s = colorAttrib;", colorVarying.vsOut());
247 fVaryingColorName = colorVarying.fsIn();
248 }
249 }
250 };
251 return std::make_unique<Impl>();
252 }
253
254 } // namespace
255
Make(const GrShaderCaps & shaderCaps,SkArenaAlloc * arena,const SkMatrix & viewMatrix,const SkPMColor4f & color,PatchAttribs attribs)256 GrPathTessellationShader* GrPathTessellationShader::Make(const GrShaderCaps& shaderCaps,
257 SkArenaAlloc* arena,
258 const SkMatrix& viewMatrix,
259 const SkPMColor4f& color,
260 PatchAttribs attribs) {
261 // We should use explicit curve type when, and only when, there isn't infinity support.
262 // Otherwise the GPU can infer curve type based on infinity.
263 SkASSERT(shaderCaps.fInfinitySupport != (attribs & PatchAttribs::kExplicitCurveType));
264 return arena->make<MiddleOutShader>(shaderCaps, viewMatrix, color, attribs);
265 }
266
MakeSimpleTriangleShader(SkArenaAlloc * arena,const SkMatrix & viewMatrix,const SkPMColor4f & color)267 GrPathTessellationShader* GrPathTessellationShader::MakeSimpleTriangleShader(
268 SkArenaAlloc* arena, const SkMatrix& viewMatrix, const SkPMColor4f& color) {
269 return arena->make<SimpleTriangleShader>(viewMatrix, color);
270 }
271
MakeStencilOnlyPipeline(const ProgramArgs & args,GrAAType aaType,const GrAppliedHardClip & hardClip,GrPipeline::InputFlags pipelineFlags)272 const GrPipeline* GrPathTessellationShader::MakeStencilOnlyPipeline(
273 const ProgramArgs& args,
274 GrAAType aaType,
275 const GrAppliedHardClip& hardClip,
276 GrPipeline::InputFlags pipelineFlags) {
277 GrPipeline::InitArgs pipelineArgs;
278 pipelineArgs.fInputFlags = pipelineFlags;
279 pipelineArgs.fCaps = args.fCaps;
280 return args.fArena->make<GrPipeline>(pipelineArgs,
281 GrDisableColorXPFactory::MakeXferProcessor(),
282 hardClip);
283 }
284
285 // Evaluate our point of interest using numerically stable linear interpolations. We add our own
286 // "safe_mix" method to guarantee we get exactly "b" when T=1. The builtin mix() function seems
287 // spec'd to behave this way, but empirical results results have shown it does not always.
288 const char* GrPathTessellationShader::Impl::kEvalRationalCubicFn =
289 "float3 safe_mix(float3 a, float3 b, float T, float one_minus_T) {"
290 "return a*one_minus_T + b*T;"
291 "}"
292 "float2 eval_rational_cubic(float4x3 P, float T) {"
293 "float one_minus_T = 1.0 - T;"
294 "float3 ab = safe_mix(P[0], P[1], T, one_minus_T);"
295 "float3 bc = safe_mix(P[1], P[2], T, one_minus_T);"
296 "float3 cd = safe_mix(P[2], P[3], T, one_minus_T);"
297 "float3 abc = safe_mix(ab, bc, T, one_minus_T);"
298 "float3 bcd = safe_mix(bc, cd, T, one_minus_T);"
299 "float3 abcd = safe_mix(abc, bcd, T, one_minus_T);"
300 "return abcd.xy / abcd.z;"
301 "}";
302
onEmitCode(EmitArgs & args,GrGPArgs * gpArgs)303 void GrPathTessellationShader::Impl::onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) {
304 const auto& shader = args.fGeomProc.cast<GrPathTessellationShader>();
305 args.fVaryingHandler->emitAttributes(shader);
306
307 // Vertex shader.
308 const char* affineMatrix, *translate;
309 fAffineMatrixUniform = args.fUniformHandler->addUniform(nullptr, kVertex_GrShaderFlag,
310 SkSLType::kFloat4, "affineMatrix",
311 &affineMatrix);
312 fTranslateUniform = args.fUniformHandler->addUniform(nullptr, kVertex_GrShaderFlag,
313 SkSLType::kFloat2, "translate", &translate);
314 args.fVertBuilder->codeAppendf("float2x2 AFFINE_MATRIX = float2x2(%s.xy, %s.zw);",
315 affineMatrix, affineMatrix);
316 args.fVertBuilder->codeAppendf("float2 TRANSLATE = %s;", translate);
317 this->emitVertexCode(*args.fShaderCaps,
318 shader,
319 args.fVertBuilder,
320 args.fVaryingHandler,
321 gpArgs);
322
323 // Fragment shader.
324 if (!(shader.fAttribs & PatchAttribs::kColor)) {
325 const char* color;
326 fColorUniform = args.fUniformHandler->addUniform(nullptr, kFragment_GrShaderFlag,
327 SkSLType::kHalf4, "color", &color);
328 args.fFragBuilder->codeAppendf("half4 %s = %s;", args.fOutputColor, color);
329 } else {
330 args.fFragBuilder->codeAppendf("half4 %s = %s;",
331 args.fOutputColor, fVaryingColorName.c_str());
332 }
333 args.fFragBuilder->codeAppendf("const half4 %s = half4(1);", args.fOutputCoverage);
334 }
335
setData(const GrGLSLProgramDataManager & pdman,const GrShaderCaps &,const GrGeometryProcessor & geomProc)336 void GrPathTessellationShader::Impl::setData(const GrGLSLProgramDataManager& pdman, const
337 GrShaderCaps&, const GrGeometryProcessor& geomProc) {
338 const auto& shader = geomProc.cast<GrPathTessellationShader>();
339 const SkMatrix& m = shader.viewMatrix();
340 pdman.set4f(fAffineMatrixUniform, m.getScaleX(), m.getSkewY(), m.getSkewX(), m.getScaleY());
341 pdman.set2f(fTranslateUniform, m.getTranslateX(), m.getTranslateY());
342
343 if (!(shader.fAttribs & PatchAttribs::kColor)) {
344 const SkPMColor4f& color = shader.color();
345 pdman.set4f(fColorUniform, color.fR, color.fG, color.fB, color.fA);
346 }
347 }
348