Debian Codegraph @

src/gpu/graphite/compute/VelloRenderer.cpp

raw
1 /*
2 * Copyright 2023 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/compute/VelloRenderer.h"
9
10 #include "include/core/SkPath.h"
11 #include "include/core/SkTypes.h"
12 #include "include/gpu/graphite/Recorder.h"
13 #include "src/core/SkGeometry.h"
14 #include "src/core/SkPathPriv.h"
15 #include "src/core/SkTraceEvent.h"
16 #include "src/gpu/graphite/BufferManager.h"
17 #include "src/gpu/graphite/Caps.h"
18 #include "src/gpu/graphite/DrawParams.h"
19 #include "src/gpu/graphite/Log.h"
20 #include "src/gpu/graphite/PipelineData.h"
21 #include "src/gpu/graphite/RecorderPriv.h"
22 #include "src/gpu/graphite/TextureProxy.h"
23 #include "src/gpu/graphite/TextureUtils.h"
24 #include "src/gpu/graphite/UniformManager.h"
25 #include "src/gpu/graphite/compute/DispatchGroup.h"
26 #include "src/gpu/graphite/geom/Transform.h"
27
28 #include <algorithm>
29
30 namespace skgpu::graphite {
31 namespace {
32
33 BindBufferInfo new_scratch_slice(BufferSubAllocator& scratch) {
34 size_t size = scratch.remainingBytes(); // Use the whole buffer.
35 return scratch.getSubrange(size, /*stride=*/1);
36 }
37
38 BindBufferInfo new_indirect_slice(DrawBufferManager* mgr, size_t size) {
39 return mgr->getIndirectStorage(size, ClearBuffer::kYes);
40 }
41
42 ::rust::Slice<uint8_t> to_slice(SkSpan<uint8_t> slice) {
43 return {slice.data(), slice.size_bytes()};
44 }
45
46 vello_cpp::Affine to_vello_affine(const SkMatrix& m) {
47 // Vello currently doesn't support perspective scaling and the encoding only accepts a 2x3
48 // affine transform matrix.
49 return {{m.get(0), m.get(3), m.get(1), m.get(4), m.get(2), m.get(5)}};
50 }
51
52 vello_cpp::Point to_vello_point(const SkPoint& p) { return {p.x(), p.y()}; }
53
54 vello_cpp::Color to_vello_color(const SkColor4f& color) {
55 SkColor c = color.toSkColor();
56 return {
57 static_cast<uint8_t>(SkColorGetR(c)),
58 static_cast<uint8_t>(SkColorGetG(c)),
59 static_cast<uint8_t>(SkColorGetB(c)),
60 static_cast<uint8_t>(SkColorGetA(c)),
61 };
62 }
63
64 WorkgroupSize to_wg_size(const vello_cpp::WorkgroupSize& src) {
65 return WorkgroupSize(src.x, src.y, src.z);
66 }
67
68 vello_cpp::Fill to_fill_type(SkPathFillType fillType) {
69 // Vello does not provide an encoding for inverse fill types. When Skia uses vello to render
70 // a coverage mask for an inverse fill, it encodes a regular fill and inverts the coverage value
71 // after sampling the mask.
72 switch (fillType) {
73 case SkPathFillType::kWinding:
74 case SkPathFillType::kInverseWinding:
75 return vello_cpp::Fill::NonZero;
76 case SkPathFillType::kEvenOdd:
77 case SkPathFillType::kInverseEvenOdd:
78 return vello_cpp::Fill::EvenOdd;
79 }
80 return vello_cpp::Fill::NonZero;
81 }
82
83 vello_cpp::CapStyle to_cap_style(SkPaint::Cap cap) {
84 switch (cap) {
85 case SkPaint::Cap::kButt_Cap:
86 return vello_cpp::CapStyle::Butt;
87 case SkPaint::Cap::kRound_Cap:
88 return vello_cpp::CapStyle::Round;
89 case SkPaint::Cap::kSquare_Cap:
90 return vello_cpp::CapStyle::Square;
91 }
92 SkUNREACHABLE;
93 }
94
95 vello_cpp::JoinStyle to_join_style(SkPaint::Join join) {
96 switch (join) {
97 case SkPaint::Join::kMiter_Join:
98 return vello_cpp::JoinStyle::Miter;
99 case SkPaint::Join::kBevel_Join:
100 return vello_cpp::JoinStyle::Bevel;
101 case SkPaint::Join::kRound_Join:
102 return vello_cpp::JoinStyle::Round;
103 }
104 SkUNREACHABLE;
105 }
106
107 vello_cpp::Stroke to_stroke(const SkStrokeRec& style) {
108 return vello_cpp::Stroke{
109 /*width=*/style.getWidth(),
110 /*miter_limit=*/style.getMiter(),
111 /*cap*/ to_cap_style(style.getCap()),
112 /*join*/ to_join_style(style.getJoin()),
113 };
114 }
115
116 class PathIter : public vello_cpp::PathIterator {
117 public:
118 PathIter(const SkPath& path, const Transform& t)
119 : fIterate(path), fIter(fIterate.begin()), fTransform(t) {}
120
121 bool next_element(vello_cpp::PathElement* outElem) override {
122 if (fConicQuadIdx < fConicConverter.countQuads()) {
123 SkASSERT(fConicQuads != nullptr);
124 outElem->verb = vello_cpp::PathVerb::QuadTo;
125 int pointIdx = fConicQuadIdx * 2;
126 outElem->points[0] = to_vello_point(fConicQuads[pointIdx]);
127 outElem->points[1] = to_vello_point(fConicQuads[pointIdx + 1]);
128 outElem->points[2] = to_vello_point(fConicQuads[pointIdx + 2]);
129 fConicQuadIdx++;
130 return true;
131 }
132
133 if (fIter == fIterate.end()) {
134 return false;
135 }
136
137 SkASSERT(outElem);
138 auto [verb, points, weights] = *fIter;
139 fIter++;
140
141 switch (verb) {
142 case SkPathVerb::kMove:
143 outElem->verb = vello_cpp::PathVerb::MoveTo;
144 outElem->points[0] = to_vello_point(points[0]);
145 break;
146 case SkPathVerb::kLine:
147 outElem->verb = vello_cpp::PathVerb::LineTo;
148 outElem->points[0] = to_vello_point(points[0]);
149 outElem->points[1] = to_vello_point(points[1]);
150 break;
151 case SkPathVerb::kConic:
152 // The vello encoding API doesn't handle conic sections. Approximate it with
153 // quadratic Béziers.
154 SkASSERT(fConicQuadIdx >= fConicConverter.countQuads()); // No other conic->quad
155 // conversions should be
156 // in progress
157 fConicQuads = fConicConverter.computeQuads(
158 points, *weights, 0.25 / fTransform.maxScaleFactor());
159 outElem->verb = vello_cpp::PathVerb::QuadTo;
160 outElem->points[0] = to_vello_point(fConicQuads[0]);
161 outElem->points[1] = to_vello_point(fConicQuads[1]);
162 outElem->points[2] = to_vello_point(fConicQuads[2]);
163
164 // The next call to `next_element` will yield the next quad in the list (at index 1)
165 // if `fConicConverter` contains more than 1 quad.
166 fConicQuadIdx = 1;
167 break;
168 case SkPathVerb::kQuad:
169 outElem->verb = vello_cpp::PathVerb::QuadTo;
170 outElem->points[0] = to_vello_point(points[0]);
171 outElem->points[1] = to_vello_point(points[1]);
172 outElem->points[2] = to_vello_point(points[2]);
173 break;
174 case SkPathVerb::kCubic:
175 outElem->verb = vello_cpp::PathVerb::CurveTo;
176 outElem->points[0] = to_vello_point(points[0]);
177 outElem->points[1] = to_vello_point(points[1]);
178 outElem->points[2] = to_vello_point(points[2]);
179 outElem->points[3] = to_vello_point(points[3]);
180 break;
181 case SkPathVerb::kClose:
182 outElem->verb = vello_cpp::PathVerb::Close;
183 break;
184 }
185
186 return true;
187 }
188
189 private:
190 SkPathPriv::Iterate fIterate;
191 SkPathPriv::RangeIter fIter;
192
193 // Variables used to track conic to quadratic spline conversion. `fTransform` is used to
194 // determine the subpixel error tolerance in device coordinate space.
195 const Transform& fTransform;
196 SkAutoConicToQuads fConicConverter;
197 const SkPoint* fConicQuads = nullptr;
198 int fConicQuadIdx = 0;
199 };
200
201 } // namespace
202
203 VelloScene::VelloScene() : fEncoding(vello_cpp::new_encoding()) {}
204
205 void VelloScene::reset() {
206 fEncoding->reset();
207 }
208
209 void VelloScene::solidFill(const SkPath& shape,
210 const SkColor4f& fillColor,
211 const SkPathFillType fillType,
212 const Transform& t) {
213 PathIter iter(shape, t);
214 fEncoding->fill(to_fill_type(fillType),
215 to_vello_affine(t),
216 {vello_cpp::BrushKind::Solid, {to_vello_color(fillColor)}},
217 iter);
218 }
219
220 void VelloScene::solidStroke(const SkPath& shape,
221 const SkColor4f& fillColor,
222 const SkStrokeRec& style,
223 const Transform& t) {
224 // TODO: Obtain dashing pattern here and let Vello handle dashing on the CPU while
225 // encoding the path?
226 PathIter iter(shape, t);
227 vello_cpp::Brush brush{vello_cpp::BrushKind::Solid, {to_vello_color(fillColor)}};
228 fEncoding->stroke(to_stroke(style), to_vello_affine(t), brush, iter);
229 }
230
231 void VelloScene::pushClipLayer(const SkPath& shape, const Transform& t) {
232 PathIter iter(shape, t);
233 fEncoding->begin_clip(to_vello_affine(t), iter);
234 SkDEBUGCODE(fLayers++;)
235 }
236
237 void VelloScene::popClipLayer() {
238 SkASSERT(fLayers > 0);
239 fEncoding->end_clip();
240 SkDEBUGCODE(fLayers--;)
241 }
242
243 void VelloScene::append(const VelloScene& other) {
244 fEncoding->append(*other.fEncoding);
245 }
246
247 VelloRenderer::VelloRenderer(const Caps* caps) {
248 if (ComputeShaderCoverageMaskTargetFormat(caps) == kAlpha_8_SkColorType) {
249 fFineArea = std::make_unique<VelloFineAreaAlpha8Step>();
250 fFineMsaa16 = std::make_unique<VelloFineMsaa16Alpha8Step>();
251 fFineMsaa8 = std::make_unique<VelloFineMsaa8Alpha8Step>();
252 } else {
253 fFineArea = std::make_unique<VelloFineAreaStep>();
254 fFineMsaa16 = std::make_unique<VelloFineMsaa16Step>();
255 fFineMsaa8 = std::make_unique<VelloFineMsaa8Step>();
256 }
257 }
258
259 VelloRenderer::~VelloRenderer() = default;
260
261 std::unique_ptr<DispatchGroup> VelloRenderer::renderScene(const RenderParams& params,
262 const VelloScene& scene,
263 sk_sp<TextureProxy> target,
264 Recorder* recorder) const {
265 TRACE_EVENT0("skia.gpu", TRACE_FUNC);
266 SkASSERT(target);
267
268 if (scene.fEncoding->is_empty()) {
269 return nullptr;
270 }
271
272 if (params.fWidth == 0 || params.fHeight == 0) {
273 return nullptr;
274 }
275
276 // TODO: validate that the pixel format matches the pipeline layout.
277 // Clamp the draw region to the target texture dimensions.
278 const SkISize dims = target->dimensions();
279 if (dims.isEmpty() || dims.fWidth < 0 || dims.fHeight < 0) {
280 SKGPU_LOG_W("VelloRenderer: cannot render to an empty target");
281 return nullptr;
282 }
283
284 SkASSERT(scene.fLayers == 0); // Begin/end clips must be matched.
285 auto config = scene.fEncoding->prepare_render(
286 std::min(params.fWidth, static_cast<uint32_t>(dims.fWidth)),
287 std::min(params.fHeight, static_cast<uint32_t>(dims.fHeight)),
288 to_vello_color(params.fBaseColor));
289 auto dispatchInfo = config->workgroup_counts();
290 auto bufferSizes = config->buffer_sizes();
291
292 DispatchGroup::Builder builder(recorder);
293
294 // In total there are 25 resources that are used across the full pipeline stages. The sizes of
295 // these resources depend on the encoded scene. We allocate all of them and assign them
296 // directly to the builder here instead of delegating the logic to the ComputeSteps.
297 DrawBufferManager* bufMgr = recorder->priv().drawBufferManager();
298
299 // TODO(b/285189802): The default sizes for the bump buffers (~97MB) exceed Graphite's resource
300 // budget if multiple passes are necessary per frame (250MB, see ResouceCache.h). We apply a
301 // crude size reduction here which seems to be enough for a 4k x 4k atlas render for the GMs
302 // that we have tested. The numbers below are able to render GM_longpathdash with CPU-side
303 // stroke expansion.
304 //
305 // We need to come up with a better approach to accurately predict the sizes for these buffers
306 // based on the scene encoding and our resource budget. It should be possible to build a
307 // conservative estimate using the total number of path verbs, some heuristic based on the verb
308 // and the path's transform, and the total number of tiles.
309 //
310 // The following numbers amount to ~48MB
311 const size_t lines_size = bufferSizes.lines;
312 const size_t bin_data_size = bufferSizes.bin_data;
313 const size_t tiles_size = bufferSizes.tiles;
314 const size_t segments_size = bufferSizes.segments;
315 const size_t seg_counts_size = bufferSizes.seg_counts;
316 const size_t ptcl_size = bufferSizes.ptcl;
317
318 // See the comments in VelloComputeSteps.h for an explanation of the logic here.
319
320 {
321 size_t uboSize = config->config_uniform_buffer_size();
322 auto [uboWriter, configBuf, _] = bufMgr->getMappedUniformBuffer(uboSize, /*stride=*/1);
323 if (!uboWriter ||
324 !config->write_config_uniform_buffer(to_slice(uboWriter.slice(uboSize)))) {
325 return nullptr;
326 }
327 builder.assignSharedBuffer(configBuf, kVelloSlot_ConfigUniform);
328 }
329
330 {
331 size_t sceneSize = config->scene_buffer_size();
332 auto [sceneWriter, sceneBuf, _] = bufMgr->getMappedStorageBuffer(sceneSize, /*stride=*/1);
333 if (!sceneWriter || !config->write_scene_buffer(to_slice(sceneWriter.slice(sceneSize)))) {
334 return nullptr;
335 }
336 builder.assignSharedBuffer(sceneBuf, kVelloSlot_Scene);
337 }
338
339 // Buffers get cleared ahead of the entire DispatchGroup. Allocate the bump buffer early to
340 // avoid a potentially recycled (and prematurely cleared) scratch buffer.
341 BufferSubAllocator bump = bufMgr->getScratchStorage(bufferSizes.bump_alloc);
342 builder.assignSharedBuffer(new_scratch_slice(bump), kVelloSlot_BumpAlloc, ClearBuffer::kYes);
343
344 // path_reduce
345 BufferSubAllocator tagmonoids = bufMgr->getScratchStorage(bufferSizes.path_monoids);
346 {
347 // This can be immediately returned after input processing.
348 BufferSubAllocator pathtagReduceOutput =
349 bufMgr->getScratchStorage(bufferSizes.path_reduced);
350 builder.assignSharedBuffer(new_scratch_slice(pathtagReduceOutput),
351 kVelloSlot_PathtagReduceOutput);
352 builder.assignSharedBuffer(new_scratch_slice(tagmonoids), kVelloSlot_TagMonoid);
353 builder.appendStep(&fPathtagReduce, to_wg_size(dispatchInfo.path_reduce));
354
355 // If the input is too large to be fully processed by a single workgroup then a second
356 // reduce step and two scan steps are necessary. Otherwise one reduce+scan pair is
357 // sufficient.
358 //
359 // In either case, the result is `tagmonoids`.
360 if (dispatchInfo.use_large_path_scan) {
361 BufferSubAllocator reduced2 = bufMgr->getScratchStorage(bufferSizes.path_reduced2);
362 BufferSubAllocator reducedScan =
363 bufMgr->getScratchStorage(bufferSizes.path_reduced_scan);
364
365 builder.assignSharedBuffer(new_scratch_slice(reduced2),
366 kVelloSlot_LargePathtagReduceSecondPassOutput);
367 builder.assignSharedBuffer(new_scratch_slice(reducedScan),
368 kVelloSlot_LargePathtagScanFirstPassOutput);
369
370 builder.appendStep(&fPathtagReduce2, to_wg_size(dispatchInfo.path_reduce2));
371 builder.appendStep(&fPathtagScan1, to_wg_size(dispatchInfo.path_scan1));
372 builder.appendStep(&fPathtagScanLarge, to_wg_size(dispatchInfo.path_scan));
373 } else {
374 builder.appendStep(&fPathtagScanSmall, to_wg_size(dispatchInfo.path_scan));
375 }
376 }
377
378 // bbox_clear
379 BufferSubAllocator pathBboxes = bufMgr->getScratchStorage(bufferSizes.path_bboxes);
380 builder.assignSharedBuffer(new_scratch_slice(pathBboxes), kVelloSlot_PathBBoxes);
381 builder.appendStep(&fBboxClear, to_wg_size(dispatchInfo.bbox_clear));
382
383 // flatten
384 BufferSubAllocator lines = bufMgr->getScratchStorage(lines_size);
385 builder.assignSharedBuffer(new_scratch_slice(lines), kVelloSlot_Lines);
386 builder.appendStep(&fFlatten, to_wg_size(dispatchInfo.flatten));
387
388 tagmonoids.reset();
389
390 // draw_reduce
391 BufferSubAllocator drawReduced = bufMgr->getScratchStorage(bufferSizes.draw_reduced);
392 builder.assignSharedBuffer(new_scratch_slice(drawReduced), kVelloSlot_DrawReduceOutput);
393 builder.appendStep(&fDrawReduce, to_wg_size(dispatchInfo.draw_reduce));
394
395 // draw_leaf
396 BufferSubAllocator drawMonoids = bufMgr->getScratchStorage(bufferSizes.draw_monoids);
397 BufferSubAllocator binData = bufMgr->getScratchStorage(bin_data_size);
398 // A clip input buffer must still get bound even if the encoding doesn't contain any clips
399 BufferSubAllocator clipInput = bufMgr->getScratchStorage(bufferSizes.clip_inps);
400 builder.assignSharedBuffer(new_scratch_slice(drawMonoids), kVelloSlot_DrawMonoid);
401 builder.assignSharedBuffer(new_scratch_slice(binData), kVelloSlot_InfoBinData);
402 builder.assignSharedBuffer(new_scratch_slice(clipInput), kVelloSlot_ClipInput);
403 builder.appendStep(&fDrawLeaf, to_wg_size(dispatchInfo.draw_leaf));
404
405 drawReduced.reset();
406
407 // clip_reduce, clip_leaf
408 // The clip bbox buffer is always an input to the binning stage, even when the encoding doesn't
409 // contain any clips
410 BufferSubAllocator clipBboxes = bufMgr->getScratchStorage(bufferSizes.clip_bboxes);
411 builder.assignSharedBuffer(new_scratch_slice(clipBboxes), kVelloSlot_ClipBBoxes);
412 WorkgroupSize clipReduceWgCount = to_wg_size(dispatchInfo.clip_reduce);
413 WorkgroupSize clipLeafWgCount = to_wg_size(dispatchInfo.clip_leaf);
414 bool doClipReduce = clipReduceWgCount.scalarSize() > 0u;
415 bool doClipLeaf = clipLeafWgCount.scalarSize() > 0u;
416 if (doClipReduce || doClipLeaf) {
417 BufferSubAllocator clipBic = bufMgr->getScratchStorage(bufferSizes.clip_bics);
418 BufferSubAllocator clipEls = bufMgr->getScratchStorage(bufferSizes.clip_els);
419 builder.assignSharedBuffer(new_scratch_slice(clipBic), kVelloSlot_ClipBicyclic);
420 builder.assignSharedBuffer(new_scratch_slice(clipEls), kVelloSlot_ClipElement);
421 if (doClipReduce) {
422 builder.appendStep(&fClipReduce, clipReduceWgCount);
423 }
424 if (doClipLeaf) {
425 builder.appendStep(&fClipLeaf, clipLeafWgCount);
426 }
427 }
428
429 clipInput.reset();
430
431 // binning
432 BufferSubAllocator drawBboxes = bufMgr->getScratchStorage(bufferSizes.draw_bboxes);
433 BufferSubAllocator binHeaders = bufMgr->getScratchStorage(bufferSizes.bin_headers);
434 builder.assignSharedBuffer(new_scratch_slice(drawBboxes), kVelloSlot_DrawBBoxes);
435 builder.assignSharedBuffer(new_scratch_slice(binHeaders), kVelloSlot_BinHeader);
436 builder.appendStep(&fBinning, to_wg_size(dispatchInfo.binning));
437
438 pathBboxes.reset();
439 clipBboxes.reset();
440
441 // tile_alloc
442 BufferSubAllocator paths = bufMgr->getScratchStorage(bufferSizes.paths);
443 BufferSubAllocator tiles = bufMgr->getScratchStorage(tiles_size);
444 builder.assignSharedBuffer(new_scratch_slice(paths), kVelloSlot_Path);
445 builder.assignSharedBuffer(new_scratch_slice(tiles), kVelloSlot_Tile);
446 builder.appendStep(&fTileAlloc, to_wg_size(dispatchInfo.tile_alloc));
447
448 drawBboxes.reset();
449
450 // path_count_setup
451 auto indirectCountBuffer = new_indirect_slice(bufMgr, bufferSizes.indirect_count);
452 builder.assignSharedBuffer(indirectCountBuffer, kVelloSlot_IndirectCount);
453 builder.appendStep(&fPathCountSetup, to_wg_size(dispatchInfo.path_count_setup));
454
455 // Rasterization stage scratch buffers.
456 BufferSubAllocator seg_counts = bufMgr->getScratchStorage(seg_counts_size);
457 BufferSubAllocator segments = bufMgr->getScratchStorage(segments_size);
458 BufferSubAllocator ptcl = bufMgr->getScratchStorage(ptcl_size);
459
460 // path_count
461 builder.assignSharedBuffer(new_scratch_slice(seg_counts), kVelloSlot_SegmentCounts);
462 builder.appendStepIndirect(&fPathCount, indirectCountBuffer);
463
464 // backdrop
465 builder.appendStep(&fBackdrop, to_wg_size(dispatchInfo.backdrop));
466
467 // coarse
468 builder.assignSharedBuffer(new_scratch_slice(ptcl), kVelloSlot_PTCL);
469 builder.appendStep(&fCoarse, to_wg_size(dispatchInfo.coarse));
470
471 // path_tiling_setup
472 builder.appendStep(&fPathTilingSetup, to_wg_size(dispatchInfo.path_tiling_setup));
473
474 // path_tiling
475 builder.assignSharedBuffer(new_scratch_slice(segments), kVelloSlot_Segments);
476 builder.appendStepIndirect(&fPathTiling, indirectCountBuffer);
477
478 // fine
479 builder.assignSharedTexture(std::move(target), kVelloSlot_OutputImage);
480 const ComputeStep* fineVariant = nullptr;
481 switch (params.fAaConfig) {
482 case VelloAaConfig::kAnalyticArea:
483 fineVariant = fFineArea.get();
484 break;
485 case VelloAaConfig::kMSAA16:
486 fineVariant = fFineMsaa16.get();
487 break;
488 case VelloAaConfig::kMSAA8:
489 fineVariant = fFineMsaa8.get();
490 break;
491 }
492 SkASSERT(fineVariant != nullptr);
493 builder.appendStep(fineVariant, to_wg_size(dispatchInfo.fine));
494
495 return builder.finalize();
496 }
497
498 } // namespace skgpu::graphite