2 * Copyright 2012 The Android Open Source Project
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
8 #include "SkMorphologyImageFilter.h"
10 #include "SkColorPriv.h"
11 #include "SkFlattenableBuffers.h"
13 #include "SkMorphology_opts.h"
15 #include "GrContext.h"
16 #include "GrTexture.h"
17 #include "GrTBackendEffectFactory.h"
18 #include "gl/GrGLEffect.h"
19 #include "effects/Gr1DKernelEffect.h"
20 #include "SkImageFilterUtils.h"
23 SkMorphologyImageFilter::SkMorphologyImageFilter(SkFlattenableReadBuffer& buffer)
24 : INHERITED(1, buffer) {
25 fRadius.fWidth = buffer.readInt();
26 fRadius.fHeight = buffer.readInt();
27 buffer.validate((fRadius.fWidth >= 0) &&
28 (fRadius.fHeight >= 0));
31 SkMorphologyImageFilter::SkMorphologyImageFilter(int radiusX,
34 const CropRect* cropRect)
35 : INHERITED(input, cropRect), fRadius(SkISize::Make(radiusX, radiusY)) {
39 void SkMorphologyImageFilter::flatten(SkFlattenableWriteBuffer& buffer) const {
40 this->INHERITED::flatten(buffer);
41 buffer.writeInt(fRadius.fWidth);
42 buffer.writeInt(fRadius.fHeight);
49 template<MorphDirection direction>
50 static void erode(const SkPMColor* src, SkPMColor* dst,
51 int radius, int width, int height,
52 int srcStride, int dstStride)
54 const int srcStrideX = direction == kX ? 1 : srcStride;
55 const int dstStrideX = direction == kX ? 1 : dstStride;
56 const int srcStrideY = direction == kX ? srcStride : 1;
57 const int dstStrideY = direction == kX ? dstStride : 1;
58 radius = SkMin32(radius, width - 1);
59 const SkPMColor* upperSrc = src + radius * srcStrideX;
60 for (int x = 0; x < width; ++x) {
61 const SkPMColor* lp = src;
62 const SkPMColor* up = upperSrc;
63 SkPMColor* dptr = dst;
64 for (int y = 0; y < height; ++y) {
65 int minB = 255, minG = 255, minR = 255, minA = 255;
66 for (const SkPMColor* p = lp; p <= up; p += srcStrideX) {
67 int b = SkGetPackedB32(*p);
68 int g = SkGetPackedG32(*p);
69 int r = SkGetPackedR32(*p);
70 int a = SkGetPackedA32(*p);
71 if (b < minB) minB = b;
72 if (g < minG) minG = g;
73 if (r < minR) minR = r;
74 if (a < minA) minA = a;
76 *dptr = SkPackARGB32(minA, minR, minG, minB);
81 if (x >= radius) src += srcStrideX;
82 if (x + radius < width - 1) upperSrc += srcStrideX;
87 template<MorphDirection direction>
88 static void dilate(const SkPMColor* src, SkPMColor* dst,
89 int radius, int width, int height,
90 int srcStride, int dstStride)
92 const int srcStrideX = direction == kX ? 1 : srcStride;
93 const int dstStrideX = direction == kX ? 1 : dstStride;
94 const int srcStrideY = direction == kX ? srcStride : 1;
95 const int dstStrideY = direction == kX ? dstStride : 1;
96 radius = SkMin32(radius, width - 1);
97 const SkPMColor* upperSrc = src + radius * srcStrideX;
98 for (int x = 0; x < width; ++x) {
99 const SkPMColor* lp = src;
100 const SkPMColor* up = upperSrc;
101 SkPMColor* dptr = dst;
102 for (int y = 0; y < height; ++y) {
103 int maxB = 0, maxG = 0, maxR = 0, maxA = 0;
104 for (const SkPMColor* p = lp; p <= up; p += srcStrideX) {
105 int b = SkGetPackedB32(*p);
106 int g = SkGetPackedG32(*p);
107 int r = SkGetPackedR32(*p);
108 int a = SkGetPackedA32(*p);
109 if (b > maxB) maxB = b;
110 if (g > maxG) maxG = g;
111 if (r > maxR) maxR = r;
112 if (a > maxA) maxA = a;
114 *dptr = SkPackARGB32(maxA, maxR, maxG, maxB);
119 if (x >= radius) src += srcStrideX;
120 if (x + radius < width - 1) upperSrc += srcStrideX;
125 static void callProcX(SkMorphologyImageFilter::Proc procX, const SkBitmap& src, SkBitmap* dst, int radiusX, const SkIRect& bounds)
127 procX(src.getAddr32(bounds.left(), bounds.top()), dst->getAddr32(0, 0),
128 radiusX, bounds.width(), bounds.height(),
129 src.rowBytesAsPixels(), dst->rowBytesAsPixels());
132 static void callProcY(SkMorphologyImageFilter::Proc procY, const SkBitmap& src, SkBitmap* dst, int radiusY, const SkIRect& bounds)
134 procY(src.getAddr32(bounds.left(), bounds.top()), dst->getAddr32(0, 0),
135 radiusY, bounds.height(), bounds.width(),
136 src.rowBytesAsPixels(), dst->rowBytesAsPixels());
139 bool SkMorphologyImageFilter::filterImageGeneric(SkMorphologyImageFilter::Proc procX,
140 SkMorphologyImageFilter::Proc procY,
142 const SkBitmap& source,
146 SkBitmap src = source;
147 SkIPoint srcOffset = SkIPoint::Make(0, 0);
148 if (getInput(0) && !getInput(0)->filterImage(proxy, source, ctm, &src, &srcOffset)) {
152 if (src.config() != SkBitmap::kARGB_8888_Config) {
157 src.getBounds(&bounds);
158 bounds.offset(srcOffset);
159 if (!this->applyCropRect(&bounds, ctm)) {
163 SkAutoLockPixels alp(src);
164 if (!src.getPixels()) {
168 dst->setConfig(src.config(), bounds.width(), bounds.height());
170 if (!dst->getPixels()) {
174 SkVector radius = SkVector::Make(SkIntToScalar(this->radius().width()),
175 SkIntToScalar(this->radius().height()));
176 ctm.mapVectors(&radius, 1);
177 int width = SkScalarFloorToInt(radius.fX);
178 int height = SkScalarFloorToInt(radius.fY);
180 if (width < 0 || height < 0) {
184 SkIRect srcBounds = bounds;
185 srcBounds.offset(-srcOffset);
187 if (width == 0 && height == 0) {
188 src.extractSubset(dst, srcBounds);
189 offset->fX = bounds.left();
190 offset->fY = bounds.top();
195 temp.setConfig(dst->config(), dst->width(), dst->height());
196 if (!temp.allocPixels()) {
200 if (width > 0 && height > 0) {
201 callProcX(procX, src, &temp, width, srcBounds);
202 SkIRect tmpBounds = SkIRect::MakeWH(srcBounds.width(), srcBounds.height());
203 callProcY(procY, temp, dst, height, tmpBounds);
204 } else if (width > 0) {
205 callProcX(procX, src, dst, width, srcBounds);
206 } else if (height > 0) {
207 callProcY(procY, src, dst, height, srcBounds);
209 offset->fX = bounds.left();
210 offset->fY = bounds.top();
214 bool SkErodeImageFilter::onFilterImage(Proxy* proxy,
215 const SkBitmap& source, const SkMatrix& ctm,
216 SkBitmap* dst, SkIPoint* offset) {
217 Proc erodeXProc = SkMorphologyGetPlatformProc(kErodeX_SkMorphologyProcType);
219 erodeXProc = erode<kX>;
221 Proc erodeYProc = SkMorphologyGetPlatformProc(kErodeY_SkMorphologyProcType);
223 erodeYProc = erode<kY>;
225 return this->filterImageGeneric(erodeXProc, erodeYProc, proxy, source, ctm, dst, offset);
228 bool SkDilateImageFilter::onFilterImage(Proxy* proxy,
229 const SkBitmap& source, const SkMatrix& ctm,
230 SkBitmap* dst, SkIPoint* offset) {
231 Proc dilateXProc = SkMorphologyGetPlatformProc(kDilateX_SkMorphologyProcType);
233 dilateXProc = dilate<kX>;
235 Proc dilateYProc = SkMorphologyGetPlatformProc(kDilateY_SkMorphologyProcType);
237 dilateYProc = dilate<kY>;
239 return this->filterImageGeneric(dilateXProc, dilateYProc, proxy, source, ctm, dst, offset);
244 ///////////////////////////////////////////////////////////////////////////////
246 class GrGLMorphologyEffect;
249 * Morphology effects. Depending upon the type of morphology, either the
250 * component-wise min (Erode_Type) or max (Dilate_Type) of all pixels in the
251 * kernel is selected as the new color. The new color is modulated by the input
254 class GrMorphologyEffect : public Gr1DKernelEffect {
258 enum MorphologyType {
259 kErode_MorphologyType,
260 kDilate_MorphologyType,
263 static GrEffectRef* Create(GrTexture* tex, Direction dir, int radius, MorphologyType type) {
264 AutoEffectUnref effect(SkNEW_ARGS(GrMorphologyEffect, (tex, dir, radius, type)));
265 return CreateEffectRef(effect);
268 virtual ~GrMorphologyEffect();
270 MorphologyType type() const { return fType; }
272 static const char* Name() { return "Morphology"; }
274 typedef GrGLMorphologyEffect GLEffect;
276 virtual const GrBackendEffectFactory& getFactory() const SK_OVERRIDE;
277 virtual void getConstantColorComponents(GrColor* color, uint32_t* validFlags) const SK_OVERRIDE;
281 MorphologyType fType;
284 virtual bool onIsEqual(const GrEffect&) const SK_OVERRIDE;
286 GrMorphologyEffect(GrTexture*, Direction, int radius, MorphologyType);
288 GR_DECLARE_EFFECT_TEST;
290 typedef Gr1DKernelEffect INHERITED;
293 ///////////////////////////////////////////////////////////////////////////////
295 class GrGLMorphologyEffect : public GrGLEffect {
297 GrGLMorphologyEffect (const GrBackendEffectFactory&, const GrDrawEffect&);
299 virtual void emitCode(GrGLShaderBuilder*,
302 const char* outputColor,
303 const char* inputColor,
304 const TransformedCoordsArray&,
305 const TextureSamplerArray&) SK_OVERRIDE;
307 static inline EffectKey GenKey(const GrDrawEffect&, const GrGLCaps&);
309 virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE;
312 int width() const { return GrMorphologyEffect::WidthFromRadius(fRadius); }
315 GrMorphologyEffect::MorphologyType fType;
316 GrGLUniformManager::UniformHandle fImageIncrementUni;
318 typedef GrGLEffect INHERITED;
321 GrGLMorphologyEffect::GrGLMorphologyEffect(const GrBackendEffectFactory& factory,
322 const GrDrawEffect& drawEffect)
323 : INHERITED(factory) {
324 const GrMorphologyEffect& m = drawEffect.castEffect<GrMorphologyEffect>();
325 fRadius = m.radius();
329 void GrGLMorphologyEffect::emitCode(GrGLShaderBuilder* builder,
332 const char* outputColor,
333 const char* inputColor,
334 const TransformedCoordsArray& coords,
335 const TextureSamplerArray& samplers) {
336 SkString coords2D = builder->ensureFSCoords2D(coords, 0);
337 fImageIncrementUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
338 kVec2f_GrSLType, "ImageIncrement");
342 case GrMorphologyEffect::kErode_MorphologyType:
343 builder->fsCodeAppendf("\t\t%s = vec4(1, 1, 1, 1);\n", outputColor);
346 case GrMorphologyEffect::kDilate_MorphologyType:
347 builder->fsCodeAppendf("\t\t%s = vec4(0, 0, 0, 0);\n", outputColor);
351 GrCrash("Unexpected type");
352 func = ""; // suppress warning
355 const char* imgInc = builder->getUniformCStr(fImageIncrementUni);
357 builder->fsCodeAppendf("\t\tvec2 coord = %s - %d.0 * %s;\n", coords2D.c_str(), fRadius, imgInc);
358 builder->fsCodeAppendf("\t\tfor (int i = 0; i < %d; i++) {\n", this->width());
359 builder->fsCodeAppendf("\t\t\t%s = %s(%s, ", outputColor, func, outputColor);
360 builder->fsAppendTextureLookup(samplers[0], "coord");
361 builder->fsCodeAppend(");\n");
362 builder->fsCodeAppendf("\t\t\tcoord += %s;\n", imgInc);
363 builder->fsCodeAppend("\t\t}\n");
365 GrGLSLMulVarBy4f(&modulate, 2, outputColor, inputColor);
366 builder->fsCodeAppend(modulate.c_str());
369 GrGLEffect::EffectKey GrGLMorphologyEffect::GenKey(const GrDrawEffect& drawEffect,
371 const GrMorphologyEffect& m = drawEffect.castEffect<GrMorphologyEffect>();
372 EffectKey key = static_cast<EffectKey>(m.radius());
373 key |= (m.type() << 8);
377 void GrGLMorphologyEffect::setData(const GrGLUniformManager& uman,
378 const GrDrawEffect& drawEffect) {
379 const Gr1DKernelEffect& kern = drawEffect.castEffect<Gr1DKernelEffect>();
380 GrTexture& texture = *kern.texture(0);
381 // the code we generated was for a specific kernel radius
382 SkASSERT(kern.radius() == fRadius);
383 float imageIncrement[2] = { 0 };
384 switch (kern.direction()) {
385 case Gr1DKernelEffect::kX_Direction:
386 imageIncrement[0] = 1.0f / texture.width();
388 case Gr1DKernelEffect::kY_Direction:
389 imageIncrement[1] = 1.0f / texture.height();
392 GrCrash("Unknown filter direction.");
394 uman.set2fv(fImageIncrementUni, 1, imageIncrement);
397 ///////////////////////////////////////////////////////////////////////////////
399 GrMorphologyEffect::GrMorphologyEffect(GrTexture* texture,
403 : Gr1DKernelEffect(texture, direction, radius)
407 GrMorphologyEffect::~GrMorphologyEffect() {
410 const GrBackendEffectFactory& GrMorphologyEffect::getFactory() const {
411 return GrTBackendEffectFactory<GrMorphologyEffect>::getInstance();
414 bool GrMorphologyEffect::onIsEqual(const GrEffect& sBase) const {
415 const GrMorphologyEffect& s = CastEffect<GrMorphologyEffect>(sBase);
416 return (this->texture(0) == s.texture(0) &&
417 this->radius() == s.radius() &&
418 this->direction() == s.direction() &&
419 this->type() == s.type());
422 void GrMorphologyEffect::getConstantColorComponents(GrColor* color, uint32_t* validFlags) const {
423 // This is valid because the color components of the result of the kernel all come
424 // exactly from existing values in the source texture.
425 this->updateConstantColorComponentsForModulation(color, validFlags);
428 ///////////////////////////////////////////////////////////////////////////////
430 GR_DEFINE_EFFECT_TEST(GrMorphologyEffect);
432 GrEffectRef* GrMorphologyEffect::TestCreate(SkRandom* random,
434 const GrDrawTargetCaps&,
435 GrTexture* textures[]) {
436 int texIdx = random->nextBool() ? GrEffectUnitTest::kSkiaPMTextureIdx :
437 GrEffectUnitTest::kAlphaTextureIdx;
438 Direction dir = random->nextBool() ? kX_Direction : kY_Direction;
439 static const int kMaxRadius = 10;
440 int radius = random->nextRangeU(1, kMaxRadius);
441 MorphologyType type = random->nextBool() ? GrMorphologyEffect::kErode_MorphologyType :
442 GrMorphologyEffect::kDilate_MorphologyType;
444 return GrMorphologyEffect::Create(textures[texIdx], dir, radius, type);
449 void apply_morphology_pass(GrContext* context,
451 const SkIRect& srcRect,
452 const SkIRect& dstRect,
454 GrMorphologyEffect::MorphologyType morphType,
455 Gr1DKernelEffect::Direction direction) {
457 paint.addColorEffect(GrMorphologyEffect::Create(texture,
460 morphType))->unref();
461 context->drawRectToRect(paint, SkRect::Make(dstRect), SkRect::Make(srcRect));
464 bool apply_morphology(const SkBitmap& input,
466 GrMorphologyEffect::MorphologyType morphType,
469 GrTexture* srcTexture = input.getTexture();
470 SkASSERT(NULL != srcTexture);
471 GrContext* context = srcTexture->getContext();
473 SkAutoTUnref<GrTexture> src(srcTexture);
475 GrContext::AutoMatrix am;
476 am.setIdentity(context);
478 GrContext::AutoClip acs(context, SkRect::MakeWH(SkIntToScalar(srcTexture->width()),
479 SkIntToScalar(srcTexture->height())));
481 SkIRect dstRect = SkIRect::MakeWH(rect.width(), rect.height());
483 desc.fFlags = kRenderTarget_GrTextureFlagBit | kNoStencil_GrTextureFlagBit;
484 desc.fWidth = rect.width();
485 desc.fHeight = rect.height();
486 desc.fConfig = kSkia8888_GrPixelConfig;
487 SkIRect srcRect = rect;
489 if (radius.fWidth > 0) {
490 GrAutoScratchTexture ast(context, desc);
491 GrContext::AutoRenderTarget art(context, ast.texture()->asRenderTarget());
492 apply_morphology_pass(context, src, srcRect, dstRect, radius.fWidth,
493 morphType, Gr1DKernelEffect::kX_Direction);
494 SkIRect clearRect = SkIRect::MakeXYWH(dstRect.fLeft, dstRect.fBottom,
495 dstRect.width(), radius.fHeight);
496 context->clear(&clearRect, GrMorphologyEffect::kErode_MorphologyType == morphType ?
498 SK_ColorTRANSPARENT, false);
499 src.reset(ast.detach());
502 if (radius.fHeight > 0) {
503 GrAutoScratchTexture ast(context, desc);
504 GrContext::AutoRenderTarget art(context, ast.texture()->asRenderTarget());
505 apply_morphology_pass(context, src, srcRect, dstRect, radius.fHeight,
506 morphType, Gr1DKernelEffect::kY_Direction);
507 src.reset(ast.detach());
509 return SkImageFilterUtils::WrapTexture(src, rect.width(), rect.height(), dst);
514 bool SkMorphologyImageFilter::filterImageGPUGeneric(bool dilate,
521 SkIPoint srcOffset = SkIPoint::Make(0, 0);
522 if (!SkImageFilterUtils::GetInputResultGPU(getInput(0), proxy, src, ctm, &input, &srcOffset)) {
526 input.getBounds(&bounds);
527 bounds.offset(srcOffset);
528 if (!this->applyCropRect(&bounds, ctm)) {
531 SkVector radius = SkVector::Make(SkIntToScalar(this->radius().width()),
532 SkIntToScalar(this->radius().height()));
533 ctm.mapVectors(&radius, 1);
534 int width = SkScalarFloorToInt(radius.fX);
535 int height = SkScalarFloorToInt(radius.fY);
537 if (width < 0 || height < 0) {
541 SkIRect srcBounds = bounds;
542 srcBounds.offset(-srcOffset);
543 if (width == 0 && height == 0) {
544 input.extractSubset(result, srcBounds);
545 offset->fX = bounds.left();
546 offset->fY = bounds.top();
550 GrMorphologyEffect::MorphologyType type = dilate ? GrMorphologyEffect::kDilate_MorphologyType : GrMorphologyEffect::kErode_MorphologyType;
551 if (!apply_morphology(input, srcBounds, type,
552 SkISize::Make(width, height), result)) {
555 offset->fX = bounds.left();
556 offset->fY = bounds.top();
560 bool SkDilateImageFilter::filterImageGPU(Proxy* proxy, const SkBitmap& src, const SkMatrix& ctm,
561 SkBitmap* result, SkIPoint* offset) {
562 return this->filterImageGPUGeneric(true, proxy, src, ctm, result, offset);
565 bool SkErodeImageFilter::filterImageGPU(Proxy* proxy, const SkBitmap& src, const SkMatrix& ctm,
566 SkBitmap* result, SkIPoint* offset) {
567 return this->filterImageGPUGeneric(false, proxy, src, ctm, result, offset);