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