2 * Copyright 2011 Google Inc.
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
10 #include "GrGLStencilBuffer.h"
12 #include "GrGLPathRange.h"
13 #include "GrGLPathRendering.h"
14 #include "GrGLShaderBuilder.h"
15 #include "GrTemplates.h"
17 #include "SkStrokeRec.h"
18 #include "SkTemplates.h"
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)
23 #define SKIP_CACHE_CHECK true
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)
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
36 ///////////////////////////////////////////////////////////////////////////////
38 static const GrGLenum gXformType2GLType[] = {
43 GR_GL_TRANSPOSE_AFFINE_2D
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);
53 static const GrGLenum gXfermodeCoeff2Blend[] = {
57 GR_GL_ONE_MINUS_SRC_COLOR,
59 GR_GL_ONE_MINUS_DST_COLOR,
61 GR_GL_ONE_MINUS_SRC_ALPHA,
63 GR_GL_ONE_MINUS_DST_ALPHA,
65 GR_GL_ONE_MINUS_CONSTANT_COLOR,
67 GR_GL_ONE_MINUS_CONSTANT_ALPHA,
69 // extended blend coeffs
71 GR_GL_ONE_MINUS_SRC1_COLOR,
73 GR_GL_ONE_MINUS_SRC1_ALPHA,
76 bool GrGpuGL::BlendCoeffReferencesConstant(GrBlendCoeff coeff) {
77 static const bool gCoeffReferencesBlendConst[] = {
93 // extended blend coeffs
99 return gCoeffReferencesBlendConst[coeff];
100 GR_STATIC_ASSERT(kTotalGrBlendCoeffCount ==
101 SK_ARRAY_COUNT(gCoeffReferencesBlendConst));
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);
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);
123 // assertion for gXfermodeCoeff2Blend have to be in GrGpu scope
124 GR_STATIC_ASSERT(kTotalGrBlendCoeffCount ==
125 SK_ARRAY_COUNT(gXfermodeCoeff2Blend));
128 ///////////////////////////////////////////////////////////////////////////////
130 static bool gPrintStartupSpew;
132 GrGpuGL::GrGpuGL(const GrGLContext& ctx, GrContext* context)
136 SkASSERT(ctx.isInitialized());
137 fCaps.reset(SkRef(ctx.caps()));
139 fHWBoundTextureUniqueIDs.reset(this->glCaps().maxFragmentTextureUnits());
140 fHWPathTexGenSettings.reset(this->glCaps().maxFixedFunctionTextureCoords());
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",
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();
158 GrPrintf(this->glCaps().dump().c_str());
161 fProgramCache = SkNEW_ARGS(ProgramCache, (this));
163 SkASSERT(this->glCaps().maxVertexAttributes() >= GrDrawState::kMaxVertexAttribCnt);
165 fLastSuccessfulStencilFmtIdx = 0;
168 if (this->glCaps().pathRenderingSupport()) {
169 fPathRendering.reset(GrGLPathRendering::Create(glInterface()));
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));
181 delete fProgramCache;
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();
190 ///////////////////////////////////////////////////////////////////////////////
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;
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;
221 bool GrGpuGL::canWriteTexturePixels(const GrTexture* texture, GrPixelConfig srcConfig) const {
222 if (kIndex_8_GrPixelConfig == srcConfig || kIndex_8_GrPixelConfig == texture->config()) {
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
231 if (this->glCaps().isConfigTexturable(kBGRA_8888_GrPixelConfig) &&
232 !this->glCaps().bgraIsInternalFormat() &&
233 kBGRA_8888_GrPixelConfig == srcConfig &&
234 kRGBA_8888_GrPixelConfig == texture->config()) {
244 bool GrGpuGL::fullReadPixelsIsFasterThanPartial() const {
245 return SkToBool(GR_GL_FULL_READPIXELS_FASTER_THAN_PARTIAL);
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));
254 fHWDrawFace = GrDrawState::kInvalid_DrawFace;
255 fHWDitherEnabled = kUnknown_TriState;
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));
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
270 if (this->glCaps().imagingSupport() && !this->glCaps().isCoreProfile()) {
271 GL_CALL(Disable(GR_GL_COLOR_TABLE));
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));
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
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));
289 fHWWriteToColor = kUnknown_TriState;
290 // we only ever use lines in hairline mode
291 GL_CALL(LineWidth(1));
294 if (resetBits & kMSAAEnable_GrGLBackendState) {
295 fMSAAEnabled = kUnknown_TriState;
298 fHWActiveTextureUnitIdx = -1; // invalid
300 if (resetBits & kTextureBinding_GrGLBackendState) {
301 for (int s = 0; s < fHWBoundTextureUniqueIDs.count(); ++s) {
302 fHWBoundTextureUniqueIDs[s] = SK_InvalidUniqueID;
306 if (resetBits & kBlend_GrGLBackendState) {
307 fHWBlendState.invalidate();
310 if (resetBits & kView_GrGLBackendState) {
311 fHWScissorSettings.invalidate();
312 fHWViewport.invalidate();
315 if (resetBits & kStencil_GrGLBackendState) {
316 fHWStencilSettings.invalidate();
317 fHWStencilTestEnabled = kUnknown_TriState;
321 if (resetBits & kVertex_GrGLBackendState) {
322 fHWGeometryState.invalidate();
325 if (resetBits & kRenderTarget_GrGLBackendState) {
326 fHWBoundRenderTargetUniqueID = SK_InvalidUniqueID;
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));
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;
340 fHWActivePathTexGenSets = 0;
342 fHWPathStencilSettings.invalidate();
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));
350 if (this->glCaps().packRowLengthSupport()) {
351 GL_CALL(PixelStorei(GR_GL_PACK_ROW_LENGTH, 0));
353 if (this->glCaps().unpackFlipYSupport()) {
354 GL_CALL(PixelStorei(GR_GL_UNPACK_FLIP_Y, GR_GL_FALSE));
356 if (this->glCaps().packFlipYSupport()) {
357 GL_CALL(PixelStorei(GR_GL_PACK_REVERSE_ROW_ORDER, GR_GL_FALSE));
361 if (resetBits & kProgram_GrGLBackendState) {
363 fSharedGLProgramState.invalidate();
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;
382 GrTexture* GrGpuGL::onWrapBackendTexture(const GrBackendTextureDesc& desc) {
383 if (!this->configToGLFormats(desc.fConfig, false, NULL, NULL, NULL)) {
387 if (0 == desc.fTextureHandle) {
391 int maxSize = this->caps()->maxTextureSize();
392 if (desc.fWidth > maxSize || desc.fHeight > maxSize) {
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;
413 glTexDesc.fOrigin = desc.fOrigin;
416 GrGLTexture* texture = NULL;
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,
428 glTexDesc.fTextureID,
432 texture = SkNEW_ARGS(GrGLTexture, (this, glTexDesc, glRTDesc));
434 texture = SkNEW_ARGS(GrGLTexture, (this, glTexDesc));
436 if (NULL == texture) {
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;
453 glDesc.fOrigin = resolve_origin(desc.fOrigin, true);
456 viewport.fBottom = 0;
457 viewport.fWidth = desc.fWidth;
458 viewport.fHeight = desc.fHeight;
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,
477 tgt->setStencilBuffer(sb);
483 ////////////////////////////////////////////////////////////////////////////////
485 bool GrGpuGL::onWriteTexturePixels(GrTexture* texture,
486 int left, int top, int width, int height,
487 GrPixelConfig config, const void* buffer,
489 if (NULL == buffer) {
492 GrGLTexture* glTex = static_cast<GrGLTexture*>(texture);
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();
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);
512 success = this->uploadTexData(desc, false,
513 left, top, width, height,
514 config, buffer, rowBytes);
518 texture->impl()->dirtyMipMaps(true);
526 bool adjust_pixel_ops_params(int surfaceWidth,
529 int* left, int* top, int* width, int* height,
533 *rowBytes = *width * bpp;
536 SkIRect subRect = SkIRect::MakeXYWH(*left, *top, *width, *height);
537 SkIRect bounds = SkIRect::MakeWH(surfaceWidth, surfaceHeight);
539 if (!subRect.intersect(bounds)) {
542 *data = reinterpret_cast<const void*>(reinterpret_cast<intptr_t>(*data) +
543 (subRect.fTop - *top) * *rowBytes + (subRect.fLeft - *left) * bpp);
545 *left = subRect.fLeft;
547 *width = subRect.width();
548 *height = subRect.height();
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);
556 return CHECK_ALLOC_ERROR(interface);
562 bool GrGpuGL::uploadTexData(const GrGLTexture::Desc& desc,
564 int left, int top, int width, int height,
565 GrPixelConfig dataConfig,
568 SkASSERT(NULL != data || isNewTexture);
570 // If we're uploading compressed data then we should be using uploadCompressedTexData
571 SkASSERT(!GrPixelConfigIsCompressed(dataConfig));
573 size_t bpp = GrBytesPerPixel(dataConfig);
574 if (!adjust_pixel_ops_params(desc.fWidth, desc.fHeight, bpp, &left, &top,
575 &width, &height, &data, &rowBytes)) {
578 size_t trimRowBytes = width * bpp;
580 // in case we need a temporary, trimmed copy of the src pixels
581 GrAutoMalloc<128 * 128> tempStorage;
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
587 bool useTexStorage = false &&
589 this->glCaps().texStorageSupport();
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;
599 GrGLenum internalFormat;
600 GrGLenum externalFormat = 0x0; // suprress warning
601 GrGLenum externalType = 0x0;// suprress warning
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;
614 if (!this->configToGLFormats(dataConfig, useSizedFormat, &internalFormat,
615 &externalFormat, &externalType)) {
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.
625 bool restoreGLRowLength = false;
626 bool swFlipY = false;
627 bool glFlipY = false;
629 if (kBottomLeft_GrSurfaceOrigin == desc.fOrigin) {
630 if (this->glCaps().unpackFlipYSupport()) {
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;
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;
649 src += (height - 1) * rowBytes;
651 char* dst = (char*)tempStorage.reset(trimSize);
652 for (int y = 0; y < height; y++) {
653 memcpy(dst, src, trimRowBytes);
661 // now point data to our copied version
662 data = tempStorage.get();
666 GL_CALL(PixelStorei(GR_GL_UNPACK_FLIP_Y, GR_GL_TRUE));
668 GL_CALL(PixelStorei(GR_GL_UNPACK_ALIGNMENT,
669 static_cast<GrGLint>(GrUnpackAlignment(dataConfig))));
671 bool succeeded = true;
673 0 == left && 0 == top &&
674 desc.fWidth == width && desc.fHeight == height) {
675 CLEAR_ERROR_BEFORE_ALLOC(this->glInterface());
677 // We never resize or change formats of textures.
678 GL_ALLOC_CALL(this->glInterface(),
679 TexStorage2D(GR_GL_TEXTURE_2D,
682 desc.fWidth, desc.fHeight));
684 GL_ALLOC_CALL(this->glInterface(),
685 TexImage2D(GR_GL_TEXTURE_2D,
688 desc.fWidth, desc.fHeight,
690 externalFormat, externalType,
693 GrGLenum error = check_alloc_error(desc, this->glInterface());
694 if (error != GR_GL_NO_ERROR) {
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,
704 externalFormat, externalType,
709 if (swFlipY || glFlipY) {
710 top = desc.fHeight - (top + height);
712 GL_CALL(TexSubImage2D(GR_GL_TEXTURE_2D,
716 externalFormat, externalType, data));
719 if (restoreGLRowLength) {
720 SkASSERT(this->glCaps().unpackRowLengthSupport());
721 GL_CALL(PixelStorei(GR_GL_UNPACK_ROW_LENGTH, 0));
724 GL_CALL(PixelStorei(GR_GL_UNPACK_FLIP_Y, GR_GL_FALSE));
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,
737 int left, int top, int width, int height) {
738 SkASSERT(NULL != data || isNewTexture);
740 // No support for software flip y, yet...
741 SkASSERT(kBottomLeft_GrSurfaceOrigin != desc.fOrigin);
748 SkASSERT(width <= desc.fWidth);
753 height = desc.fHeight;
757 SkASSERT(height <= desc.fHeight);
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);
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)) {
772 CLEAR_ERROR_BEFORE_ALLOC(this->glInterface());
773 GL_ALLOC_CALL(this->glInterface(),
774 CompressedTexImage2D(GR_GL_TEXTURE_2D,
781 GrGLenum error = check_alloc_error(desc, this->glInterface());
782 if (error != GR_GL_NO_ERROR) {
786 // Paletted textures can't be updated.
787 if (GR_GL_PALETTE8_RGBA8 == internalFormat) {
790 GL_CALL(CompressedTexSubImage2D(GR_GL_TEXTURE_2D,
802 static bool renderbuffer_storage_msaa(GrGLContext& ctx,
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,
818 case GrGLCaps::kES_Apple_MSFBOType:
819 GL_ALLOC_CALL(ctx.interface(),
820 RenderbufferStorageMultisampleES2APPLE(GR_GL_RENDERBUFFER,
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,
833 case GrGLCaps::kNone_MSFBOType:
834 SkFAIL("Shouldn't be here if we don't support multisampled renderbuffers.");
837 return (GR_GL_NO_ERROR == CHECK_ALLOC_ERROR(ctx.interface()));;
840 bool GrGpuGL::createRenderTargetObjects(int width, int height,
842 GrGLRenderTarget::Desc* desc) {
843 desc->fMSColorRenderbufferID = 0;
846 desc->fIsWrapped = false;
850 GrGLenum msColorFormat = 0; // suppress warning
852 if (desc->fSampleCnt > 0 && GrGLCaps::kNone_MSFBOType == this->glCaps().msFBOType()) {
856 GL_CALL(GenFramebuffers(1, &desc->fTexFBOID));
857 if (!desc->fTexFBOID) {
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
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(),
880 desc->fRTFBOID = desc->fTexFBOID;
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,
895 GL_CALL(BindFramebuffer(GR_GL_FRAMEBUFFER, desc->fRTFBOID));
896 GL_CALL(FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
897 GR_GL_COLOR_ATTACHMENT0,
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) {
906 fGLContext.caps()->markConfigAsValidColorAttachment(desc->fConfig);
909 GL_CALL(BindFramebuffer(GR_GL_FRAMEBUFFER, desc->fTexFBOID));
911 if (this->glCaps().usesImplicitMSAAResolve() && desc->fSampleCnt > 0) {
912 GL_CALL(FramebufferTexture2DMultisample(GR_GL_FRAMEBUFFER,
913 GR_GL_COLOR_ATTACHMENT0,
915 texID, 0, desc->fSampleCnt));
917 GL_CALL(FramebufferTexture2D(GR_GL_FRAMEBUFFER,
918 GR_GL_COLOR_ATTACHMENT0,
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) {
928 fGLContext.caps()->markConfigAsValidColorAttachment(desc->fConfig);
934 if (desc->fMSColorRenderbufferID) {
935 GL_CALL(DeleteRenderbuffers(1, &desc->fMSColorRenderbufferID));
937 if (desc->fRTFBOID != desc->fTexFBOID) {
938 GL_CALL(DeleteFramebuffers(1, &desc->fRTFBOID));
940 if (desc->fTexFBOID) {
941 GL_CALL(DeleteFramebuffers(1, &desc->fTexFBOID));
946 // good to set a break-point here to know when createTexture fails
947 static GrTexture* return_null_texture() {
948 // SkDEBUGFAIL("null texture");
952 #if 0 && defined(SK_DEBUG)
953 static size_t as_size_t(int x) {
958 GrTexture* GrGpuGL::onCreateTexture(const GrTextureDesc& desc,
962 GrGLTexture::Desc glTexDesc;
963 GrGLRenderTarget::Desc glRTDesc;
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();
972 // If the sample count exceeds the max then we clamp it.
973 glTexDesc.fSampleCnt = SkTMin(desc.fSampleCnt, this->caps()->maxSampleCount());
975 glTexDesc.fFlags = desc.fFlags;
976 glTexDesc.fWidth = desc.fWidth;
977 glTexDesc.fHeight = desc.fHeight;
978 glTexDesc.fConfig = desc.fConfig;
979 glTexDesc.fIsWrapped = false;
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);
988 bool renderTarget = SkToBool(desc.fFlags & kRenderTarget_GrTextureFlagBit);
990 glTexDesc.fOrigin = resolve_origin(desc.fOrigin, renderTarget);
991 glRTDesc.fOrigin = glTexDesc.fOrigin;
993 glRTDesc.fSampleCnt = glTexDesc.fSampleCnt;
994 if (GrGLCaps::kNone_MSFBOType == this->glCaps().msFBOType() &&
996 //GrPrintf("MSAA RT requested but not supported on this platform.");
997 return return_null_texture();
1001 int maxRTSize = this->caps()->maxRenderTargetSize();
1002 if (glTexDesc.fWidth > maxRTSize || glTexDesc.fHeight > maxRTSize) {
1003 return return_null_texture();
1006 int maxSize = this->caps()->maxTextureSize();
1007 if (glTexDesc.fWidth > maxSize || glTexDesc.fHeight > maxSize) {
1008 return return_null_texture();
1012 GL_CALL(GenTextures(1, &glTexDesc.fTextureID));
1014 if (!glTexDesc.fTextureID) {
1015 return return_null_texture();
1018 this->setScratchTextureUnit();
1019 GL_CALL(BindTexture(GR_GL_TEXTURE_2D, glTexDesc.fTextureID));
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));
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();
1059 // unbind the texture from the texture unit before binding it to the frame buffer
1060 GL_CALL(BindTexture(GR_GL_TEXTURE_2D, 0));
1062 if (!this->createRenderTargetObjects(glTexDesc.fWidth,
1064 glTexDesc.fTextureID,
1066 GL_CALL(DeleteTextures(1, &glTexDesc.fTextureID));
1067 return return_null_texture();
1069 tex = SkNEW_ARGS(GrGLTexture, (this, glTexDesc, glRTDesc));
1071 tex = SkNEW_ARGS(GrGLTexture, (this, glTexDesc));
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);
1081 GrTexture* GrGpuGL::onCreateCompressedTexture(const GrTextureDesc& desc,
1082 const void* srcData) {
1084 if(SkToBool(desc.fFlags & kRenderTarget_GrTextureFlagBit)) {
1085 return return_null_texture();
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();
1094 GrGLTexture::Desc glTexDesc;
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;
1103 int maxSize = this->caps()->maxTextureSize();
1104 if (glTexDesc.fWidth > maxSize || glTexDesc.fHeight > maxSize) {
1105 return return_null_texture();
1108 GL_CALL(GenTextures(1, &glTexDesc.fTextureID));
1110 if (!glTexDesc.fTextureID) {
1111 return return_null_texture();
1114 this->setScratchTextureUnit();
1115 GL_CALL(BindTexture(GR_GL_TEXTURE_2D, glTexDesc.fTextureID));
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));
1140 if (!this->uploadCompressedTexData(glTexDesc, srcData)) {
1141 GL_CALL(DeleteTextures(1, &glTexDesc.fTextureID));
1142 return return_null_texture();
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);
1157 const GrGLuint kUnknownBitCount = GrGLStencilBuffer::kUnknownBitCount;
1159 void inline get_stencil_rb_sizes(const GrGLInterface* gl,
1160 GrGLStencilBuffer::Format* format) {
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;
1175 format->fTotalBits = format->fStencilBits;
1181 bool GrGpuGL::createStencilBufferForRenderTarget(GrRenderTarget* rt,
1182 int width, int height) {
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());
1190 int samples = rt->numSamples();
1192 GL_CALL(GenRenderbuffers(1, &sbID));
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.
1211 created = renderbuffer_storage_msaa(fGLContext,
1213 sFmt.fInternalFormat,
1216 GL_ALLOC_CALL(this->glInterface(),
1217 RenderbufferStorage(GR_GL_RENDERBUFFER,
1218 sFmt.fInternalFormat,
1221 (GR_GL_NO_ERROR == check_alloc_error(rt->desc(), this->glInterface()));
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,
1232 if (this->attachStencilBufferToRenderTarget(sb, rt)) {
1233 fLastSuccessfulStencilFmtIdx = sIdx;
1234 sb->transferToCache();
1235 rt->setStencilBuffer(sb);
1238 sb->abandon(); // otherwise we lose sbID
1241 GL_CALL(DeleteRenderbuffers(1, &sbID));
1245 bool GrGpuGL::attachStencilBufferToRenderTarget(GrStencilBuffer* sb, GrRenderTarget* rt) {
1246 GrGLRenderTarget* glrt = (GrGLRenderTarget*) rt;
1248 GrGLuint fbo = glrt->renderFBOID();
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));
1260 GL_CALL_RET(status, CheckFramebufferStatus(GR_GL_FRAMEBUFFER));
1261 SkASSERT(GR_GL_FRAMEBUFFER_COMPLETE == status);
1266 GrGLStencilBuffer* glsb = static_cast<GrGLStencilBuffer*>(sb);
1267 GrGLuint rb = glsb->renderbufferID();
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));
1279 GL_CALL(FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
1280 GR_GL_DEPTH_ATTACHMENT,
1281 GR_GL_RENDERBUFFER, 0));
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));
1298 fGLContext.caps()->markColorConfigAndStencilFormatAsVerified(
1307 ////////////////////////////////////////////////////////////////////////////////
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;
1315 if (this->glCaps().useNonVBOVertexAndIndexDynamicData() && desc.fDynamic) {
1317 GrGLVertexBuffer* vertexBuffer = SkNEW_ARGS(GrGLVertexBuffer, (this, desc));
1318 return vertexBuffer;
1320 GL_CALL(GenBuffers(1, &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,
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);
1335 GrGLVertexBuffer* vertexBuffer = SkNEW_ARGS(GrGLVertexBuffer, (this, desc));
1336 return vertexBuffer;
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;
1348 if (this->glCaps().useNonVBOVertexAndIndexDynamicData() && desc.fDynamic) {
1350 GrIndexBuffer* indexBuffer = SkNEW_ARGS(GrGLIndexBuffer, (this, desc));
1353 GL_CALL(GenBuffers(1, &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,
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);
1368 GrIndexBuffer* indexBuffer = SkNEW_ARGS(GrGLIndexBuffer, (this, desc));
1375 GrPath* GrGpuGL::onCreatePath(const SkPath& inPath, const SkStrokeRec& stroke) {
1376 SkASSERT(this->caps()->pathRenderingSupport());
1377 return SkNEW_ARGS(GrGLPath, (this, inPath, stroke));
1380 GrPathRange* GrGpuGL::onCreatePathRange(size_t size, const SkStrokeRec& stroke) {
1381 SkASSERT(this->caps()->pathRenderingSupport());
1382 return SkNEW_ARGS(GrGLPathRange, (this, size, stroke));
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
1390 const GrDrawState& drawState = this->getDrawState();
1391 const GrGLRenderTarget* rt =
1392 static_cast<const GrGLRenderTarget*>(drawState.getRenderTarget());
1394 SkASSERT(NULL != rt);
1395 const GrGLIRect& vp = rt->getViewport();
1397 scissor.setRelativeTo(vp,
1398 fScissorState.fRect.fLeft,
1399 fScissorState.fRect.fTop,
1400 fScissorState.fRect.width(),
1401 fScissorState.fRect.height(),
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;
1410 if (kYes_TriState != fHWScissorSettings.fEnabled) {
1411 GL_CALL(Enable(GR_GL_SCISSOR_TEST));
1412 fHWScissorSettings.fEnabled = kYes_TriState;
1417 if (kNo_TriState != fHWScissorSettings.fEnabled) {
1418 GL_CALL(Disable(GR_GL_SCISSOR_TEST));
1419 fHWScissorSettings.fEnabled = kNo_TriState;
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);
1430 if (canIgnoreRect && this->glCaps().fullClearIsFree()) {
1434 SkIRect clippedRect;
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;
1446 this->flushRenderTarget(rect);
1447 GrAutoTRestore<ScissorState> asr(&fScissorState);
1448 fScissorState.fEnabled = (NULL != rect);
1449 if (fScissorState.fEnabled) {
1450 fScissorState.fRect = *rect;
1452 this->flushScissor();
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;
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));
1468 void GrGpuGL::discard(GrRenderTarget* renderTarget) {
1469 if (!this->caps()->discardRenderTargetSupport()) {
1472 if (NULL == renderTarget) {
1473 renderTarget = this->drawState()->getRenderTarget();
1474 if (NULL == renderTarget) {
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()));
1484 switch (this->glCaps().invalidateFBType()) {
1485 case GrGLCaps::kNone_InvalidateFBType:
1486 SkFAIL("Should never get here.");
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
1493 static const GrGLenum attachments[] = { GR_GL_COLOR };
1494 GL_CALL(InvalidateFramebuffer(GR_GL_FRAMEBUFFER, SK_ARRAY_COUNT(attachments),
1497 static const GrGLenum attachments[] = { GR_GL_COLOR_ATTACHMENT0 };
1498 GL_CALL(InvalidateFramebuffer(GR_GL_FRAMEBUFFER, SK_ARRAY_COUNT(attachments),
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),
1511 static const GrGLenum attachments[] = { GR_GL_COLOR_ATTACHMENT0 };
1512 GL_CALL(DiscardFramebuffer(GR_GL_FRAMEBUFFER, SK_ARRAY_COUNT(attachments),
1518 renderTarget->flagAsResolved();
1522 void GrGpuGL::clearStencil() {
1523 if (NULL == this->getDrawState().getRenderTarget()) {
1527 this->flushRenderTarget(&SkIRect::EmptyIRect());
1529 GrAutoTRestore<ScissorState> asr(&fScissorState);
1530 fScissorState.fEnabled = false;
1531 this->flushScissor();
1533 GL_CALL(StencilMask(0xffffffff));
1534 GL_CALL(ClearStencil(0));
1535 GL_CALL(Clear(GR_GL_STENCIL_BUFFER_BIT));
1536 fHWStencilSettings.invalidate();
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);
1544 // this should only be called internally when we know we have a
1546 SkASSERT(NULL != rt->getStencilBuffer());
1547 GrGLint stencilBitCount = rt->getStencilBuffer()->bits();
1549 SkASSERT(stencilBitCount > 0);
1550 GrGLint clipStencilMask = (1 << (stencilBitCount - 1));
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;
1561 value = (1 << (stencilBitCount - 1));
1565 this->flushRenderTarget(&SkIRect::EmptyIRect());
1567 GrAutoTRestore<ScissorState> asr(&fScissorState);
1568 fScissorState.fEnabled = true;
1569 fScissorState.fRect = rect;
1570 this->flushScissor();
1572 GL_CALL(StencilMask((uint32_t) clipStencilMask));
1573 GL_CALL(ClearStencil(value));
1574 GL_CALL(Clear(GR_GL_STENCIL_BUFFER_BIT));
1575 fHWStencilSettings.invalidate();
1578 bool GrGpuGL::readPixelsWillPayForYFlip(GrRenderTarget* renderTarget,
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()) {
1588 // if GL can do the flip then we'll never pay for it.
1589 if (this->glCaps().packFlipYSupport()) {
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()) {
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;
1609 bool GrGpuGL::onReadPixels(GrRenderTarget* target,
1611 int width, int height,
1612 GrPixelConfig config,
1615 // We cannot read pixels into a compressed buffer
1616 if (GrPixelConfigIsCompressed(config)) {
1620 GrGLenum format = 0;
1622 bool flipY = kBottomLeft_GrSurfaceOrigin == target->origin();
1623 if (!this->configToGLFormats(config, false, NULL, &format, &type)) {
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),
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:
1640 case GrGLRenderTarget::kAutoResolves_ResolveType:
1641 artr.set(this->drawState(), target);
1642 this->flushRenderTarget(&SkIRect::EmptyIRect());
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()));
1651 SkFAIL("Unknown resolve type");
1654 const GrGLIRect& glvp = tgt->getViewport();
1656 // the read rect is viewport-relative
1658 readRect.setRelativeTo(glvp, left, top, width, height, target->origin());
1660 size_t tightRowBytes = bpp * width;
1661 if (0 == rowBytes) {
1662 rowBytes = tightRowBytes;
1664 size_t readDstRowBytes = tightRowBytes;
1665 void* readDst = buffer;
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;
1677 scratch.reset(tightRowBytes * height);
1678 readDst = scratch.get();
1681 if (flipY && this->glCaps().packFlipYSupport()) {
1682 GL_CALL(PixelStorei(GR_GL_PACK_REVERSE_ROW_ORDER, 1));
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));
1691 if (flipY && this->glCaps().packFlipYSupport()) {
1692 GL_CALL(PixelStorei(GR_GL_PACK_REVERSE_ROW_ORDER, 0));
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);
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);
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);
1723 dst += (height-1) * rowBytes;
1725 for (int y = 0; y < height; y++) {
1726 memcpy(dst, src, tightRowBytes);
1727 src += readDstRowBytes;
1738 void GrGpuGL::flushRenderTarget(const SkIRect* bound) {
1740 GrGLRenderTarget* rt =
1741 static_cast<GrGLRenderTarget*>(this->drawState()->getRenderTarget());
1742 SkASSERT(NULL != rt);
1744 uint32_t rtID = rt->getUniqueID();
1745 if (fHWBoundRenderTargetUniqueID != rtID) {
1746 GL_CALL(BindFramebuffer(GR_GL_FRAMEBUFFER, rt->renderFBOID()));
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
1752 if (!this->glContext().isChromium()) {
1754 GL_CALL_RET(status, CheckFramebufferStatus(GR_GL_FRAMEBUFFER));
1755 if (status != GR_GL_FRAMEBUFFER_COMPLETE) {
1756 GrPrintf("GrGpuGL::flushRenderTarget glCheckFramebufferStatus %x\n", status);
1760 fHWBoundRenderTargetUniqueID = rtID;
1761 const GrGLIRect& vp = rt->getViewport();
1762 if (fHWViewport != vp) {
1763 vp.pushToGLViewport(this->glInterface());
1767 if (NULL == bound || !bound->isEmpty()) {
1768 rt->flagAsNeedingResolve(bound);
1771 GrTexture *texture = rt->asTexture();
1772 if (NULL != texture) {
1773 texture->impl()->dirtyMipMaps(true);
1777 GrGLenum gPrimitiveType2GLMode[] = {
1779 GR_GL_TRIANGLE_STRIP,
1786 #define SWAP_PER_DRAW 0
1789 #if defined(SK_BUILD_FOR_MAC)
1790 #include <AGL/agl.h>
1791 #elif defined(SK_BUILD_FOR_WIN32)
1794 DWORD procID = GetCurrentProcessId();
1795 HWND hwnd = GetTopWindow(GetDesktopWindow());
1797 DWORD wndProcID = 0;
1798 GetWindowThreadProcessId(hwnd, &wndProcID);
1799 if(wndProcID == procID) {
1800 SwapBuffers(GetDC(hwnd));
1802 hwnd = GetNextWindow(hwnd, GW_HWNDNEXT);
1808 void GrGpuGL::onGpuDraw(const DrawInfo& info) {
1809 size_t indexOffsetInBytes;
1810 this->setupGeometry(info, &indexOffsetInBytes);
1812 SkASSERT((size_t)info.primitiveType() < SK_ARRAY_COUNT(gPrimitiveType2GLMode));
1814 if (info.isIndexed()) {
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()],
1820 GR_GL_UNSIGNED_SHORT,
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()));
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)
1836 int set_a_break_pt_here = 9;
1842 static GrGLenum gr_stencil_op_to_gl_path_rendering_fill_mode(GrStencilOp op) {
1845 SkFAIL("Unexpected path fill.");
1847 case kIncClamp_StencilOp:
1848 return GR_GL_COUNT_UP;
1849 case kInvert_StencilOp:
1850 return GR_GL_INVERT;
1854 void GrGpuGL::onGpuStencilPath(const GrPath* path, SkPath::FillType fill) {
1855 SkASSERT(this->caps()->pathRenderingSupport());
1857 GrGLuint id = static_cast<const GrGLPath*>(path)->pathID();
1858 SkASSERT(NULL != this->drawState()->getRenderTarget());
1859 SkASSERT(NULL != this->drawState()->getRenderTarget()->getStencilBuffer());
1861 flushPathStencilSettings(fill);
1863 // Decide how to manipulate the stencil buffer based on the fill rule.
1864 SkASSERT(!fHWPathStencilSettings.isTwoSided());
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);
1872 void GrGpuGL::onGpuDrawPath(const GrPath* path, SkPath::FillType fill) {
1873 SkASSERT(this->caps()->pathRenderingSupport());
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());
1880 flushPathStencilSettings(fill);
1881 const SkStrokeRec& stroke = path->getStroke();
1883 SkPath::FillType nonInvertedFill = SkPath::ConvertToNonInverseFillType(fill);
1884 SkASSERT(!fHWPathStencilSettings.isTwoSided());
1886 gr_stencil_op_to_gl_path_rendering_fill_mode(fHWPathStencilSettings.passOp(GrStencilSettings::kFront_Face));
1887 GrGLint writeMask = fHWPathStencilSettings.writeMask(GrStencilSettings::kFront_Face);
1889 if (nonInvertedFill == fill) {
1890 if (stroke.needToApply()) {
1891 if (SkStrokeRec::kStrokeAndFill_Style == stroke.getStyle()) {
1892 fPathRendering->stencilFillPath(id, fillMode, writeMask);
1894 fPathRendering->stencilThenCoverStrokePath(id, 0xffff, writeMask, GR_GL_BOUNDING_BOX);
1896 fPathRendering->stencilThenCoverFillPath(id, fillMode, writeMask, GR_GL_BOUNDING_BOX);
1899 if (stroke.isFillStyle() || SkStrokeRec::kStrokeAndFill_Style == stroke.getStyle()) {
1900 fPathRendering->stencilFillPath(id, fillMode, writeMask);
1902 if (stroke.needToApply()) {
1903 fPathRendering->stencilStrokePath(id, 0xffff, writeMask);
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()));
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
1917 SkScalar bloat = drawState->getViewMatrix().getMaxScale() * SK_ScalarHalf;
1918 bounds.outset(bloat, bloat);
1920 avmr.setIdentity(drawState);
1923 this->drawSimpleRect(bounds);
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());
1936 GrGLuint baseID = static_cast<const GrGLPathRange*>(pathRange)->basePathID();
1938 flushPathStencilSettings(fill);
1939 const SkStrokeRec& stroke = pathRange->getStroke();
1941 SkPath::FillType nonInvertedFill =
1942 SkPath::ConvertToNonInverseFillType(fill);
1944 SkASSERT(!fHWPathStencilSettings.isTwoSided());
1946 gr_stencil_op_to_gl_path_rendering_fill_mode(
1947 fHWPathStencilSettings.passOp(GrStencilSettings::kFront_Face));
1949 fHWPathStencilSettings.writeMask(GrStencilSettings::kFront_Face);
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],
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);
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);
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],
1976 if (stroke.needToApply()) {
1977 fPathRendering->stencilStrokePathInstanced(
1978 count, GR_GL_UNSIGNED_INT, indices, baseID, 0xffff,
1979 writeMask, gXformType2GLType[transformsType],
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()));
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
1994 SkScalar bloat = drawState->getViewMatrix().getMaxScale() * SK_ScalarHalf;
1995 bounds.outset(bloat, bloat);
1997 avmr.setIdentity(drawState);
2000 this->drawSimpleRect(bounds);
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();
2018 r.setRelativeTo(vp, dirtyRect.fLeft, dirtyRect.fTop,
2019 dirtyRect.width(), dirtyRect.height(), target->origin());
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());
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();
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));
2043 rt->flagAsResolved();
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,
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);
2071 return gTable[basicFunc];
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
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);
2098 void set_gl_stencil(const GrGLInterface* gl,
2099 const GrStencilSettings& settings,
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));
2106 GrGLint ref = settings.funcRef(grFace);
2107 GrGLint mask = settings.funcMask(grFace);
2108 GrGLint writeMask = settings.writeMask(grFace);
2110 if (GR_GL_FRONT_AND_BACK == glFace) {
2111 // we call the combined func just in case separate stencil is not
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));
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));
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;
2132 if (kYes_TriState != fHWStencilTestEnabled) {
2133 GL_CALL(Enable(GR_GL_STENCIL_TEST));
2134 fHWStencilTestEnabled = kYes_TriState;
2137 if (!fStencilSettings.isDisabled()) {
2138 if (this->caps()->twoSidedStencilSupport()) {
2139 set_gl_stencil(this->glInterface(),
2142 GrStencilSettings::kFront_Face);
2143 set_gl_stencil(this->glInterface(),
2146 GrStencilSettings::kBack_Face);
2148 set_gl_stencil(this->glInterface(),
2150 GR_GL_FRONT_AND_BACK,
2151 GrStencilSettings::kFront_Face);
2154 fHWStencilSettings = fStencilSettings;
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.
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()
2165 #define RT_HAS_MSAA (rt->isMultisampled() || kDrawLines_DrawType == type)
2168 const GrRenderTarget* rt = this->getDrawState().getRenderTarget();
2169 if (kGL_GrGLStandard == this->glStandard()) {
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();
2176 if (kYes_TriState != fMSAAEnabled) {
2177 GL_CALL(Enable(GR_GL_MULTISAMPLE));
2178 fMSAAEnabled = kYes_TriState;
2181 if (kNo_TriState != fMSAAEnabled) {
2182 GL_CALL(Disable(GR_GL_MULTISAMPLE));
2183 fMSAAEnabled = kNo_TriState;
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)
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));
2202 fHWPathStencilSettings = pathStencilSettings;
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;
2213 if (kNo_TriState != fHWBlendState.fEnabled) {
2214 GL_CALL(Disable(GR_GL_BLEND));
2215 fHWBlendState.fEnabled = kNo_TriState;
2218 if (kYes_TriState != fHWBlendState.fEnabled) {
2219 GL_CALL(Enable(GR_GL_BLEND));
2220 fHWBlendState.fEnabled = kYes_TriState;
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;
2229 GrColor blendConst = this->getDrawState().getBlendConstant();
2230 if ((BlendCoeffReferencesConstant(srcCoeff) ||
2231 BlendCoeffReferencesConstant(dstCoeff)) &&
2232 (!fHWBlendState.fConstColorValid ||
2233 fHWBlendState.fConstColor != blendConst)) {
2235 GrColorToRGBAFloat(blendConst, c);
2236 GL_CALL(BlendColor(c[0], c[1], c[2], c[3]));
2237 fHWBlendState.fConstColor = blendConst;
2238 fHWBlendState.fConstColorValid = true;
2243 static inline GrGLenum tile_to_gl_wrap(SkShader::TileMode tm) {
2244 static const GrGLenum gWrapModes[] = {
2245 GR_GL_CLAMP_TO_EDGE,
2247 GR_GL_MIRRORED_REPEAT
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];
2256 void GrGpuGL::bindTexture(int unitIdx, const GrTextureParams& params, GrGLTexture* texture) {
2257 SkASSERT(NULL != texture);
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);
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;
2274 ResetTimestamp timestamp;
2275 const GrGLTexture::TexParams& oldTexParams = texture->getCachedTexParams(×tamp);
2276 bool setAll = timestamp < this->getResetTimestamp();
2277 GrGLTexture::TexParams newTexParams;
2279 static GrGLenum glMinFilterModes[] = {
2282 GR_GL_LINEAR_MIPMAP_LINEAR
2284 static GrGLenum glMagFilterModes[] = {
2289 GrTextureParams::FilterMode filterMode = params.filterMode();
2290 if (!this->caps()->mipMapSupport() && GrTextureParams::kMipMap_FilterMode == filterMode) {
2291 filterMode = GrTextureParams::kBilerp_FilterMode;
2293 newTexParams.fMinFilter = glMinFilterModes[filterMode];
2294 newTexParams.fMagFilter = glMagFilterModes[filterMode];
2296 if (GrTextureParams::kMipMap_FilterMode == filterMode &&
2297 texture->mipMapsAreDirty() && !GrPixelConfigIsCompressed(texture->config())) {
2298 GL_CALL(GenerateMipmap(GR_GL_TEXTURE_2D));
2299 texture->dirtyMipMaps(false);
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));
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));
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));
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));
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]));
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));
2349 texture->setCachedTexParams(newTexParams, this->getResetTimestamp());
2352 void GrGpuGL::setProjectionMatrix(const SkMatrix& matrix,
2353 const SkISize& renderTargetSize,
2354 GrSurfaceOrigin renderTargetOrigin) {
2356 SkASSERT(this->glCaps().pathRenderingSupport());
2358 if (renderTargetOrigin == fHWProjectionMatrixState.fRenderTargetOrigin &&
2359 renderTargetSize == fHWProjectionMatrixState.fRenderTargetSize &&
2360 matrix.cheapEqualTo(fHWProjectionMatrixState.fViewMatrix)) {
2364 fHWProjectionMatrixState.fViewMatrix = matrix;
2365 fHWProjectionMatrixState.fRenderTargetSize = renderTargetSize;
2366 fHWProjectionMatrixState.fRenderTargetOrigin = renderTargetOrigin;
2368 GrGLfloat glMatrix[4 * 4];
2369 fHWProjectionMatrixState.getRTAdjustedGLMatrix<4>(glMatrix);
2370 GL_CALL(MatrixLoadf(GR_GL_PROJECTION, glMatrix));
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);
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))) {
2388 this->setTextureUnit(unitIdx);
2390 fHWPathTexGenSettings[unitIdx].fNumComponents = components;
2391 fPathRendering->pathTexGen(GR_GL_TEXTURE0 + unitIdx,
2392 GR_GL_OBJECT_LINEAR,
2396 memcpy(fHWPathTexGenSettings[unitIdx].fCoefficients, coefficients,
2397 3 * components * sizeof(GrGLfloat));
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);
2407 coefficients[0] = SkScalarToFloat(matrix[SkMatrix::kMScaleX]);
2408 coefficients[1] = SkScalarToFloat(matrix[SkMatrix::kMSkewX]);
2409 coefficients[2] = SkScalarToFloat(matrix[SkMatrix::kMTransX]);
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]);
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]);
2423 enablePathTexGen(unitIdx, components, coefficients);
2426 void GrGpuGL::flushPathTexGenSettings(int numUsedTexCoordSets) {
2427 SkASSERT(this->glCaps().pathRenderingSupport());
2428 SkASSERT(this->glCaps().maxFixedFunctionTextureCoords() >= numUsedTexCoordSets);
2430 // Only write the inactive path tex gens, since active path tex gens were
2431 // written when they were enabled.
2434 for (int i = 0; i < numUsedTexCoordSets; i++) {
2435 SkASSERT(0 != fHWPathTexGenSettings[i].fNumComponents);
2439 for (int i = numUsedTexCoordSets; i < fHWActivePathTexGenSets; i++) {
2440 SkASSERT(0 != fHWPathTexGenSettings[i].fNumComponents);
2442 this->setTextureUnit(i);
2443 fPathRendering->pathTexGen(GR_GL_TEXTURE0 + i, GR_GL_NONE, 0, NULL);
2444 fHWPathTexGenSettings[i].fNumComponents = 0;
2447 fHWActivePathTexGenSets = numUsedTexCoordSets;
2450 void GrGpuGL::flushMiscFixedFunctionState() {
2452 const GrDrawState& drawState = this->getDrawState();
2454 if (drawState.isDitherState()) {
2455 if (kYes_TriState != fHWDitherEnabled) {
2456 GL_CALL(Enable(GR_GL_DITHER));
2457 fHWDitherEnabled = kYes_TriState;
2460 if (kNo_TriState != fHWDitherEnabled) {
2461 GL_CALL(Disable(GR_GL_DITHER));
2462 fHWDitherEnabled = kNo_TriState;
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;
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;
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));
2485 case GrDrawState::kCW_DrawFace:
2486 GL_CALL(Enable(GR_GL_CULL_FACE));
2487 GL_CALL(CullFace(GR_GL_FRONT));
2489 case GrDrawState::kBoth_DrawFace:
2490 GL_CALL(Disable(GR_GL_CULL_FACE));
2493 SkFAIL("Unknown draw face.");
2495 fHWDrawFace = drawState.getDrawFace();
2499 bool GrGpuGL::configToGLFormats(GrPixelConfig config,
2500 bool getSizedInternalFormat,
2501 GrGLenum* internalFormat,
2502 GrGLenum* externalFormat,
2503 GrGLenum* externalType) {
2505 if (NULL == internalFormat) {
2506 internalFormat = &dontCare;
2508 if (NULL == externalFormat) {
2509 externalFormat = &dontCare;
2511 if (NULL == externalType) {
2512 externalType = &dontCare;
2515 if(!this->glCaps().isConfigTexturable(config)) {
2520 case kRGBA_8888_GrPixelConfig:
2521 *internalFormat = GR_GL_RGBA;
2522 *externalFormat = GR_GL_RGBA;
2523 if (getSizedInternalFormat) {
2524 *internalFormat = GR_GL_RGBA8;
2526 *internalFormat = GR_GL_RGBA;
2528 *externalType = GR_GL_UNSIGNED_BYTE;
2530 case kBGRA_8888_GrPixelConfig:
2531 if (this->glCaps().bgraIsInternalFormat()) {
2532 if (getSizedInternalFormat) {
2533 *internalFormat = GR_GL_BGRA8;
2535 *internalFormat = GR_GL_BGRA;
2538 if (getSizedInternalFormat) {
2539 *internalFormat = GR_GL_RGBA8;
2541 *internalFormat = GR_GL_RGBA;
2544 *externalFormat = GR_GL_BGRA;
2545 *externalType = GR_GL_UNSIGNED_BYTE;
2547 case kRGB_565_GrPixelConfig:
2548 *internalFormat = GR_GL_RGB;
2549 *externalFormat = GR_GL_RGB;
2550 if (getSizedInternalFormat) {
2551 if (this->glStandard() == kGL_GrGLStandard) {
2554 *internalFormat = GR_GL_RGB565;
2557 *internalFormat = GR_GL_RGB;
2559 *externalType = GR_GL_UNSIGNED_SHORT_5_6_5;
2561 case kRGBA_4444_GrPixelConfig:
2562 *internalFormat = GR_GL_RGBA;
2563 *externalFormat = GR_GL_RGBA;
2564 if (getSizedInternalFormat) {
2565 *internalFormat = GR_GL_RGBA4;
2567 *internalFormat = GR_GL_RGBA;
2569 *externalType = GR_GL_UNSIGNED_SHORT_4_4_4_4;
2571 case kIndex_8_GrPixelConfig:
2572 // no sized/unsized internal format distinction here
2573 *internalFormat = GR_GL_PALETTE8_RGBA8;
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;
2582 *internalFormat = GR_GL_RED;
2584 *externalType = GR_GL_UNSIGNED_BYTE;
2586 *internalFormat = GR_GL_ALPHA;
2587 *externalFormat = GR_GL_ALPHA;
2588 if (getSizedInternalFormat) {
2589 *internalFormat = GR_GL_ALPHA8;
2591 *internalFormat = GR_GL_ALPHA;
2593 *externalType = GR_GL_UNSIGNED_BYTE;
2596 case kETC1_GrPixelConfig:
2597 *internalFormat = GR_GL_COMPRESSED_RGB8_ETC1;
2599 case kLATC_GrPixelConfig:
2600 switch(this->glCaps().latcAlias()) {
2601 case GrGLCaps::kLATC_LATCAlias:
2602 *internalFormat = GR_GL_COMPRESSED_LUMINANCE_LATC1;
2604 case GrGLCaps::kRGTC_LATCAlias:
2605 *internalFormat = GR_GL_COMPRESSED_RED_RGTC1;
2607 case GrGLCaps::k3DC_LATCAlias:
2608 *internalFormat = GR_GL_COMPRESSED_3DC_X;
2612 case kR11_EAC_GrPixelConfig:
2613 *internalFormat = GR_GL_COMPRESSED_R11;
2616 case kASTC_12x12_GrPixelConfig:
2617 *internalFormat = GR_GL_COMPRESSED_RGBA_ASTC_12x12;
2620 case kRGBA_float_GrPixelConfig:
2621 *internalFormat = GR_GL_RGBA32F;
2622 *externalFormat = GR_GL_RGBA;
2623 *externalType = GR_GL_FLOAT;
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;
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;
2647 // clear out the this field so that if a program does use this unit it will rebind the correct
2649 fHWBoundTextureUniqueIDs[lastUnitIdx] = SK_InvalidUniqueID;
2653 // Determines whether glBlitFramebuffer could be used between src and dst.
2654 inline bool can_blit_framebuffer(const GrSurface* dst,
2655 const GrSurface* src,
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())) {
2667 if (NULL != wouldNeedTempFBO) {
2668 *wouldNeedTempFBO = NULL == dst->asRenderTarget() || NULL == src->asRenderTarget();
2676 inline bool can_copy_texsubimage(const GrSurface* dst,
2677 const GrSurface* src,
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())) {
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()) {
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()) {
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();
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,
2717 GrGLIRect* viewport) {
2718 GrGLRenderTarget* rt = static_cast<GrGLRenderTarget*>(surface->asRenderTarget());
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,
2730 viewport->fLeft = 0;
2731 viewport->fBottom = 0;
2732 viewport->fWidth = surface->width();
2733 viewport->fHeight = surface->height();
2736 GR_GL_CALL(gl, BindFramebuffer(fboTarget, rt->renderFBOID()));
2737 *viewport = rt->getViewport();
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);
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);
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);
2764 desc->fConfig = src->config();
2765 desc->fOrigin = src->origin();
2766 desc->fFlags = kNone_GrTextureFlags;
2770 bool GrGpuGL::onCopySurface(GrSurface* dst,
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)) {
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,
2794 this->setScratchTextureUnit();
2795 GL_CALL(BindTexture(GR_GL_TEXTURE_2D, dstTex->textureID()));
2797 if (kBottomLeft_GrSurfaceOrigin == dst->origin()) {
2798 dstY = dst->height() - (dstPoint.fY + srcGLRect.fHeight);
2802 GL_CALL(CopyTexSubImage2D(GR_GL_TEXTURE_2D, 0,
2804 srcGLRect.fLeft, srcGLRect.fBottom,
2805 srcGLRect.fWidth, srcGLRect.fHeight));
2808 GL_CALL(DeleteFramebuffers(1, &srcFBO));
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);
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,
2836 dstGLRect.setRelativeTo(dstVP,
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();
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;
2857 srcY0 = srcGLRect.fBottom + srcGLRect.fHeight;
2858 srcY1 = srcGLRect.fBottom;
2860 GL_CALL(BlitFramebuffer(srcGLRect.fLeft,
2862 srcGLRect.fLeft + srcGLRect.fWidth,
2866 dstGLRect.fLeft + dstGLRect.fWidth,
2867 dstGLRect.fBottom + dstGLRect.fHeight,
2868 GR_GL_COLOR_BUFFER_BIT, GR_GL_NEAREST));
2870 GL_CALL(DeleteFramebuffers(1, &dstFBO));
2873 GL_CALL(DeleteFramebuffers(1, &srcFBO));
2878 if (!copied && inheritedCouldCopy) {
2879 copied = INHERITED::onCopySurface(dst, src, srcRect, dstPoint);
2885 bool GrGpuGL::onCanCopySurface(GrSurface* dst,
2887 const SkIRect& srcRect,
2888 const SkIPoint& dstPoint) {
2889 // This mirrors the logic in onCopySurface.
2890 if (can_copy_texsubimage(dst, src, this)) {
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)) {
2904 return INHERITED::onCanCopySurface(dst, src, srcRect, dstPoint);
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()));
2915 void GrGpuGL::didRemoveGpuTraceMarker() {
2916 if (this->caps()->gpuTracingSupport()) {
2917 GL_CALL(PopGroupMarker());
2920 ///////////////////////////////////////////////////////////////////////////////
2922 GrGLAttribArrayState* GrGpuGL::HWGeometryState::bindArrayAndBuffersToDraw(
2924 const GrGLVertexBuffer* vbuffer,
2925 const GrGLIndexBuffer* ibuffer) {
2926 SkASSERT(NULL != vbuffer);
2927 GrGLAttribArrayState* attribState;
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);
2934 GR_GL_CALL(gpu->glInterface(), GenVertexArrays(1, &arrayID));
2935 int attrCount = gpu->glCaps().maxVertexAttributes();
2936 fVBOVertexArray = SkNEW_ARGS(GrGLVertexArray, (gpu, arrayID, attrCount));
2938 attribState = fVBOVertexArray->bindWithIndexBuffer(ibuffer);
2940 if (NULL != ibuffer) {
2941 this->setIndexBufferIDOnDefaultVertexArray(gpu, ibuffer->bufferID());
2943 this->setVertexArrayID(gpu, 0);
2945 int attrCount = gpu->glCaps().maxVertexAttributes();
2946 if (fDefaultVertexArrayAttribState.count() != attrCount) {
2947 fDefaultVertexArrayAttribState.resize(attrCount);
2949 attribState = &fDefaultVertexArrayAttribState;