Upstream version 5.34.92.0
[platform/framework/web/crosswalk.git] / src / third_party / skia / src / effects / SkMorphologyImageFilter.cpp
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 "SkMorphologyImageFilter.h"
9 #include "SkBitmap.h"
10 #include "SkColorPriv.h"
11 #include "SkFlattenableBuffers.h"
12 #include "SkRect.h"
13 #include "SkMorphology_opts.h"
14 #if SK_SUPPORT_GPU
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"
21 #endif
22
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));
29 }
30
31 SkMorphologyImageFilter::SkMorphologyImageFilter(int radiusX,
32                                                  int radiusY,
33                                                  SkImageFilter* input,
34                                                  const CropRect* cropRect)
35     : INHERITED(input, cropRect), fRadius(SkISize::Make(radiusX, radiusY)) {
36 }
37
38
39 void SkMorphologyImageFilter::flatten(SkFlattenableWriteBuffer& buffer) const {
40     this->INHERITED::flatten(buffer);
41     buffer.writeInt(fRadius.fWidth);
42     buffer.writeInt(fRadius.fHeight);
43 }
44
45 enum MorphDirection {
46     kX, kY
47 };
48
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)
53 {
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;
75             }
76             *dptr = SkPackARGB32(minA, minR, minG, minB);
77             dptr += dstStrideY;
78             lp += srcStrideY;
79             up += srcStrideY;
80         }
81         if (x >= radius) src += srcStrideX;
82         if (x + radius < width - 1) upperSrc += srcStrideX;
83         dst += dstStrideX;
84     }
85 }
86
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)
91 {
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;
113             }
114             *dptr = SkPackARGB32(maxA, maxR, maxG, maxB);
115             dptr += dstStrideY;
116             lp += srcStrideY;
117             up += srcStrideY;
118         }
119         if (x >= radius) src += srcStrideX;
120         if (x + radius < width - 1) upperSrc += srcStrideX;
121         dst += dstStrideX;
122     }
123 }
124
125 static void callProcX(SkMorphologyImageFilter::Proc procX, const SkBitmap& src, SkBitmap* dst, int radiusX, const SkIRect& bounds)
126 {
127     procX(src.getAddr32(bounds.left(), bounds.top()), dst->getAddr32(0, 0),
128           radiusX, bounds.width(), bounds.height(),
129           src.rowBytesAsPixels(), dst->rowBytesAsPixels());
130 }
131
132 static void callProcY(SkMorphologyImageFilter::Proc procY, const SkBitmap& src, SkBitmap* dst, int radiusY, const SkIRect& bounds)
133 {
134     procY(src.getAddr32(bounds.left(), bounds.top()), dst->getAddr32(0, 0),
135           radiusY, bounds.height(), bounds.width(),
136           src.rowBytesAsPixels(), dst->rowBytesAsPixels());
137 }
138
139 bool SkMorphologyImageFilter::filterImageGeneric(SkMorphologyImageFilter::Proc procX,
140                                                  SkMorphologyImageFilter::Proc procY,
141                                                  Proxy* proxy,
142                                                  const SkBitmap& source,
143                                                  const SkMatrix& ctm,
144                                                  SkBitmap* dst,
145                                                  SkIPoint* offset) {
146     SkBitmap src = source;
147     SkIPoint srcOffset = SkIPoint::Make(0, 0);
148     if (getInput(0) && !getInput(0)->filterImage(proxy, source, ctm, &src, &srcOffset)) {
149         return false;
150     }
151
152     if (src.config() != SkBitmap::kARGB_8888_Config) {
153         return false;
154     }
155
156     SkIRect bounds;
157     src.getBounds(&bounds);
158     bounds.offset(srcOffset);
159     if (!this->applyCropRect(&bounds, ctm)) {
160         return false;
161     }
162
163     SkAutoLockPixels alp(src);
164     if (!src.getPixels()) {
165         return false;
166     }
167
168     dst->setConfig(src.config(), bounds.width(), bounds.height());
169     dst->allocPixels();
170     if (!dst->getPixels()) {
171         return false;
172     }
173
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);
179
180     if (width < 0 || height < 0) {
181         return false;
182     }
183
184     SkIRect srcBounds = bounds;
185     srcBounds.offset(-srcOffset);
186
187     if (width == 0 && height == 0) {
188         src.extractSubset(dst, srcBounds);
189         offset->fX = bounds.left();
190         offset->fY = bounds.top();
191         return true;
192     }
193
194     SkBitmap temp;
195     temp.setConfig(dst->config(), dst->width(), dst->height());
196     if (!temp.allocPixels()) {
197         return false;
198     }
199
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);
208     }
209     offset->fX = bounds.left();
210     offset->fY = bounds.top();
211     return true;
212 }
213
214 bool SkErodeImageFilter::onFilterImage(Proxy* proxy,
215                                        const SkBitmap& source, const SkMatrix& ctm,
216                                        SkBitmap* dst, SkIPoint* offset) {
217     Proc erodeXProc = SkMorphologyGetPlatformProc(kErodeX_SkMorphologyProcType);
218     if (!erodeXProc) {
219         erodeXProc = erode<kX>;
220     }
221     Proc erodeYProc = SkMorphologyGetPlatformProc(kErodeY_SkMorphologyProcType);
222     if (!erodeYProc) {
223         erodeYProc = erode<kY>;
224     }
225     return this->filterImageGeneric(erodeXProc, erodeYProc, proxy, source, ctm, dst, offset);
226 }
227
228 bool SkDilateImageFilter::onFilterImage(Proxy* proxy,
229                                         const SkBitmap& source, const SkMatrix& ctm,
230                                         SkBitmap* dst, SkIPoint* offset) {
231     Proc dilateXProc = SkMorphologyGetPlatformProc(kDilateX_SkMorphologyProcType);
232     if (!dilateXProc) {
233         dilateXProc = dilate<kX>;
234     }
235     Proc dilateYProc = SkMorphologyGetPlatformProc(kDilateY_SkMorphologyProcType);
236     if (!dilateYProc) {
237         dilateYProc = dilate<kY>;
238     }
239     return this->filterImageGeneric(dilateXProc, dilateYProc, proxy, source, ctm, dst, offset);
240 }
241
242 #if SK_SUPPORT_GPU
243
244 ///////////////////////////////////////////////////////////////////////////////
245
246 class GrGLMorphologyEffect;
247
248 /**
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
252  * color.
253  */
254 class GrMorphologyEffect : public Gr1DKernelEffect {
255
256 public:
257
258     enum MorphologyType {
259         kErode_MorphologyType,
260         kDilate_MorphologyType,
261     };
262
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);
266     }
267
268     virtual ~GrMorphologyEffect();
269
270     MorphologyType type() const { return fType; }
271
272     static const char* Name() { return "Morphology"; }
273
274     typedef GrGLMorphologyEffect GLEffect;
275
276     virtual const GrBackendEffectFactory& getFactory() const SK_OVERRIDE;
277     virtual void getConstantColorComponents(GrColor* color, uint32_t* validFlags) const SK_OVERRIDE;
278
279 protected:
280
281     MorphologyType fType;
282
283 private:
284     virtual bool onIsEqual(const GrEffect&) const SK_OVERRIDE;
285
286     GrMorphologyEffect(GrTexture*, Direction, int radius, MorphologyType);
287
288     GR_DECLARE_EFFECT_TEST;
289
290     typedef Gr1DKernelEffect INHERITED;
291 };
292
293 ///////////////////////////////////////////////////////////////////////////////
294
295 class GrGLMorphologyEffect : public GrGLEffect {
296 public:
297     GrGLMorphologyEffect (const GrBackendEffectFactory&, const GrDrawEffect&);
298
299     virtual void emitCode(GrGLShaderBuilder*,
300                           const GrDrawEffect&,
301                           EffectKey,
302                           const char* outputColor,
303                           const char* inputColor,
304                           const TransformedCoordsArray&,
305                           const TextureSamplerArray&) SK_OVERRIDE;
306
307     static inline EffectKey GenKey(const GrDrawEffect&, const GrGLCaps&);
308
309     virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE;
310
311 private:
312     int width() const { return GrMorphologyEffect::WidthFromRadius(fRadius); }
313
314     int                                 fRadius;
315     GrMorphologyEffect::MorphologyType  fType;
316     GrGLUniformManager::UniformHandle   fImageIncrementUni;
317
318     typedef GrGLEffect INHERITED;
319 };
320
321 GrGLMorphologyEffect::GrGLMorphologyEffect(const GrBackendEffectFactory& factory,
322                                            const GrDrawEffect& drawEffect)
323     : INHERITED(factory) {
324     const GrMorphologyEffect& m = drawEffect.castEffect<GrMorphologyEffect>();
325     fRadius = m.radius();
326     fType = m.type();
327 }
328
329 void GrGLMorphologyEffect::emitCode(GrGLShaderBuilder* builder,
330                                     const GrDrawEffect&,
331                                     EffectKey key,
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");
339
340     const char* func;
341     switch (fType) {
342         case GrMorphologyEffect::kErode_MorphologyType:
343             builder->fsCodeAppendf("\t\t%s = vec4(1, 1, 1, 1);\n", outputColor);
344             func = "min";
345             break;
346         case GrMorphologyEffect::kDilate_MorphologyType:
347             builder->fsCodeAppendf("\t\t%s = vec4(0, 0, 0, 0);\n", outputColor);
348             func = "max";
349             break;
350         default:
351             GrCrash("Unexpected type");
352             func = ""; // suppress warning
353             break;
354     }
355     const char* imgInc = builder->getUniformCStr(fImageIncrementUni);
356
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");
364     SkString modulate;
365     GrGLSLMulVarBy4f(&modulate, 2, outputColor, inputColor);
366     builder->fsCodeAppend(modulate.c_str());
367 }
368
369 GrGLEffect::EffectKey GrGLMorphologyEffect::GenKey(const GrDrawEffect& drawEffect,
370                                                    const GrGLCaps&) {
371     const GrMorphologyEffect& m = drawEffect.castEffect<GrMorphologyEffect>();
372     EffectKey key = static_cast<EffectKey>(m.radius());
373     key |= (m.type() << 8);
374     return key;
375 }
376
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();
387             break;
388         case Gr1DKernelEffect::kY_Direction:
389             imageIncrement[1] = 1.0f / texture.height();
390             break;
391         default:
392             GrCrash("Unknown filter direction.");
393     }
394     uman.set2fv(fImageIncrementUni, 1, imageIncrement);
395 }
396
397 ///////////////////////////////////////////////////////////////////////////////
398
399 GrMorphologyEffect::GrMorphologyEffect(GrTexture* texture,
400                                        Direction direction,
401                                        int radius,
402                                        MorphologyType type)
403     : Gr1DKernelEffect(texture, direction, radius)
404     , fType(type) {
405 }
406
407 GrMorphologyEffect::~GrMorphologyEffect() {
408 }
409
410 const GrBackendEffectFactory& GrMorphologyEffect::getFactory() const {
411     return GrTBackendEffectFactory<GrMorphologyEffect>::getInstance();
412 }
413
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());
420 }
421
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);
426 }
427
428 ///////////////////////////////////////////////////////////////////////////////
429
430 GR_DEFINE_EFFECT_TEST(GrMorphologyEffect);
431
432 GrEffectRef* GrMorphologyEffect::TestCreate(SkRandom* random,
433                                             GrContext*,
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;
443
444     return GrMorphologyEffect::Create(textures[texIdx], dir, radius, type);
445 }
446
447 namespace {
448
449 void apply_morphology_pass(GrContext* context,
450                            GrTexture* texture,
451                            const SkIRect& srcRect,
452                            const SkIRect& dstRect,
453                            int radius,
454                            GrMorphologyEffect::MorphologyType morphType,
455                            Gr1DKernelEffect::Direction direction) {
456     GrPaint paint;
457     paint.addColorEffect(GrMorphologyEffect::Create(texture,
458                                                     direction,
459                                                     radius,
460                                                     morphType))->unref();
461     context->drawRectToRect(paint, SkRect::Make(dstRect), SkRect::Make(srcRect));
462 }
463
464 bool apply_morphology(const SkBitmap& input,
465                       const SkIRect& rect,
466                       GrMorphologyEffect::MorphologyType morphType,
467                       SkISize radius,
468                       SkBitmap* dst) {
469     GrTexture* srcTexture = input.getTexture();
470     SkASSERT(NULL != srcTexture);
471     GrContext* context = srcTexture->getContext();
472     srcTexture->ref();
473     SkAutoTUnref<GrTexture> src(srcTexture);
474
475     GrContext::AutoMatrix am;
476     am.setIdentity(context);
477
478     GrContext::AutoClip acs(context, SkRect::MakeWH(SkIntToScalar(srcTexture->width()),
479                                                     SkIntToScalar(srcTexture->height())));
480
481     SkIRect dstRect = SkIRect::MakeWH(rect.width(), rect.height());
482     GrTextureDesc desc;
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;
488
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 ?
497                                    SK_ColorWHITE :
498                                    SK_ColorTRANSPARENT, false);
499         src.reset(ast.detach());
500         srcRect = dstRect;
501     }
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());
508     }
509     return SkImageFilterUtils::WrapTexture(src, rect.width(), rect.height(), dst);
510 }
511
512 };
513
514 bool SkMorphologyImageFilter::filterImageGPUGeneric(bool dilate,
515                                                     Proxy* proxy,
516                                                     const SkBitmap& src,
517                                                     const SkMatrix& ctm,
518                                                     SkBitmap* result,
519                                                     SkIPoint* offset) {
520     SkBitmap input;
521     SkIPoint srcOffset = SkIPoint::Make(0, 0);
522     if (!SkImageFilterUtils::GetInputResultGPU(getInput(0), proxy, src, ctm, &input, &srcOffset)) {
523         return false;
524     }
525     SkIRect bounds;
526     input.getBounds(&bounds);
527     bounds.offset(srcOffset);
528     if (!this->applyCropRect(&bounds, ctm)) {
529         return false;
530     }
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);
536
537     if (width < 0 || height < 0) {
538         return false;
539     }
540
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();
547         return true;
548     }
549
550     GrMorphologyEffect::MorphologyType type = dilate ? GrMorphologyEffect::kDilate_MorphologyType : GrMorphologyEffect::kErode_MorphologyType;
551     if (!apply_morphology(input, srcBounds, type,
552                           SkISize::Make(width, height), result)) {
553         return false;
554     }
555     offset->fX = bounds.left();
556     offset->fY = bounds.top();
557     return true;
558 }
559
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);
563 }
564
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);
568 }
569
570 #endif