blob: 480780a578494f4cfdf6503f628279618d538a52 [file] [log] [blame]
Michael Ludwiga195d102020-09-15 14:51:52 -04001/*
2 * Copyright 2020 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/GrClipStack.h"
9
10#include "include/core/SkMatrix.h"
Chris Dalton7d592cd2021-03-11 22:49:33 -070011#include "src/core/SkPathPriv.h"
Michael Ludwiga195d102020-09-15 14:51:52 -040012#include "src/core/SkRRectPriv.h"
13#include "src/core/SkRectPriv.h"
14#include "src/core/SkTaskGroup.h"
15#include "src/gpu/GrClip.h"
Adlai Holler9e2c50e2021-02-09 14:41:52 -050016#include "src/gpu/GrDeferredProxyUploader.h"
Adlai Hollera0693042020-10-14 11:23:11 -040017#include "src/gpu/GrDirectContextPriv.h"
Michael Ludwiga195d102020-09-15 14:51:52 -040018#include "src/gpu/GrProxyProvider.h"
19#include "src/gpu/GrRecordingContextPriv.h"
Michael Ludwiga195d102020-09-15 14:51:52 -040020#include "src/gpu/GrSWMaskHelper.h"
21#include "src/gpu/GrStencilMaskHelper.h"
22#include "src/gpu/ccpr/GrCoverageCountingPathRenderer.h"
23#include "src/gpu/effects/GrBlendFragmentProcessor.h"
24#include "src/gpu/effects/GrConvexPolyEffect.h"
25#include "src/gpu/effects/GrRRectEffect.h"
26#include "src/gpu/effects/GrTextureEffect.h"
27#include "src/gpu/effects/generated/GrAARectEffect.h"
28#include "src/gpu/effects/generated/GrDeviceSpaceEffect.h"
29#include "src/gpu/geometry/GrQuadUtils.h"
30
31namespace {
32
33// This captures which of the two elements in (A op B) would be required when they are combined,
34// where op is intersect or difference.
35enum class ClipGeometry {
36 kEmpty,
37 kAOnly,
38 kBOnly,
39 kBoth
40};
41
42// A and B can be Element, SaveRecord, or Draw. Supported combinations are, order not mattering,
43// (Element, Element), (Element, SaveRecord), (Element, Draw), and (SaveRecord, Draw).
44template<typename A, typename B>
45static ClipGeometry get_clip_geometry(const A& a, const B& b) {
46 // NOTE: SkIRect::Intersects() returns false when two rectangles touch at an edge (so the result
47 // is empty). This behavior is desired for the following clip effect policies.
48 if (a.op() == SkClipOp::kIntersect) {
49 if (b.op() == SkClipOp::kIntersect) {
50 // Intersect (A) + Intersect (B)
51 if (!SkIRect::Intersects(a.outerBounds(), b.outerBounds())) {
52 // Regions with non-zero coverage are disjoint, so intersection = empty
53 return ClipGeometry::kEmpty;
54 } else if (b.contains(a)) {
55 // B's full coverage region contains entirety of A, so intersection = A
56 return ClipGeometry::kAOnly;
57 } else if (a.contains(b)) {
58 // A's full coverage region contains entirety of B, so intersection = B
59 return ClipGeometry::kBOnly;
60 } else {
61 // The shapes intersect in some non-trivial manner
62 return ClipGeometry::kBoth;
63 }
64 } else {
65 SkASSERT(b.op() == SkClipOp::kDifference);
66 // Intersect (A) + Difference (B)
67 if (!SkIRect::Intersects(a.outerBounds(), b.outerBounds())) {
68 // A only intersects B's full coverage region, so intersection = A
69 return ClipGeometry::kAOnly;
70 } else if (b.contains(a)) {
71 // B's zero coverage region completely contains A, so intersection = empty
72 return ClipGeometry::kEmpty;
73 } else {
74 // Intersection cannot be simplified. Note that the combination of a intersect
75 // and difference op in this order cannot produce kBOnly
76 return ClipGeometry::kBoth;
77 }
78 }
79 } else {
80 SkASSERT(a.op() == SkClipOp::kDifference);
81 if (b.op() == SkClipOp::kIntersect) {
82 // Difference (A) + Intersect (B) - the mirror of Intersect(A) + Difference(B),
83 // but combining is commutative so this is equivalent barring naming.
84 if (!SkIRect::Intersects(b.outerBounds(), a.outerBounds())) {
85 // B only intersects A's full coverage region, so intersection = B
86 return ClipGeometry::kBOnly;
87 } else if (a.contains(b)) {
88 // A's zero coverage region completely contains B, so intersection = empty
89 return ClipGeometry::kEmpty;
90 } else {
91 // Cannot be simplified
92 return ClipGeometry::kBoth;
93 }
94 } else {
95 SkASSERT(b.op() == SkClipOp::kDifference);
96 // Difference (A) + Difference (B)
97 if (a.contains(b)) {
98 // A's zero coverage region contains B, so B doesn't remove any extra
99 // coverage from their intersection.
100 return ClipGeometry::kAOnly;
101 } else if (b.contains(a)) {
102 // Mirror of the above case, intersection = B instead
103 return ClipGeometry::kBOnly;
104 } else {
105 // Intersection of the two differences cannot be simplified. Note that for
106 // this op combination it is not possible to produce kEmpty.
107 return ClipGeometry::kBoth;
108 }
109 }
110 }
111}
112
113// a.contains(b) where a's local space is defined by 'aToDevice', and b's possibly separate local
114// space is defined by 'bToDevice'. 'a' and 'b' geometry are provided in their local spaces.
115// Automatically takes into account if the anti-aliasing policies differ. When the policies match,
116// we assume that coverage AA or GPU's non-AA rasterization will apply to A and B equivalently, so
117// we can compare the original shapes. When the modes are mixed, we outset B in device space first.
118static bool shape_contains_rect(
119 const GrShape& a, const SkMatrix& aToDevice, const SkMatrix& deviceToA,
120 const SkRect& b, const SkMatrix& bToDevice, bool mixedAAMode) {
121 if (!a.convex()) {
122 return false;
123 }
124
125 if (!mixedAAMode && aToDevice == bToDevice) {
126 // A and B are in the same coordinate space, so don't bother mapping
127 return a.conservativeContains(b);
Michael Ludwigd30e9ef2020-09-28 12:03:01 -0400128 } else if (bToDevice.isIdentity() && aToDevice.preservesAxisAlignment()) {
Michael Ludwig84a008f2020-09-18 15:30:55 -0400129 // Optimize the common case of draws (B, with identity matrix) and axis-aligned shapes,
130 // instead of checking the four corners separately.
131 SkRect bInA = b;
132 if (mixedAAMode) {
133 bInA.outset(0.5f, 0.5f);
134 }
135 SkAssertResult(deviceToA.mapRect(&bInA));
136 return a.conservativeContains(bInA);
Michael Ludwiga195d102020-09-15 14:51:52 -0400137 }
138
139 // Test each corner for contains; since a is convex, if all 4 corners of b's bounds are
140 // contained, then the entirety of b is within a.
141 GrQuad deviceQuad = GrQuad::MakeFromRect(b, bToDevice);
142 if (any(deviceQuad.w4f() < SkPathPriv::kW0PlaneDistance)) {
143 // Something in B actually projects behind the W = 0 plane and would be clipped to infinity,
144 // so it's extremely unlikely that A can contain B.
145 return false;
146 }
147 if (mixedAAMode) {
148 // Outset it so its edges are 1/2px out, giving us a buffer to avoid cases where a non-AA
149 // clip or draw would snap outside an aa element.
150 GrQuadUtils::Outset({0.5f, 0.5f, 0.5f, 0.5f}, &deviceQuad);
151 }
152
153 for (int i = 0; i < 4; ++i) {
154 SkPoint cornerInA = deviceQuad.point(i);
155 deviceToA.mapPoints(&cornerInA, 1);
156 if (!a.conservativeContains(cornerInA)) {
157 return false;
158 }
159 }
160
161 return true;
162}
163
164static SkIRect subtract(const SkIRect& a, const SkIRect& b, bool exact) {
165 SkIRect diff;
166 if (SkRectPriv::Subtract(a, b, &diff) || !exact) {
167 // Either A-B is exactly the rectangle stored in diff, or we don't need an exact answer
168 // and can settle for the subrect of A excluded from B (which is also 'diff')
169 return diff;
170 } else {
171 // For our purposes, we want the original A when A-B cannot be exactly represented
172 return a;
173 }
174}
175
176static GrClipEdgeType get_clip_edge_type(SkClipOp op, GrAA aa) {
177 if (op == SkClipOp::kIntersect) {
178 return aa == GrAA::kYes ? GrClipEdgeType::kFillAA : GrClipEdgeType::kFillBW;
179 } else {
180 return aa == GrAA::kYes ? GrClipEdgeType::kInverseFillAA : GrClipEdgeType::kInverseFillBW;
181 }
182}
183
184static uint32_t kInvalidGenID = 0;
185static uint32_t kEmptyGenID = 1;
186static uint32_t kWideOpenGenID = 2;
187
188static uint32_t next_gen_id() {
189 // 0-2 are reserved for invalid, empty & wide-open
190 static const uint32_t kFirstUnreservedGenID = 3;
191 static std::atomic<uint32_t> nextID{kFirstUnreservedGenID};
192
193 uint32_t id;
194 do {
Adlai Holler4888cda2020-11-06 16:37:37 -0500195 id = nextID.fetch_add(1, std::memory_order_relaxed);
Michael Ludwiga195d102020-09-15 14:51:52 -0400196 } while (id < kFirstUnreservedGenID);
197 return id;
198}
199
200// Functions for rendering / applying clip shapes in various ways
201// The general strategy is:
202// - Represent the clip element as an analytic FP that tests sk_FragCoord vs. its device shape
203// - Render the clip element to the stencil, if stencil is allowed and supports the AA, and the
204// size of the element indicates stenciling will be worth it, vs. making a mask.
205// - Try to put the individual element into a clip atlas, which is then sampled during the draw
206// - Render the element into a SW mask and upload it. If possible, the SW rasterization happens
207// in parallel.
208static constexpr GrSurfaceOrigin kMaskOrigin = kTopLeft_GrSurfaceOrigin;
209
210static GrFPResult analytic_clip_fp(const GrClipStack::Element& e,
211 const GrShaderCaps& caps,
212 std::unique_ptr<GrFragmentProcessor> fp) {
213 // All analytic clip shape FPs need to be in device space
214 GrClipEdgeType edgeType = get_clip_edge_type(e.fOp, e.fAA);
215 if (e.fLocalToDevice.isIdentity()) {
216 if (e.fShape.isRect()) {
217 return GrFPSuccess(GrAARectEffect::Make(std::move(fp), edgeType, e.fShape.rect()));
218 } else if (e.fShape.isRRect()) {
219 return GrRRectEffect::Make(std::move(fp), edgeType, e.fShape.rrect(), caps);
220 }
221 }
222
223 // A convex hull can be transformed into device space (this will handle rect shapes with a
224 // non-identity transform).
225 if (e.fShape.segmentMask() == SkPath::kLine_SegmentMask && e.fShape.convex()) {
226 SkPath devicePath;
227 e.fShape.asPath(&devicePath);
228 devicePath.transform(e.fLocalToDevice);
229 return GrConvexPolyEffect::Make(std::move(fp), edgeType, devicePath);
230 }
231
232 return GrFPFailure(std::move(fp));
233}
234
Michael Ludwiga195d102020-09-15 14:51:52 -0400235static void draw_to_sw_mask(GrSWMaskHelper* helper, const GrClipStack::Element& e, bool clearMask) {
236 // If the first element to draw is an intersect, we clear to 0 and will draw it directly with
237 // coverage 1 (subsequent intersect elements will be inverse-filled and draw 0 outside).
238 // If the first element to draw is a difference, we clear to 1, and in all cases we draw the
239 // difference element directly with coverage 0.
240 if (clearMask) {
241 helper->clear(e.fOp == SkClipOp::kIntersect ? 0x00 : 0xFF);
242 }
243
244 uint8_t alpha;
245 bool invert;
246 if (e.fOp == SkClipOp::kIntersect) {
247 // Intersect modifies pixels outside of its geometry. If this isn't the first op, we
248 // draw the inverse-filled shape with 0 coverage to erase everything outside the element
249 // But if we are the first element, we can draw directly with coverage 1 since we
250 // cleared to 0.
251 if (clearMask) {
252 alpha = 0xFF;
253 invert = false;
254 } else {
255 alpha = 0x00;
256 invert = true;
257 }
258 } else {
259 // For difference ops, can always just subtract the shape directly by drawing 0 coverage
260 SkASSERT(e.fOp == SkClipOp::kDifference);
261 alpha = 0x00;
262 invert = false;
263 }
264
265 // Draw the shape; based on how we've initialized the buffer and chosen alpha+invert,
266 // every element is drawn with the kReplace_Op
267 if (invert) {
268 // Must invert the path
269 SkASSERT(!e.fShape.inverted());
270 // TODO: this is an extra copy effectively, just so we can toggle inversion; would be
271 // better perhaps to just call a drawPath() since we know it'll use path rendering w/
272 // the inverse fill type.
273 GrShape inverted(e.fShape);
274 inverted.setInverted(true);
275 helper->drawShape(inverted, e.fLocalToDevice, SkRegion::kReplace_Op, e.fAA, alpha);
276 } else {
277 helper->drawShape(e.fShape, e.fLocalToDevice, SkRegion::kReplace_Op, e.fAA, alpha);
278 }
279}
280
281static GrSurfaceProxyView render_sw_mask(GrRecordingContext* context, const SkIRect& bounds,
282 const GrClipStack::Element** elements, int count) {
283 SkASSERT(count > 0);
284
Adlai Hollercc25d532021-02-10 13:58:34 +0000285 SkTaskGroup* taskGroup = nullptr;
286 if (auto direct = context->asDirectContext()) {
287 taskGroup = direct->priv().getTaskGroup();
Michael Ludwiga195d102020-09-15 14:51:52 -0400288 }
Adlai Hollercc25d532021-02-10 13:58:34 +0000289
290 if (taskGroup) {
291 const GrCaps* caps = context->priv().caps();
292 GrProxyProvider* proxyProvider = context->priv().proxyProvider();
293
294 // Create our texture proxy
295 GrBackendFormat format = caps->getDefaultBackendFormat(GrColorType::kAlpha_8,
296 GrRenderable::kNo);
297
298 GrSwizzle swizzle = context->priv().caps()->getReadSwizzle(format, GrColorType::kAlpha_8);
299 auto proxy = proxyProvider->createProxy(format, bounds.size(), GrRenderable::kNo, 1,
300 GrMipMapped::kNo, SkBackingFit::kApprox,
301 SkBudgeted::kYes, GrProtected::kNo);
302
303 // Since this will be rendered on another thread, make a copy of the elements in case
304 // the clip stack is modified on the main thread
305 using Uploader = GrTDeferredProxyUploader<SkTArray<GrClipStack::Element>>;
306 std::unique_ptr<Uploader> uploader = std::make_unique<Uploader>(count);
307 for (int i = 0; i < count; ++i) {
308 uploader->data().push_back(*(elements[i]));
Michael Ludwiga195d102020-09-15 14:51:52 -0400309 }
Adlai Hollercc25d532021-02-10 13:58:34 +0000310
311 Uploader* uploaderRaw = uploader.get();
312 auto drawAndUploadMask = [uploaderRaw, bounds] {
313 TRACE_EVENT0("skia.gpu", "Threaded SW Clip Mask Render");
314 GrSWMaskHelper helper(uploaderRaw->getPixels());
315 if (helper.init(bounds)) {
316 for (int i = 0; i < uploaderRaw->data().count(); ++i) {
317 draw_to_sw_mask(&helper, uploaderRaw->data()[i], i == 0);
318 }
319 } else {
320 SkDEBUGFAIL("Unable to allocate SW clip mask.");
321 }
322 uploaderRaw->signalAndFreeData();
323 };
324
325 taskGroup->add(std::move(drawAndUploadMask));
326 proxy->texPriv().setDeferredUploader(std::move(uploader));
327
328 return {std::move(proxy), kMaskOrigin, swizzle};
329 } else {
330 GrSWMaskHelper helper;
331 if (!helper.init(bounds)) {
332 return {};
333 }
334
335 for (int i = 0; i < count; ++i) {
336 draw_to_sw_mask(&helper,*(elements[i]), i == 0);
337 }
338
339 return helper.toTextureView(context, SkBackingFit::kApprox);
340 }
Michael Ludwiga195d102020-09-15 14:51:52 -0400341}
342
Brian Salomoneebe7352020-12-09 16:37:04 -0500343static void render_stencil_mask(GrRecordingContext* context, GrSurfaceDrawContext* rtc,
Michael Ludwiga195d102020-09-15 14:51:52 -0400344 uint32_t genID, const SkIRect& bounds,
345 const GrClipStack::Element** elements, int count,
346 GrAppliedClip* out) {
347 GrStencilMaskHelper helper(context, rtc);
348 if (helper.init(bounds, genID, out->windowRectsState().windows(), 0)) {
349 // This follows the same logic as in draw_sw_mask
350 bool startInside = elements[0]->fOp == SkClipOp::kDifference;
351 helper.clear(startInside);
352 for (int i = 0; i < count; ++i) {
353 const GrClipStack::Element& e = *(elements[i]);
354 SkRegion::Op op;
355 if (e.fOp == SkClipOp::kIntersect) {
356 op = (i == 0) ? SkRegion::kReplace_Op : SkRegion::kIntersect_Op;
357 } else {
358 op = SkRegion::kDifference_Op;
359 }
360 helper.drawShape(e.fShape, e.fLocalToDevice, op, e.fAA);
361 }
362 helper.finish();
363 }
364 out->hardClip().addStencilClip(genID);
365}
366
367} // anonymous namespace
368
369class GrClipStack::Draw {
370public:
371 Draw(const SkRect& drawBounds, GrAA aa)
372 : fBounds(GrClip::GetPixelIBounds(drawBounds, aa, BoundsType::kExterior))
373 , fAA(aa) {
374 // Be slightly more forgiving on whether or not a draw is inside a clip element.
375 fOriginalBounds = drawBounds.makeInset(GrClip::kBoundsTolerance, GrClip::kBoundsTolerance);
376 if (fOriginalBounds.isEmpty()) {
377 fOriginalBounds = drawBounds;
378 }
379 }
380
381 // Common clip type interface
382 SkClipOp op() const { return SkClipOp::kIntersect; }
383 const SkIRect& outerBounds() const { return fBounds; }
384
385 // Draw does not have inner bounds so cannot contain anything.
386 bool contains(const RawElement& e) const { return false; }
387 bool contains(const SaveRecord& s) const { return false; }
388
389 bool applyDeviceBounds(const SkIRect& deviceBounds) {
390 return fBounds.intersect(deviceBounds);
391 }
392
393 const SkRect& bounds() const { return fOriginalBounds; }
394 GrAA aa() const { return fAA; }
395
396private:
397 SkRect fOriginalBounds;
398 SkIRect fBounds;
399 GrAA fAA;
400};
401
402///////////////////////////////////////////////////////////////////////////////
403// GrClipStack::Element
404
405GrClipStack::RawElement::RawElement(const SkMatrix& localToDevice, const GrShape& shape,
406 GrAA aa, SkClipOp op)
407 : Element{shape, localToDevice, op, aa}
408 , fInnerBounds(SkIRect::MakeEmpty())
409 , fOuterBounds(SkIRect::MakeEmpty())
410 , fInvalidatedByIndex(-1) {
411 if (!localToDevice.invert(&fDeviceToLocal)) {
412 // If the transform can't be inverted, it means that two dimensions are collapsed to 0 or
413 // 1 dimension, making the device-space geometry effectively empty.
414 fShape.reset();
415 }
416}
417
418void GrClipStack::RawElement::markInvalid(const SaveRecord& current) {
419 SkASSERT(!this->isInvalid());
420 fInvalidatedByIndex = current.firstActiveElementIndex();
421}
422
423void GrClipStack::RawElement::restoreValid(const SaveRecord& current) {
424 if (current.firstActiveElementIndex() < fInvalidatedByIndex) {
425 fInvalidatedByIndex = -1;
426 }
427}
428
429bool GrClipStack::RawElement::contains(const Draw& d) const {
430 if (fInnerBounds.contains(d.outerBounds())) {
431 return true;
432 } else {
433 // If the draw is non-AA, use the already computed outer bounds so we don't need to use
434 // device-space outsetting inside shape_contains_rect.
435 SkRect queryBounds = d.aa() == GrAA::kYes ? d.bounds() : SkRect::Make(d.outerBounds());
436 return shape_contains_rect(fShape, fLocalToDevice, fDeviceToLocal,
437 queryBounds, SkMatrix::I(), /* mixed-aa */ false);
438 }
439}
440
441bool GrClipStack::RawElement::contains(const SaveRecord& s) const {
442 if (fInnerBounds.contains(s.outerBounds())) {
443 return true;
444 } else {
445 // This is very similar to contains(Draw) but we just have outerBounds to work with.
446 SkRect queryBounds = SkRect::Make(s.outerBounds());
447 return shape_contains_rect(fShape, fLocalToDevice, fDeviceToLocal,
448 queryBounds, SkMatrix::I(), /* mixed-aa */ false);
449 }
450}
451
452bool GrClipStack::RawElement::contains(const RawElement& e) const {
453 // This is similar to how RawElement checks containment for a Draw, except that both the tester
454 // and testee have a transform that needs to be considered.
455 if (fInnerBounds.contains(e.fOuterBounds)) {
456 return true;
457 }
458
459 bool mixedAA = fAA != e.fAA;
460 if (!mixedAA && fLocalToDevice == e.fLocalToDevice) {
461 // Test the shapes directly against each other, with a special check for a rrect+rrect
462 // containment (a intersect b == a implies b contains a) and paths (same gen ID, or same
463 // path for small paths means they contain each other).
464 static constexpr int kMaxPathComparePoints = 16;
465 if (fShape.isRRect() && e.fShape.isRRect()) {
466 return SkRRectPriv::ConservativeIntersect(fShape.rrect(), e.fShape.rrect())
467 == e.fShape.rrect();
468 } else if (fShape.isPath() && e.fShape.isPath()) {
469 return fShape.path().getGenerationID() == e.fShape.path().getGenerationID() ||
470 (fShape.path().getPoints(nullptr, 0) <= kMaxPathComparePoints &&
471 fShape.path() == e.fShape.path());
472 } // else fall through to shape_contains_rect
473 }
474
475 return shape_contains_rect(fShape, fLocalToDevice, fDeviceToLocal,
476 e.fShape.bounds(), e.fLocalToDevice, mixedAA);
477
478}
479
480void GrClipStack::RawElement::simplify(const SkIRect& deviceBounds, bool forceAA) {
481 // Make sure the shape is not inverted. An inverted shape is equivalent to a non-inverted shape
482 // with the clip op toggled.
483 if (fShape.inverted()) {
484 fOp = fOp == SkClipOp::kIntersect ? SkClipOp::kDifference : SkClipOp::kIntersect;
485 fShape.setInverted(false);
486 }
487
488 // Then simplify the base shape, if it becomes empty, no need to update the bounds
489 fShape.simplify();
490 SkASSERT(!fShape.inverted());
491 if (fShape.isEmpty()) {
492 return;
493 }
494
495 // Lines and points should have been turned into empty since we assume everything is filled
496 SkASSERT(!fShape.isPoint() && !fShape.isLine());
497 // Validity check, we have no public API to create an arc at the moment
498 SkASSERT(!fShape.isArc());
499
500 SkRect outer = fLocalToDevice.mapRect(fShape.bounds());
501 if (!outer.intersect(SkRect::Make(deviceBounds))) {
502 // A non-empty shape is offscreen, so treat it as empty
503 fShape.reset();
504 return;
505 }
506
Michael Ludwig462bdfc2020-09-22 16:27:04 -0400507 // Except for axis-aligned clip rects, upgrade to AA when forced. We skip axis-aligned clip
508 // rects because a non-AA axis aligned rect can always be set as just a scissor test or window
509 // rect, avoiding an expensive stencil mask generation.
Michael Ludwigd30e9ef2020-09-28 12:03:01 -0400510 if (forceAA && !(fShape.isRect() && fLocalToDevice.preservesAxisAlignment())) {
Michael Ludwiga195d102020-09-15 14:51:52 -0400511 fAA = GrAA::kYes;
512 }
513
514 // Except for non-AA axis-aligned rects, the outer bounds is the rounded-out device-space
515 // mapped bounds of the shape.
516 fOuterBounds = GrClip::GetPixelIBounds(outer, fAA, BoundsType::kExterior);
517
Michael Ludwigd30e9ef2020-09-28 12:03:01 -0400518 if (fLocalToDevice.preservesAxisAlignment()) {
Michael Ludwiga195d102020-09-15 14:51:52 -0400519 if (fShape.isRect()) {
520 // The actual geometry can be updated to the device-intersected bounds and we can
521 // know the inner bounds
522 fShape.rect() = outer;
523 fLocalToDevice.setIdentity();
524 fDeviceToLocal.setIdentity();
525
526 if (fAA == GrAA::kNo && outer.width() >= 1.f && outer.height() >= 1.f) {
527 // NOTE: Legacy behavior to avoid performance regressions. For non-aa axis-aligned
528 // clip rects we always just round so that they can be scissor-only (avoiding the
529 // uncertainty in how a GPU might actually round an edge on fractional coords).
530 fOuterBounds = outer.round();
531 fInnerBounds = fOuterBounds;
532 } else {
533 fInnerBounds = GrClip::GetPixelIBounds(outer, fAA, BoundsType::kInterior);
534 SkASSERT(fOuterBounds.contains(fInnerBounds) || fInnerBounds.isEmpty());
535 }
536 } else if (fShape.isRRect()) {
Michael Ludwig3dad8032020-09-28 11:24:05 -0400537 // Can't transform in place and must still check transform result since some very
538 // ill-formed scale+translate matrices can cause invalid rrect radii.
539 SkRRect src;
540 if (fShape.rrect().transform(fLocalToDevice, &src)) {
541 fShape.rrect() = src;
542 fLocalToDevice.setIdentity();
543 fDeviceToLocal.setIdentity();
Michael Ludwiga195d102020-09-15 14:51:52 -0400544
Michael Ludwig3dad8032020-09-28 11:24:05 -0400545 SkRect inner = SkRRectPriv::InnerBounds(fShape.rrect());
546 fInnerBounds = GrClip::GetPixelIBounds(inner, fAA, BoundsType::kInterior);
547 if (!fInnerBounds.intersect(deviceBounds)) {
548 fInnerBounds = SkIRect::MakeEmpty();
549 }
Michael Ludwiga195d102020-09-15 14:51:52 -0400550 }
551 }
552 }
553
554 if (fOuterBounds.isEmpty()) {
555 // This can happen if we have non-AA shapes smaller than a pixel that do not cover a pixel
556 // center. We could round out, but rasterization would still result in an empty clip.
557 fShape.reset();
558 }
559
560 // Post-conditions on inner and outer bounds
561 SkASSERT(fShape.isEmpty() || (!fOuterBounds.isEmpty() && deviceBounds.contains(fOuterBounds)));
562 SkASSERT(fShape.isEmpty() || fInnerBounds.isEmpty() || fOuterBounds.contains(fInnerBounds));
563}
564
565bool GrClipStack::RawElement::combine(const RawElement& other, const SaveRecord& current) {
566 // To reduce the number of possibilities, only consider intersect+intersect. Difference and
567 // mixed op cases could be analyzed to simplify one of the shapes, but that is a rare
568 // occurrence and the math is much more complicated.
569 if (other.fOp != SkClipOp::kIntersect || fOp != SkClipOp::kIntersect) {
570 return false;
571 }
572
573 // At the moment, only rect+rect or rrect+rrect are supported (although rect+rrect is
574 // treated as a degenerate case of rrect+rrect).
575 bool shapeUpdated = false;
576 if (fShape.isRect() && other.fShape.isRect()) {
577 bool aaMatch = fAA == other.fAA;
578 if (fLocalToDevice.isIdentity() && other.fLocalToDevice.isIdentity() && !aaMatch) {
579 if (GrClip::IsPixelAligned(fShape.rect())) {
580 // Our AA type doesn't really matter, take other's since its edges may not be
581 // pixel aligned, so after intersection clip behavior should respect its aa type.
582 fAA = other.fAA;
583 } else if (!GrClip::IsPixelAligned(other.fShape.rect())) {
584 // Neither shape is pixel aligned and AA types don't match so can't combine
585 return false;
586 }
587 // Either we've updated this->fAA to actually match, or other->fAA doesn't matter so
588 // this can be set to true. We just can't modify other to set it's aa to this->fAA.
589 // But since 'this' becomes the combo of the two, other will be deleted so that's fine.
590 aaMatch = true;
591 }
592
593 if (aaMatch && fLocalToDevice == other.fLocalToDevice) {
594 if (!fShape.rect().intersect(other.fShape.rect())) {
595 // By floating point, it turns out the combination should be empty
596 this->fShape.reset();
597 this->markInvalid(current);
598 return true;
599 }
600 shapeUpdated = true;
601 }
602 } else if ((fShape.isRect() || fShape.isRRect()) &&
603 (other.fShape.isRect() || other.fShape.isRRect())) {
604 // No such pixel-aligned disregard for AA for round rects
605 if (fAA == other.fAA && fLocalToDevice == other.fLocalToDevice) {
606 // Treat rrect+rect intersections as rrect+rrect
607 SkRRect a = fShape.isRect() ? SkRRect::MakeRect(fShape.rect()) : fShape.rrect();
608 SkRRect b = other.fShape.isRect() ? SkRRect::MakeRect(other.fShape.rect())
609 : other.fShape.rrect();
610
611 SkRRect joined = SkRRectPriv::ConservativeIntersect(a, b);
612 if (!joined.isEmpty()) {
613 // Can reduce to a single element
614 if (joined.isRect()) {
615 // And with a simplified type
616 fShape.setRect(joined.rect());
617 } else {
618 fShape.setRRect(joined);
619 }
620 shapeUpdated = true;
621 } else if (!a.getBounds().intersects(b.getBounds())) {
622 // Like the rect+rect combination, the intersection is actually empty
623 fShape.reset();
624 this->markInvalid(current);
625 return true;
626 }
627 }
628 }
629
630 if (shapeUpdated) {
631 // This logic works under the assumption that both combined elements were intersect, so we
632 // don't do the full bounds computations like in simplify().
633 SkASSERT(fOp == SkClipOp::kIntersect && other.fOp == SkClipOp::kIntersect);
634 SkAssertResult(fOuterBounds.intersect(other.fOuterBounds));
635 if (!fInnerBounds.intersect(other.fInnerBounds)) {
636 fInnerBounds = SkIRect::MakeEmpty();
637 }
638 return true;
639 } else {
640 return false;
641 }
642}
643
644void GrClipStack::RawElement::updateForElement(RawElement* added, const SaveRecord& current) {
645 if (this->isInvalid()) {
646 // Already doesn't do anything, so skip this element
647 return;
648 }
649
650 // 'A' refers to this element, 'B' refers to 'added'.
651 switch (get_clip_geometry(*this, *added)) {
652 case ClipGeometry::kEmpty:
653 // Mark both elements as invalid to signal that the clip is fully empty
654 this->markInvalid(current);
655 added->markInvalid(current);
656 break;
657
658 case ClipGeometry::kAOnly:
659 // This element already clips more than 'added', so mark 'added' is invalid to skip it
660 added->markInvalid(current);
661 break;
662
663 case ClipGeometry::kBOnly:
664 // 'added' clips more than this element, so mark this as invalid
665 this->markInvalid(current);
666 break;
667
668 case ClipGeometry::kBoth:
669 // Else the bounds checks think we need to keep both, but depending on the combination
670 // of the ops and shape kinds, we may be able to do better.
671 if (added->combine(*this, current)) {
672 // 'added' now fully represents the combination of the two elements
673 this->markInvalid(current);
674 }
675 break;
676 }
677}
678
679GrClipStack::ClipState GrClipStack::RawElement::clipType() const {
680 // Map from the internal shape kind to the clip state enum
681 switch (fShape.type()) {
682 case GrShape::Type::kEmpty:
683 return ClipState::kEmpty;
684
685 case GrShape::Type::kRect:
686 return fOp == SkClipOp::kIntersect && fLocalToDevice.isIdentity()
687 ? ClipState::kDeviceRect : ClipState::kComplex;
688
689 case GrShape::Type::kRRect:
690 return fOp == SkClipOp::kIntersect && fLocalToDevice.isIdentity()
691 ? ClipState::kDeviceRRect : ClipState::kComplex;
692
693 case GrShape::Type::kArc:
694 case GrShape::Type::kLine:
695 case GrShape::Type::kPoint:
696 // These types should never become RawElements
697 SkASSERT(false);
698 [[fallthrough]];
699
700 case GrShape::Type::kPath:
701 return ClipState::kComplex;
702 }
703 SkUNREACHABLE;
704}
705
706///////////////////////////////////////////////////////////////////////////////
707// GrClipStack::Mask
708
709GrClipStack::Mask::Mask(const SaveRecord& current, const SkIRect& drawBounds)
710 : fBounds(drawBounds)
711 , fGenID(current.genID()) {
712 static const GrUniqueKey::Domain kDomain = GrUniqueKey::GenerateDomain();
713
714 // The gen ID should not be invalid, empty, or wide open, since those do not require masks
715 SkASSERT(fGenID != kInvalidGenID && fGenID != kEmptyGenID && fGenID != kWideOpenGenID);
716
717 GrUniqueKey::Builder builder(&fKey, kDomain, 3, "clip_mask");
718 builder[0] = fGenID;
719 // SkToS16 because image filters outset layers to a size indicated by the filter, which can
720 // sometimes result in negative coordinates from device space.
721 builder[1] = SkToS16(drawBounds.fLeft) | (SkToS16(drawBounds.fRight) << 16);
722 builder[2] = SkToS16(drawBounds.fTop) | (SkToS16(drawBounds.fBottom) << 16);
723 SkASSERT(fKey.isValid());
724
725 SkDEBUGCODE(fOwner = &current;)
726}
727
728bool GrClipStack::Mask::appliesToDraw(const SaveRecord& current, const SkIRect& drawBounds) const {
729 // For the same save record, a larger mask will have the same or more elements
730 // baked into it, so it can be reused to clip the smaller draw.
731 SkASSERT(fGenID != current.genID() || &current == fOwner);
732 return fGenID == current.genID() && fBounds.contains(drawBounds);
733}
734
735void GrClipStack::Mask::invalidate(GrProxyProvider* proxyProvider) {
736 SkASSERT(proxyProvider);
737 SkASSERT(fKey.isValid()); // Should only be invalidated once
738 proxyProvider->processInvalidUniqueKey(
739 fKey, nullptr, GrProxyProvider::InvalidateGPUResource::kYes);
740 fKey.reset();
741}
742
743///////////////////////////////////////////////////////////////////////////////
744// GrClipStack::SaveRecord
745
746GrClipStack::SaveRecord::SaveRecord(const SkIRect& deviceBounds)
747 : fInnerBounds(deviceBounds)
748 , fOuterBounds(deviceBounds)
749 , fShader(nullptr)
750 , fStartingMaskIndex(0)
751 , fStartingElementIndex(0)
752 , fOldestValidIndex(0)
753 , fDeferredSaveCount(0)
754 , fStackOp(SkClipOp::kIntersect)
755 , fState(ClipState::kWideOpen)
756 , fGenID(kInvalidGenID) {}
757
758GrClipStack::SaveRecord::SaveRecord(const SaveRecord& prior,
759 int startingMaskIndex,
760 int startingElementIndex)
761 : fInnerBounds(prior.fInnerBounds)
762 , fOuterBounds(prior.fOuterBounds)
763 , fShader(prior.fShader)
764 , fStartingMaskIndex(startingMaskIndex)
765 , fStartingElementIndex(startingElementIndex)
766 , fOldestValidIndex(prior.fOldestValidIndex)
767 , fDeferredSaveCount(0)
768 , fStackOp(prior.fStackOp)
769 , fState(prior.fState)
770 , fGenID(kInvalidGenID) {
771 // If the prior record never needed a mask, this one will insert into the same index
772 // (that's okay since we'll remove it when this record is popped off the stack).
773 SkASSERT(startingMaskIndex >= prior.fStartingMaskIndex);
774 // The same goes for elements (the prior could have been wide open).
775 SkASSERT(startingElementIndex >= prior.fStartingElementIndex);
776}
777
778uint32_t GrClipStack::SaveRecord::genID() const {
779 if (fState == ClipState::kEmpty) {
780 return kEmptyGenID;
781 } else if (fState == ClipState::kWideOpen) {
782 return kWideOpenGenID;
783 } else {
784 // The gen ID shouldn't be empty or wide open, since they are reserved for the above
785 // if-cases. It may be kInvalid if the record hasn't had any elements added to it yet.
786 SkASSERT(fGenID != kEmptyGenID && fGenID != kWideOpenGenID);
787 return fGenID;
788 }
789}
790
791GrClipStack::ClipState GrClipStack::SaveRecord::state() const {
792 if (fShader && fState != ClipState::kEmpty) {
793 return ClipState::kComplex;
794 } else {
795 return fState;
796 }
797}
798
799bool GrClipStack::SaveRecord::contains(const GrClipStack::Draw& draw) const {
800 return fInnerBounds.contains(draw.outerBounds());
801}
802
803bool GrClipStack::SaveRecord::contains(const GrClipStack::RawElement& element) const {
804 return fInnerBounds.contains(element.outerBounds());
805}
806
807void GrClipStack::SaveRecord::removeElements(RawElement::Stack* elements) {
808 while (elements->count() > fStartingElementIndex) {
809 elements->pop_back();
810 }
811}
812
813void GrClipStack::SaveRecord::restoreElements(RawElement::Stack* elements) {
814 // Presumably this SaveRecord is the new top of the stack, and so it owns the elements
815 // from its starting index to restoreCount - 1. Elements from the old save record have
816 // been destroyed already, so their indices would have been >= restoreCount, and any
817 // still-present element can be un-invalidated based on that.
818 int i = elements->count() - 1;
819 for (RawElement& e : elements->ritems()) {
820 if (i < fOldestValidIndex) {
821 break;
822 }
823 e.restoreValid(*this);
824 --i;
825 }
826}
827
828void GrClipStack::SaveRecord::invalidateMasks(GrProxyProvider* proxyProvider,
829 Mask::Stack* masks) {
830 // Must explicitly invalidate the key before removing the mask object from the stack
831 while (masks->count() > fStartingMaskIndex) {
832 SkASSERT(masks->back().owner() == this && proxyProvider);
833 masks->back().invalidate(proxyProvider);
834 masks->pop_back();
835 }
836 SkASSERT(masks->empty() || masks->back().genID() != fGenID);
837}
838
839void GrClipStack::SaveRecord::reset(const SkIRect& bounds) {
840 SkASSERT(this->canBeUpdated());
841 fOldestValidIndex = fStartingElementIndex;
842 fOuterBounds = bounds;
843 fInnerBounds = bounds;
844 fStackOp = SkClipOp::kIntersect;
845 fState = ClipState::kWideOpen;
846 fShader = nullptr;
847}
848
849void GrClipStack::SaveRecord::addShader(sk_sp<SkShader> shader) {
850 SkASSERT(shader);
851 SkASSERT(this->canBeUpdated());
852 if (!fShader) {
853 fShader = std::move(shader);
854 } else {
855 // The total coverage is computed by multiplying the coverage from each element (shape or
856 // shader), but since multiplication is associative, we can use kSrcIn blending to make
857 // a new shader that represents 'shader' * 'fShader'
858 fShader = SkShaders::Blend(SkBlendMode::kSrcIn, std::move(shader), fShader);
859 }
860}
861
862bool GrClipStack::SaveRecord::addElement(RawElement&& toAdd, RawElement::Stack* elements) {
863 // Validity check the element's state first; if the shape class isn't empty, the outer bounds
864 // shouldn't be empty; if the inner bounds are not empty, they must be contained in outer.
865 SkASSERT((toAdd.shape().isEmpty() || !toAdd.outerBounds().isEmpty()) &&
866 (toAdd.innerBounds().isEmpty() || toAdd.outerBounds().contains(toAdd.innerBounds())));
867 // And we shouldn't be adding an element if we have a deferred save
868 SkASSERT(this->canBeUpdated());
869
870 if (fState == ClipState::kEmpty) {
871 // The clip is already empty, and we only shrink, so there's no need to record this element.
872 return false;
873 } else if (toAdd.shape().isEmpty()) {
874 // An empty difference op should have been detected earlier, since it's a no-op
875 SkASSERT(toAdd.op() == SkClipOp::kIntersect);
876 fState = ClipState::kEmpty;
877 return true;
878 }
879
880 // In this invocation, 'A' refers to the existing stack's bounds and 'B' refers to the new
881 // element.
882 switch (get_clip_geometry(*this, toAdd)) {
883 case ClipGeometry::kEmpty:
884 // The combination results in an empty clip
885 fState = ClipState::kEmpty;
886 return true;
887
888 case ClipGeometry::kAOnly:
889 // The combination would not be any different than the existing clip
890 return false;
891
892 case ClipGeometry::kBOnly:
893 // The combination would invalidate the entire existing stack and can be replaced with
894 // just the new element.
895 this->replaceWithElement(std::move(toAdd), elements);
896 return true;
897
898 case ClipGeometry::kBoth:
899 // The new element combines in a complex manner, so update the stack's bounds based on
900 // the combination of its and the new element's ops (handled below)
901 break;
902 }
903
904 if (fState == ClipState::kWideOpen) {
905 // When the stack was wide open and the clip effect was kBoth, the "complex" manner is
906 // simply to keep the element and update the stack bounds to be the element's intersected
907 // with the device.
908 this->replaceWithElement(std::move(toAdd), elements);
909 return true;
910 }
911
912 // Some form of actual clip element(s) to combine with.
913 if (fStackOp == SkClipOp::kIntersect) {
914 if (toAdd.op() == SkClipOp::kIntersect) {
915 // Intersect (stack) + Intersect (toAdd)
916 // - Bounds updates is simply the paired intersections of outer and inner.
917 SkAssertResult(fOuterBounds.intersect(toAdd.outerBounds()));
918 if (!fInnerBounds.intersect(toAdd.innerBounds())) {
919 // NOTE: this does the right thing if either rect is empty, since we set the
920 // inner bounds to empty here
921 fInnerBounds = SkIRect::MakeEmpty();
922 }
923 } else {
924 // Intersect (stack) + Difference (toAdd)
925 // - Shrink the stack's outer bounds if the difference op's inner bounds completely
926 // cuts off an edge.
927 // - Shrink the stack's inner bounds to completely exclude the op's outer bounds.
928 fOuterBounds = subtract(fOuterBounds, toAdd.innerBounds(), /* exact */ true);
929 fInnerBounds = subtract(fInnerBounds, toAdd.outerBounds(), /* exact */ false);
930 }
931 } else {
932 if (toAdd.op() == SkClipOp::kIntersect) {
933 // Difference (stack) + Intersect (toAdd)
934 // - Bounds updates are just the mirror of Intersect(stack) + Difference(toAdd)
935 SkIRect oldOuter = fOuterBounds;
936 fOuterBounds = subtract(toAdd.outerBounds(), fInnerBounds, /* exact */ true);
937 fInnerBounds = subtract(toAdd.innerBounds(), oldOuter, /* exact */ false);
938 } else {
939 // Difference (stack) + Difference (toAdd)
940 // - The updated outer bounds is the union of outer bounds and the inner becomes the
941 // largest of the two possible inner bounds
942 fOuterBounds.join(toAdd.outerBounds());
943 if (toAdd.innerBounds().width() * toAdd.innerBounds().height() >
944 fInnerBounds.width() * fInnerBounds.height()) {
945 fInnerBounds = toAdd.innerBounds();
946 }
947 }
948 }
949
950 // If we get here, we're keeping the new element and the stack's bounds have been updated.
951 // We ought to have caught the cases where the stack bounds resemble an empty or wide open
952 // clip, so assert that's the case.
953 SkASSERT(!fOuterBounds.isEmpty() &&
954 (fInnerBounds.isEmpty() || fOuterBounds.contains(fInnerBounds)));
955
956 return this->appendElement(std::move(toAdd), elements);
957}
958
959bool GrClipStack::SaveRecord::appendElement(RawElement&& toAdd, RawElement::Stack* elements) {
960 // Update past elements to account for the new element
961 int i = elements->count() - 1;
962
963 // After the loop, elements between [max(youngestValid, startingIndex)+1, count-1] can be
964 // removed from the stack (these are the active elements that have been invalidated by the
965 // newest element; since it's the active part of the stack, no restore() can bring them back).
966 int youngestValid = fStartingElementIndex - 1;
967 // After the loop, elements between [0, oldestValid-1] are all invalid. The value of oldestValid
968 // becomes the save record's new fLastValidIndex value.
969 int oldestValid = elements->count();
970 // After the loop, this is the earliest active element that was invalidated. It may be
971 // older in the stack than earliestValid, so cannot be popped off, but can be used to store
972 // the new element instead of allocating more.
973 RawElement* oldestActiveInvalid = nullptr;
974 int oldestActiveInvalidIndex = elements->count();
975
976 for (RawElement& existing : elements->ritems()) {
977 if (i < fOldestValidIndex) {
978 break;
979 }
980 // We don't need to pass the actual index that toAdd will be saved to; just the minimum
981 // index of this save record, since that will result in the same restoration behavior later.
982 existing.updateForElement(&toAdd, *this);
983
984 if (toAdd.isInvalid()) {
985 if (existing.isInvalid()) {
986 // Both new and old invalid implies the entire clip becomes empty
987 fState = ClipState::kEmpty;
988 return true;
989 } else {
990 // The new element doesn't change the clip beyond what the old element already does
991 return false;
992 }
993 } else if (existing.isInvalid()) {
994 // The new element cancels out the old element. The new element may have been modified
995 // to account for the old element's geometry.
996 if (i >= fStartingElementIndex) {
997 // Still active, so the invalidated index could be used to store the new element
998 oldestActiveInvalid = &existing;
999 oldestActiveInvalidIndex = i;
1000 }
1001 } else {
1002 // Keep both new and old elements
1003 oldestValid = i;
1004 if (i > youngestValid) {
1005 youngestValid = i;
1006 }
1007 }
1008
1009 --i;
1010 }
1011
1012 // Post-iteration validity check
1013 SkASSERT(oldestValid == elements->count() ||
1014 (oldestValid >= fOldestValidIndex && oldestValid < elements->count()));
1015 SkASSERT(youngestValid == fStartingElementIndex - 1 ||
1016 (youngestValid >= fStartingElementIndex && youngestValid < elements->count()));
1017 SkASSERT((oldestActiveInvalid && oldestActiveInvalidIndex >= fStartingElementIndex &&
1018 oldestActiveInvalidIndex < elements->count()) || !oldestActiveInvalid);
1019
1020 // Update final state
1021 SkASSERT(oldestValid >= fOldestValidIndex);
1022 fOldestValidIndex = std::min(oldestValid, oldestActiveInvalidIndex);
1023 fState = oldestValid == elements->count() ? toAdd.clipType() : ClipState::kComplex;
1024 if (fStackOp == SkClipOp::kDifference && toAdd.op() == SkClipOp::kIntersect) {
1025 // The stack remains in difference mode only as long as all elements are difference
1026 fStackOp = SkClipOp::kIntersect;
1027 }
1028
1029 int targetCount = youngestValid + 1;
1030 if (!oldestActiveInvalid || oldestActiveInvalidIndex >= targetCount) {
1031 // toAdd will be stored right after youngestValid
1032 targetCount++;
1033 oldestActiveInvalid = nullptr;
1034 }
1035 while (elements->count() > targetCount) {
1036 SkASSERT(oldestActiveInvalid != &elements->back()); // shouldn't delete what we'll reuse
1037 elements->pop_back();
1038 }
1039 if (oldestActiveInvalid) {
1040 *oldestActiveInvalid = std::move(toAdd);
1041 } else if (elements->count() < targetCount) {
1042 elements->push_back(std::move(toAdd));
1043 } else {
1044 elements->back() = std::move(toAdd);
1045 }
1046
1047 // Changing this will prompt GrClipStack to invalidate any masks associated with this record.
1048 fGenID = next_gen_id();
1049 return true;
1050}
1051
1052void GrClipStack::SaveRecord::replaceWithElement(RawElement&& toAdd, RawElement::Stack* elements) {
1053 // The aggregate state of the save record mirrors the element
1054 fInnerBounds = toAdd.innerBounds();
1055 fOuterBounds = toAdd.outerBounds();
1056 fStackOp = toAdd.op();
1057 fState = toAdd.clipType();
1058
1059 // All prior active element can be removed from the stack: [startingIndex, count - 1]
1060 int targetCount = fStartingElementIndex + 1;
1061 while (elements->count() > targetCount) {
1062 elements->pop_back();
1063 }
1064 if (elements->count() < targetCount) {
1065 elements->push_back(std::move(toAdd));
1066 } else {
1067 elements->back() = std::move(toAdd);
1068 }
1069
1070 SkASSERT(elements->count() == fStartingElementIndex + 1);
1071
1072 // This invalidates all older elements that are owned by save records lower in the clip stack.
1073 fOldestValidIndex = fStartingElementIndex;
1074 fGenID = next_gen_id();
1075}
1076
1077///////////////////////////////////////////////////////////////////////////////
1078// GrClipStack
1079
1080// NOTE: Based on draw calls in all GMs, SKPs, and SVGs as of 08/20, 98% use a clip stack with
1081// one Element and up to two SaveRecords, thus the inline size for RawElement::Stack and
1082// SaveRecord::Stack (this conveniently keeps the size of GrClipStack manageable). The max
1083// encountered element stack depth was 5 and the max save depth was 6. Using an increment of 8 for
1084// these stacks means that clip management will incur a single allocation for the remaining 2%
1085// of the draws, with extra head room for more complex clips encountered in the wild.
1086//
1087// The mask stack increment size was chosen to be smaller since only 0.2% of the evaluated draw call
Chris Dalton92b35672021-04-01 11:39:21 -06001088// set ever used a mask (which includes stencil masks), or up to 0.3% when atlas clips are disabled.
Michael Ludwiga195d102020-09-15 14:51:52 -04001089static constexpr int kElementStackIncrement = 8;
1090static constexpr int kSaveStackIncrement = 8;
1091static constexpr int kMaskStackIncrement = 4;
1092
1093// And from this same draw call set, the most complex clip could only use 5 analytic coverage FPs.
1094// Historically we limited it to 4 based on Blink's call pattern, so we keep the limit as-is since
1095// it's so close to the empirically encountered max.
1096static constexpr int kMaxAnalyticFPs = 4;
1097// The number of stack-allocated mask pointers to store before extending the arrays.
1098// Stack size determined empirically, the maximum number of elements put in a SW mask was 4
1099// across our set of GMs, SKPs, and SVGs used for testing.
1100static constexpr int kNumStackMasks = 4;
1101
1102GrClipStack::GrClipStack(const SkIRect& deviceBounds, const SkMatrixProvider* matrixProvider,
1103 bool forceAA)
1104 : fElements(kElementStackIncrement)
1105 , fSaves(kSaveStackIncrement)
1106 , fMasks(kMaskStackIncrement)
1107 , fProxyProvider(nullptr)
1108 , fDeviceBounds(deviceBounds)
1109 , fMatrixProvider(matrixProvider)
1110 , fForceAA(forceAA) {
1111 // Start with a save record that is wide open
1112 fSaves.emplace_back(deviceBounds);
1113}
1114
1115GrClipStack::~GrClipStack() {
1116 // Invalidate all mask keys that remain. Since we're tearing the clip stack down, we don't need
1117 // to go through SaveRecord.
1118 SkASSERT(fProxyProvider || fMasks.empty());
1119 if (fProxyProvider) {
1120 for (Mask& m : fMasks.ritems()) {
1121 m.invalidate(fProxyProvider);
1122 }
1123 }
1124}
1125
1126void GrClipStack::save() {
1127 SkASSERT(!fSaves.empty());
1128 fSaves.back().pushSave();
1129}
1130
1131void GrClipStack::restore() {
1132 SkASSERT(!fSaves.empty());
1133 SaveRecord& current = fSaves.back();
1134 if (current.popSave()) {
1135 // This was just a deferred save being undone, so the record doesn't need to be removed yet
1136 return;
1137 }
1138
1139 // When we remove a save record, we delete all elements >= its starting index and any masks
1140 // that were rasterized for it.
1141 current.removeElements(&fElements);
1142 SkASSERT(fProxyProvider || fMasks.empty());
1143 if (fProxyProvider) {
1144 current.invalidateMasks(fProxyProvider, &fMasks);
1145 }
1146 fSaves.pop_back();
1147 // Restore any remaining elements that were only invalidated by the now-removed save record.
1148 fSaves.back().restoreElements(&fElements);
1149}
1150
1151SkIRect GrClipStack::getConservativeBounds() const {
1152 const SaveRecord& current = this->currentSaveRecord();
1153 if (current.state() == ClipState::kEmpty) {
1154 return SkIRect::MakeEmpty();
1155 } else if (current.state() == ClipState::kWideOpen) {
1156 return fDeviceBounds;
1157 } else {
1158 if (current.op() == SkClipOp::kDifference) {
1159 // The outer/inner bounds represent what's cut out, so full bounds remains the device
1160 // bounds, minus any fully clipped content that spans the device edge.
1161 return subtract(fDeviceBounds, current.innerBounds(), /* exact */ true);
1162 } else {
1163 SkASSERT(fDeviceBounds.contains(current.outerBounds()));
1164 return current.outerBounds();
1165 }
1166 }
1167}
1168
1169GrClip::PreClipResult GrClipStack::preApply(const SkRect& bounds, GrAA aa) const {
1170 Draw draw(bounds, fForceAA ? GrAA::kYes : aa);
1171 if (!draw.applyDeviceBounds(fDeviceBounds)) {
1172 return GrClip::Effect::kClippedOut;
1173 }
1174
1175 const SaveRecord& cs = this->currentSaveRecord();
1176 // Early out if we know a priori that the clip is full 0s or full 1s.
1177 if (cs.state() == ClipState::kEmpty) {
1178 return GrClip::Effect::kClippedOut;
1179 } else if (cs.state() == ClipState::kWideOpen) {
1180 SkASSERT(!cs.shader());
1181 return GrClip::Effect::kUnclipped;
1182 }
1183
1184 // Given argument order, 'A' == current clip, 'B' == draw
1185 switch (get_clip_geometry(cs, draw)) {
1186 case ClipGeometry::kEmpty:
1187 // Can ignore the shader since the geometry removed everything already
1188 return GrClip::Effect::kClippedOut;
1189
1190 case ClipGeometry::kBOnly:
1191 // Geometrically, the draw is unclipped, but can't ignore a shader
1192 return cs.shader() ? GrClip::Effect::kClipped : GrClip::Effect::kUnclipped;
1193
1194 case ClipGeometry::kAOnly:
1195 // Shouldn't happen since the inner bounds of a draw are unknown
1196 SkASSERT(false);
1197 // But if it did, it technically means the draw covered the clip and should be
1198 // considered kClipped or similar, which is what the next case handles.
1199 [[fallthrough]];
1200
1201 case ClipGeometry::kBoth: {
1202 SkASSERT(fElements.count() > 0);
1203 const RawElement& back = fElements.back();
1204 if (cs.state() == ClipState::kDeviceRect) {
1205 SkASSERT(back.clipType() == ClipState::kDeviceRect);
1206 return {back.shape().rect(), back.aa()};
1207 } else if (cs.state() == ClipState::kDeviceRRect) {
1208 SkASSERT(back.clipType() == ClipState::kDeviceRRect);
1209 return {back.shape().rrect(), back.aa()};
1210 } else {
1211 // The clip stack has complex shapes, multiple elements, or a shader; we could
1212 // iterate per element like we would in apply(), but preApply() is meant to be
1213 // conservative and efficient.
1214 SkASSERT(cs.state() == ClipState::kComplex);
1215 return GrClip::Effect::kClipped;
1216 }
1217 }
1218 }
1219
1220 SkUNREACHABLE;
1221}
1222
Brian Salomoneebe7352020-12-09 16:37:04 -05001223GrClip::Effect GrClipStack::apply(GrRecordingContext* context, GrSurfaceDrawContext* rtc,
Michael Ludwiga195d102020-09-15 14:51:52 -04001224 GrAAType aa, bool hasUserStencilSettings,
Chris Dalton92b35672021-04-01 11:39:21 -06001225 GrAppliedClip* out, SkRect* bounds,
1226 SkTArray<SkPath>* pathsForClipAtlas) const {
1227 SkASSERT(!pathsForClipAtlas || pathsForClipAtlas->empty());
1228
Michael Ludwiga195d102020-09-15 14:51:52 -04001229 // TODO: Once we no longer store SW masks, we don't need to sneak the provider in like this
1230 if (!fProxyProvider) {
1231 fProxyProvider = context->priv().proxyProvider();
1232 }
1233 SkASSERT(fProxyProvider == context->priv().proxyProvider());
1234 const GrCaps* caps = context->priv().caps();
1235
1236 // Convert the bounds to a Draw and apply device bounds clipping, making our query as tight
1237 // as possible.
1238 Draw draw(*bounds, GrAA(fForceAA || aa != GrAAType::kNone));
1239 if (!draw.applyDeviceBounds(fDeviceBounds)) {
1240 return Effect::kClippedOut;
1241 }
1242 SkAssertResult(bounds->intersect(SkRect::Make(fDeviceBounds)));
1243
1244 const SaveRecord& cs = this->currentSaveRecord();
1245 // Early out if we know a priori that the clip is full 0s or full 1s.
1246 if (cs.state() == ClipState::kEmpty) {
1247 return Effect::kClippedOut;
1248 } else if (cs.state() == ClipState::kWideOpen) {
1249 SkASSERT(!cs.shader());
1250 return Effect::kUnclipped;
1251 }
1252
1253 // Convert any clip shader first, since it's not geometrically related to the draw bounds
1254 std::unique_ptr<GrFragmentProcessor> clipFP = nullptr;
1255 if (cs.shader()) {
1256 static const GrColorInfo kCoverageColorInfo{GrColorType::kUnknown, kPremul_SkAlphaType,
1257 nullptr};
Mike Reed12a75582021-03-20 10:49:02 -04001258 GrFPArgs args(context, *fMatrixProvider, &kCoverageColorInfo);
Michael Ludwiga195d102020-09-15 14:51:52 -04001259 clipFP = as_SB(cs.shader())->asFragmentProcessor(args);
1260 if (clipFP) {
Michael Ludwig4ce77862020-10-27 18:07:29 -04001261 // The initial input is the coverage from the geometry processor, so this ensures it
1262 // is multiplied properly with the alpha of the clip shader.
1263 clipFP = GrFragmentProcessor::MulInputByChildAlpha(std::move(clipFP));
Michael Ludwiga195d102020-09-15 14:51:52 -04001264 }
1265 }
1266
1267 // A refers to the entire clip stack, B refers to the draw
1268 switch (get_clip_geometry(cs, draw)) {
1269 case ClipGeometry::kEmpty:
1270 return Effect::kClippedOut;
1271
1272 case ClipGeometry::kBOnly:
1273 // Geometrically unclipped, but may need to add the shader as a coverage FP
1274 if (clipFP) {
1275 out->addCoverageFP(std::move(clipFP));
1276 return Effect::kClipped;
1277 } else {
1278 return Effect::kUnclipped;
1279 }
1280
1281 case ClipGeometry::kAOnly:
1282 // Shouldn't happen since draws don't report inner bounds
1283 SkASSERT(false);
1284 [[fallthrough]];
1285
1286 case ClipGeometry::kBoth:
1287 // The draw is combined with the saved clip elements; the below logic tries to skip
1288 // as many elements as possible.
1289 SkASSERT(cs.state() == ClipState::kDeviceRect ||
1290 cs.state() == ClipState::kDeviceRRect ||
1291 cs.state() == ClipState::kComplex);
1292 break;
1293 }
1294
1295 // We can determine a scissor based on the draw and the overall stack bounds.
1296 SkIRect scissorBounds;
1297 if (cs.op() == SkClipOp::kIntersect) {
1298 // Initially we keep this as large as possible; if the clip is applied solely with coverage
1299 // FPs then using a loose scissor increases the chance we can batch the draws.
1300 // We tighten it later if any form of mask or atlas element is needed.
1301 scissorBounds = cs.outerBounds();
1302 } else {
1303 scissorBounds = subtract(draw.outerBounds(), cs.innerBounds(), /* exact */ true);
1304 }
1305
1306 // We mark this true once we have a coverage FP (since complex clipping is occurring), or we
1307 // have an element that wouldn't affect the scissored draw bounds, but does affect the regular
1308 // draw bounds. In that case, the scissor is sufficient for clipping and we can skip the
1309 // element but definitely cannot then drop the scissor.
1310 bool scissorIsNeeded = SkToBool(cs.shader());
1311
1312 int remainingAnalyticFPs = kMaxAnalyticFPs;
Michael Ludwigb28e1412020-09-18 15:07:49 -04001313 if (hasUserStencilSettings) {
1314 // Disable analytic clips when there are user stencil settings to ensure the clip is
1315 // respected in the stencil buffer.
Michael Ludwiga195d102020-09-15 14:51:52 -04001316 remainingAnalyticFPs = 0;
Michael Ludwigb28e1412020-09-18 15:07:49 -04001317 // If we have user stencil settings, we shouldn't be avoiding the stencil buffer anyways.
Michael Ludwiga195d102020-09-15 14:51:52 -04001318 SkASSERT(!context->priv().caps()->avoidStencilBuffers());
1319 }
1320
1321 // If window rectangles are supported, we can use them to exclude inner bounds of difference ops
Brian Salomon70fe17e2020-11-30 14:33:58 -05001322 int maxWindowRectangles = rtc->maxWindowRectangles();
Michael Ludwiga195d102020-09-15 14:51:52 -04001323 GrWindowRectangles windowRects;
1324
1325 // Elements not represented as an analytic FP or skipped will be collected here and later
Chris Dalton92b35672021-04-01 11:39:21 -06001326 // applied by using the stencil buffer, clip atlas, or a cached SW mask.
Michael Ludwiga195d102020-09-15 14:51:52 -04001327 SkSTArray<kNumStackMasks, const Element*> elementsForMask;
Michael Ludwiga195d102020-09-15 14:51:52 -04001328
1329 bool maskRequiresAA = false;
Michael Ludwiga195d102020-09-15 14:51:52 -04001330
1331 int i = fElements.count();
1332 for (const RawElement& e : fElements.ritems()) {
1333 --i;
1334 if (i < cs.oldestElementIndex()) {
1335 // All earlier elements have been invalidated by elements already processed
1336 break;
1337 } else if (e.isInvalid()) {
1338 continue;
1339 }
1340
1341 switch (get_clip_geometry(e, draw)) {
1342 case ClipGeometry::kEmpty:
1343 // This can happen for difference op elements that have a larger fInnerBounds than
1344 // can be preserved at the next level.
1345 return Effect::kClippedOut;
1346
1347 case ClipGeometry::kBOnly:
1348 // We don't need to produce a coverage FP or mask for the element
1349 break;
1350
1351 case ClipGeometry::kAOnly:
1352 // Shouldn't happen for draws, fall through to regular element processing
1353 SkASSERT(false);
1354 [[fallthrough]];
1355
1356 case ClipGeometry::kBoth: {
1357 // The element must apply coverage to the draw, enable the scissor to limit overdraw
1358 scissorIsNeeded = true;
1359
1360 // First apply using HW methods (scissor and window rects). When the inner and outer
1361 // bounds match, nothing else needs to be done.
1362 bool fullyApplied = false;
1363 if (e.op() == SkClipOp::kIntersect) {
1364 // The second test allows clipped draws that are scissored by multiple elements
1365 // to remain scissor-only.
1366 fullyApplied = e.innerBounds() == e.outerBounds() ||
1367 e.innerBounds().contains(scissorBounds);
1368 } else {
Robert Phillipsc4fbc8d2020-11-30 10:17:53 -05001369 if (!e.innerBounds().isEmpty() && windowRects.count() < maxWindowRectangles) {
Michael Ludwiga195d102020-09-15 14:51:52 -04001370 // TODO: If we have more difference ops than available window rects, we
1371 // should prioritize those with the largest inner bounds.
1372 windowRects.addWindow(e.innerBounds());
1373 fullyApplied = e.innerBounds() == e.outerBounds();
1374 }
1375 }
1376
1377 if (!fullyApplied && remainingAnalyticFPs > 0) {
1378 std::tie(fullyApplied, clipFP) = analytic_clip_fp(e.asElement(),
1379 *caps->shaderCaps(),
1380 std::move(clipFP));
1381 if (fullyApplied) {
1382 remainingAnalyticFPs--;
Chris Dalton92b35672021-04-01 11:39:21 -06001383 } else if (pathsForClipAtlas && e.aa() == GrAA::kYes) {
Chris Dalton1e7b2e52021-03-09 21:29:32 -07001384 constexpr static int64_t kMaxClipPathArea =
1385 GrCoverageCountingPathRenderer::kMaxClipPathArea;
1386 SkIRect maskBounds;
1387 if (maskBounds.intersect(e.outerBounds(), draw.outerBounds()) &&
1388 maskBounds.height64() * maskBounds.width64() < kMaxClipPathArea) {
1389 // While technically the element is turned into a mask, each atlas entry
1390 // counts towards the FP complexity of the clip.
Chris Dalton92b35672021-04-01 11:39:21 -06001391 if (e.devicePath()->isEmpty()) {
1392 // Lazily fill in e.devicePath() if needed.
1393 e.shape().asPath(e.devicePath());
1394 e.devicePath()->transform(e.localToDevice());
1395 SkASSERT(!e.devicePath()->isEmpty());
1396 }
1397 pathsForClipAtlas->push_back(*e.devicePath());
1398 if (e.op() == SkClipOp::kDifference) {
1399 pathsForClipAtlas->back().toggleInverseFillType();
1400 }
Chris Dalton1e7b2e52021-03-09 21:29:32 -07001401 remainingAnalyticFPs--;
1402 fullyApplied = true;
1403 }
Michael Ludwiga195d102020-09-15 14:51:52 -04001404 }
1405 }
1406
1407 if (!fullyApplied) {
1408 elementsForMask.push_back(&e.asElement());
1409 maskRequiresAA |= (e.aa() == GrAA::kYes);
1410 }
1411
1412 break;
1413 }
1414 }
1415 }
1416
1417 if (!scissorIsNeeded) {
1418 // More detailed analysis of the element shapes determined no clip is needed
Chris Dalton92b35672021-04-01 11:39:21 -06001419 SkASSERT(elementsForMask.empty() && (!pathsForClipAtlas || pathsForClipAtlas->empty()) &&
1420 !clipFP);
Michael Ludwiga195d102020-09-15 14:51:52 -04001421 return Effect::kUnclipped;
1422 }
1423
1424 // Fill out the GrAppliedClip with what we know so far, possibly with a tightened scissor
1425 if (cs.op() == SkClipOp::kIntersect &&
Chris Dalton92b35672021-04-01 11:39:21 -06001426 (!elementsForMask.empty() || (pathsForClipAtlas && !pathsForClipAtlas->empty()))) {
Michael Ludwiga195d102020-09-15 14:51:52 -04001427 SkAssertResult(scissorBounds.intersect(draw.outerBounds()));
1428 }
1429 if (!GrClip::IsInsideClip(scissorBounds, *bounds)) {
Chris Dalton92b35672021-04-01 11:39:21 -06001430 if (!out->hardClip().addScissor(scissorBounds)) {
1431 return Effect::kClippedOut;
1432 }
1433 }
1434 if (!bounds->intersect(SkRect::Make(scissorBounds))) {
1435 return Effect::kClippedOut;
Michael Ludwiga195d102020-09-15 14:51:52 -04001436 }
1437 if (!windowRects.empty()) {
1438 out->hardClip().addWindowRectangles(windowRects, GrWindowRectsState::Mode::kExclusive);
1439 }
1440
1441 // Now rasterize any remaining elements, either to the stencil or a SW mask. All elements are
1442 // flattened into a single mask.
1443 if (!elementsForMask.empty()) {
1444 bool stencilUnavailable = context->priv().caps()->avoidStencilBuffers() ||
1445 rtc->wrapsVkSecondaryCB();
1446
1447 bool hasSWMask = false;
1448 if ((rtc->numSamples() <= 1 && maskRequiresAA) || stencilUnavailable) {
1449 // Must use a texture mask to represent the combined clip elements since the stencil
1450 // cannot be used, or cannot handle smooth clips.
1451 std::tie(hasSWMask, clipFP) = GetSWMaskFP(
1452 context, &fMasks, cs, scissorBounds, elementsForMask.begin(),
1453 elementsForMask.count(), std::move(clipFP));
1454 }
1455
1456 if (!hasSWMask) {
1457 if (stencilUnavailable) {
1458 SkDebugf("WARNING: Clip mask requires stencil, but stencil unavailable. "
1459 "Draw will be ignored.\n");
1460 return Effect::kClippedOut;
1461 } else {
1462 // Rasterize the remaining elements to the stencil buffer
1463 render_stencil_mask(context, rtc, cs.genID(), scissorBounds,
1464 elementsForMask.begin(), elementsForMask.count(), out);
1465 }
1466 }
1467 }
1468
Michael Ludwiga195d102020-09-15 14:51:52 -04001469 if (clipFP) {
Chris Dalton92b35672021-04-01 11:39:21 -06001470 // This will include all analytic FPs and a SW mask FP. The caller is responsible to add
1471 // atlas clip FPs once they know exactly which opsTask the atlas will come from.
Michael Ludwiga195d102020-09-15 14:51:52 -04001472 out->addCoverageFP(std::move(clipFP));
1473 }
1474
Chris Dalton92b35672021-04-01 11:39:21 -06001475 SkASSERT(scissorBounds.contains(*bounds));
1476 SkASSERT(out->doesClip() || (pathsForClipAtlas && !pathsForClipAtlas->empty()));
Michael Ludwiga195d102020-09-15 14:51:52 -04001477 return Effect::kClipped;
1478}
1479
1480GrClipStack::SaveRecord& GrClipStack::writableSaveRecord(bool* wasDeferred) {
1481 SaveRecord& current = fSaves.back();
1482 if (current.canBeUpdated()) {
1483 // Current record is still open, so it can be modified directly
1484 *wasDeferred = false;
1485 return current;
1486 } else {
1487 // Must undefer the save to get a new record.
1488 SkAssertResult(current.popSave());
1489 *wasDeferred = true;
1490 return fSaves.emplace_back(current, fMasks.count(), fElements.count());
1491 }
1492}
1493
1494void GrClipStack::clipShader(sk_sp<SkShader> shader) {
1495 // Shaders can't bring additional coverage
1496 if (this->currentSaveRecord().state() == ClipState::kEmpty) {
1497 return;
1498 }
1499
1500 bool wasDeferred;
1501 this->writableSaveRecord(&wasDeferred).addShader(std::move(shader));
1502 // Masks and geometry elements are not invalidated by updating the clip shader
1503}
1504
1505void GrClipStack::replaceClip(const SkIRect& rect) {
1506 bool wasDeferred;
1507 SaveRecord& save = this->writableSaveRecord(&wasDeferred);
1508
1509 if (!wasDeferred) {
1510 save.removeElements(&fElements);
1511 save.invalidateMasks(fProxyProvider, &fMasks);
1512 }
1513
1514 save.reset(fDeviceBounds);
1515 if (rect != fDeviceBounds) {
1516 this->clipRect(SkMatrix::I(), SkRect::Make(rect), GrAA::kNo, SkClipOp::kIntersect);
1517 }
1518}
1519
1520void GrClipStack::clip(RawElement&& element) {
1521 if (this->currentSaveRecord().state() == ClipState::kEmpty) {
1522 return;
1523 }
1524
1525 // Reduce the path to anything simpler, will apply the transform if it's a scale+translate
1526 // and ensures the element's bounds are clipped to the device (NOT the conservative clip bounds,
1527 // since those are based on the net effect of all elements while device bounds clipping happens
1528 // implicitly. During addElement, we may still be able to invalidate some older elements).
1529 element.simplify(fDeviceBounds, fForceAA);
1530 SkASSERT(!element.shape().inverted());
1531
1532 // An empty op means do nothing (for difference), or close the save record, so we try and detect
1533 // that early before doing additional unnecessary save record allocation.
1534 if (element.shape().isEmpty()) {
1535 if (element.op() == SkClipOp::kDifference) {
1536 // If the shape is empty and we're subtracting, this has no effect on the clip
1537 return;
1538 }
1539 // else we will make the clip empty, but we need a new save record to record that change
1540 // in the clip state; fall through to below and updateForElement() will handle it.
1541 }
1542
1543 bool wasDeferred;
1544 SaveRecord& save = this->writableSaveRecord(&wasDeferred);
1545 SkDEBUGCODE(uint32_t oldGenID = save.genID();)
1546 SkDEBUGCODE(int elementCount = fElements.count();)
1547 if (!save.addElement(std::move(element), &fElements)) {
1548 if (wasDeferred) {
1549 // We made a new save record, but ended up not adding an element to the stack.
1550 // So instead of keeping an empty save record around, pop it off and restore the counter
1551 SkASSERT(elementCount == fElements.count());
1552 fSaves.pop_back();
1553 fSaves.back().pushSave();
1554 } else {
1555 // Should not have changed gen ID if the element and save were not modified
1556 SkASSERT(oldGenID == save.genID());
1557 }
1558 } else {
1559 // The gen ID should be new, and should not be invalid
1560 SkASSERT(oldGenID != save.genID() && save.genID() != kInvalidGenID);
1561 if (fProxyProvider && !wasDeferred) {
1562 // We modified an active save record so any old masks it had can be invalidated
1563 save.invalidateMasks(fProxyProvider, &fMasks);
1564 }
1565 }
1566}
1567
1568GrFPResult GrClipStack::GetSWMaskFP(GrRecordingContext* context, Mask::Stack* masks,
1569 const SaveRecord& current, const SkIRect& bounds,
1570 const Element** elements, int count,
1571 std::unique_ptr<GrFragmentProcessor> clipFP) {
1572 GrProxyProvider* proxyProvider = context->priv().proxyProvider();
Brian Salomonc85bce82020-12-29 09:32:52 -05001573 GrSurfaceProxyView maskProxy;
Michael Ludwiga195d102020-09-15 14:51:52 -04001574
1575 SkIRect maskBounds; // may not be 'bounds' if we reuse a large clip mask
1576 // Check the existing masks from this save record for compatibility
1577 for (const Mask& m : masks->ritems()) {
1578 if (m.genID() != current.genID()) {
1579 break;
1580 }
1581 if (m.appliesToDraw(current, bounds)) {
Brian Salomonc85bce82020-12-29 09:32:52 -05001582 maskProxy = proxyProvider->findCachedProxyWithColorTypeFallback(
1583 m.key(), kMaskOrigin, GrColorType::kAlpha_8, 1);
1584 if (maskProxy) {
Michael Ludwiga195d102020-09-15 14:51:52 -04001585 maskBounds = m.bounds();
1586 break;
1587 }
1588 }
1589 }
1590
Brian Salomonc85bce82020-12-29 09:32:52 -05001591 if (!maskProxy) {
Michael Ludwiga195d102020-09-15 14:51:52 -04001592 // No existing mask was found, so need to render a new one
Brian Salomonc85bce82020-12-29 09:32:52 -05001593 maskProxy = render_sw_mask(context, bounds, elements, count);
1594 if (!maskProxy) {
Michael Ludwiga195d102020-09-15 14:51:52 -04001595 // If we still don't have one, there's nothing we can do
1596 return GrFPFailure(std::move(clipFP));
1597 }
1598
1599 // Register the mask for later invalidation
1600 Mask& mask = masks->emplace_back(current, bounds);
Brian Salomonc85bce82020-12-29 09:32:52 -05001601 proxyProvider->assignUniqueKeyToProxy(mask.key(), maskProxy.asTextureProxy());
Michael Ludwiga195d102020-09-15 14:51:52 -04001602 maskBounds = bounds;
1603 }
1604
1605 // Wrap the mask in an FP that samples it for coverage
Brian Salomonc85bce82020-12-29 09:32:52 -05001606 SkASSERT(maskProxy && maskProxy.origin() == kMaskOrigin);
Michael Ludwiga195d102020-09-15 14:51:52 -04001607
1608 GrSamplerState samplerState(GrSamplerState::WrapMode::kClampToBorder,
1609 GrSamplerState::Filter::kNearest);
1610 // Maps the device coords passed to the texture effect to the top-left corner of the mask, and
1611 // make sure that the draw bounds are pre-mapped into the mask's space as well.
1612 auto m = SkMatrix::Translate(-maskBounds.fLeft, -maskBounds.fTop);
1613 auto subset = SkRect::Make(bounds);
1614 subset.offset(-maskBounds.fLeft, -maskBounds.fTop);
1615 // We scissor to bounds. The mask's texel centers are aligned to device space
1616 // pixel centers. Hence this domain of texture coordinates.
1617 auto domain = subset.makeInset(0.5, 0.5);
Brian Salomonc85bce82020-12-29 09:32:52 -05001618 auto fp = GrTextureEffect::MakeSubset(std::move(maskProxy), kPremul_SkAlphaType, m,
1619 samplerState, subset, domain, *context->priv().caps());
Michael Ludwiga195d102020-09-15 14:51:52 -04001620 fp = GrDeviceSpaceEffect::Make(std::move(fp));
1621
1622 // Must combine the coverage sampled from the texture effect with the previous coverage
Brian Salomonb43d6992021-01-05 14:37:40 -05001623 fp = GrBlendFragmentProcessor::Make(std::move(fp), std::move(clipFP), SkBlendMode::kDstIn);
Michael Ludwiga195d102020-09-15 14:51:52 -04001624 return GrFPSuccess(std::move(fp));
1625}