Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / third_party / skia / src / gpu / gl / GrGpuGL.cpp
1 /*
2  * Copyright 2011 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
9 #include "GrGpuGL.h"
10 #include "GrGLStencilBuffer.h"
11 #include "GrGLPath.h"
12 #include "GrGLPathRange.h"
13 #include "GrGLPathRendering.h"
14 #include "GrGLShaderBuilder.h"
15 #include "GrTemplates.h"
16 #include "GrTypes.h"
17 #include "SkStrokeRec.h"
18 #include "SkTemplates.h"
19
20 #define GL_CALL(X) GR_GL_CALL(this->glInterface(), X)
21 #define GL_CALL_RET(RET, X) GR_GL_CALL_RET(this->glInterface(), RET, X)
22
23 #define SKIP_CACHE_CHECK    true
24
25 #if GR_GL_CHECK_ALLOC_WITH_GET_ERROR
26     #define CLEAR_ERROR_BEFORE_ALLOC(iface)   GrGLClearErr(iface)
27     #define GL_ALLOC_CALL(iface, call)        GR_GL_CALL_NOERRCHECK(iface, call)
28     #define CHECK_ALLOC_ERROR(iface)          GR_GL_GET_ERROR(iface)
29 #else
30     #define CLEAR_ERROR_BEFORE_ALLOC(iface)
31     #define GL_ALLOC_CALL(iface, call)        GR_GL_CALL(iface, call)
32     #define CHECK_ALLOC_ERROR(iface)          GR_GL_NO_ERROR
33 #endif
34
35
36 ///////////////////////////////////////////////////////////////////////////////
37
38 static const GrGLenum gXformType2GLType[] = {
39     GR_GL_NONE,
40     GR_GL_TRANSLATE_X,
41     GR_GL_TRANSLATE_Y,
42     GR_GL_TRANSLATE_2D,
43     GR_GL_TRANSPOSE_AFFINE_2D
44 };
45
46 GR_STATIC_ASSERT(0 == GrDrawTarget::kNone_PathTransformType);
47 GR_STATIC_ASSERT(1 == GrDrawTarget::kTranslateX_PathTransformType);
48 GR_STATIC_ASSERT(2 == GrDrawTarget::kTranslateY_PathTransformType);
49 GR_STATIC_ASSERT(3 == GrDrawTarget::kTranslate_PathTransformType);
50 GR_STATIC_ASSERT(4 == GrDrawTarget::kAffine_PathTransformType);
51 GR_STATIC_ASSERT(GrDrawTarget::kAffine_PathTransformType == GrDrawTarget::kLast_PathTransformType);
52
53 static const GrGLenum gXfermodeCoeff2Blend[] = {
54     GR_GL_ZERO,
55     GR_GL_ONE,
56     GR_GL_SRC_COLOR,
57     GR_GL_ONE_MINUS_SRC_COLOR,
58     GR_GL_DST_COLOR,
59     GR_GL_ONE_MINUS_DST_COLOR,
60     GR_GL_SRC_ALPHA,
61     GR_GL_ONE_MINUS_SRC_ALPHA,
62     GR_GL_DST_ALPHA,
63     GR_GL_ONE_MINUS_DST_ALPHA,
64     GR_GL_CONSTANT_COLOR,
65     GR_GL_ONE_MINUS_CONSTANT_COLOR,
66     GR_GL_CONSTANT_ALPHA,
67     GR_GL_ONE_MINUS_CONSTANT_ALPHA,
68
69     // extended blend coeffs
70     GR_GL_SRC1_COLOR,
71     GR_GL_ONE_MINUS_SRC1_COLOR,
72     GR_GL_SRC1_ALPHA,
73     GR_GL_ONE_MINUS_SRC1_ALPHA,
74 };
75
76 bool GrGpuGL::BlendCoeffReferencesConstant(GrBlendCoeff coeff) {
77     static const bool gCoeffReferencesBlendConst[] = {
78         false,
79         false,
80         false,
81         false,
82         false,
83         false,
84         false,
85         false,
86         false,
87         false,
88         true,
89         true,
90         true,
91         true,
92
93         // extended blend coeffs
94         false,
95         false,
96         false,
97         false,
98     };
99     return gCoeffReferencesBlendConst[coeff];
100     GR_STATIC_ASSERT(kTotalGrBlendCoeffCount ==
101                      SK_ARRAY_COUNT(gCoeffReferencesBlendConst));
102
103     GR_STATIC_ASSERT(0 == kZero_GrBlendCoeff);
104     GR_STATIC_ASSERT(1 == kOne_GrBlendCoeff);
105     GR_STATIC_ASSERT(2 == kSC_GrBlendCoeff);
106     GR_STATIC_ASSERT(3 == kISC_GrBlendCoeff);
107     GR_STATIC_ASSERT(4 == kDC_GrBlendCoeff);
108     GR_STATIC_ASSERT(5 == kIDC_GrBlendCoeff);
109     GR_STATIC_ASSERT(6 == kSA_GrBlendCoeff);
110     GR_STATIC_ASSERT(7 == kISA_GrBlendCoeff);
111     GR_STATIC_ASSERT(8 == kDA_GrBlendCoeff);
112     GR_STATIC_ASSERT(9 == kIDA_GrBlendCoeff);
113     GR_STATIC_ASSERT(10 == kConstC_GrBlendCoeff);
114     GR_STATIC_ASSERT(11 == kIConstC_GrBlendCoeff);
115     GR_STATIC_ASSERT(12 == kConstA_GrBlendCoeff);
116     GR_STATIC_ASSERT(13 == kIConstA_GrBlendCoeff);
117
118     GR_STATIC_ASSERT(14 == kS2C_GrBlendCoeff);
119     GR_STATIC_ASSERT(15 == kIS2C_GrBlendCoeff);
120     GR_STATIC_ASSERT(16 == kS2A_GrBlendCoeff);
121     GR_STATIC_ASSERT(17 == kIS2A_GrBlendCoeff);
122
123     // assertion for gXfermodeCoeff2Blend have to be in GrGpu scope
124     GR_STATIC_ASSERT(kTotalGrBlendCoeffCount ==
125                      SK_ARRAY_COUNT(gXfermodeCoeff2Blend));
126 }
127
128 ///////////////////////////////////////////////////////////////////////////////
129
130 static bool gPrintStartupSpew;
131
132 GrGpuGL::GrGpuGL(const GrGLContext& ctx, GrContext* context)
133     : GrGpu(context)
134     , fGLContext(ctx) {
135
136     SkASSERT(ctx.isInitialized());
137     fCaps.reset(SkRef(ctx.caps()));
138
139     fHWBoundTextureUniqueIDs.reset(this->glCaps().maxFragmentTextureUnits());
140     fHWPathTexGenSettings.reset(this->glCaps().maxFixedFunctionTextureCoords());
141
142     GrGLClearErr(fGLContext.interface());
143     if (gPrintStartupSpew) {
144         const GrGLubyte* vendor;
145         const GrGLubyte* renderer;
146         const GrGLubyte* version;
147         GL_CALL_RET(vendor, GetString(GR_GL_VENDOR));
148         GL_CALL_RET(renderer, GetString(GR_GL_RENDERER));
149         GL_CALL_RET(version, GetString(GR_GL_VERSION));
150         GrPrintf("------------------------- create GrGpuGL %p --------------\n",
151                  this);
152         GrPrintf("------ VENDOR %s\n", vendor);
153         GrPrintf("------ RENDERER %s\n", renderer);
154         GrPrintf("------ VERSION %s\n",  version);
155         GrPrintf("------ EXTENSIONS\n");
156         ctx.extensions().print();
157         GrPrintf("\n");
158         GrPrintf(this->glCaps().dump().c_str());
159     }
160
161     fProgramCache = SkNEW_ARGS(ProgramCache, (this));
162
163     SkASSERT(this->glCaps().maxVertexAttributes() >= GrDrawState::kMaxVertexAttribCnt);
164
165     fLastSuccessfulStencilFmtIdx = 0;
166     fHWProgramID = 0;
167
168     if (this->glCaps().pathRenderingSupport()) {
169         fPathRendering.reset(GrGLPathRendering::Create(glInterface()));
170     }
171 }
172
173 GrGpuGL::~GrGpuGL() {
174     if (0 != fHWProgramID) {
175         // detach the current program so there is no confusion on OpenGL's part
176         // that we want it to be deleted
177         SkASSERT(fHWProgramID == fCurrentProgram->programID());
178         GL_CALL(UseProgram(0));
179     }
180
181     delete fProgramCache;
182
183     // This must be called by before the GrDrawTarget destructor
184     this->releaseGeometry();
185     // This subclass must do this before the base class destructor runs
186     // since we will unref the GrGLInterface.
187     this->releaseResources();
188 }
189
190 ///////////////////////////////////////////////////////////////////////////////
191
192
193 GrPixelConfig GrGpuGL::preferredReadPixelsConfig(GrPixelConfig readConfig,
194                                                  GrPixelConfig surfaceConfig) const {
195     if (GR_GL_RGBA_8888_PIXEL_OPS_SLOW && kRGBA_8888_GrPixelConfig == readConfig) {
196         return kBGRA_8888_GrPixelConfig;
197     } else if (this->glContext().isMesa() &&
198                GrBytesPerPixel(readConfig) == 4 &&
199                GrPixelConfigSwapRAndB(readConfig) == surfaceConfig) {
200         // Mesa 3D takes a slow path on when reading back  BGRA from an RGBA surface and vice-versa.
201         // Perhaps this should be guarded by some compiletime or runtime check.
202         return surfaceConfig;
203     } else if (readConfig == kBGRA_8888_GrPixelConfig &&
204                !this->glCaps().readPixelsSupported(this->glInterface(),
205                                                    GR_GL_BGRA, GR_GL_UNSIGNED_BYTE)) {
206         return kRGBA_8888_GrPixelConfig;
207     } else {
208         return readConfig;
209     }
210 }
211
212 GrPixelConfig GrGpuGL::preferredWritePixelsConfig(GrPixelConfig writeConfig,
213                                                   GrPixelConfig surfaceConfig) const {
214     if (GR_GL_RGBA_8888_PIXEL_OPS_SLOW && kRGBA_8888_GrPixelConfig == writeConfig) {
215         return kBGRA_8888_GrPixelConfig;
216     } else {
217         return writeConfig;
218     }
219 }
220
221 bool GrGpuGL::canWriteTexturePixels(const GrTexture* texture, GrPixelConfig srcConfig) const {
222     if (kIndex_8_GrPixelConfig == srcConfig || kIndex_8_GrPixelConfig == texture->config()) {
223         return false;
224     }
225     if (srcConfig != texture->config() && kGLES_GrGLStandard == this->glStandard()) {
226         // In general ES2 requires the internal format of the texture and the format of the src
227         // pixels to match. However, It may or may not be possible to upload BGRA data to a RGBA
228         // texture. It depends upon which extension added BGRA. The Apple extension allows it
229         // (BGRA's internal format is RGBA) while the EXT extension does not (BGRA is its own
230         // internal format).
231         if (this->glCaps().isConfigTexturable(kBGRA_8888_GrPixelConfig) &&
232             !this->glCaps().bgraIsInternalFormat() &&
233             kBGRA_8888_GrPixelConfig == srcConfig &&
234             kRGBA_8888_GrPixelConfig == texture->config()) {
235             return true;
236         } else {
237             return false;
238         }
239     } else {
240         return true;
241     }
242 }
243
244 bool GrGpuGL::fullReadPixelsIsFasterThanPartial() const {
245     return SkToBool(GR_GL_FULL_READPIXELS_FASTER_THAN_PARTIAL);
246 }
247
248 void GrGpuGL::onResetContext(uint32_t resetBits) {
249     // we don't use the zb at all
250     if (resetBits & kMisc_GrGLBackendState) {
251         GL_CALL(Disable(GR_GL_DEPTH_TEST));
252         GL_CALL(DepthMask(GR_GL_FALSE));
253
254         fHWDrawFace = GrDrawState::kInvalid_DrawFace;
255         fHWDitherEnabled = kUnknown_TriState;
256
257         if (kGL_GrGLStandard == this->glStandard()) {
258             // Desktop-only state that we never change
259             if (!this->glCaps().isCoreProfile()) {
260                 GL_CALL(Disable(GR_GL_POINT_SMOOTH));
261                 GL_CALL(Disable(GR_GL_LINE_SMOOTH));
262                 GL_CALL(Disable(GR_GL_POLYGON_SMOOTH));
263                 GL_CALL(Disable(GR_GL_POLYGON_STIPPLE));
264                 GL_CALL(Disable(GR_GL_COLOR_LOGIC_OP));
265                 GL_CALL(Disable(GR_GL_INDEX_LOGIC_OP));
266             }
267             // The windows NVIDIA driver has GL_ARB_imaging in the extension string when using a
268             // core profile. This seems like a bug since the core spec removes any mention of
269             // GL_ARB_imaging.
270             if (this->glCaps().imagingSupport() && !this->glCaps().isCoreProfile()) {
271                 GL_CALL(Disable(GR_GL_COLOR_TABLE));
272             }
273             GL_CALL(Disable(GR_GL_POLYGON_OFFSET_FILL));
274             // Since ES doesn't support glPointSize at all we always use the VS to
275             // set the point size
276             GL_CALL(Enable(GR_GL_VERTEX_PROGRAM_POINT_SIZE));
277
278             // We should set glPolygonMode(FRONT_AND_BACK,FILL) here, too. It isn't
279             // currently part of our gl interface. There are probably others as
280             // well.
281         }
282
283         if (kGLES_GrGLStandard == this->glStandard() &&
284                 fGLContext.hasExtension("GL_ARM_shader_framebuffer_fetch")) {
285             // The arm extension requires specifically enabling MSAA fetching per sample.
286             // On some devices this may have a perf hit.  Also multiple render targets are disabled
287             GL_CALL(Enable(GR_GL_FETCH_PER_SAMPLE_ARM));
288         }
289         fHWWriteToColor = kUnknown_TriState;
290         // we only ever use lines in hairline mode
291         GL_CALL(LineWidth(1));
292     }
293
294     if (resetBits & kMSAAEnable_GrGLBackendState) {
295         fMSAAEnabled = kUnknown_TriState;
296     }
297
298     fHWActiveTextureUnitIdx = -1; // invalid
299
300     if (resetBits & kTextureBinding_GrGLBackendState) {
301         for (int s = 0; s < fHWBoundTextureUniqueIDs.count(); ++s) {
302             fHWBoundTextureUniqueIDs[s] = SK_InvalidUniqueID;
303         }
304     }
305
306     if (resetBits & kBlend_GrGLBackendState) {
307         fHWBlendState.invalidate();
308     }
309
310     if (resetBits & kView_GrGLBackendState) {
311         fHWScissorSettings.invalidate();
312         fHWViewport.invalidate();
313     }
314
315     if (resetBits & kStencil_GrGLBackendState) {
316         fHWStencilSettings.invalidate();
317         fHWStencilTestEnabled = kUnknown_TriState;
318     }
319
320     // Vertex
321     if (resetBits & kVertex_GrGLBackendState) {
322         fHWGeometryState.invalidate();
323     }
324
325     if (resetBits & kRenderTarget_GrGLBackendState) {
326         fHWBoundRenderTargetUniqueID = SK_InvalidUniqueID;
327     }
328
329     if (resetBits & kPathRendering_GrGLBackendState) {
330         if (this->caps()->pathRenderingSupport()) {
331             fHWProjectionMatrixState.invalidate();
332             // we don't use the model view matrix.
333             GL_CALL(MatrixLoadIdentity(GR_GL_MODELVIEW));
334
335             for (int i = 0; i < this->glCaps().maxFixedFunctionTextureCoords(); ++i) {
336                 fPathRendering->pathTexGen(GR_GL_TEXTURE0 + i, GR_GL_NONE, 0, NULL);
337                 fHWPathTexGenSettings[i].fMode = GR_GL_NONE;
338                 fHWPathTexGenSettings[i].fNumComponents = 0;
339             }
340             fHWActivePathTexGenSets = 0;
341         }
342         fHWPathStencilSettings.invalidate();
343     }
344
345     // we assume these values
346     if (resetBits & kPixelStore_GrGLBackendState) {
347         if (this->glCaps().unpackRowLengthSupport()) {
348             GL_CALL(PixelStorei(GR_GL_UNPACK_ROW_LENGTH, 0));
349         }
350         if (this->glCaps().packRowLengthSupport()) {
351             GL_CALL(PixelStorei(GR_GL_PACK_ROW_LENGTH, 0));
352         }
353         if (this->glCaps().unpackFlipYSupport()) {
354             GL_CALL(PixelStorei(GR_GL_UNPACK_FLIP_Y, GR_GL_FALSE));
355         }
356         if (this->glCaps().packFlipYSupport()) {
357             GL_CALL(PixelStorei(GR_GL_PACK_REVERSE_ROW_ORDER, GR_GL_FALSE));
358         }
359     }
360
361     if (resetBits & kProgram_GrGLBackendState) {
362         fHWProgramID = 0;
363         fSharedGLProgramState.invalidate();
364     }
365 }
366
367 namespace {
368
369 GrSurfaceOrigin resolve_origin(GrSurfaceOrigin origin, bool renderTarget) {
370     // By default, GrRenderTargets are GL's normal orientation so that they
371     // can be drawn to by the outside world without the client having
372     // to render upside down.
373     if (kDefault_GrSurfaceOrigin == origin) {
374         return renderTarget ? kBottomLeft_GrSurfaceOrigin : kTopLeft_GrSurfaceOrigin;
375     } else {
376         return origin;
377     }
378 }
379
380 }
381
382 GrTexture* GrGpuGL::onWrapBackendTexture(const GrBackendTextureDesc& desc) {
383     if (!this->configToGLFormats(desc.fConfig, false, NULL, NULL, NULL)) {
384         return NULL;
385     }
386
387     if (0 == desc.fTextureHandle) {
388         return NULL;
389     }
390
391     int maxSize = this->caps()->maxTextureSize();
392     if (desc.fWidth > maxSize || desc.fHeight > maxSize) {
393         return NULL;
394     }
395
396     GrGLTexture::Desc glTexDesc;
397     // next line relies on GrBackendTextureDesc's flags matching GrTexture's
398     glTexDesc.fFlags = (GrTextureFlags) desc.fFlags;
399     glTexDesc.fWidth = desc.fWidth;
400     glTexDesc.fHeight = desc.fHeight;
401     glTexDesc.fConfig = desc.fConfig;
402     glTexDesc.fSampleCnt = desc.fSampleCnt;
403     glTexDesc.fTextureID = static_cast<GrGLuint>(desc.fTextureHandle);
404     glTexDesc.fIsWrapped = true;
405     bool renderTarget = SkToBool(desc.fFlags & kRenderTarget_GrBackendTextureFlag);
406     // FIXME:  this should be calling resolve_origin(), but Chrome code is currently
407     // assuming the old behaviour, which is that backend textures are always
408     // BottomLeft, even for non-RT's.  Once Chrome is fixed, change this to:
409     // glTexDesc.fOrigin = resolve_origin(desc.fOrigin, renderTarget);
410     if (kDefault_GrSurfaceOrigin == desc.fOrigin) {
411         glTexDesc.fOrigin = kBottomLeft_GrSurfaceOrigin;
412     } else {
413         glTexDesc.fOrigin = desc.fOrigin;
414     }
415
416     GrGLTexture* texture = NULL;
417     if (renderTarget) {
418         GrGLRenderTarget::Desc glRTDesc;
419         glRTDesc.fRTFBOID = 0;
420         glRTDesc.fTexFBOID = 0;
421         glRTDesc.fMSColorRenderbufferID = 0;
422         glRTDesc.fConfig = desc.fConfig;
423         glRTDesc.fSampleCnt = desc.fSampleCnt;
424         glRTDesc.fOrigin = glTexDesc.fOrigin;
425         glRTDesc.fCheckAllocation = false;
426         if (!this->createRenderTargetObjects(glTexDesc.fWidth,
427                                              glTexDesc.fHeight,
428                                              glTexDesc.fTextureID,
429                                              &glRTDesc)) {
430             return NULL;
431         }
432         texture = SkNEW_ARGS(GrGLTexture, (this, glTexDesc, glRTDesc));
433     } else {
434         texture = SkNEW_ARGS(GrGLTexture, (this, glTexDesc));
435     }
436     if (NULL == texture) {
437         return NULL;
438     }
439
440     return texture;
441 }
442
443 GrRenderTarget* GrGpuGL::onWrapBackendRenderTarget(const GrBackendRenderTargetDesc& desc) {
444     GrGLRenderTarget::Desc glDesc;
445     glDesc.fConfig = desc.fConfig;
446     glDesc.fRTFBOID = static_cast<GrGLuint>(desc.fRenderTargetHandle);
447     glDesc.fMSColorRenderbufferID = 0;
448     glDesc.fTexFBOID = GrGLRenderTarget::kUnresolvableFBOID;
449     glDesc.fSampleCnt = desc.fSampleCnt;
450     glDesc.fIsWrapped = true;
451     glDesc.fCheckAllocation = false;
452
453     glDesc.fOrigin = resolve_origin(desc.fOrigin, true);
454     GrGLIRect viewport;
455     viewport.fLeft   = 0;
456     viewport.fBottom = 0;
457     viewport.fWidth  = desc.fWidth;
458     viewport.fHeight = desc.fHeight;
459
460     GrRenderTarget* tgt = SkNEW_ARGS(GrGLRenderTarget,
461                                      (this, glDesc, viewport));
462     if (desc.fStencilBits) {
463         GrGLStencilBuffer::Format format;
464         format.fInternalFormat = GrGLStencilBuffer::kUnknownInternalFormat;
465         format.fPacked = false;
466         format.fStencilBits = desc.fStencilBits;
467         format.fTotalBits = desc.fStencilBits;
468         static const bool kIsSBWrapped = false;
469         GrGLStencilBuffer* sb = SkNEW_ARGS(GrGLStencilBuffer,
470                                            (this,
471                                             kIsSBWrapped,
472                                             0,
473                                             desc.fWidth,
474                                             desc.fHeight,
475                                             desc.fSampleCnt,
476                                             format));
477         tgt->setStencilBuffer(sb);
478         sb->unref();
479     }
480     return tgt;
481 }
482
483 ////////////////////////////////////////////////////////////////////////////////
484
485 bool GrGpuGL::onWriteTexturePixels(GrTexture* texture,
486                                    int left, int top, int width, int height,
487                                    GrPixelConfig config, const void* buffer,
488                                    size_t rowBytes) {
489     if (NULL == buffer) {
490         return false;
491     }
492     GrGLTexture* glTex = static_cast<GrGLTexture*>(texture);
493
494     this->setScratchTextureUnit();
495     GL_CALL(BindTexture(GR_GL_TEXTURE_2D, glTex->textureID()));
496     GrGLTexture::Desc desc;
497     desc.fFlags = glTex->desc().fFlags;
498     desc.fWidth = glTex->width();
499     desc.fHeight = glTex->height();
500     desc.fConfig = glTex->config();
501     desc.fSampleCnt = glTex->desc().fSampleCnt;
502     desc.fTextureID = glTex->textureID();
503     desc.fOrigin = glTex->origin();
504
505     bool success = false;
506     if (GrPixelConfigIsCompressed(desc.fConfig)) {
507         // We check that config == desc.fConfig in GrGpuGL::canWriteTexturePixels()
508         SkASSERT(config == desc.fConfig);
509         success = this->uploadCompressedTexData(desc, buffer, false,
510                                                 left, top, width, height);
511     } else {
512         success = this->uploadTexData(desc, false,
513                                       left, top, width, height,
514                                       config, buffer, rowBytes);
515     }
516
517     if (success) {
518         texture->impl()->dirtyMipMaps(true);
519         return true;
520     }
521
522     return false;
523 }
524
525 namespace {
526 bool adjust_pixel_ops_params(int surfaceWidth,
527                              int surfaceHeight,
528                              size_t bpp,
529                              int* left, int* top, int* width, int* height,
530                              const void** data,
531                              size_t* rowBytes) {
532     if (!*rowBytes) {
533         *rowBytes = *width * bpp;
534     }
535
536     SkIRect subRect = SkIRect::MakeXYWH(*left, *top, *width, *height);
537     SkIRect bounds = SkIRect::MakeWH(surfaceWidth, surfaceHeight);
538
539     if (!subRect.intersect(bounds)) {
540         return false;
541     }
542     *data = reinterpret_cast<const void*>(reinterpret_cast<intptr_t>(*data) +
543           (subRect.fTop - *top) * *rowBytes + (subRect.fLeft - *left) * bpp);
544
545     *left = subRect.fLeft;
546     *top = subRect.fTop;
547     *width = subRect.width();
548     *height = subRect.height();
549     return true;
550 }
551
552 GrGLenum check_alloc_error(const GrTextureDesc& desc, const GrGLInterface* interface) {
553     if (SkToBool(desc.fFlags & kCheckAllocation_GrTextureFlagBit)) {
554         return GR_GL_GET_ERROR(interface);
555     } else {
556         return CHECK_ALLOC_ERROR(interface);
557     }
558 }
559
560 }
561
562 bool GrGpuGL::uploadTexData(const GrGLTexture::Desc& desc,
563                             bool isNewTexture,
564                             int left, int top, int width, int height,
565                             GrPixelConfig dataConfig,
566                             const void* data,
567                             size_t rowBytes) {
568     SkASSERT(NULL != data || isNewTexture);
569
570     // If we're uploading compressed data then we should be using uploadCompressedTexData
571     SkASSERT(!GrPixelConfigIsCompressed(dataConfig));
572
573     size_t bpp = GrBytesPerPixel(dataConfig);
574     if (!adjust_pixel_ops_params(desc.fWidth, desc.fHeight, bpp, &left, &top,
575                                  &width, &height, &data, &rowBytes)) {
576         return false;
577     }
578     size_t trimRowBytes = width * bpp;
579
580     // in case we need a temporary, trimmed copy of the src pixels
581     GrAutoMalloc<128 * 128> tempStorage;
582
583     // We currently lazily create MIPMAPs when the we see a draw with
584     // GrTextureParams::kMipMap_FilterMode. Using texture storage requires that the
585     // MIP levels are all created when the texture is created. So for now we don't use
586     // texture storage.
587     bool useTexStorage = false &&
588                          isNewTexture &&
589                          this->glCaps().texStorageSupport();
590
591     if (useTexStorage && kGL_GrGLStandard == this->glStandard()) {
592         // 565 is not a sized internal format on desktop GL. So on desktop with
593         // 565 we always use an unsized internal format to let the system pick
594         // the best sized format to convert the 565 data to. Since TexStorage
595         // only allows sized internal formats we will instead use TexImage2D.
596         useTexStorage = desc.fConfig != kRGB_565_GrPixelConfig;
597     }
598
599     GrGLenum internalFormat;
600     GrGLenum externalFormat = 0x0; // suprress warning
601     GrGLenum externalType = 0x0;// suprress warning
602
603     // glTexStorage requires sized internal formats on both desktop and ES. ES2 requires an unsized
604     // format for glTexImage, unlike ES3 and desktop. However, we allow the driver to decide the
605     // size of the internal format whenever possible and so only use a sized internal format when
606     // using texture storage.
607     bool useSizedFormat = useTexStorage;
608     // At least some versions of the desktop ES3 drivers for NVIDIA won't accept GL_RED in
609     // glTexImage2D for the internal format but will accept GL_R8.
610     if (!useSizedFormat && kNVIDIA_GrGLVendor == this->glContext().vendor() &&
611         kGLES_GrGLStandard == this->glStandard() && this->glVersion() >= GR_GL_VER(3, 0)) {
612         useSizedFormat = true;
613     }
614     if (!this->configToGLFormats(dataConfig, useSizedFormat, &internalFormat,
615                                  &externalFormat, &externalType)) {
616         return false;
617     }
618
619     /*
620      *  check whether to allocate a temporary buffer for flipping y or
621      *  because our srcData has extra bytes past each row. If so, we need
622      *  to trim those off here, since GL ES may not let us specify
623      *  GL_UNPACK_ROW_LENGTH.
624      */
625     bool restoreGLRowLength = false;
626     bool swFlipY = false;
627     bool glFlipY = false;
628     if (NULL != data) {
629         if (kBottomLeft_GrSurfaceOrigin == desc.fOrigin) {
630             if (this->glCaps().unpackFlipYSupport()) {
631                 glFlipY = true;
632             } else {
633                 swFlipY = true;
634             }
635         }
636         if (this->glCaps().unpackRowLengthSupport() && !swFlipY) {
637             // can't use this for flipping, only non-neg values allowed. :(
638             if (rowBytes != trimRowBytes) {
639                 GrGLint rowLength = static_cast<GrGLint>(rowBytes / bpp);
640                 GL_CALL(PixelStorei(GR_GL_UNPACK_ROW_LENGTH, rowLength));
641                 restoreGLRowLength = true;
642             }
643         } else {
644             if (trimRowBytes != rowBytes || swFlipY) {
645                 // copy data into our new storage, skipping the trailing bytes
646                 size_t trimSize = height * trimRowBytes;
647                 const char* src = (const char*)data;
648                 if (swFlipY) {
649                     src += (height - 1) * rowBytes;
650                 }
651                 char* dst = (char*)tempStorage.reset(trimSize);
652                 for (int y = 0; y < height; y++) {
653                     memcpy(dst, src, trimRowBytes);
654                     if (swFlipY) {
655                         src -= rowBytes;
656                     } else {
657                         src += rowBytes;
658                     }
659                     dst += trimRowBytes;
660                 }
661                 // now point data to our copied version
662                 data = tempStorage.get();
663             }
664         }
665         if (glFlipY) {
666             GL_CALL(PixelStorei(GR_GL_UNPACK_FLIP_Y, GR_GL_TRUE));
667         }
668         GL_CALL(PixelStorei(GR_GL_UNPACK_ALIGNMENT,
669               static_cast<GrGLint>(GrUnpackAlignment(dataConfig))));
670     }
671     bool succeeded = true;
672     if (isNewTexture &&
673         0 == left && 0 == top &&
674         desc.fWidth == width && desc.fHeight == height) {
675         CLEAR_ERROR_BEFORE_ALLOC(this->glInterface());
676         if (useTexStorage) {
677             // We never resize  or change formats of textures.
678             GL_ALLOC_CALL(this->glInterface(),
679                           TexStorage2D(GR_GL_TEXTURE_2D,
680                                        1, // levels
681                                        internalFormat,
682                                        desc.fWidth, desc.fHeight));
683         } else {
684             GL_ALLOC_CALL(this->glInterface(),
685                           TexImage2D(GR_GL_TEXTURE_2D,
686                                      0, // level
687                                      internalFormat,
688                                      desc.fWidth, desc.fHeight,
689                                      0, // border
690                                      externalFormat, externalType,
691                                      data));
692         }
693         GrGLenum error = check_alloc_error(desc, this->glInterface());
694         if (error != GR_GL_NO_ERROR) {
695             succeeded = false;
696         } else {
697             // if we have data and we used TexStorage to create the texture, we
698             // now upload with TexSubImage.
699             if (NULL != data && useTexStorage) {
700                 GL_CALL(TexSubImage2D(GR_GL_TEXTURE_2D,
701                                       0, // level
702                                       left, top,
703                                       width, height,
704                                       externalFormat, externalType,
705                                       data));
706             }
707         }
708     } else {
709         if (swFlipY || glFlipY) {
710             top = desc.fHeight - (top + height);
711         }
712         GL_CALL(TexSubImage2D(GR_GL_TEXTURE_2D,
713                               0, // level
714                               left, top,
715                               width, height,
716                               externalFormat, externalType, data));
717     }
718
719     if (restoreGLRowLength) {
720         SkASSERT(this->glCaps().unpackRowLengthSupport());
721         GL_CALL(PixelStorei(GR_GL_UNPACK_ROW_LENGTH, 0));
722     }
723     if (glFlipY) {
724         GL_CALL(PixelStorei(GR_GL_UNPACK_FLIP_Y, GR_GL_FALSE));
725     }
726     return succeeded;
727 }
728
729 // TODO: This function is using a lot of wonky semantics like, if width == -1
730 // then set width = desc.fWdith ... blah. A better way to do it might be to 
731 // create a CompressedTexData struct that takes a desc/ptr and figures out
732 // the proper upload semantics. Then users can construct this function how they
733 // see fit if they want to go against the "standard" way to do it.
734 bool GrGpuGL::uploadCompressedTexData(const GrGLTexture::Desc& desc,
735                                       const void* data,
736                                       bool isNewTexture,
737                                       int left, int top, int width, int height) {
738     SkASSERT(NULL != data || isNewTexture);
739
740     // No support for software flip y, yet...
741     SkASSERT(kBottomLeft_GrSurfaceOrigin != desc.fOrigin);
742
743     if (-1 == width) {
744         width = desc.fWidth;
745     }
746 #ifdef SK_DEBUG
747     else {
748         SkASSERT(width <= desc.fWidth);
749     }
750 #endif
751
752     if (-1 == height) {
753         height = desc.fHeight;
754     }
755 #ifdef SK_DEBUG
756     else {
757         SkASSERT(height <= desc.fHeight);
758     }
759 #endif
760
761     // Make sure that the width and height that we pass to OpenGL
762     // is a multiple of the block size.
763     int dataSize = GrCompressedFormatDataSize(desc.fConfig, width, height);
764
765     // We only need the internal format for compressed 2D textures.
766     GrGLenum internalFormat = 0;
767     if (!this->configToGLFormats(desc.fConfig, false, &internalFormat, NULL, NULL)) {
768         return false;
769     }
770
771     if (isNewTexture) {
772         CLEAR_ERROR_BEFORE_ALLOC(this->glInterface());
773         GL_ALLOC_CALL(this->glInterface(),
774                       CompressedTexImage2D(GR_GL_TEXTURE_2D,
775                                            0, // level
776                                            internalFormat,
777                                            width, height,
778                                            0, // border
779                                            dataSize,
780                                            data));
781         GrGLenum error = check_alloc_error(desc, this->glInterface());
782         if (error != GR_GL_NO_ERROR) {
783             return false;
784         }
785     } else {
786         // Paletted textures can't be updated.
787         if (GR_GL_PALETTE8_RGBA8 == internalFormat) {
788             return false;
789         }
790         GL_CALL(CompressedTexSubImage2D(GR_GL_TEXTURE_2D,
791                                         0, // level
792                                         left, top,
793                                         width, height,
794                                         internalFormat,
795                                         dataSize,
796                                         data));
797     }
798
799     return true;
800 }
801
802 static bool renderbuffer_storage_msaa(GrGLContext& ctx,
803                                       int sampleCount,
804                                       GrGLenum format,
805                                       int width, int height) {
806     CLEAR_ERROR_BEFORE_ALLOC(ctx.interface());
807     SkASSERT(GrGLCaps::kNone_MSFBOType != ctx.caps()->msFBOType());
808     switch (ctx.caps()->msFBOType()) {
809         case GrGLCaps::kDesktop_ARB_MSFBOType:
810         case GrGLCaps::kDesktop_EXT_MSFBOType:
811         case GrGLCaps::kES_3_0_MSFBOType:
812             GL_ALLOC_CALL(ctx.interface(),
813                             RenderbufferStorageMultisample(GR_GL_RENDERBUFFER,
814                                                             sampleCount,
815                                                             format,
816                                                             width, height));
817             break;
818         case GrGLCaps::kES_Apple_MSFBOType:
819             GL_ALLOC_CALL(ctx.interface(),
820                             RenderbufferStorageMultisampleES2APPLE(GR_GL_RENDERBUFFER,
821                                                                     sampleCount,
822                                                                     format,
823                                                                     width, height));
824             break;
825         case GrGLCaps::kES_EXT_MsToTexture_MSFBOType:
826         case GrGLCaps::kES_IMG_MsToTexture_MSFBOType:
827             GL_ALLOC_CALL(ctx.interface(),
828                             RenderbufferStorageMultisampleES2EXT(GR_GL_RENDERBUFFER,
829                                                                 sampleCount,
830                                                                 format,
831                                                                 width, height));
832             break;
833         case GrGLCaps::kNone_MSFBOType:
834             SkFAIL("Shouldn't be here if we don't support multisampled renderbuffers.");
835             break;
836     }
837     return (GR_GL_NO_ERROR == CHECK_ALLOC_ERROR(ctx.interface()));;
838 }
839
840 bool GrGpuGL::createRenderTargetObjects(int width, int height,
841                                         GrGLuint texID,
842                                         GrGLRenderTarget::Desc* desc) {
843     desc->fMSColorRenderbufferID = 0;
844     desc->fRTFBOID = 0;
845     desc->fTexFBOID = 0;
846     desc->fIsWrapped = false;
847
848     GrGLenum status;
849
850     GrGLenum msColorFormat = 0; // suppress warning
851
852     if (desc->fSampleCnt > 0 && GrGLCaps::kNone_MSFBOType == this->glCaps().msFBOType()) {
853         goto FAILED;
854     }
855
856     GL_CALL(GenFramebuffers(1, &desc->fTexFBOID));
857     if (!desc->fTexFBOID) {
858         goto FAILED;
859     }
860
861
862     // If we are using multisampling we will create two FBOS. We render to one and then resolve to
863     // the texture bound to the other. The exception is the IMG multisample extension. With this
864     // extension the texture is multisampled when rendered to and then auto-resolves it when it is
865     // rendered from.
866     if (desc->fSampleCnt > 0 && this->glCaps().usesMSAARenderBuffers()) {
867         GL_CALL(GenFramebuffers(1, &desc->fRTFBOID));
868         GL_CALL(GenRenderbuffers(1, &desc->fMSColorRenderbufferID));
869         if (!desc->fRTFBOID ||
870             !desc->fMSColorRenderbufferID ||
871             !this->configToGLFormats(desc->fConfig,
872                                      // ES2 and ES3 require sized internal formats for rb storage.
873                                      kGLES_GrGLStandard == this->glStandard(),
874                                      &msColorFormat,
875                                      NULL,
876                                      NULL)) {
877             goto FAILED;
878         }
879     } else {
880         desc->fRTFBOID = desc->fTexFBOID;
881     }
882
883     // below here we may bind the FBO
884     fHWBoundRenderTargetUniqueID = SK_InvalidUniqueID;
885     if (desc->fRTFBOID != desc->fTexFBOID) {
886         SkASSERT(desc->fSampleCnt > 0);
887         GL_CALL(BindRenderbuffer(GR_GL_RENDERBUFFER,
888                                desc->fMSColorRenderbufferID));
889         if (!renderbuffer_storage_msaa(fGLContext,
890                                        desc->fSampleCnt,
891                                        msColorFormat,
892                                        width, height)) {
893             goto FAILED;
894         }
895         GL_CALL(BindFramebuffer(GR_GL_FRAMEBUFFER, desc->fRTFBOID));
896         GL_CALL(FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
897                                       GR_GL_COLOR_ATTACHMENT0,
898                                       GR_GL_RENDERBUFFER,
899                                       desc->fMSColorRenderbufferID));
900         if (desc->fCheckAllocation ||
901             !this->glCaps().isConfigVerifiedColorAttachment(desc->fConfig)) {
902             GL_CALL_RET(status, CheckFramebufferStatus(GR_GL_FRAMEBUFFER));
903             if (status != GR_GL_FRAMEBUFFER_COMPLETE) {
904                 goto FAILED;
905             }
906             fGLContext.caps()->markConfigAsValidColorAttachment(desc->fConfig);
907         }
908     }
909     GL_CALL(BindFramebuffer(GR_GL_FRAMEBUFFER, desc->fTexFBOID));
910
911     if (this->glCaps().usesImplicitMSAAResolve() && desc->fSampleCnt > 0) {
912         GL_CALL(FramebufferTexture2DMultisample(GR_GL_FRAMEBUFFER,
913                                                 GR_GL_COLOR_ATTACHMENT0,
914                                                 GR_GL_TEXTURE_2D,
915                                                 texID, 0, desc->fSampleCnt));
916     } else {
917         GL_CALL(FramebufferTexture2D(GR_GL_FRAMEBUFFER,
918                                      GR_GL_COLOR_ATTACHMENT0,
919                                      GR_GL_TEXTURE_2D,
920                                      texID, 0));
921     }
922     if (desc->fCheckAllocation ||
923         !this->glCaps().isConfigVerifiedColorAttachment(desc->fConfig)) {
924         GL_CALL_RET(status, CheckFramebufferStatus(GR_GL_FRAMEBUFFER));
925         if (status != GR_GL_FRAMEBUFFER_COMPLETE) {
926             goto FAILED;
927         }
928         fGLContext.caps()->markConfigAsValidColorAttachment(desc->fConfig);
929     }
930
931     return true;
932
933 FAILED:
934     if (desc->fMSColorRenderbufferID) {
935         GL_CALL(DeleteRenderbuffers(1, &desc->fMSColorRenderbufferID));
936     }
937     if (desc->fRTFBOID != desc->fTexFBOID) {
938         GL_CALL(DeleteFramebuffers(1, &desc->fRTFBOID));
939     }
940     if (desc->fTexFBOID) {
941         GL_CALL(DeleteFramebuffers(1, &desc->fTexFBOID));
942     }
943     return false;
944 }
945
946 // good to set a break-point here to know when createTexture fails
947 static GrTexture* return_null_texture() {
948 //    SkDEBUGFAIL("null texture");
949     return NULL;
950 }
951
952 #if 0 && defined(SK_DEBUG)
953 static size_t as_size_t(int x) {
954     return x;
955 }
956 #endif
957
958 GrTexture* GrGpuGL::onCreateTexture(const GrTextureDesc& desc,
959                                     const void* srcData,
960                                     size_t rowBytes) {
961
962     GrGLTexture::Desc glTexDesc;
963     GrGLRenderTarget::Desc  glRTDesc;
964
965     // Attempt to catch un- or wrongly initialized sample counts;
966     SkASSERT(desc.fSampleCnt >= 0 && desc.fSampleCnt <= 64);
967     // We fail if the MSAA was requested and is not available.
968     if (GrGLCaps::kNone_MSFBOType == this->glCaps().msFBOType() && desc.fSampleCnt) {
969         //GrPrintf("MSAA RT requested but not supported on this platform.");
970         return return_null_texture();
971     }
972     // If the sample count exceeds the max then we clamp it.
973     glTexDesc.fSampleCnt = SkTMin(desc.fSampleCnt, this->caps()->maxSampleCount());
974
975     glTexDesc.fFlags  = desc.fFlags;
976     glTexDesc.fWidth  = desc.fWidth;
977     glTexDesc.fHeight = desc.fHeight;
978     glTexDesc.fConfig = desc.fConfig;
979     glTexDesc.fIsWrapped = false;
980
981     glRTDesc.fMSColorRenderbufferID = 0;
982     glRTDesc.fRTFBOID = 0;
983     glRTDesc.fTexFBOID = 0;
984     glRTDesc.fIsWrapped = false;
985     glRTDesc.fConfig = glTexDesc.fConfig;
986     glRTDesc.fCheckAllocation = SkToBool(desc.fFlags & kCheckAllocation_GrTextureFlagBit);
987
988     bool renderTarget = SkToBool(desc.fFlags & kRenderTarget_GrTextureFlagBit);
989
990     glTexDesc.fOrigin = resolve_origin(desc.fOrigin, renderTarget);
991     glRTDesc.fOrigin = glTexDesc.fOrigin;
992
993     glRTDesc.fSampleCnt = glTexDesc.fSampleCnt;
994     if (GrGLCaps::kNone_MSFBOType == this->glCaps().msFBOType() &&
995         desc.fSampleCnt) {
996         //GrPrintf("MSAA RT requested but not supported on this platform.");
997         return return_null_texture();
998     }
999
1000     if (renderTarget) {
1001         int maxRTSize = this->caps()->maxRenderTargetSize();
1002         if (glTexDesc.fWidth > maxRTSize || glTexDesc.fHeight > maxRTSize) {
1003             return return_null_texture();
1004         }
1005     } else {
1006         int maxSize = this->caps()->maxTextureSize();
1007         if (glTexDesc.fWidth > maxSize || glTexDesc.fHeight > maxSize) {
1008             return return_null_texture();
1009         }
1010     }
1011
1012     GL_CALL(GenTextures(1, &glTexDesc.fTextureID));
1013
1014     if (!glTexDesc.fTextureID) {
1015         return return_null_texture();
1016     }
1017
1018     this->setScratchTextureUnit();
1019     GL_CALL(BindTexture(GR_GL_TEXTURE_2D, glTexDesc.fTextureID));
1020
1021     if (renderTarget && this->glCaps().textureUsageSupport()) {
1022         // provides a hint about how this texture will be used
1023         GL_CALL(TexParameteri(GR_GL_TEXTURE_2D,
1024                               GR_GL_TEXTURE_USAGE,
1025                               GR_GL_FRAMEBUFFER_ATTACHMENT));
1026     }
1027
1028     // Some drivers like to know filter/wrap before seeing glTexImage2D. Some
1029     // drivers have a bug where an FBO won't be complete if it includes a
1030     // texture that is not mipmap complete (considering the filter in use).
1031     GrGLTexture::TexParams initialTexParams;
1032     // we only set a subset here so invalidate first
1033     initialTexParams.invalidate();
1034     initialTexParams.fMinFilter = GR_GL_NEAREST;
1035     initialTexParams.fMagFilter = GR_GL_NEAREST;
1036     initialTexParams.fWrapS = GR_GL_CLAMP_TO_EDGE;
1037     initialTexParams.fWrapT = GR_GL_CLAMP_TO_EDGE;
1038     GL_CALL(TexParameteri(GR_GL_TEXTURE_2D,
1039                           GR_GL_TEXTURE_MAG_FILTER,
1040                           initialTexParams.fMagFilter));
1041     GL_CALL(TexParameteri(GR_GL_TEXTURE_2D,
1042                           GR_GL_TEXTURE_MIN_FILTER,
1043                           initialTexParams.fMinFilter));
1044     GL_CALL(TexParameteri(GR_GL_TEXTURE_2D,
1045                           GR_GL_TEXTURE_WRAP_S,
1046                           initialTexParams.fWrapS));
1047     GL_CALL(TexParameteri(GR_GL_TEXTURE_2D,
1048                           GR_GL_TEXTURE_WRAP_T,
1049                           initialTexParams.fWrapT));
1050     if (!this->uploadTexData(glTexDesc, true, 0, 0,
1051                              glTexDesc.fWidth, glTexDesc.fHeight,
1052                              desc.fConfig, srcData, rowBytes)) {
1053         GL_CALL(DeleteTextures(1, &glTexDesc.fTextureID));
1054         return return_null_texture();
1055     }
1056
1057     GrGLTexture* tex;
1058     if (renderTarget) {
1059         // unbind the texture from the texture unit before binding it to the frame buffer
1060         GL_CALL(BindTexture(GR_GL_TEXTURE_2D, 0));
1061
1062         if (!this->createRenderTargetObjects(glTexDesc.fWidth,
1063                                              glTexDesc.fHeight,
1064                                              glTexDesc.fTextureID,
1065                                              &glRTDesc)) {
1066             GL_CALL(DeleteTextures(1, &glTexDesc.fTextureID));
1067             return return_null_texture();
1068         }
1069         tex = SkNEW_ARGS(GrGLTexture, (this, glTexDesc, glRTDesc));
1070     } else {
1071         tex = SkNEW_ARGS(GrGLTexture, (this, glTexDesc));
1072     }
1073     tex->setCachedTexParams(initialTexParams, this->getResetTimestamp());
1074 #ifdef TRACE_TEXTURE_CREATION
1075     GrPrintf("--- new texture [%d] size=(%d %d) config=%d\n",
1076              glTexDesc.fTextureID, desc.fWidth, desc.fHeight, desc.fConfig);
1077 #endif
1078     return tex;
1079 }
1080
1081 GrTexture* GrGpuGL::onCreateCompressedTexture(const GrTextureDesc& desc,
1082                                               const void* srcData) {
1083
1084     if(SkToBool(desc.fFlags & kRenderTarget_GrTextureFlagBit)) {
1085         return return_null_texture();
1086     }
1087
1088     // Make sure that we're not flipping Y.
1089     GrSurfaceOrigin texOrigin = resolve_origin(desc.fOrigin, false);
1090     if (kBottomLeft_GrSurfaceOrigin == texOrigin) {
1091         return return_null_texture();
1092     }
1093
1094     GrGLTexture::Desc glTexDesc;
1095
1096     glTexDesc.fFlags  = desc.fFlags;
1097     glTexDesc.fWidth  = desc.fWidth;
1098     glTexDesc.fHeight = desc.fHeight;
1099     glTexDesc.fConfig = desc.fConfig;
1100     glTexDesc.fIsWrapped = false;
1101     glTexDesc.fOrigin = texOrigin;
1102
1103     int maxSize = this->caps()->maxTextureSize();
1104     if (glTexDesc.fWidth > maxSize || glTexDesc.fHeight > maxSize) {
1105         return return_null_texture();
1106     }
1107
1108     GL_CALL(GenTextures(1, &glTexDesc.fTextureID));
1109
1110     if (!glTexDesc.fTextureID) {
1111         return return_null_texture();
1112     }
1113
1114     this->setScratchTextureUnit();
1115     GL_CALL(BindTexture(GR_GL_TEXTURE_2D, glTexDesc.fTextureID));
1116
1117     // Some drivers like to know filter/wrap before seeing glTexImage2D. Some
1118     // drivers have a bug where an FBO won't be complete if it includes a
1119     // texture that is not mipmap complete (considering the filter in use).
1120     GrGLTexture::TexParams initialTexParams;
1121     // we only set a subset here so invalidate first
1122     initialTexParams.invalidate();
1123     initialTexParams.fMinFilter = GR_GL_NEAREST;
1124     initialTexParams.fMagFilter = GR_GL_NEAREST;
1125     initialTexParams.fWrapS = GR_GL_CLAMP_TO_EDGE;
1126     initialTexParams.fWrapT = GR_GL_CLAMP_TO_EDGE;
1127     GL_CALL(TexParameteri(GR_GL_TEXTURE_2D,
1128                           GR_GL_TEXTURE_MAG_FILTER,
1129                           initialTexParams.fMagFilter));
1130     GL_CALL(TexParameteri(GR_GL_TEXTURE_2D,
1131                           GR_GL_TEXTURE_MIN_FILTER,
1132                           initialTexParams.fMinFilter));
1133     GL_CALL(TexParameteri(GR_GL_TEXTURE_2D,
1134                           GR_GL_TEXTURE_WRAP_S,
1135                           initialTexParams.fWrapS));
1136     GL_CALL(TexParameteri(GR_GL_TEXTURE_2D,
1137                           GR_GL_TEXTURE_WRAP_T,
1138                           initialTexParams.fWrapT));
1139
1140     if (!this->uploadCompressedTexData(glTexDesc, srcData)) {
1141         GL_CALL(DeleteTextures(1, &glTexDesc.fTextureID));
1142         return return_null_texture();
1143     }
1144
1145     GrGLTexture* tex;
1146     tex = SkNEW_ARGS(GrGLTexture, (this, glTexDesc));
1147     tex->setCachedTexParams(initialTexParams, this->getResetTimestamp());
1148 #ifdef TRACE_TEXTURE_CREATION
1149     GrPrintf("--- new compressed texture [%d] size=(%d %d) config=%d\n",
1150              glTexDesc.fTextureID, desc.fWidth, desc.fHeight, desc.fConfig);
1151 #endif
1152     return tex;
1153 }
1154
1155 namespace {
1156
1157 const GrGLuint kUnknownBitCount = GrGLStencilBuffer::kUnknownBitCount;
1158
1159 void inline get_stencil_rb_sizes(const GrGLInterface* gl,
1160                                  GrGLStencilBuffer::Format* format) {
1161
1162     // we shouldn't ever know one size and not the other
1163     SkASSERT((kUnknownBitCount == format->fStencilBits) ==
1164              (kUnknownBitCount == format->fTotalBits));
1165     if (kUnknownBitCount == format->fStencilBits) {
1166         GR_GL_GetRenderbufferParameteriv(gl, GR_GL_RENDERBUFFER,
1167                                          GR_GL_RENDERBUFFER_STENCIL_SIZE,
1168                                          (GrGLint*)&format->fStencilBits);
1169         if (format->fPacked) {
1170             GR_GL_GetRenderbufferParameteriv(gl, GR_GL_RENDERBUFFER,
1171                                              GR_GL_RENDERBUFFER_DEPTH_SIZE,
1172                                              (GrGLint*)&format->fTotalBits);
1173             format->fTotalBits += format->fStencilBits;
1174         } else {
1175             format->fTotalBits = format->fStencilBits;
1176         }
1177     }
1178 }
1179 }
1180
1181 bool GrGpuGL::createStencilBufferForRenderTarget(GrRenderTarget* rt,
1182                                                  int width, int height) {
1183
1184     // All internally created RTs are also textures. We don't create
1185     // SBs for a client's standalone RT (that is a RT that isn't also a texture).
1186     SkASSERT(rt->asTexture());
1187     SkASSERT(width >= rt->width());
1188     SkASSERT(height >= rt->height());
1189
1190     int samples = rt->numSamples();
1191     GrGLuint sbID;
1192     GL_CALL(GenRenderbuffers(1, &sbID));
1193     if (!sbID) {
1194         return false;
1195     }
1196
1197     int stencilFmtCnt = this->glCaps().stencilFormats().count();
1198     for (int i = 0; i < stencilFmtCnt; ++i) {
1199         GL_CALL(BindRenderbuffer(GR_GL_RENDERBUFFER, sbID));
1200         // we start with the last stencil format that succeeded in hopes
1201         // that we won't go through this loop more than once after the
1202         // first (painful) stencil creation.
1203         int sIdx = (i + fLastSuccessfulStencilFmtIdx) % stencilFmtCnt;
1204         const GrGLCaps::StencilFormat& sFmt =
1205                 this->glCaps().stencilFormats()[sIdx];
1206         CLEAR_ERROR_BEFORE_ALLOC(this->glInterface());
1207         // we do this "if" so that we don't call the multisample
1208         // version on a GL that doesn't have an MSAA extension.
1209         bool created;
1210         if (samples > 0) {
1211             created = renderbuffer_storage_msaa(fGLContext,
1212                                                 samples,
1213                                                 sFmt.fInternalFormat,
1214                                                 width, height);
1215         } else {
1216             GL_ALLOC_CALL(this->glInterface(),
1217                           RenderbufferStorage(GR_GL_RENDERBUFFER,
1218                                               sFmt.fInternalFormat,
1219                                               width, height));
1220             created =
1221                 (GR_GL_NO_ERROR == check_alloc_error(rt->desc(), this->glInterface()));
1222         }
1223         if (created) {
1224             // After sized formats we attempt an unsized format and take
1225             // whatever sizes GL gives us. In that case we query for the size.
1226             GrGLStencilBuffer::Format format = sFmt;
1227             get_stencil_rb_sizes(this->glInterface(), &format);
1228             static const bool kIsWrapped = false;
1229             SkAutoTUnref<GrStencilBuffer> sb(SkNEW_ARGS(GrGLStencilBuffer,
1230                                                   (this, kIsWrapped, sbID, width, height,
1231                                                   samples, format)));
1232             if (this->attachStencilBufferToRenderTarget(sb, rt)) {
1233                 fLastSuccessfulStencilFmtIdx = sIdx;
1234                 sb->transferToCache();
1235                 rt->setStencilBuffer(sb);
1236                 return true;
1237            }
1238            sb->abandon(); // otherwise we lose sbID
1239         }
1240     }
1241     GL_CALL(DeleteRenderbuffers(1, &sbID));
1242     return false;
1243 }
1244
1245 bool GrGpuGL::attachStencilBufferToRenderTarget(GrStencilBuffer* sb, GrRenderTarget* rt) {
1246     GrGLRenderTarget* glrt = (GrGLRenderTarget*) rt;
1247
1248     GrGLuint fbo = glrt->renderFBOID();
1249
1250     if (NULL == sb) {
1251         if (NULL != rt->getStencilBuffer()) {
1252             GL_CALL(FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
1253                                             GR_GL_STENCIL_ATTACHMENT,
1254                                             GR_GL_RENDERBUFFER, 0));
1255             GL_CALL(FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
1256                                             GR_GL_DEPTH_ATTACHMENT,
1257                                             GR_GL_RENDERBUFFER, 0));
1258 #ifdef SK_DEBUG
1259             GrGLenum status;
1260             GL_CALL_RET(status, CheckFramebufferStatus(GR_GL_FRAMEBUFFER));
1261             SkASSERT(GR_GL_FRAMEBUFFER_COMPLETE == status);
1262 #endif
1263         }
1264         return true;
1265     } else {
1266         GrGLStencilBuffer* glsb = static_cast<GrGLStencilBuffer*>(sb);
1267         GrGLuint rb = glsb->renderbufferID();
1268
1269         fHWBoundRenderTargetUniqueID = SK_InvalidUniqueID;
1270         GL_CALL(BindFramebuffer(GR_GL_FRAMEBUFFER, fbo));
1271         GL_CALL(FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
1272                                         GR_GL_STENCIL_ATTACHMENT,
1273                                         GR_GL_RENDERBUFFER, rb));
1274         if (glsb->format().fPacked) {
1275             GL_CALL(FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
1276                                             GR_GL_DEPTH_ATTACHMENT,
1277                                             GR_GL_RENDERBUFFER, rb));
1278         } else {
1279             GL_CALL(FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
1280                                             GR_GL_DEPTH_ATTACHMENT,
1281                                             GR_GL_RENDERBUFFER, 0));
1282         }
1283
1284         GrGLenum status;
1285         if (!this->glCaps().isColorConfigAndStencilFormatVerified(rt->config(), glsb->format())) {
1286             GL_CALL_RET(status, CheckFramebufferStatus(GR_GL_FRAMEBUFFER));
1287             if (status != GR_GL_FRAMEBUFFER_COMPLETE) {
1288                 GL_CALL(FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
1289                                               GR_GL_STENCIL_ATTACHMENT,
1290                                               GR_GL_RENDERBUFFER, 0));
1291                 if (glsb->format().fPacked) {
1292                     GL_CALL(FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
1293                                                   GR_GL_DEPTH_ATTACHMENT,
1294                                                   GR_GL_RENDERBUFFER, 0));
1295                 }
1296                 return false;
1297             } else {
1298                 fGLContext.caps()->markColorConfigAndStencilFormatAsVerified(
1299                     rt->config(),
1300                     glsb->format());
1301             }
1302         }
1303         return true;
1304     }
1305 }
1306
1307 ////////////////////////////////////////////////////////////////////////////////
1308
1309 GrVertexBuffer* GrGpuGL::onCreateVertexBuffer(size_t size, bool dynamic) {
1310     GrGLVertexBuffer::Desc desc;
1311     desc.fDynamic = dynamic;
1312     desc.fSizeInBytes = size;
1313     desc.fIsWrapped = false;
1314
1315     if (this->glCaps().useNonVBOVertexAndIndexDynamicData() && desc.fDynamic) {
1316         desc.fID = 0;
1317         GrGLVertexBuffer* vertexBuffer = SkNEW_ARGS(GrGLVertexBuffer, (this, desc));
1318         return vertexBuffer;
1319     } else {
1320         GL_CALL(GenBuffers(1, &desc.fID));
1321         if (desc.fID) {
1322             fHWGeometryState.setVertexBufferID(this, desc.fID);
1323             CLEAR_ERROR_BEFORE_ALLOC(this->glInterface());
1324             // make sure driver can allocate memory for this buffer
1325             GL_ALLOC_CALL(this->glInterface(),
1326                           BufferData(GR_GL_ARRAY_BUFFER,
1327                                      (GrGLsizeiptr) desc.fSizeInBytes,
1328                                      NULL,   // data ptr
1329                                      desc.fDynamic ? GR_GL_DYNAMIC_DRAW : GR_GL_STATIC_DRAW));
1330             if (CHECK_ALLOC_ERROR(this->glInterface()) != GR_GL_NO_ERROR) {
1331                 GL_CALL(DeleteBuffers(1, &desc.fID));
1332                 this->notifyVertexBufferDelete(desc.fID);
1333                 return NULL;
1334             }
1335             GrGLVertexBuffer* vertexBuffer = SkNEW_ARGS(GrGLVertexBuffer, (this, desc));
1336             return vertexBuffer;
1337         }
1338         return NULL;
1339     }
1340 }
1341
1342 GrIndexBuffer* GrGpuGL::onCreateIndexBuffer(size_t size, bool dynamic) {
1343     GrGLIndexBuffer::Desc desc;
1344     desc.fDynamic = dynamic;
1345     desc.fSizeInBytes = size;
1346     desc.fIsWrapped = false;
1347
1348     if (this->glCaps().useNonVBOVertexAndIndexDynamicData() && desc.fDynamic) {
1349         desc.fID = 0;
1350         GrIndexBuffer* indexBuffer = SkNEW_ARGS(GrGLIndexBuffer, (this, desc));
1351         return indexBuffer;
1352     } else {
1353         GL_CALL(GenBuffers(1, &desc.fID));
1354         if (desc.fID) {
1355             fHWGeometryState.setIndexBufferIDOnDefaultVertexArray(this, desc.fID);
1356             CLEAR_ERROR_BEFORE_ALLOC(this->glInterface());
1357             // make sure driver can allocate memory for this buffer
1358             GL_ALLOC_CALL(this->glInterface(),
1359                           BufferData(GR_GL_ELEMENT_ARRAY_BUFFER,
1360                                      (GrGLsizeiptr) desc.fSizeInBytes,
1361                                      NULL,  // data ptr
1362                                      desc.fDynamic ? GR_GL_DYNAMIC_DRAW : GR_GL_STATIC_DRAW));
1363             if (CHECK_ALLOC_ERROR(this->glInterface()) != GR_GL_NO_ERROR) {
1364                 GL_CALL(DeleteBuffers(1, &desc.fID));
1365                 this->notifyIndexBufferDelete(desc.fID);
1366                 return NULL;
1367             }
1368             GrIndexBuffer* indexBuffer = SkNEW_ARGS(GrGLIndexBuffer, (this, desc));
1369             return indexBuffer;
1370         }
1371         return NULL;
1372     }
1373 }
1374
1375 GrPath* GrGpuGL::onCreatePath(const SkPath& inPath, const SkStrokeRec& stroke) {
1376     SkASSERT(this->caps()->pathRenderingSupport());
1377     return SkNEW_ARGS(GrGLPath, (this, inPath, stroke));
1378 }
1379
1380 GrPathRange* GrGpuGL::onCreatePathRange(size_t size, const SkStrokeRec& stroke) {
1381     SkASSERT(this->caps()->pathRenderingSupport());
1382     return SkNEW_ARGS(GrGLPathRange, (this, size, stroke));
1383 }
1384
1385 void GrGpuGL::flushScissor() {
1386     if (fScissorState.fEnabled) {
1387         // Only access the RT if scissoring is being enabled. We can call this before performing
1388         // a glBitframebuffer for a surface->surface copy, which requires no RT to be bound to the
1389         // GrDrawState.
1390         const GrDrawState& drawState = this->getDrawState();
1391         const GrGLRenderTarget* rt =
1392             static_cast<const GrGLRenderTarget*>(drawState.getRenderTarget());
1393
1394         SkASSERT(NULL != rt);
1395         const GrGLIRect& vp = rt->getViewport();
1396         GrGLIRect scissor;
1397         scissor.setRelativeTo(vp,
1398                               fScissorState.fRect.fLeft,
1399                               fScissorState.fRect.fTop,
1400                               fScissorState.fRect.width(),
1401                               fScissorState.fRect.height(),
1402                               rt->origin());
1403         // if the scissor fully contains the viewport then we fall through and
1404         // disable the scissor test.
1405         if (!scissor.contains(vp)) {
1406             if (fHWScissorSettings.fRect != scissor) {
1407                 scissor.pushToGLScissor(this->glInterface());
1408                 fHWScissorSettings.fRect = scissor;
1409             }
1410             if (kYes_TriState != fHWScissorSettings.fEnabled) {
1411                 GL_CALL(Enable(GR_GL_SCISSOR_TEST));
1412                 fHWScissorSettings.fEnabled = kYes_TriState;
1413             }
1414             return;
1415         }
1416     }
1417     if (kNo_TriState != fHWScissorSettings.fEnabled) {
1418         GL_CALL(Disable(GR_GL_SCISSOR_TEST));
1419         fHWScissorSettings.fEnabled = kNo_TriState;
1420         return;
1421     }
1422 }
1423
1424 void GrGpuGL::onClear(const SkIRect* rect, GrColor color, bool canIgnoreRect) {
1425     const GrDrawState& drawState = this->getDrawState();
1426     const GrRenderTarget* rt = drawState.getRenderTarget();
1427     // parent class should never let us get here with no RT
1428     SkASSERT(NULL != rt);
1429
1430     if (canIgnoreRect && this->glCaps().fullClearIsFree()) {
1431         rect = NULL;
1432     }
1433
1434     SkIRect clippedRect;
1435     if (NULL != rect) {
1436         // flushScissor expects rect to be clipped to the target.
1437         clippedRect = *rect;
1438         SkIRect rtRect = SkIRect::MakeWH(rt->width(), rt->height());
1439         if (clippedRect.intersect(rtRect)) {
1440             rect = &clippedRect;
1441         } else {
1442             return;
1443         }
1444     }
1445
1446     this->flushRenderTarget(rect);
1447     GrAutoTRestore<ScissorState> asr(&fScissorState);
1448     fScissorState.fEnabled = (NULL != rect);
1449     if (fScissorState.fEnabled) {
1450         fScissorState.fRect = *rect;
1451     }
1452     this->flushScissor();
1453
1454     GrGLfloat r, g, b, a;
1455     static const GrGLfloat scale255 = 1.f / 255.f;
1456     a = GrColorUnpackA(color) * scale255;
1457     GrGLfloat scaleRGB = scale255;
1458     r = GrColorUnpackR(color) * scaleRGB;
1459     g = GrColorUnpackG(color) * scaleRGB;
1460     b = GrColorUnpackB(color) * scaleRGB;
1461
1462     GL_CALL(ColorMask(GR_GL_TRUE, GR_GL_TRUE, GR_GL_TRUE, GR_GL_TRUE));
1463     fHWWriteToColor = kYes_TriState;
1464     GL_CALL(ClearColor(r, g, b, a));
1465     GL_CALL(Clear(GR_GL_COLOR_BUFFER_BIT));
1466 }
1467
1468 void GrGpuGL::discard(GrRenderTarget* renderTarget) {
1469     if (!this->caps()->discardRenderTargetSupport()) {
1470         return;
1471     }
1472     if (NULL == renderTarget) {
1473         renderTarget = this->drawState()->getRenderTarget();
1474         if (NULL == renderTarget) {
1475             return;
1476         }
1477     }
1478
1479     GrGLRenderTarget* glRT = static_cast<GrGLRenderTarget*>(renderTarget);
1480     if (renderTarget->getUniqueID() != fHWBoundRenderTargetUniqueID) {
1481         fHWBoundRenderTargetUniqueID = SK_InvalidUniqueID;
1482         GL_CALL(BindFramebuffer(GR_GL_FRAMEBUFFER, glRT->renderFBOID()));
1483     }
1484     switch (this->glCaps().invalidateFBType()) {
1485         case GrGLCaps::kNone_InvalidateFBType:
1486             SkFAIL("Should never get here.");
1487             break;
1488         case GrGLCaps::kInvalidate_InvalidateFBType:
1489             if (0 == glRT->renderFBOID()) {
1490                 //  When rendering to the default framebuffer the legal values for attachments
1491                 //  are GL_COLOR, GL_DEPTH, GL_STENCIL, ... rather than the various FBO attachment
1492                 //  types.
1493                 static const GrGLenum attachments[] = { GR_GL_COLOR };
1494                 GL_CALL(InvalidateFramebuffer(GR_GL_FRAMEBUFFER, SK_ARRAY_COUNT(attachments),
1495                         attachments));
1496             } else {
1497                 static const GrGLenum attachments[] = { GR_GL_COLOR_ATTACHMENT0 };
1498                 GL_CALL(InvalidateFramebuffer(GR_GL_FRAMEBUFFER, SK_ARRAY_COUNT(attachments),
1499                         attachments));
1500             }
1501             break;
1502         case GrGLCaps::kDiscard_InvalidateFBType: {
1503             if (0 == glRT->renderFBOID()) {
1504                 //  When rendering to the default framebuffer the legal values for attachments
1505                 //  are GL_COLOR, GL_DEPTH, GL_STENCIL, ... rather than the various FBO attachment
1506                 //  types. See glDiscardFramebuffer() spec.
1507                 static const GrGLenum attachments[] = { GR_GL_COLOR };
1508                 GL_CALL(DiscardFramebuffer(GR_GL_FRAMEBUFFER, SK_ARRAY_COUNT(attachments),
1509                         attachments));
1510             } else {
1511                 static const GrGLenum attachments[] = { GR_GL_COLOR_ATTACHMENT0 };
1512                 GL_CALL(DiscardFramebuffer(GR_GL_FRAMEBUFFER, SK_ARRAY_COUNT(attachments),
1513                         attachments));
1514             }
1515             break;
1516         }
1517     }
1518     renderTarget->flagAsResolved();
1519 }
1520
1521
1522 void GrGpuGL::clearStencil() {
1523     if (NULL == this->getDrawState().getRenderTarget()) {
1524         return;
1525     }
1526
1527     this->flushRenderTarget(&SkIRect::EmptyIRect());
1528
1529     GrAutoTRestore<ScissorState> asr(&fScissorState);
1530     fScissorState.fEnabled = false;
1531     this->flushScissor();
1532
1533     GL_CALL(StencilMask(0xffffffff));
1534     GL_CALL(ClearStencil(0));
1535     GL_CALL(Clear(GR_GL_STENCIL_BUFFER_BIT));
1536     fHWStencilSettings.invalidate();
1537 }
1538
1539 void GrGpuGL::clearStencilClip(const SkIRect& rect, bool insideClip) {
1540     const GrDrawState& drawState = this->getDrawState();
1541     const GrRenderTarget* rt = drawState.getRenderTarget();
1542     SkASSERT(NULL != rt);
1543
1544     // this should only be called internally when we know we have a
1545     // stencil buffer.
1546     SkASSERT(NULL != rt->getStencilBuffer());
1547     GrGLint stencilBitCount =  rt->getStencilBuffer()->bits();
1548 #if 0
1549     SkASSERT(stencilBitCount > 0);
1550     GrGLint clipStencilMask  = (1 << (stencilBitCount - 1));
1551 #else
1552     // we could just clear the clip bit but when we go through
1553     // ANGLE a partial stencil mask will cause clears to be
1554     // turned into draws. Our contract on GrDrawTarget says that
1555     // changing the clip between stencil passes may or may not
1556     // zero the client's clip bits. So we just clear the whole thing.
1557     static const GrGLint clipStencilMask  = ~0;
1558 #endif
1559     GrGLint value;
1560     if (insideClip) {
1561         value = (1 << (stencilBitCount - 1));
1562     } else {
1563         value = 0;
1564     }
1565     this->flushRenderTarget(&SkIRect::EmptyIRect());
1566
1567     GrAutoTRestore<ScissorState> asr(&fScissorState);
1568     fScissorState.fEnabled = true;
1569     fScissorState.fRect = rect;
1570     this->flushScissor();
1571
1572     GL_CALL(StencilMask((uint32_t) clipStencilMask));
1573     GL_CALL(ClearStencil(value));
1574     GL_CALL(Clear(GR_GL_STENCIL_BUFFER_BIT));
1575     fHWStencilSettings.invalidate();
1576 }
1577
1578 bool GrGpuGL::readPixelsWillPayForYFlip(GrRenderTarget* renderTarget,
1579                                         int left, int top,
1580                                         int width, int height,
1581                                         GrPixelConfig config,
1582                                         size_t rowBytes) const {
1583     // If this rendertarget is aready TopLeft, we don't need to flip.
1584     if (kTopLeft_GrSurfaceOrigin == renderTarget->origin()) {
1585         return false;
1586     }
1587
1588     // if GL can do the flip then we'll never pay for it.
1589     if (this->glCaps().packFlipYSupport()) {
1590         return false;
1591     }
1592
1593     // If we have to do memcpy to handle non-trim rowBytes then we
1594     // get the flip for free. Otherwise it costs.
1595     if (this->glCaps().packRowLengthSupport()) {
1596         return true;
1597     }
1598     // If we have to do memcpys to handle rowBytes then y-flip is free
1599     // Note the rowBytes might be tight to the passed in data, but if data
1600     // gets clipped in x to the target the rowBytes will no longer be tight.
1601     if (left >= 0 && (left + width) < renderTarget->width()) {
1602            return 0 == rowBytes ||
1603                   GrBytesPerPixel(config) * width == rowBytes;
1604     } else {
1605         return false;
1606     }
1607 }
1608
1609 bool GrGpuGL::onReadPixels(GrRenderTarget* target,
1610                            int left, int top,
1611                            int width, int height,
1612                            GrPixelConfig config,
1613                            void* buffer,
1614                            size_t rowBytes) {
1615     // We cannot read pixels into a compressed buffer
1616     if (GrPixelConfigIsCompressed(config)) {
1617         return false;
1618     }
1619
1620     GrGLenum format = 0;
1621     GrGLenum type = 0;
1622     bool flipY = kBottomLeft_GrSurfaceOrigin == target->origin();
1623     if (!this->configToGLFormats(config, false, NULL, &format, &type)) {
1624         return false;
1625     }
1626     size_t bpp = GrBytesPerPixel(config);
1627     if (!adjust_pixel_ops_params(target->width(), target->height(), bpp,
1628                                  &left, &top, &width, &height,
1629                                  const_cast<const void**>(&buffer),
1630                                  &rowBytes)) {
1631         return false;
1632     }
1633
1634     // resolve the render target if necessary
1635     GrGLRenderTarget* tgt = static_cast<GrGLRenderTarget*>(target);
1636     GrDrawState::AutoRenderTargetRestore artr;
1637     switch (tgt->getResolveType()) {
1638         case GrGLRenderTarget::kCantResolve_ResolveType:
1639             return false;
1640         case GrGLRenderTarget::kAutoResolves_ResolveType:
1641             artr.set(this->drawState(), target);
1642             this->flushRenderTarget(&SkIRect::EmptyIRect());
1643             break;
1644         case GrGLRenderTarget::kCanResolve_ResolveType:
1645             this->onResolveRenderTarget(tgt);
1646             // we don't track the state of the READ FBO ID.
1647             GL_CALL(BindFramebuffer(GR_GL_READ_FRAMEBUFFER,
1648                                     tgt->textureFBOID()));
1649             break;
1650         default:
1651             SkFAIL("Unknown resolve type");
1652     }
1653
1654     const GrGLIRect& glvp = tgt->getViewport();
1655
1656     // the read rect is viewport-relative
1657     GrGLIRect readRect;
1658     readRect.setRelativeTo(glvp, left, top, width, height, target->origin());
1659
1660     size_t tightRowBytes = bpp * width;
1661     if (0 == rowBytes) {
1662         rowBytes = tightRowBytes;
1663     }
1664     size_t readDstRowBytes = tightRowBytes;
1665     void* readDst = buffer;
1666
1667     // determine if GL can read using the passed rowBytes or if we need
1668     // a scratch buffer.
1669     GrAutoMalloc<32 * sizeof(GrColor)> scratch;
1670     if (rowBytes != tightRowBytes) {
1671         if (this->glCaps().packRowLengthSupport()) {
1672             SkASSERT(!(rowBytes % sizeof(GrColor)));
1673             GL_CALL(PixelStorei(GR_GL_PACK_ROW_LENGTH,
1674                                 static_cast<GrGLint>(rowBytes / sizeof(GrColor))));
1675             readDstRowBytes = rowBytes;
1676         } else {
1677             scratch.reset(tightRowBytes * height);
1678             readDst = scratch.get();
1679         }
1680     }
1681     if (flipY && this->glCaps().packFlipYSupport()) {
1682         GL_CALL(PixelStorei(GR_GL_PACK_REVERSE_ROW_ORDER, 1));
1683     }
1684     GL_CALL(ReadPixels(readRect.fLeft, readRect.fBottom,
1685                        readRect.fWidth, readRect.fHeight,
1686                        format, type, readDst));
1687     if (readDstRowBytes != tightRowBytes) {
1688         SkASSERT(this->glCaps().packRowLengthSupport());
1689         GL_CALL(PixelStorei(GR_GL_PACK_ROW_LENGTH, 0));
1690     }
1691     if (flipY && this->glCaps().packFlipYSupport()) {
1692         GL_CALL(PixelStorei(GR_GL_PACK_REVERSE_ROW_ORDER, 0));
1693         flipY = false;
1694     }
1695
1696     // now reverse the order of the rows, since GL's are bottom-to-top, but our
1697     // API presents top-to-bottom. We must preserve the padding contents. Note
1698     // that the above readPixels did not overwrite the padding.
1699     if (readDst == buffer) {
1700         SkASSERT(rowBytes == readDstRowBytes);
1701         if (flipY) {
1702             scratch.reset(tightRowBytes);
1703             void* tmpRow = scratch.get();
1704             // flip y in-place by rows
1705             const int halfY = height >> 1;
1706             char* top = reinterpret_cast<char*>(buffer);
1707             char* bottom = top + (height - 1) * rowBytes;
1708             for (int y = 0; y < halfY; y++) {
1709                 memcpy(tmpRow, top, tightRowBytes);
1710                 memcpy(top, bottom, tightRowBytes);
1711                 memcpy(bottom, tmpRow, tightRowBytes);
1712                 top += rowBytes;
1713                 bottom -= rowBytes;
1714             }
1715         }
1716     } else {
1717         SkASSERT(readDst != buffer);        SkASSERT(rowBytes != tightRowBytes);
1718         // copy from readDst to buffer while flipping y
1719         // const int halfY = height >> 1;
1720         const char* src = reinterpret_cast<const char*>(readDst);
1721         char* dst = reinterpret_cast<char*>(buffer);
1722         if (flipY) {
1723             dst += (height-1) * rowBytes;
1724         }
1725         for (int y = 0; y < height; y++) {
1726             memcpy(dst, src, tightRowBytes);
1727             src += readDstRowBytes;
1728             if (!flipY) {
1729                 dst += rowBytes;
1730             } else {
1731                 dst -= rowBytes;
1732             }
1733         }
1734     }
1735     return true;
1736 }
1737
1738 void GrGpuGL::flushRenderTarget(const SkIRect* bound) {
1739
1740     GrGLRenderTarget* rt =
1741         static_cast<GrGLRenderTarget*>(this->drawState()->getRenderTarget());
1742     SkASSERT(NULL != rt);
1743
1744     uint32_t rtID = rt->getUniqueID();
1745     if (fHWBoundRenderTargetUniqueID != rtID) {
1746         GL_CALL(BindFramebuffer(GR_GL_FRAMEBUFFER, rt->renderFBOID()));
1747 #ifdef SK_DEBUG
1748         // don't do this check in Chromium -- this is causing
1749         // lots of repeated command buffer flushes when the compositor is
1750         // rendering with Ganesh, which is really slow; even too slow for
1751         // Debug mode.
1752         if (!this->glContext().isChromium()) {
1753             GrGLenum status;
1754             GL_CALL_RET(status, CheckFramebufferStatus(GR_GL_FRAMEBUFFER));
1755             if (status != GR_GL_FRAMEBUFFER_COMPLETE) {
1756                 GrPrintf("GrGpuGL::flushRenderTarget glCheckFramebufferStatus %x\n", status);
1757             }
1758         }
1759 #endif
1760         fHWBoundRenderTargetUniqueID = rtID;
1761         const GrGLIRect& vp = rt->getViewport();
1762         if (fHWViewport != vp) {
1763             vp.pushToGLViewport(this->glInterface());
1764             fHWViewport = vp;
1765         }
1766     }
1767     if (NULL == bound || !bound->isEmpty()) {
1768         rt->flagAsNeedingResolve(bound);
1769     }
1770
1771     GrTexture *texture = rt->asTexture();
1772     if (NULL != texture) {
1773         texture->impl()->dirtyMipMaps(true);
1774     }
1775 }
1776
1777 GrGLenum gPrimitiveType2GLMode[] = {
1778     GR_GL_TRIANGLES,
1779     GR_GL_TRIANGLE_STRIP,
1780     GR_GL_TRIANGLE_FAN,
1781     GR_GL_POINTS,
1782     GR_GL_LINES,
1783     GR_GL_LINE_STRIP
1784 };
1785
1786 #define SWAP_PER_DRAW 0
1787
1788 #if SWAP_PER_DRAW
1789     #if defined(SK_BUILD_FOR_MAC)
1790         #include <AGL/agl.h>
1791     #elif defined(SK_BUILD_FOR_WIN32)
1792         #include <gl/GL.h>
1793         void SwapBuf() {
1794             DWORD procID = GetCurrentProcessId();
1795             HWND hwnd = GetTopWindow(GetDesktopWindow());
1796             while(hwnd) {
1797                 DWORD wndProcID = 0;
1798                 GetWindowThreadProcessId(hwnd, &wndProcID);
1799                 if(wndProcID == procID) {
1800                     SwapBuffers(GetDC(hwnd));
1801                 }
1802                 hwnd = GetNextWindow(hwnd, GW_HWNDNEXT);
1803             }
1804          }
1805     #endif
1806 #endif
1807
1808 void GrGpuGL::onGpuDraw(const DrawInfo& info) {
1809     size_t indexOffsetInBytes;
1810     this->setupGeometry(info, &indexOffsetInBytes);
1811
1812     SkASSERT((size_t)info.primitiveType() < SK_ARRAY_COUNT(gPrimitiveType2GLMode));
1813
1814     if (info.isIndexed()) {
1815         GrGLvoid* indices =
1816             reinterpret_cast<GrGLvoid*>(indexOffsetInBytes + sizeof(uint16_t) * info.startIndex());
1817         // info.startVertex() was accounted for by setupGeometry.
1818         GL_CALL(DrawElements(gPrimitiveType2GLMode[info.primitiveType()],
1819                              info.indexCount(),
1820                              GR_GL_UNSIGNED_SHORT,
1821                              indices));
1822     } else {
1823         // Pass 0 for parameter first. We have to adjust glVertexAttribPointer() to account for
1824         // startVertex in the DrawElements case. So we always rely on setupGeometry to have
1825         // accounted for startVertex.
1826         GL_CALL(DrawArrays(gPrimitiveType2GLMode[info.primitiveType()], 0, info.vertexCount()));
1827     }
1828 #if SWAP_PER_DRAW
1829     glFlush();
1830     #if defined(SK_BUILD_FOR_MAC)
1831         aglSwapBuffers(aglGetCurrentContext());
1832         int set_a_break_pt_here = 9;
1833         aglSwapBuffers(aglGetCurrentContext());
1834     #elif defined(SK_BUILD_FOR_WIN32)
1835         SwapBuf();
1836         int set_a_break_pt_here = 9;
1837         SwapBuf();
1838     #endif
1839 #endif
1840 }
1841
1842 static GrGLenum gr_stencil_op_to_gl_path_rendering_fill_mode(GrStencilOp op) {
1843     switch (op) {
1844         default:
1845             SkFAIL("Unexpected path fill.");
1846             /* fallthrough */;
1847         case kIncClamp_StencilOp:
1848             return GR_GL_COUNT_UP;
1849         case kInvert_StencilOp:
1850             return GR_GL_INVERT;
1851     }
1852 }
1853
1854 void GrGpuGL::onGpuStencilPath(const GrPath* path, SkPath::FillType fill) {
1855     SkASSERT(this->caps()->pathRenderingSupport());
1856
1857     GrGLuint id = static_cast<const GrGLPath*>(path)->pathID();
1858     SkASSERT(NULL != this->drawState()->getRenderTarget());
1859     SkASSERT(NULL != this->drawState()->getRenderTarget()->getStencilBuffer());
1860
1861     flushPathStencilSettings(fill);
1862
1863     // Decide how to manipulate the stencil buffer based on the fill rule.
1864     SkASSERT(!fHWPathStencilSettings.isTwoSided());
1865
1866     GrGLenum fillMode =
1867         gr_stencil_op_to_gl_path_rendering_fill_mode(fHWPathStencilSettings.passOp(GrStencilSettings::kFront_Face));
1868     GrGLint writeMask = fHWPathStencilSettings.writeMask(GrStencilSettings::kFront_Face);
1869     fPathRendering->stencilFillPath(id, fillMode, writeMask);
1870 }
1871
1872 void GrGpuGL::onGpuDrawPath(const GrPath* path, SkPath::FillType fill) {
1873     SkASSERT(this->caps()->pathRenderingSupport());
1874
1875     GrGLuint id = static_cast<const GrGLPath*>(path)->pathID();
1876     SkASSERT(NULL != this->drawState()->getRenderTarget());
1877     SkASSERT(NULL != this->drawState()->getRenderTarget()->getStencilBuffer());
1878     SkASSERT(!fCurrentProgram->hasVertexShader());
1879
1880     flushPathStencilSettings(fill);
1881     const SkStrokeRec& stroke = path->getStroke();
1882
1883     SkPath::FillType nonInvertedFill = SkPath::ConvertToNonInverseFillType(fill);
1884     SkASSERT(!fHWPathStencilSettings.isTwoSided());
1885     GrGLenum fillMode =
1886         gr_stencil_op_to_gl_path_rendering_fill_mode(fHWPathStencilSettings.passOp(GrStencilSettings::kFront_Face));
1887     GrGLint writeMask = fHWPathStencilSettings.writeMask(GrStencilSettings::kFront_Face);
1888
1889     if (nonInvertedFill == fill) {
1890         if (stroke.needToApply()) {
1891             if (SkStrokeRec::kStrokeAndFill_Style == stroke.getStyle()) {
1892                 fPathRendering->stencilFillPath(id, fillMode, writeMask);
1893             }
1894             fPathRendering->stencilThenCoverStrokePath(id, 0xffff, writeMask, GR_GL_BOUNDING_BOX);
1895         } else {
1896             fPathRendering->stencilThenCoverFillPath(id, fillMode, writeMask, GR_GL_BOUNDING_BOX);
1897         }
1898     } else {
1899         if (stroke.isFillStyle() || SkStrokeRec::kStrokeAndFill_Style == stroke.getStyle()) {
1900             fPathRendering->stencilFillPath(id, fillMode, writeMask);
1901         }
1902         if (stroke.needToApply()) {
1903             fPathRendering->stencilStrokePath(id, 0xffff, writeMask);
1904         }
1905
1906         GrDrawState* drawState = this->drawState();
1907         GrDrawState::AutoViewMatrixRestore avmr;
1908         SkRect bounds = SkRect::MakeLTRB(0, 0,
1909                                          SkIntToScalar(drawState->getRenderTarget()->width()),
1910                                          SkIntToScalar(drawState->getRenderTarget()->height()));
1911         SkMatrix vmi;
1912         // mapRect through persp matrix may not be correct
1913         if (!drawState->getViewMatrix().hasPerspective() && drawState->getViewInverse(&vmi)) {
1914             vmi.mapRect(&bounds);
1915             // theoretically could set bloat = 0, instead leave it because of matrix inversion
1916             // precision.
1917             SkScalar bloat = drawState->getViewMatrix().getMaxScale() * SK_ScalarHalf;
1918             bounds.outset(bloat, bloat);
1919         } else {
1920             avmr.setIdentity(drawState);
1921         }
1922
1923         this->drawSimpleRect(bounds);
1924     }
1925 }
1926
1927 void GrGpuGL::onGpuDrawPaths(const GrPathRange* pathRange,
1928                              const uint32_t indices[], int count,
1929                              const float transforms[], PathTransformType transformsType,
1930                              SkPath::FillType fill) {
1931     SkASSERT(this->caps()->pathRenderingSupport());
1932     SkASSERT(NULL != this->drawState()->getRenderTarget());
1933     SkASSERT(NULL != this->drawState()->getRenderTarget()->getStencilBuffer());
1934     SkASSERT(!fCurrentProgram->hasVertexShader());
1935
1936     GrGLuint baseID = static_cast<const GrGLPathRange*>(pathRange)->basePathID();
1937
1938     flushPathStencilSettings(fill);
1939     const SkStrokeRec& stroke = pathRange->getStroke();
1940
1941     SkPath::FillType nonInvertedFill =
1942         SkPath::ConvertToNonInverseFillType(fill);
1943
1944     SkASSERT(!fHWPathStencilSettings.isTwoSided());
1945     GrGLenum fillMode =
1946         gr_stencil_op_to_gl_path_rendering_fill_mode(
1947             fHWPathStencilSettings.passOp(GrStencilSettings::kFront_Face));
1948     GrGLint writeMask =
1949         fHWPathStencilSettings.writeMask(GrStencilSettings::kFront_Face);
1950
1951     if (nonInvertedFill == fill) {
1952         if (stroke.needToApply()) {
1953             if (SkStrokeRec::kStrokeAndFill_Style == stroke.getStyle()) {
1954                 fPathRendering->stencilFillPathInstanced(
1955                                     count, GR_GL_UNSIGNED_INT, indices, baseID, fillMode,
1956                                     writeMask, gXformType2GLType[transformsType],
1957                                     transforms);
1958             }
1959             fPathRendering->stencilThenCoverStrokePathInstanced(
1960                                 count, GR_GL_UNSIGNED_INT, indices, baseID, 0xffff, writeMask,
1961                                 GR_GL_BOUNDING_BOX_OF_BOUNDING_BOXES,
1962                                 gXformType2GLType[transformsType], transforms);
1963         } else {
1964             fPathRendering->stencilThenCoverFillPathInstanced(
1965                                 count, GR_GL_UNSIGNED_INT, indices, baseID, fillMode, writeMask,
1966                                 GR_GL_BOUNDING_BOX_OF_BOUNDING_BOXES,
1967                                 gXformType2GLType[transformsType], transforms);
1968         }
1969     } else {
1970         if (stroke.isFillStyle() || SkStrokeRec::kStrokeAndFill_Style == stroke.getStyle()) {
1971             fPathRendering->stencilFillPathInstanced(
1972                                 count, GR_GL_UNSIGNED_INT, indices, baseID, fillMode,
1973                                 writeMask, gXformType2GLType[transformsType],
1974                                 transforms);
1975         }
1976         if (stroke.needToApply()) {
1977             fPathRendering->stencilStrokePathInstanced(
1978                                 count, GR_GL_UNSIGNED_INT, indices, baseID, 0xffff,
1979                                 writeMask, gXformType2GLType[transformsType],
1980                                 transforms);
1981         }
1982
1983         GrDrawState* drawState = this->drawState();
1984         GrDrawState::AutoViewMatrixRestore avmr;
1985         SkRect bounds = SkRect::MakeLTRB(0, 0,
1986                                          SkIntToScalar(drawState->getRenderTarget()->width()),
1987                                          SkIntToScalar(drawState->getRenderTarget()->height()));
1988         SkMatrix vmi;
1989         // mapRect through persp matrix may not be correct
1990         if (!drawState->getViewMatrix().hasPerspective() && drawState->getViewInverse(&vmi)) {
1991             vmi.mapRect(&bounds);
1992             // theoretically could set bloat = 0, instead leave it because of matrix inversion
1993             // precision.
1994             SkScalar bloat = drawState->getViewMatrix().getMaxScale() * SK_ScalarHalf;
1995             bounds.outset(bloat, bloat);
1996         } else {
1997             avmr.setIdentity(drawState);
1998         }
1999
2000         this->drawSimpleRect(bounds);
2001     }
2002 }
2003
2004 void GrGpuGL::onResolveRenderTarget(GrRenderTarget* target) {
2005     GrGLRenderTarget* rt = static_cast<GrGLRenderTarget*>(target);
2006     if (rt->needsResolve()) {
2007         // Some extensions automatically resolves the texture when it is read.
2008         if (this->glCaps().usesMSAARenderBuffers()) {
2009             SkASSERT(rt->textureFBOID() != rt->renderFBOID());
2010             GL_CALL(BindFramebuffer(GR_GL_READ_FRAMEBUFFER, rt->renderFBOID()));
2011             GL_CALL(BindFramebuffer(GR_GL_DRAW_FRAMEBUFFER, rt->textureFBOID()));
2012             // make sure we go through flushRenderTarget() since we've modified
2013             // the bound DRAW FBO ID.
2014             fHWBoundRenderTargetUniqueID = SK_InvalidUniqueID;
2015             const GrGLIRect& vp = rt->getViewport();
2016             const SkIRect dirtyRect = rt->getResolveRect();
2017             GrGLIRect r;
2018             r.setRelativeTo(vp, dirtyRect.fLeft, dirtyRect.fTop,
2019                             dirtyRect.width(), dirtyRect.height(), target->origin());
2020
2021             GrAutoTRestore<ScissorState> asr;
2022             if (GrGLCaps::kES_Apple_MSFBOType == this->glCaps().msFBOType()) {
2023                 // Apple's extension uses the scissor as the blit bounds.
2024                 asr.reset(&fScissorState);
2025                 fScissorState.fEnabled = true;
2026                 fScissorState.fRect = dirtyRect;
2027                 this->flushScissor();
2028                 GL_CALL(ResolveMultisampleFramebuffer());
2029             } else {
2030                 if (GrGLCaps::kDesktop_EXT_MSFBOType == this->glCaps().msFBOType()) {
2031                     // this respects the scissor during the blit, so disable it.
2032                     asr.reset(&fScissorState);
2033                     fScissorState.fEnabled = false;
2034                     this->flushScissor();
2035                 }
2036                 int right = r.fLeft + r.fWidth;
2037                 int top = r.fBottom + r.fHeight;
2038                 GL_CALL(BlitFramebuffer(r.fLeft, r.fBottom, right, top,
2039                                         r.fLeft, r.fBottom, right, top,
2040                                         GR_GL_COLOR_BUFFER_BIT, GR_GL_NEAREST));
2041             }
2042         }
2043         rt->flagAsResolved();
2044     }
2045 }
2046
2047 namespace {
2048
2049 GrGLenum gr_to_gl_stencil_func(GrStencilFunc basicFunc) {
2050     static const GrGLenum gTable[] = {
2051         GR_GL_ALWAYS,           // kAlways_StencilFunc
2052         GR_GL_NEVER,            // kNever_StencilFunc
2053         GR_GL_GREATER,          // kGreater_StencilFunc
2054         GR_GL_GEQUAL,           // kGEqual_StencilFunc
2055         GR_GL_LESS,             // kLess_StencilFunc
2056         GR_GL_LEQUAL,           // kLEqual_StencilFunc,
2057         GR_GL_EQUAL,            // kEqual_StencilFunc,
2058         GR_GL_NOTEQUAL,         // kNotEqual_StencilFunc,
2059     };
2060     GR_STATIC_ASSERT(SK_ARRAY_COUNT(gTable) == kBasicStencilFuncCount);
2061     GR_STATIC_ASSERT(0 == kAlways_StencilFunc);
2062     GR_STATIC_ASSERT(1 == kNever_StencilFunc);
2063     GR_STATIC_ASSERT(2 == kGreater_StencilFunc);
2064     GR_STATIC_ASSERT(3 == kGEqual_StencilFunc);
2065     GR_STATIC_ASSERT(4 == kLess_StencilFunc);
2066     GR_STATIC_ASSERT(5 == kLEqual_StencilFunc);
2067     GR_STATIC_ASSERT(6 == kEqual_StencilFunc);
2068     GR_STATIC_ASSERT(7 == kNotEqual_StencilFunc);
2069     SkASSERT((unsigned) basicFunc < kBasicStencilFuncCount);
2070
2071     return gTable[basicFunc];
2072 }
2073
2074 GrGLenum gr_to_gl_stencil_op(GrStencilOp op) {
2075     static const GrGLenum gTable[] = {
2076         GR_GL_KEEP,        // kKeep_StencilOp
2077         GR_GL_REPLACE,     // kReplace_StencilOp
2078         GR_GL_INCR_WRAP,   // kIncWrap_StencilOp
2079         GR_GL_INCR,        // kIncClamp_StencilOp
2080         GR_GL_DECR_WRAP,   // kDecWrap_StencilOp
2081         GR_GL_DECR,        // kDecClamp_StencilOp
2082         GR_GL_ZERO,        // kZero_StencilOp
2083         GR_GL_INVERT,      // kInvert_StencilOp
2084     };
2085     GR_STATIC_ASSERT(SK_ARRAY_COUNT(gTable) == kStencilOpCount);
2086     GR_STATIC_ASSERT(0 == kKeep_StencilOp);
2087     GR_STATIC_ASSERT(1 == kReplace_StencilOp);
2088     GR_STATIC_ASSERT(2 == kIncWrap_StencilOp);
2089     GR_STATIC_ASSERT(3 == kIncClamp_StencilOp);
2090     GR_STATIC_ASSERT(4 == kDecWrap_StencilOp);
2091     GR_STATIC_ASSERT(5 == kDecClamp_StencilOp);
2092     GR_STATIC_ASSERT(6 == kZero_StencilOp);
2093     GR_STATIC_ASSERT(7 == kInvert_StencilOp);
2094     SkASSERT((unsigned) op < kStencilOpCount);
2095     return gTable[op];
2096 }
2097
2098 void set_gl_stencil(const GrGLInterface* gl,
2099                     const GrStencilSettings& settings,
2100                     GrGLenum glFace,
2101                     GrStencilSettings::Face grFace) {
2102     GrGLenum glFunc = gr_to_gl_stencil_func(settings.func(grFace));
2103     GrGLenum glFailOp = gr_to_gl_stencil_op(settings.failOp(grFace));
2104     GrGLenum glPassOp = gr_to_gl_stencil_op(settings.passOp(grFace));
2105
2106     GrGLint ref = settings.funcRef(grFace);
2107     GrGLint mask = settings.funcMask(grFace);
2108     GrGLint writeMask = settings.writeMask(grFace);
2109
2110     if (GR_GL_FRONT_AND_BACK == glFace) {
2111         // we call the combined func just in case separate stencil is not
2112         // supported.
2113         GR_GL_CALL(gl, StencilFunc(glFunc, ref, mask));
2114         GR_GL_CALL(gl, StencilMask(writeMask));
2115         GR_GL_CALL(gl, StencilOp(glFailOp, glPassOp, glPassOp));
2116     } else {
2117         GR_GL_CALL(gl, StencilFuncSeparate(glFace, glFunc, ref, mask));
2118         GR_GL_CALL(gl, StencilMaskSeparate(glFace, writeMask));
2119         GR_GL_CALL(gl, StencilOpSeparate(glFace, glFailOp, glPassOp, glPassOp));
2120     }
2121 }
2122 }
2123
2124 void GrGpuGL::flushStencil(DrawType type) {
2125     if (kStencilPath_DrawType != type && fHWStencilSettings != fStencilSettings) {
2126         if (fStencilSettings.isDisabled()) {
2127             if (kNo_TriState != fHWStencilTestEnabled) {
2128                 GL_CALL(Disable(GR_GL_STENCIL_TEST));
2129                 fHWStencilTestEnabled = kNo_TriState;
2130             }
2131         } else {
2132             if (kYes_TriState != fHWStencilTestEnabled) {
2133                 GL_CALL(Enable(GR_GL_STENCIL_TEST));
2134                 fHWStencilTestEnabled = kYes_TriState;
2135             }
2136         }
2137         if (!fStencilSettings.isDisabled()) {
2138             if (this->caps()->twoSidedStencilSupport()) {
2139                 set_gl_stencil(this->glInterface(),
2140                                fStencilSettings,
2141                                GR_GL_FRONT,
2142                                GrStencilSettings::kFront_Face);
2143                 set_gl_stencil(this->glInterface(),
2144                                fStencilSettings,
2145                                GR_GL_BACK,
2146                                GrStencilSettings::kBack_Face);
2147             } else {
2148                 set_gl_stencil(this->glInterface(),
2149                                fStencilSettings,
2150                                GR_GL_FRONT_AND_BACK,
2151                                GrStencilSettings::kFront_Face);
2152             }
2153         }
2154         fHWStencilSettings = fStencilSettings;
2155     }
2156 }
2157
2158 void GrGpuGL::flushAAState(DrawType type) {
2159 // At least some ATI linux drivers will render GL_LINES incorrectly when MSAA state is enabled but
2160 // the target is not multisampled. Single pixel wide lines are rendered thicker than 1 pixel wide.
2161 #if 0
2162     // Replace RT_HAS_MSAA with this definition once this driver bug is no longer a relevant concern
2163     #define RT_HAS_MSAA rt->isMultisampled()
2164 #else
2165     #define RT_HAS_MSAA (rt->isMultisampled() || kDrawLines_DrawType == type)
2166 #endif
2167
2168     const GrRenderTarget* rt = this->getDrawState().getRenderTarget();
2169     if (kGL_GrGLStandard == this->glStandard()) {
2170         if (RT_HAS_MSAA) {
2171             // FIXME: GL_NV_pr doesn't seem to like MSAA disabled. The paths
2172             // convex hulls of each segment appear to get filled.
2173             bool enableMSAA = kStencilPath_DrawType == type ||
2174                               this->getDrawState().isHWAntialiasState();
2175             if (enableMSAA) {
2176                 if (kYes_TriState != fMSAAEnabled) {
2177                     GL_CALL(Enable(GR_GL_MULTISAMPLE));
2178                     fMSAAEnabled = kYes_TriState;
2179                 }
2180             } else {
2181                 if (kNo_TriState != fMSAAEnabled) {
2182                     GL_CALL(Disable(GR_GL_MULTISAMPLE));
2183                     fMSAAEnabled = kNo_TriState;
2184                 }
2185             }
2186         }
2187     }
2188 }
2189
2190 void GrGpuGL::flushPathStencilSettings(SkPath::FillType fill) {
2191     GrStencilSettings pathStencilSettings;
2192     this->getPathStencilSettingsForFillType(fill, &pathStencilSettings);
2193     if (fHWPathStencilSettings != pathStencilSettings) {
2194         // Just the func, ref, and mask is set here. The op and write mask are params to the call
2195         // that draws the path to the SB (glStencilFillPath)
2196         GrGLenum func =
2197             gr_to_gl_stencil_func(pathStencilSettings.func(GrStencilSettings::kFront_Face));
2198         fPathRendering->pathStencilFunc(
2199                             func, pathStencilSettings.funcRef(GrStencilSettings::kFront_Face),
2200                             pathStencilSettings.funcMask(GrStencilSettings::kFront_Face));
2201
2202         fHWPathStencilSettings = pathStencilSettings;
2203     }
2204 }
2205
2206 void GrGpuGL::flushBlend(bool isLines,
2207                          GrBlendCoeff srcCoeff,
2208                          GrBlendCoeff dstCoeff) {
2209     // Any optimization to disable blending should have already been applied and
2210     // tweaked the coeffs to (1, 0).
2211     bool blendOff = kOne_GrBlendCoeff == srcCoeff && kZero_GrBlendCoeff == dstCoeff;
2212     if (blendOff) {
2213         if (kNo_TriState != fHWBlendState.fEnabled) {
2214             GL_CALL(Disable(GR_GL_BLEND));
2215             fHWBlendState.fEnabled = kNo_TriState;
2216         }
2217     } else {
2218         if (kYes_TriState != fHWBlendState.fEnabled) {
2219             GL_CALL(Enable(GR_GL_BLEND));
2220             fHWBlendState.fEnabled = kYes_TriState;
2221         }
2222         if (fHWBlendState.fSrcCoeff != srcCoeff ||
2223             fHWBlendState.fDstCoeff != dstCoeff) {
2224             GL_CALL(BlendFunc(gXfermodeCoeff2Blend[srcCoeff],
2225                               gXfermodeCoeff2Blend[dstCoeff]));
2226             fHWBlendState.fSrcCoeff = srcCoeff;
2227             fHWBlendState.fDstCoeff = dstCoeff;
2228         }
2229         GrColor blendConst = this->getDrawState().getBlendConstant();
2230         if ((BlendCoeffReferencesConstant(srcCoeff) ||
2231              BlendCoeffReferencesConstant(dstCoeff)) &&
2232             (!fHWBlendState.fConstColorValid ||
2233              fHWBlendState.fConstColor != blendConst)) {
2234             GrGLfloat c[4];
2235             GrColorToRGBAFloat(blendConst, c);
2236             GL_CALL(BlendColor(c[0], c[1], c[2], c[3]));
2237             fHWBlendState.fConstColor = blendConst;
2238             fHWBlendState.fConstColorValid = true;
2239         }
2240     }
2241 }
2242
2243 static inline GrGLenum tile_to_gl_wrap(SkShader::TileMode tm) {
2244     static const GrGLenum gWrapModes[] = {
2245         GR_GL_CLAMP_TO_EDGE,
2246         GR_GL_REPEAT,
2247         GR_GL_MIRRORED_REPEAT
2248     };
2249     GR_STATIC_ASSERT(SkShader::kTileModeCount == SK_ARRAY_COUNT(gWrapModes));
2250     GR_STATIC_ASSERT(0 == SkShader::kClamp_TileMode);
2251     GR_STATIC_ASSERT(1 == SkShader::kRepeat_TileMode);
2252     GR_STATIC_ASSERT(2 == SkShader::kMirror_TileMode);
2253     return gWrapModes[tm];
2254 }
2255
2256 void GrGpuGL::bindTexture(int unitIdx, const GrTextureParams& params, GrGLTexture* texture) {
2257     SkASSERT(NULL != texture);
2258
2259     // If we created a rt/tex and rendered to it without using a texture and now we're texturing
2260     // from the rt it will still be the last bound texture, but it needs resolving. So keep this
2261     // out of the "last != next" check.
2262     GrGLRenderTarget* texRT =  static_cast<GrGLRenderTarget*>(texture->asRenderTarget());
2263     if (NULL != texRT) {
2264         this->onResolveRenderTarget(texRT);
2265     }
2266
2267     uint32_t textureID = texture->getUniqueID();
2268     if (fHWBoundTextureUniqueIDs[unitIdx] != textureID) {
2269         this->setTextureUnit(unitIdx);
2270         GL_CALL(BindTexture(GR_GL_TEXTURE_2D, texture->textureID()));
2271         fHWBoundTextureUniqueIDs[unitIdx] = textureID;
2272     }
2273
2274     ResetTimestamp timestamp;
2275     const GrGLTexture::TexParams& oldTexParams = texture->getCachedTexParams(&timestamp);
2276     bool setAll = timestamp < this->getResetTimestamp();
2277     GrGLTexture::TexParams newTexParams;
2278
2279     static GrGLenum glMinFilterModes[] = {
2280         GR_GL_NEAREST,
2281         GR_GL_LINEAR,
2282         GR_GL_LINEAR_MIPMAP_LINEAR
2283     };
2284     static GrGLenum glMagFilterModes[] = {
2285         GR_GL_NEAREST,
2286         GR_GL_LINEAR,
2287         GR_GL_LINEAR
2288     };
2289     GrTextureParams::FilterMode filterMode = params.filterMode();
2290     if (!this->caps()->mipMapSupport() && GrTextureParams::kMipMap_FilterMode == filterMode) {
2291         filterMode = GrTextureParams::kBilerp_FilterMode;
2292     }
2293     newTexParams.fMinFilter = glMinFilterModes[filterMode];
2294     newTexParams.fMagFilter = glMagFilterModes[filterMode];
2295
2296     if (GrTextureParams::kMipMap_FilterMode == filterMode &&
2297         texture->mipMapsAreDirty() && !GrPixelConfigIsCompressed(texture->config())) {
2298         GL_CALL(GenerateMipmap(GR_GL_TEXTURE_2D));
2299         texture->dirtyMipMaps(false);
2300     }
2301
2302     newTexParams.fWrapS = tile_to_gl_wrap(params.getTileModeX());
2303     newTexParams.fWrapT = tile_to_gl_wrap(params.getTileModeY());
2304     memcpy(newTexParams.fSwizzleRGBA,
2305            GrGLShaderBuilder::GetTexParamSwizzle(texture->config(), this->glCaps()),
2306            sizeof(newTexParams.fSwizzleRGBA));
2307     if (setAll || newTexParams.fMagFilter != oldTexParams.fMagFilter) {
2308         this->setTextureUnit(unitIdx);
2309         GL_CALL(TexParameteri(GR_GL_TEXTURE_2D,
2310                               GR_GL_TEXTURE_MAG_FILTER,
2311                               newTexParams.fMagFilter));
2312     }
2313     if (setAll || newTexParams.fMinFilter != oldTexParams.fMinFilter) {
2314         this->setTextureUnit(unitIdx);
2315         GL_CALL(TexParameteri(GR_GL_TEXTURE_2D,
2316                               GR_GL_TEXTURE_MIN_FILTER,
2317                               newTexParams.fMinFilter));
2318     }
2319     if (setAll || newTexParams.fWrapS != oldTexParams.fWrapS) {
2320         this->setTextureUnit(unitIdx);
2321         GL_CALL(TexParameteri(GR_GL_TEXTURE_2D,
2322                               GR_GL_TEXTURE_WRAP_S,
2323                               newTexParams.fWrapS));
2324     }
2325     if (setAll || newTexParams.fWrapT != oldTexParams.fWrapT) {
2326         this->setTextureUnit(unitIdx);
2327         GL_CALL(TexParameteri(GR_GL_TEXTURE_2D,
2328                               GR_GL_TEXTURE_WRAP_T,
2329                               newTexParams.fWrapT));
2330     }
2331     if (this->glCaps().textureSwizzleSupport() &&
2332         (setAll || memcmp(newTexParams.fSwizzleRGBA,
2333                           oldTexParams.fSwizzleRGBA,
2334                           sizeof(newTexParams.fSwizzleRGBA)))) {
2335         this->setTextureUnit(unitIdx);
2336         if (this->glStandard() == kGLES_GrGLStandard) {
2337             // ES3 added swizzle support but not GL_TEXTURE_SWIZZLE_RGBA.
2338             const GrGLenum* swizzle = newTexParams.fSwizzleRGBA;
2339             GL_CALL(TexParameteri(GR_GL_TEXTURE_2D, GR_GL_TEXTURE_SWIZZLE_R, swizzle[0]));
2340             GL_CALL(TexParameteri(GR_GL_TEXTURE_2D, GR_GL_TEXTURE_SWIZZLE_G, swizzle[1]));
2341             GL_CALL(TexParameteri(GR_GL_TEXTURE_2D, GR_GL_TEXTURE_SWIZZLE_B, swizzle[2]));
2342             GL_CALL(TexParameteri(GR_GL_TEXTURE_2D, GR_GL_TEXTURE_SWIZZLE_A, swizzle[3]));
2343         } else {
2344             GR_STATIC_ASSERT(sizeof(newTexParams.fSwizzleRGBA[0]) == sizeof(GrGLint));
2345             const GrGLint* swizzle = reinterpret_cast<const GrGLint*>(newTexParams.fSwizzleRGBA);
2346             GL_CALL(TexParameteriv(GR_GL_TEXTURE_2D, GR_GL_TEXTURE_SWIZZLE_RGBA, swizzle));
2347         }
2348     }
2349     texture->setCachedTexParams(newTexParams, this->getResetTimestamp());
2350 }
2351
2352 void GrGpuGL::setProjectionMatrix(const SkMatrix& matrix,
2353                                   const SkISize& renderTargetSize,
2354                                   GrSurfaceOrigin renderTargetOrigin) {
2355
2356     SkASSERT(this->glCaps().pathRenderingSupport());
2357
2358     if (renderTargetOrigin == fHWProjectionMatrixState.fRenderTargetOrigin &&
2359         renderTargetSize == fHWProjectionMatrixState.fRenderTargetSize &&
2360         matrix.cheapEqualTo(fHWProjectionMatrixState.fViewMatrix)) {
2361         return;
2362     }
2363
2364     fHWProjectionMatrixState.fViewMatrix = matrix;
2365     fHWProjectionMatrixState.fRenderTargetSize = renderTargetSize;
2366     fHWProjectionMatrixState.fRenderTargetOrigin = renderTargetOrigin;
2367
2368     GrGLfloat glMatrix[4 * 4];
2369     fHWProjectionMatrixState.getRTAdjustedGLMatrix<4>(glMatrix);
2370     GL_CALL(MatrixLoadf(GR_GL_PROJECTION, glMatrix));
2371 }
2372
2373 void GrGpuGL::enablePathTexGen(int unitIdx,
2374                                PathTexGenComponents components,
2375                                const GrGLfloat* coefficients) {
2376     SkASSERT(this->glCaps().pathRenderingSupport());
2377     SkASSERT(components >= kS_PathTexGenComponents &&
2378              components <= kSTR_PathTexGenComponents);
2379     SkASSERT(this->glCaps().maxFixedFunctionTextureCoords() >= unitIdx);
2380
2381     if (GR_GL_OBJECT_LINEAR == fHWPathTexGenSettings[unitIdx].fMode &&
2382         components == fHWPathTexGenSettings[unitIdx].fNumComponents &&
2383         !memcmp(coefficients, fHWPathTexGenSettings[unitIdx].fCoefficients,
2384                 3 * components * sizeof(GrGLfloat))) {
2385         return;
2386     }
2387
2388     this->setTextureUnit(unitIdx);
2389
2390     fHWPathTexGenSettings[unitIdx].fNumComponents = components;
2391     fPathRendering->pathTexGen(GR_GL_TEXTURE0 + unitIdx,
2392                                GR_GL_OBJECT_LINEAR,
2393                                components,
2394                                coefficients);
2395
2396     memcpy(fHWPathTexGenSettings[unitIdx].fCoefficients, coefficients,
2397            3 * components * sizeof(GrGLfloat));
2398 }
2399
2400 void GrGpuGL::enablePathTexGen(int unitIdx, PathTexGenComponents components,
2401                                const SkMatrix& matrix) {
2402     GrGLfloat coefficients[3 * 3];
2403     SkASSERT(this->glCaps().pathRenderingSupport());
2404     SkASSERT(components >= kS_PathTexGenComponents &&
2405              components <= kSTR_PathTexGenComponents);
2406
2407     coefficients[0] = SkScalarToFloat(matrix[SkMatrix::kMScaleX]);
2408     coefficients[1] = SkScalarToFloat(matrix[SkMatrix::kMSkewX]);
2409     coefficients[2] = SkScalarToFloat(matrix[SkMatrix::kMTransX]);
2410
2411     if (components >= kST_PathTexGenComponents) {
2412         coefficients[3] = SkScalarToFloat(matrix[SkMatrix::kMSkewY]);
2413         coefficients[4] = SkScalarToFloat(matrix[SkMatrix::kMScaleY]);
2414         coefficients[5] = SkScalarToFloat(matrix[SkMatrix::kMTransY]);
2415     }
2416
2417     if (components >= kSTR_PathTexGenComponents) {
2418         coefficients[6] = SkScalarToFloat(matrix[SkMatrix::kMPersp0]);
2419         coefficients[7] = SkScalarToFloat(matrix[SkMatrix::kMPersp1]);
2420         coefficients[8] = SkScalarToFloat(matrix[SkMatrix::kMPersp2]);
2421     }
2422
2423     enablePathTexGen(unitIdx, components, coefficients);
2424 }
2425
2426 void GrGpuGL::flushPathTexGenSettings(int numUsedTexCoordSets) {
2427     SkASSERT(this->glCaps().pathRenderingSupport());
2428     SkASSERT(this->glCaps().maxFixedFunctionTextureCoords() >= numUsedTexCoordSets);
2429
2430     // Only write the inactive path tex gens, since active path tex gens were
2431     // written when they were enabled.
2432
2433     SkDEBUGCODE(
2434         for (int i = 0; i < numUsedTexCoordSets; i++) {
2435             SkASSERT(0 != fHWPathTexGenSettings[i].fNumComponents);
2436         }
2437     );
2438
2439     for (int i = numUsedTexCoordSets; i < fHWActivePathTexGenSets; i++) {
2440         SkASSERT(0 != fHWPathTexGenSettings[i].fNumComponents);
2441
2442         this->setTextureUnit(i);
2443         fPathRendering->pathTexGen(GR_GL_TEXTURE0 + i, GR_GL_NONE, 0, NULL);
2444         fHWPathTexGenSettings[i].fNumComponents = 0;
2445     }
2446
2447     fHWActivePathTexGenSets = numUsedTexCoordSets;
2448 }
2449
2450 void GrGpuGL::flushMiscFixedFunctionState() {
2451
2452     const GrDrawState& drawState = this->getDrawState();
2453
2454     if (drawState.isDitherState()) {
2455         if (kYes_TriState != fHWDitherEnabled) {
2456             GL_CALL(Enable(GR_GL_DITHER));
2457             fHWDitherEnabled = kYes_TriState;
2458         }
2459     } else {
2460         if (kNo_TriState != fHWDitherEnabled) {
2461             GL_CALL(Disable(GR_GL_DITHER));
2462             fHWDitherEnabled = kNo_TriState;
2463         }
2464     }
2465
2466     if (drawState.isColorWriteDisabled()) {
2467         if (kNo_TriState != fHWWriteToColor) {
2468             GL_CALL(ColorMask(GR_GL_FALSE, GR_GL_FALSE,
2469                               GR_GL_FALSE, GR_GL_FALSE));
2470             fHWWriteToColor = kNo_TriState;
2471         }
2472     } else {
2473         if (kYes_TriState != fHWWriteToColor) {
2474             GL_CALL(ColorMask(GR_GL_TRUE, GR_GL_TRUE, GR_GL_TRUE, GR_GL_TRUE));
2475             fHWWriteToColor = kYes_TriState;
2476         }
2477     }
2478
2479     if (fHWDrawFace != drawState.getDrawFace()) {
2480         switch (this->getDrawState().getDrawFace()) {
2481             case GrDrawState::kCCW_DrawFace:
2482                 GL_CALL(Enable(GR_GL_CULL_FACE));
2483                 GL_CALL(CullFace(GR_GL_BACK));
2484                 break;
2485             case GrDrawState::kCW_DrawFace:
2486                 GL_CALL(Enable(GR_GL_CULL_FACE));
2487                 GL_CALL(CullFace(GR_GL_FRONT));
2488                 break;
2489             case GrDrawState::kBoth_DrawFace:
2490                 GL_CALL(Disable(GR_GL_CULL_FACE));
2491                 break;
2492             default:
2493                 SkFAIL("Unknown draw face.");
2494         }
2495         fHWDrawFace = drawState.getDrawFace();
2496     }
2497 }
2498
2499 bool GrGpuGL::configToGLFormats(GrPixelConfig config,
2500                                 bool getSizedInternalFormat,
2501                                 GrGLenum* internalFormat,
2502                                 GrGLenum* externalFormat,
2503                                 GrGLenum* externalType) {
2504     GrGLenum dontCare;
2505     if (NULL == internalFormat) {
2506         internalFormat = &dontCare;
2507     }
2508     if (NULL == externalFormat) {
2509         externalFormat = &dontCare;
2510     }
2511     if (NULL == externalType) {
2512         externalType = &dontCare;
2513     }
2514
2515     if(!this->glCaps().isConfigTexturable(config)) {
2516         return false;
2517     }
2518
2519     switch (config) {
2520         case kRGBA_8888_GrPixelConfig:
2521             *internalFormat = GR_GL_RGBA;
2522             *externalFormat = GR_GL_RGBA;
2523             if (getSizedInternalFormat) {
2524                 *internalFormat = GR_GL_RGBA8;
2525             } else {
2526                 *internalFormat = GR_GL_RGBA;
2527             }
2528             *externalType = GR_GL_UNSIGNED_BYTE;
2529             break;
2530         case kBGRA_8888_GrPixelConfig:
2531             if (this->glCaps().bgraIsInternalFormat()) {
2532                 if (getSizedInternalFormat) {
2533                     *internalFormat = GR_GL_BGRA8;
2534                 } else {
2535                     *internalFormat = GR_GL_BGRA;
2536                 }
2537             } else {
2538                 if (getSizedInternalFormat) {
2539                     *internalFormat = GR_GL_RGBA8;
2540                 } else {
2541                     *internalFormat = GR_GL_RGBA;
2542                 }
2543             }
2544             *externalFormat = GR_GL_BGRA;
2545             *externalType = GR_GL_UNSIGNED_BYTE;
2546             break;
2547         case kRGB_565_GrPixelConfig:
2548             *internalFormat = GR_GL_RGB;
2549             *externalFormat = GR_GL_RGB;
2550             if (getSizedInternalFormat) {
2551                 if (this->glStandard() == kGL_GrGLStandard) {
2552                     return false;
2553                 } else {
2554                     *internalFormat = GR_GL_RGB565;
2555                 }
2556             } else {
2557                 *internalFormat = GR_GL_RGB;
2558             }
2559             *externalType = GR_GL_UNSIGNED_SHORT_5_6_5;
2560             break;
2561         case kRGBA_4444_GrPixelConfig:
2562             *internalFormat = GR_GL_RGBA;
2563             *externalFormat = GR_GL_RGBA;
2564             if (getSizedInternalFormat) {
2565                 *internalFormat = GR_GL_RGBA4;
2566             } else {
2567                 *internalFormat = GR_GL_RGBA;
2568             }
2569             *externalType = GR_GL_UNSIGNED_SHORT_4_4_4_4;
2570             break;
2571         case kIndex_8_GrPixelConfig:
2572             // no sized/unsized internal format distinction here
2573             *internalFormat = GR_GL_PALETTE8_RGBA8;
2574             break;
2575         case kAlpha_8_GrPixelConfig:
2576             if (this->glCaps().textureRedSupport()) {
2577                 *internalFormat = GR_GL_RED;
2578                 *externalFormat = GR_GL_RED;
2579                 if (getSizedInternalFormat) {
2580                     *internalFormat = GR_GL_R8;
2581                 } else {
2582                     *internalFormat = GR_GL_RED;
2583                 }
2584                 *externalType = GR_GL_UNSIGNED_BYTE;
2585             } else {
2586                 *internalFormat = GR_GL_ALPHA;
2587                 *externalFormat = GR_GL_ALPHA;
2588                 if (getSizedInternalFormat) {
2589                     *internalFormat = GR_GL_ALPHA8;
2590                 } else {
2591                     *internalFormat = GR_GL_ALPHA;
2592                 }
2593                 *externalType = GR_GL_UNSIGNED_BYTE;
2594             }
2595             break;
2596         case kETC1_GrPixelConfig:
2597             *internalFormat = GR_GL_COMPRESSED_RGB8_ETC1;
2598             break;
2599         case kLATC_GrPixelConfig:
2600             switch(this->glCaps().latcAlias()) {
2601                 case GrGLCaps::kLATC_LATCAlias:
2602                     *internalFormat = GR_GL_COMPRESSED_LUMINANCE_LATC1;
2603                     break;
2604                 case GrGLCaps::kRGTC_LATCAlias:
2605                     *internalFormat = GR_GL_COMPRESSED_RED_RGTC1;
2606                     break;
2607                 case GrGLCaps::k3DC_LATCAlias:
2608                     *internalFormat = GR_GL_COMPRESSED_3DC_X;
2609                     break;
2610             }
2611             break;
2612         case kR11_EAC_GrPixelConfig:
2613             *internalFormat = GR_GL_COMPRESSED_R11;
2614             break;
2615
2616         case kASTC_12x12_GrPixelConfig:
2617             *internalFormat = GR_GL_COMPRESSED_RGBA_ASTC_12x12;
2618             break;
2619
2620         case kRGBA_float_GrPixelConfig:
2621             *internalFormat = GR_GL_RGBA32F;
2622             *externalFormat = GR_GL_RGBA;
2623             *externalType = GR_GL_FLOAT;
2624             break;
2625
2626         default:
2627             return false;
2628     }
2629     return true;
2630 }
2631
2632 void GrGpuGL::setTextureUnit(int unit) {
2633     SkASSERT(unit >= 0 && unit < fHWBoundTextureUniqueIDs.count());
2634     if (unit != fHWActiveTextureUnitIdx) {
2635         GL_CALL(ActiveTexture(GR_GL_TEXTURE0 + unit));
2636         fHWActiveTextureUnitIdx = unit;
2637     }
2638 }
2639
2640 void GrGpuGL::setScratchTextureUnit() {
2641     // Bind the last texture unit since it is the least likely to be used by GrGLProgram.
2642     int lastUnitIdx = fHWBoundTextureUniqueIDs.count() - 1;
2643     if (lastUnitIdx != fHWActiveTextureUnitIdx) {
2644         GL_CALL(ActiveTexture(GR_GL_TEXTURE0 + lastUnitIdx));
2645         fHWActiveTextureUnitIdx = lastUnitIdx;
2646     }
2647     // clear out the this field so that if a program does use this unit it will rebind the correct
2648     // texture.
2649     fHWBoundTextureUniqueIDs[lastUnitIdx] = SK_InvalidUniqueID;
2650 }
2651
2652 namespace {
2653 // Determines whether glBlitFramebuffer could be used between src and dst.
2654 inline bool can_blit_framebuffer(const GrSurface* dst,
2655                                  const GrSurface* src,
2656                                  const GrGpuGL* gpu,
2657                                  bool* wouldNeedTempFBO = NULL) {
2658     if (gpu->glCaps().isConfigRenderable(dst->config(), dst->desc().fSampleCnt > 0) &&
2659         gpu->glCaps().isConfigRenderable(src->config(), src->desc().fSampleCnt > 0) &&
2660         gpu->glCaps().usesMSAARenderBuffers()) {
2661         // ES3 doesn't allow framebuffer blits when the src has MSAA and the configs don't match
2662         // or the rects are not the same (not just the same size but have the same edges).
2663         if (GrGLCaps::kES_3_0_MSFBOType == gpu->glCaps().msFBOType() &&
2664             (src->desc().fSampleCnt > 0 || src->config() != dst->config())) {
2665            return false;
2666         }
2667         if (NULL != wouldNeedTempFBO) {
2668             *wouldNeedTempFBO = NULL == dst->asRenderTarget() || NULL == src->asRenderTarget();
2669         }
2670         return true;
2671     } else {
2672         return false;
2673     }
2674 }
2675
2676 inline bool can_copy_texsubimage(const GrSurface* dst,
2677                                  const GrSurface* src,
2678                                  const GrGpuGL* gpu,
2679                                  bool* wouldNeedTempFBO = NULL) {
2680     // Table 3.9 of the ES2 spec indicates the supported formats with CopyTexSubImage
2681     // and BGRA isn't in the spec. There doesn't appear to be any extension that adds it. Perhaps
2682     // many drivers would allow it to work, but ANGLE does not.
2683     if (kGLES_GrGLStandard == gpu->glStandard() && gpu->glCaps().bgraIsInternalFormat() &&
2684         (kBGRA_8888_GrPixelConfig == dst->config() || kBGRA_8888_GrPixelConfig == src->config())) {
2685         return false;
2686     }
2687     const GrGLRenderTarget* dstRT = static_cast<const GrGLRenderTarget*>(dst->asRenderTarget());
2688     // If dst is multisampled (and uses an extension where there is a separate MSAA renderbuffer)
2689     // then we don't want to copy to the texture but to the MSAA buffer.
2690     if (NULL != dstRT && dstRT->renderFBOID() != dstRT->textureFBOID()) {
2691         return false;
2692     }
2693     const GrGLRenderTarget* srcRT = static_cast<const GrGLRenderTarget*>(src->asRenderTarget());
2694     // If the src is multisampled (and uses an extension where there is a separate MSAA
2695     // renderbuffer) then it is an invalid operation to call CopyTexSubImage
2696     if (NULL != srcRT && srcRT->renderFBOID() != srcRT->textureFBOID()) {
2697         return false;
2698     }
2699     if (gpu->glCaps().isConfigRenderable(src->config(), src->desc().fSampleCnt > 0) &&
2700         NULL != dst->asTexture() &&
2701         dst->origin() == src->origin() &&
2702         !GrPixelConfigIsCompressed(src->config())) {
2703         if (NULL != wouldNeedTempFBO) {
2704             *wouldNeedTempFBO = NULL == src->asRenderTarget();
2705         }
2706         return true;
2707     } else {
2708         return false;
2709     }
2710 }
2711
2712 // If a temporary FBO was created, its non-zero ID is returned. The viewport that the copy rect is
2713 // relative to is output.
2714 inline GrGLuint bind_surface_as_fbo(const GrGLInterface* gl,
2715                                     GrSurface* surface,
2716                                     GrGLenum fboTarget,
2717                                     GrGLIRect* viewport) {
2718     GrGLRenderTarget* rt = static_cast<GrGLRenderTarget*>(surface->asRenderTarget());
2719     GrGLuint tempFBOID;
2720     if (NULL == rt) {
2721         SkASSERT(NULL != surface->asTexture());
2722         GrGLuint texID = static_cast<GrGLTexture*>(surface->asTexture())->textureID();
2723         GR_GL_CALL(gl, GenFramebuffers(1, &tempFBOID));
2724         GR_GL_CALL(gl, BindFramebuffer(fboTarget, tempFBOID));
2725         GR_GL_CALL(gl, FramebufferTexture2D(fboTarget,
2726                                             GR_GL_COLOR_ATTACHMENT0,
2727                                             GR_GL_TEXTURE_2D,
2728                                             texID,
2729                                             0));
2730         viewport->fLeft = 0;
2731         viewport->fBottom = 0;
2732         viewport->fWidth = surface->width();
2733         viewport->fHeight = surface->height();
2734     } else {
2735         tempFBOID = 0;
2736         GR_GL_CALL(gl, BindFramebuffer(fboTarget, rt->renderFBOID()));
2737         *viewport = rt->getViewport();
2738     }
2739     return tempFBOID;
2740 }
2741
2742 }
2743
2744 void GrGpuGL::initCopySurfaceDstDesc(const GrSurface* src, GrTextureDesc* desc) {
2745     // Check for format issues with glCopyTexSubImage2D
2746     if (kGLES_GrGLStandard == this->glStandard() && this->glCaps().bgraIsInternalFormat() &&
2747         kBGRA_8888_GrPixelConfig == src->config()) {
2748         // glCopyTexSubImage2D doesn't work with this config. We'll want to make it a render target
2749         // in order to call glBlitFramebuffer or to copy to it by rendering.
2750         INHERITED::initCopySurfaceDstDesc(src, desc);
2751         return;
2752     } else if (NULL == src->asRenderTarget()) {
2753         // We don't want to have to create an FBO just to use glCopyTexSubImage2D. Let the base
2754         // class handle it by rendering.
2755         INHERITED::initCopySurfaceDstDesc(src, desc);
2756         return;
2757     }
2758
2759     const GrGLRenderTarget* srcRT = static_cast<const GrGLRenderTarget*>(src->asRenderTarget());
2760     if (NULL != srcRT && srcRT->renderFBOID() != srcRT->textureFBOID()) {
2761         // It's illegal to call CopyTexSubImage2D on a MSAA renderbuffer.
2762         INHERITED::initCopySurfaceDstDesc(src, desc);
2763     } else {
2764         desc->fConfig = src->config();
2765         desc->fOrigin = src->origin();
2766         desc->fFlags = kNone_GrTextureFlags;
2767     }
2768 }
2769
2770 bool GrGpuGL::onCopySurface(GrSurface* dst,
2771                             GrSurface* src,
2772                             const SkIRect& srcRect,
2773                             const SkIPoint& dstPoint) {
2774     bool inheritedCouldCopy = INHERITED::onCanCopySurface(dst, src, srcRect, dstPoint);
2775     bool copied = false;
2776     bool wouldNeedTempFBO = false;
2777     if (can_copy_texsubimage(dst, src, this, &wouldNeedTempFBO) &&
2778         (!wouldNeedTempFBO || !inheritedCouldCopy)) {
2779         GrGLuint srcFBO;
2780         GrGLIRect srcVP;
2781         srcFBO = bind_surface_as_fbo(this->glInterface(), src, GR_GL_FRAMEBUFFER, &srcVP);
2782         GrGLTexture* dstTex = static_cast<GrGLTexture*>(dst->asTexture());
2783         SkASSERT(NULL != dstTex);
2784         // We modified the bound FBO
2785         fHWBoundRenderTargetUniqueID = SK_InvalidUniqueID;
2786         GrGLIRect srcGLRect;
2787         srcGLRect.setRelativeTo(srcVP,
2788                                 srcRect.fLeft,
2789                                 srcRect.fTop,
2790                                 srcRect.width(),
2791                                 srcRect.height(),
2792                                 src->origin());
2793
2794         this->setScratchTextureUnit();
2795         GL_CALL(BindTexture(GR_GL_TEXTURE_2D, dstTex->textureID()));
2796         GrGLint dstY;
2797         if (kBottomLeft_GrSurfaceOrigin == dst->origin()) {
2798             dstY = dst->height() - (dstPoint.fY + srcGLRect.fHeight);
2799         } else {
2800             dstY = dstPoint.fY;
2801         }
2802         GL_CALL(CopyTexSubImage2D(GR_GL_TEXTURE_2D, 0,
2803                                   dstPoint.fX, dstY,
2804                                   srcGLRect.fLeft, srcGLRect.fBottom,
2805                                   srcGLRect.fWidth, srcGLRect.fHeight));
2806         copied = true;
2807         if (srcFBO) {
2808             GL_CALL(DeleteFramebuffers(1, &srcFBO));
2809         }
2810     } else if (can_blit_framebuffer(dst, src, this, &wouldNeedTempFBO) &&
2811                (!wouldNeedTempFBO || !inheritedCouldCopy)) {
2812         SkIRect dstRect = SkIRect::MakeXYWH(dstPoint.fX, dstPoint.fY,
2813                                             srcRect.width(), srcRect.height());
2814         bool selfOverlap = false;
2815         if (dst->isSameAs(src)) {
2816             selfOverlap = SkIRect::IntersectsNoEmptyCheck(dstRect, srcRect);
2817         }
2818
2819         if (!selfOverlap) {
2820             GrGLuint dstFBO;
2821             GrGLuint srcFBO;
2822             GrGLIRect dstVP;
2823             GrGLIRect srcVP;
2824             dstFBO = bind_surface_as_fbo(this->glInterface(), dst, GR_GL_DRAW_FRAMEBUFFER, &dstVP);
2825             srcFBO = bind_surface_as_fbo(this->glInterface(), src, GR_GL_READ_FRAMEBUFFER, &srcVP);
2826             // We modified the bound FBO
2827             fHWBoundRenderTargetUniqueID = SK_InvalidUniqueID;
2828             GrGLIRect srcGLRect;
2829             GrGLIRect dstGLRect;
2830             srcGLRect.setRelativeTo(srcVP,
2831                                     srcRect.fLeft,
2832                                     srcRect.fTop,
2833                                     srcRect.width(),
2834                                     srcRect.height(),
2835                                     src->origin());
2836             dstGLRect.setRelativeTo(dstVP,
2837                                     dstRect.fLeft,
2838                                     dstRect.fTop,
2839                                     dstRect.width(),
2840                                     dstRect.height(),
2841                                     dst->origin());
2842
2843             GrAutoTRestore<ScissorState> asr;
2844             if (GrGLCaps::kDesktop_EXT_MSFBOType == this->glCaps().msFBOType()) {
2845                 // The EXT version applies the scissor during the blit, so disable it.
2846                 asr.reset(&fScissorState);
2847                 fScissorState.fEnabled = false;
2848                 this->flushScissor();
2849             }
2850             GrGLint srcY0;
2851             GrGLint srcY1;
2852             // Does the blit need to y-mirror or not?
2853             if (src->origin() == dst->origin()) {
2854                 srcY0 = srcGLRect.fBottom;
2855                 srcY1 = srcGLRect.fBottom + srcGLRect.fHeight;
2856             } else {
2857                 srcY0 = srcGLRect.fBottom + srcGLRect.fHeight;
2858                 srcY1 = srcGLRect.fBottom;
2859             }
2860             GL_CALL(BlitFramebuffer(srcGLRect.fLeft,
2861                                     srcY0,
2862                                     srcGLRect.fLeft + srcGLRect.fWidth,
2863                                     srcY1,
2864                                     dstGLRect.fLeft,
2865                                     dstGLRect.fBottom,
2866                                     dstGLRect.fLeft + dstGLRect.fWidth,
2867                                     dstGLRect.fBottom + dstGLRect.fHeight,
2868                                     GR_GL_COLOR_BUFFER_BIT, GR_GL_NEAREST));
2869             if (dstFBO) {
2870                 GL_CALL(DeleteFramebuffers(1, &dstFBO));
2871             }
2872             if (srcFBO) {
2873                 GL_CALL(DeleteFramebuffers(1, &srcFBO));
2874             }
2875             copied = true;
2876         }
2877     }
2878     if (!copied && inheritedCouldCopy) {
2879         copied = INHERITED::onCopySurface(dst, src, srcRect, dstPoint);
2880         SkASSERT(copied);
2881     }
2882     return copied;
2883 }
2884
2885 bool GrGpuGL::onCanCopySurface(GrSurface* dst,
2886                                GrSurface* src,
2887                                const SkIRect& srcRect,
2888                                const SkIPoint& dstPoint) {
2889     // This mirrors the logic in onCopySurface.
2890     if (can_copy_texsubimage(dst, src, this)) {
2891         return true;
2892     }
2893     if (can_blit_framebuffer(dst, src, this)) {
2894         if (dst->isSameAs(src)) {
2895             SkIRect dstRect = SkIRect::MakeXYWH(dstPoint.fX, dstPoint.fY,
2896                                                 srcRect.width(), srcRect.height());
2897             if(!SkIRect::IntersectsNoEmptyCheck(dstRect, srcRect)) {
2898                 return true;
2899             }
2900         } else {
2901             return true;
2902         }
2903     }
2904     return INHERITED::onCanCopySurface(dst, src, srcRect, dstPoint);
2905 }
2906
2907 void GrGpuGL::didAddGpuTraceMarker() {
2908     if (this->caps()->gpuTracingSupport()) {
2909         const GrTraceMarkerSet& markerArray = this->getActiveTraceMarkers();
2910         SkString markerString = markerArray.toStringLast();
2911         GL_CALL(PushGroupMarker(0, markerString.c_str()));
2912     }
2913 }
2914
2915 void GrGpuGL::didRemoveGpuTraceMarker() {
2916     if (this->caps()->gpuTracingSupport()) {
2917         GL_CALL(PopGroupMarker());
2918     }
2919 }
2920 ///////////////////////////////////////////////////////////////////////////////
2921
2922 GrGLAttribArrayState* GrGpuGL::HWGeometryState::bindArrayAndBuffersToDraw(
2923                                                 GrGpuGL* gpu,
2924                                                 const GrGLVertexBuffer* vbuffer,
2925                                                 const GrGLIndexBuffer* ibuffer) {
2926     SkASSERT(NULL != vbuffer);
2927     GrGLAttribArrayState* attribState;
2928
2929     // We use a vertex array if we're on a core profile and the verts are in a VBO.
2930     if (gpu->glCaps().isCoreProfile() && !vbuffer->isCPUBacked()) {
2931         if (NULL == fVBOVertexArray || fVBOVertexArray->wasDestroyed()) {
2932             SkSafeUnref(fVBOVertexArray);
2933             GrGLuint arrayID;
2934             GR_GL_CALL(gpu->glInterface(), GenVertexArrays(1, &arrayID));
2935             int attrCount = gpu->glCaps().maxVertexAttributes();
2936             fVBOVertexArray = SkNEW_ARGS(GrGLVertexArray, (gpu, arrayID, attrCount));
2937         }
2938         attribState = fVBOVertexArray->bindWithIndexBuffer(ibuffer);
2939     } else {
2940         if (NULL != ibuffer) {
2941             this->setIndexBufferIDOnDefaultVertexArray(gpu, ibuffer->bufferID());
2942         } else {
2943             this->setVertexArrayID(gpu, 0);
2944         }
2945         int attrCount = gpu->glCaps().maxVertexAttributes();
2946         if (fDefaultVertexArrayAttribState.count() != attrCount) {
2947             fDefaultVertexArrayAttribState.resize(attrCount);
2948         }
2949         attribState = &fDefaultVertexArrayAttribState;
2950     }
2951     return attribState;
2952 }