Create GLSLUniformHandler class for gpu backend
[platform/upstream/libSkiaSharp.git] / src / gpu / effects / GrBicubicEffect.cpp
1 /*
2  * Copyright 2014 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 "GrBicubicEffect.h"
9 #include "GrInvariantOutput.h"
10 #include "glsl/GrGLSLFragmentShaderBuilder.h"
11 #include "glsl/GrGLSLProgramDataManager.h"
12 #include "glsl/GrGLSLUniformHandler.h"
13
14 #define DS(x) SkDoubleToScalar(x)
15
16 const SkScalar GrBicubicEffect::gMitchellCoefficients[16] = {
17     DS( 1.0 / 18.0), DS(-9.0 / 18.0), DS( 15.0 / 18.0), DS( -7.0 / 18.0),
18     DS(16.0 / 18.0), DS( 0.0 / 18.0), DS(-36.0 / 18.0), DS( 21.0 / 18.0),
19     DS( 1.0 / 18.0), DS( 9.0 / 18.0), DS( 27.0 / 18.0), DS(-21.0 / 18.0),
20     DS( 0.0 / 18.0), DS( 0.0 / 18.0), DS( -6.0 / 18.0), DS(  7.0 / 18.0),
21 };
22
23
24 class GrGLBicubicEffect : public GrGLSLFragmentProcessor {
25 public:
26     GrGLBicubicEffect(const GrProcessor&);
27
28     virtual void emitCode(EmitArgs&) override;
29
30     static inline void GenKey(const GrProcessor& effect, const GrGLSLCaps&,
31                               GrProcessorKeyBuilder* b) {
32         const GrTextureDomain& domain = effect.cast<GrBicubicEffect>().domain();
33         b->add32(GrTextureDomain::GLDomain::DomainKey(domain));
34     }
35
36 protected:
37     void onSetData(const GrGLSLProgramDataManager&, const GrProcessor&) override;
38
39 private:
40     typedef GrGLSLProgramDataManager::UniformHandle UniformHandle;
41
42     UniformHandle               fCoefficientsUni;
43     UniformHandle               fImageIncrementUni;
44     GrTextureDomain::GLDomain   fDomain;
45
46     typedef GrGLSLFragmentProcessor INHERITED;
47 };
48
49 GrGLBicubicEffect::GrGLBicubicEffect(const GrProcessor&) {
50 }
51
52 void GrGLBicubicEffect::emitCode(EmitArgs& args) {
53     const GrTextureDomain& domain = args.fFp.cast<GrBicubicEffect>().domain();
54
55     GrGLSLUniformHandler* uniformHandler = args.fUniformHandler;
56     fCoefficientsUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility,
57                                                   kMat44f_GrSLType, kDefault_GrSLPrecision,
58                                                   "Coefficients");
59     fImageIncrementUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility,
60                                                     kVec2f_GrSLType, kDefault_GrSLPrecision,
61                                                     "ImageIncrement");
62
63     const char* imgInc = uniformHandler->getUniformCStr(fImageIncrementUni);
64     const char* coeff = uniformHandler->getUniformCStr(fCoefficientsUni);
65
66     SkString cubicBlendName;
67
68     static const GrGLSLShaderVar gCubicBlendArgs[] = {
69         GrGLSLShaderVar("coefficients",  kMat44f_GrSLType),
70         GrGLSLShaderVar("t",             kFloat_GrSLType),
71         GrGLSLShaderVar("c0",            kVec4f_GrSLType),
72         GrGLSLShaderVar("c1",            kVec4f_GrSLType),
73         GrGLSLShaderVar("c2",            kVec4f_GrSLType),
74         GrGLSLShaderVar("c3",            kVec4f_GrSLType),
75     };
76     GrGLSLFragmentBuilder* fragBuilder = args.fFragBuilder;
77     SkString coords2D = fragBuilder->ensureFSCoords2D(args.fCoords, 0);
78     fragBuilder->emitFunction(kVec4f_GrSLType,
79                               "cubicBlend",
80                               SK_ARRAY_COUNT(gCubicBlendArgs),
81                               gCubicBlendArgs,
82                               "\tvec4 ts = vec4(1.0, t, t * t, t * t * t);\n"
83                               "\tvec4 c = coefficients * ts;\n"
84                               "\treturn c.x * c0 + c.y * c1 + c.z * c2 + c.w * c3;\n",
85                               &cubicBlendName);
86     fragBuilder->codeAppendf("\tvec2 coord = %s - %s * vec2(0.5);\n", coords2D.c_str(), imgInc);
87     // We unnormalize the coord in order to determine our fractional offset (f) within the texel
88     // We then snap coord to a texel center and renormalize. The snap prevents cases where the
89     // starting coords are near a texel boundary and accumulations of imgInc would cause us to skip/
90     // double hit a texel.
91     fragBuilder->codeAppendf("\tcoord /= %s;\n", imgInc);
92     fragBuilder->codeAppend("\tvec2 f = fract(coord);\n");
93     fragBuilder->codeAppendf("\tcoord = (coord - f + vec2(0.5)) * %s;\n", imgInc);
94     fragBuilder->codeAppend("\tvec4 rowColors[4];\n");
95     for (int y = 0; y < 4; ++y) {
96         for (int x = 0; x < 4; ++x) {
97             SkString coord;
98             coord.printf("coord + %s * vec2(%d, %d)", imgInc, x - 1, y - 1);
99             SkString sampleVar;
100             sampleVar.printf("rowColors[%d]", x);
101             fDomain.sampleTexture(fragBuilder,
102                                   args.fUniformHandler,
103                                   args.fGLSLCaps,
104                                   domain,
105                                   sampleVar.c_str(),
106                                   coord,
107                                   args.fSamplers[0]);
108         }
109         fragBuilder->codeAppendf(
110             "\tvec4 s%d = %s(%s, f.x, rowColors[0], rowColors[1], rowColors[2], rowColors[3]);\n",
111             y, cubicBlendName.c_str(), coeff);
112     }
113     SkString bicubicColor;
114     bicubicColor.printf("%s(%s, f.y, s0, s1, s2, s3)", cubicBlendName.c_str(), coeff);
115     fragBuilder->codeAppendf("\t%s = %s;\n",
116                              args.fOutputColor, (GrGLSLExpr4(bicubicColor.c_str()) *
117                                                  GrGLSLExpr4(args.fInputColor)).c_str());
118 }
119
120 void GrGLBicubicEffect::onSetData(const GrGLSLProgramDataManager& pdman,
121                                   const GrProcessor& processor) {
122     const GrBicubicEffect& bicubicEffect = processor.cast<GrBicubicEffect>();
123     const GrTexture& texture = *processor.texture(0);
124     float imageIncrement[2];
125     imageIncrement[0] = 1.0f / texture.width();
126     imageIncrement[1] = 1.0f / texture.height();
127     pdman.set2fv(fImageIncrementUni, 1, imageIncrement);
128     pdman.setMatrix4f(fCoefficientsUni, bicubicEffect.coefficients());
129     fDomain.setData(pdman, bicubicEffect.domain(), texture.origin());
130 }
131
132 static inline void convert_row_major_scalar_coeffs_to_column_major_floats(float dst[16],
133                                                                           const SkScalar src[16]) {
134     for (int y = 0; y < 4; y++) {
135         for (int x = 0; x < 4; x++) {
136             dst[x * 4 + y] = SkScalarToFloat(src[y * 4 + x]);
137         }
138     }
139 }
140
141 GrBicubicEffect::GrBicubicEffect(GrTexture* texture,
142                                  const SkScalar coefficients[16],
143                                  const SkMatrix &matrix,
144                                  const SkShader::TileMode tileModes[2])
145   : INHERITED(texture, matrix, GrTextureParams(tileModes, GrTextureParams::kNone_FilterMode))
146   , fDomain(GrTextureDomain::IgnoredDomain()) {
147     this->initClassID<GrBicubicEffect>();
148     convert_row_major_scalar_coeffs_to_column_major_floats(fCoefficients, coefficients);
149 }
150
151 GrBicubicEffect::GrBicubicEffect(GrTexture* texture,
152                                  const SkScalar coefficients[16],
153                                  const SkMatrix &matrix,
154                                  const SkRect& domain)
155   : INHERITED(texture, matrix,
156               GrTextureParams(SkShader::kClamp_TileMode, GrTextureParams::kNone_FilterMode))
157   , fDomain(domain, GrTextureDomain::kClamp_Mode) {
158     this->initClassID<GrBicubicEffect>();
159     convert_row_major_scalar_coeffs_to_column_major_floats(fCoefficients, coefficients);
160 }
161
162 GrBicubicEffect::~GrBicubicEffect() {
163 }
164
165 void GrBicubicEffect::onGetGLSLProcessorKey(const GrGLSLCaps& caps,
166                                             GrProcessorKeyBuilder* b) const {
167     GrGLBicubicEffect::GenKey(*this, caps, b);
168 }
169
170 GrGLSLFragmentProcessor* GrBicubicEffect::onCreateGLSLInstance() const  {
171     return new GrGLBicubicEffect(*this);
172 }
173
174 bool GrBicubicEffect::onIsEqual(const GrFragmentProcessor& sBase) const {
175     const GrBicubicEffect& s = sBase.cast<GrBicubicEffect>();
176     return !memcmp(fCoefficients, s.coefficients(), 16) &&
177            fDomain == s.fDomain;
178 }
179
180 void GrBicubicEffect::onComputeInvariantOutput(GrInvariantOutput* inout) const {
181     // FIXME: Perhaps we can do better.
182     inout->mulByUnknownSingleComponent();
183 }
184
185 GR_DEFINE_FRAGMENT_PROCESSOR_TEST(GrBicubicEffect);
186
187 const GrFragmentProcessor* GrBicubicEffect::TestCreate(GrProcessorTestData* d) {
188     int texIdx = d->fRandom->nextBool() ? GrProcessorUnitTest::kSkiaPMTextureIdx :
189                                           GrProcessorUnitTest::kAlphaTextureIdx;
190     SkScalar coefficients[16];
191     for (int i = 0; i < 16; i++) {
192         coefficients[i] = d->fRandom->nextSScalar1();
193     }
194     return GrBicubicEffect::Create(d->fTextures[texIdx], coefficients);
195 }
196
197 //////////////////////////////////////////////////////////////////////////////
198
199 bool GrBicubicEffect::ShouldUseBicubic(const SkMatrix& matrix,
200                                        GrTextureParams::FilterMode* filterMode) {
201     if (matrix.isIdentity()) {
202         *filterMode = GrTextureParams::kNone_FilterMode;
203         return false;
204     }
205
206     SkScalar scales[2];
207     if (!matrix.getMinMaxScales(scales) || scales[0] < SK_Scalar1) {
208         // Bicubic doesn't handle arbitrary minimization well, as src texels can be skipped
209         // entirely,
210         *filterMode = GrTextureParams::kMipMap_FilterMode;
211         return false;
212     }
213     // At this point if scales[1] == SK_Scalar1 then the matrix doesn't do any scaling.
214     if (scales[1] == SK_Scalar1) {
215         if (matrix.rectStaysRect() && SkScalarIsInt(matrix.getTranslateX()) &&
216             SkScalarIsInt(matrix.getTranslateY())) {
217             *filterMode = GrTextureParams::kNone_FilterMode;
218         } else {
219             // Use bilerp to handle rotation or fractional translation.
220             *filterMode = GrTextureParams::kBilerp_FilterMode;
221         }
222         return false;
223     }
224     // When we use the bicubic filtering effect each sample is read from the texture using
225     // nearest neighbor sampling.
226     *filterMode = GrTextureParams::kNone_FilterMode;
227     return true;
228 }