2 * Copyright 2013 Google Inc.
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
8 #include "SkAlphaThresholdFilter.h"
10 #include "SkReadBuffer.h"
11 #include "SkWriteBuffer.h"
14 class SK_API SkAlphaThresholdFilterImpl : public SkImageFilter {
16 SkAlphaThresholdFilterImpl(const SkRegion& region, SkScalar innerThreshold,
17 SkScalar outerThreshold, SkImageFilter* input);
19 SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkAlphaThresholdFilterImpl)
22 explicit SkAlphaThresholdFilterImpl(SkReadBuffer& buffer);
23 virtual void flatten(SkWriteBuffer&) const SK_OVERRIDE;
25 virtual bool onFilterImage(Proxy*, const SkBitmap& src, const Context&,
26 SkBitmap* result, SkIPoint* offset) const SK_OVERRIDE;
28 virtual bool asNewEffect(GrEffect** effect, GrTexture* texture,
29 const SkMatrix& matrix, const SkIRect& bounds) const SK_OVERRIDE;
34 SkScalar fInnerThreshold;
35 SkScalar fOuterThreshold;
36 typedef SkImageFilter INHERITED;
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));
47 #include "GrContext.h"
48 #include "GrCoordTransform.h"
50 #include "gl/GrGLEffect.h"
51 #include "gl/GrGLShaderBuilder.h"
52 #include "GrTBackendEffectFactory.h"
53 #include "GrTextureAccess.h"
57 class GrGLAlphaThresholdEffect;
59 class AlphaThresholdEffect : public GrEffect {
62 static GrEffect* Create(GrTexture* texture,
63 GrTexture* maskTexture,
65 float outerThreshold) {
66 return SkNEW_ARGS(AlphaThresholdEffect, (texture,
72 virtual ~AlphaThresholdEffect() {};
74 static const char* Name() { return "Alpha Threshold"; }
76 virtual const GrBackendEffectFactory& getFactory() const SK_OVERRIDE;
77 virtual void getConstantColorComponents(GrColor* color, uint32_t* validFlags) const SK_OVERRIDE;
79 float innerThreshold() const { return fInnerThreshold; }
80 float outerThreshold() const { return fOuterThreshold; }
82 typedef GrGLAlphaThresholdEffect GLEffect;
85 AlphaThresholdEffect(GrTexture* texture,
86 GrTexture* maskTexture,
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);
101 virtual bool onIsEqual(const GrEffect&) const SK_OVERRIDE;
103 GR_DECLARE_EFFECT_TEST;
105 float fInnerThreshold;
106 float fOuterThreshold;
107 GrCoordTransform fImageCoordTransform;
108 GrTextureAccess fImageTextureAccess;
109 GrCoordTransform fMaskCoordTransform;
110 GrTextureAccess fMaskTextureAccess;
112 typedef GrEffect INHERITED;
115 class GrGLAlphaThresholdEffect : public GrGLEffect {
117 GrGLAlphaThresholdEffect(const GrBackendEffectFactory&, const GrDrawEffect&);
119 virtual void emitCode(GrGLShaderBuilder*,
122 const char* outputColor,
123 const char* inputColor,
124 const TransformedCoordsArray&,
125 const TextureSamplerArray&) SK_OVERRIDE;
127 virtual void setData(const GrGLProgramDataManager&, const GrDrawEffect&) SK_OVERRIDE;
131 GrGLProgramDataManager::UniformHandle fInnerThresholdVar;
132 GrGLProgramDataManager::UniformHandle fOuterThresholdVar;
134 typedef GrGLEffect INHERITED;
137 GrGLAlphaThresholdEffect::GrGLAlphaThresholdEffect(const GrBackendEffectFactory& factory, const GrDrawEffect&)
138 : INHERITED(factory) {
141 void GrGLAlphaThresholdEffect::emitCode(GrGLShaderBuilder* builder,
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");
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");
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");
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"
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"
185 builder->fsCodeAppendf("%s = %s;\n", outputColor,
186 (GrGLSLExpr4(inputColor) * GrGLSLExpr4("color")).c_str());
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());
197 /////////////////////////////////////////////////////////////////////
199 GR_DEFINE_EFFECT_TEST(AlphaThresholdEffect);
201 GrEffect* AlphaThresholdEffect::TestCreate(SkRandom* random,
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);
212 ///////////////////////////////////////////////////////////////////////////////
214 const GrBackendEffectFactory& AlphaThresholdEffect::getFactory() const {
215 return GrTBackendEffectFactory<AlphaThresholdEffect>::getInstance();
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);
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;
236 SkAlphaThresholdFilterImpl::SkAlphaThresholdFilterImpl(SkReadBuffer& buffer)
237 : INHERITED(1, buffer) {
238 fInnerThreshold = buffer.readScalar();
239 fOuterThreshold = buffer.readScalar();
240 buffer.readRegion(&fRegion);
243 SkAlphaThresholdFilterImpl::SkAlphaThresholdFilterImpl(const SkRegion& region,
244 SkScalar innerThreshold,
245 SkScalar outerThreshold,
246 SkImageFilter* input)
247 : INHERITED(1, &input)
249 , fInnerThreshold(innerThreshold)
250 , fOuterThreshold(outerThreshold) {
254 bool SkAlphaThresholdFilterImpl::asNewEffect(GrEffect** effect, GrTexture* texture,
255 const SkMatrix& in_matrix, const SkIRect&) const {
257 GrContext* context = texture->getContext();
258 GrTextureDesc maskDesc;
259 if (context->isConfigRenderable(kAlpha_8_GrPixelConfig, false)) {
260 maskDesc.fConfig = kAlpha_8_GrPixelConfig;
262 maskDesc.fConfig = kRGBA_8888_GrPixelConfig;
264 maskDesc.fFlags = kRenderTarget_GrTextureFlagBit | kNoStencil_GrTextureFlagBit;
265 // Add one pixel of border to ensure that clamp mode will be all zeros
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) {
276 GrContext::AutoRenderTarget art(context, ast.texture()->asRenderTarget());
278 grPaint.setBlendFunc(kOne_GrBlendCoeff, kZero_GrBlendCoeff);
279 SkRegion::Iterator iter(fRegion);
280 context->clear(NULL, 0x0, true);
282 SkMatrix old_matrix = context->getMatrix();
283 context->setMatrix(in_matrix);
285 while (!iter.done()) {
286 SkRect rect = SkRect::Make(iter.rect());
287 context->drawRect(grPaint, rect);
290 context->setMatrix(old_matrix);
293 *effect = AlphaThresholdEffect::Create(texture,
302 void SkAlphaThresholdFilterImpl::flatten(SkWriteBuffer& buffer) const {
303 this->INHERITED::flatten(buffer);
304 buffer.writeScalar(fInnerThreshold);
305 buffer.writeScalar(fOuterThreshold);
306 buffer.writeRegion(fRegion);
309 bool SkAlphaThresholdFilterImpl::onFilterImage(Proxy*, const SkBitmap& src,
310 const Context& ctx, SkBitmap* dst,
311 SkIPoint* offset) const {
312 SkASSERT(src.colorType() == kN32_SkColorType);
314 if (src.colorType() != kN32_SkColorType) {
318 SkMatrix localInverse;
319 if (!ctx.ctm().invert(&localInverse)) {
323 SkAutoLockPixels alp(src);
324 SkASSERT(src.getPixels());
325 if (!src.getPixels() || src.width() <= 0 || src.height() <= 0) {
329 if (!dst->allocPixels(src.info())) {
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);
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);
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));
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));
364 dptr[y * dst->width() + x] = output_color;