Debian Codegraph @

src/gpu/graphite/render/AnalyticRRectRenderStep.cpp

raw
1 /*
2 * Copyright 2022 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/graphite/render/AnalyticRRectRenderStep.h"
9
10 #include "include/core/SkM44.h"
11 #include "include/core/SkPaint.h"
12 #include "include/core/SkRRect.h"
13 #include "include/core/SkScalar.h"
14 #include "include/private/base/SkAssert.h"
15 #include "include/private/base/SkDebug.h"
16 #include "include/private/base/SkFloatingPoint.h"
17 #include "include/private/base/SkPoint_impl.h"
18 #include "src/base/SkEnumBitMask.h"
19 #include "src/base/SkVx.h"
20 #include "src/core/SkRRectPriv.h"
21 #include "src/core/SkSLTypeShared.h"
22 #include "src/gpu/BufferWriter.h"
23 #include "src/gpu/graphite/Attribute.h"
24 #include "src/gpu/graphite/BufferManager.h"
25 #include "src/gpu/graphite/DrawOrder.h"
26 #include "src/gpu/graphite/DrawParams.h"
27 #include "src/gpu/graphite/DrawTypes.h"
28 #include "src/gpu/graphite/DrawWriter.h"
29 #include "src/gpu/graphite/PipelineData.h"
30 #include "src/gpu/graphite/geom/EdgeAAQuad.h"
31 #include "src/gpu/graphite/geom/Geometry.h"
32 #include "src/gpu/graphite/geom/Rect.h"
33 #include "src/gpu/graphite/geom/Shape.h"
34 #include "src/gpu/graphite/geom/Transform.h"
35 #include "src/gpu/graphite/render/CommonDepthStencilSettings.h"
36
37 #include <array>
38 #include <cstdint>
39
40 // This RenderStep is flexible and can draw filled rectangles, filled quadrilaterals with per-edge
41 // AA, filled rounded rectangles with arbitrary corner radii, stroked rectangles with any join,
42 // stroked lines with any cap, stroked rounded rectangles with circular corners (each corner can be
43 // different or square), hairline rectangles, hairline lines, and hairline rounded rectangles with
44 // arbitrary corners.
45 //
46 // We combine all of these together to maximize batching across simple geometric draws and reduce
47 // the number pipeline specializations. Additionally, these primitives are the most common
48 // operations and help us avoid triggering MSAA.
49 //
50 // Each of these "primitives" is represented by a single instance. The instance attributes are
51 // flexible enough to describe any of the above shapes without relying on uniforms to define its
52 // operation. The attributes encode shape as follows:
53 //
54 // float4 xRadiiOrFlags - if any components is > 0, the instance represents a filled round rect
55 // with elliptical corners and these values specify the X radii in top-left CW order.
56 // Otherwise, if .x < -1, the instance represents a stroked or hairline [round] rect or line,
57 // where .y differentiates hairline vs. stroke. If .y is negative, then it is a hairline [round]
58 // rect and xRadiiOrFlags stores (-2 - X radii); if .y is zero, it is a regular stroked [round]
59 // rect; if .y is positive, then it is a stroked *or* hairline line. For .y >= 0, .z holds the
60 // stroke radius and .w stores the join limit (matching StrokeStyle's conventions).
61 // Lastly, if -1 <= .x <= 0, it's a filled quadrilateral with per-edge AA defined by each by the
62 // component: aa != 0.
63 // float4 radiiOrQuadXs - if in filled round rect or hairline [round] rect mode, these values
64 // provide the Y radii in top-left CW order. If in stroked [round] rect mode, these values
65 // provide the circular corner radii (same order). Otherwise, when in per-edge quad mode, these
66 // values provide the X coordinates of the quadrilateral (same order).
67 // float4 ltrbOrQuadYs - if in filled round rect mode or stroked [round] rect mode, these values
68 // define the LTRB edge coordinates of the rectangle surrounding the round rect (or the
69 // rect itself when the radii are 0s). In stroked line mode, LTRB is treated as (x0,y0) and
70 // (x1,y1) that defines the line. Otherwise, in per-edge quad mode, these values provide
71 // the Y coordinates of the quadrilateral.
72 //
73 // From the other direction, shapes produce instance values like:
74 // - filled rect: [-1 -1 -1 -1] [L R R L] [T T B B]
75 // - stroked rect: [-2 0 stroke join] [0 0 0 0] [L T R B]
76 // - hairline rect: [-2 -2 -2 -2] [0 0 0 0] [L T R B]
77 // - filled rrect: [xRadii(tl,tr,br,bl)] [yRadii(tl,tr,br,bl)] [L T R B]
78 // - stroked rrect: [-2 0 stroke join] [radii(tl,tr,br,bl)] [L T R B]
79 // - hairline rrect: [-2-xRadii(tl,tr,br,bl)] [radii(tl,tr,br,bl)] [L T R B]
80 // - filled line: N/A, discarded higher in the stack
81 // - stroked line: [-2 1 stroke cap] [0 0 0 0] [x0,y0,x1,y1]
82 // - hairline line: [-2 1 0 1] [0 0 0 0] [x0,y0,x1,y1]
83 // - per-edge quad: [aa(t,r,b,l) ? -1 : 0] [xs(tl,tr,br,bl)] [ys(tl,tr,br,bl)]
84 //
85 // This encoding relies on the fact that a valid SkRRect with all x radii equal to 0 must have
86 // y radii equal to 0 (so it's a rectangle and we can treat it as a quadrilateral with
87 // all edges AA'ed). This avoids other encodings' inability to represent a quad with all edges
88 // anti-aliased (e.g. checking for negatives in xRadiiOrFlags to turn on per-edge mode).
89 //
90 // From this encoding, data can be unpacked for each corner, which are equivalent under
91 // rotational symmetry. A corner can have an outer curve, be mitered, or be beveled. It can
92 // have an inner curve, an inner miter, or fill the interior. Per-edge quads are always mitered
93 // and fill the interior, but the vertices are placed such that the edge coverage ramps can
94 // collapse to 0 area on non-AA edges.
95 //
96 // The vertices that describe each corner are placed so that edges, miters, and bevels calculate
97 // coverage by interpolating a varying and then clamping in the fragment shader. Triangles that
98 // cover the inner and outer curves calculate distance to the curve within the fragment shader.
99 //
100 // See https://docs.google.com/presentation/d/1MCPstNsSlDBhR8CrsJo0r-cZNbu-sEJEvU9W94GOJoY/edit?usp=sharing
101 // for diagrams and explanation of how the geometry is defined.
102 //
103 // AnalyticRRectRenderStep uses the common technique of approximating distance to the level set by
104 // one expansion of the Taylor's series for the level set's equation. Given a level set function
105 // C(x,y), this amounts to calculating C(px,py)/|∇C(px,py)|. For the straight edges the level set
106 // is linear and calculated in the vertex shader and then interpolated exactly over the rectangle.
107 // This provides distances to all four exterior edges within the fragment shader and allows it to
108 // reconstruct a relative position per elliptical corner. Unfortunately this requires the fragment
109 // shader to calculate the length of the gradient for straight edges instead of interpolating
110 // exact device-space distance.
111 //
112 // All four corner radii are potentially evaluated by the fragment shader although each corner's
113 // coverage is only calculated when the pixel is within the bounding box of its quadrant. For fills
114 // and simple strokes it's theoretically valid to have each pixel calculate a single corner's
115 // coverage that was controlled via the vertex shader. However, testing all four corners is
116 // necessary in order to correctly handle self-intersecting stroke interiors. Similarly, all four
117 // edges must be evaluated in order to handle extremely thin shapes; whereas often you could get
118 // away with tracking a single edge distance per pixel.
119 //
120 // Analytic derivatives are used so that a single pipeline can be used regardless of HW derivative
121 // support or for geometry that would prove difficult for forward differencing. The device-space
122 // gradient for ellipses is calculated per-pixel by transforming a per-pixel local gradient vector
123 // with the Jacobian of the inverse local-to-device transform:
124 //
125 // (px,py) is the projected point of (u,v) transformed by a 3x3 matrix, M:
126 // [x(u,v) / w(u,v)] [x] [m00 m01 m02] [u]
127 // (px,py) = [y(u,v) / w(u,v)] where [y] = [m10 m11 m12]X[v] = M*(u,v,1)
128 // [w] [m20 m21 m22] [1]
129 //
130 // C(px,py) can be defined in terms of a local Cl(u,v) as C(px,py) = Cl(p^-1(px,py)), where p^-1 =
131 //
132 // [x'(px,py) / w'(px,py)] [x'] [m00' m01' * m02'] [px]
133 // (u,v) = [y'(px,py) / w'(px,py)] where [y'] = [m10' m11' * m12']X[py] = M^-1*(px,py,0,1)
134 // [w'] [m20' m21' * m22'] [ 1]
135 //
136 // Note that if the 3x3 M was arrived by dropping the 3rd row and column from a 4x4 since we assume
137 // a local 3rd coordinate of 0, M^-1 is not equal to the 4x4 inverse with dropped rows and columns.
138 //
139 // Using the chain rule, then ∇C(px,py)
140 // = ∇Cl(u,v)X[1/w'(px,py) 0 -x'(px,py)/w'(px,py)^2] [m00' m01']
141 // [ 0 1/w'(px,py) -y'(px,py)/w'(px,py)^2]X[m10' m11']
142 // [m20' m21']
143 //
144 // = 1/w'(px,py)*∇Cl(u,v)X[1 0 -x'(px,py)/w'(px,py)] [m00' m01']
145 // [0 1 -y'(px,py)/w'(px,py)]X[m10' m11']
146 // [m20' m21']
147 //
148 // = w(u,v)*∇Cl(u,v)X[1 0 0 -u] [m00' m01']
149 // [0 1 0 -v]X[m10' m11']
150 // [m20' m21']
151 //
152 // = w(u,v)*∇Cl(u,v)X[m00'-m20'u m01'-m21'u]
153 // [m10'-m20'v m11'-m21'v]
154 //
155 // The vertex shader calculates the rightmost 2x2 matrix and interpolates it across the shape since
156 // each component is linear in (u,v). ∇Cl(u,v) is evaluated per pixel in the fragment shader and
157 // depends on which corner and edge being evaluated. w(u,v) is the device-space W coordinate, so
158 // its reciprocal is provided in sk_FragCoord.w.
159 namespace skgpu::graphite {
160
161 using AAFlags = EdgeAAQuad::Flags;
162
163 static skvx::float4 load_x_radii(const SkRRect& rrect) {
164 return skvx::float4{rrect.radii(SkRRect::kUpperLeft_Corner).fX,
165 rrect.radii(SkRRect::kUpperRight_Corner).fX,
166 rrect.radii(SkRRect::kLowerRight_Corner).fX,
167 rrect.radii(SkRRect::kLowerLeft_Corner).fX};
168 }
169 static skvx::float4 load_y_radii(const SkRRect& rrect) {
170 return skvx::float4{rrect.radii(SkRRect::kUpperLeft_Corner).fY,
171 rrect.radii(SkRRect::kUpperRight_Corner).fY,
172 rrect.radii(SkRRect::kLowerRight_Corner).fY,
173 rrect.radii(SkRRect::kLowerLeft_Corner).fY};
174 }
175
176 static bool opposite_insets_intersect(const SkRRect& rrect, float strokeRadius, float aaRadius) {
177 // One AA inset per side
178 const float maxInset = strokeRadius + 2.f * aaRadius;
179 return // Horizontal insets would intersect opposite corner's curve
180 maxInset >= rrect.width() - rrect.radii(SkRRect::kLowerLeft_Corner).fX ||
181 maxInset >= rrect.width() - rrect.radii(SkRRect::kLowerRight_Corner).fX ||
182 maxInset >= rrect.width() - rrect.radii(SkRRect::kUpperLeft_Corner).fX ||
183 maxInset >= rrect.width() - rrect.radii(SkRRect::kUpperRight_Corner).fX ||
184 // Vertical insets would intersect opposite corner's curve
185 maxInset >= rrect.height() - rrect.radii(SkRRect::kLowerLeft_Corner).fY ||
186 maxInset >= rrect.height() - rrect.radii(SkRRect::kLowerRight_Corner).fY ||
187 maxInset >= rrect.height() - rrect.radii(SkRRect::kUpperLeft_Corner).fY ||
188 maxInset >= rrect.height() - rrect.radii(SkRRect::kUpperRight_Corner).fY;
189 }
190
191 static bool opposite_insets_intersect(const Rect& rect, float strokeRadius, float aaRadius) {
192 return any(rect.size() <= 2.f * (strokeRadius + aaRadius));
193 }
194
195 static bool opposite_insets_intersect(const Geometry& geometry,
196 float strokeRadius,
197 float aaRadius) {
198 if (geometry.isEdgeAAQuad()) {
199 SkASSERT(strokeRadius == 0.f);
200 const EdgeAAQuad& quad = geometry.edgeAAQuad();
201 if (quad.edgeFlags() == AAFlags::kNone) {
202 // If all edges are non-AA, there won't be any insetting. This allows completely non-AA
203 // quads to use the fill triangles for simpler fragment shader work.
204 return false;
205 } else if (quad.isRect() && quad.edgeFlags() == AAFlags::kAll) {
206 return opposite_insets_intersect(quad.bounds(), 0.f, aaRadius);
207 } else {
208 // Quads with mixed AA edges are tiles where non-AA edges must seam perfectly together.
209 // If we were to inset along just the axis with AA at a corner, two adjacent quads could
210 // arrive at slightly different inset coordinates and then we wouldn't have a perfect
211 // mesh. Forcing insets to snap to the center means all non-AA edges are formed solely
212 // by the original quad coordinates and should seam perfectly assuming perfect input.
213 // The only downside to this is the fill triangles cannot be used since they would
214 // partially extend into the coverage ramp from adjacent AA edges.
215 return true;
216 }
217 } else {
218 const Shape& shape = geometry.shape();
219 if (shape.isLine()) {
220 return strokeRadius <= aaRadius;
221 } else if (shape.isRect()) {
222 return opposite_insets_intersect(shape.rect(), strokeRadius, aaRadius);
223 } else {
224 SkASSERT(shape.isRRect());
225 return opposite_insets_intersect(shape.rrect(), strokeRadius, aaRadius);
226 }
227 }
228 }
229
230 static bool is_clockwise(const EdgeAAQuad& quad) {
231 if (quad.isRect()) {
232 return true; // by construction, these are always locally clockwise
233 }
234
235 // This assumes that each corner has a consistent winding, which is the case for convex inputs,
236 // which is an assumption of the per-edge AA API. Check the sign of cross product between the
237 // first two edges.
238 const skvx::float4& xs = quad.xs();
239 const skvx::float4& ys = quad.ys();
240
241 float winding = (xs[0] - xs[3])*(ys[1] - ys[0]) - (ys[0] - ys[3])*(xs[1] - xs[0]);
242 if (winding == 0.f) {
243 // The input possibly forms a triangle with duplicate vertices, so check the opposite corner
244 winding = (xs[2] - xs[1])*(ys[3] - ys[2]) - (ys[2] - ys[1])*(xs[3] - xs[2]);
245 }
246
247 // At this point if winding is < 0, the quad's vertices are CCW. If it's still 0, the vertices
248 // form a line, in which case the vertex shader constructs a correct CW winding. Otherwise,
249 // the quad or triangle vertices produce a positive winding and are CW.
250 return winding >= 0.f;
251 }
252
253 static skvx::float2 quad_center(const EdgeAAQuad& quad) {
254 // The center of the bounding box is *not* a good center to use. Take the average of the
255 // four points instead (which is slightly biased if they form a triangle, but still okay).
256 return skvx::float2(dot(quad.xs(), skvx::float4(0.25f)),
257 dot(quad.ys(), skvx::float4(0.25f)));
258 }
259
260 // Allowed values for the center weight instance value (selected at record time based on style
261 // and transform), and are defined such that when (insance-weight > vertex-weight) is true, the
262 // vertex should be snapped to the center instead of its regular calculation.
263 static constexpr float kSolidInterior = 1.f;
264 static constexpr float kStrokeInterior = 0.f;
265 static constexpr float kFilledStrokeInterior = -1.f;
266
267 // Special value for local AA radius to signal when the self-intersections of a stroke interior
268 // need extra calculations in the vertex shader.
269 static constexpr float kComplexAAInsets = -1.f;
270
271 static constexpr int kCornerVertexCount = 9; // sk_VertexID is divided by this in SkSL
272 static constexpr int kVertexCount = 4 * kCornerVertexCount;
273 static constexpr int kIndexCount = 69;
274
275 // Represents the per-vertex attributes used in each instance.
276 struct Vertex {
277 uint32_t fCornerID;
278 SkV2 fPosition;
279 SkV2 fNormal;
280 float fNormalScale;
281 float fCenterWeight;
282 };
283
284 // This template is repeated 4 times in the vertex buffer, for each of the four corners: TL -> TR ->
285 // BR -> BL. The corner ID is used to lookup per-corner instance properties such as corner radii or
286 // positions.
287 template<uint32_t kCornerID>
288 constexpr std::array<Vertex, kCornerVertexCount> get_per_corner_vertex_attrs() {
289 // Allowed values for the normal scale attribute. +1 signals a device-space outset along the
290 // normal away from the outer edge of the stroke. 0 signals no outset, but placed on the outer
291 // edge of the stroke. -1 signals a local inset along the normal from the inner edge.
292 constexpr float kOutset = 1.0;
293 constexpr float kInset = -1.0;
294
295 constexpr float kCenter = 1.f; // "true" as a float
296
297 // Zero, but named this way to help call out non-zero parameters.
298 constexpr float _______ = 0.f;
299
300 constexpr float kHR2 = 0.5f * SK_FloatSqrt2; // "half root 2"
301 return {{
302 // Device-space AA outsets from outer curve
303 { kCornerID, {1.0f, 0.0f}, {1.0f, 0.0f}, kOutset, _______ },
304 { kCornerID, {1.0f, 0.0f}, {kHR2, kHR2}, kOutset, _______ },
305 { kCornerID, {0.0f, 1.0f}, {kHR2, kHR2}, kOutset, _______ },
306 { kCornerID, {0.0f, 1.0f}, {0.0f, 1.0f}, kOutset, _______ },
307
308 // Outer anchors (no local or device-space normal outset)
309 { kCornerID, {1.0f, 0.0f}, {kHR2, kHR2}, _______, _______ },
310 { kCornerID, {0.0f, 1.0f}, {kHR2, kHR2}, _______, _______ },
311
312 // Inner curve (with additional AA inset in the common case)
313 { kCornerID, {1.0f, 0.0f}, {1.0f, 0.0f}, kInset, _______ },
314 { kCornerID, {0.0f, 1.0f}, {0.0f, 1.0f}, kInset, _______ },
315
316 // Center filling vertices (equal to inner AA insets unless 'center' triggers a fill).
317 // TODO: On backends that support "cull" distances (and with SkSL support), these vertices
318 // and their corresponding triangles can be completely removed. The inset vertices can
319 // set their cull distance value to cause all filling triangles to be discarded or not
320 // depending on the instance's style.
321 { kCornerID, {1.0f, 0.0f}, {1.0f, 0.0f}, kInset, kCenter },
322 }};
323 }
324
325 static void write_index_buffer(VertexWriter writer) {
326 static constexpr uint16_t kTL = 0 * kCornerVertexCount;
327 static constexpr uint16_t kTR = 1 * kCornerVertexCount;
328 static constexpr uint16_t kBR = 2 * kCornerVertexCount;
329 static constexpr uint16_t kBL = 3 * kCornerVertexCount;
330
331 static const uint16_t kIndices[kIndexCount] = {
332 // Exterior AA ramp outset
333 kTL+0,kTL+4,kTL+1,kTL+5,kTL+2,kTL+3,kTL+5,
334 kTR+0,kTR+4,kTR+1,kTR+5,kTR+2,kTR+3,kTR+5,
335 kBR+0,kBR+4,kBR+1,kBR+5,kBR+2,kBR+3,kBR+5,
336 kBL+0,kBL+4,kBL+1,kBL+5,kBL+2,kBL+3,kBL+5,
337 kTL+0,kTL+4, // close and jump to next strip
338 // Outer to inner edges
339 kTL+4,kTL+6,kTL+5,kTL+7,
340 kTR+4,kTR+6,kTR+5,kTR+7,
341 kBR+4,kBR+6,kBR+5,kBR+7,
342 kBL+4,kBL+6,kBL+5,kBL+7,
343 kTL+4,kTL+6, // close and jump to next strip
344 // Fill triangles
345 kTL+6,kTL+8,kTL+7, kTL+7,kTR+8,
346 kTR+6,kTR+8,kTR+7, kTR+7,kBR+8,
347 kBR+6,kBR+8,kBR+7, kBR+7,kBL+8,
348 kBL+6,kBL+8,kBL+7, kBL+7,kTL+8,
349 kTL+6 // close
350 };
351
352 if (writer) {
353 writer << kIndices;
354 } // otherwise static buffer creation failed, so do nothing; Context initialization will fail.
355 }
356
357 static void write_vertex_buffer(VertexWriter writer) {
358 if (writer) {
359 writer << get_per_corner_vertex_attrs<0>() // TL
360 << get_per_corner_vertex_attrs<1>() // TR
361 << get_per_corner_vertex_attrs<2>() // BR
362 << get_per_corner_vertex_attrs<3>(); // BL
363 } // otherwise static buffer creation failed, so do nothing; Context initialization will fail.
364 }
365
366 AnalyticRRectRenderStep::AnalyticRRectRenderStep(Layout layout, StaticBufferManager* bufferManager)
367 : RenderStep(layout,
368 RenderStepID::kAnalyticRRect,
369 Flags::kPerformsShading | Flags::kEmitsCoverage | Flags::kOutsetBoundsForAA |
370 Flags::kUseNonAAInnerFill | Flags::kAppendInstances,
371 /*uniforms=*/{},
372 PrimitiveType::kTriangleStrip,
373 kDirectDepthLessPass,
374 /*staticAttrs=*/{{
375 {"cornerID", VertexAttribType::kUInt, SkSLType::kUInt},
376 {"position", VertexAttribType::kFloat2, SkSLType::kFloat2},
377 {"normal", VertexAttribType::kFloat2, SkSLType::kFloat2},
378 // TODO: These values are all +1/0/-1, or +1/0, so could be packed
379 // much more densely than as three floats.
380 {"normalScale", VertexAttribType::kFloat, SkSLType::kFloat},
381 {"centerWeight", VertexAttribType::kFloat, SkSLType::kFloat}
382 }},
383 /*appendAttrs=*/{{
384 {"xRadiiOrFlags", VertexAttribType::kFloat4, SkSLType::kFloat4},
385 {"radiiOrQuadXs", VertexAttribType::kFloat4, SkSLType::kFloat4},
386 {"ltrbOrQuadYs", VertexAttribType::kFloat4, SkSLType::kFloat4},
387 // XY stores center of rrect in local coords. Z and W store values to
388 // control interior fill behavior. Z can be -1, 0, or 1:
389 // -1: A stroked interior where AA insets overlap, but isn't solid.
390 // 0: A stroked interior with no complications.
391 // 1: A solid interior (fill or sufficiently large stroke width).
392 // W specifies the size of the AA inset if it's >= 0, or signals that
393 // the inner curves intersect in a complex manner (rare).
394 {"center", VertexAttribType::kFloat4, SkSLType::kFloat4},
395
396 // TODO: pack depth and ssbo index into one 32-bit attribute, if we can
397 // go without needing both render step and paint ssbo index attributes.
398 {"depth", VertexAttribType::kFloat, SkSLType::kFloat},
399 {"ssboIndex", VertexAttribType::kUInt, SkSLType::kUInt},
400
401 {"mat0", VertexAttribType::kFloat3, SkSLType::kFloat3},
402 {"mat1", VertexAttribType::kFloat3, SkSLType::kFloat3},
403 {"mat2", VertexAttribType::kFloat3, SkSLType::kFloat3}
404 }},
405 /*varyings=*/{{
406 // TODO: If the inverse transform is part of the draw's SSBO, we can
407 // reconstruct the Jacobian in the fragment shader using the existing
408 // local coordinates varying
409 {"jacobian", SkSLType::kFloat4}, // float2x2
410 // Distance to LTRB edges of unstroked shape. Depending on
411 // 'perPixelControl' these will either be local or device-space values.
412 {"edgeDistances", SkSLType::kFloat4}, // distance to LTRB edges
413 // TODO: These are constant for all fragments for a given instance,
414 // could we store them in the draw's SSBO?
415 {"xRadii", SkSLType::kFloat4},
416 {"yRadii", SkSLType::kFloat4},
417 // Matches the StrokeStyle struct (X is radius, Y < 0 is round join,
418 // Y = 0 is bevel, Y > 0 is miter join).
419 // TODO: These could easily be considered part of the draw's uniforms.
420 {"strokeParams", SkSLType::kFloat2},
421 // 'perPixelControl' is a tightly packed description of how to
422 // evaluate the possible edges that influence coverage in a pixel.
423 // The decision points and encoded values are spread across X and Y
424 // so that they are consistent regardless of whether or not MSAA is
425 // used and does not require centroid sampling.
426 //
427 // The signs of values are used to determine the type of coverage to
428 // calculate in the fragment shader and depending on the state, extra
429 // varying state is encoded in the fields:
430 // - A positive X value overrides all per-pixel coverage calculations
431 // and sets the pixel to full coverage. Y is ignored in this case.
432 // - A zero X value represents a solid interior shape.
433 // - X much less than 0 represents bidirectional coverage for a
434 // stroke, using a sufficiently negative value to avoid
435 // extrapolation from fill triangles. For actual shapes with
436 // bidirectional coverage, the fill triangles are zero area.
437 //
438 // - Y much greater than 0 takes precedence over the latter two X
439 // rules and signals that 'edgeDistances' holds device-space values
440 // and does not require additional per-pixel calculations. The
441 // coverage scale is encoded as (1+scale*w) and the bias is
442 // reconstructed from that. X is always 0 for non-fill triangles
443 // since device-space edge distance is only used for solid interiors
444 // - Otherwise, any negative Y value represents an additional
445 // reduction in coverage due to a device-space outset. It is clamped
446 // below 0 to avoid adding coverage from extrapolation.
447 {"perPixelControl", SkSLType::kFloat2},
448 }}) {
449 // Initialize the static buffers we'll use when recording draw calls.
450 // NOTE: Each instance of this RenderStep gets its own copy of the data. Since there should only
451 // ever be one AnalyticRRectRenderStep at a time, this shouldn't be an issue.
452 write_vertex_buffer(bufferManager->getVertexWriter(kVertexCount, sizeof(Vertex),
453 &fVertexBuffer));
454 write_index_buffer(bufferManager->getIndexWriter(sizeof(uint16_t) * kIndexCount,
455 &fIndexBuffer));
456 }
457
458 AnalyticRRectRenderStep::~AnalyticRRectRenderStep() {}
459
460 std::string AnalyticRRectRenderStep::vertexSkSL() const {
461 // Returns the body of a vertex function, which must define a float4 devPosition variable and
462 // must write to an already-defined float2 stepLocalCoords variable.
463 return "float4 devPosition = analytic_rrect_vertex_fn("
464 // Static Data Attributes
465 "cornerID, position, normal, normalScale, centerWeight, "
466 // Append Data Attributes
467 "xRadiiOrFlags, radiiOrQuadXs, ltrbOrQuadYs, center, depth, "
468 "float3x3(mat0, mat1, mat2), "
469 // Varyings
470 "jacobian, edgeDistances, xRadii, yRadii, strokeParams, perPixelControl, "
471 // Render Step
472 "stepLocalCoords);\n";
473 }
474
475 const char* AnalyticRRectRenderStep::fragmentCoverageSkSL() const {
476 // The returned SkSL must write its coverage into a 'half4 outputCoverage' variable (defined in
477 // the calling code) with the actual coverage splatted out into all four channels.
478 return "outputCoverage = analytic_rrect_coverage_fn(sk_FragCoord, "
479 "jacobian, "
480 "edgeDistances, "
481 "xRadii, "
482 "yRadii, "
483 "strokeParams, "
484 "perPixelControl);";
485 }
486
487 void AnalyticRRectRenderStep::writeVertices(DrawWriter* writer,
488 const DrawParams& params,
489 uint32_t ssboIndex) const {
490 SkASSERT(params.geometry().isShape() || params.geometry().isEdgeAAQuad());
491
492 DrawWriter::Instances instance{*writer, fVertexBuffer, fIndexBuffer, kIndexCount};
493 auto vw = instance.append(1);
494
495 // The bounds of a rect is the rect, and the bounds of a rrect is tight (== SkRRect::getRect()).
496 Rect bounds = params.geometry().bounds();
497
498 // aaRadius will be set to a negative value to signal a complex self-intersection that has to
499 // be calculated in the vertex shader.
500 float aaRadius = params.transform().localAARadius(bounds);
501 float strokeInset = 0.f;
502 float centerWeight = kSolidInterior;
503
504 if (params.isStroke()) {
505 // EdgeAAQuads are not stroked so we know it's a Shape, but we support rects, rrects, and
506 // lines that all need to be converted to the same form.
507 const Shape& shape = params.geometry().shape();
508
509 SkASSERT(params.strokeStyle().halfWidth() >= 0.f);
510 SkASSERT(shape.isRect() || shape.isLine() || params.strokeStyle().halfWidth() == 0.f ||
511 (shape.isRRect() && SkRRectPriv::AllCornersRelativelyCircular(
512 shape.rrect(), aaRadius * Shape::kDefaultPixelTolerance)));
513
514 float strokeRadius = params.strokeStyle().halfWidth();
515
516 skvx::float2 size = shape.isLine() ? skvx::float2(length(shape.p1() - shape.p0()), 0.f)
517 : bounds.size(); // rect or [r]rect
518
519 skvx::float2 innerGap = size - 2.f * params.strokeStyle().halfWidth();
520 if (any(innerGap <= 0.f) && strokeRadius > 0.f) {
521 // AA inset intersections are measured from the *outset* and remain marked as "solid"
522 strokeInset = -strokeRadius;
523 } else {
524 // This will be upgraded to kFilledStrokeInterior if insets intersect
525 centerWeight = kStrokeInterior;
526 strokeInset = strokeRadius;
527 }
528
529 skvx::float4 xRadii = shape.isRRect() ? load_x_radii(shape.rrect()) : skvx::float4(0.f);
530 if (strokeRadius > 0.f || shape.isLine()) {
531 // Regular strokes only need to upload 4 corner radii; hairline lines can be uploaded in
532 // the same manner since it has no real corner radii.
533 float joinStyle = params.strokeStyle().joinLimit();
534 float lineFlag = shape.isLine() ? 1.f : 0.f;
535 auto empty = size == 0.f;
536
537 // Points and lines produce caps instead of joins. However, the capped geometry is
538 // visually equivalent to a joined, stroked [r]rect of the paired join style.
539 if (shape.isLine() || all(empty)) {
540 // However, butt-cap points are defined not to produce any geometry, so that combo
541 // should have been rejected earlier.
542 SkASSERT(shape.isLine() || params.strokeStyle().cap() != SkPaint::kButt_Cap);
543 switch(params.strokeStyle().cap()) {
544 case SkPaint::kRound_Cap: joinStyle = -1.f; break; // round cap == round join
545 case SkPaint::kButt_Cap: joinStyle = 0.f; break; // butt cap == bevel join
546 case SkPaint::kSquare_Cap: joinStyle = 1.f; break; // square cap == miter join
547 }
548 } else if (params.strokeStyle().isMiterJoin()) {
549 // Normal corners are 90-degrees so become beveled if the miter limit is < sqrt(2).
550 // If the [r]rect has a width or height of 0, the corners are actually 180-degrees,
551 // so the must always be beveled (or, equivalently, butt-capped).
552 if (params.strokeStyle().miterLimit() < SK_ScalarSqrt2 || any(empty)) {
553 joinStyle = 0.f; // == bevel (or butt if width or height are zero)
554 } else {
555 // Discard actual miter limit because a 90-degree corner never exceeds it.
556 joinStyle = 1.f;
557 }
558 } // else no join style correction needed for non-empty geometry or round joins
559
560 // Write a negative value outside [-1, 0] to signal a stroked shape, the line flag, then
561 // the style params, followed by corner radii and coords.
562 vw << -2.f << lineFlag << strokeRadius << joinStyle << xRadii
563 << (shape.isLine() ? shape.line() : bounds.ltrb());
564 } else {
565 // Write -2 - cornerRadii to encode the X radii in such a way to trigger stroking but
566 // guarantee the 2nd field is non-zero to signal hairline. Then we upload Y radii as
567 // well to allow for elliptical hairlines.
568 skvx::float4 yRadii = shape.isRRect() ? load_y_radii(shape.rrect()) : skvx::float4(0.f);
569 vw << (-2.f - xRadii) << yRadii << bounds.ltrb();
570 }
571 } else {
572 // Empty fills should not have been recorded at all.
573 SkASSERT(!bounds.isEmptyNegativeOrNaN());
574
575 if (params.geometry().isEdgeAAQuad()) {
576 // NOTE: If quad.isRect() && quad.edgeFlags() == kAll, the written data is identical to
577 // Shape.isRect() case below.
578 const EdgeAAQuad& quad = params.geometry().edgeAAQuad();
579
580 // If all edges are non-AA, set localAARadius to 0 so that the fill triangles cover the
581 // entire shape. Otherwise leave it as-is for the full AA rect case; in the event it's
582 // mixed-AA or a quad, it'll be converted to complex insets down below.
583 if (quad.edgeFlags() == EdgeAAQuad::Flags::kNone) {
584 aaRadius = 0.f;
585 }
586
587 // -1 for AA on, 0 for AA off
588 auto edgeSigns = skvx::float4{quad.edgeFlags() & AAFlags::kLeft ? -1.f : 0.f,
589 quad.edgeFlags() & AAFlags::kTop ? -1.f : 0.f,
590 quad.edgeFlags() & AAFlags::kRight ? -1.f : 0.f,
591 quad.edgeFlags() & AAFlags::kBottom ? -1.f : 0.f};
592
593 // The vertex shader expects points to be in clockwise order. EdgeAAQuad is the only
594 // shape that *might* have counter-clockwise input.
595 if (is_clockwise(quad)) {
596 vw << edgeSigns << quad.xs() << quad.ys();
597 } else {
598 vw << skvx::shuffle<2,1,0,3>(edgeSigns) // swap left and right AA bits
599 << skvx::shuffle<1,0,3,2>(quad.xs()) // swap TL with TR, and BL with BR
600 << skvx::shuffle<1,0,3,2>(quad.ys()); // ""
601 }
602 } else {
603 const Shape& shape = params.geometry().shape();
604 // Filled lines are empty by definition, so they shouldn't have been recorded
605 SkASSERT(!shape.isLine());
606
607 if (shape.isRect() || (shape.isRRect() && shape.rrect().isRect())) {
608 // Rectangles (or rectangles embedded in an SkRRect) are converted to the
609 // quadrilateral case, but with all edges anti-aliased (== -1).
610 skvx::float4 ltrb = bounds.ltrb();
611 vw << /*edge flags*/ skvx::float4(-1.f)
612 << /*xs*/ skvx::shuffle<0,2,2,0>(ltrb)
613 << /*ys*/ skvx::shuffle<1,1,3,3>(ltrb);
614 } else {
615 // A filled rounded rectangle, so make sure at least one corner radii > 0 or the
616 // shader won't detect it as a rounded rect.
617 SkASSERT(any(load_x_radii(shape.rrect()) > 0.f));
618
619 vw << load_x_radii(shape.rrect()) << load_y_radii(shape.rrect()) << bounds.ltrb();
620 }
621 }
622 }
623
624 if (opposite_insets_intersect(params.geometry(), strokeInset, aaRadius)) {
625 aaRadius = kComplexAAInsets;
626 if (centerWeight == kStrokeInterior) {
627 centerWeight = kFilledStrokeInterior;
628 }
629 }
630
631 // All instance types share the remaining instance attribute definitions
632 const SkM44& m = params.transform().matrix();
633 auto center = params.geometry().isEdgeAAQuad() ? quad_center(params.geometry().edgeAAQuad())
634 : bounds.center();
635 vw << center << centerWeight << aaRadius
636 << params.order().depthAsFloat()
637 << ssboIndex
638 << m.rc(0,0) << m.rc(1,0) << m.rc(3,0) // mat0
639 << m.rc(0,1) << m.rc(1,1) << m.rc(3,1) // mat1
640 << m.rc(0,3) << m.rc(1,3) << m.rc(3,3); // mat2
641 }
642
643 void AnalyticRRectRenderStep::writeUniformsAndTextures(const DrawParams&,
644 PipelineDataGatherer* gatherer) const {
645 // All data is uploaded as instance attributes, so no uniforms are needed.
646 SkDEBUGCODE(gatherer->checkRewind());
647 }
648
649 } // namespace skgpu::graphite