1/*
2 * Copyright 2018 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 "src/gpu/ops/GrQuadPerEdgeAA.h"
9
10#include "include/private/SkVx.h"
11#include "src/gpu/SkGr.h"
12#include "src/gpu/geometry/GrQuadUtils.h"
13#include "src/gpu/glsl/GrGLSLColorSpaceXformHelper.h"
14#include "src/gpu/glsl/GrGLSLFragmentShaderBuilder.h"
15#include "src/gpu/glsl/GrGLSLGeometryProcessor.h"
16#include "src/gpu/glsl/GrGLSLPrimitiveProcessor.h"
17#include "src/gpu/glsl/GrGLSLVarying.h"
18#include "src/gpu/glsl/GrGLSLVertexGeoBuilder.h"
19
20static_assert((int)GrQuadAAFlags::kLeft == SkCanvas::kLeft_QuadAAFlag);
21static_assert((int)GrQuadAAFlags::kTop == SkCanvas::kTop_QuadAAFlag);
22static_assert((int)GrQuadAAFlags::kRight == SkCanvas::kRight_QuadAAFlag);
23static_assert((int)GrQuadAAFlags::kBottom == SkCanvas::kBottom_QuadAAFlag);
24static_assert((int)GrQuadAAFlags::kNone == SkCanvas::kNone_QuadAAFlags);
25static_assert((int)GrQuadAAFlags::kAll == SkCanvas::kAll_QuadAAFlags);
26
27namespace {
28
29// Generic WriteQuadProc that can handle any VertexSpec. It writes the 4 vertices in triangle strip
30// order, although the data per-vertex is dependent on the VertexSpec.
31static void write_quad_generic(GrVertexWriter* vb, const GrQuadPerEdgeAA::VertexSpec& spec,
32 const GrQuad* deviceQuad, const GrQuad* localQuad,
33 const float coverage[4], const SkPMColor4f& color,
34 const SkRect& geomSubset, const SkRect& texSubset) {
35 static constexpr auto If = GrVertexWriter::If<float>;
36
37 SkASSERT(!spec.hasLocalCoords() || localQuad);
38
39 GrQuadPerEdgeAA::CoverageMode mode = spec.coverageMode();
40 for (int i = 0; i < 4; ++i) {
41 // save position, this is a float2 or float3 or float4 depending on the combination of
42 // perspective and coverage mode.
43 vb->write(deviceQuad->x(i), deviceQuad->y(i),
44 If(spec.deviceQuadType() == GrQuad::Type::kPerspective, deviceQuad->w(i)),
45 If(mode == GrQuadPerEdgeAA::CoverageMode::kWithPosition, coverage[i]));
46
47 // save color
48 if (spec.hasVertexColors()) {
49 bool wide = spec.colorType() == GrQuadPerEdgeAA::ColorType::kFloat;
50 vb->write(GrVertexColor(
51 color * (mode == GrQuadPerEdgeAA::CoverageMode::kWithColor ? coverage[i] : 1.f),
52 wide));
53 }
54
55 // save local position
56 if (spec.hasLocalCoords()) {
57 vb->write(localQuad->x(i), localQuad->y(i),
58 If(spec.localQuadType() == GrQuad::Type::kPerspective, localQuad->w(i)));
59 }
60
61 // save the geometry subset
62 if (spec.requiresGeometrySubset()) {
63 vb->write(geomSubset);
64 }
65
66 // save the texture subset
67 if (spec.hasSubset()) {
68 vb->write(texSubset);
69 }
70 }
71}
72
73// Specialized WriteQuadProcs for particular VertexSpecs that show up frequently (determined
74// experimentally through recorded GMs, SKPs, and SVGs, as well as SkiaRenderer's usage patterns):
75
76// 2D (XY), no explicit coverage, vertex color, no locals, no geometry subset, no texture subsetn
77// This represents simple, solid color or shader, non-AA (or AA with cov. as alpha) rects.
78static void write_2d_color(GrVertexWriter* vb, const GrQuadPerEdgeAA::VertexSpec& spec,
79 const GrQuad* deviceQuad, const GrQuad* localQuad,
80 const float coverage[4], const SkPMColor4f& color,
81 const SkRect& geomSubset, const SkRect& texSubset) {
82 // Assert assumptions about VertexSpec
83 SkASSERT(spec.deviceQuadType() != GrQuad::Type::kPerspective);
84 SkASSERT(!spec.hasLocalCoords());
85 SkASSERT(spec.coverageMode() == GrQuadPerEdgeAA::CoverageMode::kNone ||
86 spec.coverageMode() == GrQuadPerEdgeAA::CoverageMode::kWithColor);
87 SkASSERT(spec.hasVertexColors());
88 SkASSERT(!spec.requiresGeometrySubset());
89 SkASSERT(!spec.hasSubset());
90 // We don't assert that localQuad == nullptr, since it is possible for GrFillRectOp to
91 // accumulate local coords conservatively (paint not trivial), and then after analysis realize
92 // the processors don't need local coordinates.
93
94 bool wide = spec.colorType() == GrQuadPerEdgeAA::ColorType::kFloat;
95 for (int i = 0; i < 4; ++i) {
96 // If this is not coverage-with-alpha, make sure coverage == 1 so it doesn't do anything
97 SkASSERT(spec.coverageMode() == GrQuadPerEdgeAA::CoverageMode::kWithColor ||
98 coverage[i] == 1.f);
99 vb->write(deviceQuad->x(i), deviceQuad->y(i), GrVertexColor(color * coverage[i], wide));
100 }
101}
102
103// 2D (XY), no explicit coverage, UV locals, no color, no geometry subset, no texture subset
104// This represents opaque, non AA, textured rects
105static void write_2d_uv(GrVertexWriter* vb, const GrQuadPerEdgeAA::VertexSpec& spec,
106 const GrQuad* deviceQuad, const GrQuad* localQuad,
107 const float coverage[4], const SkPMColor4f& color,
108 const SkRect& geomSubset, const SkRect& texSubset) {
109 // Assert assumptions about VertexSpec
110 SkASSERT(spec.deviceQuadType() != GrQuad::Type::kPerspective);
111 SkASSERT(spec.hasLocalCoords() && spec.localQuadType() != GrQuad::Type::kPerspective);
112 SkASSERT(spec.coverageMode() == GrQuadPerEdgeAA::CoverageMode::kNone);
113 SkASSERT(!spec.hasVertexColors());
114 SkASSERT(!spec.requiresGeometrySubset());
115 SkASSERT(!spec.hasSubset());
116 SkASSERT(localQuad);
117
118 for (int i = 0; i < 4; ++i) {
119 vb->write(deviceQuad->x(i), deviceQuad->y(i), localQuad->x(i), localQuad->y(i));
120 }
121}
122
123// 2D (XY), no explicit coverage, UV locals, vertex color, no geometry or texture subsets
124// This represents transparent, non AA (or AA with cov. as alpha), textured rects
125static void write_2d_color_uv(GrVertexWriter* vb, const GrQuadPerEdgeAA::VertexSpec& spec,
126 const GrQuad* deviceQuad, const GrQuad* localQuad,
127 const float coverage[4], const SkPMColor4f& color,
128 const SkRect& geomSubset, const SkRect& texSubset) {
129 // Assert assumptions about VertexSpec
130 SkASSERT(spec.deviceQuadType() != GrQuad::Type::kPerspective);
131 SkASSERT(spec.hasLocalCoords() && spec.localQuadType() != GrQuad::Type::kPerspective);
132 SkASSERT(spec.coverageMode() == GrQuadPerEdgeAA::CoverageMode::kNone ||
133 spec.coverageMode() == GrQuadPerEdgeAA::CoverageMode::kWithColor);
134 SkASSERT(spec.hasVertexColors());
135 SkASSERT(!spec.requiresGeometrySubset());
136 SkASSERT(!spec.hasSubset());
137 SkASSERT(localQuad);
138
139 bool wide = spec.colorType() == GrQuadPerEdgeAA::ColorType::kFloat;
140 for (int i = 0; i < 4; ++i) {
141 // If this is not coverage-with-alpha, make sure coverage == 1 so it doesn't do anything
142 SkASSERT(spec.coverageMode() == GrQuadPerEdgeAA::CoverageMode::kWithColor ||
143 coverage[i] == 1.f);
144 vb->write(deviceQuad->x(i), deviceQuad->y(i), GrVertexColor(color * coverage[i], wide),
145 localQuad->x(i), localQuad->y(i));
146 }
147}
148
149// 2D (XY), explicit coverage, UV locals, no color, no geometry subset, no texture subset
150// This represents opaque, AA, textured rects
151static void write_2d_cov_uv(GrVertexWriter* vb, const GrQuadPerEdgeAA::VertexSpec& spec,
152 const GrQuad* deviceQuad, const GrQuad* localQuad,
153 const float coverage[4], const SkPMColor4f& color,
154 const SkRect& geomSubset, const SkRect& texSubset) {
155 // Assert assumptions about VertexSpec
156 SkASSERT(spec.deviceQuadType() != GrQuad::Type::kPerspective);
157 SkASSERT(spec.hasLocalCoords() && spec.localQuadType() != GrQuad::Type::kPerspective);
158 SkASSERT(spec.coverageMode() == GrQuadPerEdgeAA::CoverageMode::kWithPosition);
159 SkASSERT(!spec.hasVertexColors());
160 SkASSERT(!spec.requiresGeometrySubset());
161 SkASSERT(!spec.hasSubset());
162 SkASSERT(localQuad);
163
164 for (int i = 0; i < 4; ++i) {
165 vb->write(deviceQuad->x(i), deviceQuad->y(i), coverage[i],
166 localQuad->x(i), localQuad->y(i));
167 }
168}
169
170// NOTE: The three _strict specializations below match the non-strict uv functions above, except
171// that they also write the UV subset. These are included to benefit SkiaRenderer, which must make
172// use of both fast and strict constrained subsets. When testing _strict was not that common across
173// GMS, SKPs, and SVGs but we have little visibility into actual SkiaRenderer statistics. If
174// SkiaRenderer can avoid subsets more, these 3 functions should probably be removed for simplicity.
175
176// 2D (XY), no explicit coverage, UV locals, no color, tex subset but no geometry subset
177// This represents opaque, non AA, textured rects with strict uv sampling
178static void write_2d_uv_strict(GrVertexWriter* vb, const GrQuadPerEdgeAA::VertexSpec& spec,
179 const GrQuad* deviceQuad, const GrQuad* localQuad,
180 const float coverage[4], const SkPMColor4f& color,
181 const SkRect& geomSubset, const SkRect& texSubset) {
182 // Assert assumptions about VertexSpec
183 SkASSERT(spec.deviceQuadType() != GrQuad::Type::kPerspective);
184 SkASSERT(spec.hasLocalCoords() && spec.localQuadType() != GrQuad::Type::kPerspective);
185 SkASSERT(spec.coverageMode() == GrQuadPerEdgeAA::CoverageMode::kNone);
186 SkASSERT(!spec.hasVertexColors());
187 SkASSERT(!spec.requiresGeometrySubset());
188 SkASSERT(spec.hasSubset());
189 SkASSERT(localQuad);
190
191 for (int i = 0; i < 4; ++i) {
192 vb->write(deviceQuad->x(i), deviceQuad->y(i), localQuad->x(i), localQuad->y(i), texSubset);
193 }
194}
195
196// 2D (XY), no explicit coverage, UV locals, vertex color, tex subset but no geometry subset
197// This represents transparent, non AA (or AA with cov. as alpha), textured rects with strict sample
198static void write_2d_color_uv_strict(GrVertexWriter* vb, const GrQuadPerEdgeAA::VertexSpec& spec,
199 const GrQuad* deviceQuad, const GrQuad* localQuad,
200 const float coverage[4], const SkPMColor4f& color,
201 const SkRect& geomSubset, const SkRect& texSubset) {
202 // Assert assumptions about VertexSpec
203 SkASSERT(spec.deviceQuadType() != GrQuad::Type::kPerspective);
204 SkASSERT(spec.hasLocalCoords() && spec.localQuadType() != GrQuad::Type::kPerspective);
205 SkASSERT(spec.coverageMode() == GrQuadPerEdgeAA::CoverageMode::kNone ||
206 spec.coverageMode() == GrQuadPerEdgeAA::CoverageMode::kWithColor);
207 SkASSERT(spec.hasVertexColors());
208 SkASSERT(!spec.requiresGeometrySubset());
209 SkASSERT(spec.hasSubset());
210 SkASSERT(localQuad);
211
212 bool wide = spec.colorType() == GrQuadPerEdgeAA::ColorType::kFloat;
213 for (int i = 0; i < 4; ++i) {
214 // If this is not coverage-with-alpha, make sure coverage == 1 so it doesn't do anything
215 SkASSERT(spec.coverageMode() == GrQuadPerEdgeAA::CoverageMode::kWithColor ||
216 coverage[i] == 1.f);
217 vb->write(deviceQuad->x(i), deviceQuad->y(i), GrVertexColor(color * coverage[i], wide),
218 localQuad->x(i), localQuad->y(i), texSubset);
219 }
220}
221
222// 2D (XY), explicit coverage, UV locals, no color, tex subset but no geometry subset
223// This represents opaque, AA, textured rects with strict uv sampling
224static void write_2d_cov_uv_strict(GrVertexWriter* vb, const GrQuadPerEdgeAA::VertexSpec& spec,
225 const GrQuad* deviceQuad, const GrQuad* localQuad,
226 const float coverage[4], const SkPMColor4f& color,
227 const SkRect& geomSubset, const SkRect& texSubset) {
228 // Assert assumptions about VertexSpec
229 SkASSERT(spec.deviceQuadType() != GrQuad::Type::kPerspective);
230 SkASSERT(spec.hasLocalCoords() && spec.localQuadType() != GrQuad::Type::kPerspective);
231 SkASSERT(spec.coverageMode() == GrQuadPerEdgeAA::CoverageMode::kWithPosition);
232 SkASSERT(!spec.hasVertexColors());
233 SkASSERT(!spec.requiresGeometrySubset());
234 SkASSERT(spec.hasSubset());
235 SkASSERT(localQuad);
236
237 for (int i = 0; i < 4; ++i) {
238 vb->write(deviceQuad->x(i), deviceQuad->y(i), coverage[i],
239 localQuad->x(i), localQuad->y(i), texSubset);
240 }
241}
242
243} // anonymous namespace
244
245namespace GrQuadPerEdgeAA {
246
247IndexBufferOption CalcIndexBufferOption(GrAAType aa, int numQuads) {
248 if (aa == GrAAType::kCoverage) {
249 return IndexBufferOption::kPictureFramed;
250 } else if (numQuads > 1) {
251 return IndexBufferOption::kIndexedRects;
252 } else {
253 return IndexBufferOption::kTriStrips;
254 }
255}
256
257// This is a more elaborate version of fitsInBytes() that allows "no color" for white
258ColorType MinColorType(SkPMColor4f color) {
259 if (color == SK_PMColor4fWHITE) {
260 return ColorType::kNone;
261 } else {
262 return color.fitsInBytes() ? ColorType::kByte : ColorType::kFloat;
263 }
264}
265
266////////////////// Tessellator Implementation
267
268Tessellator::WriteQuadProc Tessellator::GetWriteQuadProc(const VertexSpec& spec) {
269 // All specialized writing functions requires 2D geometry and no geometry subset. This is not
270 // the same as just checking device type vs. kRectilinear since non-AA general 2D quads do not
271 // require a geometry subset and could then go through a fast path.
272 if (spec.deviceQuadType() != GrQuad::Type::kPerspective && !spec.requiresGeometrySubset()) {
273 CoverageMode mode = spec.coverageMode();
274 if (spec.hasVertexColors()) {
275 if (mode != CoverageMode::kWithPosition) {
276 // Vertex colors, but no explicit coverage
277 if (!spec.hasLocalCoords()) {
278 // Non-UV with vertex colors (possibly with coverage folded into alpha)
279 return write_2d_color;
280 } else if (spec.localQuadType() != GrQuad::Type::kPerspective) {
281 // UV locals with vertex colors (possibly with coverage-as-alpha)
282 return spec.hasSubset() ? write_2d_color_uv_strict : write_2d_color_uv;
283 }
284 }
285 // Else fall through; this is a spec that requires vertex colors and explicit coverage,
286 // which means it's anti-aliased and the FPs don't support coverage as alpha, or
287 // it uses 3D local coordinates.
288 } else if (spec.hasLocalCoords() && spec.localQuadType() != GrQuad::Type::kPerspective) {
289 if (mode == CoverageMode::kWithPosition) {
290 // UV locals with explicit coverage
291 return spec.hasSubset() ? write_2d_cov_uv_strict : write_2d_cov_uv;
292 } else {
293 SkASSERT(mode == CoverageMode::kNone);
294 return spec.hasSubset() ? write_2d_uv_strict : write_2d_uv;
295 }
296 }
297 // Else fall through to generic vertex function; this is a spec that has no vertex colors
298 // and [no|uvr] local coords, which doesn't happen often enough to warrant specialization.
299 }
300
301 // Arbitrary spec hits the slow path
302 return write_quad_generic;
303}
304
305Tessellator::Tessellator(const VertexSpec& spec, char* vertices)
306 : fVertexSpec(spec)
307 , fVertexWriter{vertices}
308 , fWriteProc(Tessellator::GetWriteQuadProc(spec)) {}
309
310void Tessellator::append(GrQuad* deviceQuad, GrQuad* localQuad,
311 const SkPMColor4f& color, const SkRect& uvSubset, GrQuadAAFlags aaFlags) {
312 // We allow Tessellator to be created with a null vertices pointer for convenience, but it is
313 // assumed it will never actually be used in those cases.
314 SkASSERT(fVertexWriter.fPtr);
315 SkASSERT(deviceQuad->quadType() <= fVertexSpec.deviceQuadType());
316 SkASSERT(localQuad || !fVertexSpec.hasLocalCoords());
317 SkASSERT(!fVertexSpec.hasLocalCoords() || localQuad->quadType() <= fVertexSpec.localQuadType());
318
319 static const float kFullCoverage[4] = {1.f, 1.f, 1.f, 1.f};
320 static const float kZeroCoverage[4] = {0.f, 0.f, 0.f, 0.f};
321 static const SkRect kIgnoredSubset = SkRect::MakeEmpty();
322
323 if (fVertexSpec.usesCoverageAA()) {
324 SkASSERT(fVertexSpec.coverageMode() == CoverageMode::kWithColor ||
325 fVertexSpec.coverageMode() == CoverageMode::kWithPosition);
326 // Must calculate inner and outer quadrilaterals for the vertex coverage ramps, and possibly
327 // a geometry subset if corners are not right angles
328 SkRect geomSubset;
329 if (fVertexSpec.requiresGeometrySubset()) {
330 geomSubset = deviceQuad->bounds();
331 geomSubset.outset(0.5f, 0.5f); // account for AA expansion
332 }
333
334 if (aaFlags == GrQuadAAFlags::kNone) {
335 // Have to write the coverage AA vertex structure, but there's no math to be done for a
336 // non-aa quad batched into a coverage AA op.
337 fWriteProc(&fVertexWriter, fVertexSpec, deviceQuad, localQuad, kFullCoverage, color,
338 geomSubset, uvSubset);
339 // Since we pass the same corners in, the outer vertex structure will have 0 area and
340 // the coverage interpolation from 1 to 0 will not be visible.
341 fWriteProc(&fVertexWriter, fVertexSpec, deviceQuad, localQuad, kZeroCoverage, color,
342 geomSubset, uvSubset);
343 } else {
344 // Reset the tessellation helper to match the current geometry
345 fAAHelper.reset(*deviceQuad, localQuad);
346
347 // Edge inset/outset distance ordered LBTR, set to 0.5 for a half pixel if the AA flag
348 // is turned on, or 0.0 if the edge is not anti-aliased.
349 skvx::Vec<4, float> edgeDistances;
350 if (aaFlags == GrQuadAAFlags::kAll) {
351 edgeDistances = 0.5f;
352 } else {
353 edgeDistances = { (aaFlags & GrQuadAAFlags::kLeft) ? 0.5f : 0.f,
354 (aaFlags & GrQuadAAFlags::kBottom) ? 0.5f : 0.f,
355 (aaFlags & GrQuadAAFlags::kTop) ? 0.5f : 0.f,
356 (aaFlags & GrQuadAAFlags::kRight) ? 0.5f : 0.f };
357 }
358
359 // Write inner vertices first
360 float coverage[4];
361 fAAHelper.inset(edgeDistances, deviceQuad, localQuad).store(coverage);
362 fWriteProc(&fVertexWriter, fVertexSpec, deviceQuad, localQuad, coverage, color,
363 geomSubset, uvSubset);
364
365 // Then outer vertices, which use 0.f for their coverage
366 fAAHelper.outset(edgeDistances, deviceQuad, localQuad);
367 fWriteProc(&fVertexWriter, fVertexSpec, deviceQuad, localQuad, kZeroCoverage, color,
368 geomSubset, uvSubset);
369 }
370 } else {
371 // No outsetting needed, just write a single quad with full coverage
372 SkASSERT(fVertexSpec.coverageMode() == CoverageMode::kNone &&
373 !fVertexSpec.requiresGeometrySubset());
374 fWriteProc(&fVertexWriter, fVertexSpec, deviceQuad, localQuad, kFullCoverage, color,
375 kIgnoredSubset, uvSubset);
376 }
377}
378
379sk_sp<const GrBuffer> GetIndexBuffer(GrMeshDrawOp::Target* target,
380 IndexBufferOption indexBufferOption) {
381 auto resourceProvider = target->resourceProvider();
382
383 switch (indexBufferOption) {
384 case IndexBufferOption::kPictureFramed: return resourceProvider->refAAQuadIndexBuffer();
385 case IndexBufferOption::kIndexedRects: return resourceProvider->refNonAAQuadIndexBuffer();
386 case IndexBufferOption::kTriStrips: // fall through
387 default: return nullptr;
388 }
389}
390
391int QuadLimit(IndexBufferOption option) {
392 switch (option) {
393 case IndexBufferOption::kPictureFramed: return GrResourceProvider::MaxNumAAQuads();
394 case IndexBufferOption::kIndexedRects: return GrResourceProvider::MaxNumNonAAQuads();
395 case IndexBufferOption::kTriStrips: return SK_MaxS32; // not limited by an indexBuffer
396 }
397
398 SkUNREACHABLE;
399}
400
401void IssueDraw(const GrCaps& caps, GrOpsRenderPass* renderPass, const VertexSpec& spec,
402 int runningQuadCount, int quadsInDraw, int maxVerts, int absVertBufferOffset) {
403 if (spec.indexBufferOption() == IndexBufferOption::kTriStrips) {
404 int offset = absVertBufferOffset +
405 runningQuadCount * GrResourceProvider::NumVertsPerNonAAQuad();
406 renderPass->draw(4, offset);
407 return;
408 }
409
410 SkASSERT(spec.indexBufferOption() == IndexBufferOption::kPictureFramed ||
411 spec.indexBufferOption() == IndexBufferOption::kIndexedRects);
412
413 int maxNumQuads, numIndicesPerQuad, numVertsPerQuad;
414
415 if (spec.indexBufferOption() == IndexBufferOption::kPictureFramed) {
416 // AA uses 8 vertices and 30 indices per quad, basically nested rectangles
417 maxNumQuads = GrResourceProvider::MaxNumAAQuads();
418 numIndicesPerQuad = GrResourceProvider::NumIndicesPerAAQuad();
419 numVertsPerQuad = GrResourceProvider::NumVertsPerAAQuad();
420 } else {
421 // Non-AA uses 4 vertices and 6 indices per quad
422 maxNumQuads = GrResourceProvider::MaxNumNonAAQuads();
423 numIndicesPerQuad = GrResourceProvider::NumIndicesPerNonAAQuad();
424 numVertsPerQuad = GrResourceProvider::NumVertsPerNonAAQuad();
425 }
426
427 SkASSERT(runningQuadCount + quadsInDraw <= maxNumQuads);
428
429 if (caps.avoidLargeIndexBufferDraws()) {
430 // When we need to avoid large index buffer draws we modify the base vertex of the draw
431 // which, in GL, requires rebinding all vertex attrib arrays, so a base index is generally
432 // preferred.
433 int offset = absVertBufferOffset + runningQuadCount * numVertsPerQuad;
434
435 renderPass->drawIndexPattern(numIndicesPerQuad, quadsInDraw, maxNumQuads, numVertsPerQuad,
436 offset);
437 } else {
438 int baseIndex = runningQuadCount * numIndicesPerQuad;
439 int numIndicesToDraw = quadsInDraw * numIndicesPerQuad;
440
441 int minVertex = runningQuadCount * numVertsPerQuad;
442 int maxVertex = (runningQuadCount + quadsInDraw) * numVertsPerQuad;
443
444 renderPass->drawIndexed(numIndicesToDraw, baseIndex, minVertex, maxVertex,
445 absVertBufferOffset);
446 }
447}
448
449////////////////// VertexSpec Implementation
450
451int VertexSpec::deviceDimensionality() const {
452 return this->deviceQuadType() == GrQuad::Type::kPerspective ? 3 : 2;
453}
454
455int VertexSpec::localDimensionality() const {
456 return fHasLocalCoords ? (this->localQuadType() == GrQuad::Type::kPerspective ? 3 : 2) : 0;
457}
458
459CoverageMode VertexSpec::coverageMode() const {
460 if (this->usesCoverageAA()) {
461 if (this->compatibleWithCoverageAsAlpha() && this->hasVertexColors() &&
462 !this->requiresGeometrySubset()) {
463 // Using a geometric subset acts as a second source of coverage and folding
464 // the original coverage into color makes it impossible to apply the color's
465 // alpha to the geometric subset's coverage when the original shape is clipped.
466 return CoverageMode::kWithColor;
467 } else {
468 return CoverageMode::kWithPosition;
469 }
470 } else {
471 return CoverageMode::kNone;
472 }
473}
474
475// This needs to stay in sync w/ QuadPerEdgeAAGeometryProcessor::initializeAttrs
476size_t VertexSpec::vertexSize() const {
477 bool needsPerspective = (this->deviceDimensionality() == 3);
478 CoverageMode coverageMode = this->coverageMode();
479
480 size_t count = 0;
481
482 if (coverageMode == CoverageMode::kWithPosition) {
483 if (needsPerspective) {
484 count += GrVertexAttribTypeSize(kFloat4_GrVertexAttribType);
485 } else {
486 count += GrVertexAttribTypeSize(kFloat2_GrVertexAttribType) +
487 GrVertexAttribTypeSize(kFloat_GrVertexAttribType);
488 }
489 } else {
490 if (needsPerspective) {
491 count += GrVertexAttribTypeSize(kFloat3_GrVertexAttribType);
492 } else {
493 count += GrVertexAttribTypeSize(kFloat2_GrVertexAttribType);
494 }
495 }
496
497 if (this->requiresGeometrySubset()) {
498 count += GrVertexAttribTypeSize(kFloat4_GrVertexAttribType);
499 }
500
501 count += this->localDimensionality() * GrVertexAttribTypeSize(kFloat_GrVertexAttribType);
502
503 if (ColorType::kByte == this->colorType()) {
504 count += GrVertexAttribTypeSize(kUByte4_norm_GrVertexAttribType);
505 } else if (ColorType::kFloat == this->colorType()) {
506 count += GrVertexAttribTypeSize(kFloat4_GrVertexAttribType);
507 }
508
509 if (this->hasSubset()) {
510 count += GrVertexAttribTypeSize(kFloat4_GrVertexAttribType);
511 }
512
513 return count;
514}
515
516////////////////// Geometry Processor Implementation
517
518class QuadPerEdgeAAGeometryProcessor : public GrGeometryProcessor {
519public:
520 using Saturate = GrTextureOp::Saturate;
521
522 static GrGeometryProcessor* Make(SkArenaAlloc* arena, const VertexSpec& spec) {
523 return arena->make<QuadPerEdgeAAGeometryProcessor>(spec);
524 }
525
526 static GrGeometryProcessor* Make(SkArenaAlloc* arena,
527 const VertexSpec& vertexSpec,
528 const GrShaderCaps& caps,
529 const GrBackendFormat& backendFormat,
530 GrSamplerState samplerState,
531 const GrSwizzle& swizzle,
532 sk_sp<GrColorSpaceXform> textureColorSpaceXform,
533 Saturate saturate) {
534 return arena->make<QuadPerEdgeAAGeometryProcessor>(
535 vertexSpec, caps, backendFormat, samplerState, swizzle,
536 std::move(textureColorSpaceXform), saturate);
537 }
538
539 const char* name() const override { return "QuadPerEdgeAAGeometryProcessor"; }
540
541 void getGLSLProcessorKey(const GrShaderCaps&, GrProcessorKeyBuilder* b) const override {
542 // texturing, device-dimensions are single bit flags
543 uint32_t x = (fTexSubset.isInitialized() ? 0 : 0x1)
544 | (fSampler.isInitialized() ? 0 : 0x2)
545 | (fNeedsPerspective ? 0 : 0x4)
546 | (fSaturate == Saturate::kNo ? 0 : 0x8);
547 // local coords require 2 bits (3 choices), 00 for none, 01 for 2d, 10 for 3d
548 if (fLocalCoord.isInitialized()) {
549 x |= kFloat3_GrVertexAttribType == fLocalCoord.cpuType() ? 0x10 : 0x20;
550 }
551 // similar for colors, 00 for none, 01 for bytes, 10 for half-floats
552 if (fColor.isInitialized()) {
553 x |= kUByte4_norm_GrVertexAttribType == fColor.cpuType() ? 0x40 : 0x80;
554 }
555 // and coverage mode, 00 for none, 01 for withposition, 10 for withcolor, 11 for
556 // position+geomsubset
557 SkASSERT(!fGeomSubset.isInitialized() || fCoverageMode == CoverageMode::kWithPosition);
558 if (fCoverageMode != CoverageMode::kNone) {
559 x |= fGeomSubset.isInitialized()
560 ? 0x300
561 : (CoverageMode::kWithPosition == fCoverageMode ? 0x100 : 0x200);
562 }
563
564 b->add32(GrColorSpaceXform::XformKey(fTextureColorSpaceXform.get()));
565 b->add32(x);
566 }
567
568 GrGLSLPrimitiveProcessor* createGLSLInstance(const GrShaderCaps& caps) const override {
569 class GLSLProcessor : public GrGLSLGeometryProcessor {
570 public:
571 void setData(const GrGLSLProgramDataManager& pdman,
572 const GrPrimitiveProcessor& proc) override {
573 const auto& gp = proc.cast<QuadPerEdgeAAGeometryProcessor>();
574 fTextureColorSpaceXformHelper.setData(pdman, gp.fTextureColorSpaceXform.get());
575 }
576
577 private:
578 void onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) override {
579 using Interpolation = GrGLSLVaryingHandler::Interpolation;
580
581 const auto& gp = args.fGP.cast<QuadPerEdgeAAGeometryProcessor>();
582 fTextureColorSpaceXformHelper.emitCode(args.fUniformHandler,
583 gp.fTextureColorSpaceXform.get());
584
585 args.fVaryingHandler->emitAttributes(gp);
586
587 if (gp.fCoverageMode == CoverageMode::kWithPosition) {
588 // Strip last channel from the vertex attribute to remove coverage and get the
589 // actual position
590 if (gp.fNeedsPerspective) {
591 args.fVertBuilder->codeAppendf("float3 position = %s.xyz;",
592 gp.fPosition.name());
593 } else {
594 args.fVertBuilder->codeAppendf("float2 position = %s.xy;",
595 gp.fPosition.name());
596 }
597 gpArgs->fPositionVar = {"position",
598 gp.fNeedsPerspective ? kFloat3_GrSLType
599 : kFloat2_GrSLType,
600 GrShaderVar::TypeModifier::None};
601 } else {
602 // No coverage to eliminate
603 gpArgs->fPositionVar = gp.fPosition.asShaderVar();
604 }
605
606 // This attribute will be uninitialized if earlier FP analysis determined no
607 // local coordinates are needed (and this will not include the inline texture
608 // fetch this GP does before invoking FPs).
609 gpArgs->fLocalCoordVar = gp.fLocalCoord.asShaderVar();
610
611 // Solid color before any texturing gets modulated in
612 if (gp.fColor.isInitialized()) {
613 SkASSERT(gp.fCoverageMode != CoverageMode::kWithColor || !gp.fNeedsPerspective);
614 // The color cannot be flat if the varying coverage has been modulated into it
615 args.fVaryingHandler->addPassThroughAttribute(gp.fColor, args.fOutputColor,
616 gp.fCoverageMode == CoverageMode::kWithColor ?
617 Interpolation::kInterpolated : Interpolation::kCanBeFlat);
618 } else {
619 // Output color must be initialized to something
620 args.fFragBuilder->codeAppendf("%s = half4(1);", args.fOutputColor);
621 }
622
623 // If there is a texture, must also handle texture coordinates and reading from
624 // the texture in the fragment shader before continuing to fragment processors.
625 if (gp.fSampler.isInitialized()) {
626 // Texture coordinates clamped by the subset on the fragment shader; if the GP
627 // has a texture, it's guaranteed to have local coordinates
628 args.fFragBuilder->codeAppend("float2 texCoord;");
629 if (gp.fLocalCoord.cpuType() == kFloat3_GrVertexAttribType) {
630 // Can't do a pass through since we need to perform perspective division
631 GrGLSLVarying v(gp.fLocalCoord.gpuType());
632 args.fVaryingHandler->addVarying(gp.fLocalCoord.name(), &v);
633 args.fVertBuilder->codeAppendf("%s = %s;",
634 v.vsOut(), gp.fLocalCoord.name());
635 args.fFragBuilder->codeAppendf("texCoord = %s.xy / %s.z;",
636 v.fsIn(), v.fsIn());
637 } else {
638 args.fVaryingHandler->addPassThroughAttribute(gp.fLocalCoord, "texCoord");
639 }
640
641 // Clamp the now 2D localCoordName variable by the subset if it is provided
642 if (gp.fTexSubset.isInitialized()) {
643 args.fFragBuilder->codeAppend("float4 subset;");
644 args.fVaryingHandler->addPassThroughAttribute(gp.fTexSubset, "subset",
645 Interpolation::kCanBeFlat);
646 args.fFragBuilder->codeAppend(
647 "texCoord = clamp(texCoord, subset.xy, subset.zw);");
648 }
649
650 // Now modulate the starting output color by the texture lookup
651 args.fFragBuilder->codeAppendf("%s = ", args.fOutputColor);
652 args.fFragBuilder->appendTextureLookupAndBlend(
653 args.fOutputColor, SkBlendMode::kModulate, args.fTexSamplers[0],
654 "texCoord", &fTextureColorSpaceXformHelper);
655 args.fFragBuilder->codeAppend(";");
656 if (gp.fSaturate == Saturate::kYes) {
657 args.fFragBuilder->codeAppendf("%s = saturate(%s);",
658 args.fOutputColor, args.fOutputColor);
659 }
660 } else {
661 // Saturate is only intended for use with a proxy to account for the fact
662 // that GrTextureOp skips SkPaint conversion, which normally handles this.
663 SkASSERT(gp.fSaturate == Saturate::kNo);
664 }
665
666 // And lastly, output the coverage calculation code
667 if (gp.fCoverageMode == CoverageMode::kWithPosition) {
668 GrGLSLVarying coverage(kFloat_GrSLType);
669 args.fVaryingHandler->addVarying("coverage", &coverage);
670 if (gp.fNeedsPerspective) {
671 // Multiply by "W" in the vertex shader, then by 1/w (sk_FragCoord.w) in
672 // the fragment shader to get screen-space linear coverage.
673 args.fVertBuilder->codeAppendf("%s = %s.w * %s.z;",
674 coverage.vsOut(), gp.fPosition.name(),
675 gp.fPosition.name());
676 args.fFragBuilder->codeAppendf("float coverage = %s * sk_FragCoord.w;",
677 coverage.fsIn());
678 } else {
679 args.fVertBuilder->codeAppendf("%s = %s;",
680 coverage.vsOut(), gp.fCoverage.name());
681 args.fFragBuilder->codeAppendf("float coverage = %s;", coverage.fsIn());
682 }
683
684 if (gp.fGeomSubset.isInitialized()) {
685 // Calculate distance from sk_FragCoord to the 4 edges of the subset
686 // and clamp them to (0, 1). Use the minimum of these and the original
687 // coverage. This only has to be done in the exterior triangles, the
688 // interior of the quad geometry can never be clipped by the subset box.
689 args.fFragBuilder->codeAppend("float4 geoSubset;");
690 args.fVaryingHandler->addPassThroughAttribute(gp.fGeomSubset, "geoSubset",
691 Interpolation::kCanBeFlat);
692 args.fFragBuilder->codeAppend(
693 "if (coverage < 0.5) {"
694 " float4 dists4 = clamp(float4(1, 1, -1, -1) * "
695 "(sk_FragCoord.xyxy - geoSubset), 0, 1);"
696 " float2 dists2 = dists4.xy * dists4.zw;"
697 " coverage = min(coverage, dists2.x * dists2.y);"
698 "}");
699 }
700
701 args.fFragBuilder->codeAppendf("%s = half4(half(coverage));",
702 args.fOutputCoverage);
703 } else {
704 // Set coverage to 1, since it's either non-AA or the coverage was already
705 // folded into the output color
706 SkASSERT(!gp.fGeomSubset.isInitialized());
707 args.fFragBuilder->codeAppendf("%s = half4(1);", args.fOutputCoverage);
708 }
709 }
710 GrGLSLColorSpaceXformHelper fTextureColorSpaceXformHelper;
711 };
712 return new GLSLProcessor;
713 }
714
715private:
716 friend class ::SkArenaAlloc; // for access to ctor
717
718 QuadPerEdgeAAGeometryProcessor(const VertexSpec& spec)
719 : INHERITED(kQuadPerEdgeAAGeometryProcessor_ClassID)
720 , fTextureColorSpaceXform(nullptr) {
721 SkASSERT(!spec.hasSubset());
722 this->initializeAttrs(spec);
723 this->setTextureSamplerCnt(0);
724 }
725
726 QuadPerEdgeAAGeometryProcessor(const VertexSpec& spec,
727 const GrShaderCaps& caps,
728 const GrBackendFormat& backendFormat,
729 GrSamplerState samplerState,
730 const GrSwizzle& swizzle,
731 sk_sp<GrColorSpaceXform> textureColorSpaceXform,
732 Saturate saturate)
733 : INHERITED(kQuadPerEdgeAAGeometryProcessor_ClassID)
734 , fSaturate(saturate)
735 , fTextureColorSpaceXform(std::move(textureColorSpaceXform))
736 , fSampler(samplerState, backendFormat, swizzle) {
737 SkASSERT(spec.hasLocalCoords());
738 this->initializeAttrs(spec);
739 this->setTextureSamplerCnt(1);
740 }
741
742 // This needs to stay in sync w/ VertexSpec::vertexSize
743 void initializeAttrs(const VertexSpec& spec) {
744 fNeedsPerspective = spec.deviceDimensionality() == 3;
745 fCoverageMode = spec.coverageMode();
746
747 if (fCoverageMode == CoverageMode::kWithPosition) {
748 if (fNeedsPerspective) {
749 fPosition = {"positionWithCoverage", kFloat4_GrVertexAttribType, kFloat4_GrSLType};
750 } else {
751 fPosition = {"position", kFloat2_GrVertexAttribType, kFloat2_GrSLType};
752 fCoverage = {"coverage", kFloat_GrVertexAttribType, kFloat_GrSLType};
753 }
754 } else {
755 if (fNeedsPerspective) {
756 fPosition = {"position", kFloat3_GrVertexAttribType, kFloat3_GrSLType};
757 } else {
758 fPosition = {"position", kFloat2_GrVertexAttribType, kFloat2_GrSLType};
759 }
760 }
761
762 // Need a geometry subset when the quads are AA and not rectilinear, since their AA
763 // outsetting can go beyond a half pixel.
764 if (spec.requiresGeometrySubset()) {
765 fGeomSubset = {"geomSubset", kFloat4_GrVertexAttribType, kFloat4_GrSLType};
766 }
767
768 int localDim = spec.localDimensionality();
769 if (localDim == 3) {
770 fLocalCoord = {"localCoord", kFloat3_GrVertexAttribType, kFloat3_GrSLType};
771 } else if (localDim == 2) {
772 fLocalCoord = {"localCoord", kFloat2_GrVertexAttribType, kFloat2_GrSLType};
773 } // else localDim == 0 and attribute remains uninitialized
774
775 if (spec.hasVertexColors()) {
776 fColor = MakeColorAttribute("color", ColorType::kFloat == spec.colorType());
777 }
778
779 if (spec.hasSubset()) {
780 fTexSubset = {"texSubset", kFloat4_GrVertexAttribType, kFloat4_GrSLType};
781 }
782
783 this->setVertexAttributes(&fPosition, 6);
784 }
785
786 const TextureSampler& onTextureSampler(int) const override { return fSampler; }
787
788 Attribute fPosition; // May contain coverage as last channel
789 Attribute fCoverage; // Used for non-perspective position to avoid Intel Metal issues
790 Attribute fColor; // May have coverage modulated in if the FPs support it
791 Attribute fLocalCoord;
792 Attribute fGeomSubset; // Screen-space bounding box on geometry+aa outset
793 Attribute fTexSubset; // Texture-space bounding box on local coords
794
795 // The positions attribute may have coverage built into it, so float3 is an ambiguous type
796 // and may mean 2d with coverage, or 3d with no coverage
797 bool fNeedsPerspective;
798 // Should saturate() be called on the color? Only relevant when created with a texture.
799 Saturate fSaturate = Saturate::kNo;
800 CoverageMode fCoverageMode;
801
802 // Color space will be null and fSampler.isInitialized() returns false when the GP is configured
803 // to skip texturing.
804 sk_sp<GrColorSpaceXform> fTextureColorSpaceXform;
805 TextureSampler fSampler;
806
807 typedef GrGeometryProcessor INHERITED;
808};
809
810GrGeometryProcessor* MakeProcessor(SkArenaAlloc* arena, const VertexSpec& spec) {
811 return QuadPerEdgeAAGeometryProcessor::Make(arena, spec);
812}
813
814GrGeometryProcessor* MakeTexturedProcessor(SkArenaAlloc* arena,
815 const VertexSpec& spec,
816 const GrShaderCaps& caps,
817 const GrBackendFormat& backendFormat,
818 GrSamplerState samplerState,
819 const GrSwizzle& swizzle,
820 sk_sp<GrColorSpaceXform> textureColorSpaceXform,
821 Saturate saturate) {
822 return QuadPerEdgeAAGeometryProcessor::Make(arena, spec, caps, backendFormat, samplerState,
823 swizzle, std::move(textureColorSpaceXform),
824 saturate);
825}
826
827} // namespace GrQuadPerEdgeAA
828