Added registerChild; transforms, textures, glKey automatically handled.
[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 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 SkNEW_ARGS(GrConfigConversionEffect,
140                                       (d->fProcDataManager,
141                                        d->fTextures[GrProcessorUnitTest::kSkiaPMTextureIdx],
142                                        swapRB,
143                                        pmConv,
144                                        GrTest::TestMatrix(d->fRandom)));
145 }
146
147 ///////////////////////////////////////////////////////////////////////////////
148
149 void GrConfigConversionEffect::onGetGLProcessorKey(const GrGLSLCaps& caps,
150                                                  GrProcessorKeyBuilder* b) const {
151     GrGLConfigConversionEffect::GenKey(*this, caps, b);
152 }
153
154 GrGLFragmentProcessor* GrConfigConversionEffect::createGLInstance() const {
155     return SkNEW_ARGS(GrGLConfigConversionEffect, (*this));
156 }
157
158
159
160 void GrConfigConversionEffect::TestForPreservingPMConversions(GrContext* context,
161                                                               PMConversion* pmToUPMRule,
162                                                               PMConversion* upmToPMRule) {
163     *pmToUPMRule = kNone_PMConversion;
164     *upmToPMRule = kNone_PMConversion;
165     SkAutoTMalloc<uint32_t> data(256 * 256 * 3);
166     uint32_t* srcData = data.get();
167     uint32_t* firstRead = data.get() + 256 * 256;
168     uint32_t* secondRead = data.get() + 2 * 256 * 256;
169
170     // Fill with every possible premultiplied A, color channel value. There will be 256-y duplicate
171     // values in row y. We set r,g, and b to the same value since they are handled identically.
172     for (int y = 0; y < 256; ++y) {
173         for (int x = 0; x < 256; ++x) {
174             uint8_t* color = reinterpret_cast<uint8_t*>(&srcData[256*y + x]);
175             color[3] = y;
176             color[2] = SkTMin(x, y);
177             color[1] = SkTMin(x, y);
178             color[0] = SkTMin(x, y);
179         }
180     }
181
182     GrSurfaceDesc desc;
183     desc.fFlags = kRenderTarget_GrSurfaceFlag;
184     desc.fWidth = 256;
185     desc.fHeight = 256;
186     desc.fConfig = kRGBA_8888_GrPixelConfig;
187
188     SkAutoTUnref<GrTexture> readTex(context->textureProvider()->createTexture(desc, true, NULL, 0));
189     if (!readTex.get()) {
190         return;
191     }
192     SkAutoTUnref<GrTexture> tempTex(context->textureProvider()->createTexture(desc, true, NULL, 0));
193     if (!tempTex.get()) {
194         return;
195     }
196     desc.fFlags = kNone_GrSurfaceFlags;
197     SkAutoTUnref<GrTexture> dataTex(context->textureProvider()->createTexture(desc, true, data, 0));
198     if (!dataTex.get()) {
199         return;
200     }
201
202     static const PMConversion kConversionRules[][2] = {
203         {kDivByAlpha_RoundDown_PMConversion, kMulByAlpha_RoundUp_PMConversion},
204         {kDivByAlpha_RoundUp_PMConversion, kMulByAlpha_RoundDown_PMConversion},
205     };
206
207     bool failed = true;
208
209     for (size_t i = 0; i < SK_ARRAY_COUNT(kConversionRules) && failed; ++i) {
210         *pmToUPMRule = kConversionRules[i][0];
211         *upmToPMRule = kConversionRules[i][1];
212
213         static const SkRect kDstRect = SkRect::MakeWH(SkIntToScalar(256), SkIntToScalar(256));
214         static const SkRect kSrcRect = SkRect::MakeWH(SK_Scalar1, SK_Scalar1);
215         // We do a PM->UPM draw from dataTex to readTex and read the data. Then we do a UPM->PM draw
216         // from readTex to tempTex followed by a PM->UPM draw to readTex and finally read the data.
217         // We then verify that two reads produced the same values.
218
219         GrPaint paint1;
220         GrPaint paint2;
221         GrPaint paint3;
222         SkAutoTUnref<GrFragmentProcessor> pmToUPM1(
223                 SkNEW_ARGS(GrConfigConversionEffect,
224                            (paint1.getProcessorDataManager(), dataTex, false, *pmToUPMRule,
225                             SkMatrix::I())));
226         SkAutoTUnref<GrFragmentProcessor> upmToPM(
227                 SkNEW_ARGS(GrConfigConversionEffect,
228                            (paint2.getProcessorDataManager(), readTex, false, *upmToPMRule,
229                             SkMatrix::I())));
230         SkAutoTUnref<GrFragmentProcessor> pmToUPM2(
231                 SkNEW_ARGS(GrConfigConversionEffect,
232                            (paint3.getProcessorDataManager(), tempTex, false, *pmToUPMRule,
233                             SkMatrix::I())));
234
235         paint1.addColorProcessor(pmToUPM1);
236
237
238         GrDrawContext* readDrawContext = context->drawContext();
239         if (!readDrawContext) {
240             failed = true;
241             break;
242         }
243
244         readDrawContext->drawNonAARectToRect(readTex->asRenderTarget(),
245                                              GrClip::WideOpen(),
246                                              paint1,
247                                              SkMatrix::I(),
248                                              kDstRect,
249                                              kSrcRect);
250
251         readTex->readPixels(0, 0, 256, 256, kRGBA_8888_GrPixelConfig, firstRead);
252
253         paint2.addColorProcessor(upmToPM);
254
255         GrDrawContext* tempDrawContext = context->drawContext();
256         if (!tempDrawContext) {
257             failed = true;
258             break;
259         }
260         tempDrawContext->drawNonAARectToRect(tempTex->asRenderTarget(),
261                                              GrClip::WideOpen(),
262                                              paint2,
263                                              SkMatrix::I(),
264                                              kDstRect,
265                                              kSrcRect);
266
267         paint3.addColorProcessor(pmToUPM2);
268
269         readDrawContext = context->drawContext();
270         if (!readDrawContext) {
271             failed = true;
272             break;
273         }
274
275         readDrawContext->drawNonAARectToRect(readTex->asRenderTarget(),
276                                              GrClip::WideOpen(),
277                                              paint3,
278                                              SkMatrix::I(),
279                                              kDstRect,
280                                              kSrcRect);
281
282         readTex->readPixels(0, 0, 256, 256, kRGBA_8888_GrPixelConfig, secondRead);
283
284         failed = false;
285         for (int y = 0; y < 256 && !failed; ++y) {
286             for (int x = 0; x <= y; ++x) {
287                 if (firstRead[256 * y + x] != secondRead[256 * y + x]) {
288                     failed = true;
289                     break;
290                 }
291             }
292         }
293     }
294     if (failed) {
295         *pmToUPMRule = kNone_PMConversion;
296         *upmToPMRule = kNone_PMConversion;
297     }
298 }
299
300 const GrFragmentProcessor* GrConfigConversionEffect::Create(GrProcessorDataManager* procDataManager,
301                                                             GrTexture* texture,
302                                                             bool swapRedAndBlue,
303                                                             PMConversion pmConversion,
304                                                             const SkMatrix& matrix) {
305     if (!swapRedAndBlue && kNone_PMConversion == pmConversion) {
306         // If we returned a GrConfigConversionEffect that was equivalent to a GrSimpleTextureEffect
307         // then we may pollute our texture cache with redundant shaders. So in the case that no
308         // conversions were requested we instead return a GrSimpleTextureEffect.
309         return GrSimpleTextureEffect::Create(procDataManager, texture, matrix);
310     } else {
311         if (kRGBA_8888_GrPixelConfig != texture->config() &&
312             kBGRA_8888_GrPixelConfig != texture->config() &&
313             kNone_PMConversion != pmConversion) {
314             // The PM conversions assume colors are 0..255
315             return NULL;
316         }
317         return SkNEW_ARGS(GrConfigConversionEffect, (procDataManager,
318                                                      texture,
319                                                      swapRedAndBlue,
320                                                      pmConversion,
321                                                      matrix));
322     }
323 }