Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / third_party / skia / src / effects / SkAlphaThresholdFilter.cpp
1 /*
2  * Copyright 2013 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 "SkAlphaThresholdFilter.h"
9 #include "SkBitmap.h"
10 #include "SkReadBuffer.h"
11 #include "SkWriteBuffer.h"
12 #include "SkRegion.h"
13
14 class SK_API SkAlphaThresholdFilterImpl : public SkImageFilter {
15 public:
16     SkAlphaThresholdFilterImpl(const SkRegion& region, SkScalar innerThreshold,
17                                SkScalar outerThreshold, SkImageFilter* input);
18
19     SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkAlphaThresholdFilterImpl)
20
21 protected:
22     explicit SkAlphaThresholdFilterImpl(SkReadBuffer& buffer);
23     virtual void flatten(SkWriteBuffer&) const SK_OVERRIDE;
24
25     virtual bool onFilterImage(Proxy*, const SkBitmap& src, const Context&,
26                                SkBitmap* result, SkIPoint* offset) const SK_OVERRIDE;
27 #if SK_SUPPORT_GPU
28     virtual bool asNewEffect(GrEffect** effect, GrTexture* texture,
29                              const SkMatrix& matrix, const SkIRect& bounds) const SK_OVERRIDE;
30 #endif
31
32 private:
33     SkRegion fRegion;
34     SkScalar fInnerThreshold;
35     SkScalar fOuterThreshold;
36     typedef SkImageFilter INHERITED;
37 };
38
39 SkImageFilter* SkAlphaThresholdFilter::Create(const SkRegion& region,
40                                               SkScalar innerThreshold,
41                                               SkScalar outerThreshold,
42                                               SkImageFilter* input) {
43     return SkNEW_ARGS(SkAlphaThresholdFilterImpl, (region, innerThreshold, outerThreshold, input));
44 }
45
46 #if SK_SUPPORT_GPU
47 #include "GrContext.h"
48 #include "GrCoordTransform.h"
49 #include "GrEffect.h"
50 #include "gl/GrGLEffect.h"
51 #include "gl/GrGLShaderBuilder.h"
52 #include "GrTBackendEffectFactory.h"
53 #include "GrTextureAccess.h"
54
55 #include "SkGr.h"
56
57 class GrGLAlphaThresholdEffect;
58
59 class AlphaThresholdEffect : public GrEffect {
60
61 public:
62     static GrEffect* Create(GrTexture* texture,
63                             GrTexture* maskTexture,
64                             float innerThreshold,
65                             float outerThreshold) {
66         return SkNEW_ARGS(AlphaThresholdEffect, (texture,
67                                                  maskTexture,
68                                                  innerThreshold,
69                                                  outerThreshold));
70     }
71
72     virtual ~AlphaThresholdEffect() {};
73
74     static const char* Name() { return "Alpha Threshold"; }
75
76     virtual const GrBackendEffectFactory& getFactory() const SK_OVERRIDE;
77     virtual void getConstantColorComponents(GrColor* color, uint32_t* validFlags) const SK_OVERRIDE;
78
79     float innerThreshold() const { return fInnerThreshold; }
80     float outerThreshold() const { return fOuterThreshold; }
81
82     typedef GrGLAlphaThresholdEffect GLEffect;
83
84 private:
85     AlphaThresholdEffect(GrTexture* texture,
86                          GrTexture* maskTexture,
87                          float innerThreshold,
88                          float outerThreshold)
89         : fInnerThreshold(innerThreshold)
90         , fOuterThreshold(outerThreshold)
91         , fImageCoordTransform(kLocal_GrCoordSet, MakeDivByTextureWHMatrix(texture), texture)
92         , fImageTextureAccess(texture)
93         , fMaskCoordTransform(kLocal_GrCoordSet, MakeDivByTextureWHMatrix(maskTexture), maskTexture)
94         , fMaskTextureAccess(maskTexture) {
95         this->addCoordTransform(&fImageCoordTransform);
96         this->addTextureAccess(&fImageTextureAccess);
97         this->addCoordTransform(&fMaskCoordTransform);
98         this->addTextureAccess(&fMaskTextureAccess);
99     }
100
101     virtual bool onIsEqual(const GrEffect&) const SK_OVERRIDE;
102
103     GR_DECLARE_EFFECT_TEST;
104
105     float fInnerThreshold;
106     float fOuterThreshold;
107     GrCoordTransform fImageCoordTransform;
108     GrTextureAccess  fImageTextureAccess;
109     GrCoordTransform fMaskCoordTransform;
110     GrTextureAccess  fMaskTextureAccess;
111
112     typedef GrEffect INHERITED;
113 };
114
115 class GrGLAlphaThresholdEffect : public GrGLEffect {
116 public:
117     GrGLAlphaThresholdEffect(const GrBackendEffectFactory&, const GrDrawEffect&);
118
119     virtual void emitCode(GrGLShaderBuilder*,
120                           const GrDrawEffect&,
121                           const GrEffectKey&,
122                           const char* outputColor,
123                           const char* inputColor,
124                           const TransformedCoordsArray&,
125                           const TextureSamplerArray&) SK_OVERRIDE;
126
127     virtual void setData(const GrGLProgramDataManager&, const GrDrawEffect&) SK_OVERRIDE;
128
129 private:
130
131     GrGLProgramDataManager::UniformHandle fInnerThresholdVar;
132     GrGLProgramDataManager::UniformHandle fOuterThresholdVar;
133
134     typedef GrGLEffect INHERITED;
135 };
136
137 GrGLAlphaThresholdEffect::GrGLAlphaThresholdEffect(const GrBackendEffectFactory& factory, const GrDrawEffect&)
138     : INHERITED(factory) {
139 }
140
141 void GrGLAlphaThresholdEffect::emitCode(GrGLShaderBuilder* builder,
142                                         const GrDrawEffect&,
143                                         const GrEffectKey& key,
144                                         const char* outputColor,
145                                         const char* inputColor,
146                                         const TransformedCoordsArray& coords,
147                                         const TextureSamplerArray& samplers) {
148     SkString coords2D = builder->ensureFSCoords2D(coords, 0);
149     SkString maskCoords2D = builder->ensureFSCoords2D(coords, 1);
150     fInnerThresholdVar = builder->addUniform(
151         GrGLShaderBuilder::kFragment_Visibility,
152         kFloat_GrSLType, "inner_threshold");
153     fOuterThresholdVar = builder->addUniform(
154         GrGLShaderBuilder::kFragment_Visibility,
155         kFloat_GrSLType, "outer_threshold");
156
157     builder->fsCodeAppendf("\t\tvec2 coord = %s;\n", coords2D.c_str());
158     builder->fsCodeAppendf("\t\tvec2 mask_coord = %s;\n", maskCoords2D.c_str());
159     builder->fsCodeAppend("\t\tvec4 input_color = ");
160     builder->fsAppendTextureLookup(samplers[0], "coord");
161     builder->fsCodeAppend(";\n");
162     builder->fsCodeAppend("\t\tvec4 mask_color = ");
163     builder->fsAppendTextureLookup(samplers[1], "mask_coord");
164     builder->fsCodeAppend(";\n");
165
166     builder->fsCodeAppendf("\t\tfloat inner_thresh = %s;\n",
167                            builder->getUniformCStr(fInnerThresholdVar));
168     builder->fsCodeAppendf("\t\tfloat outer_thresh = %s;\n",
169                            builder->getUniformCStr(fOuterThresholdVar));
170     builder->fsCodeAppend("\t\tfloat mask = mask_color.a;\n");
171
172     builder->fsCodeAppend("vec4 color = input_color;\n");
173     builder->fsCodeAppend("\t\tif (mask < 0.5) {\n"
174                           "\t\t\tif (color.a > outer_thresh) {\n"
175                           "\t\t\t\tfloat scale = outer_thresh / color.a;\n"
176                           "\t\t\t\tcolor.rgb *= scale;\n"
177                           "\t\t\t\tcolor.a = outer_thresh;\n"
178                           "\t\t\t}\n"
179                           "\t\t} else if (color.a < inner_thresh) {\n"
180                           "\t\t\tfloat scale = inner_thresh / max(0.001, color.a);\n"
181                           "\t\t\tcolor.rgb *= scale;\n"
182                           "\t\t\tcolor.a = inner_thresh;\n"
183                           "\t\t}\n");
184
185     builder->fsCodeAppendf("%s = %s;\n", outputColor,
186                            (GrGLSLExpr4(inputColor) * GrGLSLExpr4("color")).c_str());
187 }
188
189 void GrGLAlphaThresholdEffect::setData(const GrGLProgramDataManager& pdman,
190                                   const GrDrawEffect& drawEffect) {
191     const AlphaThresholdEffect& alpha_threshold =
192         drawEffect.castEffect<AlphaThresholdEffect>();
193     pdman.set1f(fInnerThresholdVar, alpha_threshold.innerThreshold());
194     pdman.set1f(fOuterThresholdVar, alpha_threshold.outerThreshold());
195 }
196
197 /////////////////////////////////////////////////////////////////////
198
199 GR_DEFINE_EFFECT_TEST(AlphaThresholdEffect);
200
201 GrEffect* AlphaThresholdEffect::TestCreate(SkRandom* random,
202                                            GrContext* context,
203                                            const GrDrawTargetCaps&,
204                                            GrTexture** textures) {
205     GrTexture* bmpTex = textures[GrEffectUnitTest::kSkiaPMTextureIdx];
206     GrTexture* maskTex = textures[GrEffectUnitTest::kAlphaTextureIdx];
207     float inner_thresh = random->nextUScalar1();
208     float outer_thresh = random->nextUScalar1();
209     return AlphaThresholdEffect::Create(bmpTex, maskTex, inner_thresh, outer_thresh);
210 }
211
212 ///////////////////////////////////////////////////////////////////////////////
213
214 const GrBackendEffectFactory& AlphaThresholdEffect::getFactory() const {
215     return GrTBackendEffectFactory<AlphaThresholdEffect>::getInstance();
216 }
217
218 bool AlphaThresholdEffect::onIsEqual(const GrEffect& sBase) const {
219     const AlphaThresholdEffect& s = CastEffect<AlphaThresholdEffect>(sBase);
220     return (this->texture(0) == s.texture(0) &&
221             this->fInnerThreshold == s.fInnerThreshold &&
222             this->fOuterThreshold == s.fOuterThreshold);
223 }
224
225 void AlphaThresholdEffect::getConstantColorComponents(GrColor* color, uint32_t* validFlags) const {
226     if ((*validFlags & kA_GrColorComponentFlag) && 0xFF == GrColorUnpackA(*color) &&
227         GrPixelConfigIsOpaque(this->texture(0)->config())) {
228         *validFlags = kA_GrColorComponentFlag;
229     } else {
230         *validFlags = 0;
231     }
232 }
233
234 #endif
235
236 SkAlphaThresholdFilterImpl::SkAlphaThresholdFilterImpl(SkReadBuffer& buffer)
237   : INHERITED(1, buffer) {
238     fInnerThreshold = buffer.readScalar();
239     fOuterThreshold = buffer.readScalar();
240     buffer.readRegion(&fRegion);
241 }
242
243 SkAlphaThresholdFilterImpl::SkAlphaThresholdFilterImpl(const SkRegion& region,
244                                                        SkScalar innerThreshold,
245                                                        SkScalar outerThreshold,
246                                                        SkImageFilter* input)
247     : INHERITED(1, &input)
248     , fRegion(region)
249     , fInnerThreshold(innerThreshold)
250     , fOuterThreshold(outerThreshold) {
251 }
252
253 #if SK_SUPPORT_GPU
254 bool SkAlphaThresholdFilterImpl::asNewEffect(GrEffect** effect, GrTexture* texture,
255                                              const SkMatrix& in_matrix, const SkIRect&) const {
256     if (effect) {
257         GrContext* context = texture->getContext();
258         GrTextureDesc maskDesc;
259         if (context->isConfigRenderable(kAlpha_8_GrPixelConfig, false)) {
260             maskDesc.fConfig = kAlpha_8_GrPixelConfig;
261         } else {
262             maskDesc.fConfig = kRGBA_8888_GrPixelConfig;
263         }
264         maskDesc.fFlags = kRenderTarget_GrTextureFlagBit | kNoStencil_GrTextureFlagBit;
265         // Add one pixel of border to ensure that clamp mode will be all zeros
266         // the outside.
267         maskDesc.fWidth = texture->width();
268         maskDesc.fHeight = texture->height();
269         GrAutoScratchTexture ast(context, maskDesc, GrContext::kApprox_ScratchTexMatch);
270         GrTexture*  maskTexture = ast.texture();
271         if (NULL == maskTexture) {
272             return false;
273         }
274
275         {
276             GrContext::AutoRenderTarget art(context, ast.texture()->asRenderTarget());
277             GrPaint grPaint;
278             grPaint.setBlendFunc(kOne_GrBlendCoeff, kZero_GrBlendCoeff);
279             SkRegion::Iterator iter(fRegion);
280             context->clear(NULL, 0x0, true);
281
282             SkMatrix old_matrix = context->getMatrix();
283             context->setMatrix(in_matrix);
284
285             while (!iter.done()) {
286                 SkRect rect = SkRect::Make(iter.rect());
287                 context->drawRect(grPaint, rect);
288                 iter.next();
289             }
290             context->setMatrix(old_matrix);
291         }
292
293         *effect = AlphaThresholdEffect::Create(texture,
294                                                maskTexture,
295                                                fInnerThreshold,
296                                                fOuterThreshold);
297     }
298     return true;
299 }
300 #endif
301
302 void SkAlphaThresholdFilterImpl::flatten(SkWriteBuffer& buffer) const {
303     this->INHERITED::flatten(buffer);
304     buffer.writeScalar(fInnerThreshold);
305     buffer.writeScalar(fOuterThreshold);
306     buffer.writeRegion(fRegion);
307 }
308
309 bool SkAlphaThresholdFilterImpl::onFilterImage(Proxy*, const SkBitmap& src,
310                                                const Context& ctx, SkBitmap* dst,
311                                                SkIPoint* offset) const {
312     SkASSERT(src.colorType() == kN32_SkColorType);
313
314     if (src.colorType() != kN32_SkColorType) {
315         return false;
316     }
317
318     SkMatrix localInverse;
319     if (!ctx.ctm().invert(&localInverse)) {
320         return false;
321     }
322
323     SkAutoLockPixels alp(src);
324     SkASSERT(src.getPixels());
325     if (!src.getPixels() || src.width() <= 0 || src.height() <= 0) {
326         return false;
327     }
328
329     if (!dst->allocPixels(src.info())) {
330         return false;
331     }
332
333     U8CPU innerThreshold = (U8CPU)(fInnerThreshold * 0xFF);
334     U8CPU outerThreshold = (U8CPU)(fOuterThreshold * 0xFF);
335     SkColor* sptr = src.getAddr32(0, 0);
336     SkColor* dptr = dst->getAddr32(0, 0);
337     int width = src.width(), height = src.height();
338     for (int y = 0; y < height; ++y) {
339         for (int x = 0; x < width; ++x) {
340             const SkColor& source = sptr[y * width + x];
341             SkColor output_color(source);
342             SkPoint position;
343             localInverse.mapXY((SkScalar)x, (SkScalar)y, &position);
344             if (fRegion.contains((int32_t)position.x(), (int32_t)position.y())) {
345                 if (SkColorGetA(source) < innerThreshold) {
346                     U8CPU alpha = SkColorGetA(source);
347                     if (alpha == 0)
348                         alpha = 1;
349                     float scale = (float)innerThreshold / alpha;
350                     output_color = SkColorSetARGB(innerThreshold,
351                                                   (U8CPU)(SkColorGetR(source) * scale),
352                                                   (U8CPU)(SkColorGetG(source) * scale),
353                                                   (U8CPU)(SkColorGetB(source) * scale));
354                 }
355             } else {
356                 if (SkColorGetA(source) > outerThreshold) {
357                     float scale = (float)outerThreshold / SkColorGetA(source);
358                     output_color = SkColorSetARGB(outerThreshold,
359                                                   (U8CPU)(SkColorGetR(source) * scale),
360                                                   (U8CPU)(SkColorGetG(source) * scale),
361                                                   (U8CPU)(SkColorGetB(source) * scale));
362                 }
363             }
364             dptr[y * dst->width() + x] = output_color;
365         }
366     }
367
368     return true;
369 }