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/tessellate/shaders/GrPathTessellationShader.h"
9
10 #include "src/core/SkMathPriv.h"
11 #include "src/gpu/glsl/GrGLSLVertexGeoBuilder.h"
12 #include "src/gpu/tessellate/PathTessellator.h"
13 #include "src/gpu/tessellate/Tessellation.h"
14 #include "src/gpu/tessellate/WangsFormula.h"
15
16 using skgpu::PatchAttribs;
17 using skgpu::VertexWriter;
18
19 namespace {
20
21 // Uses instanced draws to triangulate standalone closed curves with a "middle-out" topology.
22 // Middle-out draws a triangle with vertices at T=[0, 1/2, 1] and then recurses breadth first:
23 //
24 // depth=0: T=[0, 1/2, 1]
25 // depth=1: T=[0, 1/4, 2/4], T=[2/4, 3/4, 1]
26 // 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]
27 // ...
28 //
29 // The shader determines how many segments are required to render each individual curve smoothly,
30 // and emits empty triangles at any vertices whose sk_VertexIDs are higher than necessary. It is the
31 // caller's responsibility to draw enough vertices per instance for the most complex curve in the
32 // batch to render smoothly (i.e., NumTrianglesAtResolveLevel() * 3).
33 class MiddleOutShader : public GrPathTessellationShader {
34 public:
MiddleOutShader(const GrShaderCaps & shaderCaps,const SkMatrix & viewMatrix,const SkPMColor4f & color,PatchAttribs attribs)35 MiddleOutShader(const GrShaderCaps& shaderCaps, const SkMatrix& viewMatrix,
36 const SkPMColor4f& color, PatchAttribs attribs)
37 : GrPathTessellationShader(kTessellate_MiddleOutShader_ClassID,
38 GrPrimitiveType::kTriangles, 0, viewMatrix, color, attribs) {
39 fInstanceAttribs.emplace_back("p01", kFloat4_GrVertexAttribType, kFloat4_GrSLType);
40 fInstanceAttribs.emplace_back("p23", kFloat4_GrVertexAttribType, kFloat4_GrSLType);
41 if (fAttribs & PatchAttribs::kFanPoint) {
42 fInstanceAttribs.emplace_back("fanPointAttrib",
43 kFloat2_GrVertexAttribType,
44 kFloat2_GrSLType);
45 }
46 if (fAttribs & PatchAttribs::kColor) {
47 fInstanceAttribs.emplace_back("colorAttrib",
48 (fAttribs & PatchAttribs::kWideColorIfEnabled)
49 ? kFloat4_GrVertexAttribType
50 : kUByte4_norm_GrVertexAttribType,
51 kHalf4_GrSLType);
52 }
53 if (fAttribs & PatchAttribs::kExplicitCurveType) {
54 // A conic curve is written out with p3=[w,Infinity], but GPUs that don't support
55 // infinity can't detect this. On these platforms we also write out an extra float with
56 // each patch that explicitly tells the shader what type of curve it is.
57 fInstanceAttribs.emplace_back("curveType", kFloat_GrVertexAttribType, kFloat_GrSLType);
58 }
59 this->setInstanceAttributes(fInstanceAttribs.data(), fInstanceAttribs.count());
60 SkASSERT(fInstanceAttribs.count() <= kMaxInstanceAttribCount);
61 SkASSERT(this->instanceStride() ==
62 sizeof(SkPoint) * 4 + skgpu::PatchAttribsStride(fAttribs));
63
64 constexpr static Attribute kVertexAttrib("resolveLevel_and_idx", kFloat2_GrVertexAttribType,
65 kFloat2_GrSLType);
66 this->setVertexAttributes(&kVertexAttrib, 1);
67 }
68
maxTessellationSegments(const GrShaderCaps &) const69 int maxTessellationSegments(const GrShaderCaps&) const override {
70 return 1 << skgpu::PathTessellator::kMaxFixedResolveLevel;
71 }
72
73 private:
name() const74 const char* name() const final { return "tessellate_MiddleOutShader"; }
addToKey(const GrShaderCaps &,GrProcessorKeyBuilder * b) const75 void addToKey(const GrShaderCaps&, GrProcessorKeyBuilder* b) const final {
76 // When color is in a uniform, it's always wide so we need to ignore kWideColorIfEnabled.
77 // When color is in an attrib, its wideness is accounted for as part of the attrib key in
78 // GrGeometryProcessor::getAttributeKey().
79 // Either way, we get the correct key by ignoring .
80 b->add32((uint32_t)(fAttribs & ~PatchAttribs::kWideColorIfEnabled));
81 }
82 std::unique_ptr<ProgramImpl> makeProgramImpl(const GrShaderCaps&) const final;
83
84 constexpr static int kMaxInstanceAttribCount = 5;
85 SkSTArray<kMaxInstanceAttribCount, Attribute> fInstanceAttribs;
86 };
87
makeProgramImpl(const GrShaderCaps &) const88 std::unique_ptr<GrGeometryProcessor::ProgramImpl> MiddleOutShader::makeProgramImpl(
89 const GrShaderCaps&) const {
90 class Impl : public GrPathTessellationShader::Impl {
91 void emitVertexCode(const GrShaderCaps& shaderCaps,
92 const GrPathTessellationShader& shader,
93 GrGLSLVertexBuilder* v,
94 GrGLSLVaryingHandler* varyingHandler,
95 GrGPArgs* gpArgs) override {
96 const MiddleOutShader& middleOutShader = shader.cast<MiddleOutShader>();
97 v->defineConstant("PRECISION", skgpu::kTessellationPrecision);
98 v->defineConstant("MAX_FIXED_RESOLVE_LEVEL",
99 (float)skgpu::PathTessellator::kMaxFixedResolveLevel);
100 v->defineConstant("MAX_FIXED_SEGMENTS",
101 (float)(1 << skgpu::PathTessellator::kMaxFixedResolveLevel));
102 v->insertFunction(skgpu::wangs_formula::as_sksl().c_str());
103 if (middleOutShader.fAttribs & PatchAttribs::kExplicitCurveType) {
104 v->insertFunction(SkStringPrintf(R"(
105 bool is_conic_curve() { return curveType != %g; })", kCubicCurveType).c_str());
106 v->insertFunction(SkStringPrintf(R"(
107 bool is_triangular_conic_curve() {
108 return curveType == %g;
109 })", kTriangularConicCurveType).c_str());
110 } else {
111 SkASSERT(shaderCaps.infinitySupport());
112 v->insertFunction(R"(
113 bool is_conic_curve() { return isinf(p23.w); }
114 bool is_triangular_conic_curve() { return isinf(p23.z); })");
115 }
116 if (shaderCaps.bitManipulationSupport()) {
117 v->insertFunction(R"(
118 float ldexp_portable(float x, float p) {
119 return ldexp(x, int(p));
120 })");
121 } else {
122 v->insertFunction(R"(
123 float ldexp_portable(float x, float p) {
124 return x * exp2(p);
125 })");
126 }
127 v->codeAppend(R"(
128 float resolveLevel = resolveLevel_and_idx.x;
129 float idxInResolveLevel = resolveLevel_and_idx.y;
130 float2 localcoord;)");
131 if (middleOutShader.fAttribs & PatchAttribs::kFanPoint) {
132 v->codeAppend(R"(
133 // A negative resolve level means this is the fan point.
134 if (resolveLevel < 0) {
135 localcoord = fanPointAttrib;
136 } else)"); // Fall through to next if ().
137 }
138 v->codeAppend(R"(
139 if (is_triangular_conic_curve()) {
140 // This patch is an exact triangle.
141 localcoord = (resolveLevel != 0) ? p01.zw
142 : (idxInResolveLevel != 0) ? p23.xy
143 : p01.xy;
144 } else {
145 float2 p0=p01.xy, p1=p01.zw, p2=p23.xy, p3=p23.zw;
146 float w = -1; // w < 0 tells us to treat the instance as an integral cubic.
147 float maxResolveLevel;
148 if (is_conic_curve()) {
149 // Conics are 3 points, with the weight in p3.
150 w = p3.x;
151 maxResolveLevel = wangs_formula_conic_log2(PRECISION, AFFINE_MATRIX * p0,
152 AFFINE_MATRIX * p1,
153 AFFINE_MATRIX * p2, w);
154 p1 *= w; // Unproject p1.
155 p3 = p2; // Duplicate the endpoint for shared code that also runs on cubics.
156 } else {
157 // The patch is an integral cubic.
158 maxResolveLevel = wangs_formula_cubic_log2(PRECISION, p0, p1, p2, p3,
159 AFFINE_MATRIX);
160 }
161 if (resolveLevel > maxResolveLevel) {
162 // This vertex is at a higher resolve level than we need. Demote to a lower
163 // resolveLevel, which will produce a degenerate triangle.
164 idxInResolveLevel = floor(ldexp_portable(idxInResolveLevel,
165 maxResolveLevel - resolveLevel));
166 resolveLevel = maxResolveLevel;
167 }
168 // Promote our location to a discrete position in the maximum fixed resolve level.
169 // This is extra paranoia to ensure we get the exact same fp32 coordinates for
170 // colocated points from different resolve levels (e.g., the vertices T=3/4 and
171 // T=6/8 should be exactly colocated).
172 float fixedVertexID = floor(.5 + ldexp_portable(
173 idxInResolveLevel, MAX_FIXED_RESOLVE_LEVEL - resolveLevel));
174 if (0 < fixedVertexID && fixedVertexID < MAX_FIXED_SEGMENTS) {
175 float T = fixedVertexID * (1 / MAX_FIXED_SEGMENTS);
176
177 // Evaluate at T. Use De Casteljau's for its accuracy and stability.
178 float2 ab = mix(p0, p1, T);
179 float2 bc = mix(p1, p2, T);
180 float2 cd = mix(p2, p3, T);
181 float2 abc = mix(ab, bc, T);
182 float2 bcd = mix(bc, cd, T);
183 float2 abcd = mix(abc, bcd, T);
184
185 // Evaluate the conic weight at T.
186 float u = mix(1.0, w, T);
187 float v = w + 1 - u; // == mix(w, 1, T)
188 float uv = mix(u, v, T);
189
190 localcoord = (w < 0) ? /*cubic*/ abcd : /*conic*/ abc/uv;
191 } else {
192 localcoord = (fixedVertexID == 0) ? p0.xy : p3.xy;
193 }
194 }
195 float2 vertexpos = AFFINE_MATRIX * localcoord + TRANSLATE;)");
196 gpArgs->fLocalCoordVar.set(kFloat2_GrSLType, "localcoord");
197 gpArgs->fPositionVar.set(kFloat2_GrSLType, "vertexpos");
198 if (middleOutShader.fAttribs & PatchAttribs::kColor) {
199 GrGLSLVarying colorVarying(GrSLType::kHalf4_GrSLType);
200 varyingHandler->addVarying("color",
201 &colorVarying,
202 GrGLSLVaryingHandler::Interpolation::kCanBeFlat);
203 v->codeAppendf("%s = colorAttrib;", colorVarying.vsOut());
204 fVaryingColorName = colorVarying.fsIn();
205 }
206 }
207 };
208 return std::make_unique<Impl>();
209 }
210
211 } // namespace
212
MakeMiddleOutFixedCountShader(const GrShaderCaps & shaderCaps,SkArenaAlloc * arena,const SkMatrix & viewMatrix,const SkPMColor4f & color,PatchAttribs attribs)213 GrPathTessellationShader* GrPathTessellationShader::MakeMiddleOutFixedCountShader(
214 const GrShaderCaps& shaderCaps,
215 SkArenaAlloc* arena,
216 const SkMatrix& viewMatrix,
217 const SkPMColor4f& color,
218 PatchAttribs attribs) {
219 // We should use explicit curve type when, and only when, there isn't infinity support.
220 // Otherwise the GPU can infer curve type based on infinity.
221 SkASSERT(shaderCaps.infinitySupport() != (attribs & PatchAttribs::kExplicitCurveType));
222 return arena->make<MiddleOutShader>(shaderCaps, viewMatrix, color, attribs);
223 }
224