Create GLSLUniformHandler class for gpu backend
[platform/upstream/libSkiaSharp.git] / src / gpu / effects / GrTextureDomain.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 "GrTextureDomain.h"
9 #include "GrInvariantOutput.h"
10 #include "GrSimpleTextureEffect.h"
11 #include "SkFloatingPoint.h"
12 #include "glsl/GrGLSLFragmentProcessor.h"
13 #include "glsl/GrGLSLFragmentShaderBuilder.h"
14 #include "glsl/GrGLSLProgramDataManager.h"
15 #include "glsl/GrGLSLShaderBuilder.h"
16 #include "glsl/GrGLSLTextureSampler.h"
17 #include "glsl/GrGLSLUniformHandler.h"
18
19 GrTextureDomain::GrTextureDomain(const SkRect& domain, Mode mode, int index)
20     : fIndex(index) {
21
22     static const SkRect kFullRect = {0, 0, SK_Scalar1, SK_Scalar1};
23     if (domain.contains(kFullRect) && kClamp_Mode == mode) {
24         fMode = kIgnore_Mode;
25     } else {
26         fMode = mode;
27     }
28
29     if (fMode != kIgnore_Mode) {
30         // We don't currently handle domains that are empty or don't intersect the texture.
31         // It is OK if the domain rect is a line or point, but it should not be inverted. We do not
32         // handle rects that do not intersect the [0..1]x[0..1] rect.
33         SkASSERT(domain.fLeft <= domain.fRight);
34         SkASSERT(domain.fTop <= domain.fBottom);
35         fDomain.fLeft = SkScalarPin(domain.fLeft, kFullRect.fLeft, kFullRect.fRight);
36         fDomain.fRight = SkScalarPin(domain.fRight, kFullRect.fLeft, kFullRect.fRight);
37         fDomain.fTop = SkScalarPin(domain.fTop, kFullRect.fTop, kFullRect.fBottom);
38         fDomain.fBottom = SkScalarPin(domain.fBottom, kFullRect.fTop, kFullRect.fBottom);
39         SkASSERT(fDomain.fLeft <= fDomain.fRight);
40         SkASSERT(fDomain.fTop <= fDomain.fBottom);
41     }
42 }
43
44 //////////////////////////////////////////////////////////////////////////////
45
46 void GrTextureDomain::GLDomain::sampleTexture(GrGLSLShaderBuilder* builder,
47                                               GrGLSLUniformHandler* uniformHandler,
48                                               const GrGLSLCaps* glslCaps,
49                                               const GrTextureDomain& textureDomain,
50                                               const char* outColor,
51                                               const SkString& inCoords,
52                                               const GrGLSLTextureSampler& sampler,
53                                               const char* inModulateColor) {
54     SkASSERT((Mode)-1 == fMode || textureDomain.mode() == fMode);
55     SkDEBUGCODE(fMode = textureDomain.mode();)
56
57     if (textureDomain.mode() != kIgnore_Mode && !fDomainUni.isValid()) {
58         const char* name;
59         SkString uniName("TexDom");
60         if (textureDomain.fIndex >= 0) {
61             uniName.appendS32(textureDomain.fIndex);
62         }
63         fDomainUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility,
64                                                 kVec4f_GrSLType, kDefault_GrSLPrecision,
65                                                 uniName.c_str(), &name);
66         fDomainName = name;
67     }
68
69     switch (textureDomain.mode()) {
70         case kIgnore_Mode: {
71             builder->codeAppendf("%s = ", outColor);
72             builder->appendTextureLookupAndModulate(inModulateColor, sampler,
73                                                       inCoords.c_str());
74             builder->codeAppend(";");
75             break;
76         }
77         case kClamp_Mode: {
78             SkString clampedCoords;
79             clampedCoords.appendf("clamp(%s, %s.xy, %s.zw)",
80                                   inCoords.c_str(), fDomainName.c_str(), fDomainName.c_str());
81
82             builder->codeAppendf("%s = ", outColor);
83             builder->appendTextureLookupAndModulate(inModulateColor, sampler,
84                                                       clampedCoords.c_str());
85             builder->codeAppend(";");
86             break;
87         }
88         case kDecal_Mode: {
89             // Add a block since we're going to declare variables.
90             GrGLSLShaderBuilder::ShaderBlock block(builder);
91
92             const char* domain = fDomainName.c_str();
93             if (!glslCaps->canUseAnyFunctionInShader()) {
94                 // On the NexusS and GalaxyNexus, the other path (with the 'any'
95                 // call) causes the compilation error "Calls to any function that
96                 // may require a gradient calculation inside a conditional block
97                 // may return undefined results". This appears to be an issue with
98                 // the 'any' call since even the simple "result=black; if (any())
99                 // result=white;" code fails to compile.
100                 builder->codeAppend("vec4 outside = vec4(0.0, 0.0, 0.0, 0.0);");
101                 builder->codeAppend("vec4 inside = ");
102                 builder->appendTextureLookupAndModulate(inModulateColor, sampler,
103                                                           inCoords.c_str());
104                 builder->codeAppend(";");
105                 
106                 builder->codeAppend(GrGLSLShaderVar::PrecisionString(glslCaps,
107                                                                      kHigh_GrSLPrecision));
108                 builder->codeAppendf("float x = (%s).x;", inCoords.c_str());
109                 builder->codeAppend(GrGLSLShaderVar::PrecisionString(glslCaps,
110                                                                      kHigh_GrSLPrecision));
111                 builder->codeAppendf("float y = (%s).y;", inCoords.c_str());
112
113                 builder->codeAppendf("x = abs(2.0*(x - %s.x)/(%s.z - %s.x) - 1.0);",
114                                      domain, domain, domain);
115                 builder->codeAppendf("y = abs(2.0*(y - %s.y)/(%s.w - %s.y) - 1.0);",
116                                      domain, domain, domain);
117                 builder->codeAppend("float blend = step(1.0, max(x, y));");
118                 builder->codeAppendf("%s = mix(inside, outside, blend);", outColor);
119             } else {
120                 builder->codeAppend("bvec4 outside;\n");
121                 builder->codeAppendf("outside.xy = lessThan(%s, %s.xy);", inCoords.c_str(),
122                                        domain);
123                 builder->codeAppendf("outside.zw = greaterThan(%s, %s.zw);", inCoords.c_str(),
124                                        domain);
125                 builder->codeAppendf("%s = any(outside) ? vec4(0.0, 0.0, 0.0, 0.0) : ",
126                                        outColor);
127                 builder->appendTextureLookupAndModulate(inModulateColor, sampler,
128                                                           inCoords.c_str());
129                 builder->codeAppend(";");
130             }
131             break;
132         }
133         case kRepeat_Mode: {
134             SkString clampedCoords;
135             clampedCoords.printf("mod(%s - %s.xy, %s.zw - %s.xy) + %s.xy",
136                                  inCoords.c_str(), fDomainName.c_str(), fDomainName.c_str(),
137                                  fDomainName.c_str(), fDomainName.c_str());
138
139             builder->codeAppendf("%s = ", outColor);
140             builder->appendTextureLookupAndModulate(inModulateColor, sampler,
141                                                       clampedCoords.c_str());
142             builder->codeAppend(";");
143             break;
144         }
145     }
146 }
147
148 void GrTextureDomain::GLDomain::setData(const GrGLSLProgramDataManager& pdman,
149                                         const GrTextureDomain& textureDomain,
150                                         GrSurfaceOrigin textureOrigin) {
151     SkASSERT(textureDomain.mode() == fMode);
152     if (kIgnore_Mode != textureDomain.mode()) {
153         float values[kPrevDomainCount] = {
154             SkScalarToFloat(textureDomain.domain().left()),
155             SkScalarToFloat(textureDomain.domain().top()),
156             SkScalarToFloat(textureDomain.domain().right()),
157             SkScalarToFloat(textureDomain.domain().bottom())
158         };
159         // vertical flip if necessary
160         if (kBottomLeft_GrSurfaceOrigin == textureOrigin) {
161             values[1] = 1.0f - values[1];
162             values[3] = 1.0f - values[3];
163             // The top and bottom were just flipped, so correct the ordering
164             // of elements so that values = (l, t, r, b).
165             SkTSwap(values[1], values[3]);
166         }
167         if (0 != memcmp(values, fPrevDomain, kPrevDomainCount * sizeof(float))) {
168             pdman.set4fv(fDomainUni, 1, values);
169             memcpy(fPrevDomain, values, kPrevDomainCount * sizeof(float));
170         }
171     }
172 }
173
174
175 //////////////////////////////////////////////////////////////////////////////
176
177 class GrGLTextureDomainEffect : public GrGLSLFragmentProcessor {
178 public:
179     GrGLTextureDomainEffect(const GrProcessor&);
180
181     virtual void emitCode(EmitArgs&) override;
182
183     static inline void GenKey(const GrProcessor&, const GrGLSLCaps&, GrProcessorKeyBuilder*);
184
185 protected:
186     void onSetData(const GrGLSLProgramDataManager&, const GrProcessor&) override;
187
188 private:
189     GrTextureDomain::GLDomain         fGLDomain;
190     typedef GrGLSLFragmentProcessor INHERITED;
191 };
192
193 GrGLTextureDomainEffect::GrGLTextureDomainEffect(const GrProcessor&) {
194 }
195
196 void GrGLTextureDomainEffect::emitCode(EmitArgs& args) {
197     const GrTextureDomainEffect& textureDomainEffect = args.fFp.cast<GrTextureDomainEffect>();
198     const GrTextureDomain& domain = textureDomainEffect.textureDomain();
199
200     GrGLSLFragmentBuilder* fragBuilder = args.fFragBuilder;
201     SkString coords2D = fragBuilder->ensureFSCoords2D(args.fCoords, 0);
202     fGLDomain.sampleTexture(fragBuilder,
203                             args.fUniformHandler,
204                             args.fGLSLCaps,
205                             domain,
206                             args.fOutputColor,
207                             coords2D,
208                             args.fSamplers[0],
209                             args.fInputColor);
210 }
211
212 void GrGLTextureDomainEffect::onSetData(const GrGLSLProgramDataManager& pdman,
213                                         const GrProcessor& processor) {
214     const GrTextureDomainEffect& textureDomainEffect = processor.cast<GrTextureDomainEffect>();
215     const GrTextureDomain& domain = textureDomainEffect.textureDomain();
216     fGLDomain.setData(pdman, domain, processor.texture(0)->origin());
217 }
218
219 void GrGLTextureDomainEffect::GenKey(const GrProcessor& processor, const GrGLSLCaps&,
220                                      GrProcessorKeyBuilder* b) {
221     const GrTextureDomain& domain = processor.cast<GrTextureDomainEffect>().textureDomain();
222     b->add32(GrTextureDomain::GLDomain::DomainKey(domain));
223 }
224
225
226 ///////////////////////////////////////////////////////////////////////////////
227
228 const GrFragmentProcessor* GrTextureDomainEffect::Create(GrTexture* texture,
229                                                          const SkMatrix& matrix,
230                                                          const SkRect& domain,
231                                                          GrTextureDomain::Mode mode,
232                                                          GrTextureParams::FilterMode filterMode,
233                                                          GrCoordSet coordSet) {
234     static const SkRect kFullRect = {0, 0, SK_Scalar1, SK_Scalar1};
235     if (GrTextureDomain::kIgnore_Mode == mode ||
236         (GrTextureDomain::kClamp_Mode == mode && domain.contains(kFullRect))) {
237         return GrSimpleTextureEffect::Create(texture, matrix, filterMode);
238     } else {
239         return new GrTextureDomainEffect(texture, matrix, domain, mode, filterMode, coordSet);
240     }
241 }
242
243 GrTextureDomainEffect::GrTextureDomainEffect(GrTexture* texture,
244                                              const SkMatrix& matrix,
245                                              const SkRect& domain,
246                                              GrTextureDomain::Mode mode,
247                                              GrTextureParams::FilterMode filterMode,
248                                              GrCoordSet coordSet)
249     : GrSingleTextureEffect(texture, matrix, filterMode, coordSet)
250     , fTextureDomain(domain, mode) {
251     SkASSERT(mode != GrTextureDomain::kRepeat_Mode ||
252             filterMode == GrTextureParams::kNone_FilterMode);
253     this->initClassID<GrTextureDomainEffect>();
254 }
255
256 GrTextureDomainEffect::~GrTextureDomainEffect() {}
257
258 void GrTextureDomainEffect::onGetGLSLProcessorKey(const GrGLSLCaps& caps,
259                                                   GrProcessorKeyBuilder* b) const {
260     GrGLTextureDomainEffect::GenKey(*this, caps, b);
261 }
262
263 GrGLSLFragmentProcessor* GrTextureDomainEffect::onCreateGLSLInstance() const  {
264     return new GrGLTextureDomainEffect(*this);
265 }
266
267 bool GrTextureDomainEffect::onIsEqual(const GrFragmentProcessor& sBase) const {
268     const GrTextureDomainEffect& s = sBase.cast<GrTextureDomainEffect>();
269     return this->fTextureDomain == s.fTextureDomain;
270 }
271
272 void GrTextureDomainEffect::onComputeInvariantOutput(GrInvariantOutput* inout) const {
273     if (GrTextureDomain::kDecal_Mode == fTextureDomain.mode()) { // TODO: helper
274         if (GrPixelConfigIsAlphaOnly(this->texture(0)->config())) {
275             inout->mulByUnknownSingleComponent();
276         } else {
277             inout->mulByUnknownFourComponents();
278         }
279     } else {
280         this->updateInvariantOutputForModulation(inout);
281     }
282 }
283
284 ///////////////////////////////////////////////////////////////////////////////
285
286 GR_DEFINE_FRAGMENT_PROCESSOR_TEST(GrTextureDomainEffect);
287
288 const GrFragmentProcessor* GrTextureDomainEffect::TestCreate(GrProcessorTestData* d) {
289     int texIdx = d->fRandom->nextBool() ? GrProcessorUnitTest::kSkiaPMTextureIdx :
290                                           GrProcessorUnitTest::kAlphaTextureIdx;
291     SkRect domain;
292     domain.fLeft = d->fRandom->nextUScalar1();
293     domain.fRight = d->fRandom->nextRangeScalar(domain.fLeft, SK_Scalar1);
294     domain.fTop = d->fRandom->nextUScalar1();
295     domain.fBottom = d->fRandom->nextRangeScalar(domain.fTop, SK_Scalar1);
296     GrTextureDomain::Mode mode =
297         (GrTextureDomain::Mode) d->fRandom->nextULessThan(GrTextureDomain::kModeCount);
298     const SkMatrix& matrix = GrTest::TestMatrix(d->fRandom);
299     bool bilerp = mode != GrTextureDomain::kRepeat_Mode ? d->fRandom->nextBool() : false;
300     GrCoordSet coords = d->fRandom->nextBool() ? kLocal_GrCoordSet : kDevice_GrCoordSet;
301     return GrTextureDomainEffect::Create(
302         d->fTextures[texIdx],
303         matrix,
304         domain,
305         mode,
306         bilerp ? GrTextureParams::kBilerp_FilterMode : GrTextureParams::kNone_FilterMode,
307         coords);
308 }