Debian Codegraph @

src/core/SkDevice.cpp

raw
1 /*
2 * Copyright 2011 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #include "src/core/SkDevice.h"
9
10 #include "include/core/SkAlphaType.h"
11 #include "include/core/SkColorSpace.h"
12 #include "include/core/SkColorType.h"
13 #include "include/core/SkDrawable.h"
14 #include "include/core/SkImage.h"
15 #include "include/core/SkPaint.h"
16 #include "include/core/SkPath.h"
17 #include "include/core/SkPathBuilder.h"
18 #include "include/core/SkPathTypes.h"
19 #include "include/core/SkPixmap.h"
20 #include "include/core/SkRRect.h"
21 #include "include/core/SkRSXform.h"
22 #include "include/core/SkScalar.h"
23 #include "include/core/SkShader.h"
24 #include "include/core/SkSpan.h"
25 #include "include/core/SkSurface.h"
26 #include "include/core/SkTypes.h"
27 #include "include/core/SkVertices.h"
28 #include "include/private/base/SkFloatingPoint.h"
29 #include "include/private/chromium/Slug.h" // IWYU pragma: keep
30 #include "src/core/SkColorPriv.h"
31 #include "src/core/SkEnumerate.h"
32 #include "src/core/SkImageFilterTypes.h"
33 #include "src/core/SkImageFilter_Base.h"
34 #include "src/core/SkLatticeIter.h"
35 #include "src/core/SkMatrixPriv.h"
36 #include "src/core/SkMemset.h"
37 #include "src/core/SkPathPriv.h"
38 #include "src/core/SkRectPriv.h"
39 #include "src/core/SkScalerContext.h"
40 #include "src/core/SkSpecialImage.h"
41 #include "src/text/GlyphRun.h"
42 #include "src/utils/SkPatchUtils.h"
43
44 #include <cstddef>
45 #include <cstdint>
46
47
48 SkDevice::SkDevice(const SkImageInfo& info, const SkSurfaceProps& surfaceProps)
49 : fInfo(info)
50 , fSurfaceProps(surfaceProps) {
51 fDeviceToGlobal.setIdentity();
52 fGlobalToDevice.setIdentity();
53 }
54
55 void SkDevice::setDeviceCoordinateSystem(const SkM44& deviceToGlobal,
56 const SkM44& globalToDevice,
57 const SkM44& localToDevice,
58 int bufferOriginX,
59 int bufferOriginY) {
60 fDeviceToGlobal = deviceToGlobal;
61 fDeviceToGlobal.normalizePerspective();
62 fGlobalToDevice = globalToDevice;
63 fGlobalToDevice.normalizePerspective();
64
65 fLocalToDevice = localToDevice;
66 fLocalToDevice.normalizePerspective();
67 if (bufferOriginX | bufferOriginY) {
68 fDeviceToGlobal.preTranslate(bufferOriginX, bufferOriginY);
69 fGlobalToDevice.postTranslate(-bufferOriginX, -bufferOriginY);
70 fLocalToDevice.postTranslate(-bufferOriginX, -bufferOriginY);
71 }
72 fLocalToDevice33 = fLocalToDevice.asM33();
73 fLocalToDeviceDirty = true;
74 }
75
76 void SkDevice::setGlobalCTM(const SkM44& ctm) {
77 fLocalToDevice = ctm;
78 fLocalToDevice.normalizePerspective();
79 // Map from the global CTM state to this device's coordinate system.
80 fLocalToDevice.postConcat(fGlobalToDevice);
81 fLocalToDevice33 = fLocalToDevice.asM33();
82 fLocalToDeviceDirty = true;
83 }
84
85 bool SkDevice::isPixelAlignedToGlobal() const {
86 // pixelAligned is set to the identity + integer translation of the device-to-global matrix.
87 // If they are equal then the device is by definition pixel aligned.
88 SkM44 pixelAligned = SkM44();
89 pixelAligned.setRC(0, 3, SkScalarFloorToScalar(fDeviceToGlobal.rc(0, 3)));
90 pixelAligned.setRC(1, 3, SkScalarFloorToScalar(fDeviceToGlobal.rc(1, 3)));
91 return pixelAligned == fDeviceToGlobal;
92 }
93
94 SkIPoint SkDevice::getOrigin() const {
95 // getOrigin() is deprecated, the old origin has been moved into the fDeviceToGlobal matrix.
96 // This extracts the origin from the matrix, but asserts that a more complicated coordinate
97 // space hasn't been set of the device. This function can be removed once existing use cases
98 // have been updated to use the device-to-global matrix instead or have themselves been removed
99 // (e.g. Android's device-space clip regions are going away, and are not compatible with the
100 // generalized device coordinate system).
101 SkASSERT(this->isPixelAlignedToGlobal());
102 return SkIPoint::Make(SkScalarFloorToInt(fDeviceToGlobal.rc(0, 3)),
103 SkScalarFloorToInt(fDeviceToGlobal.rc(1, 3)));
104 }
105
106 SkM44 SkDevice::getRelativeTransform(const SkDevice& dstDevice) const {
107 // To get the transform from this space to the other device's, transform from our space to
108 // global and then from global to the other device.
109 return dstDevice.fGlobalToDevice * fDeviceToGlobal;
110 }
111
112 static inline bool is_int(float x) {
113 return x == (float) sk_float_round2int(x);
114 }
115
116 void SkDevice::drawRegion(const SkRegion& region, const SkPaint& paint) {
117 const SkMatrix& localToDevice = this->localToDevice();
118 bool isNonTranslate = localToDevice.getType() & ~(SkMatrix::kTranslate_Mask);
119 bool complexPaint = paint.getStyle() != SkPaint::kFill_Style || paint.getMaskFilter() ||
120 paint.getPathEffect();
121 bool antiAlias = paint.isAntiAlias() && (!is_int(localToDevice.getTranslateX()) ||
122 !is_int(localToDevice.getTranslateY()));
123 if (isNonTranslate || complexPaint || antiAlias) {
124 SkPathBuilder builder;
125 region.addBoundaryPath(&builder);
126 builder.setIsVolatile(true);
127 return this->drawPath(builder.detach(), paint);
128 }
129
130 SkRegion::Iterator it(region);
131 while (!it.done()) {
132 this->drawRect(SkRect::Make(it.rect()), paint);
133 it.next();
134 }
135 }
136
137 void SkDevice::drawArc(const SkArc& arc, const SkPaint& paint) {
138 bool isFillNoPathEffect = SkPaint::kFill_Style == paint.getStyle() && !paint.getPathEffect();
139 SkPath path = SkPathPriv::CreateDrawArcPath(arc, isFillNoPathEffect);
140 this->drawPath(path, paint);
141 }
142
143 void SkDevice::drawDRRect(const SkRRect& outer,
144 const SkRRect& inner, const SkPaint& paint) {
145 SkPathBuilder builder;
146 builder.addRRect(outer);
147 builder.addRRect(inner);
148 builder.setFillType(SkPathFillType::kEvenOdd);
149 builder.setIsVolatile(true);
150
151 this->drawPath(builder.detach(), paint);
152 }
153
154 void SkDevice::drawPatch(const SkPoint cubics[12], const SkColor colors[4],
155 const SkPoint texCoords[4], sk_sp<SkBlender> blender,
156 const SkPaint& paint) {
157 SkISize lod = SkPatchUtils::GetLevelOfDetail(cubics, &this->localToDevice());
158 auto vertices = SkPatchUtils::MakeVertices(cubics, colors, texCoords, lod.width(), lod.height(),
159 this->imageInfo().colorSpace());
160 if (vertices) {
161 this->drawVertices(vertices.get(), std::move(blender), paint);
162 }
163 }
164
165 void SkDevice::drawImageLattice(const SkImage* image, const SkCanvas::Lattice& lattice,
166 const SkRect& dst, SkFilterMode filter, const SkPaint& paint) {
167 SkLatticeIter iter(lattice, dst);
168
169 SkRect srcR, dstR;
170 SkColor c;
171 bool isFixedColor = false;
172 const SkImageInfo info = SkImageInfo::Make(1, 1, kBGRA_8888_SkColorType, kUnpremul_SkAlphaType);
173
174 while (iter.next(&srcR, &dstR, &isFixedColor, &c)) {
175 // TODO: support this fast-path for GPU images
176 if (isFixedColor || (srcR.width() <= 1.0f && srcR.height() <= 1.0f &&
177 image->readPixels(nullptr, info, &c, 4, srcR.fLeft, srcR.fTop))) {
178 // Fast draw with drawRect, if this is a patch containing a single color
179 // or if this is a patch containing a single pixel.
180 if (0 != c || !paint.isSrcOver()) {
181 SkPaint paintCopy(paint);
182 int alpha = SkAlphaMul(SkColorGetA(c), SkAlpha255To256(paint.getAlpha()));
183 paintCopy.setColor(SkColorSetA(c, alpha));
184 this->drawRect(dstR, paintCopy);
185 }
186 } else {
187 this->drawImageRect(image, &srcR, dstR, SkSamplingOptions(filter), paint,
188 SkCanvas::kStrict_SrcRectConstraint);
189 }
190 }
191 }
192
193 static SkPoint* quad_to_tris(SkPoint tris[6], SkSpan<const SkPoint> quad) {
194 SkASSERT(quad.size() == 4);
195
196 tris[0] = quad[0];
197 tris[1] = quad[1];
198 tris[2] = quad[2];
199
200 tris[3] = quad[0];
201 tris[4] = quad[2];
202 tris[5] = quad[3];
203
204 return tris + 6;
205 }
206
207 void SkDevice::drawAtlas(SkSpan<const SkRSXform> xform,
208 SkSpan<const SkRect> tex,
209 SkSpan<const SkColor> colors,
210 sk_sp<SkBlender> blender,
211 const SkPaint& paint) {
212 const size_t quadCount = xform.size();
213 const size_t triCount = quadCount << 1;
214 const size_t vertexCount = triCount * 3;
215 uint32_t flags = SkVertices::kHasTexCoords_BuilderFlag;
216 if (!colors.empty()) {
217 flags |= SkVertices::kHasColors_BuilderFlag;
218 }
219 SkVertices::Builder builder(SkVertices::kTriangles_VertexMode, vertexCount, 0, flags);
220
221 SkPoint* vPos = builder.positions();
222 SkPoint* vTex = builder.texCoords();
223 SkColor* vCol = builder.colors();
224 for (size_t i = 0; i < quadCount; ++i) {
225 SkPoint tmp[4];
226 xform[i].toQuad(tex[i].width(), tex[i].height(), tmp);
227 vPos = quad_to_tris(vPos, tmp);
228
229 vTex = quad_to_tris(vTex, tex[i].toQuad());
230
231 if (!colors.empty()) {
232 SkOpts::memset32(vCol, colors[i], 6);
233 vCol += 6;
234 }
235 }
236 this->drawVertices(builder.detach().get(), std::move(blender), paint);
237 }
238
239 void SkDevice::drawEdgeAAQuad(const SkRect& r, const SkPoint clip[4], SkCanvas::QuadAAFlags aa,
240 const SkColor4f& color, SkBlendMode mode) {
241 SkPaint paint;
242 paint.setColor4f(color);
243 paint.setBlendMode(mode);
244 paint.setAntiAlias(aa == SkCanvas::kAll_QuadAAFlags);
245
246 if (clip) {
247 // Draw the clip directly as a quad since it's a filled color with no local coords
248 this->drawPath(SkPath::Polygon({clip, 4}, true), paint);
249 } else {
250 this->drawRect(r, paint);
251 }
252 }
253
254 void SkDevice::drawEdgeAAImageSet(const SkCanvas::ImageSetEntry images[], int count,
255 const SkPoint dstClips[], const SkMatrix preViewMatrices[],
256 const SkSamplingOptions& sampling, const SkPaint& paint,
257 SkCanvas::SrcRectConstraint constraint) {
258 SkASSERT(paint.getStyle() == SkPaint::kFill_Style);
259 SkASSERT(!paint.getPathEffect());
260
261 SkPaint entryPaint = paint;
262 const SkM44 baseLocalToDevice = this->localToDevice44();
263 int clipIndex = 0;
264 for (int i = 0; i < count; ++i) {
265 // TODO: Handle per-edge AA. Right now this mirrors the SkiaRenderer component of Chrome
266 // which turns off antialiasing unless all four edges should be antialiased. This avoids
267 // seaming in tiled composited layers.
268 entryPaint.setAntiAlias(images[i].fAAFlags == SkCanvas::kAll_QuadAAFlags);
269 entryPaint.setAlphaf(paint.getAlphaf() * images[i].fAlpha);
270
271 SkASSERT(images[i].fMatrixIndex < 0 || preViewMatrices);
272 if (images[i].fMatrixIndex >= 0) {
273 this->setLocalToDevice(baseLocalToDevice *
274 SkM44(preViewMatrices[images[i].fMatrixIndex]));
275 }
276
277 SkASSERT(!images[i].fHasClip || dstClips);
278 if (images[i].fHasClip) {
279 // Since drawImageRect requires a srcRect, the dst clip is implemented as a true clip
280 this->pushClipStack();
281 SkPath clipPath = SkPath::Polygon({dstClips + clipIndex, 4}, true);
282 this->clipPath(clipPath, SkClipOp::kIntersect, entryPaint.isAntiAlias());
283 clipIndex += 4;
284 }
285 this->drawImageRect(images[i].fImage.get(), &images[i].fSrcRect, images[i].fDstRect,
286 sampling, entryPaint, constraint);
287 if (images[i].fHasClip) {
288 this->popClipStack();
289 }
290 if (images[i].fMatrixIndex >= 0) {
291 this->setLocalToDevice(baseLocalToDevice);
292 }
293 }
294 }
295
296 ///////////////////////////////////////////////////////////////////////////////////////////////////
297
298 void SkDevice::drawDrawable(SkCanvas* canvas, SkDrawable* drawable, const SkMatrix* matrix) {
299 drawable->draw(canvas, matrix);
300 }
301
302 ///////////////////////////////////////////////////////////////////////////////////////////////////
303
304 void SkDevice::drawSpecial(SkSpecialImage*, const SkMatrix&, const SkSamplingOptions&,
305 const SkPaint&, SkCanvas::SrcRectConstraint) {}
306 void SkDevice::drawCoverageMask(const SkSpecialImage*, const SkMatrix& maskToDevice,
307 const SkSamplingOptions&, const SkPaint&) {
308 // This shouldn't be reached; SkCanvas will only call this if
309 // useDrawCoverageMaskForMaskFilters() is overridden to return true.
310 SK_ABORT("Must override if useDrawCoverageMaskForMaskFilters() is true");
311 }
312
313 sk_sp<SkSpecialImage> SkDevice::snapSpecial(const SkIRect&, bool forceCopy) { return nullptr; }
314 sk_sp<SkSpecialImage> SkDevice::snapSpecialScaled(const SkIRect& subset,
315 const SkISize& dstDims) {
316 return nullptr;
317 }
318 sk_sp<SkSpecialImage> SkDevice::snapSpecial() {
319 return this->snapSpecial(SkIRect::MakeWH(this->width(), this->height()));
320 }
321
322 sk_sp<skif::Backend> SkDevice::createImageFilteringBackend(const SkSurfaceProps& surfaceProps,
323 SkColorType colorType) const {
324 return skif::MakeRasterBackend(surfaceProps, colorType);
325 }
326
327 void SkDevice::drawDevice(SkDevice* device,
328 const SkSamplingOptions& sampling,
329 const SkPaint& paint) {
330 sk_sp<SkSpecialImage> deviceImage = device->snapSpecial();
331 if (deviceImage) {
332 // SkCanvas only calls drawDevice() when there are no filters (so the transform is pixel
333 // aligned). As such it can be drawn without clamping.
334 SkMatrix relativeTransform = device->getRelativeTransform(*this).asM33();
335 const bool strict = sampling != SkFilterMode::kNearest ||
336 !relativeTransform.isTranslate() ||
337 !SkScalarIsInt(relativeTransform.getTranslateX()) ||
338 !SkScalarIsInt(relativeTransform.getTranslateY());
339 this->drawSpecial(deviceImage.get(), relativeTransform, sampling, paint,
340 strict ? SkCanvas::kStrict_SrcRectConstraint
341 : SkCanvas::kFast_SrcRectConstraint);
342 }
343 }
344
345 void SkDevice::drawFilteredImage(const skif::Mapping& mapping,
346 SkSpecialImage* src,
347 SkColorType colorType,
348 const SkImageFilter* filter,
349 const SkSamplingOptions& sampling,
350 const SkPaint& paint) {
351 SkASSERT(!paint.getImageFilter() && !paint.getMaskFilter());
352
353 skif::LayerSpace<SkIRect> targetOutput = mapping.deviceToLayer(
354 skif::DeviceSpace<SkIRect>(this->devClipBounds()));
355
356 if (colorType == kUnknown_SkColorType) {
357 colorType = kRGBA_8888_SkColorType;
358 }
359
360 skif::Stats stats;
361 skif::Context ctx{this->createImageFilteringBackend(src ? src->props() : this->surfaceProps(),
362 colorType),
363 mapping,
364 targetOutput,
365 skif::FilterResult(sk_ref_sp(src)),
366 this->imageInfo().colorSpace(),
367 &stats};
368
369 SkIPoint offset;
370 sk_sp<SkSpecialImage> result = as_IFB(filter)->filterImage(ctx).imageAndOffset(ctx, &offset);
371 stats.reportStats();
372 if (result) {
373 SkMatrix deviceMatrixWithOffset = mapping.layerToDevice().asM33();
374 deviceMatrixWithOffset.preTranslate(offset.fX, offset.fY);
375 this->drawSpecial(result.get(), deviceMatrixWithOffset, sampling, paint);
376 }
377 }
378
379 ///////////////////////////////////////////////////////////////////////////////////////////////////
380
381 bool SkDevice::accessPixels(SkPixmap* pmap) {
382 SkPixmap tempStorage;
383 if (nullptr == pmap) {
384 pmap = &tempStorage;
385 }
386 return this->onAccessPixels(pmap);
387 }
388
389 bool SkDevice::peekPixels(SkPixmap* pmap) {
390 SkPixmap tempStorage;
391 if (nullptr == pmap) {
392 pmap = &tempStorage;
393 }
394 return this->onPeekPixels(pmap);
395 }
396
397 //////////////////////////////////////////////////////////////////////////////////////////
398
399 static sk_sp<SkShader> make_post_inverse_lm(const SkShader* shader, const SkMatrix& lm) {
400 auto inverse_lm = lm.invert();
401 if (!shader || !inverse_lm) {
402 return nullptr;
403 }
404
405 #if defined(SK_BUILD_FOR_ANDROID_FRAMEWORK) // b/256873449
406 // Legacy impl for old concat order. This does not work for arbitrary shader DAGs (when there is
407 // no single leaf local matrix).
408
409 // LMs pre-compose. In order to push a post local matrix, we peel off any existing local matrix
410 // and set a new local matrix of inverse_lm * prev_local_matrix.
411 SkMatrix prev_local_matrix;
412 const auto nested_shader = as_SB(shader)->makeAsALocalMatrixShader(&prev_local_matrix);
413 if (nested_shader) {
414 // unfurl the shader
415 shader = nested_shader.get();
416 }
417
418 return shader->makeWithLocalMatrix(*inverse_lm * prev_local_matrix);
419 #endif
420
421 return shader->makeWithLocalMatrix(*inverse_lm);
422 }
423
424 void SkDevice::drawGlyphRunList(SkCanvas* canvas,
425 const sktext::GlyphRunList& glyphRunList,
426 const SkPaint& paint) {
427 if (!this->localToDevice().isFinite()) {
428 return;
429 }
430
431 if (!glyphRunList.hasRSXForm()) {
432 this->onDrawGlyphRunList(canvas, glyphRunList, paint);
433 } else {
434 this->simplifyGlyphRunRSXFormAndRedraw(canvas, glyphRunList, paint);
435 }
436 }
437
438 void SkDevice::simplifyGlyphRunRSXFormAndRedraw(SkCanvas* canvas,
439 const sktext::GlyphRunList& glyphRunList,
440 const SkPaint& paint) {
441 for (const sktext::GlyphRun& run : glyphRunList) {
442 if (run.scaledRotations().empty()) {
443 auto subList = glyphRunList.builder()->makeGlyphRunList(run, paint, {0, 0});
444 this->drawGlyphRunList(canvas, subList, paint);
445 } else {
446 SkPoint origin = glyphRunList.origin();
447 SkPoint sharedPos{0, 0}; // we're at the origin
448 SkGlyphID sharedGlyphID;
449 sktext::GlyphRun glyphRun {
450 run.font(),
451 SkSpan<const SkPoint>{&sharedPos, 1},
452 SkSpan<const SkGlyphID>{&sharedGlyphID, 1},
453 SkSpan<const char>{},
454 SkSpan<const uint32_t>{},
455 SkSpan<const SkVector>{}
456 };
457
458 for (auto [i, glyphID, pos] : SkMakeEnumerate(run.source())) {
459 sharedGlyphID = glyphID;
460 auto [scos, ssin] = run.scaledRotations()[i];
461 SkRSXform rsxForm = SkRSXform::Make(scos, ssin, pos.x(), pos.y());
462 SkMatrix glyphToLocal;
463 glyphToLocal.setRSXform(rsxForm).postTranslate(origin.x(), origin.y());
464
465 // We want to rotate each glyph by the rsxform, but we don't want to rotate "space"
466 // (i.e. the shader that cares about the ctm) so we have to undo our little ctm
467 // trick with a localmatrixshader so that the shader draws as if there was no
468 // change to the ctm.
469 SkPaint invertingPaint{paint};
470 invertingPaint.setShader(make_post_inverse_lm(paint.getShader(), glyphToLocal));
471 SkAutoCanvasRestore acr(canvas, true);
472 canvas->concat(SkM44(glyphToLocal));
473 sktext::GlyphRunList subList =
474 glyphRunList.builder()->makeGlyphRunList(glyphRun, paint, {0, 0});
475 this->drawGlyphRunList(canvas, subList, invertingPaint);
476 }
477 }
478 }
479 }
480
481 sk_sp<sktext::gpu::Slug> SkDevice::convertGlyphRunListToSlug(
482 const sktext::GlyphRunList& glyphRunList, const SkPaint& paint) {
483 return nullptr;
484 }
485
486 void SkDevice::drawSlug(SkCanvas*, const sktext::gpu::Slug*, const SkPaint&) {
487 SK_ABORT("Slug drawing not supported.");
488 }
489
490 //////////////////////////////////////////////////////////////////////////////////////////
491
492 sk_sp<SkSurface> SkDevice::makeSurface(SkImageInfo const&, SkSurfaceProps const&) {
493 return nullptr;
494 }
495
496 SkScalerContextFlags SkDevice::scalerContextFlags() const {
497 // If we're doing linear blending, then we can disable the gamma hacks.
498 // Otherwise, leave them on. In either case, we still want the contrast boost:
499 // TODO: Can we be even smarter about mask gamma based on the dest transfer function?
500 const SkColorSpace* const cs = fInfo.colorSpace();
501 if (cs && cs->gammaIsLinear()) {
502 return SkScalerContextFlags::kBoostContrast;
503 } else {
504 return SkScalerContextFlags::kFakeGammaAndBoostContrast;
505 }
506 }
507
508 //////////////////////////////////////////////////////////////////////////////////////////
509
510 SkNoPixelsDevice::SkNoPixelsDevice(const SkIRect& bounds, const SkSurfaceProps& props)
511 : SkNoPixelsDevice(bounds, props, nullptr) {}
512
513 SkNoPixelsDevice::SkNoPixelsDevice(const SkIRect& bounds, const SkSurfaceProps& props,
514 sk_sp<SkColorSpace> colorSpace)
515 : SkDevice(SkImageInfo::Make(bounds.size(), kUnknown_SkColorType, kUnknown_SkAlphaType,
516 std::move(colorSpace)), props) {
517 // this fails if we enable this assert: DiscardableImageMapTest.GetDiscardableImagesInRectMaxImage
518 //SkASSERT(bounds.width() >= 0 && bounds.height() >= 0);
519
520 this->setOrigin(SkM44(), bounds.left(), bounds.top());
521 fClipStack.emplace_back(this->bounds(), /*isAA=*/false, /*isRect=*/true);
522 }
523
524 bool SkNoPixelsDevice::resetForNextPicture(const SkIRect& bounds) {
525 // Resetting should only happen on the root SkNoPixelsDevice, so its device-to-global
526 // transform should be pixel aligned.
527 SkASSERT(this->isPixelAlignedToGlobal());
528 // We can only reset the device as long as its dimensions are not changing.
529 if (bounds.width() != this->width() || bounds.height() != this->height()) {
530 return false;
531 }
532
533 // And the canvas should have restored back to the original save count.
534 SkASSERT(fClipStack.size() == 1 && fClipStack[0].fDeferredSaveCount == 0);
535 // But in the event that the clip was modified w/o a save(), reset the tracking state
536 fClipStack[0].fClipBounds = this->bounds();
537 fClipStack[0].fIsAA = false;
538 fClipStack[0].fIsRect = true;
539
540 this->setOrigin(SkM44(), bounds.left(), bounds.top());
541 return true;
542 }
543
544 void SkNoPixelsDevice::pushClipStack() {
545 SkASSERT(!fClipStack.empty());
546 fClipStack.back().fDeferredSaveCount++;
547 }
548
549 void SkNoPixelsDevice::popClipStack() {
550 SkASSERT(!fClipStack.empty());
551 if (fClipStack.back().fDeferredSaveCount > 0) {
552 fClipStack.back().fDeferredSaveCount--;
553 } else {
554 fClipStack.pop_back();
555 SkASSERT(!fClipStack.empty());
556 }
557 }
558
559 SkNoPixelsDevice::ClipState& SkNoPixelsDevice::writableClip() {
560 SkASSERT(!fClipStack.empty());
561 ClipState& current = fClipStack.back();
562 if (current.fDeferredSaveCount > 0) {
563 current.fDeferredSaveCount--;
564 // Stash current state in case 'current' moves during a resize
565 SkIRect bounds = current.fClipBounds;
566 bool aa = current.fIsAA;
567 bool rect = current.fIsRect;
568 return fClipStack.emplace_back(bounds, aa, rect);
569 } else {
570 return current;
571 }
572 }
573
574 void SkNoPixelsDevice::clipRect(const SkRect& rect, SkClipOp op, bool aa) {
575 this->writableClip().op(op, this->localToDevice44(), rect,
576 aa, /*fillsBounds=*/true);
577 }
578
579 void SkNoPixelsDevice::clipRRect(const SkRRect& rrect, SkClipOp op, bool aa) {
580 this->writableClip().op(op, this->localToDevice44(), rrect.getBounds(),
581 aa, /*fillsBounds=*/rrect.isRect());
582 }
583
584 void SkNoPixelsDevice::clipPath(const SkPath& path, SkClipOp op, bool aa) {
585 // Toggle op if the path is inverse filled
586 if (path.isInverseFillType()) {
587 op = (op == SkClipOp::kDifference ? SkClipOp::kIntersect : SkClipOp::kDifference);
588 }
589 this->writableClip().op(op, this->localToDevice44(), path.getBounds(),
590 aa, /*fillsBounds=*/false);
591 }
592
593 void SkNoPixelsDevice::clipRegion(const SkRegion& globalRgn, SkClipOp op) {
594 this->writableClip().op(op, this->globalToDevice(), SkRect::Make(globalRgn.getBounds()),
595 /*isAA=*/false, /*fillsBounds=*/globalRgn.isRect());
596 }
597
598 void SkNoPixelsDevice::onClipShader(sk_sp<SkShader> shader) {
599 this->writableClip().fIsRect = false;
600 }
601
602 void SkNoPixelsDevice::replaceClip(const SkIRect& rect) {
603 SkIRect deviceRect = SkMatrixPriv::MapRect(this->globalToDevice(), SkRect::Make(rect)).round();
604 if (!deviceRect.intersect(this->bounds())) {
605 deviceRect.setEmpty();
606 }
607 auto& clip = this->writableClip();
608 clip.fClipBounds = deviceRect;
609 clip.fIsRect = true;
610 clip.fIsAA = false;
611 }
612
613 void SkNoPixelsDevice::ClipState::op(SkClipOp op, const SkM44& transform, const SkRect& bounds,
614 bool isAA, bool fillsBounds) {
615 const bool isRect = fillsBounds && SkMatrixPriv::IsScaleTranslateAsM33(transform);
616 fIsAA |= isAA;
617
618 SkRect devBounds = bounds.isEmpty() ? SkRect::MakeEmpty()
619 : SkMatrixPriv::MapRect(transform, bounds);
620 if (op == SkClipOp::kIntersect) {
621 if (!fClipBounds.intersect(isAA ? devBounds.roundOut() : devBounds.round())) {
622 fClipBounds.setEmpty();
623 }
624 // A rectangular clip remains rectangular if the intersection is a rect
625 fIsRect &= isRect;
626 } else if (isRect) {
627 // Conservatively, we can leave the clip bounds unchanged and respect the difference op.
628 // But, if we're subtracting out an axis-aligned rectangle that fully spans our existing
629 // clip on an axis, we can shrink the clip bounds.
630 SkASSERT(op == SkClipOp::kDifference);
631 SkIRect difference;
632 if (SkRectPriv::Subtract(fClipBounds, isAA ? devBounds.roundIn() : devBounds.round(),
633 &difference)) {
634 fClipBounds = difference;
635 } else {
636 // The difference couldn't be represented as a rect
637 fIsRect = false;
638 }
639 } else {
640 // A non-rect shape was applied
641 fIsRect = false;
642 }
643 }