Debian Codegraph @

src/gpu/graphite/render/CircularArcRenderStep.cpp

raw
1 /*
2 * Copyright 2024 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/CircularArcRenderStep.h"
9
10 #include "include/core/SkArc.h"
11 #include "include/core/SkM44.h"
12 #include "include/core/SkPaint.h"
13 #include "include/core/SkRect.h"
14 #include "include/core/SkScalar.h"
15 #include "include/private/base/SkAssert.h"
16 #include "include/private/base/SkDebug.h"
17 #include "include/private/base/SkPoint_impl.h"
18 #include "src/base/SkEnumBitMask.h"
19 #include "src/core/SkSLTypeShared.h"
20 #include "src/gpu/BufferWriter.h"
21 #include "src/gpu/graphite/Attribute.h"
22 #include "src/gpu/graphite/BufferManager.h"
23 #include "src/gpu/graphite/DrawOrder.h"
24 #include "src/gpu/graphite/DrawParams.h"
25 #include "src/gpu/graphite/DrawTypes.h"
26 #include "src/gpu/graphite/DrawWriter.h"
27 #include "src/gpu/graphite/PipelineData.h"
28 #include "src/gpu/graphite/geom/Geometry.h"
29 #include "src/gpu/graphite/geom/Shape.h"
30 #include "src/gpu/graphite/geom/Transform.h"
31 #include "src/gpu/graphite/render/CommonDepthStencilSettings.h"
32
33 #include <utility>
34
35 // This RenderStep is used to render filled circular arcs and stroked circular arcs that
36 // don't include the center. Currently it only supports butt caps but will be extended
37 // to include round caps.
38 //
39 // Each arc is represented by a single instance. The instance attributes are enough to
40 // describe the given arc types without relying on uniforms to define its operation.
41 // The attributes encode shape as follows:
42
43 // float4 centerScales - used to transform the vertex data into local space.
44 // The vertex data represents interleaved octagons that are respectively circumscribed
45 // and inscribed on a unit circle, and have to be transformed into local space.
46 // So the .xy values here are the center of the arc in local space, and .zw its outer and inner
47 // radii, respectively. If the vertex is an outer vertex its local position will be computed as
48 // centerScales.xy + position.xy * centerScales.z
49 // Otherwise it will be computed as
50 // centerScales.xy + position.xy * centerScales.w
51 // We can tell whether a vertex is an outer or inner vertex by looking at the sign
52 // of its z component. This z value is also used to compute half-pixel anti-aliasing offsets
53 // once the vertex data is transformed into device space.
54 // float3 radiiAndFlags - in the fragment shader we will pass an offset in unit circle space to
55 // determine the circle edge and for use for clipping. The .x value here is outerRadius+0.5 and
56 // will be compared against the unit circle radius (i.e., 1.0) to compute the outer edge. The .y
57 // value is innerRadius-0.5/outerRadius+0.5 and will be used as the comparison point for the
58 // inner edge. The .z value is a flag which indicates whether fragClipPlane1 is for intersection
59 // (+) or for union (-), and whether to set up rounded caps (-2/+2).
60 // float3 geoClipPlane - For very thin acute arcs, because of the 1/2 pixel boundary we can get
61 // non-clipped artifacts beyond the center of the circle. To solve this, we clip the geometry
62 // so any rendering doesn't cross that point.
63
64 // In addition, these values will be passed to the fragment shader:
65 //
66 // float3 fragClipPlane0 - the arc will always be clipped against this half plane, and passed as
67 // the varying clipPlane.
68 // float3 fragClipPlane1 - for convex/acute arcs, we pass this via the varying isectPlane to clip
69 // against this and multiply its value by the ClipPlane clip result. For concave/obtuse arcs,
70 // we pass this via the varying unionPlane which will clip against this and add its value to the
71 // ClipPlane clip result. This is controlled by the flag value in radiiAndFlags: if the
72 // flag is > 0, it's passed as isectClip, if it's < 0 it's passed as unionClip. We set default
73 // values for the alternative clip plane that end up being a null clip.
74 // float roundCapRadius - this is computed in the vertex shader. If we're using round caps (i.e.,
75 // if abs(flags) > 1), this will be half the distance between the outer and inner radii.
76 // Otherwise it will be 0 which will end up zeroing out any round cap calculation.
77 // float4 inRoundCapPos - locations of the centers of the round caps in normalized space. This
78 // will be all zeroes if not needed.
79
80 namespace skgpu::graphite {
81
82 // Represents the per-vertex attributes used in each instance.
83 struct Vertex {
84 // Unit circle local space position (.xy) and AA offset (.z)
85 SkV3 fPosition;
86 };
87
88 static constexpr int kVertexCount = 18;
89
90 static void write_vertex_buffer(VertexWriter writer) {
91 // Normalized geometry for octagons that circumscribe/inscribe a unit circle.
92 // Outer ring offset
93 static constexpr float kOctOffset = 0.41421356237f; // sqrt(2) - 1
94 // Inner ring points
95 static constexpr SkScalar kCosPi8 = 0.923579533f;
96 static constexpr SkScalar kSinPi8 = 0.382683432f;
97
98 // Directional offset for anti-aliasing.
99 // Also used as marker for whether this is an outer or inner vertex.
100 static constexpr float kOuterAAOffset = 0.5f;
101 static constexpr float kInnerAAOffset = -0.5f;
102
103 static constexpr SkV3 kOctagonVertices[kVertexCount] = {
104 {-kOctOffset, -1, kOuterAAOffset},
105 {-kSinPi8, -kCosPi8, kInnerAAOffset},
106 { kOctOffset, -1, kOuterAAOffset},
107 {kSinPi8, -kCosPi8, kInnerAAOffset},
108 { 1, -kOctOffset, kOuterAAOffset},
109 {kCosPi8, -kSinPi8, kInnerAAOffset},
110 { 1, kOctOffset, kOuterAAOffset},
111 {kCosPi8, kSinPi8, kInnerAAOffset},
112 { kOctOffset, 1, kOuterAAOffset},
113 {kSinPi8, kCosPi8, kInnerAAOffset},
114 {-kOctOffset, 1, kOuterAAOffset},
115 {-kSinPi8, kCosPi8, kInnerAAOffset},
116 {-1, kOctOffset, kOuterAAOffset},
117 {-kCosPi8, kSinPi8, kInnerAAOffset},
118 {-1, -kOctOffset, kOuterAAOffset},
119 {-kCosPi8, -kSinPi8, kInnerAAOffset},
120 {-kOctOffset, -1, kOuterAAOffset},
121 {-kSinPi8, -kCosPi8, kInnerAAOffset},
122 };
123
124 if (writer) {
125 writer << kOctagonVertices;
126 } // otherwise static buffer creation failed, so do nothing; Context initialization will fail.
127 }
128
129 CircularArcRenderStep::CircularArcRenderStep(Layout layout, StaticBufferManager* bufferManager)
130 : RenderStep(layout,
131 RenderStepID::kCircularArc,
132 Flags::kPerformsShading | Flags::kEmitsCoverage | Flags::kOutsetBoundsForAA |
133 Flags::kAppendInstances,
134 /*uniforms=*/{},
135 PrimitiveType::kTriangleStrip,
136 kDirectDepthLessPass,
137 /*staticAttrs=*/{{
138 {"position", VertexAttribType::kFloat3, SkSLType::kFloat3},
139 }},
140 /*appendAttrs=*/{{
141 // Center plus radii, used to transform to local position
142 {"centerScales", VertexAttribType::kFloat4, SkSLType::kFloat4},
143 // Outer (device space) and inner (normalized) radii
144 // + flags for determining clipping and roundcaps
145 {"radiiAndFlags", VertexAttribType::kFloat3, SkSLType::kFloat3},
146 // Clips the geometry for acute arcs
147 {"geoClipPlane", VertexAttribType::kFloat3, SkSLType::kFloat3},
148 // Clip planes sent to the fragment shader for arc extents
149 {"fragClipPlane0", VertexAttribType::kFloat3, SkSLType::kFloat3},
150 {"fragClipPlane1", VertexAttribType::kFloat3, SkSLType::kFloat3},
151 // Roundcap positions, if needed
152 {"inRoundCapPos", VertexAttribType::kFloat4, SkSLType::kFloat4},
153 {"inRoundCapRadius", VertexAttribType::kFloat, SkSLType::kFloat},
154 {"depth", VertexAttribType::kFloat, SkSLType::kFloat},
155 {"ssboIndex", VertexAttribType::kUInt, SkSLType::kUInt},
156
157 {"mat0", VertexAttribType::kFloat3, SkSLType::kFloat3},
158 {"mat1", VertexAttribType::kFloat3, SkSLType::kFloat3},
159 {"mat2", VertexAttribType::kFloat3, SkSLType::kFloat3},
160 }},
161 /*varyings=*/{{
162 // Normalized offset vector plus radii
163 {"circleEdge", SkSLType::kFloat4},
164 // Half-planes used to clip to arc shape.
165 {"clipPlane", SkSLType::kFloat3},
166 {"isectPlane", SkSLType::kFloat3},
167 {"unionPlane", SkSLType::kFloat3},
168 // Roundcap data
169 {"roundCapRadius", SkSLType::kFloat},
170 {"roundCapPos", SkSLType::kFloat4},
171 }}) {
172 // Initialize the static buffer we'll use when recording draw calls.
173 // NOTE: Each instance of this RenderStep gets its own copy of the data. Since there should only
174 // ever be one CircularArcRenderStep at a time, this shouldn't be an issue.
175 write_vertex_buffer(bufferManager->getVertexWriter(kVertexCount, sizeof(Vertex),
176 &fVertexBuffer));
177 }
178
179 CircularArcRenderStep::~CircularArcRenderStep() {}
180
181 std::string CircularArcRenderStep::vertexSkSL() const {
182 // Returns the body of a vertex function, which must define a float4 devPosition variable and
183 // must write to an already-defined float2 stepLocalCoords variable.
184 return "float4 devPosition = circular_arc_vertex_fn("
185 // Static Data Attributes
186 "position, "
187 // Append Data Attributes
188 "centerScales, radiiAndFlags, geoClipPlane, fragClipPlane0, fragClipPlane1, "
189 "inRoundCapPos, inRoundCapRadius, depth, float3x3(mat0, mat1, mat2), "
190 // Varyings
191 "circleEdge, clipPlane, isectPlane, unionPlane, "
192 "roundCapRadius, roundCapPos, "
193 // Render Step
194 "stepLocalCoords);\n";
195 }
196
197 const char* CircularArcRenderStep::fragmentCoverageSkSL() const {
198 // The returned SkSL must write its coverage into a 'half4 outputCoverage' variable (defined in
199 // the calling code) with the actual coverage splatted out into all four channels.
200 return "outputCoverage = circular_arc_coverage_fn(circleEdge, "
201 "clipPlane, "
202 "isectPlane, "
203 "unionPlane, "
204 "roundCapRadius, "
205 "roundCapPos);";
206 }
207
208 void CircularArcRenderStep::writeVertices(DrawWriter* writer,
209 const DrawParams& params,
210 uint32_t ssboIndex) const {
211 SkASSERT(params.geometry().isShape() && params.geometry().shape().isArc());
212
213 DrawWriter::Instances instance{*writer, fVertexBuffer, {}, kVertexCount};
214 auto vw = instance.append(1);
215
216 const Shape& shape = params.geometry().shape();
217 const SkArc& arc = shape.arc();
218
219 SkPoint localCenter = arc.oval().center();
220 float localOuterRadius = arc.oval().width() / 2;
221 float localInnerRadius = 0.0f;
222
223 // We know that we have a similarity matrix so this will transform radius to device space
224 const Transform& transform = params.transform();
225 float radius = localOuterRadius * transform.maxScaleFactor();
226 bool isStroke = params.isStroke();
227
228 float innerRadius = -SK_ScalarHalf;
229 float outerRadius = radius;
230 float halfWidth = 0;
231 if (isStroke) {
232 float localHalfWidth = params.strokeStyle().halfWidth();
233
234 halfWidth = localHalfWidth * transform.maxScaleFactor();
235 if (SkScalarNearlyZero(halfWidth)) {
236 halfWidth = SK_ScalarHalf;
237 // Need to map this back to local space
238 localHalfWidth = halfWidth / transform.maxScaleFactor();
239 }
240
241 outerRadius += halfWidth;
242 innerRadius = radius - halfWidth;
243 localInnerRadius = localOuterRadius - localHalfWidth;
244 localOuterRadius += localHalfWidth;
245 }
246
247 // The radii are outset for two reasons. First, it allows the shader to simply perform
248 // simpler computation because the computed alpha is zero, rather than 50%, at the radius.
249 // Second, the outer radius is used to compute the verts of the bounding box that is
250 // rendered and the outset ensures the box will cover all partially covered by the circle.
251 outerRadius += SK_ScalarHalf;
252 innerRadius -= SK_ScalarHalf;
253
254 // The shader operates in a space where the circle is translated to be centered at the
255 // origin. Here we compute points on the unit circle at the starting and ending angles.
256 SkV2 localPoints[3];
257 float startAngleRadians = SkDegreesToRadians(arc.startAngle());
258 float sweepAngleRadians = SkDegreesToRadians(arc.sweepAngle());
259 localPoints[0].y = SkScalarSin(startAngleRadians);
260 localPoints[0].x = SkScalarCos(startAngleRadians);
261 SkScalar endAngle = startAngleRadians + sweepAngleRadians;
262 localPoints[1].y = SkScalarSin(endAngle);
263 localPoints[1].x = SkScalarCos(endAngle);
264 localPoints[2] = {0, 0};
265
266 // Adjust the start and end points based on the view matrix (to handle rotated arcs)
267 SkV4 devPoints[3];
268 transform.mapPoints(localPoints, devPoints, 3);
269 // Translate the point relative to the transformed origin
270 SkV2 startPoint = {devPoints[0].x - devPoints[2].x, devPoints[0].y - devPoints[2].y};
271 SkV2 stopPoint = {devPoints[1].x - devPoints[2].x, devPoints[1].y - devPoints[2].y};
272 startPoint = startPoint.normalize();
273 stopPoint = stopPoint.normalize();
274
275 // We know the matrix is a similarity here. Detect mirroring which will affect how we
276 // should orient the clip planes for arcs.
277 const SkM44& m = transform.matrix();
278 auto upperLeftDet = m.rc(0,0) * m.rc(1,1) -
279 m.rc(0,1) * m.rc(1,0);
280 if (upperLeftDet < 0) {
281 std::swap(startPoint, stopPoint);
282 }
283
284 // Like a fill without useCenter, butt-cap stroke can be implemented by clipping against
285 // radial lines. We treat round caps the same way, but track coverage of circles at the
286 // center of the butts.
287 // However, in both cases we have to be careful about the half-circle.
288 // case. In that case the two radial lines are equal and so that edge gets clipped
289 // twice. Since the shared edge goes through the center we fall back on the !useCenter
290 // case.
291 auto absSweep = SkScalarAbs(sweepAngleRadians);
292 bool useCenter = (arc.isWedge() || isStroke) &&
293 !SkScalarNearlyEqual(absSweep, SK_ScalarPI);
294
295 // This makes every point fully inside the plane.
296 SkV3 geoClipPlane = {0.f, 0.f, 1.f};
297 SkV3 clipPlane0;
298 SkV3 clipPlane1;
299 SkV2 roundCapPos0 = {0, 0};
300 SkV2 roundCapPos1 = {0, 0};
301 static constexpr float kIntersection_NoRoundCaps = 1;
302 static constexpr float kIntersection_RoundCaps = 2;
303
304 float roundCapRadius = 0;
305 // Default to intersection and no round caps.
306 float flags = kIntersection_NoRoundCaps;
307 // Determine if we need round caps.
308 if (isStroke &&
309 params.strokeStyle().halfWidth() > 0 &&
310 params.strokeStyle().cap() == SkPaint::kRound_Cap) {
311 // Compute the cap center points in the normalized space.
312 float midRadius = (innerRadius + outerRadius) / (2 * outerRadius);
313 roundCapPos0 = startPoint * midRadius;
314 roundCapPos1 = stopPoint * midRadius;
315 flags = kIntersection_RoundCaps;
316 // Compute the cap radius in the normalized space.
317 roundCapRadius = (outerRadius - innerRadius) / (2 * outerRadius);
318 }
319
320 // Determine clip planes.
321 if (useCenter) {
322 SkV2 norm0 = {startPoint.y, -startPoint.x};
323 SkV2 norm1 = {stopPoint.y, -stopPoint.x};
324 // This ensures that norm0 is always the clockwise plane, and norm1 is CCW.
325 if (sweepAngleRadians < 0) {
326 std::swap(norm0, norm1);
327 }
328 norm0 = -norm0;
329 clipPlane0 = {norm0.x, norm0.y, 0.5f};
330 clipPlane1 = {norm1.x, norm1.y, 0.5f};
331 if (absSweep > SK_ScalarPI) {
332 // Union
333 flags = -flags;
334 } else {
335 // Intersection
336 // Highly acute arc. We need to clip the vertices to the perpendicular half-plane.
337 if (!isStroke && absSweep < 0.5f*SK_ScalarPI) {
338 // We do this clipping in normalized space so use our original local points.
339 // Should already be normalized since they're sin/cos.
340 SkV2 localNorm0 = {localPoints[0].y, -localPoints[0].x};
341 SkV2 localNorm1 = {localPoints[1].y, -localPoints[1].x};
342 // This ensures that norm0 is always the clockwise plane, and norm1 is CCW.
343 if (sweepAngleRadians < 0) {
344 std::swap(localNorm0, localNorm1);
345 }
346 // Negate norm0 and compute the perpendicular of the difference
347 SkV2 clipNorm = {-localNorm0.y - localNorm1.y, localNorm1.x + localNorm0.x};
348 clipNorm = clipNorm.normalize();
349 // This should give us 1/2 pixel spacing from the half-plane
350 // after transforming from normalized to local to device space.
351 float dist = 0.5f / radius / transform.maxScaleFactor();
352 geoClipPlane = {clipNorm.x, clipNorm.y, dist};
353 }
354 }
355 } else {
356 // We clip to a secant of the original circle, only one clip plane
357 startPoint *= radius;
358 stopPoint *= radius;
359 SkV2 norm = {startPoint.y - stopPoint.y, stopPoint.x - startPoint.x};
360 norm = norm.normalize();
361 if (sweepAngleRadians > 0) {
362 norm = -norm;
363 }
364 float d = -norm.dot(startPoint) + 0.5f;
365 clipPlane0 = {norm.x, norm.y, d};
366 clipPlane1 = {0.f, 0.f, 1.f}; // no clipping
367 }
368
369 if (isStroke && innerRadius < -SK_ScalarHalf) {
370 // Reset the inner radius to render a filled arc instead of a stroked arc, as the stroke
371 // width is greater than or equal to the oval's width.
372 innerRadius = -SK_ScalarHalf;
373 localInnerRadius = 0.f;
374 }
375
376 // The inner radius in the vertex data must be specified in normalized space.
377 innerRadius = innerRadius / outerRadius;
378
379 vw << localCenter << localOuterRadius << localInnerRadius
380 << outerRadius << innerRadius << flags
381 << geoClipPlane << clipPlane0 << clipPlane1
382 << roundCapPos0 << roundCapPos1 << roundCapRadius
383 << params.order().depthAsFloat()
384 << ssboIndex
385 << m.rc(0,0) << m.rc(1,0) << m.rc(3,0) // mat0
386 << m.rc(0,1) << m.rc(1,1) << m.rc(3,1) // mat1
387 << m.rc(0,3) << m.rc(1,3) << m.rc(3,3); // mat2
388 }
389
390 void CircularArcRenderStep::writeUniformsAndTextures(const DrawParams&,
391 PipelineDataGatherer* gatherer) const {
392 // All data is uploaded as instance attributes, so no uniforms are needed.
393 SkDEBUGCODE(gatherer->checkRewind());
394 }
395
396 } // namespace skgpu::graphite