Debian Codegraph @

src/gpu/graphite/ComputePathAtlas.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 #include "src/gpu/graphite/ComputePathAtlas.h"
8
9 #include "include/gpu/graphite/Recorder.h"
10 #include "src/core/SkIPoint16.h"
11 #include "src/gpu/graphite/AtlasProvider.h"
12 #include "src/gpu/graphite/Log.h"
13 #include "src/gpu/graphite/RecorderPriv.h"
14 #include "src/gpu/graphite/TextureProxy.h"
15 #include "src/gpu/graphite/TextureUtils.h"
16
17 #ifdef SK_ENABLE_VELLO_SHADERS
18 #include "src/core/SkTraceEvent.h"
19 #include "src/gpu/graphite/ContextOptionsPriv.h"
20 #include "src/gpu/graphite/RendererProvider.h"
21 #include "src/gpu/graphite/compute/DispatchGroup.h"
22 #include "src/gpu/graphite/geom/Transform.h"
23 #endif
24
25 #include <cmath>
26 #include <cstddef>
27 #include <cstdint>
28
29 enum SkColorType : int;
30
31 namespace skgpu::graphite {
32 namespace {
33
34 // TODO: This is the maximum target dimension that vello can handle today.
35 constexpr uint16_t kComputeAtlasDim = 4096;
36
37 // TODO: Currently we reject shapes that are smaller than a subset of a given atlas page to avoid
38 // creating too many flushes in a Recording containing many large path draws. These shapes often
39 // don't make efficient use of the available atlas texture space and the cost of sequential
40 // dispatches to render multiple atlas pages can be prohibitive.
41 constexpr size_t kBboxAreaThreshold = 1024 * 512;
42
43 // Coordinate size that is too large for vello to handle efficiently. See the discussion on
44 // https://github.com/linebender/vello/pull/542.
45 constexpr float kCoordinateThreshold = 1e10;
46
47 } // namespace
48
49 ComputePathAtlas::ComputePathAtlas(Recorder* recorder)
50 : PathAtlas(recorder, kComputeAtlasDim, kComputeAtlasDim)
51 , fRectanizer(this->width(), this->height()) {}
52
53 bool ComputePathAtlas::initializeTextureIfNeeded() {
54 if (!fTexture) {
55 SkColorType targetCT = ComputeShaderCoverageMaskTargetFormat(fRecorder->priv().caps());
56 fTexture = fRecorder->priv().atlasProvider()->getAtlasTexture(fRecorder,
57 this->width(),
58 this->height(),
59 targetCT,
60 /*identifier=*/0,
61 /*requireStorageUsage=*/true);
62 }
63 return fTexture != nullptr;
64 }
65
66 bool ComputePathAtlas::isSuitableForAtlasing(const Rect& transformedShapeBounds,
67 const Rect& clipBounds) const {
68 Rect shapeBounds = transformedShapeBounds.makeRoundOut();
69 Rect maskBounds = shapeBounds.makeIntersect(clipBounds);
70 skvx::float2 maskSize = maskBounds.size();
71 float width = maskSize.x(), height = maskSize.y();
72
73 if (width > this->width() || height > this->height()) {
74 return false;
75 }
76
77 // For now we're allowing paths that are smaller than 1/32nd of the full 4096x4096 atlas size
78 // to prevent the atlas texture from filling up too often. There are several approaches we
79 // should explore to alleviate the cost of atlasing large paths.
80 if (width * height > kBboxAreaThreshold) {
81 return false;
82 }
83
84 // Reject pathological shapes that vello can't handle efficiently yet.
85 skvx::float2 unclippedSize = shapeBounds.size();
86 if (std::fabs(unclippedSize.x()) > kCoordinateThreshold ||
87 std::fabs(unclippedSize.y()) > kCoordinateThreshold) {
88 return false;
89 }
90
91 return true;
92 }
93
94 sk_sp<TextureProxy> ComputePathAtlas::addRect(skvx::half2 maskSize,
95 SkIPoint16* outPos) {
96 if (!this->initializeTextureIfNeeded()) {
97 SKGPU_LOG_E("Failed to instantiate an atlas texture");
98 return nullptr;
99 }
100
101 // An empty mask always fits, so just return the texture.
102 // TODO: This may not be needed if we can handle clipped out bounds with inverse fills
103 // another way. See PathAtlas::addShape().
104 if (!all(maskSize)) {
105 *outPos = {0, 0};
106 return fTexture;
107 }
108
109 if (!fRectanizer.addPaddedRect(maskSize.x(), maskSize.y(), kEntryPadding, outPos)) {
110 return nullptr;
111 }
112
113 return fTexture;
114 }
115
116 void ComputePathAtlas::reset() {
117 fRectanizer.reset();
118
119 this->onReset();
120 }
121
122 #ifdef SK_ENABLE_VELLO_SHADERS
123
124 /**
125 * ComputePathAtlas that uses a VelloRenderer.
126 */
127 class VelloComputePathAtlas final : public ComputePathAtlas {
128 public:
129 explicit VelloComputePathAtlas(Recorder* recorder)
130 : ComputePathAtlas(recorder)
131 , fCachedAtlasMgr(fWidth, fHeight, recorder->priv().caps()) {}
132 // Record the compute dispatches that will draw the atlas contents.
133 bool recordDispatches(Recorder*, ComputeTask::DispatchGroupList*) const override;
134
135 private:
136 sk_sp<TextureProxy> onAddShape(const Shape&,
137 const Transform& localToDevice,
138 const SkStrokeRec&,
139 skvx::half2 maskOrigin,
140 skvx::half2 maskSize,
141 SkIVector transformedMaskOffset,
142 skvx::half2* outPos) override;
143 void onReset() override {
144 fCachedAtlasMgr.onReset();
145
146 fUncachedScene.reset();
147 fUncachedOccupiedArea = { 0, 0 };
148 }
149
150 class VelloAtlasMgr : public PathAtlas::DrawAtlasMgr {
151 public:
152 VelloAtlasMgr(size_t width, size_t height, const Caps* caps)
153 : PathAtlas::DrawAtlasMgr(width, height, width, height,
154 DrawAtlas::UseStorageTextures::kYes,
155 /*label=*/"VelloPathAtlas", caps) {}
156
157 bool recordDispatches(Recorder* recorder, ComputeTask::DispatchGroupList* dispatches) const;
158
159 void onReset() {
160 fDrawAtlas->markUsedPlotsAsFull();
161 for (int i = 0; i < PlotLocator::kMaxMultitexturePages; ++i) {
162 fScenes[i].reset();
163 fOccupiedAreas[i] = {0, 0};
164 }
165 }
166
167 protected:
168 bool onAddToAtlas(const Shape&,
169 const Transform& localToDevice,
170 const SkStrokeRec&,
171 SkIRect shapeBounds,
172 SkIVector transformedMaskOffset,
173 const AtlasLocator&) override;
174
175 private:
176 VelloScene fScenes[PlotLocator::kMaxMultitexturePages];
177 SkISize fOccupiedAreas[PlotLocator::kMaxMultitexturePages] = {
178 {0, 0}, {0, 0}, {0, 0}, {0, 0}
179 };
180 };
181
182 VelloAtlasMgr fCachedAtlasMgr;
183
184 // Contains the encoded scene buffer data that serves as the input to a vello compute pass.
185 // For the uncached atlas.
186 VelloScene fUncachedScene;
187
188 // Occupied bounds of the uncached atlas
189 SkISize fUncachedOccupiedArea = { 0, 0 };
190 };
191
192 static VelloAaConfig get_vello_aa_config(Recorder* recorder) {
193 PathRendererStrategy strategy = recorder->priv().rendererProvider()->pathRendererStrategy();
194 if (strategy == PathRendererStrategy::kComputeMSAA16) {
195 return VelloAaConfig::kMSAA16;
196 } else if (strategy == PathRendererStrategy::kComputeMSAA8) {
197 return VelloAaConfig::kMSAA8;
198 } else {
199 SkASSERT(strategy == PathRendererStrategy::kComputeAnalyticAA);
200 return VelloAaConfig::kAnalyticArea;
201 }
202 }
203
204 static std::unique_ptr<DispatchGroup> render_vello_scene(Recorder* recorder,
205 sk_sp<TextureProxy> texture,
206 const VelloScene& scene,
207 SkISize occupiedArea,
208 VelloAaConfig config) {
209 return recorder->priv().rendererProvider()->velloRenderer()->renderScene(
210 {(uint32_t)occupiedArea.width(),
211 (uint32_t)occupiedArea.height(),
212 SkColors::kBlack,
213 config},
214 scene,
215 std::move(texture),
216 recorder);
217 }
218
219 static void add_shape_to_scene(const Shape& shape,
220 const Transform& localToDevice,
221 const SkStrokeRec& style,
222 Rect atlasBounds,
223 SkIVector transformedMaskOffset,
224 VelloScene* scene,
225 SkISize* occupiedArea) {
226 occupiedArea->fWidth = std::max(occupiedArea->fWidth,
227 (int)atlasBounds.right() + PathAtlas::kEntryPadding);
228 occupiedArea->fHeight = std::max(occupiedArea->fHeight,
229 (int)atlasBounds.bot() + PathAtlas::kEntryPadding);
230
231 // TODO(b/283876964): Apply clips here. Initially we'll need to encode the clip stack repeatedly
232 // for each shape since the full vello renderer treats clips and their affected draws as a
233 // single shape hierarchy in the same scene coordinate space. For coverage masks we want each
234 // mask to be transformed to its atlas allocation coordinates and for the clip to be applied
235 // with a translation relative to the atlas slot.
236 //
237 // Repeatedly encoding the clip stack should be relatively cheap (depending on how deep the
238 // clips get) however it is wasteful both in terms of time and memory. If this proves to hurt
239 // performance, future work will explore building an atlas-oriented element processing stage
240 // that applies the atlas-relative translation while evaluating the stack monoid on the GPU.
241
242 // Clip the mask to the bounds of the atlas slot, which are already inset by 1px relative to
243 // the bounds that the Rectanizer assigned.
244 SkPath clipRect = SkPath::Rect(atlasBounds.asSkRect());
245 scene->pushClipLayer(clipRect, Transform::Identity());
246
247 // The atlas transform of the shape is `localToDevice` translated by the top-left offset of the
248 // 'atlasBounds' and the inverse of the base mask transform offset.
249 Transform atlasTransform = localToDevice.postTranslate(
250 atlasBounds.x()-transformedMaskOffset.x(), atlasBounds.y()-transformedMaskOffset.y());
251 SkPath devicePath = shape.asPath();
252
253 // For stroke-and-fill, draw two masks into the same atlas slot: one for the stroke and one for
254 // the fill.
255 SkStrokeRec::Style styleType = style.getStyle();
256 if (styleType == SkStrokeRec::kStroke_Style ||
257 styleType == SkStrokeRec::kHairline_Style ||
258 styleType == SkStrokeRec::kStrokeAndFill_Style) {
259 // We need to special-case hairline strokes and strokes with sub-pixel width as Vello
260 // draws these with aliasing and the results are barely visible. Draw the stroke with a
261 // device-space width of 1 pixel and scale down the alpha by the true width to approximate
262 // the sampled area.
263 float width = style.getWidth();
264 float deviceWidth = width * atlasTransform.maxScaleFactor();
265 if (style.isHairlineStyle() || deviceWidth <= 1.0) {
266 // Both strokes get 1/2 weight scaled by the theoretical area (1 for hairlines,
267 // `deviceWidth` otherwise).
268 SkColor4f color = SkColors::kRed;
269 color.fR *= style.isHairlineStyle() ? 1.0 : deviceWidth;
270
271 // Transform the stroke's width to its local coordinate space since it'll get drawn with
272 // `atlasTransform`.
273 float transformedWidth = 1.0f / atlasTransform.maxScaleFactor();
274 SkStrokeRec adjustedStyle(style);
275 adjustedStyle.setStrokeStyle(transformedWidth);
276 scene->solidStroke(devicePath, color, adjustedStyle, atlasTransform);
277 } else {
278 scene->solidStroke(devicePath, SkColors::kRed, style, atlasTransform);
279 }
280 }
281 if (styleType == SkStrokeRec::kFill_Style || styleType == SkStrokeRec::kStrokeAndFill_Style) {
282 scene->solidFill(devicePath, SkColors::kRed, shape.fillType(), atlasTransform);
283 }
284
285 scene->popClipLayer();
286 }
287
288 bool VelloComputePathAtlas::recordDispatches(Recorder* recorder,
289 ComputeTask::DispatchGroupList* dispatches) const {
290 bool addedDispatches = fCachedAtlasMgr.recordDispatches(recorder, dispatches);
291
292 if (this->texture() && !fUncachedOccupiedArea.isEmpty()) {
293 SkASSERT(recorder && recorder == fRecorder);
294
295 VelloAaConfig config = get_vello_aa_config(recorder);
296 std::unique_ptr<DispatchGroup> dispatchGroup =
297 render_vello_scene(recorder,
298 sk_ref_sp(this->texture()),
299 fUncachedScene,
300 fUncachedOccupiedArea,
301 config);
302 if (dispatchGroup) {
303 TRACE_EVENT_INSTANT1("skia.gpu", TRACE_FUNC, TRACE_EVENT_SCOPE_THREAD,
304 "# dispatches", dispatchGroup->dispatches().size());
305 dispatches->emplace_back(std::move(dispatchGroup));
306 return true;
307 } else {
308 SKGPU_LOG_E("VelloComputePathAtlas:: Failed to create dispatch group.");
309 }
310 }
311
312 return addedDispatches;
313 }
314
315 sk_sp<TextureProxy> VelloComputePathAtlas::onAddShape(
316 const Shape& shape,
317 const Transform& localToDevice,
318 const SkStrokeRec& style,
319 skvx::half2 maskOrigin,
320 skvx::half2 maskSize,
321 SkIVector transformedMaskOffset,
322 skvx::half2* outPos) {
323
324 skgpu::UniqueKey maskKey;
325 if (!shape.isVolatilePath()) {
326 // Try to locate or add to cached DrawAtlas
327 sk_sp<TextureProxy> proxy = fCachedAtlasMgr.findOrCreateEntry(fRecorder,
328 shape,
329 localToDevice,
330 style,
331 maskOrigin,
332 maskSize,
333 transformedMaskOffset,
334 outPos);
335 if (proxy) {
336 return proxy;
337 }
338 }
339
340 // Try to add to uncached texture
341 SkIPoint16 iPos;
342 sk_sp<TextureProxy> texProxy = this->addRect(maskSize, &iPos);
343 if (!texProxy) {
344 return nullptr;
345 }
346 *outPos = skvx::half2(iPos.x(), iPos.y());
347 // If the mask is empty, just return.
348 // TODO: This may not be needed if we can handle clipped out bounds with inverse fills
349 // another way. See PathAtlas::addShape().
350 if (!all(maskSize)) {
351 return texProxy;
352 }
353
354 // TODO: The compute renderer doesn't support perspective yet. We assume that the path has been
355 // appropriately transformed in that case.
356 SkASSERT(localToDevice.type() != Transform::Type::kPerspective);
357
358 // Restrict the render to the occupied area of the atlas, including entry padding so that the
359 // padded row/column is cleared when Vello renders.
360 Rect atlasBounds = Rect::XYWH(skvx::float2(iPos.x(), iPos.y()), skvx::cast<float>(maskSize));
361
362 add_shape_to_scene(shape, localToDevice, style, atlasBounds, transformedMaskOffset,
363 &fUncachedScene, &fUncachedOccupiedArea);
364
365 return texProxy;
366 }
367
368 /////////////////////////////////////////////////////////////////////////////////////////
369
370 bool VelloComputePathAtlas::VelloAtlasMgr::onAddToAtlas(const Shape& shape,
371 const Transform& localToDevice,
372 const SkStrokeRec& style,
373 SkIRect shapeBounds,
374 SkIVector transformedMaskOffset,
375 const AtlasLocator& locator) {
376 uint32_t index = locator.pageIndex();
377 const TextureProxy* texProxy = fDrawAtlas->getProxies()[index].get();
378 if (!texProxy) {
379 return false;
380 }
381
382 // TODO: The compute renderer doesn't support perspective yet. We assume that the path has been
383 // appropriately transformed in that case.
384 SkASSERT(localToDevice.type() != Transform::Type::kPerspective);
385
386 // Restrict the render to the occupied area of the atlas, including entry padding so that the
387 // padded row/column is cleared when Vello renders.
388 SkIPoint iPos = locator.topLeft();
389 Rect atlasBounds = Rect::XYWH(skvx::float2(iPos.x() + kEntryPadding, iPos.y() + kEntryPadding),
390 skvx::float2(shapeBounds.width(), shapeBounds.height()));
391
392 add_shape_to_scene(shape, localToDevice, style, atlasBounds, transformedMaskOffset,
393 &fScenes[index], &fOccupiedAreas[index]);
394
395 return true;
396 }
397
398 bool VelloComputePathAtlas::VelloAtlasMgr::recordDispatches(
399 Recorder* recorder, ComputeTask::DispatchGroupList* dispatches) const {
400 SkASSERT(recorder);
401 VelloAaConfig config = get_vello_aa_config(recorder);
402
403 bool addedDispatches = false;
404 for (int i = 0; i < 4; ++i) {
405 if (!fOccupiedAreas[i].isEmpty()) {
406 std::unique_ptr<DispatchGroup> dispatchGroup =
407 render_vello_scene(recorder,
408 fDrawAtlas->getProxies()[i],
409 fScenes[i],
410 fOccupiedAreas[i],
411 config);
412 if (dispatchGroup) {
413 TRACE_EVENT_INSTANT1("skia.gpu", TRACE_FUNC, TRACE_EVENT_SCOPE_THREAD,
414 "# dispatches", dispatchGroup->dispatches().size());
415 dispatches->emplace_back(std::move(dispatchGroup));
416 addedDispatches = true;
417 } else {
418 SKGPU_LOG_E("VelloComputePathAtlas:: Failed to create dispatch group.");
419 }
420 }
421 }
422 return addedDispatches;
423 }
424
425
426 #endif // SK_ENABLE_VELLO_SHADERS
427
428 std::unique_ptr<ComputePathAtlas> ComputePathAtlas::CreateDefault(Recorder* recorder) {
429 #ifdef SK_ENABLE_VELLO_SHADERS
430 return std::make_unique<VelloComputePathAtlas>(recorder);
431 #else
432 return nullptr;
433 #endif
434 }
435
436 } // namespace skgpu::graphite