Change SkShader;asFragmentProcessor signature to no longer take skpaint\grcolor*
[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 "gl/GrGLFragmentProcessor.h"
15 #include "gl/builders/GrGLProgramBuilder.h"
16
17 class GrGLConfigConversionEffect : public GrGLFragmentProcessor {
18 public:
19     GrGLConfigConversionEffect(const GrProcessor& processor) {
20         const GrConfigConversionEffect& configConversionEffect =
21                 processor.cast<GrConfigConversionEffect>();
22         fSwapRedAndBlue = configConversionEffect.swapsRedAndBlue();
23         fPMConversion = configConversionEffect.pmConversion();
24     }
25
26     virtual void emitCode(EmitArgs& args) override {
27         // Using highp for GLES here in order to avoid some precision issues on specific GPUs.
28         GrGLShaderVar tmpVar("tmpColor", kVec4f_GrSLType, 0, kHigh_GrSLPrecision);
29         SkString tmpDecl;
30         tmpVar.appendDecl(args.fBuilder->ctxInfo(), &tmpDecl);
31
32         GrGLFragmentBuilder* fsBuilder = args.fBuilder->getFragmentShaderBuilder();
33
34         fsBuilder->codeAppendf("%s;", tmpDecl.c_str());
35
36         fsBuilder->codeAppendf("%s = ", tmpVar.c_str());
37         fsBuilder->appendTextureLookup(args.fSamplers[0], args.fCoords[0].c_str(),
38                                        args.fCoords[0].getType());
39         fsBuilder->codeAppend(";");
40
41         if (GrConfigConversionEffect::kNone_PMConversion == fPMConversion) {
42             SkASSERT(fSwapRedAndBlue);
43             fsBuilder->codeAppendf("%s = %s.bgra;", args.fOutputColor, tmpVar.c_str());
44         } else {
45             const char* swiz = fSwapRedAndBlue ? "bgr" : "rgb";
46             switch (fPMConversion) {
47                 case GrConfigConversionEffect::kMulByAlpha_RoundUp_PMConversion:
48                     fsBuilder->codeAppendf(
49                         "%s = vec4(ceil(%s.%s * %s.a * 255.0) / 255.0, %s.a);",
50                         tmpVar.c_str(), tmpVar.c_str(), swiz, tmpVar.c_str(), tmpVar.c_str());
51                     break;
52                 case GrConfigConversionEffect::kMulByAlpha_RoundDown_PMConversion:
53                     // Add a compensation(0.001) here to avoid the side effect of the floor operation.
54                     // In Intel GPUs, the integer value converted from floor(%s.r * 255.0) / 255.0
55                     // is less than the integer value converted from  %s.r by 1 when the %s.r is
56                     // converted from the integer value 2^n, such as 1, 2, 4, 8, etc.
57                     fsBuilder->codeAppendf(
58                         "%s = vec4(floor(%s.%s * %s.a * 255.0 + 0.001) / 255.0, %s.a);",
59                         tmpVar.c_str(), tmpVar.c_str(), swiz, tmpVar.c_str(), tmpVar.c_str());
60                     break;
61                 case GrConfigConversionEffect::kDivByAlpha_RoundUp_PMConversion:
62                     fsBuilder->codeAppendf(
63                         "%s = %s.a <= 0.0 ? vec4(0,0,0,0) : vec4(ceil(%s.%s / %s.a * 255.0) / 255.0, %s.a);",
64                         tmpVar.c_str(), tmpVar.c_str(), tmpVar.c_str(), swiz, tmpVar.c_str(), tmpVar.c_str());
65                     break;
66                 case GrConfigConversionEffect::kDivByAlpha_RoundDown_PMConversion:
67                     fsBuilder->codeAppendf(
68                         "%s = %s.a <= 0.0 ? vec4(0,0,0,0) : vec4(floor(%s.%s / %s.a * 255.0) / 255.0, %s.a);",
69                         tmpVar.c_str(), tmpVar.c_str(), tmpVar.c_str(), swiz, tmpVar.c_str(), tmpVar.c_str());
70                     break;
71                 default:
72                     SkFAIL("Unknown conversion op.");
73                     break;
74             }
75             fsBuilder->codeAppendf("%s = %s;", args.fOutputColor, tmpVar.c_str());
76         }
77         SkString modulate;
78         GrGLSLMulVarBy4f(&modulate, args.fOutputColor, args.fInputColor);
79         fsBuilder->codeAppend(modulate.c_str());
80     }
81
82     static inline void GenKey(const GrProcessor& processor, const GrGLSLCaps&,
83                               GrProcessorKeyBuilder* b) {
84         const GrConfigConversionEffect& conv = processor.cast<GrConfigConversionEffect>();
85         uint32_t key = (conv.swapsRedAndBlue() ? 0 : 1) | (conv.pmConversion() << 1);
86         b->add32(key);
87     }
88
89 private:
90     bool                                    fSwapRedAndBlue;
91     GrConfigConversionEffect::PMConversion  fPMConversion;
92
93     typedef GrGLFragmentProcessor INHERITED;
94
95 };
96
97 ///////////////////////////////////////////////////////////////////////////////
98
99 GrConfigConversionEffect::GrConfigConversionEffect(GrProcessorDataManager* procDataManager,
100                                                    GrTexture* texture,
101                                                    bool swapRedAndBlue,
102                                                    PMConversion pmConversion,
103                                                    const SkMatrix& matrix)
104     : INHERITED(procDataManager, 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->fProcDataManager,
140                                         d->fTextures[GrProcessorUnitTest::kSkiaPMTextureIdx],
141                                         swapRB, pmConv, GrTest::TestMatrix(d->fRandom));
142 }
143
144 ///////////////////////////////////////////////////////////////////////////////
145
146 void GrConfigConversionEffect::onGetGLProcessorKey(const GrGLSLCaps& caps,
147                                                  GrProcessorKeyBuilder* b) const {
148     GrGLConfigConversionEffect::GenKey(*this, caps, b);
149 }
150
151 GrGLFragmentProcessor* GrConfigConversionEffect::onCreateGLInstance() const {
152     return new GrGLConfigConversionEffect(*this);
153 }
154
155
156
157 void GrConfigConversionEffect::TestForPreservingPMConversions(GrContext* context,
158                                                               PMConversion* pmToUPMRule,
159                                                               PMConversion* upmToPMRule) {
160     *pmToUPMRule = kNone_PMConversion;
161     *upmToPMRule = kNone_PMConversion;
162     SkAutoTMalloc<uint32_t> data(256 * 256 * 3);
163     uint32_t* srcData = data.get();
164     uint32_t* firstRead = data.get() + 256 * 256;
165     uint32_t* secondRead = data.get() + 2 * 256 * 256;
166
167     // Fill with every possible premultiplied A, color channel value. There will be 256-y duplicate
168     // values in row y. We set r,g, and b to the same value since they are handled identically.
169     for (int y = 0; y < 256; ++y) {
170         for (int x = 0; x < 256; ++x) {
171             uint8_t* color = reinterpret_cast<uint8_t*>(&srcData[256*y + x]);
172             color[3] = y;
173             color[2] = SkTMin(x, y);
174             color[1] = SkTMin(x, y);
175             color[0] = SkTMin(x, y);
176         }
177     }
178
179     GrSurfaceDesc desc;
180     desc.fFlags = kRenderTarget_GrSurfaceFlag;
181     desc.fWidth = 256;
182     desc.fHeight = 256;
183     desc.fConfig = kRGBA_8888_GrPixelConfig;
184
185     SkAutoTUnref<GrTexture> readTex(context->textureProvider()->createTexture(desc, true, nullptr, 0));
186     if (!readTex.get()) {
187         return;
188     }
189     SkAutoTUnref<GrTexture> tempTex(context->textureProvider()->createTexture(desc, true, nullptr, 0));
190     if (!tempTex.get()) {
191         return;
192     }
193     desc.fFlags = kNone_GrSurfaceFlags;
194     SkAutoTUnref<GrTexture> dataTex(context->textureProvider()->createTexture(desc, true, data, 0));
195     if (!dataTex.get()) {
196         return;
197     }
198
199     static const PMConversion kConversionRules[][2] = {
200         {kDivByAlpha_RoundDown_PMConversion, kMulByAlpha_RoundUp_PMConversion},
201         {kDivByAlpha_RoundUp_PMConversion, kMulByAlpha_RoundDown_PMConversion},
202     };
203
204     bool failed = true;
205
206     for (size_t i = 0; i < SK_ARRAY_COUNT(kConversionRules) && failed; ++i) {
207         *pmToUPMRule = kConversionRules[i][0];
208         *upmToPMRule = kConversionRules[i][1];
209
210         static const SkRect kDstRect = SkRect::MakeWH(SkIntToScalar(256), SkIntToScalar(256));
211         static const SkRect kSrcRect = SkRect::MakeWH(SK_Scalar1, SK_Scalar1);
212         // We do a PM->UPM draw from dataTex to readTex and read the data. Then we do a UPM->PM draw
213         // from readTex to tempTex followed by a PM->UPM draw to readTex and finally read the data.
214         // We then verify that two reads produced the same values.
215
216         GrPaint paint1;
217         GrPaint paint2;
218         GrPaint paint3;
219         SkAutoTUnref<GrFragmentProcessor> pmToUPM1(new GrConfigConversionEffect(
220                 paint1.getProcessorDataManager(), dataTex, false, *pmToUPMRule, SkMatrix::I()));
221         SkAutoTUnref<GrFragmentProcessor> upmToPM(new GrConfigConversionEffect(
222                 paint2.getProcessorDataManager(), readTex, false, *upmToPMRule, SkMatrix::I()));
223         SkAutoTUnref<GrFragmentProcessor> pmToUPM2(new GrConfigConversionEffect(
224                 paint3.getProcessorDataManager(), tempTex, false, *pmToUPMRule, SkMatrix::I()));
225
226         paint1.addColorFragmentProcessor(pmToUPM1);
227
228
229         GrDrawContext* readDrawContext = context->drawContext();
230         if (!readDrawContext) {
231             failed = true;
232             break;
233         }
234
235         readDrawContext->drawNonAARectToRect(readTex->asRenderTarget(),
236                                              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
246         GrDrawContext* tempDrawContext = context->drawContext();
247         if (!tempDrawContext) {
248             failed = true;
249             break;
250         }
251         tempDrawContext->drawNonAARectToRect(tempTex->asRenderTarget(),
252                                              GrClip::WideOpen(),
253                                              paint2,
254                                              SkMatrix::I(),
255                                              kDstRect,
256                                              kSrcRect);
257
258         paint3.addColorFragmentProcessor(pmToUPM2);
259
260         readDrawContext = context->drawContext();
261         if (!readDrawContext) {
262             failed = true;
263             break;
264         }
265
266         readDrawContext->drawNonAARectToRect(readTex->asRenderTarget(),
267                                              GrClip::WideOpen(),
268                                              paint3,
269                                              SkMatrix::I(),
270                                              kDstRect,
271                                              kSrcRect);
272
273         readTex->readPixels(0, 0, 256, 256, kRGBA_8888_GrPixelConfig, secondRead);
274
275         failed = false;
276         for (int y = 0; y < 256 && !failed; ++y) {
277             for (int x = 0; x <= y; ++x) {
278                 if (firstRead[256 * y + x] != secondRead[256 * y + x]) {
279                     failed = true;
280                     break;
281                 }
282             }
283         }
284     }
285     if (failed) {
286         *pmToUPMRule = kNone_PMConversion;
287         *upmToPMRule = kNone_PMConversion;
288     }
289 }
290
291 const GrFragmentProcessor* GrConfigConversionEffect::Create(GrProcessorDataManager* procDataManager,
292                                                             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(procDataManager, 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(procDataManager, texture, swapRedAndBlue, pmConversion,
309                                             matrix);
310     }
311 }