4df894b40a64de0c68df08e502c9d9e179652210
[platform/upstream/libSkiaSharp.git] / src / gpu / effects / GrConfigConversionEffect.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 "GrConfigConversionEffect.h"
9 #include "GrContext.h"
10 #include "GrDrawContext.h"
11 #include "GrInvariantOutput.h"
12 #include "GrSimpleTextureEffect.h"
13 #include "SkMatrix.h"
14 #include "glsl/GrGLSLFragmentProcessor.h"
15 #include "glsl/GrGLSLFragmentShaderBuilder.h"
16 #include "glsl/GrGLSLProgramBuilder.h"
17
18 class GrGLConfigConversionEffect : public GrGLSLFragmentProcessor {
19 public:
20     GrGLConfigConversionEffect(const GrProcessor& processor) {
21         const GrConfigConversionEffect& configConversionEffect =
22                 processor.cast<GrConfigConversionEffect>();
23         fSwapRedAndBlue = configConversionEffect.swapsRedAndBlue();
24         fPMConversion = configConversionEffect.pmConversion();
25     }
26
27     virtual void emitCode(EmitArgs& args) override {
28         // Using highp for GLES here in order to avoid some precision issues on specific GPUs.
29         GrGLSLShaderVar tmpVar("tmpColor", kVec4f_GrSLType, 0, kHigh_GrSLPrecision);
30         SkString tmpDecl;
31         tmpVar.appendDecl(args.fGLSLCaps, &tmpDecl);
32
33         GrGLSLFragmentBuilder* fragBuilder = args.fFragBuilder;
34
35         fragBuilder->codeAppendf("%s;", tmpDecl.c_str());
36
37         fragBuilder->codeAppendf("%s = ", tmpVar.c_str());
38         fragBuilder->appendTextureLookup(args.fSamplers[0], args.fCoords[0].c_str(),
39                                        args.fCoords[0].getType());
40         fragBuilder->codeAppend(";");
41
42         if (GrConfigConversionEffect::kNone_PMConversion == fPMConversion) {
43             SkASSERT(fSwapRedAndBlue);
44             fragBuilder->codeAppendf("%s = %s.bgra;", args.fOutputColor, tmpVar.c_str());
45         } else {
46             const char* swiz = fSwapRedAndBlue ? "bgr" : "rgb";
47             switch (fPMConversion) {
48                 case GrConfigConversionEffect::kMulByAlpha_RoundUp_PMConversion:
49                     fragBuilder->codeAppendf(
50                         "%s = vec4(ceil(%s.%s * %s.a * 255.0) / 255.0, %s.a);",
51                         tmpVar.c_str(), tmpVar.c_str(), swiz, tmpVar.c_str(), tmpVar.c_str());
52                     break;
53                 case GrConfigConversionEffect::kMulByAlpha_RoundDown_PMConversion:
54                     // Add a compensation(0.001) here to avoid the side effect of the floor operation.
55                     // In Intel GPUs, the integer value converted from floor(%s.r * 255.0) / 255.0
56                     // is less than the integer value converted from  %s.r by 1 when the %s.r is
57                     // converted from the integer value 2^n, such as 1, 2, 4, 8, etc.
58                     fragBuilder->codeAppendf(
59                         "%s = vec4(floor(%s.%s * %s.a * 255.0 + 0.001) / 255.0, %s.a);",
60                         tmpVar.c_str(), tmpVar.c_str(), swiz, tmpVar.c_str(), tmpVar.c_str());
61                     break;
62                 case GrConfigConversionEffect::kDivByAlpha_RoundUp_PMConversion:
63                     fragBuilder->codeAppendf(
64                         "%s = %s.a <= 0.0 ? vec4(0,0,0,0) : vec4(ceil(%s.%s / %s.a * 255.0) / 255.0, %s.a);",
65                         tmpVar.c_str(), tmpVar.c_str(), tmpVar.c_str(), swiz, tmpVar.c_str(), tmpVar.c_str());
66                     break;
67                 case GrConfigConversionEffect::kDivByAlpha_RoundDown_PMConversion:
68                     fragBuilder->codeAppendf(
69                         "%s = %s.a <= 0.0 ? vec4(0,0,0,0) : vec4(floor(%s.%s / %s.a * 255.0) / 255.0, %s.a);",
70                         tmpVar.c_str(), tmpVar.c_str(), tmpVar.c_str(), swiz, tmpVar.c_str(), tmpVar.c_str());
71                     break;
72                 default:
73                     SkFAIL("Unknown conversion op.");
74                     break;
75             }
76             fragBuilder->codeAppendf("%s = %s;", args.fOutputColor, tmpVar.c_str());
77         }
78         SkString modulate;
79         GrGLSLMulVarBy4f(&modulate, args.fOutputColor, args.fInputColor);
80         fragBuilder->codeAppend(modulate.c_str());
81     }
82
83     static inline void GenKey(const GrProcessor& processor, const GrGLSLCaps&,
84                               GrProcessorKeyBuilder* b) {
85         const GrConfigConversionEffect& conv = processor.cast<GrConfigConversionEffect>();
86         uint32_t key = (conv.swapsRedAndBlue() ? 0 : 1) | (conv.pmConversion() << 1);
87         b->add32(key);
88     }
89
90 private:
91     bool                                    fSwapRedAndBlue;
92     GrConfigConversionEffect::PMConversion  fPMConversion;
93
94     typedef GrGLSLFragmentProcessor INHERITED;
95
96 };
97
98 ///////////////////////////////////////////////////////////////////////////////
99
100 GrConfigConversionEffect::GrConfigConversionEffect(GrTexture* texture,
101                                                    bool swapRedAndBlue,
102                                                    PMConversion pmConversion,
103                                                    const SkMatrix& matrix)
104     : INHERITED(texture, matrix)
105     , fSwapRedAndBlue(swapRedAndBlue)
106     , fPMConversion(pmConversion) {
107     this->initClassID<GrConfigConversionEffect>();
108     // We expect to get here with non-BGRA/RGBA only if we're doing not doing a premul/unpremul
109     // conversion.
110     SkASSERT((kRGBA_8888_GrPixelConfig == texture->config() ||
111               kBGRA_8888_GrPixelConfig == texture->config()) ||
112               kNone_PMConversion == pmConversion);
113     // Why did we pollute our texture cache instead of using a GrSingleTextureEffect?
114     SkASSERT(swapRedAndBlue || kNone_PMConversion != pmConversion);
115 }
116
117 bool GrConfigConversionEffect::onIsEqual(const GrFragmentProcessor& s) const {
118     const GrConfigConversionEffect& other = s.cast<GrConfigConversionEffect>();
119     return other.fSwapRedAndBlue == fSwapRedAndBlue &&
120            other.fPMConversion == fPMConversion;
121 }
122
123 void GrConfigConversionEffect::onComputeInvariantOutput(GrInvariantOutput* inout) const {
124     this->updateInvariantOutputForModulation(inout);
125 }
126
127 ///////////////////////////////////////////////////////////////////////////////
128
129 GR_DEFINE_FRAGMENT_PROCESSOR_TEST(GrConfigConversionEffect);
130
131 const GrFragmentProcessor* GrConfigConversionEffect::TestCreate(GrProcessorTestData* d) {
132     PMConversion pmConv = static_cast<PMConversion>(d->fRandom->nextULessThan(kPMConversionCnt));
133     bool swapRB;
134     if (kNone_PMConversion == pmConv) {
135         swapRB = true;
136     } else {
137         swapRB = d->fRandom->nextBool();
138     }
139     return new GrConfigConversionEffect(d->fTextures[GrProcessorUnitTest::kSkiaPMTextureIdx],
140                                         swapRB, pmConv, GrTest::TestMatrix(d->fRandom));
141 }
142
143 ///////////////////////////////////////////////////////////////////////////////
144
145 void GrConfigConversionEffect::onGetGLSLProcessorKey(const GrGLSLCaps& caps,
146                                                      GrProcessorKeyBuilder* b) const {
147     GrGLConfigConversionEffect::GenKey(*this, caps, b);
148 }
149
150 GrGLSLFragmentProcessor* GrConfigConversionEffect::onCreateGLSLInstance() const {
151     return new GrGLConfigConversionEffect(*this);
152 }
153
154
155
156 void GrConfigConversionEffect::TestForPreservingPMConversions(GrContext* context,
157                                                               PMConversion* pmToUPMRule,
158                                                               PMConversion* upmToPMRule) {
159     *pmToUPMRule = kNone_PMConversion;
160     *upmToPMRule = kNone_PMConversion;
161     SkAutoTMalloc<uint32_t> data(256 * 256 * 3);
162     uint32_t* srcData = data.get();
163     uint32_t* firstRead = data.get() + 256 * 256;
164     uint32_t* secondRead = data.get() + 2 * 256 * 256;
165
166     // Fill with every possible premultiplied A, color channel value. There will be 256-y duplicate
167     // values in row y. We set r,g, and b to the same value since they are handled identically.
168     for (int y = 0; y < 256; ++y) {
169         for (int x = 0; x < 256; ++x) {
170             uint8_t* color = reinterpret_cast<uint8_t*>(&srcData[256*y + x]);
171             color[3] = y;
172             color[2] = SkTMin(x, y);
173             color[1] = SkTMin(x, y);
174             color[0] = SkTMin(x, y);
175         }
176     }
177
178     GrSurfaceDesc desc;
179     desc.fFlags = kRenderTarget_GrSurfaceFlag;
180     desc.fWidth = 256;
181     desc.fHeight = 256;
182     desc.fConfig = kRGBA_8888_GrPixelConfig;
183
184     SkAutoTUnref<GrTexture> readTex(context->textureProvider()->createTexture(desc, true, nullptr, 0));
185     if (!readTex.get()) {
186         return;
187     }
188     SkAutoTUnref<GrTexture> tempTex(context->textureProvider()->createTexture(desc, true, nullptr, 0));
189     if (!tempTex.get()) {
190         return;
191     }
192     desc.fFlags = kNone_GrSurfaceFlags;
193     SkAutoTUnref<GrTexture> dataTex(context->textureProvider()->createTexture(desc, true, data, 0));
194     if (!dataTex.get()) {
195         return;
196     }
197
198     static const PMConversion kConversionRules[][2] = {
199         {kDivByAlpha_RoundDown_PMConversion, kMulByAlpha_RoundUp_PMConversion},
200         {kDivByAlpha_RoundUp_PMConversion, kMulByAlpha_RoundDown_PMConversion},
201     };
202
203     bool failed = true;
204
205     for (size_t i = 0; i < SK_ARRAY_COUNT(kConversionRules) && failed; ++i) {
206         *pmToUPMRule = kConversionRules[i][0];
207         *upmToPMRule = kConversionRules[i][1];
208
209         static const SkRect kDstRect = SkRect::MakeWH(SkIntToScalar(256), SkIntToScalar(256));
210         static const SkRect kSrcRect = SkRect::MakeWH(SK_Scalar1, SK_Scalar1);
211         // We do a PM->UPM draw from dataTex to readTex and read the data. Then we do a UPM->PM draw
212         // from readTex to tempTex followed by a PM->UPM draw to readTex and finally read the data.
213         // We then verify that two reads produced the same values.
214
215         GrPaint paint1;
216         GrPaint paint2;
217         GrPaint paint3;
218         SkAutoTUnref<GrFragmentProcessor> pmToUPM1(new GrConfigConversionEffect(
219                 dataTex, false, *pmToUPMRule, SkMatrix::I()));
220         SkAutoTUnref<GrFragmentProcessor> upmToPM(new GrConfigConversionEffect(
221                 readTex, false, *upmToPMRule, SkMatrix::I()));
222         SkAutoTUnref<GrFragmentProcessor> pmToUPM2(new GrConfigConversionEffect(
223                 tempTex, false, *pmToUPMRule, SkMatrix::I()));
224
225         paint1.addColorFragmentProcessor(pmToUPM1);
226         paint1.setPorterDuffXPFactory(SkXfermode::kSrc_Mode);
227
228
229         SkAutoTUnref<GrDrawContext> readDrawContext(
230                                     context->drawContext(readTex->asRenderTarget()));
231         if (!readDrawContext) {
232             failed = true;
233             break;
234         }
235
236         readDrawContext->fillRectToRect(GrClip::WideOpen(),
237                                         paint1,
238                                         SkMatrix::I(),
239                                         kDstRect,
240                                         kSrcRect);
241
242         readTex->readPixels(0, 0, 256, 256, kRGBA_8888_GrPixelConfig, firstRead);
243
244         paint2.addColorFragmentProcessor(upmToPM);
245         paint2.setPorterDuffXPFactory(SkXfermode::kSrc_Mode);
246
247         SkAutoTUnref<GrDrawContext> tempDrawContext(
248                                     context->drawContext(tempTex->asRenderTarget()));
249         if (!tempDrawContext) {
250             failed = true;
251             break;
252         }
253         tempDrawContext->fillRectToRect(GrClip::WideOpen(),
254                                         paint2,
255                                         SkMatrix::I(),
256                                         kDstRect,
257                                         kSrcRect);
258
259         paint3.addColorFragmentProcessor(pmToUPM2);
260         paint3.setPorterDuffXPFactory(SkXfermode::kSrc_Mode);
261
262         readDrawContext.reset(context->drawContext(readTex->asRenderTarget()));
263         if (!readDrawContext) {
264             failed = true;
265             break;
266         }
267
268         readDrawContext->fillRectToRect(GrClip::WideOpen(),
269                                         paint3,
270                                         SkMatrix::I(),
271                                         kDstRect,
272                                         kSrcRect);
273
274         readTex->readPixels(0, 0, 256, 256, kRGBA_8888_GrPixelConfig, secondRead);
275
276         failed = false;
277         for (int y = 0; y < 256 && !failed; ++y) {
278             for (int x = 0; x <= y; ++x) {
279                 if (firstRead[256 * y + x] != secondRead[256 * y + x]) {
280                     failed = true;
281                     break;
282                 }
283             }
284         }
285     }
286     if (failed) {
287         *pmToUPMRule = kNone_PMConversion;
288         *upmToPMRule = kNone_PMConversion;
289     }
290 }
291
292 const GrFragmentProcessor* GrConfigConversionEffect::Create(GrTexture* texture,
293                                                             bool swapRedAndBlue,
294                                                             PMConversion pmConversion,
295                                                             const SkMatrix& matrix) {
296     if (!swapRedAndBlue && kNone_PMConversion == pmConversion) {
297         // If we returned a GrConfigConversionEffect that was equivalent to a GrSimpleTextureEffect
298         // then we may pollute our texture cache with redundant shaders. So in the case that no
299         // conversions were requested we instead return a GrSimpleTextureEffect.
300         return GrSimpleTextureEffect::Create(texture, matrix);
301     } else {
302         if (kRGBA_8888_GrPixelConfig != texture->config() &&
303             kBGRA_8888_GrPixelConfig != texture->config() &&
304             kNone_PMConversion != pmConversion) {
305             // The PM conversions assume colors are 0..255
306             return nullptr;
307         }
308         return new GrConfigConversionEffect(texture, swapRedAndBlue, pmConversion, matrix);
309     }
310 }