blob: c6741b99f2c18fb67395201783f890520b09fbbc [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"
11#include "src/core/SkRRectPriv.h"
12#include "src/core/SkRectPriv.h"
13#include "src/core/SkTaskGroup.h"
14#include "src/gpu/GrClip.h"
15#include "src/gpu/GrContextPriv.h"
16#include "src/gpu/GrDeferredProxyUploader.h"
17#include "src/gpu/GrProxyProvider.h"
18#include "src/gpu/GrRecordingContextPriv.h"
19#include "src/gpu/GrRenderTargetContextPriv.h"
20#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 Ludwig84a008f2020-09-18 15:30:55 -0400128 } else if (bToDevice.isIdentity() && aToDevice.isScaleTranslate()) {
129 // 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 {
195 id = nextID++;
196 } 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
235// TODO: Currently this only works with CCPR because CCPR owns and manages the clip atlas. The
236// high-level concept should be generalized to support any path renderer going into a shared atlas.
237static std::unique_ptr<GrFragmentProcessor> clip_atlas_fp(GrCoverageCountingPathRenderer* ccpr,
238 uint32_t opsTaskID,
239 const SkIRect& bounds,
240 const GrClipStack::Element& e,
241 SkPath* devicePath,
242 const GrCaps& caps,
243 std::unique_ptr<GrFragmentProcessor> fp) {
244 // TODO: Currently the atlas manages device-space paths, so we have to transform by the ctm.
245 // In the future, the atlas manager should see the local path and the ctm so that it can
246 // cache across integer-only translations (internally, it already does this, just not exposed).
247 if (devicePath->isEmpty()) {
248 e.fShape.asPath(devicePath);
249 devicePath->transform(e.fLocalToDevice);
250 SkASSERT(!devicePath->isEmpty());
251 }
252
253 SkASSERT(!devicePath->isInverseFillType());
254 if (e.fOp == SkClipOp::kIntersect) {
255 return ccpr->makeClipProcessor(std::move(fp), opsTaskID, *devicePath, bounds, caps);
256 } else {
257 // Use kDstOut to convert the non-inverted mask alpha into (1-alpha), so the atlas only
258 // ever renders non-inverse filled paths.
259 // - When the input FP is null, this turns into "(1-sample(ccpr, 1).a) * input"
260 // - When not null, it works out to
261 // (1-sample(ccpr, input.rgb1).a) * sample(fp, input.rgb1) * input.a
262 // - Since clips only care about the alpha channel, these are both equivalent to the
263 // desired product of (1-ccpr) * fp * input.a.
264 return GrBlendFragmentProcessor::Make(
265 ccpr->makeClipProcessor(nullptr, opsTaskID, *devicePath, bounds, caps), // src
266 std::move(fp), // dst
267 SkBlendMode::kDstOut);
268 }
269}
270
271static void draw_to_sw_mask(GrSWMaskHelper* helper, const GrClipStack::Element& e, bool clearMask) {
272 // If the first element to draw is an intersect, we clear to 0 and will draw it directly with
273 // coverage 1 (subsequent intersect elements will be inverse-filled and draw 0 outside).
274 // If the first element to draw is a difference, we clear to 1, and in all cases we draw the
275 // difference element directly with coverage 0.
276 if (clearMask) {
277 helper->clear(e.fOp == SkClipOp::kIntersect ? 0x00 : 0xFF);
278 }
279
280 uint8_t alpha;
281 bool invert;
282 if (e.fOp == SkClipOp::kIntersect) {
283 // Intersect modifies pixels outside of its geometry. If this isn't the first op, we
284 // draw the inverse-filled shape with 0 coverage to erase everything outside the element
285 // But if we are the first element, we can draw directly with coverage 1 since we
286 // cleared to 0.
287 if (clearMask) {
288 alpha = 0xFF;
289 invert = false;
290 } else {
291 alpha = 0x00;
292 invert = true;
293 }
294 } else {
295 // For difference ops, can always just subtract the shape directly by drawing 0 coverage
296 SkASSERT(e.fOp == SkClipOp::kDifference);
297 alpha = 0x00;
298 invert = false;
299 }
300
301 // Draw the shape; based on how we've initialized the buffer and chosen alpha+invert,
302 // every element is drawn with the kReplace_Op
303 if (invert) {
304 // Must invert the path
305 SkASSERT(!e.fShape.inverted());
306 // TODO: this is an extra copy effectively, just so we can toggle inversion; would be
307 // better perhaps to just call a drawPath() since we know it'll use path rendering w/
308 // the inverse fill type.
309 GrShape inverted(e.fShape);
310 inverted.setInverted(true);
311 helper->drawShape(inverted, e.fLocalToDevice, SkRegion::kReplace_Op, e.fAA, alpha);
312 } else {
313 helper->drawShape(e.fShape, e.fLocalToDevice, SkRegion::kReplace_Op, e.fAA, alpha);
314 }
315}
316
317static GrSurfaceProxyView render_sw_mask(GrRecordingContext* context, const SkIRect& bounds,
318 const GrClipStack::Element** elements, int count) {
319 SkASSERT(count > 0);
320
321 SkTaskGroup* taskGroup = nullptr;
322 if (auto direct = context->asDirectContext()) {
323 taskGroup = direct->priv().getTaskGroup();
324 }
325
326 if (taskGroup) {
327 const GrCaps* caps = context->priv().caps();
328 GrProxyProvider* proxyProvider = context->priv().proxyProvider();
329
330 // Create our texture proxy
331 GrBackendFormat format = caps->getDefaultBackendFormat(GrColorType::kAlpha_8,
332 GrRenderable::kNo);
333
334 GrSwizzle swizzle = context->priv().caps()->getReadSwizzle(format, GrColorType::kAlpha_8);
335 auto proxy = proxyProvider->createProxy(format, bounds.size(), GrRenderable::kNo, 1,
336 GrMipMapped::kNo, SkBackingFit::kApprox,
337 SkBudgeted::kYes, GrProtected::kNo);
338
339 // Since this will be rendered on another thread, make a copy of the elements in case
340 // the clip stack is modified on the main thread
341 using Uploader = GrTDeferredProxyUploader<SkTArray<GrClipStack::Element>>;
342 std::unique_ptr<Uploader> uploader = std::make_unique<Uploader>(count);
343 for (int i = 0; i < count; ++i) {
344 uploader->data().push_back(*(elements[i]));
345 }
346
347 Uploader* uploaderRaw = uploader.get();
348 auto drawAndUploadMask = [uploaderRaw, bounds] {
349 TRACE_EVENT0("skia.gpu", "Threaded SW Clip Mask Render");
350 GrSWMaskHelper helper(uploaderRaw->getPixels());
351 if (helper.init(bounds)) {
352 for (int i = 0; i < uploaderRaw->data().count(); ++i) {
353 draw_to_sw_mask(&helper, uploaderRaw->data()[i], i == 0);
354 }
355 } else {
356 SkDEBUGFAIL("Unable to allocate SW clip mask.");
357 }
358 uploaderRaw->signalAndFreeData();
359 };
360
361 taskGroup->add(std::move(drawAndUploadMask));
362 proxy->texPriv().setDeferredUploader(std::move(uploader));
363
364 return {std::move(proxy), kMaskOrigin, swizzle};
365 } else {
366 GrSWMaskHelper helper;
367 if (!helper.init(bounds)) {
368 return {};
369 }
370
371 for (int i = 0; i < count; ++i) {
372 draw_to_sw_mask(&helper,*(elements[i]), i == 0);
373 }
374
375 return helper.toTextureView(context, SkBackingFit::kApprox);
376 }
377}
378
379static void render_stencil_mask(GrRecordingContext* context, GrRenderTargetContext* rtc,
380 uint32_t genID, const SkIRect& bounds,
381 const GrClipStack::Element** elements, int count,
382 GrAppliedClip* out) {
383 GrStencilMaskHelper helper(context, rtc);
384 if (helper.init(bounds, genID, out->windowRectsState().windows(), 0)) {
385 // This follows the same logic as in draw_sw_mask
386 bool startInside = elements[0]->fOp == SkClipOp::kDifference;
387 helper.clear(startInside);
388 for (int i = 0; i < count; ++i) {
389 const GrClipStack::Element& e = *(elements[i]);
390 SkRegion::Op op;
391 if (e.fOp == SkClipOp::kIntersect) {
392 op = (i == 0) ? SkRegion::kReplace_Op : SkRegion::kIntersect_Op;
393 } else {
394 op = SkRegion::kDifference_Op;
395 }
396 helper.drawShape(e.fShape, e.fLocalToDevice, op, e.fAA);
397 }
398 helper.finish();
399 }
400 out->hardClip().addStencilClip(genID);
401}
402
403} // anonymous namespace
404
405class GrClipStack::Draw {
406public:
407 Draw(const SkRect& drawBounds, GrAA aa)
408 : fBounds(GrClip::GetPixelIBounds(drawBounds, aa, BoundsType::kExterior))
409 , fAA(aa) {
410 // Be slightly more forgiving on whether or not a draw is inside a clip element.
411 fOriginalBounds = drawBounds.makeInset(GrClip::kBoundsTolerance, GrClip::kBoundsTolerance);
412 if (fOriginalBounds.isEmpty()) {
413 fOriginalBounds = drawBounds;
414 }
415 }
416
417 // Common clip type interface
418 SkClipOp op() const { return SkClipOp::kIntersect; }
419 const SkIRect& outerBounds() const { return fBounds; }
420
421 // Draw does not have inner bounds so cannot contain anything.
422 bool contains(const RawElement& e) const { return false; }
423 bool contains(const SaveRecord& s) const { return false; }
424
425 bool applyDeviceBounds(const SkIRect& deviceBounds) {
426 return fBounds.intersect(deviceBounds);
427 }
428
429 const SkRect& bounds() const { return fOriginalBounds; }
430 GrAA aa() const { return fAA; }
431
432private:
433 SkRect fOriginalBounds;
434 SkIRect fBounds;
435 GrAA fAA;
436};
437
438///////////////////////////////////////////////////////////////////////////////
439// GrClipStack::Element
440
441GrClipStack::RawElement::RawElement(const SkMatrix& localToDevice, const GrShape& shape,
442 GrAA aa, SkClipOp op)
443 : Element{shape, localToDevice, op, aa}
444 , fInnerBounds(SkIRect::MakeEmpty())
445 , fOuterBounds(SkIRect::MakeEmpty())
446 , fInvalidatedByIndex(-1) {
447 if (!localToDevice.invert(&fDeviceToLocal)) {
448 // If the transform can't be inverted, it means that two dimensions are collapsed to 0 or
449 // 1 dimension, making the device-space geometry effectively empty.
450 fShape.reset();
451 }
452}
453
454void GrClipStack::RawElement::markInvalid(const SaveRecord& current) {
455 SkASSERT(!this->isInvalid());
456 fInvalidatedByIndex = current.firstActiveElementIndex();
457}
458
459void GrClipStack::RawElement::restoreValid(const SaveRecord& current) {
460 if (current.firstActiveElementIndex() < fInvalidatedByIndex) {
461 fInvalidatedByIndex = -1;
462 }
463}
464
465bool GrClipStack::RawElement::contains(const Draw& d) const {
466 if (fInnerBounds.contains(d.outerBounds())) {
467 return true;
468 } else {
469 // If the draw is non-AA, use the already computed outer bounds so we don't need to use
470 // device-space outsetting inside shape_contains_rect.
471 SkRect queryBounds = d.aa() == GrAA::kYes ? d.bounds() : SkRect::Make(d.outerBounds());
472 return shape_contains_rect(fShape, fLocalToDevice, fDeviceToLocal,
473 queryBounds, SkMatrix::I(), /* mixed-aa */ false);
474 }
475}
476
477bool GrClipStack::RawElement::contains(const SaveRecord& s) const {
478 if (fInnerBounds.contains(s.outerBounds())) {
479 return true;
480 } else {
481 // This is very similar to contains(Draw) but we just have outerBounds to work with.
482 SkRect queryBounds = SkRect::Make(s.outerBounds());
483 return shape_contains_rect(fShape, fLocalToDevice, fDeviceToLocal,
484 queryBounds, SkMatrix::I(), /* mixed-aa */ false);
485 }
486}
487
488bool GrClipStack::RawElement::contains(const RawElement& e) const {
489 // This is similar to how RawElement checks containment for a Draw, except that both the tester
490 // and testee have a transform that needs to be considered.
491 if (fInnerBounds.contains(e.fOuterBounds)) {
492 return true;
493 }
494
495 bool mixedAA = fAA != e.fAA;
496 if (!mixedAA && fLocalToDevice == e.fLocalToDevice) {
497 // Test the shapes directly against each other, with a special check for a rrect+rrect
498 // containment (a intersect b == a implies b contains a) and paths (same gen ID, or same
499 // path for small paths means they contain each other).
500 static constexpr int kMaxPathComparePoints = 16;
501 if (fShape.isRRect() && e.fShape.isRRect()) {
502 return SkRRectPriv::ConservativeIntersect(fShape.rrect(), e.fShape.rrect())
503 == e.fShape.rrect();
504 } else if (fShape.isPath() && e.fShape.isPath()) {
505 return fShape.path().getGenerationID() == e.fShape.path().getGenerationID() ||
506 (fShape.path().getPoints(nullptr, 0) <= kMaxPathComparePoints &&
507 fShape.path() == e.fShape.path());
508 } // else fall through to shape_contains_rect
509 }
510
511 return shape_contains_rect(fShape, fLocalToDevice, fDeviceToLocal,
512 e.fShape.bounds(), e.fLocalToDevice, mixedAA);
513
514}
515
516void GrClipStack::RawElement::simplify(const SkIRect& deviceBounds, bool forceAA) {
517 // Make sure the shape is not inverted. An inverted shape is equivalent to a non-inverted shape
518 // with the clip op toggled.
519 if (fShape.inverted()) {
520 fOp = fOp == SkClipOp::kIntersect ? SkClipOp::kDifference : SkClipOp::kIntersect;
521 fShape.setInverted(false);
522 }
523
524 // Then simplify the base shape, if it becomes empty, no need to update the bounds
525 fShape.simplify();
526 SkASSERT(!fShape.inverted());
527 if (fShape.isEmpty()) {
528 return;
529 }
530
531 // Lines and points should have been turned into empty since we assume everything is filled
532 SkASSERT(!fShape.isPoint() && !fShape.isLine());
533 // Validity check, we have no public API to create an arc at the moment
534 SkASSERT(!fShape.isArc());
535
536 SkRect outer = fLocalToDevice.mapRect(fShape.bounds());
537 if (!outer.intersect(SkRect::Make(deviceBounds))) {
538 // A non-empty shape is offscreen, so treat it as empty
539 fShape.reset();
540 return;
541 }
542
543 if (forceAA) {
544 fAA = GrAA::kYes;
545 }
546
547 // Except for non-AA axis-aligned rects, the outer bounds is the rounded-out device-space
548 // mapped bounds of the shape.
549 fOuterBounds = GrClip::GetPixelIBounds(outer, fAA, BoundsType::kExterior);
550
551 if (fLocalToDevice.isScaleTranslate()) {
552 if (fShape.isRect()) {
553 // The actual geometry can be updated to the device-intersected bounds and we can
554 // know the inner bounds
555 fShape.rect() = outer;
556 fLocalToDevice.setIdentity();
557 fDeviceToLocal.setIdentity();
558
559 if (fAA == GrAA::kNo && outer.width() >= 1.f && outer.height() >= 1.f) {
560 // NOTE: Legacy behavior to avoid performance regressions. For non-aa axis-aligned
561 // clip rects we always just round so that they can be scissor-only (avoiding the
562 // uncertainty in how a GPU might actually round an edge on fractional coords).
563 fOuterBounds = outer.round();
564 fInnerBounds = fOuterBounds;
565 } else {
566 fInnerBounds = GrClip::GetPixelIBounds(outer, fAA, BoundsType::kInterior);
567 SkASSERT(fOuterBounds.contains(fInnerBounds) || fInnerBounds.isEmpty());
568 }
569 } else if (fShape.isRRect()) {
570 // Can't transform in place
571 SkRRect src = fShape.rrect();
572 SkAssertResult(src.transform(fLocalToDevice, &fShape.rrect()));
573 fLocalToDevice.setIdentity();
574 fDeviceToLocal.setIdentity();
575
576 SkRect inner = SkRRectPriv::InnerBounds(fShape.rrect());
577 fInnerBounds = GrClip::GetPixelIBounds(inner, fAA, BoundsType::kInterior);
578 if (!fInnerBounds.intersect(deviceBounds)) {
579 fInnerBounds = SkIRect::MakeEmpty();
580 }
581 }
582 }
583
584 if (fOuterBounds.isEmpty()) {
585 // This can happen if we have non-AA shapes smaller than a pixel that do not cover a pixel
586 // center. We could round out, but rasterization would still result in an empty clip.
587 fShape.reset();
588 }
589
590 // Post-conditions on inner and outer bounds
591 SkASSERT(fShape.isEmpty() || (!fOuterBounds.isEmpty() && deviceBounds.contains(fOuterBounds)));
592 SkASSERT(fShape.isEmpty() || fInnerBounds.isEmpty() || fOuterBounds.contains(fInnerBounds));
593}
594
595bool GrClipStack::RawElement::combine(const RawElement& other, const SaveRecord& current) {
596 // To reduce the number of possibilities, only consider intersect+intersect. Difference and
597 // mixed op cases could be analyzed to simplify one of the shapes, but that is a rare
598 // occurrence and the math is much more complicated.
599 if (other.fOp != SkClipOp::kIntersect || fOp != SkClipOp::kIntersect) {
600 return false;
601 }
602
603 // At the moment, only rect+rect or rrect+rrect are supported (although rect+rrect is
604 // treated as a degenerate case of rrect+rrect).
605 bool shapeUpdated = false;
606 if (fShape.isRect() && other.fShape.isRect()) {
607 bool aaMatch = fAA == other.fAA;
608 if (fLocalToDevice.isIdentity() && other.fLocalToDevice.isIdentity() && !aaMatch) {
609 if (GrClip::IsPixelAligned(fShape.rect())) {
610 // Our AA type doesn't really matter, take other's since its edges may not be
611 // pixel aligned, so after intersection clip behavior should respect its aa type.
612 fAA = other.fAA;
613 } else if (!GrClip::IsPixelAligned(other.fShape.rect())) {
614 // Neither shape is pixel aligned and AA types don't match so can't combine
615 return false;
616 }
617 // Either we've updated this->fAA to actually match, or other->fAA doesn't matter so
618 // this can be set to true. We just can't modify other to set it's aa to this->fAA.
619 // But since 'this' becomes the combo of the two, other will be deleted so that's fine.
620 aaMatch = true;
621 }
622
623 if (aaMatch && fLocalToDevice == other.fLocalToDevice) {
624 if (!fShape.rect().intersect(other.fShape.rect())) {
625 // By floating point, it turns out the combination should be empty
626 this->fShape.reset();
627 this->markInvalid(current);
628 return true;
629 }
630 shapeUpdated = true;
631 }
632 } else if ((fShape.isRect() || fShape.isRRect()) &&
633 (other.fShape.isRect() || other.fShape.isRRect())) {
634 // No such pixel-aligned disregard for AA for round rects
635 if (fAA == other.fAA && fLocalToDevice == other.fLocalToDevice) {
636 // Treat rrect+rect intersections as rrect+rrect
637 SkRRect a = fShape.isRect() ? SkRRect::MakeRect(fShape.rect()) : fShape.rrect();
638 SkRRect b = other.fShape.isRect() ? SkRRect::MakeRect(other.fShape.rect())
639 : other.fShape.rrect();
640
641 SkRRect joined = SkRRectPriv::ConservativeIntersect(a, b);
642 if (!joined.isEmpty()) {
643 // Can reduce to a single element
644 if (joined.isRect()) {
645 // And with a simplified type
646 fShape.setRect(joined.rect());
647 } else {
648 fShape.setRRect(joined);
649 }
650 shapeUpdated = true;
651 } else if (!a.getBounds().intersects(b.getBounds())) {
652 // Like the rect+rect combination, the intersection is actually empty
653 fShape.reset();
654 this->markInvalid(current);
655 return true;
656 }
657 }
658 }
659
660 if (shapeUpdated) {
661 // This logic works under the assumption that both combined elements were intersect, so we
662 // don't do the full bounds computations like in simplify().
663 SkASSERT(fOp == SkClipOp::kIntersect && other.fOp == SkClipOp::kIntersect);
664 SkAssertResult(fOuterBounds.intersect(other.fOuterBounds));
665 if (!fInnerBounds.intersect(other.fInnerBounds)) {
666 fInnerBounds = SkIRect::MakeEmpty();
667 }
668 return true;
669 } else {
670 return false;
671 }
672}
673
674void GrClipStack::RawElement::updateForElement(RawElement* added, const SaveRecord& current) {
675 if (this->isInvalid()) {
676 // Already doesn't do anything, so skip this element
677 return;
678 }
679
680 // 'A' refers to this element, 'B' refers to 'added'.
681 switch (get_clip_geometry(*this, *added)) {
682 case ClipGeometry::kEmpty:
683 // Mark both elements as invalid to signal that the clip is fully empty
684 this->markInvalid(current);
685 added->markInvalid(current);
686 break;
687
688 case ClipGeometry::kAOnly:
689 // This element already clips more than 'added', so mark 'added' is invalid to skip it
690 added->markInvalid(current);
691 break;
692
693 case ClipGeometry::kBOnly:
694 // 'added' clips more than this element, so mark this as invalid
695 this->markInvalid(current);
696 break;
697
698 case ClipGeometry::kBoth:
699 // Else the bounds checks think we need to keep both, but depending on the combination
700 // of the ops and shape kinds, we may be able to do better.
701 if (added->combine(*this, current)) {
702 // 'added' now fully represents the combination of the two elements
703 this->markInvalid(current);
704 }
705 break;
706 }
707}
708
709GrClipStack::ClipState GrClipStack::RawElement::clipType() const {
710 // Map from the internal shape kind to the clip state enum
711 switch (fShape.type()) {
712 case GrShape::Type::kEmpty:
713 return ClipState::kEmpty;
714
715 case GrShape::Type::kRect:
716 return fOp == SkClipOp::kIntersect && fLocalToDevice.isIdentity()
717 ? ClipState::kDeviceRect : ClipState::kComplex;
718
719 case GrShape::Type::kRRect:
720 return fOp == SkClipOp::kIntersect && fLocalToDevice.isIdentity()
721 ? ClipState::kDeviceRRect : ClipState::kComplex;
722
723 case GrShape::Type::kArc:
724 case GrShape::Type::kLine:
725 case GrShape::Type::kPoint:
726 // These types should never become RawElements
727 SkASSERT(false);
728 [[fallthrough]];
729
730 case GrShape::Type::kPath:
731 return ClipState::kComplex;
732 }
733 SkUNREACHABLE;
734}
735
736///////////////////////////////////////////////////////////////////////////////
737// GrClipStack::Mask
738
739GrClipStack::Mask::Mask(const SaveRecord& current, const SkIRect& drawBounds)
740 : fBounds(drawBounds)
741 , fGenID(current.genID()) {
742 static const GrUniqueKey::Domain kDomain = GrUniqueKey::GenerateDomain();
743
744 // The gen ID should not be invalid, empty, or wide open, since those do not require masks
745 SkASSERT(fGenID != kInvalidGenID && fGenID != kEmptyGenID && fGenID != kWideOpenGenID);
746
747 GrUniqueKey::Builder builder(&fKey, kDomain, 3, "clip_mask");
748 builder[0] = fGenID;
749 // SkToS16 because image filters outset layers to a size indicated by the filter, which can
750 // sometimes result in negative coordinates from device space.
751 builder[1] = SkToS16(drawBounds.fLeft) | (SkToS16(drawBounds.fRight) << 16);
752 builder[2] = SkToS16(drawBounds.fTop) | (SkToS16(drawBounds.fBottom) << 16);
753 SkASSERT(fKey.isValid());
754
755 SkDEBUGCODE(fOwner = &current;)
756}
757
758bool GrClipStack::Mask::appliesToDraw(const SaveRecord& current, const SkIRect& drawBounds) const {
759 // For the same save record, a larger mask will have the same or more elements
760 // baked into it, so it can be reused to clip the smaller draw.
761 SkASSERT(fGenID != current.genID() || &current == fOwner);
762 return fGenID == current.genID() && fBounds.contains(drawBounds);
763}
764
765void GrClipStack::Mask::invalidate(GrProxyProvider* proxyProvider) {
766 SkASSERT(proxyProvider);
767 SkASSERT(fKey.isValid()); // Should only be invalidated once
768 proxyProvider->processInvalidUniqueKey(
769 fKey, nullptr, GrProxyProvider::InvalidateGPUResource::kYes);
770 fKey.reset();
771}
772
773///////////////////////////////////////////////////////////////////////////////
774// GrClipStack::SaveRecord
775
776GrClipStack::SaveRecord::SaveRecord(const SkIRect& deviceBounds)
777 : fInnerBounds(deviceBounds)
778 , fOuterBounds(deviceBounds)
779 , fShader(nullptr)
780 , fStartingMaskIndex(0)
781 , fStartingElementIndex(0)
782 , fOldestValidIndex(0)
783 , fDeferredSaveCount(0)
784 , fStackOp(SkClipOp::kIntersect)
785 , fState(ClipState::kWideOpen)
786 , fGenID(kInvalidGenID) {}
787
788GrClipStack::SaveRecord::SaveRecord(const SaveRecord& prior,
789 int startingMaskIndex,
790 int startingElementIndex)
791 : fInnerBounds(prior.fInnerBounds)
792 , fOuterBounds(prior.fOuterBounds)
793 , fShader(prior.fShader)
794 , fStartingMaskIndex(startingMaskIndex)
795 , fStartingElementIndex(startingElementIndex)
796 , fOldestValidIndex(prior.fOldestValidIndex)
797 , fDeferredSaveCount(0)
798 , fStackOp(prior.fStackOp)
799 , fState(prior.fState)
800 , fGenID(kInvalidGenID) {
801 // If the prior record never needed a mask, this one will insert into the same index
802 // (that's okay since we'll remove it when this record is popped off the stack).
803 SkASSERT(startingMaskIndex >= prior.fStartingMaskIndex);
804 // The same goes for elements (the prior could have been wide open).
805 SkASSERT(startingElementIndex >= prior.fStartingElementIndex);
806}
807
808uint32_t GrClipStack::SaveRecord::genID() const {
809 if (fState == ClipState::kEmpty) {
810 return kEmptyGenID;
811 } else if (fState == ClipState::kWideOpen) {
812 return kWideOpenGenID;
813 } else {
814 // The gen ID shouldn't be empty or wide open, since they are reserved for the above
815 // if-cases. It may be kInvalid if the record hasn't had any elements added to it yet.
816 SkASSERT(fGenID != kEmptyGenID && fGenID != kWideOpenGenID);
817 return fGenID;
818 }
819}
820
821GrClipStack::ClipState GrClipStack::SaveRecord::state() const {
822 if (fShader && fState != ClipState::kEmpty) {
823 return ClipState::kComplex;
824 } else {
825 return fState;
826 }
827}
828
829bool GrClipStack::SaveRecord::contains(const GrClipStack::Draw& draw) const {
830 return fInnerBounds.contains(draw.outerBounds());
831}
832
833bool GrClipStack::SaveRecord::contains(const GrClipStack::RawElement& element) const {
834 return fInnerBounds.contains(element.outerBounds());
835}
836
837void GrClipStack::SaveRecord::removeElements(RawElement::Stack* elements) {
838 while (elements->count() > fStartingElementIndex) {
839 elements->pop_back();
840 }
841}
842
843void GrClipStack::SaveRecord::restoreElements(RawElement::Stack* elements) {
844 // Presumably this SaveRecord is the new top of the stack, and so it owns the elements
845 // from its starting index to restoreCount - 1. Elements from the old save record have
846 // been destroyed already, so their indices would have been >= restoreCount, and any
847 // still-present element can be un-invalidated based on that.
848 int i = elements->count() - 1;
849 for (RawElement& e : elements->ritems()) {
850 if (i < fOldestValidIndex) {
851 break;
852 }
853 e.restoreValid(*this);
854 --i;
855 }
856}
857
858void GrClipStack::SaveRecord::invalidateMasks(GrProxyProvider* proxyProvider,
859 Mask::Stack* masks) {
860 // Must explicitly invalidate the key before removing the mask object from the stack
861 while (masks->count() > fStartingMaskIndex) {
862 SkASSERT(masks->back().owner() == this && proxyProvider);
863 masks->back().invalidate(proxyProvider);
864 masks->pop_back();
865 }
866 SkASSERT(masks->empty() || masks->back().genID() != fGenID);
867}
868
869void GrClipStack::SaveRecord::reset(const SkIRect& bounds) {
870 SkASSERT(this->canBeUpdated());
871 fOldestValidIndex = fStartingElementIndex;
872 fOuterBounds = bounds;
873 fInnerBounds = bounds;
874 fStackOp = SkClipOp::kIntersect;
875 fState = ClipState::kWideOpen;
876 fShader = nullptr;
877}
878
879void GrClipStack::SaveRecord::addShader(sk_sp<SkShader> shader) {
880 SkASSERT(shader);
881 SkASSERT(this->canBeUpdated());
882 if (!fShader) {
883 fShader = std::move(shader);
884 } else {
885 // The total coverage is computed by multiplying the coverage from each element (shape or
886 // shader), but since multiplication is associative, we can use kSrcIn blending to make
887 // a new shader that represents 'shader' * 'fShader'
888 fShader = SkShaders::Blend(SkBlendMode::kSrcIn, std::move(shader), fShader);
889 }
890}
891
892bool GrClipStack::SaveRecord::addElement(RawElement&& toAdd, RawElement::Stack* elements) {
893 // Validity check the element's state first; if the shape class isn't empty, the outer bounds
894 // shouldn't be empty; if the inner bounds are not empty, they must be contained in outer.
895 SkASSERT((toAdd.shape().isEmpty() || !toAdd.outerBounds().isEmpty()) &&
896 (toAdd.innerBounds().isEmpty() || toAdd.outerBounds().contains(toAdd.innerBounds())));
897 // And we shouldn't be adding an element if we have a deferred save
898 SkASSERT(this->canBeUpdated());
899
900 if (fState == ClipState::kEmpty) {
901 // The clip is already empty, and we only shrink, so there's no need to record this element.
902 return false;
903 } else if (toAdd.shape().isEmpty()) {
904 // An empty difference op should have been detected earlier, since it's a no-op
905 SkASSERT(toAdd.op() == SkClipOp::kIntersect);
906 fState = ClipState::kEmpty;
907 return true;
908 }
909
910 // In this invocation, 'A' refers to the existing stack's bounds and 'B' refers to the new
911 // element.
912 switch (get_clip_geometry(*this, toAdd)) {
913 case ClipGeometry::kEmpty:
914 // The combination results in an empty clip
915 fState = ClipState::kEmpty;
916 return true;
917
918 case ClipGeometry::kAOnly:
919 // The combination would not be any different than the existing clip
920 return false;
921
922 case ClipGeometry::kBOnly:
923 // The combination would invalidate the entire existing stack and can be replaced with
924 // just the new element.
925 this->replaceWithElement(std::move(toAdd), elements);
926 return true;
927
928 case ClipGeometry::kBoth:
929 // The new element combines in a complex manner, so update the stack's bounds based on
930 // the combination of its and the new element's ops (handled below)
931 break;
932 }
933
934 if (fState == ClipState::kWideOpen) {
935 // When the stack was wide open and the clip effect was kBoth, the "complex" manner is
936 // simply to keep the element and update the stack bounds to be the element's intersected
937 // with the device.
938 this->replaceWithElement(std::move(toAdd), elements);
939 return true;
940 }
941
942 // Some form of actual clip element(s) to combine with.
943 if (fStackOp == SkClipOp::kIntersect) {
944 if (toAdd.op() == SkClipOp::kIntersect) {
945 // Intersect (stack) + Intersect (toAdd)
946 // - Bounds updates is simply the paired intersections of outer and inner.
947 SkAssertResult(fOuterBounds.intersect(toAdd.outerBounds()));
948 if (!fInnerBounds.intersect(toAdd.innerBounds())) {
949 // NOTE: this does the right thing if either rect is empty, since we set the
950 // inner bounds to empty here
951 fInnerBounds = SkIRect::MakeEmpty();
952 }
953 } else {
954 // Intersect (stack) + Difference (toAdd)
955 // - Shrink the stack's outer bounds if the difference op's inner bounds completely
956 // cuts off an edge.
957 // - Shrink the stack's inner bounds to completely exclude the op's outer bounds.
958 fOuterBounds = subtract(fOuterBounds, toAdd.innerBounds(), /* exact */ true);
959 fInnerBounds = subtract(fInnerBounds, toAdd.outerBounds(), /* exact */ false);
960 }
961 } else {
962 if (toAdd.op() == SkClipOp::kIntersect) {
963 // Difference (stack) + Intersect (toAdd)
964 // - Bounds updates are just the mirror of Intersect(stack) + Difference(toAdd)
965 SkIRect oldOuter = fOuterBounds;
966 fOuterBounds = subtract(toAdd.outerBounds(), fInnerBounds, /* exact */ true);
967 fInnerBounds = subtract(toAdd.innerBounds(), oldOuter, /* exact */ false);
968 } else {
969 // Difference (stack) + Difference (toAdd)
970 // - The updated outer bounds is the union of outer bounds and the inner becomes the
971 // largest of the two possible inner bounds
972 fOuterBounds.join(toAdd.outerBounds());
973 if (toAdd.innerBounds().width() * toAdd.innerBounds().height() >
974 fInnerBounds.width() * fInnerBounds.height()) {
975 fInnerBounds = toAdd.innerBounds();
976 }
977 }
978 }
979
980 // If we get here, we're keeping the new element and the stack's bounds have been updated.
981 // We ought to have caught the cases where the stack bounds resemble an empty or wide open
982 // clip, so assert that's the case.
983 SkASSERT(!fOuterBounds.isEmpty() &&
984 (fInnerBounds.isEmpty() || fOuterBounds.contains(fInnerBounds)));
985
986 return this->appendElement(std::move(toAdd), elements);
987}
988
989bool GrClipStack::SaveRecord::appendElement(RawElement&& toAdd, RawElement::Stack* elements) {
990 // Update past elements to account for the new element
991 int i = elements->count() - 1;
992
993 // After the loop, elements between [max(youngestValid, startingIndex)+1, count-1] can be
994 // removed from the stack (these are the active elements that have been invalidated by the
995 // newest element; since it's the active part of the stack, no restore() can bring them back).
996 int youngestValid = fStartingElementIndex - 1;
997 // After the loop, elements between [0, oldestValid-1] are all invalid. The value of oldestValid
998 // becomes the save record's new fLastValidIndex value.
999 int oldestValid = elements->count();
1000 // After the loop, this is the earliest active element that was invalidated. It may be
1001 // older in the stack than earliestValid, so cannot be popped off, but can be used to store
1002 // the new element instead of allocating more.
1003 RawElement* oldestActiveInvalid = nullptr;
1004 int oldestActiveInvalidIndex = elements->count();
1005
1006 for (RawElement& existing : elements->ritems()) {
1007 if (i < fOldestValidIndex) {
1008 break;
1009 }
1010 // We don't need to pass the actual index that toAdd will be saved to; just the minimum
1011 // index of this save record, since that will result in the same restoration behavior later.
1012 existing.updateForElement(&toAdd, *this);
1013
1014 if (toAdd.isInvalid()) {
1015 if (existing.isInvalid()) {
1016 // Both new and old invalid implies the entire clip becomes empty
1017 fState = ClipState::kEmpty;
1018 return true;
1019 } else {
1020 // The new element doesn't change the clip beyond what the old element already does
1021 return false;
1022 }
1023 } else if (existing.isInvalid()) {
1024 // The new element cancels out the old element. The new element may have been modified
1025 // to account for the old element's geometry.
1026 if (i >= fStartingElementIndex) {
1027 // Still active, so the invalidated index could be used to store the new element
1028 oldestActiveInvalid = &existing;
1029 oldestActiveInvalidIndex = i;
1030 }
1031 } else {
1032 // Keep both new and old elements
1033 oldestValid = i;
1034 if (i > youngestValid) {
1035 youngestValid = i;
1036 }
1037 }
1038
1039 --i;
1040 }
1041
1042 // Post-iteration validity check
1043 SkASSERT(oldestValid == elements->count() ||
1044 (oldestValid >= fOldestValidIndex && oldestValid < elements->count()));
1045 SkASSERT(youngestValid == fStartingElementIndex - 1 ||
1046 (youngestValid >= fStartingElementIndex && youngestValid < elements->count()));
1047 SkASSERT((oldestActiveInvalid && oldestActiveInvalidIndex >= fStartingElementIndex &&
1048 oldestActiveInvalidIndex < elements->count()) || !oldestActiveInvalid);
1049
1050 // Update final state
1051 SkASSERT(oldestValid >= fOldestValidIndex);
1052 fOldestValidIndex = std::min(oldestValid, oldestActiveInvalidIndex);
1053 fState = oldestValid == elements->count() ? toAdd.clipType() : ClipState::kComplex;
1054 if (fStackOp == SkClipOp::kDifference && toAdd.op() == SkClipOp::kIntersect) {
1055 // The stack remains in difference mode only as long as all elements are difference
1056 fStackOp = SkClipOp::kIntersect;
1057 }
1058
1059 int targetCount = youngestValid + 1;
1060 if (!oldestActiveInvalid || oldestActiveInvalidIndex >= targetCount) {
1061 // toAdd will be stored right after youngestValid
1062 targetCount++;
1063 oldestActiveInvalid = nullptr;
1064 }
1065 while (elements->count() > targetCount) {
1066 SkASSERT(oldestActiveInvalid != &elements->back()); // shouldn't delete what we'll reuse
1067 elements->pop_back();
1068 }
1069 if (oldestActiveInvalid) {
1070 *oldestActiveInvalid = std::move(toAdd);
1071 } else if (elements->count() < targetCount) {
1072 elements->push_back(std::move(toAdd));
1073 } else {
1074 elements->back() = std::move(toAdd);
1075 }
1076
1077 // Changing this will prompt GrClipStack to invalidate any masks associated with this record.
1078 fGenID = next_gen_id();
1079 return true;
1080}
1081
1082void GrClipStack::SaveRecord::replaceWithElement(RawElement&& toAdd, RawElement::Stack* elements) {
1083 // The aggregate state of the save record mirrors the element
1084 fInnerBounds = toAdd.innerBounds();
1085 fOuterBounds = toAdd.outerBounds();
1086 fStackOp = toAdd.op();
1087 fState = toAdd.clipType();
1088
1089 // All prior active element can be removed from the stack: [startingIndex, count - 1]
1090 int targetCount = fStartingElementIndex + 1;
1091 while (elements->count() > targetCount) {
1092 elements->pop_back();
1093 }
1094 if (elements->count() < targetCount) {
1095 elements->push_back(std::move(toAdd));
1096 } else {
1097 elements->back() = std::move(toAdd);
1098 }
1099
1100 SkASSERT(elements->count() == fStartingElementIndex + 1);
1101
1102 // This invalidates all older elements that are owned by save records lower in the clip stack.
1103 fOldestValidIndex = fStartingElementIndex;
1104 fGenID = next_gen_id();
1105}
1106
1107///////////////////////////////////////////////////////////////////////////////
1108// GrClipStack
1109
1110// NOTE: Based on draw calls in all GMs, SKPs, and SVGs as of 08/20, 98% use a clip stack with
1111// one Element and up to two SaveRecords, thus the inline size for RawElement::Stack and
1112// SaveRecord::Stack (this conveniently keeps the size of GrClipStack manageable). The max
1113// encountered element stack depth was 5 and the max save depth was 6. Using an increment of 8 for
1114// these stacks means that clip management will incur a single allocation for the remaining 2%
1115// of the draws, with extra head room for more complex clips encountered in the wild.
1116//
1117// The mask stack increment size was chosen to be smaller since only 0.2% of the evaluated draw call
1118// set ever used a mask (which includes stencil masks), or up to 0.3% when CCPR is disabled.
1119static constexpr int kElementStackIncrement = 8;
1120static constexpr int kSaveStackIncrement = 8;
1121static constexpr int kMaskStackIncrement = 4;
1122
1123// And from this same draw call set, the most complex clip could only use 5 analytic coverage FPs.
1124// Historically we limited it to 4 based on Blink's call pattern, so we keep the limit as-is since
1125// it's so close to the empirically encountered max.
1126static constexpr int kMaxAnalyticFPs = 4;
1127// The number of stack-allocated mask pointers to store before extending the arrays.
1128// Stack size determined empirically, the maximum number of elements put in a SW mask was 4
1129// across our set of GMs, SKPs, and SVGs used for testing.
1130static constexpr int kNumStackMasks = 4;
1131
1132GrClipStack::GrClipStack(const SkIRect& deviceBounds, const SkMatrixProvider* matrixProvider,
1133 bool forceAA)
1134 : fElements(kElementStackIncrement)
1135 , fSaves(kSaveStackIncrement)
1136 , fMasks(kMaskStackIncrement)
1137 , fProxyProvider(nullptr)
1138 , fDeviceBounds(deviceBounds)
1139 , fMatrixProvider(matrixProvider)
1140 , fForceAA(forceAA) {
1141 // Start with a save record that is wide open
1142 fSaves.emplace_back(deviceBounds);
1143}
1144
1145GrClipStack::~GrClipStack() {
1146 // Invalidate all mask keys that remain. Since we're tearing the clip stack down, we don't need
1147 // to go through SaveRecord.
1148 SkASSERT(fProxyProvider || fMasks.empty());
1149 if (fProxyProvider) {
1150 for (Mask& m : fMasks.ritems()) {
1151 m.invalidate(fProxyProvider);
1152 }
1153 }
1154}
1155
1156void GrClipStack::save() {
1157 SkASSERT(!fSaves.empty());
1158 fSaves.back().pushSave();
1159}
1160
1161void GrClipStack::restore() {
1162 SkASSERT(!fSaves.empty());
1163 SaveRecord& current = fSaves.back();
1164 if (current.popSave()) {
1165 // This was just a deferred save being undone, so the record doesn't need to be removed yet
1166 return;
1167 }
1168
1169 // When we remove a save record, we delete all elements >= its starting index and any masks
1170 // that were rasterized for it.
1171 current.removeElements(&fElements);
1172 SkASSERT(fProxyProvider || fMasks.empty());
1173 if (fProxyProvider) {
1174 current.invalidateMasks(fProxyProvider, &fMasks);
1175 }
1176 fSaves.pop_back();
1177 // Restore any remaining elements that were only invalidated by the now-removed save record.
1178 fSaves.back().restoreElements(&fElements);
1179}
1180
1181SkIRect GrClipStack::getConservativeBounds() const {
1182 const SaveRecord& current = this->currentSaveRecord();
1183 if (current.state() == ClipState::kEmpty) {
1184 return SkIRect::MakeEmpty();
1185 } else if (current.state() == ClipState::kWideOpen) {
1186 return fDeviceBounds;
1187 } else {
1188 if (current.op() == SkClipOp::kDifference) {
1189 // The outer/inner bounds represent what's cut out, so full bounds remains the device
1190 // bounds, minus any fully clipped content that spans the device edge.
1191 return subtract(fDeviceBounds, current.innerBounds(), /* exact */ true);
1192 } else {
1193 SkASSERT(fDeviceBounds.contains(current.outerBounds()));
1194 return current.outerBounds();
1195 }
1196 }
1197}
1198
1199GrClip::PreClipResult GrClipStack::preApply(const SkRect& bounds, GrAA aa) const {
1200 Draw draw(bounds, fForceAA ? GrAA::kYes : aa);
1201 if (!draw.applyDeviceBounds(fDeviceBounds)) {
1202 return GrClip::Effect::kClippedOut;
1203 }
1204
1205 const SaveRecord& cs = this->currentSaveRecord();
1206 // Early out if we know a priori that the clip is full 0s or full 1s.
1207 if (cs.state() == ClipState::kEmpty) {
1208 return GrClip::Effect::kClippedOut;
1209 } else if (cs.state() == ClipState::kWideOpen) {
1210 SkASSERT(!cs.shader());
1211 return GrClip::Effect::kUnclipped;
1212 }
1213
1214 // Given argument order, 'A' == current clip, 'B' == draw
1215 switch (get_clip_geometry(cs, draw)) {
1216 case ClipGeometry::kEmpty:
1217 // Can ignore the shader since the geometry removed everything already
1218 return GrClip::Effect::kClippedOut;
1219
1220 case ClipGeometry::kBOnly:
1221 // Geometrically, the draw is unclipped, but can't ignore a shader
1222 return cs.shader() ? GrClip::Effect::kClipped : GrClip::Effect::kUnclipped;
1223
1224 case ClipGeometry::kAOnly:
1225 // Shouldn't happen since the inner bounds of a draw are unknown
1226 SkASSERT(false);
1227 // But if it did, it technically means the draw covered the clip and should be
1228 // considered kClipped or similar, which is what the next case handles.
1229 [[fallthrough]];
1230
1231 case ClipGeometry::kBoth: {
1232 SkASSERT(fElements.count() > 0);
1233 const RawElement& back = fElements.back();
1234 if (cs.state() == ClipState::kDeviceRect) {
1235 SkASSERT(back.clipType() == ClipState::kDeviceRect);
1236 return {back.shape().rect(), back.aa()};
1237 } else if (cs.state() == ClipState::kDeviceRRect) {
1238 SkASSERT(back.clipType() == ClipState::kDeviceRRect);
1239 return {back.shape().rrect(), back.aa()};
1240 } else {
1241 // The clip stack has complex shapes, multiple elements, or a shader; we could
1242 // iterate per element like we would in apply(), but preApply() is meant to be
1243 // conservative and efficient.
1244 SkASSERT(cs.state() == ClipState::kComplex);
1245 return GrClip::Effect::kClipped;
1246 }
1247 }
1248 }
1249
1250 SkUNREACHABLE;
1251}
1252
1253GrClip::Effect GrClipStack::apply(GrRecordingContext* context, GrRenderTargetContext* rtc,
1254 GrAAType aa, bool hasUserStencilSettings,
1255 GrAppliedClip* out, SkRect* bounds) const {
1256 // TODO: Once we no longer store SW masks, we don't need to sneak the provider in like this
1257 if (!fProxyProvider) {
1258 fProxyProvider = context->priv().proxyProvider();
1259 }
1260 SkASSERT(fProxyProvider == context->priv().proxyProvider());
1261 const GrCaps* caps = context->priv().caps();
1262
1263 // Convert the bounds to a Draw and apply device bounds clipping, making our query as tight
1264 // as possible.
1265 Draw draw(*bounds, GrAA(fForceAA || aa != GrAAType::kNone));
1266 if (!draw.applyDeviceBounds(fDeviceBounds)) {
1267 return Effect::kClippedOut;
1268 }
1269 SkAssertResult(bounds->intersect(SkRect::Make(fDeviceBounds)));
1270
1271 const SaveRecord& cs = this->currentSaveRecord();
1272 // Early out if we know a priori that the clip is full 0s or full 1s.
1273 if (cs.state() == ClipState::kEmpty) {
1274 return Effect::kClippedOut;
1275 } else if (cs.state() == ClipState::kWideOpen) {
1276 SkASSERT(!cs.shader());
1277 return Effect::kUnclipped;
1278 }
1279
1280 // Convert any clip shader first, since it's not geometrically related to the draw bounds
1281 std::unique_ptr<GrFragmentProcessor> clipFP = nullptr;
1282 if (cs.shader()) {
1283 static const GrColorInfo kCoverageColorInfo{GrColorType::kUnknown, kPremul_SkAlphaType,
1284 nullptr};
1285 GrFPArgs args(context, *fMatrixProvider, kNone_SkFilterQuality, &kCoverageColorInfo);
1286 clipFP = as_SB(cs.shader())->asFragmentProcessor(args);
1287 if (clipFP) {
1288 clipFP = GrFragmentProcessor::SwizzleOutput(std::move(clipFP), GrSwizzle::AAAA());
1289 }
1290 }
1291
1292 // A refers to the entire clip stack, B refers to the draw
1293 switch (get_clip_geometry(cs, draw)) {
1294 case ClipGeometry::kEmpty:
1295 return Effect::kClippedOut;
1296
1297 case ClipGeometry::kBOnly:
1298 // Geometrically unclipped, but may need to add the shader as a coverage FP
1299 if (clipFP) {
1300 out->addCoverageFP(std::move(clipFP));
1301 return Effect::kClipped;
1302 } else {
1303 return Effect::kUnclipped;
1304 }
1305
1306 case ClipGeometry::kAOnly:
1307 // Shouldn't happen since draws don't report inner bounds
1308 SkASSERT(false);
1309 [[fallthrough]];
1310
1311 case ClipGeometry::kBoth:
1312 // The draw is combined with the saved clip elements; the below logic tries to skip
1313 // as many elements as possible.
1314 SkASSERT(cs.state() == ClipState::kDeviceRect ||
1315 cs.state() == ClipState::kDeviceRRect ||
1316 cs.state() == ClipState::kComplex);
1317 break;
1318 }
1319
1320 // We can determine a scissor based on the draw and the overall stack bounds.
1321 SkIRect scissorBounds;
1322 if (cs.op() == SkClipOp::kIntersect) {
1323 // Initially we keep this as large as possible; if the clip is applied solely with coverage
1324 // FPs then using a loose scissor increases the chance we can batch the draws.
1325 // We tighten it later if any form of mask or atlas element is needed.
1326 scissorBounds = cs.outerBounds();
1327 } else {
1328 scissorBounds = subtract(draw.outerBounds(), cs.innerBounds(), /* exact */ true);
1329 }
1330
1331 // We mark this true once we have a coverage FP (since complex clipping is occurring), or we
1332 // have an element that wouldn't affect the scissored draw bounds, but does affect the regular
1333 // draw bounds. In that case, the scissor is sufficient for clipping and we can skip the
1334 // element but definitely cannot then drop the scissor.
1335 bool scissorIsNeeded = SkToBool(cs.shader());
1336
1337 int remainingAnalyticFPs = kMaxAnalyticFPs;
Michael Ludwigb28e1412020-09-18 15:07:49 -04001338 if (hasUserStencilSettings) {
1339 // Disable analytic clips when there are user stencil settings to ensure the clip is
1340 // respected in the stencil buffer.
Michael Ludwiga195d102020-09-15 14:51:52 -04001341 remainingAnalyticFPs = 0;
Michael Ludwigb28e1412020-09-18 15:07:49 -04001342 // If we have user stencil settings, we shouldn't be avoiding the stencil buffer anyways.
Michael Ludwiga195d102020-09-15 14:51:52 -04001343 SkASSERT(!context->priv().caps()->avoidStencilBuffers());
1344 }
1345
1346 // If window rectangles are supported, we can use them to exclude inner bounds of difference ops
1347 int maxWindowRectangles = rtc->priv().maxWindowRectangles();
1348 GrWindowRectangles windowRects;
1349
1350 // Elements not represented as an analytic FP or skipped will be collected here and later
1351 // applied by using the stencil buffer, CCPR clip atlas, or a cached SW mask.
1352 SkSTArray<kNumStackMasks, const Element*> elementsForMask;
1353 SkSTArray<kNumStackMasks, const RawElement*> elementsForAtlas;
1354
1355 bool maskRequiresAA = false;
1356 auto* ccpr = context->priv().drawingManager()->getCoverageCountingPathRenderer();
1357
1358 int i = fElements.count();
1359 for (const RawElement& e : fElements.ritems()) {
1360 --i;
1361 if (i < cs.oldestElementIndex()) {
1362 // All earlier elements have been invalidated by elements already processed
1363 break;
1364 } else if (e.isInvalid()) {
1365 continue;
1366 }
1367
1368 switch (get_clip_geometry(e, draw)) {
1369 case ClipGeometry::kEmpty:
1370 // This can happen for difference op elements that have a larger fInnerBounds than
1371 // can be preserved at the next level.
1372 return Effect::kClippedOut;
1373
1374 case ClipGeometry::kBOnly:
1375 // We don't need to produce a coverage FP or mask for the element
1376 break;
1377
1378 case ClipGeometry::kAOnly:
1379 // Shouldn't happen for draws, fall through to regular element processing
1380 SkASSERT(false);
1381 [[fallthrough]];
1382
1383 case ClipGeometry::kBoth: {
1384 // The element must apply coverage to the draw, enable the scissor to limit overdraw
1385 scissorIsNeeded = true;
1386
1387 // First apply using HW methods (scissor and window rects). When the inner and outer
1388 // bounds match, nothing else needs to be done.
1389 bool fullyApplied = false;
1390 if (e.op() == SkClipOp::kIntersect) {
1391 // The second test allows clipped draws that are scissored by multiple elements
1392 // to remain scissor-only.
1393 fullyApplied = e.innerBounds() == e.outerBounds() ||
1394 e.innerBounds().contains(scissorBounds);
1395 } else {
1396 if (!e.innerBounds().isEmpty() &&
1397 out->windowRectsState().numWindows() < maxWindowRectangles) {
1398 // TODO: If we have more difference ops than available window rects, we
1399 // should prioritize those with the largest inner bounds.
1400 windowRects.addWindow(e.innerBounds());
1401 fullyApplied = e.innerBounds() == e.outerBounds();
1402 }
1403 }
1404
1405 if (!fullyApplied && remainingAnalyticFPs > 0) {
1406 std::tie(fullyApplied, clipFP) = analytic_clip_fp(e.asElement(),
1407 *caps->shaderCaps(),
1408 std::move(clipFP));
1409 if (fullyApplied) {
1410 remainingAnalyticFPs--;
1411 } else if (ccpr && e.aa() == GrAA::kYes) {
1412 // While technically the element is turned into a mask, each atlas entry
1413 // counts towards the FP complexity of the clip.
1414 // TODO - CCPR needs a stable ops task ID so we can't create FPs until we
1415 // know any other mask generation is finished. It also only works with AA
1416 // shapes, future atlas systems can improve on this.
1417 elementsForAtlas.push_back(&e);
1418 remainingAnalyticFPs--;
1419 fullyApplied = true;
1420 }
1421 }
1422
1423 if (!fullyApplied) {
1424 elementsForMask.push_back(&e.asElement());
1425 maskRequiresAA |= (e.aa() == GrAA::kYes);
1426 }
1427
1428 break;
1429 }
1430 }
1431 }
1432
1433 if (!scissorIsNeeded) {
1434 // More detailed analysis of the element shapes determined no clip is needed
1435 SkASSERT(elementsForMask.empty() && elementsForAtlas.empty() && !clipFP);
1436 return Effect::kUnclipped;
1437 }
1438
1439 // Fill out the GrAppliedClip with what we know so far, possibly with a tightened scissor
1440 if (cs.op() == SkClipOp::kIntersect &&
1441 (!elementsForMask.empty() || !elementsForAtlas.empty())) {
1442 SkAssertResult(scissorBounds.intersect(draw.outerBounds()));
1443 }
1444 if (!GrClip::IsInsideClip(scissorBounds, *bounds)) {
1445 out->hardClip().addScissor(scissorBounds, bounds);
1446 }
1447 if (!windowRects.empty()) {
1448 out->hardClip().addWindowRectangles(windowRects, GrWindowRectsState::Mode::kExclusive);
1449 }
1450
1451 // Now rasterize any remaining elements, either to the stencil or a SW mask. All elements are
1452 // flattened into a single mask.
1453 if (!elementsForMask.empty()) {
1454 bool stencilUnavailable = context->priv().caps()->avoidStencilBuffers() ||
1455 rtc->wrapsVkSecondaryCB();
1456
1457 bool hasSWMask = false;
1458 if ((rtc->numSamples() <= 1 && maskRequiresAA) || stencilUnavailable) {
1459 // Must use a texture mask to represent the combined clip elements since the stencil
1460 // cannot be used, or cannot handle smooth clips.
1461 std::tie(hasSWMask, clipFP) = GetSWMaskFP(
1462 context, &fMasks, cs, scissorBounds, elementsForMask.begin(),
1463 elementsForMask.count(), std::move(clipFP));
1464 }
1465
1466 if (!hasSWMask) {
1467 if (stencilUnavailable) {
1468 SkDebugf("WARNING: Clip mask requires stencil, but stencil unavailable. "
1469 "Draw will be ignored.\n");
1470 return Effect::kClippedOut;
1471 } else {
1472 // Rasterize the remaining elements to the stencil buffer
1473 render_stencil_mask(context, rtc, cs.genID(), scissorBounds,
1474 elementsForMask.begin(), elementsForMask.count(), out);
1475 }
1476 }
1477 }
1478
1479 // Finish CCPR paths now that the render target's ops task is stable.
1480 if (!elementsForAtlas.empty()) {
1481 uint32_t opsTaskID = rtc->getOpsTask()->uniqueID();
1482 for (int i = 0; i < elementsForAtlas.count(); ++i) {
1483 SkASSERT(elementsForAtlas[i]->aa() == GrAA::kYes);
1484 clipFP = clip_atlas_fp(ccpr, opsTaskID, scissorBounds, elementsForAtlas[i]->asElement(),
1485 elementsForAtlas[i]->devicePath(), *caps, std::move(clipFP));
1486 }
1487 }
1488
1489 if (clipFP) {
1490 // This will include all analytic FPs, all CCPR atlas FPs, and a SW mask FP.
1491 out->addCoverageFP(std::move(clipFP));
1492 }
1493
1494 SkASSERT(out->doesClip());
1495 return Effect::kClipped;
1496}
1497
1498GrClipStack::SaveRecord& GrClipStack::writableSaveRecord(bool* wasDeferred) {
1499 SaveRecord& current = fSaves.back();
1500 if (current.canBeUpdated()) {
1501 // Current record is still open, so it can be modified directly
1502 *wasDeferred = false;
1503 return current;
1504 } else {
1505 // Must undefer the save to get a new record.
1506 SkAssertResult(current.popSave());
1507 *wasDeferred = true;
1508 return fSaves.emplace_back(current, fMasks.count(), fElements.count());
1509 }
1510}
1511
1512void GrClipStack::clipShader(sk_sp<SkShader> shader) {
1513 // Shaders can't bring additional coverage
1514 if (this->currentSaveRecord().state() == ClipState::kEmpty) {
1515 return;
1516 }
1517
1518 bool wasDeferred;
1519 this->writableSaveRecord(&wasDeferred).addShader(std::move(shader));
1520 // Masks and geometry elements are not invalidated by updating the clip shader
1521}
1522
1523void GrClipStack::replaceClip(const SkIRect& rect) {
1524 bool wasDeferred;
1525 SaveRecord& save = this->writableSaveRecord(&wasDeferred);
1526
1527 if (!wasDeferred) {
1528 save.removeElements(&fElements);
1529 save.invalidateMasks(fProxyProvider, &fMasks);
1530 }
1531
1532 save.reset(fDeviceBounds);
1533 if (rect != fDeviceBounds) {
1534 this->clipRect(SkMatrix::I(), SkRect::Make(rect), GrAA::kNo, SkClipOp::kIntersect);
1535 }
1536}
1537
1538void GrClipStack::clip(RawElement&& element) {
1539 if (this->currentSaveRecord().state() == ClipState::kEmpty) {
1540 return;
1541 }
1542
1543 // Reduce the path to anything simpler, will apply the transform if it's a scale+translate
1544 // and ensures the element's bounds are clipped to the device (NOT the conservative clip bounds,
1545 // since those are based on the net effect of all elements while device bounds clipping happens
1546 // implicitly. During addElement, we may still be able to invalidate some older elements).
1547 element.simplify(fDeviceBounds, fForceAA);
1548 SkASSERT(!element.shape().inverted());
1549
1550 // An empty op means do nothing (for difference), or close the save record, so we try and detect
1551 // that early before doing additional unnecessary save record allocation.
1552 if (element.shape().isEmpty()) {
1553 if (element.op() == SkClipOp::kDifference) {
1554 // If the shape is empty and we're subtracting, this has no effect on the clip
1555 return;
1556 }
1557 // else we will make the clip empty, but we need a new save record to record that change
1558 // in the clip state; fall through to below and updateForElement() will handle it.
1559 }
1560
1561 bool wasDeferred;
1562 SaveRecord& save = this->writableSaveRecord(&wasDeferred);
1563 SkDEBUGCODE(uint32_t oldGenID = save.genID();)
1564 SkDEBUGCODE(int elementCount = fElements.count();)
1565 if (!save.addElement(std::move(element), &fElements)) {
1566 if (wasDeferred) {
1567 // We made a new save record, but ended up not adding an element to the stack.
1568 // So instead of keeping an empty save record around, pop it off and restore the counter
1569 SkASSERT(elementCount == fElements.count());
1570 fSaves.pop_back();
1571 fSaves.back().pushSave();
1572 } else {
1573 // Should not have changed gen ID if the element and save were not modified
1574 SkASSERT(oldGenID == save.genID());
1575 }
1576 } else {
1577 // The gen ID should be new, and should not be invalid
1578 SkASSERT(oldGenID != save.genID() && save.genID() != kInvalidGenID);
1579 if (fProxyProvider && !wasDeferred) {
1580 // We modified an active save record so any old masks it had can be invalidated
1581 save.invalidateMasks(fProxyProvider, &fMasks);
1582 }
1583 }
1584}
1585
1586GrFPResult GrClipStack::GetSWMaskFP(GrRecordingContext* context, Mask::Stack* masks,
1587 const SaveRecord& current, const SkIRect& bounds,
1588 const Element** elements, int count,
1589 std::unique_ptr<GrFragmentProcessor> clipFP) {
1590 GrProxyProvider* proxyProvider = context->priv().proxyProvider();
1591 GrSurfaceProxyView maskProxy;
1592
1593 SkIRect maskBounds; // may not be 'bounds' if we reuse a large clip mask
1594 // Check the existing masks from this save record for compatibility
1595 for (const Mask& m : masks->ritems()) {
1596 if (m.genID() != current.genID()) {
1597 break;
1598 }
1599 if (m.appliesToDraw(current, bounds)) {
1600 maskProxy = proxyProvider->findCachedProxyWithColorTypeFallback(
1601 m.key(), kMaskOrigin, GrColorType::kAlpha_8, 1);
1602 if (maskProxy) {
1603 maskBounds = m.bounds();
1604 break;
1605 }
1606 }
1607 }
1608
1609 if (!maskProxy) {
1610 // No existing mask was found, so need to render a new one
1611 maskProxy = render_sw_mask(context, bounds, elements, count);
1612 if (!maskProxy) {
1613 // If we still don't have one, there's nothing we can do
1614 return GrFPFailure(std::move(clipFP));
1615 }
1616
1617 // Register the mask for later invalidation
1618 Mask& mask = masks->emplace_back(current, bounds);
1619 proxyProvider->assignUniqueKeyToProxy(mask.key(), maskProxy.asTextureProxy());
1620 maskBounds = bounds;
1621 }
1622
1623 // Wrap the mask in an FP that samples it for coverage
1624 SkASSERT(maskProxy && maskProxy.origin() == kMaskOrigin);
1625
1626 GrSamplerState samplerState(GrSamplerState::WrapMode::kClampToBorder,
1627 GrSamplerState::Filter::kNearest);
1628 // Maps the device coords passed to the texture effect to the top-left corner of the mask, and
1629 // make sure that the draw bounds are pre-mapped into the mask's space as well.
1630 auto m = SkMatrix::Translate(-maskBounds.fLeft, -maskBounds.fTop);
1631 auto subset = SkRect::Make(bounds);
1632 subset.offset(-maskBounds.fLeft, -maskBounds.fTop);
1633 // We scissor to bounds. The mask's texel centers are aligned to device space
1634 // pixel centers. Hence this domain of texture coordinates.
1635 auto domain = subset.makeInset(0.5, 0.5);
1636 auto fp = GrTextureEffect::MakeSubset(std::move(maskProxy), kPremul_SkAlphaType, m,
1637 samplerState, subset, domain, *context->priv().caps());
1638 fp = GrDeviceSpaceEffect::Make(std::move(fp));
1639
1640 // Must combine the coverage sampled from the texture effect with the previous coverage
1641 fp = GrBlendFragmentProcessor::Make(std::move(clipFP), std::move(fp), SkBlendMode::kModulate);
1642 return GrFPSuccess(std::move(fp));
1643}