Create GLSLUniformHandler class for gpu backend
[platform/upstream/libSkiaSharp.git] / 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 "SkDevice.h"
11 #include "SkReadBuffer.h"
12 #include "SkWriteBuffer.h"
13 #include "SkRegion.h"
14 #if SK_SUPPORT_GPU
15 #include "GrDrawContext.h"
16 #endif
17
18 class SK_API SkAlphaThresholdFilterImpl : public SkImageFilter {
19 public:
20     SkAlphaThresholdFilterImpl(const SkRegion& region, SkScalar innerThreshold,
21                                SkScalar outerThreshold, SkImageFilter* input);
22
23     SK_TO_STRING_OVERRIDE()
24     SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkAlphaThresholdFilterImpl)
25
26 protected:
27     void flatten(SkWriteBuffer&) const override;
28
29     bool onFilterImage(Proxy*, const SkBitmap& src, const Context&,
30                        SkBitmap* result, SkIPoint* offset) const override;
31 #if SK_SUPPORT_GPU
32     bool asFragmentProcessor(GrFragmentProcessor**, GrTexture*, const SkMatrix&,
33                              const SkIRect& bounds) const override;
34 #endif
35
36 private:
37     SkRegion fRegion;
38     SkScalar fInnerThreshold;
39     SkScalar fOuterThreshold;
40     typedef SkImageFilter INHERITED;
41 };
42
43 SkImageFilter* SkAlphaThresholdFilter::Create(const SkRegion& region,
44                                               SkScalar innerThreshold,
45                                               SkScalar outerThreshold,
46                                               SkImageFilter* input) {
47     return new SkAlphaThresholdFilterImpl(region, innerThreshold, outerThreshold, input);
48 }
49
50 #if SK_SUPPORT_GPU
51 #include "GrContext.h"
52 #include "GrCoordTransform.h"
53 #include "GrFragmentProcessor.h"
54 #include "GrInvariantOutput.h"
55 #include "GrTextureAccess.h"
56 #include "effects/GrPorterDuffXferProcessor.h"
57
58 #include "SkGr.h"
59
60 #include "glsl/GrGLSLFragmentProcessor.h"
61 #include "glsl/GrGLSLFragmentShaderBuilder.h"
62 #include "glsl/GrGLSLProgramDataManager.h"
63 #include "glsl/GrGLSLUniformHandler.h"
64
65 class AlphaThresholdEffect : public GrFragmentProcessor {
66
67 public:
68     static GrFragmentProcessor* Create(GrTexture* texture,
69                                        GrTexture* maskTexture,
70                                        float innerThreshold,
71                                        float outerThreshold) {
72         return new AlphaThresholdEffect(texture, maskTexture, innerThreshold, outerThreshold);
73     }
74
75     virtual ~AlphaThresholdEffect() {};
76
77     const char* name() const override { return "Alpha Threshold"; }
78
79     float innerThreshold() const { return fInnerThreshold; }
80     float outerThreshold() const { return fOuterThreshold; }
81
82 private:
83     AlphaThresholdEffect(GrTexture* texture,
84                          GrTexture* maskTexture,
85                          float innerThreshold,
86                          float outerThreshold)
87         : fInnerThreshold(innerThreshold)
88         , fOuterThreshold(outerThreshold)
89         , fImageCoordTransform(kLocal_GrCoordSet,
90                                GrCoordTransform::MakeDivByTextureWHMatrix(texture), texture,
91                                GrTextureParams::kNone_FilterMode)
92         , fImageTextureAccess(texture)
93         , fMaskCoordTransform(kLocal_GrCoordSet,
94                               GrCoordTransform::MakeDivByTextureWHMatrix(maskTexture), maskTexture,
95                               GrTextureParams::kNone_FilterMode)
96         , fMaskTextureAccess(maskTexture) {
97         this->initClassID<AlphaThresholdEffect>();
98         this->addCoordTransform(&fImageCoordTransform);
99         this->addTextureAccess(&fImageTextureAccess);
100         this->addCoordTransform(&fMaskCoordTransform);
101         this->addTextureAccess(&fMaskTextureAccess);
102     }
103
104     GrGLSLFragmentProcessor* onCreateGLSLInstance() const override;
105
106     void onGetGLSLProcessorKey(const GrGLSLCaps&, GrProcessorKeyBuilder*) const override;
107
108     bool onIsEqual(const GrFragmentProcessor&) const override;
109
110     void onComputeInvariantOutput(GrInvariantOutput* inout) const override;
111
112     GR_DECLARE_FRAGMENT_PROCESSOR_TEST;
113
114     float fInnerThreshold;
115     float fOuterThreshold;
116     GrCoordTransform fImageCoordTransform;
117     GrTextureAccess  fImageTextureAccess;
118     GrCoordTransform fMaskCoordTransform;
119     GrTextureAccess  fMaskTextureAccess;
120
121     typedef GrFragmentProcessor INHERITED;
122 };
123
124 class GrGLAlphaThresholdEffect : public GrGLSLFragmentProcessor {
125 public:
126     GrGLAlphaThresholdEffect(const GrFragmentProcessor&) {}
127
128     virtual void emitCode(EmitArgs&) override;
129
130 protected:
131     void onSetData(const GrGLSLProgramDataManager&, const GrProcessor&) override;
132
133 private:
134
135     GrGLSLProgramDataManager::UniformHandle fInnerThresholdVar;
136     GrGLSLProgramDataManager::UniformHandle fOuterThresholdVar;
137
138     typedef GrGLSLFragmentProcessor INHERITED;
139 };
140
141 void GrGLAlphaThresholdEffect::emitCode(EmitArgs& args) {
142     GrGLSLUniformHandler* uniformHandler = args.fUniformHandler;
143     fInnerThresholdVar = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility,
144                                                     kFloat_GrSLType, kDefault_GrSLPrecision,
145                                                     "inner_threshold");
146     fOuterThresholdVar = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility,
147                                                     kFloat_GrSLType, kDefault_GrSLPrecision,
148                                                     "outer_threshold");
149
150     GrGLSLFragmentBuilder* fragBuilder = args.fFragBuilder;
151     SkString coords2D = fragBuilder->ensureFSCoords2D(args.fCoords, 0);
152     SkString maskCoords2D = fragBuilder->ensureFSCoords2D(args.fCoords, 1);
153
154     fragBuilder->codeAppendf("\t\tvec2 coord = %s;\n", coords2D.c_str());
155     fragBuilder->codeAppendf("\t\tvec2 mask_coord = %s;\n", maskCoords2D.c_str());
156     fragBuilder->codeAppend("\t\tvec4 input_color = ");
157     fragBuilder->appendTextureLookup(args.fSamplers[0], "coord");
158     fragBuilder->codeAppend(";\n");
159     fragBuilder->codeAppend("\t\tvec4 mask_color = ");
160     fragBuilder->appendTextureLookup(args.fSamplers[1], "mask_coord");
161     fragBuilder->codeAppend(";\n");
162
163     fragBuilder->codeAppendf("\t\tfloat inner_thresh = %s;\n",
164                              uniformHandler->getUniformCStr(fInnerThresholdVar));
165     fragBuilder->codeAppendf("\t\tfloat outer_thresh = %s;\n",
166                              uniformHandler->getUniformCStr(fOuterThresholdVar));
167     fragBuilder->codeAppend("\t\tfloat mask = mask_color.a;\n");
168
169     fragBuilder->codeAppend("vec4 color = input_color;\n");
170     fragBuilder->codeAppend("\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     fragBuilder->codeAppendf("%s = %s;\n", args.fOutputColor,
183                              (GrGLSLExpr4(args.fInputColor) * GrGLSLExpr4("color")).c_str());
184 }
185
186 void GrGLAlphaThresholdEffect::onSetData(const GrGLSLProgramDataManager& pdman,
187                                        const GrProcessor& proc) {
188     const AlphaThresholdEffect& alpha_threshold = proc.cast<AlphaThresholdEffect>();
189     pdman.set1f(fInnerThresholdVar, alpha_threshold.innerThreshold());
190     pdman.set1f(fOuterThresholdVar, alpha_threshold.outerThreshold());
191 }
192
193 /////////////////////////////////////////////////////////////////////
194
195 GR_DEFINE_FRAGMENT_PROCESSOR_TEST(AlphaThresholdEffect);
196
197 const GrFragmentProcessor* AlphaThresholdEffect::TestCreate(GrProcessorTestData* d) {
198     GrTexture* bmpTex = d->fTextures[GrProcessorUnitTest::kSkiaPMTextureIdx];
199     GrTexture* maskTex = d->fTextures[GrProcessorUnitTest::kAlphaTextureIdx];
200     float innerThresh = d->fRandom->nextUScalar1();
201     float outerThresh = d->fRandom->nextUScalar1();
202     return AlphaThresholdEffect::Create(bmpTex, maskTex, innerThresh, outerThresh);
203 }
204
205 ///////////////////////////////////////////////////////////////////////////////
206
207 void AlphaThresholdEffect::onGetGLSLProcessorKey(const GrGLSLCaps& caps,
208                                                  GrProcessorKeyBuilder* b) const {
209     GrGLAlphaThresholdEffect::GenKey(*this, caps, b);
210 }
211
212 GrGLSLFragmentProcessor* AlphaThresholdEffect::onCreateGLSLInstance() const {
213     return new GrGLAlphaThresholdEffect(*this);
214 }
215
216 bool AlphaThresholdEffect::onIsEqual(const GrFragmentProcessor& sBase) const {
217     const AlphaThresholdEffect& s = sBase.cast<AlphaThresholdEffect>();
218     return (this->fInnerThreshold == s.fInnerThreshold &&
219             this->fOuterThreshold == s.fOuterThreshold);
220 }
221
222 void AlphaThresholdEffect::onComputeInvariantOutput(GrInvariantOutput* inout) const {
223     if (GrPixelConfigIsAlphaOnly(this->texture(0)->config())) {
224         inout->mulByUnknownSingleComponent();
225     } else if (GrPixelConfigIsOpaque(this->texture(0)->config()) && fOuterThreshold >= 1.f) {
226         inout->mulByUnknownOpaqueFourComponents();
227     } else {
228         inout->mulByUnknownFourComponents();
229     }
230 }
231
232 #endif
233
234 SkFlattenable* SkAlphaThresholdFilterImpl::CreateProc(SkReadBuffer& buffer) {
235     SK_IMAGEFILTER_UNFLATTEN_COMMON(common, 1);
236     SkScalar inner = buffer.readScalar();
237     SkScalar outer = buffer.readScalar();
238     SkRegion rgn;
239     buffer.readRegion(&rgn);
240     return SkAlphaThresholdFilter::Create(rgn, inner, outer, common.getInput(0));
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::asFragmentProcessor(GrFragmentProcessor** fp,
255                                                      GrTexture* texture,
256                                                      const SkMatrix& inMatrix,
257                                                      const SkIRect&) const {
258     if (fp) {
259         GrContext* context = texture->getContext();
260         GrSurfaceDesc maskDesc;
261         if (context->caps()->isConfigRenderable(kAlpha_8_GrPixelConfig, false)) {
262             maskDesc.fConfig = kAlpha_8_GrPixelConfig;
263         } else {
264             maskDesc.fConfig = kRGBA_8888_GrPixelConfig;
265         }
266         maskDesc.fFlags = kRenderTarget_GrSurfaceFlag;
267         // Add one pixel of border to ensure that clamp mode will be all zeros
268         // the outside.
269         maskDesc.fWidth = texture->width();
270         maskDesc.fHeight = texture->height();
271         SkAutoTUnref<GrTexture> maskTexture(
272             context->textureProvider()->createApproxTexture(maskDesc));
273         if (!maskTexture) {
274             return false;
275         }
276
277         SkAutoTUnref<GrDrawContext> drawContext(
278                                             context->drawContext(maskTexture->asRenderTarget()));
279         if (drawContext) {
280             GrPaint grPaint;
281             grPaint.setPorterDuffXPFactory(SkXfermode::kSrc_Mode);
282             SkRegion::Iterator iter(fRegion);
283             drawContext->clear(nullptr, 0x0, true);
284
285             while (!iter.done()) {
286                 SkRect rect = SkRect::Make(iter.rect());
287                 drawContext->drawRect(GrClip::WideOpen(), grPaint, inMatrix, rect);
288                 iter.next();
289             }
290         }
291
292         *fp = AlphaThresholdEffect::Create(texture,
293                                            maskTexture,
294                                            fInnerThreshold,
295                                            fOuterThreshold);
296     }
297     return true;
298 }
299 #endif
300
301 void SkAlphaThresholdFilterImpl::flatten(SkWriteBuffer& buffer) const {
302     this->INHERITED::flatten(buffer);
303     buffer.writeScalar(fInnerThreshold);
304     buffer.writeScalar(fOuterThreshold);
305     buffer.writeRegion(fRegion);
306 }
307
308 bool SkAlphaThresholdFilterImpl::onFilterImage(Proxy* proxy, const SkBitmap& src,
309                                                const Context& ctx, SkBitmap* dst,
310                                                SkIPoint* offset) const {
311     SkASSERT(src.colorType() == kN32_SkColorType);
312
313     if (src.colorType() != kN32_SkColorType) {
314         return false;
315     }
316
317     SkMatrix localInverse;
318     if (!ctx.ctm().invert(&localInverse)) {
319         return false;
320     }
321
322     SkAutoLockPixels alp(src);
323     SkASSERT(src.getPixels());
324     if (!src.getPixels() || src.width() <= 0 || src.height() <= 0) {
325         return false;
326     }
327
328     SkAutoTUnref<SkBaseDevice> device(proxy->createDevice(src.width(), src.height()));
329     if (!device) {
330         return false;
331     }
332     *dst = device->accessBitmap(false);
333     SkAutoLockPixels alp_dst(*dst);
334
335     U8CPU innerThreshold = (U8CPU)(fInnerThreshold * 0xFF);
336     U8CPU outerThreshold = (U8CPU)(fOuterThreshold * 0xFF);
337     SkColor* sptr = src.getAddr32(0, 0);
338     SkColor* dptr = dst->getAddr32(0, 0);
339     int width = src.width(), height = src.height();
340     for (int y = 0; y < height; ++y) {
341         for (int x = 0; x < width; ++x) {
342             const SkColor& source = sptr[y * width + x];
343             SkColor output_color(source);
344             SkPoint position;
345             localInverse.mapXY((SkScalar)x, (SkScalar)y, &position);
346             if (fRegion.contains((int32_t)position.x(), (int32_t)position.y())) {
347                 if (SkColorGetA(source) < innerThreshold) {
348                     U8CPU alpha = SkColorGetA(source);
349                     if (alpha == 0)
350                         alpha = 1;
351                     float scale = (float)innerThreshold / alpha;
352                     output_color = SkColorSetARGB(innerThreshold,
353                                                   (U8CPU)(SkColorGetR(source) * scale),
354                                                   (U8CPU)(SkColorGetG(source) * scale),
355                                                   (U8CPU)(SkColorGetB(source) * scale));
356                 }
357             } else {
358                 if (SkColorGetA(source) > outerThreshold) {
359                     float scale = (float)outerThreshold / SkColorGetA(source);
360                     output_color = SkColorSetARGB(outerThreshold,
361                                                   (U8CPU)(SkColorGetR(source) * scale),
362                                                   (U8CPU)(SkColorGetG(source) * scale),
363                                                   (U8CPU)(SkColorGetB(source) * scale));
364                 }
365             }
366             dptr[y * dst->width() + x] = output_color;
367         }
368     }
369
370     return true;
371 }
372
373 #ifndef SK_IGNORE_TO_STRING
374 void SkAlphaThresholdFilterImpl::toString(SkString* str) const {
375     str->appendf("SkAlphaThresholdImageFilter: (");
376     str->appendf("inner: %f outer: %f", fInnerThreshold, fOuterThreshold);
377     str->append(")");
378 }
379 #endif
380