[ANGLE - iOS] fast/canvas/webgl/uninitialized-test.html is still failing
[WebKit-https.git] / Source / ThirdParty / ANGLE / src / libANGLE / renderer / gl / BlitGL.cpp
1 //
2 // Copyright 2015 The ANGLE Project Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style license that can be
4 // found in the LICENSE file.
5 //
6
7 // BlitGL.cpp: Implements the BlitGL class, a helper for blitting textures
8
9 #include "libANGLE/renderer/gl/BlitGL.h"
10
11 #include "common/FixedVector.h"
12 #include "common/utilities.h"
13 #include "common/vector_utils.h"
14 #include "image_util/copyimage.h"
15 #include "libANGLE/Context.h"
16 #include "libANGLE/Framebuffer.h"
17 #include "libANGLE/formatutils.h"
18 #include "libANGLE/renderer/Format.h"
19 #include "libANGLE/renderer/gl/ContextGL.h"
20 #include "libANGLE/renderer/gl/FramebufferGL.h"
21 #include "libANGLE/renderer/gl/FunctionsGL.h"
22 #include "libANGLE/renderer/gl/RenderbufferGL.h"
23 #include "libANGLE/renderer/gl/StateManagerGL.h"
24 #include "libANGLE/renderer/gl/TextureGL.h"
25 #include "libANGLE/renderer/gl/formatutilsgl.h"
26 #include "libANGLE/renderer/gl/renderergl_utils.h"
27 #include "libANGLE/renderer/renderer_utils.h"
28 #include "platform/FeaturesGL.h"
29
30 using angle::Vector2;
31
32 namespace rx
33 {
34
35 namespace
36 {
37
38 angle::Result CheckCompileStatus(const gl::Context *context,
39                                  const rx::FunctionsGL *functions,
40                                  GLuint shader)
41 {
42     GLint compileStatus = GL_FALSE;
43     ANGLE_GL_TRY(context, functions->getShaderiv(shader, GL_COMPILE_STATUS, &compileStatus));
44
45     ASSERT(compileStatus == GL_TRUE);
46     ANGLE_CHECK(GetImplAs<ContextGL>(context), compileStatus == GL_TRUE,
47                 "Failed to compile internal blit shader.", GL_OUT_OF_MEMORY);
48
49     return angle::Result::Continue;
50 }
51
52 angle::Result CheckLinkStatus(const gl::Context *context,
53                               const rx::FunctionsGL *functions,
54                               GLuint program)
55 {
56     GLint linkStatus = GL_FALSE;
57     ANGLE_GL_TRY(context, functions->getProgramiv(program, GL_LINK_STATUS, &linkStatus));
58     ASSERT(linkStatus == GL_TRUE);
59     ANGLE_CHECK(GetImplAs<ContextGL>(context), linkStatus == GL_TRUE,
60                 "Failed to link internal blit program.", GL_OUT_OF_MEMORY);
61
62     return angle::Result::Continue;
63 }
64
65 class ScopedGLState : angle::NonCopyable
66 {
67   public:
68     enum
69     {
70         KEEP_SCISSOR = 1,
71     };
72
73     ScopedGLState() {}
74
75     ~ScopedGLState() { ASSERT(mExited); }
76
77     angle::Result enter(const gl::Context *context, gl::Rectangle viewport, int keepState = 0)
78     {
79         ContextGL *contextGL         = GetImplAs<ContextGL>(context);
80         StateManagerGL *stateManager = contextGL->getStateManager();
81
82         if (!(keepState & KEEP_SCISSOR))
83         {
84             stateManager->setScissorTestEnabled(false);
85         }
86         stateManager->setViewport(viewport);
87         stateManager->setDepthRange(0.0f, 1.0f);
88         stateManager->setBlendEnabled(false);
89         stateManager->setColorMask(true, true, true, true);
90         stateManager->setSampleAlphaToCoverageEnabled(false);
91         stateManager->setSampleCoverageEnabled(false);
92         stateManager->setDepthTestEnabled(false);
93         stateManager->setStencilTestEnabled(false);
94         stateManager->setCullFaceEnabled(false);
95         stateManager->setPolygonOffsetFillEnabled(false);
96         stateManager->setRasterizerDiscardEnabled(false);
97
98         stateManager->pauseTransformFeedback();
99         return stateManager->pauseAllQueries(context);
100     }
101
102     angle::Result exit(const gl::Context *context)
103     {
104         mExited = true;
105
106         ContextGL *contextGL         = GetImplAs<ContextGL>(context);
107         StateManagerGL *stateManager = contextGL->getStateManager();
108
109         // XFB resuming will be done automatically
110         return stateManager->resumeAllQueries(context);
111     }
112
113     void willUseTextureUnit(const gl::Context *context, int unit)
114     {
115         ContextGL *contextGL = GetImplAs<ContextGL>(context);
116
117         if (contextGL->getFunctions()->bindSampler)
118         {
119             contextGL->getStateManager()->bindSampler(unit, 0);
120         }
121     }
122
123   private:
124     bool mExited = false;
125 };
126
127 angle::Result SetClearState(StateManagerGL *stateManager,
128                             bool colorClear,
129                             bool depthClear,
130                             bool stencilClear,
131                             GLbitfield *outClearMask)
132 {
133     *outClearMask = 0;
134     if (colorClear)
135     {
136         stateManager->setClearColor(gl::ColorF(0.0f, 0.0f, 0.0f, 0.0f));
137         stateManager->setColorMask(true, true, true, true);
138         *outClearMask |= GL_COLOR_BUFFER_BIT;
139     }
140     if (depthClear)
141     {
142         stateManager->setDepthMask(true);
143         stateManager->setClearDepth(1.0f);
144         *outClearMask |= GL_DEPTH_BUFFER_BIT;
145     }
146     if (stencilClear)
147     {
148         stateManager->setClearStencil(0);
149         *outClearMask |= GL_STENCIL_BUFFER_BIT;
150     }
151
152     stateManager->setScissorTestEnabled(false);
153
154     return angle::Result::Continue;
155 }
156
157 using ClearBindTargetVector = angle::FixedVector<GLenum, 3>;
158
159 angle::Result PrepareForClear(StateManagerGL *stateManager,
160                               GLenum sizedInternalFormat,
161                               ClearBindTargetVector *outBindtargets,
162                               ClearBindTargetVector *outUnbindTargets,
163                               GLbitfield *outClearMask)
164 {
165     const gl::InternalFormat &internalFormatInfo =
166         gl::GetSizedInternalFormatInfo(sizedInternalFormat);
167     bool bindDepth   = internalFormatInfo.depthBits > 0;
168     bool bindStencil = internalFormatInfo.stencilBits > 0;
169     bool bindColor   = !bindDepth && !bindStencil;
170
171     outBindtargets->clear();
172     if (bindColor)
173     {
174         outBindtargets->push_back(GL_COLOR_ATTACHMENT0);
175     }
176     else
177     {
178         outUnbindTargets->push_back(GL_COLOR_ATTACHMENT0);
179     }
180     if (bindDepth)
181     {
182         outBindtargets->push_back(GL_DEPTH_ATTACHMENT);
183     }
184     else
185     {
186         outUnbindTargets->push_back(GL_DEPTH_ATTACHMENT);
187     }
188     if (bindStencil)
189     {
190         outBindtargets->push_back(GL_STENCIL_ATTACHMENT);
191     }
192     else
193     {
194         outUnbindTargets->push_back(GL_STENCIL_ATTACHMENT);
195     }
196
197     ANGLE_TRY(SetClearState(stateManager, bindColor, bindDepth, bindStencil, outClearMask));
198
199     return angle::Result::Continue;
200 }
201
202 angle::Result UnbindAttachments(const gl::Context *context,
203                                 const FunctionsGL *functions,
204                                 GLenum framebufferTarget,
205                                 const ClearBindTargetVector &bindTargets)
206 {
207     for (GLenum bindTarget : bindTargets)
208     {
209         ANGLE_GL_TRY(context, functions->framebufferRenderbuffer(framebufferTarget, bindTarget,
210                                                                  GL_RENDERBUFFER, 0));
211     }
212     return angle::Result::Continue;
213 }
214
215 }  // anonymous namespace
216
217 BlitGL::BlitGL(const FunctionsGL *functions,
218                const angle::FeaturesGL &features,
219                StateManagerGL *stateManager)
220     : mFunctions(functions),
221       mFeatures(features),
222       mStateManager(stateManager),
223       mScratchFBO(0),
224       mVAO(0),
225       mVertexBuffer(0)
226 {
227     for (size_t i = 0; i < ArraySize(mScratchTextures); i++)
228     {
229         mScratchTextures[i] = 0;
230     }
231
232     ASSERT(mFunctions);
233     ASSERT(mStateManager);
234 }
235
236 BlitGL::~BlitGL()
237 {
238     for (const auto &blitProgram : mBlitPrograms)
239     {
240         mStateManager->deleteProgram(blitProgram.second.program);
241     }
242     mBlitPrograms.clear();
243
244     for (size_t i = 0; i < ArraySize(mScratchTextures); i++)
245     {
246         if (mScratchTextures[i] != 0)
247         {
248             mStateManager->deleteTexture(mScratchTextures[i]);
249             mScratchTextures[i] = 0;
250         }
251     }
252
253     if (mScratchFBO != 0)
254     {
255         mStateManager->deleteFramebuffer(mScratchFBO);
256         mScratchFBO = 0;
257     }
258
259     if (mVAO != 0)
260     {
261         mStateManager->deleteVertexArray(mVAO);
262         mVAO = 0;
263     }
264 }
265
266 angle::Result BlitGL::copyImageToLUMAWorkaroundTexture(const gl::Context *context,
267                                                        GLuint texture,
268                                                        gl::TextureType textureType,
269                                                        gl::TextureTarget target,
270                                                        GLenum lumaFormat,
271                                                        size_t level,
272                                                        const gl::Rectangle &sourceArea,
273                                                        GLenum internalFormat,
274                                                        gl::Framebuffer *source)
275 {
276     mStateManager->bindTexture(textureType, texture);
277
278     // Allocate the texture memory
279     GLenum format   = gl::GetUnsizedFormat(internalFormat);
280     GLenum readType = source->getImplementationColorReadType(context);
281
282     gl::PixelUnpackState unpack;
283     mStateManager->setPixelUnpackState(unpack);
284     mStateManager->setPixelUnpackBuffer(
285         context->getState().getTargetBuffer(gl::BufferBinding::PixelUnpack));
286     ANGLE_GL_TRY_ALWAYS_CHECK(
287         context,
288         mFunctions->texImage2D(ToGLenum(target), static_cast<GLint>(level), internalFormat,
289                                sourceArea.width, sourceArea.height, 0, format, readType, nullptr));
290
291     return copySubImageToLUMAWorkaroundTexture(context, texture, textureType, target, lumaFormat,
292                                                level, gl::Offset(0, 0, 0), sourceArea, source);
293 }
294
295 angle::Result BlitGL::copySubImageToLUMAWorkaroundTexture(const gl::Context *context,
296                                                           GLuint texture,
297                                                           gl::TextureType textureType,
298                                                           gl::TextureTarget target,
299                                                           GLenum lumaFormat,
300                                                           size_t level,
301                                                           const gl::Offset &destOffset,
302                                                           const gl::Rectangle &sourceArea,
303                                                           gl::Framebuffer *source)
304 {
305     ANGLE_TRY(initializeResources(context));
306
307     BlitProgram *blitProgram = nullptr;
308     ANGLE_TRY(getBlitProgram(context, gl::TextureType::_2D, GL_FLOAT, GL_FLOAT, &blitProgram));
309
310     // Blit the framebuffer to the first scratch texture
311     const FramebufferGL *sourceFramebufferGL = GetImplAs<FramebufferGL>(source);
312     mStateManager->bindFramebuffer(GL_FRAMEBUFFER, sourceFramebufferGL->getFramebufferID());
313
314     GLenum readFormat = source->getImplementationColorReadFormat(context);
315     GLenum readType   = source->getImplementationColorReadType(context);
316
317     nativegl::CopyTexImageImageFormat copyTexImageFormat =
318         nativegl::GetCopyTexImageImageFormat(mFunctions, mFeatures, readFormat, readType);
319
320     mStateManager->bindTexture(gl::TextureType::_2D, mScratchTextures[0]);
321     ANGLE_GL_TRY_ALWAYS_CHECK(
322         context, mFunctions->copyTexImage2D(GL_TEXTURE_2D, 0, copyTexImageFormat.internalFormat,
323                                             sourceArea.x, sourceArea.y, sourceArea.width,
324                                             sourceArea.height, 0));
325
326     // Set the swizzle of the scratch texture so that the channels sample into the correct emulated
327     // LUMA channels.
328     GLint swizzle[4] = {
329         (lumaFormat == GL_ALPHA) ? GL_ALPHA : GL_RED,
330         (lumaFormat == GL_LUMINANCE_ALPHA) ? GL_ALPHA : GL_ZERO,
331         GL_ZERO,
332         GL_ZERO,
333     };
334     ANGLE_GL_TRY(context,
335                  mFunctions->texParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzle));
336
337     // Make a temporary framebuffer using the second scratch texture to render the swizzled result
338     // to.
339     mStateManager->bindTexture(gl::TextureType::_2D, mScratchTextures[1]);
340     ANGLE_GL_TRY_ALWAYS_CHECK(
341         context, mFunctions->texImage2D(GL_TEXTURE_2D, 0, copyTexImageFormat.internalFormat,
342                                         sourceArea.width, sourceArea.height, 0,
343                                         gl::GetUnsizedFormat(copyTexImageFormat.internalFormat),
344                                         readType, nullptr));
345
346     mStateManager->bindFramebuffer(GL_FRAMEBUFFER, mScratchFBO);
347     ANGLE_GL_TRY(context, mFunctions->framebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
348                                                            GL_TEXTURE_2D, mScratchTextures[1], 0));
349
350     // Render to the destination texture, sampling from the scratch texture
351     ScopedGLState scopedState;
352     ANGLE_TRY(scopedState.enter(context, gl::Rectangle(0, 0, sourceArea.width, sourceArea.height)));
353     scopedState.willUseTextureUnit(context, 0);
354
355     ANGLE_TRY(setScratchTextureParameter(context, GL_TEXTURE_MIN_FILTER, GL_NEAREST));
356     ANGLE_TRY(setScratchTextureParameter(context, GL_TEXTURE_MAG_FILTER, GL_NEAREST));
357
358     mStateManager->activeTexture(0);
359     mStateManager->bindTexture(gl::TextureType::_2D, mScratchTextures[0]);
360
361     mStateManager->useProgram(blitProgram->program);
362     ANGLE_GL_TRY(context, mFunctions->uniform1i(blitProgram->sourceTextureLocation, 0));
363     ANGLE_GL_TRY(context, mFunctions->uniform2f(blitProgram->scaleLocation, 1.0, 1.0));
364     ANGLE_GL_TRY(context, mFunctions->uniform2f(blitProgram->offsetLocation, 0.0, 0.0));
365     ANGLE_GL_TRY(context, mFunctions->uniform1i(blitProgram->multiplyAlphaLocation, 0));
366     ANGLE_GL_TRY(context, mFunctions->uniform1i(blitProgram->unMultiplyAlphaLocation, 0));
367
368     mStateManager->bindVertexArray(mVAO, 0);
369     ANGLE_GL_TRY(context, mFunctions->drawArrays(GL_TRIANGLES, 0, 3));
370
371     // Copy the swizzled texture to the destination texture
372     mStateManager->bindTexture(textureType, texture);
373
374     if (nativegl::UseTexImage3D(textureType))
375     {
376         ANGLE_GL_TRY(context,
377                      mFunctions->copyTexSubImage3D(ToGLenum(target), static_cast<GLint>(level),
378                                                    destOffset.x, destOffset.y, destOffset.z, 0, 0,
379                                                    sourceArea.width, sourceArea.height));
380     }
381     else
382     {
383         ASSERT(nativegl::UseTexImage2D(textureType));
384         ANGLE_GL_TRY(context, mFunctions->copyTexSubImage2D(
385                                   ToGLenum(target), static_cast<GLint>(level), destOffset.x,
386                                   destOffset.y, 0, 0, sourceArea.width, sourceArea.height));
387     }
388
389     // Finally orphan the scratch textures so they can be GCed by the driver.
390     ANGLE_TRY(orphanScratchTextures(context));
391
392     ANGLE_TRY(scopedState.exit(context));
393     return angle::Result::Continue;
394 }
395
396 angle::Result BlitGL::blitColorBufferWithShader(const gl::Context *context,
397                                                 const gl::Framebuffer *source,
398                                                 const GLuint destTexture,
399                                                 const gl::TextureTarget destTarget,
400                                                 const size_t destLevel,
401                                                 const gl::Rectangle &sourceAreaIn,
402                                                 const gl::Rectangle &destAreaIn,
403                                                 GLenum filter,
404                                                 bool writeAlpha)
405 {
406     ANGLE_TRY(initializeResources(context));
407     mStateManager->bindFramebuffer(GL_FRAMEBUFFER, mScratchFBO);
408     ANGLE_GL_TRY(context, mFunctions->framebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
409                                                            ToGLenum(destTarget), destTexture,
410                                                            static_cast<GLint>(destLevel)));
411     GLenum status = ANGLE_GL_TRY(context, mFunctions->checkFramebufferStatus(GL_FRAMEBUFFER));
412     if (status != GL_FRAMEBUFFER_COMPLETE)
413     {
414         return angle::Result::Stop;
415     }
416     angle::Result result = blitColorBufferWithShader(context, source, mScratchFBO, sourceAreaIn,
417                                                      destAreaIn, filter, writeAlpha);
418     // Unbind the texture from the the scratch framebuffer.
419     ANGLE_GL_TRY(context, mFunctions->framebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
420                                                               GL_RENDERBUFFER, 0));
421     return result;
422 }
423
424 angle::Result BlitGL::blitColorBufferWithShader(const gl::Context *context,
425                                                 const gl::Framebuffer *source,
426                                                 const gl::Framebuffer *dest,
427                                                 const gl::Rectangle &sourceAreaIn,
428                                                 const gl::Rectangle &destAreaIn,
429                                                 GLenum filter,
430                                                 bool writeAlpha)
431 {
432     const FramebufferGL *destGL = GetImplAs<FramebufferGL>(dest);
433     return blitColorBufferWithShader(context, source, destGL->getFramebufferID(), sourceAreaIn,
434                                      destAreaIn, filter, writeAlpha);
435 }
436
437 angle::Result BlitGL::blitColorBufferWithShader(const gl::Context *context,
438                                                 const gl::Framebuffer *source,
439                                                 const GLuint destFramebuffer,
440                                                 const gl::Rectangle &sourceAreaIn,
441                                                 const gl::Rectangle &destAreaIn,
442                                                 GLenum filter,
443                                                 bool writeAlpha)
444 {
445     ANGLE_TRY(initializeResources(context));
446
447     BlitProgram *blitProgram = nullptr;
448     ANGLE_TRY(getBlitProgram(context, gl::TextureType::_2D, GL_FLOAT, GL_FLOAT, &blitProgram));
449
450     // We'll keep things simple by removing reversed coordinates from the rectangles. In the end
451     // we'll apply the reversal to the source texture coordinates if needed. The destination
452     // rectangle will be set to the gl viewport, which can't be reversed.
453     bool reverseX            = sourceAreaIn.isReversedX() != destAreaIn.isReversedX();
454     bool reverseY            = sourceAreaIn.isReversedY() != destAreaIn.isReversedY();
455     gl::Rectangle sourceArea = sourceAreaIn.removeReversal();
456     gl::Rectangle destArea   = destAreaIn.removeReversal();
457
458     const gl::FramebufferAttachment *readAttachment = source->getReadColorAttachment();
459     ASSERT(readAttachment->getSamples() <= 1);
460
461     // Compute the part of the source that will be sampled.
462     gl::Rectangle inBoundsSource;
463     {
464         gl::Extents sourceSize = readAttachment->getSize();
465         gl::Rectangle sourceBounds(0, 0, sourceSize.width, sourceSize.height);
466         if (!gl::ClipRectangle(sourceArea, sourceBounds, &inBoundsSource))
467         {
468             // Early out when the sampled part is empty as the blit will be a noop,
469             // and it prevents a division by zero in later computations.
470             return angle::Result::Continue;
471         }
472     }
473
474     // The blit will be emulated by getting the source of the blit in a texture and sampling it
475     // with CLAMP_TO_EDGE.
476
477     GLuint textureId;
478
479     // TODO(cwallez) once texture dirty bits are landed, reuse attached texture instead of using
480     // CopyTexImage2D
481     {
482         textureId = mScratchTextures[0];
483
484         const gl::InternalFormat &sourceInternalFormat       = *readAttachment->getFormat().info;
485         nativegl::CopyTexImageImageFormat copyTexImageFormat = nativegl::GetCopyTexImageImageFormat(
486             mFunctions, mFeatures, sourceInternalFormat.internalFormat, sourceInternalFormat.type);
487         const FramebufferGL *sourceGL = GetImplAs<FramebufferGL>(source);
488         mStateManager->bindFramebuffer(GL_READ_FRAMEBUFFER, sourceGL->getFramebufferID());
489         mStateManager->bindTexture(gl::TextureType::_2D, textureId);
490
491         ANGLE_GL_TRY_ALWAYS_CHECK(
492             context, mFunctions->copyTexImage2D(GL_TEXTURE_2D, 0, copyTexImageFormat.internalFormat,
493                                                 inBoundsSource.x, inBoundsSource.y,
494                                                 inBoundsSource.width, inBoundsSource.height, 0));
495
496         // Translate sourceArea to be relative to the copied image.
497         sourceArea.x -= inBoundsSource.x;
498         sourceArea.y -= inBoundsSource.y;
499
500         ANGLE_TRY(setScratchTextureParameter(context, GL_TEXTURE_MIN_FILTER, filter));
501         ANGLE_TRY(setScratchTextureParameter(context, GL_TEXTURE_MAG_FILTER, filter));
502         ANGLE_TRY(setScratchTextureParameter(context, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
503         ANGLE_TRY(setScratchTextureParameter(context, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));
504     }
505
506     // Transform the source area to the texture coordinate space (where 0.0 and 1.0 correspond to
507     // the edges of the texture).
508     Vector2 texCoordOffset(
509         static_cast<float>(sourceArea.x) / static_cast<float>(inBoundsSource.width),
510         static_cast<float>(sourceArea.y) / static_cast<float>(inBoundsSource.height));
511     // texCoordScale is equal to the size of the source area in texture coordinates.
512     Vector2 texCoordScale(
513         static_cast<float>(sourceArea.width) / static_cast<float>(inBoundsSource.width),
514         static_cast<float>(sourceArea.height) / static_cast<float>(inBoundsSource.height));
515
516     if (reverseX)
517     {
518         texCoordOffset.x() = texCoordOffset.x() + texCoordScale.x();
519         texCoordScale.x()  = -texCoordScale.x();
520     }
521     if (reverseY)
522     {
523         texCoordOffset.y() = texCoordOffset.y() + texCoordScale.y();
524         texCoordScale.y()  = -texCoordScale.y();
525     }
526
527     // Reset all the state except scissor and use the viewport to draw exactly to the destination
528     // rectangle
529     ScopedGLState scopedState;
530     ANGLE_TRY(scopedState.enter(context, destArea, ScopedGLState::KEEP_SCISSOR));
531     scopedState.willUseTextureUnit(context, 0);
532
533     // Set the write color mask to potentially not write alpha
534     mStateManager->setColorMask(true, true, true, writeAlpha);
535
536     // Set uniforms
537     mStateManager->activeTexture(0);
538     mStateManager->bindTexture(gl::TextureType::_2D, textureId);
539
540     mStateManager->useProgram(blitProgram->program);
541     ANGLE_GL_TRY(context, mFunctions->uniform1i(blitProgram->sourceTextureLocation, 0));
542     ANGLE_GL_TRY(context, mFunctions->uniform2f(blitProgram->scaleLocation, texCoordScale.x(),
543                                                 texCoordScale.y()));
544     ANGLE_GL_TRY(context, mFunctions->uniform2f(blitProgram->offsetLocation, texCoordOffset.x(),
545                                                 texCoordOffset.y()));
546     ANGLE_GL_TRY(context, mFunctions->uniform1i(blitProgram->multiplyAlphaLocation, 0));
547     ANGLE_GL_TRY(context, mFunctions->uniform1i(blitProgram->unMultiplyAlphaLocation, 0));
548
549     mStateManager->bindFramebuffer(GL_DRAW_FRAMEBUFFER, destFramebuffer);
550
551     mStateManager->bindVertexArray(mVAO, 0);
552     ANGLE_GL_TRY(context, mFunctions->drawArrays(GL_TRIANGLES, 0, 3));
553
554     ANGLE_TRY(scopedState.exit(context));
555     return angle::Result::Continue;
556 }
557
558 angle::Result BlitGL::copySubTexture(const gl::Context *context,
559                                      TextureGL *source,
560                                      size_t sourceLevel,
561                                      GLenum sourceComponentType,
562                                      GLuint destID,
563                                      gl::TextureTarget destTarget,
564                                      size_t destLevel,
565                                      GLenum destComponentType,
566                                      const gl::Extents &sourceSize,
567                                      const gl::Rectangle &sourceArea,
568                                      const gl::Offset &destOffset,
569                                      bool needsLumaWorkaround,
570                                      GLenum lumaFormat,
571                                      bool unpackFlipY,
572                                      bool unpackPremultiplyAlpha,
573                                      bool unpackUnmultiplyAlpha,
574                                      bool *copySucceededOut)
575 {
576     ASSERT(source->getType() == gl::TextureType::_2D ||
577            source->getType() == gl::TextureType::External ||
578            source->getType() == gl::TextureType::Rectangle);
579     ANGLE_TRY(initializeResources(context));
580
581     // Make sure the destination texture can be rendered to before setting anything else up.  Some
582     // cube maps may not be renderable until all faces have been filled.
583     mStateManager->bindFramebuffer(GL_FRAMEBUFFER, mScratchFBO);
584     ANGLE_GL_TRY(context, mFunctions->framebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
585                                                            ToGLenum(destTarget), destID,
586                                                            static_cast<GLint>(destLevel)));
587     GLenum status = ANGLE_GL_TRY(context, mFunctions->checkFramebufferStatus(GL_FRAMEBUFFER));
588     if (status != GL_FRAMEBUFFER_COMPLETE)
589     {
590         *copySucceededOut = false;
591         return angle::Result::Continue;
592     }
593
594     BlitProgram *blitProgram = nullptr;
595     ANGLE_TRY(getBlitProgram(context, source->getType(), sourceComponentType, destComponentType,
596                              &blitProgram));
597
598     // Setup the source texture
599     if (needsLumaWorkaround)
600     {
601         GLint luminance = (lumaFormat == GL_ALPHA) ? GL_ZERO : GL_RED;
602
603         GLint alpha = GL_RED;
604         if (lumaFormat == GL_LUMINANCE)
605         {
606             alpha = GL_ONE;
607         }
608         else if (lumaFormat == GL_LUMINANCE_ALPHA)
609         {
610             alpha = GL_GREEN;
611         }
612         else
613         {
614             ASSERT(lumaFormat == GL_ALPHA);
615         }
616
617         GLint swizzle[4] = {luminance, luminance, luminance, alpha};
618         ANGLE_TRY(source->setSwizzle(context, swizzle));
619     }
620     ANGLE_TRY(source->setMinFilter(context, GL_NEAREST));
621     ANGLE_TRY(source->setMagFilter(context, GL_NEAREST));
622     ANGLE_TRY(source->setBaseLevel(context, static_cast<GLuint>(sourceLevel)));
623
624     // Render to the destination texture, sampling from the source texture
625     ScopedGLState scopedState;
626     ANGLE_TRY(scopedState.enter(
627         context, gl::Rectangle(destOffset.x, destOffset.y, sourceArea.width, sourceArea.height)));
628     scopedState.willUseTextureUnit(context, 0);
629
630     mStateManager->activeTexture(0);
631     mStateManager->bindTexture(source->getType(), source->getTextureID());
632
633     Vector2 scale(sourceArea.width, sourceArea.height);
634     Vector2 offset(sourceArea.x, sourceArea.y);
635     if (source->getType() != gl::TextureType::Rectangle)
636     {
637         scale.x() /= static_cast<float>(sourceSize.width);
638         scale.y() /= static_cast<float>(sourceSize.height);
639         offset.x() /= static_cast<float>(sourceSize.width);
640         offset.y() /= static_cast<float>(sourceSize.height);
641     }
642     if (unpackFlipY)
643     {
644         offset.y() += scale.y();
645         scale.y() = -scale.y();
646     }
647
648     mStateManager->useProgram(blitProgram->program);
649     ANGLE_GL_TRY(context, mFunctions->uniform1i(blitProgram->sourceTextureLocation, 0));
650     ANGLE_GL_TRY(context, mFunctions->uniform2f(blitProgram->scaleLocation, scale.x(), scale.y()));
651     ANGLE_GL_TRY(context,
652                  mFunctions->uniform2f(blitProgram->offsetLocation, offset.x(), offset.y()));
653     if (unpackPremultiplyAlpha == unpackUnmultiplyAlpha)
654     {
655         ANGLE_GL_TRY(context, mFunctions->uniform1i(blitProgram->multiplyAlphaLocation, 0));
656         ANGLE_GL_TRY(context, mFunctions->uniform1i(blitProgram->unMultiplyAlphaLocation, 0));
657     }
658     else
659     {
660         ANGLE_GL_TRY(context, mFunctions->uniform1i(blitProgram->multiplyAlphaLocation,
661                                                     unpackPremultiplyAlpha));
662         ANGLE_GL_TRY(context, mFunctions->uniform1i(blitProgram->unMultiplyAlphaLocation,
663                                                     unpackUnmultiplyAlpha));
664     }
665
666     mStateManager->bindVertexArray(mVAO, 0);
667     ANGLE_GL_TRY(context, mFunctions->drawArrays(GL_TRIANGLES, 0, 3));
668
669     *copySucceededOut = true;
670     ANGLE_TRY(scopedState.exit(context));
671     return angle::Result::Continue;
672 }
673
674 angle::Result BlitGL::copySubTextureCPUReadback(const gl::Context *context,
675                                                 TextureGL *source,
676                                                 size_t sourceLevel,
677                                                 GLenum sourceSizedInternalFormat,
678                                                 TextureGL *dest,
679                                                 gl::TextureTarget destTarget,
680                                                 size_t destLevel,
681                                                 GLenum destFormat,
682                                                 GLenum destType,
683                                                 const gl::Extents &sourceSize,
684                                                 const gl::Rectangle &sourceArea,
685                                                 const gl::Offset &destOffset,
686                                                 bool needsLumaWorkaround,
687                                                 GLenum lumaFormat,
688                                                 bool unpackFlipY,
689                                                 bool unpackPremultiplyAlpha,
690                                                 bool unpackUnmultiplyAlpha)
691 {
692     ANGLE_TRY(initializeResources(context));
693
694     ContextGL *contextGL = GetImplAs<ContextGL>(context);
695
696     ASSERT(source->getType() == gl::TextureType::_2D ||
697            source->getType() == gl::TextureType::External ||
698            source->getType() == gl::TextureType::Rectangle);
699     const auto &destInternalFormatInfo = gl::GetInternalFormatInfo(destFormat, destType);
700     const gl::InternalFormat &sourceInternalFormatInfo =
701         gl::GetSizedInternalFormatInfo(sourceSizedInternalFormat);
702
703     gl::Rectangle readPixelsArea = sourceArea;
704
705     mStateManager->bindFramebuffer(GL_FRAMEBUFFER, mScratchFBO);
706     ANGLE_GL_TRY(context, mFunctions->framebufferTexture2D(
707                               GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, ToGLenum(source->getType()),
708                               source->getTextureID(), static_cast<GLint>(sourceLevel)));
709     GLenum status = ANGLE_GL_TRY(context, mFunctions->checkFramebufferStatus(GL_FRAMEBUFFER));
710     if (status != GL_FRAMEBUFFER_COMPLETE)
711     {
712         // The source texture cannot be read with glReadPixels. Copy it into another RGBA texture
713         // and read that back instead.
714         nativegl::TexImageFormat texImageFormat = nativegl::GetTexImageFormat(
715             mFunctions, mFeatures, sourceInternalFormatInfo.internalFormat,
716             sourceInternalFormatInfo.format, sourceInternalFormatInfo.type);
717
718         gl::TextureType scratchTextureType = gl::TextureType::_2D;
719         mStateManager->bindTexture(scratchTextureType, mScratchTextures[0]);
720         ANGLE_GL_TRY_ALWAYS_CHECK(
721             context,
722             mFunctions->texImage2D(ToGLenum(scratchTextureType), 0, texImageFormat.internalFormat,
723                                    sourceArea.width, sourceArea.height, 0, texImageFormat.format,
724                                    texImageFormat.type, nullptr));
725
726         bool copySucceeded = false;
727         ANGLE_TRY(copySubTexture(
728             context, source, sourceLevel, sourceInternalFormatInfo.componentType,
729             mScratchTextures[0], NonCubeTextureTypeToTarget(scratchTextureType), 0,
730             sourceInternalFormatInfo.componentType, sourceSize, sourceArea, gl::Offset(0, 0, 0),
731             needsLumaWorkaround, lumaFormat, false, false, false, &copySucceeded));
732         if (!copySucceeded)
733         {
734             // No fallback options if we can't render to the scratch texture.
735             return angle::Result::Stop;
736         }
737
738         // Bind the scratch texture as the readback texture
739         mStateManager->bindFramebuffer(GL_FRAMEBUFFER, mScratchFBO);
740         ANGLE_GL_TRY(context, mFunctions->framebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
741                                                                ToGLenum(scratchTextureType),
742                                                                mScratchTextures[0], 0));
743
744         // The scratch texture sized to sourceArea so adjust the readpixels area
745         readPixelsArea.x = 0;
746         readPixelsArea.y = 0;
747
748         // Recheck the status
749         status = ANGLE_GL_TRY(context, mFunctions->checkFramebufferStatus(GL_FRAMEBUFFER));
750     }
751
752     ASSERT(status == GL_FRAMEBUFFER_COMPLETE);
753
754     // Create a buffer for holding the source and destination memory
755     const size_t sourcePixelSize = 4;
756     size_t sourceBufferSize      = readPixelsArea.width * readPixelsArea.height * sourcePixelSize;
757     size_t destBufferSize =
758         readPixelsArea.width * readPixelsArea.height * destInternalFormatInfo.pixelBytes;
759     angle::MemoryBuffer *buffer = nullptr;
760     ANGLE_CHECK_GL_ALLOC(contextGL,
761                          context->getScratchBuffer(sourceBufferSize + destBufferSize, &buffer));
762
763     uint8_t *sourceMemory = buffer->data();
764     uint8_t *destMemory   = buffer->data() + sourceBufferSize;
765
766     GLenum readPixelsFormat        = GL_NONE;
767     PixelReadFunction readFunction = nullptr;
768     if (sourceInternalFormatInfo.componentType == GL_UNSIGNED_INT)
769     {
770         readPixelsFormat = GL_RGBA_INTEGER;
771         readFunction     = angle::ReadColor<angle::R8G8B8A8, GLuint>;
772     }
773     else
774     {
775         ASSERT(sourceInternalFormatInfo.componentType != GL_INT);
776         readPixelsFormat = GL_RGBA;
777         readFunction     = angle::ReadColor<angle::R8G8B8A8, GLfloat>;
778     }
779
780     gl::PixelUnpackState unpack;
781     unpack.alignment = 1;
782     mStateManager->setPixelUnpackState(unpack);
783     mStateManager->setPixelUnpackBuffer(nullptr);
784     ANGLE_GL_TRY(context, mFunctions->readPixels(readPixelsArea.x, readPixelsArea.y,
785                                                  readPixelsArea.width, readPixelsArea.height,
786                                                  readPixelsFormat, GL_UNSIGNED_BYTE, sourceMemory));
787
788     angle::FormatID destFormatID =
789         angle::Format::InternalFormatToID(destInternalFormatInfo.sizedInternalFormat);
790     const auto &destFormatInfo = angle::Format::Get(destFormatID);
791     CopyImageCHROMIUM(
792         sourceMemory, readPixelsArea.width * sourcePixelSize, sourcePixelSize, 0, readFunction,
793         destMemory, readPixelsArea.width * destInternalFormatInfo.pixelBytes,
794         destInternalFormatInfo.pixelBytes, 0, destFormatInfo.pixelWriteFunction,
795         destInternalFormatInfo.format, destInternalFormatInfo.componentType, readPixelsArea.width,
796         readPixelsArea.height, 1, unpackFlipY, unpackPremultiplyAlpha, unpackUnmultiplyAlpha);
797
798     gl::PixelPackState pack;
799     pack.alignment = 1;
800     mStateManager->setPixelPackState(pack);
801     mStateManager->setPixelPackBuffer(nullptr);
802
803     nativegl::TexSubImageFormat texSubImageFormat =
804         nativegl::GetTexSubImageFormat(mFunctions, mFeatures, destFormat, destType);
805
806     mStateManager->bindTexture(dest->getType(), dest->getTextureID());
807     ANGLE_GL_TRY(context, mFunctions->texSubImage2D(
808                               ToGLenum(destTarget), static_cast<GLint>(destLevel), destOffset.x,
809                               destOffset.y, readPixelsArea.width, readPixelsArea.height,
810                               texSubImageFormat.format, texSubImageFormat.type, destMemory));
811
812     return angle::Result::Continue;
813 }
814
815 angle::Result BlitGL::copyTexSubImage(const gl::Context *context,
816                                       TextureGL *source,
817                                       size_t sourceLevel,
818                                       TextureGL *dest,
819                                       gl::TextureTarget destTarget,
820                                       size_t destLevel,
821                                       const gl::Rectangle &sourceArea,
822                                       const gl::Offset &destOffset,
823                                       bool *copySucceededOut)
824 {
825     ANGLE_TRY(initializeResources(context));
826
827     // Make sure the source texture can create a complete framebuffer before continuing.
828     mStateManager->bindFramebuffer(GL_FRAMEBUFFER, mScratchFBO);
829     ANGLE_GL_TRY(context, mFunctions->framebufferTexture2D(
830                               GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, ToGLenum(source->getType()),
831                               source->getTextureID(), static_cast<GLint>(sourceLevel)));
832     GLenum status = ANGLE_GL_TRY(context, mFunctions->checkFramebufferStatus(GL_FRAMEBUFFER));
833     if (status != GL_FRAMEBUFFER_COMPLETE)
834     {
835         *copySucceededOut = false;
836         return angle::Result::Continue;
837     }
838
839     mStateManager->bindTexture(dest->getType(), dest->getTextureID());
840
841     ANGLE_GL_TRY(context,
842                  mFunctions->copyTexSubImage2D(ToGLenum(destTarget), static_cast<GLint>(destLevel),
843                                                destOffset.x, destOffset.y, sourceArea.x,
844                                                sourceArea.y, sourceArea.width, sourceArea.height));
845
846     *copySucceededOut = true;
847     return angle::Result::Continue;
848 }
849
850 angle::Result BlitGL::clearRenderableTexture(const gl::Context *context,
851                                              TextureGL *source,
852                                              GLenum sizedInternalFormat,
853                                              int numTextureLayers,
854                                              const gl::ImageIndex &imageIndex,
855                                              bool *clearSucceededOut)
856 {
857     ANGLE_TRY(initializeResources(context));
858
859     ClearBindTargetVector bindTargets;
860     ClearBindTargetVector unbindTargets;
861     GLbitfield clearMask = 0;
862     ANGLE_TRY(PrepareForClear(mStateManager, sizedInternalFormat, &bindTargets, &unbindTargets,
863                               &clearMask));
864
865     mStateManager->bindFramebuffer(GL_FRAMEBUFFER, mScratchFBO);
866     ANGLE_TRY(UnbindAttachments(context, mFunctions, GL_FRAMEBUFFER, unbindTargets));
867
868     if (nativegl::UseTexImage2D(source->getType()))
869     {
870         ASSERT(numTextureLayers == 1);
871         for (GLenum bindTarget : bindTargets)
872         {
873             ANGLE_GL_TRY(context, mFunctions->framebufferTexture2D(
874                                       GL_FRAMEBUFFER, bindTarget, ToGLenum(imageIndex.getTarget()),
875                                       source->getTextureID(), imageIndex.getLevelIndex()));
876         }
877
878         GLenum status = ANGLE_GL_TRY(context, mFunctions->checkFramebufferStatus(GL_FRAMEBUFFER));
879         if (status == GL_FRAMEBUFFER_COMPLETE)
880         {
881             ANGLE_GL_TRY(context, mFunctions->clear(clearMask));
882         }
883         else
884         {
885             ANGLE_TRY(UnbindAttachments(context, mFunctions, GL_FRAMEBUFFER, bindTargets));
886             *clearSucceededOut = false;
887             return angle::Result::Continue;
888         }
889     }
890     else
891     {
892         ASSERT(nativegl::UseTexImage3D(source->getType()));
893
894         // Check if it's possible to bind all layers of the texture at once
895         if (mFunctions->framebufferTexture && !imageIndex.hasLayer())
896         {
897             for (GLenum bindTarget : bindTargets)
898             {
899                 ANGLE_GL_TRY(context, mFunctions->framebufferTexture(GL_FRAMEBUFFER, bindTarget,
900                                                                      source->getTextureID(),
901                                                                      imageIndex.getLevelIndex()));
902             }
903
904             GLenum status =
905                 ANGLE_GL_TRY(context, mFunctions->checkFramebufferStatus(GL_FRAMEBUFFER));
906             if (status == GL_FRAMEBUFFER_COMPLETE)
907             {
908                 ANGLE_GL_TRY(context, mFunctions->clear(clearMask));
909             }
910             else
911             {
912                 ANGLE_TRY(UnbindAttachments(context, mFunctions, GL_FRAMEBUFFER, bindTargets));
913                 *clearSucceededOut = false;
914                 return angle::Result::Continue;
915             }
916         }
917         else
918         {
919             GLint firstLayer = 0;
920             GLint layerCount = numTextureLayers;
921             if (imageIndex.hasLayer())
922             {
923                 firstLayer = imageIndex.getLayerIndex();
924                 layerCount = imageIndex.getLayerCount();
925             }
926
927             for (GLint layer = 0; layer < layerCount; layer++)
928             {
929                 for (GLenum bindTarget : bindTargets)
930                 {
931                     ANGLE_GL_TRY(context, mFunctions->framebufferTextureLayer(
932                                               GL_FRAMEBUFFER, bindTarget, source->getTextureID(),
933                                               imageIndex.getLevelIndex(), layer + firstLayer));
934                 }
935
936                 GLenum status =
937                     ANGLE_GL_TRY(context, mFunctions->checkFramebufferStatus(GL_FRAMEBUFFER));
938                 if (status == GL_FRAMEBUFFER_COMPLETE)
939                 {
940                     ANGLE_GL_TRY(context, mFunctions->clear(clearMask));
941                 }
942                 else
943                 {
944                     ANGLE_TRY(UnbindAttachments(context, mFunctions, GL_FRAMEBUFFER, bindTargets));
945                     *clearSucceededOut = false;
946                     return angle::Result::Continue;
947                 }
948             }
949         }
950     }
951
952     ANGLE_TRY(UnbindAttachments(context, mFunctions, GL_FRAMEBUFFER, bindTargets));
953     *clearSucceededOut = true;
954     return angle::Result::Continue;
955 }
956
957 angle::Result BlitGL::clearRenderbuffer(const gl::Context *context,
958                                         RenderbufferGL *source,
959                                         GLenum sizedInternalFormat)
960 {
961     ANGLE_TRY(initializeResources(context));
962
963     ClearBindTargetVector bindTargets;
964     ClearBindTargetVector unbindTargets;
965     GLbitfield clearMask = 0;
966     ANGLE_TRY(PrepareForClear(mStateManager, sizedInternalFormat, &bindTargets, &unbindTargets,
967                               &clearMask));
968
969     mStateManager->bindFramebuffer(GL_FRAMEBUFFER, mScratchFBO);
970     ANGLE_TRY(UnbindAttachments(context, mFunctions, GL_FRAMEBUFFER, unbindTargets));
971
972     for (GLenum bindTarget : bindTargets)
973     {
974         ANGLE_GL_TRY(context,
975                      mFunctions->framebufferRenderbuffer(
976                          GL_FRAMEBUFFER, bindTarget, GL_RENDERBUFFER, source->getRenderbufferID()));
977     }
978     ANGLE_GL_TRY(context, mFunctions->clear(clearMask));
979
980     // Unbind
981     for (GLenum bindTarget : bindTargets)
982     {
983         ANGLE_GL_TRY(context, mFunctions->framebufferRenderbuffer(GL_FRAMEBUFFER, bindTarget,
984                                                                   GL_RENDERBUFFER, 0));
985     }
986
987     return angle::Result::Continue;
988 }
989
990 angle::Result BlitGL::clearFramebuffer(const gl::Context *context, FramebufferGL *source)
991 {
992     // initializeResources skipped because no local state is used
993
994     // Clear all attachments
995     GLbitfield clearMask = 0;
996     ANGLE_TRY(SetClearState(mStateManager, true, true, true, &clearMask));
997
998     mStateManager->bindFramebuffer(GL_FRAMEBUFFER, source->getFramebufferID());
999     ANGLE_GL_TRY(context, mFunctions->clear(clearMask));
1000
1001     return angle::Result::Continue;
1002 }
1003
1004 angle::Result BlitGL::clearRenderableTextureAlphaToOne(const gl::Context *context,
1005                                                        GLuint texture,
1006                                                        gl::TextureTarget target,
1007                                                        size_t level)
1008 {
1009     // Clearing the alpha of 3D textures is not supported/needed yet.
1010     ASSERT(nativegl::UseTexImage2D(TextureTargetToType(target)));
1011
1012     ANGLE_TRY(initializeResources(context));
1013
1014     mStateManager->setClearColor(gl::ColorF(0.0f, 0.0f, 0.0f, 1.0f));
1015     mStateManager->setColorMask(false, false, false, true);
1016     mStateManager->setScissorTestEnabled(false);
1017
1018     mStateManager->bindFramebuffer(GL_FRAMEBUFFER, mScratchFBO);
1019     ANGLE_GL_TRY(context, mFunctions->framebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
1020                                                            ToGLenum(target), texture,
1021                                                            static_cast<GLint>(level)));
1022     ANGLE_GL_TRY(context, mFunctions->clear(GL_COLOR_BUFFER_BIT));
1023
1024     // Unbind the texture from the the scratch framebuffer
1025     ANGLE_GL_TRY(context, mFunctions->framebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
1026                                                               GL_RENDERBUFFER, 0));
1027
1028     return angle::Result::Continue;
1029 }
1030
1031 angle::Result BlitGL::initializeResources(const gl::Context *context)
1032 {
1033     for (size_t i = 0; i < ArraySize(mScratchTextures); i++)
1034     {
1035         if (mScratchTextures[i] == 0)
1036         {
1037             ANGLE_GL_TRY(context, mFunctions->genTextures(1, &mScratchTextures[i]));
1038         }
1039     }
1040
1041     if (mScratchFBO == 0)
1042     {
1043         ANGLE_GL_TRY(context, mFunctions->genFramebuffers(1, &mScratchFBO));
1044     }
1045
1046     if (mVertexBuffer == 0)
1047     {
1048         ANGLE_GL_TRY(context, mFunctions->genBuffers(1, &mVertexBuffer));
1049         mStateManager->bindBuffer(gl::BufferBinding::Array, mVertexBuffer);
1050
1051         // Use a single, large triangle, to avoid arithmetic precision issues where fragments
1052         // with the same Y coordinate don't get exactly the same interpolated texcoord Y.
1053         float vertexData[] = {
1054             -0.5f, 0.0f, 1.5f, 0.0f, 0.5f, 2.0f,
1055         };
1056
1057         ANGLE_GL_TRY(context, mFunctions->bufferData(GL_ARRAY_BUFFER, sizeof(float) * 6, vertexData,
1058                                                      GL_STATIC_DRAW));
1059     }
1060
1061     if (mVAO == 0)
1062     {
1063         ANGLE_GL_TRY(context, mFunctions->genVertexArrays(1, &mVAO));
1064
1065         mStateManager->bindVertexArray(mVAO, 0);
1066         mStateManager->bindBuffer(gl::BufferBinding::Array, mVertexBuffer);
1067
1068         // Enable all attributes with the same buffer so that it doesn't matter what location the
1069         // texcoord attribute is assigned
1070         GLint maxAttributes = 0;
1071         ANGLE_GL_TRY(context, mFunctions->getIntegerv(GL_MAX_VERTEX_ATTRIBS, &maxAttributes));
1072
1073         for (GLint i = 0; i < maxAttributes; i++)
1074         {
1075             ANGLE_GL_TRY(context, mFunctions->enableVertexAttribArray(i));
1076             ANGLE_GL_TRY(context,
1077                          mFunctions->vertexAttribPointer(i, 2, GL_FLOAT, GL_FALSE, 0, nullptr));
1078         }
1079     }
1080
1081     return angle::Result::Continue;
1082 }
1083
1084 angle::Result BlitGL::orphanScratchTextures(const gl::Context *context)
1085 {
1086     for (auto texture : mScratchTextures)
1087     {
1088         mStateManager->bindTexture(gl::TextureType::_2D, texture);
1089         gl::PixelUnpackState unpack;
1090         mStateManager->setPixelUnpackState(unpack);
1091         mStateManager->setPixelUnpackBuffer(nullptr);
1092         GLint swizzle[4] = {GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA};
1093         ANGLE_GL_TRY(context,
1094                      mFunctions->texParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzle));
1095         ANGLE_GL_TRY(context, mFunctions->texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 0, 0, 0, GL_RGBA,
1096                                                      GL_UNSIGNED_BYTE, nullptr));
1097     }
1098     return angle::Result::Continue;
1099 }
1100
1101 angle::Result BlitGL::setScratchTextureParameter(const gl::Context *context,
1102                                                  GLenum param,
1103                                                  GLenum value)
1104 {
1105     for (auto texture : mScratchTextures)
1106     {
1107         mStateManager->bindTexture(gl::TextureType::_2D, texture);
1108         ANGLE_GL_TRY(context, mFunctions->texParameteri(GL_TEXTURE_2D, param, value));
1109         ANGLE_GL_TRY(context, mFunctions->texParameteri(GL_TEXTURE_2D, param, value));
1110     }
1111     return angle::Result::Continue;
1112 }
1113
1114 angle::Result BlitGL::getBlitProgram(const gl::Context *context,
1115                                      gl::TextureType sourceTextureType,
1116                                      GLenum sourceComponentType,
1117                                      GLenum destComponentType,
1118                                      BlitProgram **program)
1119 {
1120
1121     BlitProgramType programType(sourceTextureType, sourceComponentType, destComponentType);
1122     BlitProgram &result = mBlitPrograms[programType];
1123     if (result.program == 0)
1124     {
1125         result.program = ANGLE_GL_TRY(context, mFunctions->createProgram());
1126
1127         // Depending on what types need to be output by the shaders, different versions need to be
1128         // used.
1129         std::string version;
1130         std::string vsInputVariableQualifier;
1131         std::string vsOutputVariableQualifier;
1132         std::string fsInputVariableQualifier;
1133         std::string fsOutputVariableQualifier;
1134         std::string sampleFunction;
1135         if (sourceComponentType != GL_UNSIGNED_INT && destComponentType != GL_UNSIGNED_INT &&
1136             sourceTextureType != gl::TextureType::Rectangle)
1137         {
1138             // Simple case, float-to-float with 2D or external textures.  Only needs ESSL/GLSL 100
1139             version                   = "100";
1140             vsInputVariableQualifier  = "attribute";
1141             vsOutputVariableQualifier = "varying";
1142             fsInputVariableQualifier  = "varying";
1143             fsOutputVariableQualifier = "";
1144             sampleFunction            = "texture2D";
1145         }
1146         else
1147         {
1148             // Need to use a higher version to support non-float output types
1149             if (mFunctions->standard == STANDARD_GL_DESKTOP)
1150             {
1151                 version = "330";
1152             }
1153             else
1154             {
1155                 ASSERT(mFunctions->standard == STANDARD_GL_ES);
1156                 version = "300 es";
1157             }
1158             vsInputVariableQualifier  = "in";
1159             vsOutputVariableQualifier = "out";
1160             fsInputVariableQualifier  = "in";
1161             fsOutputVariableQualifier = "out";
1162             sampleFunction            = "texture";
1163         }
1164
1165         {
1166             // Compile the vertex shader
1167             std::ostringstream vsSourceStream;
1168             vsSourceStream << "#version " << version << "\n";
1169             vsSourceStream << vsInputVariableQualifier << " vec2 a_texcoord;\n";
1170             vsSourceStream << "uniform vec2 u_scale;\n";
1171             vsSourceStream << "uniform vec2 u_offset;\n";
1172             vsSourceStream << vsOutputVariableQualifier << " vec2 v_texcoord;\n";
1173             vsSourceStream << "\n";
1174             vsSourceStream << "void main()\n";
1175             vsSourceStream << "{\n";
1176             vsSourceStream << "    gl_Position = vec4((a_texcoord * 2.0) - 1.0, 0.0, 1.0);\n";
1177             vsSourceStream << "    v_texcoord = a_texcoord * u_scale + u_offset;\n";
1178             vsSourceStream << "}\n";
1179
1180             std::string vsSourceStr  = vsSourceStream.str();
1181             const char *vsSourceCStr = vsSourceStr.c_str();
1182
1183             GLuint vs = ANGLE_GL_TRY(context, mFunctions->createShader(GL_VERTEX_SHADER));
1184             ANGLE_GL_TRY(context, mFunctions->shaderSource(vs, 1, &vsSourceCStr, nullptr));
1185             ANGLE_GL_TRY(context, mFunctions->compileShader(vs));
1186             ANGLE_TRY(CheckCompileStatus(context, mFunctions, vs));
1187
1188             ANGLE_GL_TRY(context, mFunctions->attachShader(result.program, vs));
1189             ANGLE_GL_TRY(context, mFunctions->deleteShader(vs));
1190         }
1191
1192         {
1193             // Sampling texture uniform changes depending on source texture type.
1194             std::string samplerType;
1195             switch (sourceTextureType)
1196             {
1197                 case gl::TextureType::_2D:
1198                     switch (sourceComponentType)
1199                     {
1200                         case GL_UNSIGNED_INT:
1201                             samplerType = "usampler2D";
1202                             break;
1203
1204                         default:  // Float type
1205                             samplerType = "sampler2D";
1206                             break;
1207                     }
1208                     break;
1209
1210                 case gl::TextureType::External:
1211                     ASSERT(sourceComponentType != GL_UNSIGNED_INT);
1212                     samplerType = "samplerExternalOES";
1213                     break;
1214
1215                 case gl::TextureType::Rectangle:
1216                     ASSERT(sourceComponentType != GL_UNSIGNED_INT);
1217                     samplerType = "sampler2DRect";
1218                     break;
1219
1220                 default:
1221                     UNREACHABLE();
1222                     break;
1223             }
1224
1225             std::string samplerResultType;
1226             switch (sourceComponentType)
1227             {
1228                 case GL_UNSIGNED_INT:
1229                     samplerResultType = "uvec4";
1230                     break;
1231
1232                 default:  // Float type
1233                     samplerResultType = "vec4";
1234                     break;
1235             }
1236
1237             std::string extensionRequirements;
1238             switch (sourceTextureType)
1239             {
1240                 case gl::TextureType::External:
1241                     extensionRequirements = "#extension GL_OES_EGL_image_external : require";
1242                     break;
1243
1244                 case gl::TextureType::Rectangle:
1245                     if (mFunctions->hasGLExtension("GL_ARB_texture_rectangle"))
1246                     {
1247                         extensionRequirements = "#extension GL_ARB_texture_rectangle : require";
1248                     }
1249                     else
1250                     {
1251                         ASSERT(mFunctions->isAtLeastGL(gl::Version(3, 1)));
1252                     }
1253                     break;
1254
1255                 default:
1256                     break;
1257             }
1258
1259             // Output variables depend on the output type
1260             std::string outputType;
1261             std::string outputVariableName;
1262             std::string outputMultiplier;
1263             switch (destComponentType)
1264             {
1265                 case GL_UNSIGNED_INT:
1266                     outputType         = "uvec4";
1267                     outputVariableName = "outputUint";
1268                     outputMultiplier   = "255.0";
1269                     break;
1270
1271                 default:  //  float type
1272                     if (version == "100")
1273                     {
1274                         outputType         = "";
1275                         outputVariableName = "gl_FragColor";
1276                         outputMultiplier   = "1.0";
1277                     }
1278                     else
1279                     {
1280                         outputType         = "vec4";
1281                         outputVariableName = "outputFloat";
1282                         outputMultiplier   = "1.0";
1283                     }
1284                     break;
1285             }
1286
1287             // Compile the fragment shader
1288             std::ostringstream fsSourceStream;
1289             fsSourceStream << "#version " << version << "\n";
1290             fsSourceStream << extensionRequirements << "\n";
1291             fsSourceStream << "precision highp float;\n";
1292             fsSourceStream << "uniform " << samplerType << " u_source_texture;\n";
1293
1294             // Write the rest of the uniforms and varyings
1295             fsSourceStream << "uniform bool u_multiply_alpha;\n";
1296             fsSourceStream << "uniform bool u_unmultiply_alpha;\n";
1297             fsSourceStream << fsInputVariableQualifier << " vec2 v_texcoord;\n";
1298             if (!outputType.empty())
1299             {
1300                 fsSourceStream << fsOutputVariableQualifier << " " << outputType << " "
1301                                << outputVariableName << ";\n";
1302             }
1303
1304             // Write the main body
1305             fsSourceStream << "\n";
1306             fsSourceStream << "void main()\n";
1307             fsSourceStream << "{\n";
1308
1309             std::string maxTexcoord;
1310             switch (sourceTextureType)
1311             {
1312                 case gl::TextureType::Rectangle:
1313                     // Valid texcoords are within source texture size
1314                     maxTexcoord = "vec2(textureSize(u_source_texture))";
1315                     break;
1316
1317                 default:
1318                     // Valid texcoords are in [0, 1]
1319                     maxTexcoord = "vec2(1.0)";
1320                     break;
1321             }
1322
1323             // discard if the texcoord is invalid so the blitframebuffer workaround doesn't
1324             // write when the point sampled is outside of the source framebuffer.
1325             fsSourceStream << "    if (clamp(v_texcoord, vec2(0.0), " << maxTexcoord
1326                            << ") != v_texcoord)\n";
1327             fsSourceStream << "    {\n";
1328             fsSourceStream << "        discard;\n";
1329             fsSourceStream << "    }\n";
1330
1331             // Sampling code depends on the input data type
1332             fsSourceStream << "    " << samplerResultType << " color = " << sampleFunction
1333                            << "(u_source_texture, v_texcoord);\n";
1334
1335             // Perform the premultiply or unmultiply alpha logic
1336             fsSourceStream << "    if (u_multiply_alpha)\n";
1337             fsSourceStream << "    {\n";
1338             fsSourceStream << "        color.xyz = color.xyz * color.a;\n";
1339             fsSourceStream << "    }\n";
1340             fsSourceStream << "    if (u_unmultiply_alpha && color.a != 0.0)\n";
1341             fsSourceStream << "    {\n";
1342             fsSourceStream << "         color.xyz = color.xyz / color.a;\n";
1343             fsSourceStream << "    }\n";
1344
1345             // Write the conversion to the destionation type
1346             fsSourceStream << "    color = color * " << outputMultiplier << ";\n";
1347
1348             // Write the output assignment code
1349             fsSourceStream << "    " << outputVariableName << " = " << outputType << "(color);\n";
1350             fsSourceStream << "}\n";
1351
1352             std::string fsSourceStr  = fsSourceStream.str();
1353             const char *fsSourceCStr = fsSourceStr.c_str();
1354
1355             GLuint fs = ANGLE_GL_TRY(context, mFunctions->createShader(GL_FRAGMENT_SHADER));
1356             ANGLE_GL_TRY(context, mFunctions->shaderSource(fs, 1, &fsSourceCStr, nullptr));
1357             ANGLE_GL_TRY(context, mFunctions->compileShader(fs));
1358             ANGLE_TRY(CheckCompileStatus(context, mFunctions, fs));
1359
1360             ANGLE_GL_TRY(context, mFunctions->attachShader(result.program, fs));
1361             ANGLE_GL_TRY(context, mFunctions->deleteShader(fs));
1362         }
1363
1364         ANGLE_GL_TRY(context, mFunctions->linkProgram(result.program));
1365         ANGLE_TRY(CheckLinkStatus(context, mFunctions, result.program));
1366
1367         result.sourceTextureLocation = ANGLE_GL_TRY(
1368             context, mFunctions->getUniformLocation(result.program, "u_source_texture"));
1369         result.scaleLocation =
1370             ANGLE_GL_TRY(context, mFunctions->getUniformLocation(result.program, "u_scale"));
1371         result.offsetLocation =
1372             ANGLE_GL_TRY(context, mFunctions->getUniformLocation(result.program, "u_offset"));
1373         result.multiplyAlphaLocation = ANGLE_GL_TRY(
1374             context, mFunctions->getUniformLocation(result.program, "u_multiply_alpha"));
1375         result.unMultiplyAlphaLocation = ANGLE_GL_TRY(
1376             context, mFunctions->getUniformLocation(result.program, "u_unmultiply_alpha"));
1377     }
1378
1379     *program = &result;
1380     return angle::Result::Continue;
1381 }
1382
1383 }  // namespace rx