1 /*
2 * Copyright 2012 The Android Open Source Project
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 "include/effects/SkMorphologyImageFilter.h"
9
10 #include "include/core/SkBitmap.h"
11 #include "include/core/SkRect.h"
12 #include "include/private/SkColorData.h"
13 #include "src/core/SkImageFilter_Base.h"
14 #include "src/core/SkReadBuffer.h"
15 #include "src/core/SkSpecialImage.h"
16 #include "src/core/SkWriteBuffer.h"
17
18 #if SK_SUPPORT_GPU
19 #include "include/gpu/GrContext.h"
20 #include "include/private/GrRecordingContext.h"
21 #include "src/gpu/GrContextPriv.h"
22 #include "src/gpu/GrCoordTransform.h"
23 #include "src/gpu/GrFixedClip.h"
24 #include "src/gpu/GrRecordingContextPriv.h"
25 #include "src/gpu/GrRenderTargetContext.h"
26 #include "src/gpu/GrTexture.h"
27 #include "src/gpu/GrTextureProxy.h"
28 #include "src/gpu/SkGr.h"
29 #include "src/gpu/glsl/GrGLSLFragmentProcessor.h"
30 #include "src/gpu/glsl/GrGLSLFragmentShaderBuilder.h"
31 #include "src/gpu/glsl/GrGLSLProgramDataManager.h"
32 #include "src/gpu/glsl/GrGLSLUniformHandler.h"
33 #endif
34
35 namespace {
36
37 enum class MorphType {
38 kErode,
39 kDilate,
40 kLastType = kDilate
41 };
42
43 enum class MorphDirection { kX, kY };
44
45 class SkMorphologyImageFilterImpl final : public SkImageFilter_Base {
46 public:
SkMorphologyImageFilterImpl(MorphType type,int radiusX,int radiusY,sk_sp<SkImageFilter> input,const CropRect * cropRect)47 SkMorphologyImageFilterImpl(MorphType type, int radiusX, int radiusY,
48 sk_sp<SkImageFilter> input, const CropRect* cropRect)
49 : INHERITED(&input, 1, cropRect)
50 , fType(type)
51 , fRadius(SkISize::Make(radiusX, radiusY)) {}
52
53 SkRect computeFastBounds(const SkRect& src) const override;
54 SkIRect onFilterNodeBounds(const SkIRect& src, const SkMatrix& ctm,
55 MapDirection, const SkIRect* inputRect) const override;
56
57 /**
58 * All morphology procs have the same signature: src is the source buffer, dst the
59 * destination buffer, radius is the morphology radius, width and height are the bounds
60 * of the destination buffer (in pixels), and srcStride and dstStride are the
61 * number of pixels per row in each buffer. All buffers are 8888.
62 */
63
64 typedef void (*Proc)(const SkPMColor* src, SkPMColor* dst, int radius,
65 int width, int height, int srcStride, int dstStride);
66
67 protected:
68 sk_sp<SkSpecialImage> onFilterImage(const Context&, SkIPoint* offset) const override;
69 void flatten(SkWriteBuffer&) const override;
70
radius() const71 SkISize radius() const { return fRadius; }
mappedRadius(const SkMatrix & ctm) const72 SkSize mappedRadius(const SkMatrix& ctm) const {
73 SkVector radiusVector = SkVector::Make(SkIntToScalar(fRadius.width()),
74 SkIntToScalar(fRadius.height()));
75 ctm.mapVectors(&radiusVector, 1);
76 radiusVector.setAbs(radiusVector);
77 return SkSize::Make(radiusVector.x(), radiusVector.y());
78 }
79
80 private:
81 friend void SkDilateImageFilter::RegisterFlattenables();
82
83 SK_FLATTENABLE_HOOKS(SkMorphologyImageFilterImpl)
84 // Historically the morphology op was implicitly encoded in the factory type used to decode
85 // the image filter, so provide backwards compatible functions for old SKPs.
86 static sk_sp<SkFlattenable> CreateProcWithType(SkReadBuffer&, const MorphType*);
DilateCreateProc(SkReadBuffer & buffer)87 static sk_sp<SkFlattenable> DilateCreateProc(SkReadBuffer& buffer) {
88 static const MorphType kType = MorphType::kDilate;
89 return CreateProcWithType(buffer, &kType);
90 }
ErodeCreateProc(SkReadBuffer & buffer)91 static sk_sp<SkFlattenable> ErodeCreateProc(SkReadBuffer& buffer) {
92 static const MorphType kType = MorphType::kErode;
93 return CreateProcWithType(buffer, &kType);
94 }
95
96 MorphType fType;
97 SkISize fRadius;
98
99 typedef SkImageFilter_Base INHERITED;
100 };
101
102 } // end namespace
103
Make(int radiusX,int radiusY,sk_sp<SkImageFilter> input,const SkImageFilter::CropRect * cropRect)104 sk_sp<SkImageFilter> SkDilateImageFilter::Make(int radiusX, int radiusY,
105 sk_sp<SkImageFilter> input,
106 const SkImageFilter::CropRect* cropRect) {
107 if (radiusX < 0 || radiusY < 0) {
108 return nullptr;
109 }
110 return sk_sp<SkImageFilter>(new SkMorphologyImageFilterImpl(
111 MorphType::kDilate, radiusX, radiusY, std::move(input), cropRect));
112 }
113
Make(int radiusX,int radiusY,sk_sp<SkImageFilter> input,const SkImageFilter::CropRect * cropRect)114 sk_sp<SkImageFilter> SkErodeImageFilter::Make(int radiusX, int radiusY,
115 sk_sp<SkImageFilter> input,
116 const SkImageFilter::CropRect* cropRect) {
117 if (radiusX < 0 || radiusY < 0) {
118 return nullptr;
119 }
120 return sk_sp<SkImageFilter>(new SkMorphologyImageFilterImpl(
121 MorphType::kErode, radiusX, radiusY, std::move(input), cropRect));
122 }
123
RegisterFlattenables()124 void SkDilateImageFilter::RegisterFlattenables() {
125 SK_REGISTER_FLATTENABLE(SkMorphologyImageFilterImpl);
126 // TODO (michaelludwig) - Remove after grace period for SKPs to stop using old names
127 SkFlattenable::Register("SkDilateImageFilter", SkMorphologyImageFilterImpl::DilateCreateProc);
128 SkFlattenable::Register(
129 "SkDilateImageFilterImpl", SkMorphologyImageFilterImpl::DilateCreateProc);
130 SkFlattenable::Register("SkErodeImageFilter", SkMorphologyImageFilterImpl::ErodeCreateProc);
131 SkFlattenable::Register("SkErodeImageFilterImpl", SkMorphologyImageFilterImpl::ErodeCreateProc);
132 }
133
134 ///////////////////////////////////////////////////////////////////////////////
135
136 // 'type' acts as a signal that old-style deserialization is required. It is temporary.
CreateProcWithType(SkReadBuffer & buffer,const MorphType * type)137 sk_sp<SkFlattenable> SkMorphologyImageFilterImpl::CreateProcWithType(SkReadBuffer& buffer,
138 const MorphType* type) {
139 SK_IMAGEFILTER_UNFLATTEN_COMMON(common, 1);
140 const int width = buffer.readInt();
141 const int height = buffer.readInt();
142
143 MorphType filterType;
144 if (type) {
145 // The old create procs that have an associated op should only be used on old SKPs
146 SkASSERT(buffer.isVersionLT(SkPicturePriv::kUnifyErodeDilateImpls_Version));
147 filterType = *type;
148 } else {
149 filterType = buffer.read32LE(MorphType::kLastType);
150 }
151
152 if (filterType == MorphType::kDilate) {
153 return SkDilateImageFilter::Make(width, height, common.getInput(0), &common.cropRect());
154 } else if (filterType == MorphType::kErode) {
155 return SkErodeImageFilter::Make(width, height, common.getInput(0), &common.cropRect());
156 } else {
157 return nullptr;
158 }
159 }
160
CreateProc(SkReadBuffer & buffer)161 sk_sp<SkFlattenable> SkMorphologyImageFilterImpl::CreateProc(SkReadBuffer& buffer) {
162 // Pass null to have the create proc read the op from the buffer
163 return CreateProcWithType(buffer, nullptr);
164 }
165
flatten(SkWriteBuffer & buffer) const166 void SkMorphologyImageFilterImpl::flatten(SkWriteBuffer& buffer) const {
167 this->INHERITED::flatten(buffer);
168 buffer.writeInt(fRadius.fWidth);
169 buffer.writeInt(fRadius.fHeight);
170 buffer.writeInt(static_cast<int>(fType));
171 }
172
call_proc_X(SkMorphologyImageFilterImpl::Proc procX,const SkBitmap & src,SkBitmap * dst,int radiusX,const SkIRect & bounds)173 static void call_proc_X(SkMorphologyImageFilterImpl::Proc procX,
174 const SkBitmap& src, SkBitmap* dst,
175 int radiusX, const SkIRect& bounds) {
176 procX(src.getAddr32(bounds.left(), bounds.top()), dst->getAddr32(0, 0),
177 radiusX, bounds.width(), bounds.height(),
178 src.rowBytesAsPixels(), dst->rowBytesAsPixels());
179 }
180
call_proc_Y(SkMorphologyImageFilterImpl::Proc procY,const SkPMColor * src,int srcRowBytesAsPixels,SkBitmap * dst,int radiusY,const SkIRect & bounds)181 static void call_proc_Y(SkMorphologyImageFilterImpl::Proc procY,
182 const SkPMColor* src, int srcRowBytesAsPixels, SkBitmap* dst,
183 int radiusY, const SkIRect& bounds) {
184 procY(src, dst->getAddr32(0, 0),
185 radiusY, bounds.height(), bounds.width(),
186 srcRowBytesAsPixels, dst->rowBytesAsPixels());
187 }
188
computeFastBounds(const SkRect & src) const189 SkRect SkMorphologyImageFilterImpl::computeFastBounds(const SkRect& src) const {
190 SkRect bounds = this->getInput(0) ? this->getInput(0)->computeFastBounds(src) : src;
191 bounds.outset(SkIntToScalar(fRadius.width()), SkIntToScalar(fRadius.height()));
192 return bounds;
193 }
194
onFilterNodeBounds(const SkIRect & src,const SkMatrix & ctm,MapDirection,const SkIRect * inputRect) const195 SkIRect SkMorphologyImageFilterImpl::onFilterNodeBounds(
196 const SkIRect& src, const SkMatrix& ctm, MapDirection, const SkIRect* inputRect) const {
197 SkSize radius = mappedRadius(ctm);
198 return src.makeOutset(SkScalarCeilToInt(radius.width()), SkScalarCeilToInt(radius.height()));
199 }
200
201 #if SK_SUPPORT_GPU
202
203 ///////////////////////////////////////////////////////////////////////////////
204 /**
205 * Morphology effects. Depending upon the type of morphology, either the
206 * component-wise min (Erode_Type) or max (Dilate_Type) of all pixels in the
207 * kernel is selected as the new color. The new color is modulated by the input
208 * color.
209 */
210 class GrMorphologyEffect : public GrFragmentProcessor {
211 public:
Make(GrSurfaceProxyView view,SkAlphaType srcAlphaType,MorphDirection dir,int radius,MorphType type)212 static std::unique_ptr<GrFragmentProcessor> Make(GrSurfaceProxyView view,
213 SkAlphaType srcAlphaType, MorphDirection dir,
214 int radius, MorphType type) {
215 return std::unique_ptr<GrFragmentProcessor>(
216 new GrMorphologyEffect(std::move(view), srcAlphaType, dir, radius, type, nullptr));
217 }
218
Make(GrSurfaceProxyView view,SkAlphaType srcAlphaType,MorphDirection dir,int radius,MorphType type,const float bounds[2])219 static std::unique_ptr<GrFragmentProcessor> Make(GrSurfaceProxyView view,
220 SkAlphaType srcAlphaType, MorphDirection dir,
221 int radius, MorphType type,
222 const float bounds[2]) {
223 return std::unique_ptr<GrFragmentProcessor>(
224 new GrMorphologyEffect(std::move(view), srcAlphaType, dir, radius, type, bounds));
225 }
226
type() const227 MorphType type() const { return fType; }
useRange() const228 bool useRange() const { return fUseRange; }
range() const229 const float* range() const { return fRange; }
direction() const230 MorphDirection direction() const { return fDirection; }
radius() const231 int radius() const { return fRadius; }
width() const232 int width() const { return 2 * fRadius + 1; }
233
name() const234 const char* name() const override { return "Morphology"; }
235
clone() const236 std::unique_ptr<GrFragmentProcessor> clone() const override {
237 return std::unique_ptr<GrFragmentProcessor>(new GrMorphologyEffect(*this));
238 }
239
240 private:
241 GrCoordTransform fCoordTransform;
242 TextureSampler fTextureSampler;
243 MorphDirection fDirection;
244 int fRadius;
245 MorphType fType;
246 bool fUseRange;
247 float fRange[2];
248
249 GrGLSLFragmentProcessor* onCreateGLSLInstance() const override;
250
251 void onGetGLSLProcessorKey(const GrShaderCaps&, GrProcessorKeyBuilder*) const override;
252
253 bool onIsEqual(const GrFragmentProcessor&) const override;
254
onTextureSampler(int i) const255 const TextureSampler& onTextureSampler(int i) const override { return fTextureSampler; }
256
257 GrMorphologyEffect(GrSurfaceProxyView, SkAlphaType srcAlphaType, MorphDirection, int radius,
258 MorphType, const float range[2]);
259 explicit GrMorphologyEffect(const GrMorphologyEffect&);
260
261 GR_DECLARE_FRAGMENT_PROCESSOR_TEST
262
263 typedef GrFragmentProcessor INHERITED;
264 };
265
266 ///////////////////////////////////////////////////////////////////////////////
267
268 class GrGLMorphologyEffect : public GrGLSLFragmentProcessor {
269 public:
270 void emitCode(EmitArgs&) override;
271
272 static inline void GenKey(const GrProcessor&, const GrShaderCaps&, GrProcessorKeyBuilder*);
273
274 protected:
275 void onSetData(const GrGLSLProgramDataManager&, const GrFragmentProcessor&) override;
276
277 private:
278 GrGLSLProgramDataManager::UniformHandle fPixelSizeUni;
279 GrGLSLProgramDataManager::UniformHandle fRangeUni;
280
281 typedef GrGLSLFragmentProcessor INHERITED;
282 };
283
emitCode(EmitArgs & args)284 void GrGLMorphologyEffect::emitCode(EmitArgs& args) {
285 const GrMorphologyEffect& me = args.fFp.cast<GrMorphologyEffect>();
286
287 GrGLSLUniformHandler* uniformHandler = args.fUniformHandler;
288 fPixelSizeUni = uniformHandler->addUniform(kFragment_GrShaderFlag, kHalf_GrSLType, "PixelSize");
289 const char* pixelSizeInc = uniformHandler->getUniformCStr(fPixelSizeUni);
290 fRangeUni = uniformHandler->addUniform(kFragment_GrShaderFlag, kFloat2_GrSLType, "Range");
291 const char* range = uniformHandler->getUniformCStr(fRangeUni);
292
293 GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;
294 SkString coords2D = fragBuilder->ensureCoords2D(args.fTransformedCoords[0].fVaryingPoint);
295 const char* func;
296 switch (me.type()) {
297 case MorphType::kErode:
298 fragBuilder->codeAppendf("\t\t%s = half4(1, 1, 1, 1);\n", args.fOutputColor);
299 func = "min";
300 break;
301 case MorphType::kDilate:
302 fragBuilder->codeAppendf("\t\t%s = half4(0, 0, 0, 0);\n", args.fOutputColor);
303 func = "max";
304 break;
305 default:
306 SK_ABORT("Unexpected type");
307 func = ""; // suppress warning
308 break;
309 }
310
311 const char* dir;
312 switch (me.direction()) {
313 case MorphDirection::kX:
314 dir = "x";
315 break;
316 case MorphDirection::kY:
317 dir = "y";
318 break;
319 default:
320 SK_ABORT("Unknown filter direction.");
321 dir = ""; // suppress warning
322 }
323
324 int width = me.width();
325
326 // float2 coord = coord2D;
327 fragBuilder->codeAppendf("\t\tfloat2 coord = %s;\n", coords2D.c_str());
328 // coord.x -= radius * pixelSize;
329 fragBuilder->codeAppendf("\t\tcoord.%s -= %d.0 * %s; \n", dir, me.radius(), pixelSizeInc);
330 if (me.useRange()) {
331 // highBound = min(highBound, coord.x + (width-1) * pixelSize);
332 fragBuilder->codeAppendf("\t\tfloat highBound = min(%s.y, coord.%s + %f * %s);",
333 range, dir, float(width - 1), pixelSizeInc);
334 // coord.x = max(lowBound, coord.x);
335 fragBuilder->codeAppendf("\t\tcoord.%s = max(%s.x, coord.%s);", dir, range, dir);
336 }
337 fragBuilder->codeAppendf("\t\tfor (int i = 0; i < %d; i++) {\n", width);
338 fragBuilder->codeAppendf("\t\t\t%s = %s(%s, ", args.fOutputColor, func, args.fOutputColor);
339 fragBuilder->appendTextureLookup(args.fTexSamplers[0], "coord");
340 fragBuilder->codeAppend(");\n");
341 // coord.x += pixelSize;
342 fragBuilder->codeAppendf("\t\t\tcoord.%s += %s;\n", dir, pixelSizeInc);
343 if (me.useRange()) {
344 // coord.x = min(highBound, coord.x);
345 fragBuilder->codeAppendf("\t\t\tcoord.%s = min(highBound, coord.%s);", dir, dir);
346 }
347 fragBuilder->codeAppend("\t\t}\n");
348 fragBuilder->codeAppendf("%s *= %s;\n", args.fOutputColor, args.fInputColor);
349 }
350
GenKey(const GrProcessor & proc,const GrShaderCaps &,GrProcessorKeyBuilder * b)351 void GrGLMorphologyEffect::GenKey(const GrProcessor& proc,
352 const GrShaderCaps&, GrProcessorKeyBuilder* b) {
353 const GrMorphologyEffect& m = proc.cast<GrMorphologyEffect>();
354 uint32_t key = static_cast<uint32_t>(m.radius());
355 key |= (static_cast<uint32_t>(m.type()) << 8);
356 key |= (static_cast<uint32_t>(m.direction()) << 9);
357 if (m.useRange()) {
358 key |= 1 << 10;
359 }
360 b->add32(key);
361 }
362
onSetData(const GrGLSLProgramDataManager & pdman,const GrFragmentProcessor & proc)363 void GrGLMorphologyEffect::onSetData(const GrGLSLProgramDataManager& pdman,
364 const GrFragmentProcessor& proc) {
365 const GrMorphologyEffect& m = proc.cast<GrMorphologyEffect>();
366 const auto& view = m.textureSampler(0).view();
367 GrSurfaceProxy* proxy = view.proxy();
368 GrTexture& texture = *proxy->peekTexture();
369
370 float pixelSize = 0.0f;
371 switch (m.direction()) {
372 case MorphDirection::kX:
373 pixelSize = 1.0f / texture.width();
374 break;
375 case MorphDirection::kY:
376 pixelSize = 1.0f / texture.height();
377 break;
378 default:
379 SK_ABORT("Unknown filter direction.");
380 }
381 pdman.set1f(fPixelSizeUni, pixelSize);
382
383 if (m.useRange()) {
384 const float* range = m.range();
385 if (MorphDirection::kY == m.direction() &&
386 view.origin() == kBottomLeft_GrSurfaceOrigin) {
387 pdman.set2f(fRangeUni, 1.0f - (range[1]*pixelSize), 1.0f - (range[0]*pixelSize));
388 } else {
389 pdman.set2f(fRangeUni, range[0] * pixelSize, range[1] * pixelSize);
390 }
391 }
392 }
393
394 ///////////////////////////////////////////////////////////////////////////////
395
GrMorphologyEffect(GrSurfaceProxyView view,SkAlphaType srcAlphaType,MorphDirection direction,int radius,MorphType type,const float range[2])396 GrMorphologyEffect::GrMorphologyEffect(GrSurfaceProxyView view,
397 SkAlphaType srcAlphaType,
398 MorphDirection direction,
399 int radius,
400 MorphType type,
401 const float range[2])
402 : INHERITED(kGrMorphologyEffect_ClassID, ModulateForClampedSamplerOptFlags(srcAlphaType))
403 , fCoordTransform(view.proxy(), view.origin())
404 , fTextureSampler(std::move(view))
405 , fDirection(direction)
406 , fRadius(radius)
407 , fType(type)
408 , fUseRange(SkToBool(range)) {
409 // Make sure the sampler's ctor uses the clamp wrap mode
410 SkASSERT(fTextureSampler.samplerState().wrapModeX() == GrSamplerState::WrapMode::kClamp &&
411 fTextureSampler.samplerState().wrapModeY() == GrSamplerState::WrapMode::kClamp);
412 this->addCoordTransform(&fCoordTransform);
413 this->setTextureSamplerCnt(1);
414 if (fUseRange) {
415 fRange[0] = range[0];
416 fRange[1] = range[1];
417 }
418 }
419
GrMorphologyEffect(const GrMorphologyEffect & that)420 GrMorphologyEffect::GrMorphologyEffect(const GrMorphologyEffect& that)
421 : INHERITED(kGrMorphologyEffect_ClassID, that.optimizationFlags())
422 , fCoordTransform(that.fCoordTransform)
423 , fTextureSampler(that.fTextureSampler)
424 , fDirection(that.fDirection)
425 , fRadius(that.fRadius)
426 , fType(that.fType)
427 , fUseRange(that.fUseRange) {
428 this->addCoordTransform(&fCoordTransform);
429 this->setTextureSamplerCnt(1);
430 if (that.fUseRange) {
431 fRange[0] = that.fRange[0];
432 fRange[1] = that.fRange[1];
433 }
434 }
435
onGetGLSLProcessorKey(const GrShaderCaps & caps,GrProcessorKeyBuilder * b) const436 void GrMorphologyEffect::onGetGLSLProcessorKey(const GrShaderCaps& caps,
437 GrProcessorKeyBuilder* b) const {
438 GrGLMorphologyEffect::GenKey(*this, caps, b);
439 }
440
onCreateGLSLInstance() const441 GrGLSLFragmentProcessor* GrMorphologyEffect::onCreateGLSLInstance() const {
442 return new GrGLMorphologyEffect;
443 }
onIsEqual(const GrFragmentProcessor & sBase) const444 bool GrMorphologyEffect::onIsEqual(const GrFragmentProcessor& sBase) const {
445 const GrMorphologyEffect& s = sBase.cast<GrMorphologyEffect>();
446 return (this->radius() == s.radius() &&
447 this->direction() == s.direction() &&
448 this->useRange() == s.useRange() &&
449 this->type() == s.type());
450 }
451
452 ///////////////////////////////////////////////////////////////////////////////
453
454 GR_DEFINE_FRAGMENT_PROCESSOR_TEST(GrMorphologyEffect);
455
456 #if GR_TEST_UTILS
TestCreate(GrProcessorTestData * d)457 std::unique_ptr<GrFragmentProcessor> GrMorphologyEffect::TestCreate(GrProcessorTestData* d) {
458 auto [view, ct, at] = d->randomView();
459
460 MorphDirection dir = d->fRandom->nextBool() ? MorphDirection::kX : MorphDirection::kY;
461 static const int kMaxRadius = 10;
462 int radius = d->fRandom->nextRangeU(1, kMaxRadius);
463 MorphType type = d->fRandom->nextBool() ? MorphType::kErode : MorphType::kDilate;
464 return GrMorphologyEffect::Make(std::move(view), at, dir, radius, type);
465 }
466 #endif
467
apply_morphology_rect(GrRenderTargetContext * renderTargetContext,const GrClip & clip,GrSurfaceProxyView view,SkAlphaType srcAlphaType,const SkIRect & srcRect,const SkIRect & dstRect,int radius,MorphType morphType,const float bounds[2],MorphDirection direction)468 static void apply_morphology_rect(GrRenderTargetContext* renderTargetContext,
469 const GrClip& clip,
470 GrSurfaceProxyView view,
471 SkAlphaType srcAlphaType,
472 const SkIRect& srcRect,
473 const SkIRect& dstRect,
474 int radius,
475 MorphType morphType,
476 const float bounds[2],
477 MorphDirection direction) {
478 GrPaint paint;
479 paint.addColorFragmentProcessor(GrMorphologyEffect::Make(std::move(view), srcAlphaType,
480 direction, radius, morphType, bounds));
481 paint.setPorterDuffXPFactory(SkBlendMode::kSrc);
482 renderTargetContext->fillRectToRect(clip, std::move(paint), GrAA::kNo, SkMatrix::I(),
483 SkRect::Make(dstRect), SkRect::Make(srcRect));
484 }
485
apply_morphology_rect_no_bounds(GrRenderTargetContext * renderTargetContext,const GrClip & clip,GrSurfaceProxyView view,SkAlphaType srcAlphaType,const SkIRect & srcRect,const SkIRect & dstRect,int radius,MorphType morphType,MorphDirection direction)486 static void apply_morphology_rect_no_bounds(GrRenderTargetContext* renderTargetContext,
487 const GrClip& clip,
488 GrSurfaceProxyView view,
489 SkAlphaType srcAlphaType,
490 const SkIRect& srcRect,
491 const SkIRect& dstRect,
492 int radius,
493 MorphType morphType,
494 MorphDirection direction) {
495 GrPaint paint;
496 paint.addColorFragmentProcessor(
497 GrMorphologyEffect::Make(std::move(view), srcAlphaType, direction, radius, morphType));
498 paint.setPorterDuffXPFactory(SkBlendMode::kSrc);
499 renderTargetContext->fillRectToRect(clip, std::move(paint), GrAA::kNo, SkMatrix::I(),
500 SkRect::Make(dstRect), SkRect::Make(srcRect));
501 }
502
apply_morphology_pass(GrRenderTargetContext * renderTargetContext,const GrClip & clip,GrSurfaceProxyView view,SkAlphaType srcAlphaType,const SkIRect & srcRect,const SkIRect & dstRect,int radius,MorphType morphType,MorphDirection direction)503 static void apply_morphology_pass(GrRenderTargetContext* renderTargetContext,
504 const GrClip& clip,
505 GrSurfaceProxyView view,
506 SkAlphaType srcAlphaType,
507 const SkIRect& srcRect,
508 const SkIRect& dstRect,
509 int radius,
510 MorphType morphType,
511 MorphDirection direction) {
512 float bounds[2] = { 0.0f, 1.0f };
513 SkIRect lowerSrcRect = srcRect, lowerDstRect = dstRect;
514 SkIRect middleSrcRect = srcRect, middleDstRect = dstRect;
515 SkIRect upperSrcRect = srcRect, upperDstRect = dstRect;
516 if (direction == MorphDirection::kX) {
517 bounds[0] = SkIntToScalar(srcRect.left()) + 0.5f;
518 bounds[1] = SkIntToScalar(srcRect.right()) - 0.5f;
519 lowerSrcRect.fRight = srcRect.left() + radius;
520 lowerDstRect.fRight = dstRect.left() + radius;
521 upperSrcRect.fLeft = srcRect.right() - radius;
522 upperDstRect.fLeft = dstRect.right() - radius;
523 middleSrcRect.inset(radius, 0);
524 middleDstRect.inset(radius, 0);
525 } else {
526 bounds[0] = SkIntToScalar(srcRect.top()) + 0.5f;
527 bounds[1] = SkIntToScalar(srcRect.bottom()) - 0.5f;
528 lowerSrcRect.fBottom = srcRect.top() + radius;
529 lowerDstRect.fBottom = dstRect.top() + radius;
530 upperSrcRect.fTop = srcRect.bottom() - radius;
531 upperDstRect.fTop = dstRect.bottom() - radius;
532 middleSrcRect.inset(0, radius);
533 middleDstRect.inset(0, radius);
534 }
535 if (middleSrcRect.width() <= 0) {
536 // radius covers srcRect; use bounds over entire draw
537 apply_morphology_rect(renderTargetContext, clip, std::move(view), srcAlphaType, srcRect,
538 dstRect, radius, morphType, bounds, direction);
539 } else {
540 // Draw upper and lower margins with bounds; middle without.
541 apply_morphology_rect(renderTargetContext, clip, view, srcAlphaType, lowerSrcRect,
542 lowerDstRect, radius, morphType, bounds, direction);
543 apply_morphology_rect(renderTargetContext, clip, view, srcAlphaType, upperSrcRect,
544 upperDstRect, radius, morphType, bounds, direction);
545 apply_morphology_rect_no_bounds(renderTargetContext, clip, std::move(view),
546 srcAlphaType, middleSrcRect, middleDstRect, radius,
547 morphType, direction);
548 }
549 }
550
apply_morphology(GrRecordingContext * context,SkSpecialImage * input,const SkIRect & rect,MorphType morphType,SkISize radius,const SkImageFilter_Base::Context & ctx)551 static sk_sp<SkSpecialImage> apply_morphology(
552 GrRecordingContext* context, SkSpecialImage* input, const SkIRect& rect,
553 MorphType morphType, SkISize radius, const SkImageFilter_Base::Context& ctx) {
554 GrSurfaceProxyView srcView = input->view(context);
555 SkAlphaType srcAlphaType = input->alphaType();
556 SkASSERT(srcView.asTextureProxy());
557 sk_sp<SkColorSpace> colorSpace = ctx.refColorSpace();
558 GrColorType colorType = ctx.grColorType();
559
560 GrSurfaceProxy* proxy = srcView.proxy();
561
562 // setup new clip
563 const GrFixedClip clip(SkIRect::MakeSize(proxy->dimensions()));
564
565 const SkIRect dstRect = SkIRect::MakeWH(rect.width(), rect.height());
566 SkIRect srcRect = rect;
567 // Map into proxy space
568 srcRect.offset(input->subset().x(), input->subset().y());
569 SkASSERT(radius.width() > 0 || radius.height() > 0);
570
571 if (radius.fWidth > 0) {
572 auto dstRTContext = GrRenderTargetContext::Make(
573 context, colorType, colorSpace, SkBackingFit::kApprox, rect.size(), 1,
574 GrMipMapped::kNo, proxy->isProtected(), kBottomLeft_GrSurfaceOrigin);
575 if (!dstRTContext) {
576 return nullptr;
577 }
578
579 apply_morphology_pass(dstRTContext.get(), clip, std::move(srcView), srcAlphaType,
580 srcRect, dstRect, radius.fWidth, morphType, MorphDirection::kX);
581 SkIRect clearRect = SkIRect::MakeXYWH(dstRect.fLeft, dstRect.fBottom,
582 dstRect.width(), radius.fHeight);
583 SkPMColor4f clearColor = MorphType::kErode == morphType
584 ? SK_PMColor4fWHITE : SK_PMColor4fTRANSPARENT;
585 dstRTContext->clear(&clearRect, clearColor, GrRenderTargetContext::CanClearFullscreen::kNo);
586
587 srcView = dstRTContext->readSurfaceView();
588 srcAlphaType = dstRTContext->colorInfo().alphaType();
589 srcRect = dstRect;
590 }
591 if (radius.fHeight > 0) {
592 auto dstRTContext = GrRenderTargetContext::Make(
593 context, colorType, colorSpace, SkBackingFit::kApprox, rect.size(), 1,
594 GrMipMapped::kNo, srcView.proxy()->isProtected(), kBottomLeft_GrSurfaceOrigin);
595 if (!dstRTContext) {
596 return nullptr;
597 }
598
599 apply_morphology_pass(dstRTContext.get(), clip, std::move(srcView), srcAlphaType,
600 srcRect, dstRect, radius.fHeight, morphType, MorphDirection::kY);
601
602 srcView = dstRTContext->readSurfaceView();
603 }
604
605 return SkSpecialImage::MakeDeferredFromGpu(context,
606 SkIRect::MakeWH(rect.width(), rect.height()),
607 kNeedNewImageUniqueID_SpecialImage,
608 std::move(srcView), colorType,
609 std::move(colorSpace), &input->props());
610 }
611 #endif
612
613 namespace {
614
615 #if SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_SSE2
616 template<MorphType type, MorphDirection direction>
morph(const SkPMColor * src,SkPMColor * dst,int radius,int width,int height,int srcStride,int dstStride)617 static void morph(const SkPMColor* src, SkPMColor* dst,
618 int radius, int width, int height, int srcStride, int dstStride) {
619 const int srcStrideX = direction == MorphDirection::kX ? 1 : srcStride;
620 const int dstStrideX = direction == MorphDirection::kX ? 1 : dstStride;
621 const int srcStrideY = direction == MorphDirection::kX ? srcStride : 1;
622 const int dstStrideY = direction == MorphDirection::kX ? dstStride : 1;
623 radius = std::min(radius, width - 1);
624 const SkPMColor* upperSrc = src + radius * srcStrideX;
625 for (int x = 0; x < width; ++x) {
626 const SkPMColor* lp = src;
627 const SkPMColor* up = upperSrc;
628 SkPMColor* dptr = dst;
629 for (int y = 0; y < height; ++y) {
630 __m128i extreme = (type == MorphType::kDilate) ? _mm_setzero_si128()
631 : _mm_set1_epi32(0xFFFFFFFF);
632 for (const SkPMColor* p = lp; p <= up; p += srcStrideX) {
633 __m128i src_pixel = _mm_cvtsi32_si128(*p);
634 extreme = (type == MorphType::kDilate) ? _mm_max_epu8(src_pixel, extreme)
635 : _mm_min_epu8(src_pixel, extreme);
636 }
637 *dptr = _mm_cvtsi128_si32(extreme);
638 dptr += dstStrideY;
639 lp += srcStrideY;
640 up += srcStrideY;
641 }
642 if (x >= radius) { src += srcStrideX; }
643 if (x + radius < width - 1) { upperSrc += srcStrideX; }
644 dst += dstStrideX;
645 }
646 }
647
648 #elif defined(SK_ARM_HAS_NEON)
649 template<MorphType type, MorphDirection direction>
650 static void morph(const SkPMColor* src, SkPMColor* dst,
651 int radius, int width, int height, int srcStride, int dstStride) {
652 const int srcStrideX = direction == MorphDirection::kX ? 1 : srcStride;
653 const int dstStrideX = direction == MorphDirection::kX ? 1 : dstStride;
654 const int srcStrideY = direction == MorphDirection::kX ? srcStride : 1;
655 const int dstStrideY = direction == MorphDirection::kX ? dstStride : 1;
656 radius = std::min(radius, width - 1);
657 const SkPMColor* upperSrc = src + radius * srcStrideX;
658 for (int x = 0; x < width; ++x) {
659 const SkPMColor* lp = src;
660 const SkPMColor* up = upperSrc;
661 SkPMColor* dptr = dst;
662 for (int y = 0; y < height; ++y) {
663 uint8x8_t extreme = vdup_n_u8(type == MorphType::kDilate ? 0 : 255);
664 for (const SkPMColor* p = lp; p <= up; p += srcStrideX) {
665 uint8x8_t src_pixel = vreinterpret_u8_u32(vdup_n_u32(*p));
666 extreme = (type == MorphType::kDilate) ? vmax_u8(src_pixel, extreme)
667 : vmin_u8(src_pixel, extreme);
668 }
669 *dptr = vget_lane_u32(vreinterpret_u32_u8(extreme), 0);
670 dptr += dstStrideY;
671 lp += srcStrideY;
672 up += srcStrideY;
673 }
674 if (x >= radius) src += srcStrideX;
675 if (x + radius < width - 1) upperSrc += srcStrideX;
676 dst += dstStrideX;
677 }
678 }
679
680 #else
681 template<MorphType type, MorphDirection direction>
682 static void morph(const SkPMColor* src, SkPMColor* dst,
683 int radius, int width, int height, int srcStride, int dstStride) {
684 const int srcStrideX = direction == MorphDirection::kX ? 1 : srcStride;
685 const int dstStrideX = direction == MorphDirection::kX ? 1 : dstStride;
686 const int srcStrideY = direction == MorphDirection::kX ? srcStride : 1;
687 const int dstStrideY = direction == MorphDirection::kX ? dstStride : 1;
688 radius = std::min(radius, width - 1);
689 const SkPMColor* upperSrc = src + radius * srcStrideX;
690 for (int x = 0; x < width; ++x) {
691 const SkPMColor* lp = src;
692 const SkPMColor* up = upperSrc;
693 SkPMColor* dptr = dst;
694 for (int y = 0; y < height; ++y) {
695 // If we're maxing (dilate), start from 0; if minning (erode), start from 255.
696 const int start = (type == MorphType::kDilate) ? 0 : 255;
697 int B = start, G = start, R = start, A = start;
698 for (const SkPMColor* p = lp; p <= up; p += srcStrideX) {
699 int b = SkGetPackedB32(*p),
700 g = SkGetPackedG32(*p),
701 r = SkGetPackedR32(*p),
702 a = SkGetPackedA32(*p);
703 if (type == MorphType::kDilate) {
704 B = std::max(b, B);
705 G = std::max(g, G);
706 R = std::max(r, R);
707 A = std::max(a, A);
708 } else {
709 B = std::min(b, B);
710 G = std::min(g, G);
711 R = std::min(r, R);
712 A = std::min(a, A);
713 }
714 }
715 *dptr = SkPackARGB32(A, R, G, B);
716 dptr += dstStrideY;
717 lp += srcStrideY;
718 up += srcStrideY;
719 }
720 if (x >= radius) { src += srcStrideX; }
721 if (x + radius < width - 1) { upperSrc += srcStrideX; }
722 dst += dstStrideX;
723 }
724 }
725 #endif
726 } // namespace
727
onFilterImage(const Context & ctx,SkIPoint * offset) const728 sk_sp<SkSpecialImage> SkMorphologyImageFilterImpl::onFilterImage(const Context& ctx,
729 SkIPoint* offset) const {
730 SkIPoint inputOffset = SkIPoint::Make(0, 0);
731 sk_sp<SkSpecialImage> input(this->filterInput(0, ctx, &inputOffset));
732 if (!input) {
733 return nullptr;
734 }
735
736 SkIRect bounds;
737 input = this->applyCropRectAndPad(this->mapContext(ctx), input.get(), &inputOffset, &bounds);
738 if (!input) {
739 return nullptr;
740 }
741
742 SkSize radius = mappedRadius(ctx.ctm());
743 int width = SkScalarFloorToInt(radius.width());
744 int height = SkScalarFloorToInt(radius.height());
745
746 // Width (or height) must fit in a signed 32-bit int to avoid UBSAN issues (crbug.com/1018190)
747 constexpr int kMaxRadius = (std::numeric_limits<int>::max() - 1) / 2;
748
749 if (width < 0 || height < 0 || width > kMaxRadius || height > kMaxRadius) {
750 return nullptr;
751 }
752
753 SkIRect srcBounds = bounds;
754 srcBounds.offset(-inputOffset);
755
756 if (0 == width && 0 == height) {
757 offset->fX = bounds.left();
758 offset->fY = bounds.top();
759 return input->makeSubset(srcBounds);
760 }
761
762 #if SK_SUPPORT_GPU
763 if (ctx.gpuBacked()) {
764 auto context = ctx.getContext();
765
766 // Ensure the input is in the destination color space. Typically applyCropRect will have
767 // called pad_image to account for our dilation of bounds, so the result will already be
768 // moved to the destination color space. If a filter DAG avoids that, then we use this
769 // fall-back, which saves us from having to do the xform during the filter itself.
770 input = ImageToColorSpace(input.get(), ctx.colorType(), ctx.colorSpace());
771
772 sk_sp<SkSpecialImage> result(apply_morphology(context, input.get(), srcBounds, fType,
773 SkISize::Make(width, height), ctx));
774 if (result) {
775 offset->fX = bounds.left();
776 offset->fY = bounds.top();
777 }
778 return result;
779 }
780 #endif
781
782 SkBitmap inputBM;
783
784 if (!input->getROPixels(&inputBM)) {
785 return nullptr;
786 }
787
788 if (inputBM.colorType() != kN32_SkColorType) {
789 return nullptr;
790 }
791
792 SkImageInfo info = SkImageInfo::Make(bounds.size(), inputBM.colorType(), inputBM.alphaType());
793
794 SkBitmap dst;
795 if (!dst.tryAllocPixels(info)) {
796 return nullptr;
797 }
798
799 SkMorphologyImageFilterImpl::Proc procX, procY;
800
801 if (MorphType::kDilate == fType) {
802 procX = &morph<MorphType::kDilate, MorphDirection::kX>;
803 procY = &morph<MorphType::kDilate, MorphDirection::kY>;
804 } else {
805 procX = &morph<MorphType::kErode, MorphDirection::kX>;
806 procY = &morph<MorphType::kErode, MorphDirection::kY>;
807 }
808
809 if (width > 0 && height > 0) {
810 SkBitmap tmp;
811 if (!tmp.tryAllocPixels(info)) {
812 return nullptr;
813 }
814
815 call_proc_X(procX, inputBM, &tmp, width, srcBounds);
816 SkIRect tmpBounds = SkIRect::MakeWH(srcBounds.width(), srcBounds.height());
817 call_proc_Y(procY,
818 tmp.getAddr32(tmpBounds.left(), tmpBounds.top()), tmp.rowBytesAsPixels(),
819 &dst, height, tmpBounds);
820 } else if (width > 0) {
821 call_proc_X(procX, inputBM, &dst, width, srcBounds);
822 } else if (height > 0) {
823 call_proc_Y(procY,
824 inputBM.getAddr32(srcBounds.left(), srcBounds.top()),
825 inputBM.rowBytesAsPixels(),
826 &dst, height, srcBounds);
827 }
828 offset->fX = bounds.left();
829 offset->fY = bounds.top();
830
831 return SkSpecialImage::MakeFromRaster(SkIRect::MakeWH(bounds.width(), bounds.height()),
832 dst, ctx.surfaceProps());
833 }
834