Debian Codegraph @

src/gpu/ganesh/Device.cpp

raw
1 /*
2 * Copyright 2011 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 #include "src/gpu/ganesh/Device.h"
8
9 #include "include/core/SkAlphaType.h"
10 #include "include/core/SkBlendMode.h"
11 #include "include/core/SkCanvas.h"
12 #include "include/core/SkClipOp.h"
13 #include "include/core/SkColor.h"
14 #include "include/core/SkColorSpace.h"
15 #include "include/core/SkColorType.h"
16 #include "include/core/SkDrawable.h"
17 #include "include/core/SkImage.h"
18 #include "include/core/SkImageInfo.h"
19 #include "include/core/SkM44.h"
20 #include "include/core/SkMatrix.h"
21 #include "include/core/SkMesh.h"
22 #include "include/core/SkPaint.h"
23 #include "include/core/SkPath.h"
24 #include "include/core/SkPathTypes.h"
25 #include "include/core/SkPixmap.h"
26 #include "include/core/SkPoint.h"
27 #include "include/core/SkRRect.h"
28 #include "include/core/SkRSXform.h"
29 #include "include/core/SkRect.h"
30 #include "include/core/SkRefCnt.h"
31 #include "include/core/SkRegion.h"
32 #include "include/core/SkScalar.h"
33 #include "include/core/SkSize.h"
34 #include "include/core/SkSpan.h"
35 #include "include/core/SkStrokeRec.h"
36 #include "include/core/SkSurface.h"
37 #include "include/core/SkSurfaceProps.h"
38 #include "include/core/SkVertices.h"
39 #include "include/effects/SkRuntimeEffect.h"
40 #include "include/gpu/GpuTypes.h"
41 #include "include/gpu/ganesh/GrBackendSurface.h"
42 #include "include/gpu/ganesh/GrContextOptions.h"
43 #include "include/gpu/ganesh/GrDirectContext.h"
44 #include "include/gpu/ganesh/GrRecordingContext.h"
45 #include "include/gpu/ganesh/GrTypes.h"
46 #include "include/gpu/ganesh/SkSurfaceGanesh.h"
47 #include "include/private/base/SingleOwner.h"
48 #include "include/private/base/SkAssert.h"
49 #include "include/private/base/SkDebug.h"
50 #include "include/private/base/SkTArray.h"
51 #include "include/private/base/SkTo.h"
52 #include "include/private/chromium/Slug.h" // IWYU pragma: keep
53 #include "include/private/gpu/ganesh/GrTypesPriv.h"
54 #include "src/base/SkTLazy.h"
55 #include "src/core/SkColorData.h"
56 #include "src/core/SkDevice.h"
57 #include "src/core/SkDraw.h"
58 #include "src/core/SkImageFilterTypes.h" // IWYU pragma: keep
59 #include "src/core/SkImageInfoPriv.h"
60 #include "src/core/SkLatticeIter.h"
61 #include "src/core/SkMeshPriv.h"
62 #include "src/core/SkRasterClip.h"
63 #include "src/core/SkSpecialImage.h"
64 #include "src/core/SkStrikeCache.h"
65 #include "src/core/SkTraceEvent.h"
66 #include "src/core/SkVerticesPriv.h"
67 #include "src/gpu/SkBackingFit.h"
68 #include "src/gpu/Swizzle.h"
69 #include "src/gpu/TiledTextureUtils.h"
70 #include "src/gpu/ganesh/ClipStack.h"
71 #include "src/gpu/ganesh/GrAuditTrail.h"
72 #include "src/gpu/ganesh/GrBlurUtils.h"
73 #include "src/gpu/ganesh/GrCaps.h"
74 #include "src/gpu/ganesh/GrColorInfo.h"
75 #include "src/gpu/ganesh/GrColorSpaceXform.h"
76 #include "src/gpu/ganesh/GrFPArgs.h"
77 #include "src/gpu/ganesh/GrFragmentProcessor.h"
78 #include "src/gpu/ganesh/GrFragmentProcessors.h"
79 #include "src/gpu/ganesh/GrImageInfo.h"
80 #include "src/gpu/ganesh/GrPaint.h"
81 #include "src/gpu/ganesh/GrProxyProvider.h"
82 #include "src/gpu/ganesh/GrRecordingContextPriv.h"
83 #include "src/gpu/ganesh/GrRenderTargetProxy.h"
84 #include "src/gpu/ganesh/GrShaderCaps.h"
85 #include "src/gpu/ganesh/GrStyle.h"
86 #include "src/gpu/ganesh/GrSurfaceProxy.h"
87 #include "src/gpu/ganesh/GrSurfaceProxyPriv.h"
88 #include "src/gpu/ganesh/GrSurfaceProxyView.h"
89 #include "src/gpu/ganesh/GrTextureProxy.h"
90 #include "src/gpu/ganesh/GrTracing.h"
91 #include "src/gpu/ganesh/GrUserStencilSettings.h"
92 #include "src/gpu/ganesh/GrXferProcessor.h"
93 #include "src/gpu/ganesh/SkGr.h"
94 #include "src/gpu/ganesh/SurfaceContext.h"
95 #include "src/gpu/ganesh/SurfaceDrawContext.h"
96 #include "src/gpu/ganesh/SurfaceFillContext.h"
97 #include "src/gpu/ganesh/effects/GrDisableColorXP.h"
98 #include "src/gpu/ganesh/effects/GrRRectEffect.h"
99 #include "src/gpu/ganesh/geometry/GrShape.h"
100 #include "src/gpu/ganesh/geometry/GrStyledShape.h"
101 #include "src/gpu/ganesh/image/GrImageUtils.h"
102 #include "src/gpu/ganesh/image/SkSpecialImage_Ganesh.h"
103 #include "src/gpu/ganesh/ops/AtlasTextOp.h"
104 #include "src/text/GlyphRun.h"
105 #include "src/text/gpu/SlugImpl.h"
106 #include "src/text/gpu/SubRunContainer.h"
107
108 #include <atomic>
109 #include <cstddef>
110 #include <cstdint>
111 #include <functional>
112 #include <memory>
113 #include <optional>
114 #include <utility>
115
116 class GrBackendSemaphore;
117 struct SkDrawShadowRec;
118
119 using namespace skia_private;
120
121 #define ASSERT_SINGLE_OWNER SKGPU_ASSERT_SINGLE_OWNER(fContext->priv().singleOwner())
122
123 #if defined(GPU_TEST_UTILS)
124 // GrContextOptions::fMaxTextureSizeOverride exists but doesn't allow for changing the
125 // maxTextureSize on the fly.
126 int gOverrideMaxTextureSizeGanesh = 0;
127 // Allows tests to check how many tiles were drawn on the most recent call to
128 // Device::drawAsTiledImageRect. This is an atomic because we can write to it from
129 // multiple threads during "normal" operations. However, the tests that actually
130 // read from it are done single-threaded.
131 std::atomic<int> gNumTilesDrawnGanesh{0};
132 #endif
133
134 ///////////////////////////////////////////////////////////////////////////////
135
136 namespace {
137
138 bool force_aa_clip(const skgpu::ganesh::SurfaceDrawContext* sdc) {
139 return sdc->numSamples() > 1 || sdc->alwaysAntialias();
140 }
141
142 inline GrPrimitiveType point_mode_to_primitive_type(SkCanvas::PointMode mode) {
143 switch (mode) {
144 case SkCanvas::kPoints_PointMode:
145 return GrPrimitiveType::kPoints;
146 case SkCanvas::kLines_PointMode:
147 return GrPrimitiveType::kLines;
148 case SkCanvas::kPolygon_PointMode:
149 return GrPrimitiveType::kLineStrip;
150 }
151 SK_ABORT("Unexpected mode");
152 }
153
154 std::unique_ptr<GrFragmentProcessor> make_inverse_rrect_fp(const SkMatrix& viewMatrix,
155 const SkRRect& rrect, GrAA aa,
156 const GrShaderCaps& shaderCaps) {
157 if (auto rr = rrect.transform(viewMatrix)) {
158 auto edgeType = (aa == GrAA::kYes) ? GrClipEdgeType::kInverseFillAA
159 : GrClipEdgeType::kInverseFillBW;
160 auto [success, fp] = GrRRectEffect::Make(/*inputFP=*/nullptr, edgeType, *rr, shaderCaps);
161 return (success) ? std::move(fp) : nullptr;
162 }
163 return nullptr;
164 }
165
166 bool init_vertices_paint(skgpu::ganesh::SurfaceDrawContext* sdc,
167 const SkPaint& skPaint,
168 const SkMatrix& ctm,
169 SkBlender* blender,
170 bool hasColors,
171 GrPaint* grPaint) {
172 if (hasColors) {
173 return SkPaintToGrPaintWithBlend(sdc, skPaint, ctm, blender, grPaint);
174 } else {
175 return SkPaintToGrPaint(sdc, skPaint, ctm, grPaint);
176 }
177 }
178
179 bool init_mesh_child_effects(skgpu::ganesh::SurfaceDrawContext* sdc,
180 const SkMesh& mesh,
181 TArray<std::unique_ptr<GrFragmentProcessor>>* meshChildFPs) {
182 // We use `Scope::kRuntimeEffect` here to ensure that mesh shaders get the same "raw" sampling
183 // behavior from alpha-only image shaders as a Runtime Effect would, rather than the unexpected
184 // tinting-by-input-color.
185 GrFPArgs fpArgs(sdc, &sdc->colorInfo(), sdc->surfaceProps(), GrFPArgs::Scope::kRuntimeEffect);
186
187 for (const SkRuntimeEffect::ChildPtr& child : mesh.children()) {
188 auto [success, childFP] = GrFragmentProcessors::MakeChildFP(child, fpArgs);
189 if (!success) {
190 return false;
191 }
192 meshChildFPs->push_back(std::move(childFP));
193 }
194 return true;
195 }
196
197 } // anonymous namespace
198
199 namespace skgpu::ganesh {
200
201 sk_sp<Device> Device::Make(GrRecordingContext* rContext,
202 GrColorType colorType,
203 sk_sp<GrSurfaceProxy> proxy,
204 sk_sp<SkColorSpace> colorSpace,
205 GrSurfaceOrigin origin,
206 const SkSurfaceProps& surfaceProps,
207 InitContents init) {
208 auto sdc = SurfaceDrawContext::Make(rContext,
209 colorType,
210 std::move(proxy),
211 std::move(colorSpace),
212 origin,
213 surfaceProps);
214
215 return Device::Make(std::move(sdc), kPremul_SkAlphaType, init);
216 }
217
218 SkImageInfo Device::MakeInfo(SurfaceContext* sc, DeviceFlags flags) {
219 SkColorType colorType = GrColorTypeToSkColorType(sc->colorInfo().colorType());
220 return SkImageInfo::Make(sc->width(), sc->height(), colorType,
221 flags & DeviceFlags::kIsOpaque ? kOpaque_SkAlphaType
222 : kPremul_SkAlphaType,
223 sc->colorInfo().refColorSpace());
224 }
225
226
227 /** Checks that the alpha type is legal and gets constructor flags. Returns false if device creation
228 should fail. */
229 bool Device::CheckAlphaTypeAndGetFlags(SkAlphaType alphaType,
230 InitContents init,
231 DeviceFlags* flags) {
232 *flags = DeviceFlags::kNone;
233 switch (alphaType) {
234 case kPremul_SkAlphaType:
235 break;
236 case kOpaque_SkAlphaType:
237 *flags |= DeviceFlags::kIsOpaque;
238 break;
239 default: // If it is unpremul or unknown don't try to render
240 return false;
241 }
242 if (InitContents::kClear == init) {
243 *flags |= DeviceFlags::kNeedClear;
244 }
245 return true;
246 }
247
248 sk_sp<Device> Device::Make(std::unique_ptr<SurfaceDrawContext> sdc,
249 SkAlphaType alphaType,
250 InitContents init) {
251 if (!sdc) {
252 return nullptr;
253 }
254
255 GrRecordingContext* rContext = sdc->recordingContext();
256 if (rContext->abandoned()) {
257 return nullptr;
258 }
259
260 SkColorType ct = GrColorTypeToSkColorType(sdc->colorInfo().colorType());
261
262 DeviceFlags flags;
263 if (!rContext->colorTypeSupportedAsSurface(ct) ||
264 !CheckAlphaTypeAndGetFlags(alphaType, init, &flags)) {
265 return nullptr;
266 }
267 return sk_sp<Device>(new Device(std::move(sdc), flags));
268 }
269
270 sk_sp<Device> Device::Make(GrRecordingContext* rContext,
271 skgpu::Budgeted budgeted,
272 const SkImageInfo& ii,
273 SkBackingFit fit,
274 int sampleCount,
275 skgpu::Mipmapped mipmapped,
276 GrProtected isProtected,
277 GrSurfaceOrigin origin,
278 const SkSurfaceProps& props,
279 InitContents init) {
280 if (!rContext) {
281 return nullptr;
282 }
283
284 auto sdc = SurfaceDrawContext::Make(rContext,
285 SkColorTypeToGrColorType(ii.colorType()),
286 ii.refColorSpace(),
287 fit,
288 ii.dimensions(),
289 props,
290 /*label=*/"MakeDevice",
291 sampleCount,
292 mipmapped,
293 isProtected,
294 origin,
295 budgeted);
296
297 return Device::Make(std::move(sdc), ii.alphaType(), init);
298 }
299
300 Device::Device(std::unique_ptr<SurfaceDrawContext> sdc, DeviceFlags flags)
301 : SkDevice(MakeInfo(sdc.get(), flags), sdc->surfaceProps())
302 , fContext(sk_ref_sp(sdc->recordingContext()))
303 , fSubRunControl(sdc->recordingContext()->priv().getSubRunControl(
304 sdc->surfaceProps().isUseDeviceIndependentFonts()))
305 , fSurfaceDrawContext(std::move(sdc))
306 , fClip(SkIRect::MakeSize(fSurfaceDrawContext->dimensions()),
307 &this->localToDevice(),
308 force_aa_clip(fSurfaceDrawContext.get())) {
309 if (flags & DeviceFlags::kNeedClear) {
310 this->clearAll();
311 }
312 }
313
314 Device::~Device() = default;
315
316 ///////////////////////////////////////////////////////////////////////////////
317
318 bool Device::onReadPixels(const SkPixmap& pm, int x, int y) {
319 ASSERT_SINGLE_OWNER
320
321 // Context TODO: Elevate direct context requirement to public API
322 auto dContext = fContext->asDirectContext();
323 if (!dContext || !SkImageInfoValidConversion(pm.info(), this->imageInfo())) {
324 return false;
325 }
326
327 return fSurfaceDrawContext->readPixels(dContext, pm, {x, y});
328 }
329
330 bool Device::onWritePixels(const SkPixmap& pm, int x, int y) {
331 ASSERT_SINGLE_OWNER
332
333 // Context TODO: Elevate direct context requirement to public API
334 auto dContext = fContext->asDirectContext();
335 if (!dContext || !SkImageInfoValidConversion(this->imageInfo(), pm.info())) {
336 return false;
337 }
338
339 return fSurfaceDrawContext->writePixels(dContext, pm, {x, y});
340 }
341
342 bool Device::onAccessPixels(SkPixmap* pmap) {
343 ASSERT_SINGLE_OWNER
344 return false;
345 }
346
347 SurfaceDrawContext* Device::surfaceDrawContext() {
348 ASSERT_SINGLE_OWNER
349 return fSurfaceDrawContext.get();
350 }
351
352 const SurfaceDrawContext* Device::surfaceDrawContext() const {
353 ASSERT_SINGLE_OWNER
354 return fSurfaceDrawContext.get();
355 }
356
357 SurfaceFillContext* Device::surfaceFillContext() {
358 ASSERT_SINGLE_OWNER
359 return fSurfaceDrawContext.get();
360 }
361
362 void Device::clearAll() {
363 ASSERT_SINGLE_OWNER
364 GR_CREATE_TRACE_MARKER_CONTEXT("skgpu::ganesh::Device", "clearAll", fContext.get());
365
366 SkIRect rect = SkIRect::MakeWH(this->width(), this->height());
367 fSurfaceDrawContext->clearAtLeast(rect, SK_PMColor4fTRANSPARENT);
368 }
369
370 ///////////////////////////////////////////////////////////////////////////////
371
372 void Device::clipPath(const SkPath& path, SkClipOp op, bool aa) {
373 #if defined(GPU_TEST_UTILS)
374 if (fContext->priv().options().fAllPathsVolatile && !path.isVolatile()) {
375 this->clipPath(SkPath(path).setIsVolatile(true), op, aa);
376 return;
377 }
378 #endif
379 SkASSERT(op == SkClipOp::kIntersect || op == SkClipOp::kDifference);
380 fClip.clipPath(this->localToDevice(), path, GrAA(aa), op);
381 }
382
383 void Device::clipRegion(const SkRegion& globalRgn, SkClipOp op) {
384 SkASSERT(op == SkClipOp::kIntersect || op == SkClipOp::kDifference);
385
386 // Regions don't actually need AA, but in DMSAA mode every clip element is antialiased.
387 GrAA aa = GrAA(fSurfaceDrawContext->alwaysAntialias());
388
389 if (globalRgn.isEmpty()) {
390 fClip.clipRect(SkMatrix::I(), SkRect::MakeEmpty(), aa, op);
391 } else if (globalRgn.isRect()) {
392 fClip.clipRect(this->globalToDevice().asM33(), SkRect::Make(globalRgn.getBounds()), aa, op);
393 } else {
394 SkPath path = globalRgn.getBoundaryPath();
395 fClip.clipPath(this->globalToDevice().asM33(), path, aa, op);
396 }
397 }
398
399 void Device::android_utils_clipAsRgn(SkRegion* region) const {
400 SkIRect bounds = fClip.getConservativeBounds();
401 // Assume wide open and then perform intersect/difference operations reducing the region
402 region->setRect(bounds);
403 const SkRegion deviceBounds(bounds);
404 for (const ClipStack::Element& e : fClip) {
405 SkRegion tmp;
406 if (e.fShape.isRect() && e.fLocalToDevice.isIdentity()) {
407 tmp.setRect(e.fShape.rect().roundOut());
408 } else {
409 SkPath tmpPath = e.fShape.asPath().makeTransform(e.fLocalToDevice);
410 tmp.setPath(tmpPath, deviceBounds);
411 }
412
413 region->op(tmp, (SkRegion::Op) e.fOp);
414 }
415 }
416
417 bool Device::isClipAntiAliased() const {
418 for (const ClipStack::Element& e : fClip) {
419 if (e.fAA == GrAA::kYes) {
420 return true;
421 }
422 SkASSERT(!fSurfaceDrawContext->alwaysAntialias());
423 }
424 return false;
425 }
426
427 ///////////////////////////////////////////////////////////////////////////////
428
429 void Device::drawPaint(const SkPaint& paint) {
430 ASSERT_SINGLE_OWNER
431 GR_CREATE_TRACE_MARKER_CONTEXT("skgpu::ganesh::Device", "drawPaint", fContext.get());
432
433 GrPaint grPaint;
434 if (!SkPaintToGrPaint(fSurfaceDrawContext.get(),
435 paint,
436 this->localToDevice(),
437 &grPaint)) {
438 return;
439 }
440
441 fSurfaceDrawContext->drawPaint(this->clip(), std::move(grPaint), this->localToDevice());
442 }
443
444 void Device::drawPoints(SkCanvas::PointMode mode, SkSpan<const SkPoint> pts, const SkPaint& paint) {
445 ASSERT_SINGLE_OWNER
446 GR_CREATE_TRACE_MARKER_CONTEXT("skgpu::ganesh::Device", "drawPoints", fContext.get());
447 SkScalar width = paint.getStrokeWidth();
448 if (width < 0) {
449 return;
450 }
451
452 const size_t count = pts.size();
453
454 // If there is an image filter or mask filter these bounds were already checked in
455 // the canvas.
456 if (!paint.getImageFilter() && !paint.getMaskFilter()) {
457 auto bounds = SkRect::Bounds(pts);
458 if (!bounds || paint.nothingToDraw()) {
459 return;
460 }
461
462 SkRect devBounds = SkMatrixPriv::MapRect(this->localToDevice44(), bounds.value());
463 if (!devBounds.isFinite()) {
464 return;
465 }
466 }
467
468 GrAA aa = fSurfaceDrawContext->chooseAA(paint);
469
470 if (count == 2 && mode == SkCanvas::kLines_PointMode) {
471 if (paint.getPathEffect()) {
472 // Probably a dashed line. Draw as a path.
473 GrPaint grPaint;
474 if (SkPaintToGrPaint(fSurfaceDrawContext.get(),
475 paint,
476 this->localToDevice(),
477 &grPaint)) {
478 SkPath path = SkPath::Line(pts[0], pts[1]);
479 path.setIsVolatile(true);
480 fSurfaceDrawContext->drawPath(this->clip(),
481 std::move(grPaint),
482 aa,
483 this->localToDevice(),
484 path,
485 GrStyle(paint, SkPaint::kStroke_Style));
486 }
487 return;
488 }
489 if (!paint.getMaskFilter() &&
490 paint.getStrokeWidth() > 0 && // drawStrokedLine doesn't support hairlines.
491 paint.getStrokeCap() != SkPaint::kRound_Cap) { // drawStrokedLine doesn't do round caps.
492 // Simple stroked line. Bypass path rendering.
493 GrPaint grPaint;
494 if (SkPaintToGrPaint(fSurfaceDrawContext.get(),
495 paint,
496 this->localToDevice(),
497 &grPaint)) {
498 fSurfaceDrawContext->drawStrokedLine(this->clip(),
499 std::move(grPaint),
500 aa,
501 this->localToDevice(),
502 pts.data(),
503 SkStrokeRec(paint, SkPaint::kStroke_Style));
504 }
505 return;
506 }
507 }
508
509 const GrCaps* caps = fContext->priv().caps();
510 SkScalar scales[2];
511 bool isHairline =
512 ((0 == width) ||
513 (1 == width && this->localToDevice().getMinMaxScales(scales) &&
514 SkScalarNearlyEqual(scales[0], 1.f) && SkScalarNearlyEqual(scales[1], 1.f))) &&
515
516 // Don't do this as a hairline draw, which will emit line primitives, if
517 // lines are not permitted by caps.
518 !((mode == SkCanvas::kLines_PointMode || mode == SkCanvas::kPolygon_PointMode) &&
519 caps->avoidLineDraws());
520
521 // we only handle non-coverage-aa hairlines and paints without path effects or mask filters,
522 // else we let the SkDraw call our drawPath()
523 if (!isHairline ||
524 paint.getPathEffect() ||
525 paint.getMaskFilter() ||
526 fSurfaceDrawContext->chooseAAType(aa) == GrAAType::kCoverage) {
527 SkRasterClip rc(this->devClipBounds());
528 skcpu::Draw draw;
529 // don't need to set fBlitterChoose, as it should never get used
530 draw.fDst = SkPixmap(SkImageInfo::MakeUnknown(this->width(), this->height()), nullptr, 0);
531 draw.fCTM = &this->localToDevice();
532 draw.fRC = &rc;
533 draw.drawDevicePoints(mode, pts, paint, this);
534 return;
535 }
536
537 GrPaint grPaint;
538 if (!SkPaintToGrPaint(fSurfaceDrawContext.get(), paint, this->localToDevice(), &grPaint)) {
539 return;
540 }
541
542 static constexpr SkVertices::VertexMode kIgnoredMode = SkVertices::kTriangles_VertexMode;
543 sk_sp<SkVertices> vertices = SkVertices::MakeCopy(kIgnoredMode, SkToS32(count), pts.data(),
544 nullptr, nullptr);
545
546 GrPrimitiveType primitiveType = point_mode_to_primitive_type(mode);
547 fSurfaceDrawContext->drawVertices(this->clip(), std::move(grPaint), this->localToDevice(),
548 std::move(vertices), &primitiveType);
549 }
550
551 ///////////////////////////////////////////////////////////////////////////////
552
553 void Device::drawRect(const SkRect& rect, const SkPaint& paint) {
554 ASSERT_SINGLE_OWNER
555 GR_CREATE_TRACE_MARKER_CONTEXT("skgpu::ganesh::Device", "drawRect", fContext.get());
556
557 GrStyle style(paint);
558
559 // A couple reasons we might need to call drawPath.
560 if (paint.getMaskFilter() || paint.getPathEffect()) {
561 GrStyledShape shape(rect, style);
562
563 GrBlurUtils::DrawShapeWithMaskFilter(fContext.get(), fSurfaceDrawContext.get(),
564 this->clip(), paint, this->localToDevice(), shape);
565 return;
566 }
567
568 GrPaint grPaint;
569 if (!SkPaintToGrPaint(fSurfaceDrawContext.get(), paint, this->localToDevice(), &grPaint)) {
570 return;
571 }
572
573 fSurfaceDrawContext->drawRect(this->clip(), std::move(grPaint),
574 fSurfaceDrawContext->chooseAA(paint), this->localToDevice(), rect,
575 &style);
576 }
577
578 void Device::drawEdgeAAQuad(const SkRect& rect,
579 const SkPoint clip[4],
580 SkCanvas::QuadAAFlags aaFlags,
581 const SkColor4f& color,
582 SkBlendMode mode) {
583 ASSERT_SINGLE_OWNER
584 GR_CREATE_TRACE_MARKER_CONTEXT("skgpu::ganesh::Device", "drawEdgeAAQuad", fContext.get());
585
586 SkPMColor4f dstColor = SkColor4fPrepForDst(color, fSurfaceDrawContext->colorInfo()).premul();
587
588 GrPaint grPaint;
589 grPaint.setColor4f(dstColor);
590 if (mode != SkBlendMode::kSrcOver) {
591 grPaint.setXPFactory(GrXPFactory::FromBlendMode(mode));
592 }
593
594 if (clip) {
595 // Use fillQuadWithEdgeAA
596 fSurfaceDrawContext->fillQuadWithEdgeAA(this->clip(),
597 std::move(grPaint),
598 SkToGrQuadAAFlags(aaFlags),
599 this->localToDevice(),
600 clip,
601 nullptr);
602 } else {
603 // Use fillRectWithEdgeAA to preserve mathematical properties of dst being rectangular
604 fSurfaceDrawContext->fillRectWithEdgeAA(this->clip(),
605 std::move(grPaint),
606 SkToGrQuadAAFlags(aaFlags),
607 this->localToDevice(),
608 rect);
609 }
610 }
611
612 ///////////////////////////////////////////////////////////////////////////////
613
614 void Device::drawRRect(const SkRRect& rrect, const SkPaint& paint) {
615 ASSERT_SINGLE_OWNER
616 GR_CREATE_TRACE_MARKER_CONTEXT("skgpu::ganesh::Device", "drawRRect", fContext.get());
617
618 auto mf = paint.getMaskFilter();
619 if (mf) {
620 if (GrFragmentProcessors::IsSupported(mf)) {
621 mf = nullptr; // already handled in SkPaintToGrPaint
622 }
623 }
624
625 GrStyle style(paint);
626
627 if (mf || style.pathEffect()) {
628 // A path effect will presumably transform this rrect into something else.
629 GrStyledShape shape(rrect, style);
630
631 GrBlurUtils::DrawShapeWithMaskFilter(fContext.get(), fSurfaceDrawContext.get(),
632 this->clip(), paint, this->localToDevice(), shape);
633 return;
634 }
635
636 SkASSERT(!style.pathEffect());
637
638 GrPaint grPaint;
639 if (!SkPaintToGrPaint(fSurfaceDrawContext.get(),
640 paint,
641 this->localToDevice(),
642 &grPaint)) {
643 return;
644 }
645
646 fSurfaceDrawContext->drawRRect(this->clip(), std::move(grPaint),
647 fSurfaceDrawContext->chooseAA(paint), this->localToDevice(),
648 rrect, style);
649 }
650
651 void Device::drawDRRect(const SkRRect& outer, const SkRRect& inner, const SkPaint& paint) {
652 ASSERT_SINGLE_OWNER
653 GR_CREATE_TRACE_MARKER_CONTEXT("skgpu::ganesh::Device", "drawDRRect", fContext.get());
654 if (outer.isEmpty()) {
655 return;
656 }
657
658 if (inner.isEmpty()) {
659 return this->drawRRect(outer, paint);
660 }
661
662 SkStrokeRec stroke(paint);
663
664 if (stroke.isFillStyle() && !paint.getMaskFilter() && !paint.getPathEffect()) {
665 // For axis-aligned filled DRRects, just draw a regular rrect with inner clipped out using a
666 // coverage FP instead of using path rendering.
667 if (auto fp = make_inverse_rrect_fp(this->localToDevice(), inner,
668 fSurfaceDrawContext->chooseAA(paint),
669 *fSurfaceDrawContext->caps()->shaderCaps())) {
670 GrPaint grPaint;
671 if (!SkPaintToGrPaint(fSurfaceDrawContext.get(),
672 paint,
673 this->localToDevice(),
674 &grPaint)) {
675 return;
676 }
677 SkASSERT(!grPaint.hasCoverageFragmentProcessor());
678 grPaint.setCoverageFragmentProcessor(std::move(fp));
679 fSurfaceDrawContext->drawRRect(this->clip(), std::move(grPaint),
680 fSurfaceDrawContext->chooseAA(paint),
681 this->localToDevice(), outer, GrStyle());
682 return;
683 }
684 }
685
686 auto path = SkPathBuilder(SkPathFillType::kEvenOdd)
687 .addRRect(outer)
688 .addRRect(inner)
689 .detach();
690 path.setIsVolatile(true);
691
692 // TODO: We are losing the possible mutability of the path here but this should probably be
693 // fixed by upgrading GrStyledShape to handle DRRects.
694 GrStyledShape shape(path, paint);
695
696 GrBlurUtils::DrawShapeWithMaskFilter(fContext.get(), fSurfaceDrawContext.get(), this->clip(),
697 paint, this->localToDevice(), shape);
698 }
699
700 /////////////////////////////////////////////////////////////////////////////
701
702 void Device::drawRegion(const SkRegion& region, const SkPaint& paint) {
703 ASSERT_SINGLE_OWNER
704
705 if (paint.getMaskFilter()) {
706 SkPath path = region.getBoundaryPath();
707 path.setIsVolatile(true);
708 return this->drawPath(path, paint);
709 }
710
711 GrPaint grPaint;
712 if (!SkPaintToGrPaint(fSurfaceDrawContext.get(),
713 paint,
714 this->localToDevice(),
715 &grPaint)) {
716 return;
717 }
718
719 fSurfaceDrawContext->drawRegion(this->clip(), std::move(grPaint),
720 fSurfaceDrawContext->chooseAA(paint), this->localToDevice(),
721 region, GrStyle(paint));
722 }
723
724 void Device::drawOval(const SkRect& oval, const SkPaint& paint) {
725 ASSERT_SINGLE_OWNER
726 GR_CREATE_TRACE_MARKER_CONTEXT("skgpu::ganesh::Device", "drawOval", fContext.get());
727
728 if (paint.getMaskFilter()) {
729 // The RRect path can handle special case blurring
730 SkRRect rr = SkRRect::MakeOval(oval);
731 return this->drawRRect(rr, paint);
732 }
733
734 GrPaint grPaint;
735 if (!SkPaintToGrPaint(fSurfaceDrawContext.get(), paint, this->localToDevice(), &grPaint)) {
736 return;
737 }
738
739 fSurfaceDrawContext->drawOval(this->clip(), std::move(grPaint),
740 fSurfaceDrawContext->chooseAA(paint), this->localToDevice(), oval,
741 GrStyle(paint));
742 }
743
744 void Device::drawArc(const SkArc& arc, const SkPaint& paint) {
745 ASSERT_SINGLE_OWNER
746 GR_CREATE_TRACE_MARKER_CONTEXT("skgpu::ganesh::Device", "drawArc", fContext.get());
747 if (paint.getMaskFilter()) {
748 this->SkDevice::drawArc(arc, paint);
749 return;
750 }
751 GrPaint grPaint;
752 if (!SkPaintToGrPaint(fSurfaceDrawContext.get(), paint, this->localToDevice(), &grPaint)) {
753 return;
754 }
755
756 fSurfaceDrawContext->drawArc(this->clip(),
757 std::move(grPaint),
758 fSurfaceDrawContext->chooseAA(paint),
759 this->localToDevice(),
760 arc,
761 GrStyle(paint));
762 }
763
764 ///////////////////////////////////////////////////////////////////////////////
765
766 void Device::drawPath(const SkPath& origSrcPath, const SkPaint& paint) {
767 #if defined(GPU_TEST_UTILS)
768 if (fContext->priv().options().fAllPathsVolatile && !origSrcPath.isVolatile()) {
769 this->drawPath(SkPath(origSrcPath).setIsVolatile(true), paint);
770 return;
771 }
772 #endif
773 ASSERT_SINGLE_OWNER
774 GR_CREATE_TRACE_MARKER_CONTEXT("skgpu::ganesh::Device", "drawPath", fContext.get());
775 if (!paint.getMaskFilter()) {
776 GrPaint grPaint;
777 if (!SkPaintToGrPaint(fSurfaceDrawContext.get(),
778 paint,
779 this->localToDevice(),
780 &grPaint)) {
781 return;
782 }
783 fSurfaceDrawContext->drawPath(this->clip(), std::move(grPaint),
784 fSurfaceDrawContext->chooseAA(paint), this->localToDevice(),
785 origSrcPath, GrStyle(paint));
786 return;
787 }
788
789 GrStyledShape shape(origSrcPath, paint);
790
791 GrBlurUtils::DrawShapeWithMaskFilter(fContext.get(), fSurfaceDrawContext.get(), this->clip(),
792 paint, this->localToDevice(), shape);
793 }
794
795 sk_sp<skif::Backend> Device::createImageFilteringBackend(const SkSurfaceProps& surfaceProps,
796 SkColorType colorType) const {
797 return skif::MakeGaneshBackend(
798 fContext, fSurfaceDrawContext->origin(), surfaceProps, colorType);
799 }
800
801 sk_sp<SkSpecialImage> Device::snapSpecial(const SkIRect& subset, bool forceCopy) {
802 ASSERT_SINGLE_OWNER
803
804 auto sdc = fSurfaceDrawContext.get();
805
806 // If we are wrapping a vulkan secondary command buffer, then we can't snap off a special image
807 // since it would require us to make a copy of the underlying VkImage which we don't have access
808 // to. Additionaly we can't stop and start the render pass that is used with the secondary
809 // command buffer.
810 if (sdc->wrapsVkSecondaryCB()) {
811 return nullptr;
812 }
813
814 SkASSERT(sdc->asSurfaceProxy());
815
816 SkIRect finalSubset = subset;
817 GrSurfaceProxyView view = sdc->readSurfaceView();
818 if (forceCopy || !view.asTextureProxy()) {
819 // When the device doesn't have a texture, or a copy is requested, we create a temporary
820 // texture that matches the device contents
821 view = GrSurfaceProxyView::Copy(fContext.get(),
822 std::move(view),
823 skgpu::Mipmapped::kNo, // Don't auto generate mips
824 subset,
825 SkBackingFit::kApprox,
826 skgpu::Budgeted::kYes,
827 /*label=*/"Device_SnapSpecial"); // Always budgeted
828 if (!view) {
829 return nullptr;
830 }
831 // Since this copied only the requested subset, the special image wrapping the proxy no
832 // longer needs the original subset.
833 finalSubset = SkIRect::MakeSize(view.dimensions());
834 }
835
836 return SkSpecialImages::MakeDeferredFromGpu(fContext.get(),
837 finalSubset,
838 kNeedNewImageUniqueID_SpecialImage,
839 std::move(view),
840 GrColorInfo(this->imageInfo().colorInfo()),
841 this->surfaceProps());
842 }
843
844 sk_sp<SkSpecialImage> Device::snapSpecialScaled(const SkIRect& subset, const SkISize& dstDims) {
845 ASSERT_SINGLE_OWNER
846
847 auto sdc = fSurfaceDrawContext.get();
848
849 // If we are wrapping a vulkan secondary command buffer, then we can't snap off a special image
850 // since it would require us to make a copy of the underlying VkImage which we don't have access
851 // to. Additionaly we can't stop and start the render pass that is used with the secondary
852 // command buffer.
853 if (sdc->wrapsVkSecondaryCB()) {
854 return nullptr;
855 }
856
857 SkASSERT(sdc->asSurfaceProxy());
858
859 auto scaledContext = sdc->rescale(sdc->imageInfo().makeDimensions(dstDims),
860 sdc->origin(),
861 subset,
862 RescaleGamma::kSrc,
863 RescaleMode::kLinear);
864 if (!scaledContext) {
865 return nullptr;
866 }
867
868 return SkSpecialImages::MakeDeferredFromGpu(fContext.get(),
869 SkIRect::MakeSize(dstDims),
870 kNeedNewImageUniqueID_SpecialImage,
871 scaledContext->readSurfaceView(),
872 GrColorInfo(this->imageInfo().colorInfo()),
873 this->surfaceProps());
874 }
875
876 void Device::drawDevice(SkDevice* device,
877 const SkSamplingOptions& sampling,
878 const SkPaint& paint) {
879 ASSERT_SINGLE_OWNER
880 // clear of the source device must occur before CHECK_SHOULD_DRAW
881 GR_CREATE_TRACE_MARKER_CONTEXT("skgpu::ganesh::Device", "drawDevice", fContext.get());
882 this->SkDevice::drawDevice(device, sampling, paint);
883 }
884
885 void Device::drawImageRect(const SkImage* image,
886 const SkRect* src,
887 const SkRect& dst,
888 const SkSamplingOptions& sampling,
889 const SkPaint& paint,
890 SkCanvas::SrcRectConstraint constraint) {
891 ASSERT_SINGLE_OWNER
892
893 GrAA aa = fSurfaceDrawContext->chooseAA(paint);
894 SkCanvas::QuadAAFlags aaFlags = (aa == GrAA::kYes) ? SkCanvas::kAll_QuadAAFlags
895 : SkCanvas::kNone_QuadAAFlags;
896
897 this->drawImageQuadDirect(image,
898 src ? *src
899 : SkRect::MakeIWH(image->width(), image->height()),
900 dst,
901 /* dstClip= */ nullptr,
902 aaFlags,
903 /* preViewMatrix= */ nullptr,
904 sampling,
905 paint,
906 constraint);
907 }
908
909 bool Device::drawAsTiledImageRect(SkCanvas* canvas,
910 const SkImage* image,
911 const SkRect* src,
912 const SkRect& dst,
913 const SkSamplingOptions& sampling,
914 const SkPaint& paint,
915 SkCanvas::SrcRectConstraint constraint) {
916 GrRecordingContext* rCtx = canvas->recordingContext();
917 if (!rCtx) {
918 return false;
919 }
920 ASSERT_SINGLE_OWNER
921
922 GrAA aa = fSurfaceDrawContext->chooseAA(paint);
923 SkCanvas::QuadAAFlags aaFlags = (aa == GrAA::kYes) ? SkCanvas::kAll_QuadAAFlags
924 : SkCanvas::kNone_QuadAAFlags;
925
926 // NOTE: if the context is not a direct context, it doesn't have access to the resource
927 // cache, and theoretically, the resource cache's limits could be being changed on
928 // another thread, so even having access to just the limit wouldn't be a reliable
929 // test during recording here.
930 size_t cacheSize = 0;
931 if (auto dCtx = GrAsDirectContext(rCtx)) {
932 cacheSize = dCtx->getResourceCacheLimit();
933 }
934 size_t maxTextureSize = rCtx->maxTextureSize();
935 #if defined(GPU_TEST_UTILS)
936 if (gOverrideMaxTextureSizeGanesh) {
937 maxTextureSize = gOverrideMaxTextureSizeGanesh;
938 }
939 gNumTilesDrawnGanesh.store(0, std::memory_order_relaxed);
940 #endif
941
942 [[maybe_unused]] auto [wasTiled, numTiles] = TiledTextureUtils::DrawAsTiledImageRect(
943 canvas,
944 image,
945 src ? *src : SkRect::MakeIWH(image->width(), image->height()),
946 dst,
947 aaFlags,
948 sampling,
949 &paint,
950 constraint,
951 rCtx->priv().options().fSharpenMipmappedTextures,
952 cacheSize,
953 maxTextureSize,
954 !rCtx->priv().caps()->shaderCaps()->fHasLowFragmentPrecision);
955 #if defined(GPU_TEST_UTILS)
956 gNumTilesDrawnGanesh.store(numTiles, std::memory_order_relaxed);
957 #endif
958 return wasTiled;
959 }
960
961 void Device::drawViewLattice(GrSurfaceProxyView view,
962 const GrColorInfo& info,
963 std::unique_ptr<SkLatticeIter> iter,
964 const SkRect& dst,
965 SkFilterMode filter,
966 const SkPaint& origPaint) {
967 GR_CREATE_TRACE_MARKER_CONTEXT("skgpu::ganesh::Device", "drawViewLattice", fContext.get());
968 SkASSERT(view);
969
970 SkTCopyOnFirstWrite<SkPaint> paint(&origPaint);
971
972 if (!info.isAlphaOnly() && (paint->getColor() & 0x00FFFFFF) != 0x00FFFFFF) {
973 paint.writable()->setColor(SkColorSetARGB(origPaint.getAlpha(), 0xFF, 0xFF, 0xFF));
974 }
975 GrPaint grPaint;
976 // Passing null as shaderFP indicates that the GP will provide the shader.
977 if (!SkPaintToGrPaintReplaceShader(fSurfaceDrawContext.get(),
978 *paint,
979 this->localToDevice(),
980 /*shaderFP=*/nullptr,
981 &grPaint)) {
982 return;
983 }
984
985 if (info.isAlphaOnly()) {
986 // If we were doing this with an FP graph we'd use a kDstIn blend between the texture
987 // and the paint color.
988 view.concatSwizzle(skgpu::Swizzle("aaaa"));
989 }
990 auto csxf = GrColorSpaceXform::Make(info, fSurfaceDrawContext->colorInfo());
991
992 fSurfaceDrawContext->drawImageLattice(this->clip(),
993 std::move(grPaint),
994 this->localToDevice(),
995 std::move(view),
996 info.alphaType(),
997 std::move(csxf),
998 filter,
999 std::move(iter),
1000 dst);
1001 }
1002
1003 void Device::drawImageLattice(const SkImage* image,
1004 const SkCanvas::Lattice& lattice,
1005 const SkRect& dst,
1006 SkFilterMode filter,
1007 const SkPaint& paint) {
1008 ASSERT_SINGLE_OWNER
1009 auto iter = std::make_unique<SkLatticeIter>(lattice, dst);
1010
1011 auto [view, ct] = skgpu::ganesh::AsView(this->recordingContext(),
1012 image,
1013 skgpu::Mipmapped::kNo,
1014 this->targetProxy());
1015 if (view) {
1016 GrColorInfo colorInfo(ct, image->alphaType(), image->refColorSpace());
1017 this->drawViewLattice(
1018 std::move(view), std::move(colorInfo), std::move(iter), dst, filter, paint);
1019 }
1020 }
1021
1022 void Device::drawVertices(const SkVertices* vertices,
1023 sk_sp<SkBlender> blender,
1024 const SkPaint& paint,
1025 bool skipColorXform) {
1026 ASSERT_SINGLE_OWNER
1027 GR_CREATE_TRACE_MARKER_CONTEXT("skgpu::ganesh::Device", "drawVertices", fContext.get());
1028 SkASSERT(vertices);
1029
1030 #ifdef SK_LEGACY_IGNORE_DRAW_VERTICES_BLEND_WITH_NO_SHADER
1031 if (!paint.getShader()) {
1032 blender = SkBlender::Mode(SkBlendMode::kDst);
1033 }
1034 #endif
1035
1036 SkVerticesPriv info(vertices->priv());
1037
1038 GrPaint grPaint;
1039 if (!init_vertices_paint(fSurfaceDrawContext.get(),
1040 paint,
1041 this->localToDevice(),
1042 blender.get(),
1043 info.hasColors(),
1044 &grPaint)) {
1045 return;
1046 }
1047 fSurfaceDrawContext->drawVertices(this->clip(),
1048 std::move(grPaint),
1049 this->localToDevice(),
1050 sk_ref_sp(const_cast<SkVertices*>(vertices)),
1051 nullptr,
1052 skipColorXform);
1053 }
1054
1055 void Device::drawMesh(const SkMesh& mesh, sk_sp<SkBlender> blender, const SkPaint& paint) {
1056 ASSERT_SINGLE_OWNER
1057 GR_CREATE_TRACE_MARKER_CONTEXT("skgpu::ganesh::Device", "drawMesh", fContext.get());
1058 if (!mesh.isValid()) {
1059 return;
1060 }
1061
1062 GrPaint grPaint;
1063 if (!init_vertices_paint(fSurfaceDrawContext.get(),
1064 paint,
1065 this->localToDevice(),
1066 blender.get(),
1067 SkMeshSpecificationPriv::HasColors(*mesh.spec()),
1068 &grPaint)) {
1069 return;
1070 }
1071
1072 TArray<std::unique_ptr<GrFragmentProcessor>> meshChildFPs;
1073 if (!init_mesh_child_effects(fSurfaceDrawContext.get(), mesh, &meshChildFPs)) {
1074 return;
1075 }
1076 fSurfaceDrawContext->drawMesh(this->clip(), std::move(grPaint), this->localToDevice(), mesh,
1077 std::move(meshChildFPs));
1078 }
1079
1080 ///////////////////////////////////////////////////////////////////////////////
1081
1082 #if !defined(SK_ENABLE_OPTIMIZE_SIZE)
1083 void Device::drawShadow(SkCanvas* canvas, const SkPath& path, const SkDrawShadowRec& rec) {
1084 #if defined(GPU_TEST_UTILS)
1085 if (fContext->priv().options().fAllPathsVolatile && !path.isVolatile()) {
1086 this->drawShadow(canvas, SkPath(path).setIsVolatile(true), rec);
1087 return;
1088 }
1089 #endif
1090 ASSERT_SINGLE_OWNER
1091 GR_CREATE_TRACE_MARKER_CONTEXT("skgpu::ganesh::Device", "drawShadow", fContext.get());
1092
1093 if (!fSurfaceDrawContext->drawFastShadow(this->clip(), this->localToDevice(), path, rec)) {
1094 // failed to find an accelerated case
1095 this->SkDevice::drawShadow(canvas, path, rec);
1096 }
1097 }
1098 #endif // SK_ENABLE_OPTIMIZE_SIZE
1099
1100 ///////////////////////////////////////////////////////////////////////////////
1101
1102 void Device::drawAtlas(SkSpan<const SkRSXform> xform,
1103 SkSpan<const SkRect> texRect,
1104 SkSpan<const SkColor> colors,
1105 sk_sp<SkBlender> blender,
1106 const SkPaint& paint) {
1107 ASSERT_SINGLE_OWNER
1108 GR_CREATE_TRACE_MARKER_CONTEXT("skgpu::ganesh::Device", "drawAtlas", fContext.get());
1109
1110 GrPaint grPaint;
1111 if (!colors.empty()) {
1112 if (!SkPaintToGrPaintWithBlend(fSurfaceDrawContext.get(),
1113 paint,
1114 this->localToDevice(),
1115 blender.get(),
1116 &grPaint)) {
1117 return;
1118 }
1119 } else {
1120 if (!SkPaintToGrPaint(fSurfaceDrawContext.get(),
1121 paint,
1122 this->localToDevice(),
1123 &grPaint)) {
1124 return;
1125 }
1126 }
1127
1128 fSurfaceDrawContext->drawAtlas(this->clip(), std::move(grPaint), this->localToDevice(),
1129 xform, texRect, colors);
1130 }
1131
1132 ///////////////////////////////////////////////////////////////////////////////
1133
1134 void Device::onDrawGlyphRunList(SkCanvas* canvas,
1135 const sktext::GlyphRunList& glyphRunList,
1136 const SkPaint& paint) {
1137 ASSERT_SINGLE_OWNER
1138 GR_CREATE_TRACE_MARKER_CONTEXT("skgpu::ganesh::Device", "drawGlyphRunList", fContext.get());
1139 SkASSERT(!glyphRunList.hasRSXForm());
1140
1141 if (glyphRunList.blob() == nullptr) {
1142 // If the glyphRunList does not have an associated text blob, then it was created by one of
1143 // the direct draw APIs (drawGlyphs, etc.). Use a Slug to draw the glyphs.
1144 auto slug = this->convertGlyphRunListToSlug(glyphRunList, paint);
1145 if (slug != nullptr) {
1146 this->drawSlug(canvas, slug.get(), paint);
1147 }
1148 } else {
1149 fSurfaceDrawContext->drawGlyphRunList(canvas,
1150 this->clip(),
1151 this->localToDevice(),
1152 glyphRunList,
1153 this->strikeDeviceInfo(),
1154 paint);
1155 }
1156 }
1157
1158 ///////////////////////////////////////////////////////////////////////////////
1159
1160 void Device::drawDrawable(SkCanvas* canvas, SkDrawable* drawable, const SkMatrix* matrix) {
1161 ASSERT_SINGLE_OWNER
1162
1163 GrBackendApi api = this->recordingContext()->backend();
1164 if (GrBackendApi::kVulkan == api) {
1165 const SkMatrix& ctm = this->localToDevice();
1166 const SkMatrix& combinedMatrix = matrix ? SkMatrix::Concat(ctm, *matrix) : ctm;
1167 std::unique_ptr<SkDrawable::GpuDrawHandler> gpuDraw =
1168 drawable->snapGpuDrawHandler(api, combinedMatrix, this->devClipBounds(),
1169 this->imageInfo());
1170 if (gpuDraw) {
1171 fSurfaceDrawContext->drawDrawable(
1172 std::move(gpuDraw), combinedMatrix.mapRect(drawable->getBounds()));
1173 return;
1174 }
1175 }
1176 this->SkDevice::drawDrawable(canvas, drawable, matrix);
1177 }
1178
1179
1180 ///////////////////////////////////////////////////////////////////////////////
1181
1182 GrSurfaceProxyView Device::readSurfaceView() {
1183 return this->surfaceFillContext()->readSurfaceView();
1184 }
1185
1186 GrRenderTargetProxy* Device::targetProxy() {
1187 return this->readSurfaceView().asRenderTargetProxy();
1188 }
1189
1190 bool Device::wait(int numSemaphores,
1191 const GrBackendSemaphore* waitSemaphores,
1192 bool deleteSemaphoresAfterWait) {
1193 ASSERT_SINGLE_OWNER
1194
1195 return fSurfaceDrawContext->waitOnSemaphores(numSemaphores, waitSemaphores,
1196 deleteSemaphoresAfterWait);
1197 }
1198
1199 void Device::discard() {
1200 fSurfaceDrawContext->discard();
1201 }
1202
1203 void Device::resolveMSAA() {
1204 fSurfaceDrawContext->resolveMSAA();
1205 }
1206
1207 bool Device::replaceBackingProxy(SkSurface::ContentChangeMode mode,
1208 sk_sp<GrRenderTargetProxy> newRTP,
1209 GrColorType grColorType,
1210 sk_sp<SkColorSpace> colorSpace,
1211 GrSurfaceOrigin origin,
1212 const SkSurfaceProps& props) {
1213 auto sdc = SurfaceDrawContext::Make(fContext.get(), grColorType, std::move(newRTP),
1214 std::move(colorSpace), origin, props);
1215 if (!sdc) {
1216 return false;
1217 }
1218
1219 SkASSERT(sdc->dimensions() == fSurfaceDrawContext->dimensions());
1220 SkASSERT(sdc->numSamples() == fSurfaceDrawContext->numSamples());
1221 SkASSERT(sdc->asSurfaceProxy()->priv().isExact());
1222 if (mode == SkSurface::kRetain_ContentChangeMode) {
1223 if (fContext->abandoned()) {
1224 return false;
1225 }
1226
1227 SkASSERT(fSurfaceDrawContext->asTextureProxy());
1228 SkAssertResult(sdc->blitTexture(fSurfaceDrawContext->readSurfaceView(),
1229 SkIRect::MakeWH(this->width(), this->height()),
1230 SkIPoint::Make(0, 0)));
1231 }
1232
1233 fSurfaceDrawContext = std::move(sdc);
1234 return true;
1235 }
1236
1237 bool Device::replaceBackingProxy(SkSurface::ContentChangeMode mode) {
1238 ASSERT_SINGLE_OWNER
1239
1240 const SkImageInfo& ii = this->imageInfo();
1241 GrRenderTargetProxy* oldRTP = this->targetProxy();
1242 GrSurfaceProxyView oldView = this->readSurfaceView();
1243
1244 auto grColorType = SkColorTypeToGrColorType(ii.colorType());
1245 auto format = fContext->priv().caps()->getDefaultBackendFormat(grColorType, GrRenderable::kYes);
1246 if (!format.isValid()) {
1247 return false;
1248 }
1249
1250 GrProxyProvider* proxyProvider = fContext->priv().proxyProvider();
1251 // This entry point is used by SkSurface_Ganesh::onCopyOnWrite so it must create a
1252 // kExact-backed render target proxy
1253 sk_sp<GrTextureProxy> proxy =
1254 proxyProvider->createProxy(format,
1255 ii.dimensions(),
1256 GrRenderable::kYes,
1257 oldRTP->numSamples(),
1258 oldView.mipmapped(),
1259 SkBackingFit::kExact,
1260 oldRTP->isBudgeted(),
1261 oldRTP->isProtected(),
1262 /*label=*/"BaseDevice_ReplaceBackingProxy");
1263 if (!proxy) {
1264 return false;
1265 }
1266
1267 return this->replaceBackingProxy(mode, sk_ref_sp(proxy->asRenderTargetProxy()),
1268 grColorType, ii.refColorSpace(), oldView.origin(),
1269 this->surfaceProps());
1270 }
1271
1272 void Device::asyncRescaleAndReadPixels(const SkImageInfo& info,
1273 const SkIRect& srcRect,
1274 RescaleGamma rescaleGamma,
1275 RescaleMode rescaleMode,
1276 ReadPixelsCallback callback,
1277 ReadPixelsContext context) {
1278 auto* sdc = fSurfaceDrawContext.get();
1279 // Context TODO: Elevate direct context requirement to public API.
1280 auto dContext = sdc->recordingContext()->asDirectContext();
1281 if (!dContext) {
1282 return;
1283 }
1284 sdc->asyncRescaleAndReadPixels(dContext, info, srcRect, rescaleGamma, rescaleMode, callback,
1285 context);
1286 }
1287
1288 void Device::asyncRescaleAndReadPixelsYUV420(SkYUVColorSpace yuvColorSpace,
1289 bool readAlpha,
1290 sk_sp<SkColorSpace> dstColorSpace,
1291 const SkIRect& srcRect,
1292 SkISize dstSize,
1293 RescaleGamma rescaleGamma,
1294 RescaleMode rescaleMode,
1295 ReadPixelsCallback callback,
1296 ReadPixelsContext context) {
1297 auto* sdc = fSurfaceDrawContext.get();
1298 // Context TODO: Elevate direct context requirement to public API.
1299 auto dContext = sdc->recordingContext()->asDirectContext();
1300 if (!dContext) {
1301 return;
1302 }
1303 sdc->asyncRescaleAndReadPixelsYUV420(dContext,
1304 yuvColorSpace,
1305 readAlpha,
1306 std::move(dstColorSpace),
1307 srcRect,
1308 dstSize,
1309 rescaleGamma,
1310 rescaleMode,
1311 callback,
1312 context);
1313 }
1314
1315 ///////////////////////////////////////////////////////////////////////////////
1316
1317 sk_sp<SkDevice> Device::createDevice(const CreateInfo& cinfo, const SkPaint*) {
1318 ASSERT_SINGLE_OWNER
1319
1320 SkSurfaceProps props =
1321 this->surfaceProps().cloneWithPixelGeometry(cinfo.fPixelGeometry);
1322
1323 SkASSERT(cinfo.fInfo.colorType() != kRGBA_1010102_SkColorType);
1324
1325 auto sdc = SurfaceDrawContext::MakeWithFallback(
1326 fContext.get(),
1327 SkColorTypeToGrColorType(cinfo.fInfo.colorType()),
1328 cinfo.fInfo.refColorSpace(),
1329 SkBackingFit::kApprox,
1330 cinfo.fInfo.dimensions(),
1331 props,
1332 fSurfaceDrawContext->numSamples(),
1333 skgpu::Mipmapped::kNo,
1334 fSurfaceDrawContext->asSurfaceProxy()->isProtected(),
1335 fSurfaceDrawContext->origin(),
1336 skgpu::Budgeted::kYes);
1337 if (!sdc) {
1338 return nullptr;
1339 }
1340
1341 // Skia's convention is to only clear a device if it is non-opaque.
1342 InitContents init = cinfo.fInfo.isOpaque() ? InitContents::kUninit : InitContents::kClear;
1343
1344 return Device::Make(std::move(sdc), cinfo.fInfo.alphaType(), init);
1345 }
1346
1347 sk_sp<SkSurface> Device::makeSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
1348 ASSERT_SINGLE_OWNER
1349 // TODO: Change the signature of newSurface to take a budgeted parameter.
1350 static const skgpu::Budgeted kBudgeted = skgpu::Budgeted::kNo;
1351 bool isProtected = this->targetProxy()->isProtected() == GrProtected::kYes;
1352 return SkSurfaces::RenderTarget(fContext.get(),
1353 kBudgeted,
1354 info,
1355 fSurfaceDrawContext->numSamples(),
1356 fSurfaceDrawContext->origin(),
1357 &props,
1358 /* shouldCreateWithMips= */ false,
1359 isProtected);
1360 }
1361
1362 ////////////////////////////////////////////////////////////////////////////////////
1363
1364 bool Device::android_utils_clipWithStencil() {
1365 SkRegion clipRegion;
1366 this->android_utils_clipAsRgn(&clipRegion);
1367 if (clipRegion.isEmpty()) {
1368 return false;
1369 }
1370 auto sdc = fSurfaceDrawContext.get();
1371 SkASSERT(sdc);
1372 GrPaint grPaint;
1373 grPaint.setXPFactory(GrDisableColorXPFactory::Get());
1374 static constexpr GrUserStencilSettings kDrawToStencil(
1375 GrUserStencilSettings::StaticInit<
1376 0x1,
1377 GrUserStencilTest::kAlways,
1378 0x1,
1379 GrUserStencilOp::kReplace,
1380 GrUserStencilOp::kReplace,
1381 0x1>()
1382 );
1383 // Regions don't actually need AA, but in DMSAA mode everything is antialiased.
1384 GrAA aa = GrAA(fSurfaceDrawContext->alwaysAntialias());
1385 sdc->drawRegion(nullptr, std::move(grPaint), aa, SkMatrix::I(), clipRegion,
1386 GrStyle::SimpleFill(), &kDrawToStencil);
1387 return true;
1388 }
1389
1390 SkStrikeDeviceInfo Device::strikeDeviceInfo() const {
1391 return {this->surfaceProps(), this->scalerContextFlags(), &fSubRunControl};
1392 }
1393
1394 sk_sp<sktext::gpu::Slug> Device::convertGlyphRunListToSlug(const sktext::GlyphRunList& glyphRunList,
1395 const SkPaint& paint) {
1396 return sktext::gpu::SlugImpl::Make(this->localToDevice(),
1397 glyphRunList,
1398 paint,
1399 this->strikeDeviceInfo(),
1400 SkStrikeCache::GlobalStrikeCache());
1401 }
1402
1403 #if defined(SK_DEBUG)
1404 static bool valid_slug_matrices(const SkMatrix& creationMatrix, const SkMatrix& positionMatrix) {
1405 // A Slug can be drawn with:
1406 // The exact same matrix that was used for creation
1407 // - OR -
1408 // A non-perspective matrix that has the same 2x2 and a relative integer translation
1409 //
1410 // For the second case, calculate the translation in source space to a translation in
1411 // device space by mapping (0, 0) through both the creationMatrix and the positionMatrix;
1412 // take the difference.
1413 if (creationMatrix == positionMatrix) {
1414 return true;
1415 }
1416
1417 SkVector translation = positionMatrix.mapOrigin() - creationMatrix.mapOrigin();
1418 return creationMatrix.getScaleX() == positionMatrix.getScaleX() &&
1419 creationMatrix.getScaleY() == positionMatrix.getScaleY() &&
1420 creationMatrix.getSkewX() == positionMatrix.getSkewX() &&
1421 creationMatrix.getSkewY() == positionMatrix.getSkewY() &&
1422 !positionMatrix.hasPerspective() && !creationMatrix.hasPerspective() &&
1423 SkScalarIsInt(translation.x()) && SkScalarIsInt(translation.y());
1424 }
1425 #endif
1426
1427
1428 void Device::drawSlug(SkCanvas* canvas, const sktext::gpu::Slug* slug, const SkPaint& paint) {
1429 SkASSERT(canvas);
1430 SkASSERT(slug);
1431 const sktext::gpu::SlugImpl* slugImpl = static_cast<const sktext::gpu::SlugImpl*>(slug);
1432 #if defined(SK_DEBUG)
1433 if (!fContext->priv().options().fSupportBilerpFromGlyphAtlas) {
1434 // We can draw a slug if the atlas has padding or if the creation matrix and the
1435 // drawing matrix are the same (up to integer translation).
1436 // If they are the same, then the Slug will use the direct drawing code and not use bi-lerp.
1437 SkMatrix slugMatrix = slugImpl->initialPositionMatrix();
1438 SkMatrix positionMatrix = this->localToDevice();
1439 positionMatrix.preTranslate(slugImpl->origin().x(), slugImpl->origin().y());
1440 SkASSERT(valid_slug_matrices(slugMatrix, positionMatrix));
1441 }
1442 #endif
1443 auto atlasDelegate = [&](const sktext::gpu::AtlasSubRun* subRun,
1444 SkPoint drawOrigin,
1445 const SkPaint& paint,
1446 sk_sp<SkRefCnt> subRunStorage,
1447 sktext::gpu::RendererData) {
1448 auto[drawingClip, op] = AtlasTextOp::Make(
1449 fSurfaceDrawContext.get(), subRun,
1450 this->clip(), this->localToDevice(), drawOrigin, paint,
1451 std::move(subRunStorage));
1452 if (op != nullptr) {
1453 fSurfaceDrawContext->addDrawOp(drawingClip, std::move(op));
1454 }
1455 };
1456
1457 slugImpl->subRuns()->draw(canvas, slugImpl->origin(), paint, slugImpl, atlasDelegate);
1458 }
1459
1460 } // namespace skgpu::ganesh