Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / third_party / skia / src / gpu / effects / GrConvolutionEffect.cpp
1 /*
2  * Copyright 2012 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 "GrConvolutionEffect.h"
9 #include "gl/GrGLEffect.h"
10 #include "gl/GrGLShaderBuilder.h"
11 #include "gl/GrGLSL.h"
12 #include "gl/GrGLTexture.h"
13 #include "GrTBackendEffectFactory.h"
14
15 // For brevity
16 typedef GrGLProgramDataManager::UniformHandle UniformHandle;
17
18 class GrGLConvolutionEffect : public GrGLEffect {
19 public:
20     GrGLConvolutionEffect(const GrBackendEffectFactory&, const GrDrawEffect&);
21
22     virtual void emitCode(GrGLShaderBuilder*,
23                           const GrDrawEffect&,
24                           const GrEffectKey&,
25                           const char* outputColor,
26                           const char* inputColor,
27                           const TransformedCoordsArray&,
28                           const TextureSamplerArray&) SK_OVERRIDE;
29
30     virtual void setData(const GrGLProgramDataManager& pdman, const GrDrawEffect&) SK_OVERRIDE;
31
32     static inline void GenKey(const GrDrawEffect&, const GrGLCaps&, GrEffectKeyBuilder*);
33
34 private:
35     int width() const { return Gr1DKernelEffect::WidthFromRadius(fRadius); }
36     bool useBounds() const { return fUseBounds; }
37     Gr1DKernelEffect::Direction direction() const { return fDirection; }
38
39     int                 fRadius;
40     bool                fUseBounds;
41     Gr1DKernelEffect::Direction    fDirection;
42     UniformHandle       fKernelUni;
43     UniformHandle       fImageIncrementUni;
44     UniformHandle       fBoundsUni;
45
46     typedef GrGLEffect INHERITED;
47 };
48
49 GrGLConvolutionEffect::GrGLConvolutionEffect(const GrBackendEffectFactory& factory,
50                                              const GrDrawEffect& drawEffect)
51     : INHERITED(factory) {
52     const GrConvolutionEffect& c = drawEffect.castEffect<GrConvolutionEffect>();
53     fRadius = c.radius();
54     fUseBounds = c.useBounds();
55     fDirection = c.direction();
56 }
57
58 void GrGLConvolutionEffect::emitCode(GrGLShaderBuilder* builder,
59                                      const GrDrawEffect&,
60                                      const GrEffectKey& key,
61                                      const char* outputColor,
62                                      const char* inputColor,
63                                      const TransformedCoordsArray& coords,
64                                      const TextureSamplerArray& samplers) {
65     SkString coords2D = builder->ensureFSCoords2D(coords, 0);
66     fImageIncrementUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
67                                              kVec2f_GrSLType, "ImageIncrement");
68     if (this->useBounds()) {
69         fBoundsUni = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility,
70                                          kVec2f_GrSLType, "Bounds");
71     }
72     fKernelUni = builder->addUniformArray(GrGLShaderBuilder::kFragment_Visibility,
73                                           kFloat_GrSLType, "Kernel", this->width());
74
75     builder->fsCodeAppendf("\t\t%s = vec4(0, 0, 0, 0);\n", outputColor);
76
77     int width = this->width();
78     const GrGLShaderVar& kernel = builder->getUniformVariable(fKernelUni);
79     const char* imgInc = builder->getUniformCStr(fImageIncrementUni);
80
81     builder->fsCodeAppendf("\t\tvec2 coord = %s - %d.0 * %s;\n", coords2D.c_str(), fRadius, imgInc);
82
83     // Manually unroll loop because some drivers don't; yields 20-30% speedup.
84     for (int i = 0; i < width; i++) {
85         SkString index;
86         SkString kernelIndex;
87         index.appendS32(i);
88         kernel.appendArrayAccess(index.c_str(), &kernelIndex);
89         builder->fsCodeAppendf("\t\t%s += ", outputColor);
90         builder->fsAppendTextureLookup(samplers[0], "coord");
91         if (this->useBounds()) {
92             const char* bounds = builder->getUniformCStr(fBoundsUni);
93             const char* component = this->direction() == Gr1DKernelEffect::kY_Direction ? "y" : "x";
94             builder->fsCodeAppendf(" * float(coord.%s >= %s.x && coord.%s <= %s.y)",
95                 component, bounds, component, bounds);
96         }
97         builder->fsCodeAppendf(" * %s;\n", kernelIndex.c_str());
98         builder->fsCodeAppendf("\t\tcoord += %s;\n", imgInc);
99     }
100
101     SkString modulate;
102     GrGLSLMulVarBy4f(&modulate, 2, outputColor, inputColor);
103     builder->fsCodeAppend(modulate.c_str());
104 }
105
106 void GrGLConvolutionEffect::setData(const GrGLProgramDataManager& pdman,
107                                     const GrDrawEffect& drawEffect) {
108     const GrConvolutionEffect& conv = drawEffect.castEffect<GrConvolutionEffect>();
109     GrTexture& texture = *conv.texture(0);
110     // the code we generated was for a specific kernel radius
111     SkASSERT(conv.radius() == fRadius);
112     float imageIncrement[2] = { 0 };
113     float ySign = texture.origin() != kTopLeft_GrSurfaceOrigin ? 1.0f : -1.0f;
114     switch (conv.direction()) {
115         case Gr1DKernelEffect::kX_Direction:
116             imageIncrement[0] = 1.0f / texture.width();
117             break;
118         case Gr1DKernelEffect::kY_Direction:
119             imageIncrement[1] = ySign / texture.height();
120             break;
121         default:
122             SkFAIL("Unknown filter direction.");
123     }
124     pdman.set2fv(fImageIncrementUni, 1, imageIncrement);
125     if (conv.useBounds()) {
126         const float* bounds = conv.bounds();
127         if (Gr1DKernelEffect::kY_Direction == conv.direction() &&
128             texture.origin() != kTopLeft_GrSurfaceOrigin) {
129             pdman.set2f(fBoundsUni, 1.0f - bounds[1], 1.0f - bounds[0]);
130         } else {
131             pdman.set2f(fBoundsUni, bounds[0], bounds[1]);
132         }
133     }
134     pdman.set1fv(fKernelUni, this->width(), conv.kernel());
135 }
136
137 void GrGLConvolutionEffect::GenKey(const GrDrawEffect& drawEffect, const GrGLCaps&,
138                                    GrEffectKeyBuilder* b) {
139     const GrConvolutionEffect& conv = drawEffect.castEffect<GrConvolutionEffect>();
140     uint32_t key = conv.radius();
141     key <<= 2;
142     if (conv.useBounds()) {
143         key |= 0x2;
144         key |= GrConvolutionEffect::kY_Direction == conv.direction() ? 0x1 : 0x0;
145     }
146     b->add32(key);
147 }
148
149 ///////////////////////////////////////////////////////////////////////////////
150
151 GrConvolutionEffect::GrConvolutionEffect(GrTexture* texture,
152                                          Direction direction,
153                                          int radius,
154                                          const float* kernel,
155                                          bool useBounds,
156                                          float bounds[2])
157     : Gr1DKernelEffect(texture, direction, radius), fUseBounds(useBounds) {
158     SkASSERT(radius <= kMaxKernelRadius);
159     SkASSERT(NULL != kernel);
160     int width = this->width();
161     for (int i = 0; i < width; i++) {
162         fKernel[i] = kernel[i];
163     }
164     memcpy(fBounds, bounds, sizeof(fBounds));
165 }
166
167 GrConvolutionEffect::GrConvolutionEffect(GrTexture* texture,
168                                          Direction direction,
169                                          int radius,
170                                          float gaussianSigma,
171                                          bool useBounds,
172                                          float bounds[2])
173     : Gr1DKernelEffect(texture, direction, radius), fUseBounds(useBounds) {
174     SkASSERT(radius <= kMaxKernelRadius);
175     int width = this->width();
176
177     float sum = 0.0f;
178     float denom = 1.0f / (2.0f * gaussianSigma * gaussianSigma);
179     for (int i = 0; i < width; ++i) {
180         float x = static_cast<float>(i - this->radius());
181         // Note that the constant term (1/(sqrt(2*pi*sigma^2)) of the Gaussian
182         // is dropped here, since we renormalize the kernel below.
183         fKernel[i] = sk_float_exp(- x * x * denom);
184         sum += fKernel[i];
185     }
186     // Normalize the kernel
187     float scale = 1.0f / sum;
188     for (int i = 0; i < width; ++i) {
189         fKernel[i] *= scale;
190     }
191     memcpy(fBounds, bounds, sizeof(fBounds));
192 }
193
194 GrConvolutionEffect::~GrConvolutionEffect() {
195 }
196
197 const GrBackendEffectFactory& GrConvolutionEffect::getFactory() const {
198     return GrTBackendEffectFactory<GrConvolutionEffect>::getInstance();
199 }
200
201 bool GrConvolutionEffect::onIsEqual(const GrEffect& sBase) const {
202     const GrConvolutionEffect& s = CastEffect<GrConvolutionEffect>(sBase);
203     return (this->texture(0) == s.texture(0) &&
204             this->radius() == s.radius() &&
205             this->direction() == s.direction() &&
206             this->useBounds() == s.useBounds() &&
207             0 == memcmp(fBounds, s.fBounds, sizeof(fBounds)) &&
208             0 == memcmp(fKernel, s.fKernel, this->width() * sizeof(float)));
209 }
210
211 ///////////////////////////////////////////////////////////////////////////////
212
213 GR_DEFINE_EFFECT_TEST(GrConvolutionEffect);
214
215 GrEffect* GrConvolutionEffect::TestCreate(SkRandom* random,
216                                           GrContext*,
217                                           const GrDrawTargetCaps&,
218                                           GrTexture* textures[]) {
219     int texIdx = random->nextBool() ? GrEffectUnitTest::kSkiaPMTextureIdx :
220                                       GrEffectUnitTest::kAlphaTextureIdx;
221     Direction dir = random->nextBool() ? kX_Direction : kY_Direction;
222     int radius = random->nextRangeU(1, kMaxKernelRadius);
223     float kernel[kMaxKernelWidth];
224     for (size_t i = 0; i < SK_ARRAY_COUNT(kernel); ++i) {
225         kernel[i] = random->nextSScalar1();
226     }
227     float bounds[2];
228     for (size_t i = 0; i < SK_ARRAY_COUNT(bounds); ++i) {
229         bounds[i] = random->nextF();
230     }
231
232     bool useBounds = random->nextBool();
233     return GrConvolutionEffect::Create(textures[texIdx],
234                                        dir,
235                                        radius,
236                                        kernel,
237                                        useBounds,
238                                        bounds);
239 }