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