• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2010 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 "src/gpu/GrGpu.h"
10 
11 #include "include/gpu/GrBackendSemaphore.h"
12 #include "include/gpu/GrBackendSurface.h"
13 #include "include/gpu/GrDirectContext.h"
14 #include "src/core/SkCompressedDataUtils.h"
15 #include "src/core/SkMathPriv.h"
16 #include "src/core/SkMipmap.h"
17 #include "src/gpu/GrAttachment.h"
18 #include "src/gpu/GrBackendUtils.h"
19 #include "src/gpu/GrCaps.h"
20 #include "src/gpu/GrDataUtils.h"
21 #include "src/gpu/GrDirectContextPriv.h"
22 #include "src/gpu/GrGpuResourcePriv.h"
23 #include "src/gpu/GrNativeRect.h"
24 #include "src/gpu/GrPipeline.h"
25 #include "src/gpu/GrRenderTarget.h"
26 #include "src/gpu/GrResourceCache.h"
27 #include "src/gpu/GrResourceProvider.h"
28 #include "src/gpu/GrRingBuffer.h"
29 #include "src/gpu/GrSemaphore.h"
30 #include "src/gpu/GrStagingBufferManager.h"
31 #include "src/gpu/GrStencilSettings.h"
32 #include "src/gpu/GrTextureProxyPriv.h"
33 #include "src/gpu/GrTracing.h"
34 #include "src/sksl/SkSLCompiler.h"
35 
36 ////////////////////////////////////////////////////////////////////////////////
37 
GrGpu(GrDirectContext * direct)38 GrGpu::GrGpu(GrDirectContext* direct) : fResetBits(kAll_GrBackendState), fContext(direct) {}
39 
~GrGpu()40 GrGpu::~GrGpu() {
41     this->callSubmittedProcs(false);
42 }
43 
initCapsAndCompiler(sk_sp<const GrCaps> caps)44 void GrGpu::initCapsAndCompiler(sk_sp<const GrCaps> caps) {
45     fCaps = std::move(caps);
46     fCompiler = std::make_unique<SkSL::Compiler>(fCaps->shaderCaps());
47 }
48 
disconnect(DisconnectType type)49 void GrGpu::disconnect(DisconnectType type) {}
50 
51 ////////////////////////////////////////////////////////////////////////////////
52 
validate_texel_levels(SkISize dimensions,GrColorType texelColorType,const GrMipLevel * texels,int mipLevelCount,const GrCaps * caps)53 static bool validate_texel_levels(SkISize dimensions, GrColorType texelColorType,
54                                   const GrMipLevel* texels, int mipLevelCount, const GrCaps* caps) {
55     SkASSERT(mipLevelCount > 0);
56     bool hasBasePixels = texels[0].fPixels;
57     int levelsWithPixelsCnt = 0;
58     auto bpp = GrColorTypeBytesPerPixel(texelColorType);
59     int w = dimensions.fWidth;
60     int h = dimensions.fHeight;
61     for (int currentMipLevel = 0; currentMipLevel < mipLevelCount; ++currentMipLevel) {
62         if (texels[currentMipLevel].fPixels) {
63             const size_t minRowBytes = w * bpp;
64             if (caps->writePixelsRowBytesSupport()) {
65                 if (texels[currentMipLevel].fRowBytes < minRowBytes) {
66                     return false;
67                 }
68                 if (texels[currentMipLevel].fRowBytes % bpp) {
69                     return false;
70                 }
71             } else {
72                 if (texels[currentMipLevel].fRowBytes != minRowBytes) {
73                     return false;
74                 }
75             }
76             ++levelsWithPixelsCnt;
77         }
78         if (w == 1 && h == 1) {
79             if (currentMipLevel != mipLevelCount - 1) {
80                 return false;
81             }
82         } else {
83             w = std::max(w / 2, 1);
84             h = std::max(h / 2, 1);
85         }
86     }
87     // Either just a base layer or a full stack is required.
88     if (mipLevelCount != 1 && (w != 1 || h != 1)) {
89         return false;
90     }
91     // Can specify just the base, all levels, or no levels.
92     if (!hasBasePixels) {
93         return levelsWithPixelsCnt == 0;
94     }
95     return levelsWithPixelsCnt == 1 || levelsWithPixelsCnt == mipLevelCount;
96 }
97 
createTextureCommon(SkISize dimensions,const GrBackendFormat & format,GrTextureType textureType,GrRenderable renderable,int renderTargetSampleCnt,SkBudgeted budgeted,GrProtected isProtected,int mipLevelCount,uint32_t levelClearMask)98 sk_sp<GrTexture> GrGpu::createTextureCommon(SkISize dimensions,
99                                             const GrBackendFormat& format,
100                                             GrTextureType textureType,
101                                             GrRenderable renderable,
102                                             int renderTargetSampleCnt,
103                                             SkBudgeted budgeted,
104                                             GrProtected isProtected,
105                                             int mipLevelCount,
106                                             uint32_t levelClearMask) {
107     if (this->caps()->isFormatCompressed(format)) {
108         // Call GrGpu::createCompressedTexture.
109         return nullptr;
110     }
111 
112     GrMipmapped mipMapped = mipLevelCount > 1 ? GrMipmapped::kYes : GrMipmapped::kNo;
113     if (!this->caps()->validateSurfaceParams(dimensions,
114                                              format,
115                                              renderable,
116                                              renderTargetSampleCnt,
117                                              mipMapped,
118                                              textureType)) {
119         return nullptr;
120     }
121 
122     if (renderable == GrRenderable::kYes) {
123         renderTargetSampleCnt =
124                 this->caps()->getRenderTargetSampleCount(renderTargetSampleCnt, format);
125     }
126     // Attempt to catch un- or wrongly initialized sample counts.
127     SkASSERT(renderTargetSampleCnt > 0 && renderTargetSampleCnt <= 64);
128     this->handleDirtyContext();
129     auto tex = this->onCreateTexture(dimensions,
130                                      format,
131                                      renderable,
132                                      renderTargetSampleCnt,
133                                      budgeted,
134                                      isProtected,
135                                      mipLevelCount,
136                                      levelClearMask);
137     if (tex) {
138         SkASSERT(tex->backendFormat() == format);
139         SkASSERT(GrRenderable::kNo == renderable || tex->asRenderTarget());
140         if (!this->caps()->reuseScratchTextures() && renderable == GrRenderable::kNo) {
141             tex->resourcePriv().removeScratchKey();
142         }
143         fStats.incTextureCreates();
144         if (renderTargetSampleCnt > 1 && !this->caps()->msaaResolvesAutomatically()) {
145             SkASSERT(GrRenderable::kYes == renderable);
146             tex->asRenderTarget()->setRequiresManualMSAAResolve();
147         }
148     }
149     return tex;
150 }
151 
createTexture(SkISize dimensions,const GrBackendFormat & format,GrTextureType textureType,GrRenderable renderable,int renderTargetSampleCnt,GrMipmapped mipMapped,SkBudgeted budgeted,GrProtected isProtected)152 sk_sp<GrTexture> GrGpu::createTexture(SkISize dimensions,
153                                       const GrBackendFormat& format,
154                                       GrTextureType textureType,
155                                       GrRenderable renderable,
156                                       int renderTargetSampleCnt,
157                                       GrMipmapped mipMapped,
158                                       SkBudgeted budgeted,
159                                       GrProtected isProtected) {
160     int mipLevelCount = 1;
161     if (mipMapped == GrMipmapped::kYes) {
162         mipLevelCount =
163                 32 - SkCLZ(static_cast<uint32_t>(std::max(dimensions.fWidth, dimensions.fHeight)));
164     }
165     uint32_t levelClearMask =
166             this->caps()->shouldInitializeTextures() ? (1 << mipLevelCount) - 1 : 0;
167     auto tex = this->createTextureCommon(dimensions,
168                                          format,
169                                          textureType,
170                                          renderable,
171                                          renderTargetSampleCnt,
172                                          budgeted,
173                                          isProtected,
174                                          mipLevelCount,
175                                          levelClearMask);
176     if (tex && mipMapped == GrMipmapped::kYes && levelClearMask) {
177         tex->markMipmapsClean();
178     }
179     return tex;
180 }
181 
createTexture(SkISize dimensions,const GrBackendFormat & format,GrTextureType textureType,GrRenderable renderable,int renderTargetSampleCnt,SkBudgeted budgeted,GrProtected isProtected,GrColorType textureColorType,GrColorType srcColorType,const GrMipLevel texels[],int texelLevelCount)182 sk_sp<GrTexture> GrGpu::createTexture(SkISize dimensions,
183                                       const GrBackendFormat& format,
184                                       GrTextureType textureType,
185                                       GrRenderable renderable,
186                                       int renderTargetSampleCnt,
187                                       SkBudgeted budgeted,
188                                       GrProtected isProtected,
189                                       GrColorType textureColorType,
190                                       GrColorType srcColorType,
191                                       const GrMipLevel texels[],
192                                       int texelLevelCount) {
193     TRACE_EVENT0("skia.gpu", TRACE_FUNC);
194     if (texelLevelCount) {
195         if (!validate_texel_levels(dimensions, srcColorType, texels, texelLevelCount,
196                                    this->caps())) {
197             return nullptr;
198         }
199     }
200 
201     int mipLevelCount = std::max(1, texelLevelCount);
202     uint32_t levelClearMask = 0;
203     if (this->caps()->shouldInitializeTextures()) {
204         if (texelLevelCount) {
205             for (int i = 0; i < mipLevelCount; ++i) {
206                 if (!texels->fPixels) {
207                     levelClearMask |= static_cast<uint32_t>(1 << i);
208                 }
209             }
210         } else {
211             levelClearMask = static_cast<uint32_t>((1 << mipLevelCount) - 1);
212         }
213     }
214 
215     auto tex = this->createTextureCommon(dimensions,
216                                          format,
217                                          textureType,
218                                          renderable,
219                                          renderTargetSampleCnt,
220                                          budgeted,
221                                          isProtected,
222                                          texelLevelCount,
223                                          levelClearMask);
224     if (tex) {
225         bool markMipLevelsClean = false;
226         // Currently if level 0 does not have pixels then no other level may, as enforced by
227         // validate_texel_levels.
228         if (texelLevelCount && texels[0].fPixels) {
229             if (!this->writePixels(tex.get(),
230                                    SkIRect::MakeSize(dimensions),
231                                    textureColorType,
232                                    srcColorType,
233                                    texels,
234                                    texelLevelCount)) {
235                 return nullptr;
236             }
237             // Currently if level[1] of mip map has pixel data then so must all other levels.
238             // as enforced by validate_texel_levels.
239             markMipLevelsClean = (texelLevelCount > 1 && !levelClearMask && texels[1].fPixels);
240             fStats.incTextureUploads();
241         } else if (levelClearMask && mipLevelCount > 1) {
242             markMipLevelsClean = true;
243         }
244         if (markMipLevelsClean) {
245             tex->markMipmapsClean();
246         }
247     }
248     return tex;
249 }
250 
createCompressedTexture(SkISize dimensions,const GrBackendFormat & format,SkBudgeted budgeted,GrMipmapped mipMapped,GrProtected isProtected,const void * data,size_t dataSize)251 sk_sp<GrTexture> GrGpu::createCompressedTexture(SkISize dimensions,
252                                                 const GrBackendFormat& format,
253                                                 SkBudgeted budgeted,
254                                                 GrMipmapped mipMapped,
255                                                 GrProtected isProtected,
256                                                 const void* data,
257                                                 size_t dataSize) {
258     this->handleDirtyContext();
259     if (dimensions.width()  < 1 || dimensions.width()  > this->caps()->maxTextureSize() ||
260         dimensions.height() < 1 || dimensions.height() > this->caps()->maxTextureSize()) {
261         return nullptr;
262     }
263     // Note if we relax the requirement that data must be provided then we must check
264     // caps()->shouldInitializeTextures() here.
265     if (!data) {
266         return nullptr;
267     }
268 
269     // TODO: expand CompressedDataIsCorrect to work here too
270     SkImage::CompressionType compressionType = GrBackendFormatToCompressionType(format);
271     if (compressionType == SkImage::CompressionType::kNone) {
272         return nullptr;
273     }
274 
275     if (!this->caps()->isFormatTexturable(format, GrTextureType::k2D)) {
276         return nullptr;
277     }
278 
279     if (dataSize < SkCompressedDataSize(compressionType, dimensions, nullptr,
280                                         mipMapped == GrMipmapped::kYes)) {
281         return nullptr;
282     }
283     return this->onCreateCompressedTexture(dimensions, format, budgeted, mipMapped, isProtected,
284                                            data, dataSize);
285 }
286 
createCompressedTexture(SkISize dimensions,const GrBackendFormat & format,SkBudgeted budgeted,GrMipmapped mipMapped,GrProtected isProtected,OH_NativeBuffer * nativeBuffer,size_t bufferSize)287 sk_sp<GrTexture> GrGpu::createCompressedTexture(SkISize dimensions,
288                                                 const GrBackendFormat& format,
289                                                 SkBudgeted budgeted,
290                                                 GrMipmapped mipMapped,
291                                                 GrProtected isProtected,
292                                                 OH_NativeBuffer* nativeBuffer,
293                                                 size_t bufferSize) {
294     this->handleDirtyContext();
295     if (dimensions.width()  < 1 || dimensions.width()  > this->caps()->maxTextureSize() ||
296         dimensions.height() < 1 || dimensions.height() > this->caps()->maxTextureSize()) {
297         return nullptr;
298     }
299     if (!nativeBuffer) {
300         return nullptr;
301     }
302 
303     SkImage::CompressionType compressionType = GrBackendFormatToCompressionType(format);
304     if (compressionType == SkImage::CompressionType::kNone) {
305         return nullptr;
306     }
307 
308     if (!this->caps()->isFormatTexturable(format, GrTextureType::k2D)) {
309         return nullptr;
310     }
311 
312     if (bufferSize < SkCompressedDataSize(compressionType, dimensions, nullptr,
313                                           mipMapped == GrMipmapped::kYes)) {
314         return nullptr;
315     }
316     return this->onCreateCompressedTexture(dimensions, format, budgeted, mipMapped, isProtected,
317                                            nativeBuffer, bufferSize);
318 }
319 
wrapBackendTexture(const GrBackendTexture & backendTex,GrWrapOwnership ownership,GrWrapCacheable cacheable,GrIOType ioType)320 sk_sp<GrTexture> GrGpu::wrapBackendTexture(const GrBackendTexture& backendTex,
321                                            GrWrapOwnership ownership,
322                                            GrWrapCacheable cacheable,
323                                            GrIOType ioType) {
324     SkASSERT(ioType != kWrite_GrIOType);
325     this->handleDirtyContext();
326 
327     const GrCaps* caps = this->caps();
328     SkASSERT(caps);
329 
330     if (!caps->isFormatTexturable(backendTex.getBackendFormat(), backendTex.textureType())) {
331         return nullptr;
332     }
333     if (backendTex.width() > caps->maxTextureSize() ||
334         backendTex.height() > caps->maxTextureSize()) {
335         return nullptr;
336     }
337 
338     return this->onWrapBackendTexture(backendTex, ownership, cacheable, ioType);
339 }
340 
wrapCompressedBackendTexture(const GrBackendTexture & backendTex,GrWrapOwnership ownership,GrWrapCacheable cacheable)341 sk_sp<GrTexture> GrGpu::wrapCompressedBackendTexture(const GrBackendTexture& backendTex,
342                                                      GrWrapOwnership ownership,
343                                                      GrWrapCacheable cacheable) {
344     this->handleDirtyContext();
345 
346     const GrCaps* caps = this->caps();
347     SkASSERT(caps);
348 
349     if (!caps->isFormatTexturable(backendTex.getBackendFormat(), backendTex.textureType())) {
350         return nullptr;
351     }
352     if (backendTex.width() > caps->maxTextureSize() ||
353         backendTex.height() > caps->maxTextureSize()) {
354         return nullptr;
355     }
356 
357     return this->onWrapCompressedBackendTexture(backendTex, ownership, cacheable);
358 }
359 
wrapRenderableBackendTexture(const GrBackendTexture & backendTex,int sampleCnt,GrWrapOwnership ownership,GrWrapCacheable cacheable)360 sk_sp<GrTexture> GrGpu::wrapRenderableBackendTexture(const GrBackendTexture& backendTex,
361                                                      int sampleCnt,
362                                                      GrWrapOwnership ownership,
363                                                      GrWrapCacheable cacheable) {
364     this->handleDirtyContext();
365     if (sampleCnt < 1) {
366         return nullptr;
367     }
368 
369     const GrCaps* caps = this->caps();
370 
371     if (!caps->isFormatTexturable(backendTex.getBackendFormat(), backendTex.textureType()) ||
372         !caps->isFormatRenderable(backendTex.getBackendFormat(), sampleCnt)) {
373         return nullptr;
374     }
375 
376     if (backendTex.width() > caps->maxRenderTargetSize() ||
377         backendTex.height() > caps->maxRenderTargetSize()) {
378         return nullptr;
379     }
380     sk_sp<GrTexture> tex =
381             this->onWrapRenderableBackendTexture(backendTex, sampleCnt, ownership, cacheable);
382     SkASSERT(!tex || tex->asRenderTarget());
383     if (tex && sampleCnt > 1 && !caps->msaaResolvesAutomatically()) {
384         tex->asRenderTarget()->setRequiresManualMSAAResolve();
385     }
386     return tex;
387 }
388 
wrapBackendRenderTarget(const GrBackendRenderTarget & backendRT)389 sk_sp<GrRenderTarget> GrGpu::wrapBackendRenderTarget(const GrBackendRenderTarget& backendRT) {
390     this->handleDirtyContext();
391 
392     const GrCaps* caps = this->caps();
393 
394     if (!caps->isFormatRenderable(backendRT.getBackendFormat(), backendRT.sampleCnt())) {
395         return nullptr;
396     }
397 
398     sk_sp<GrRenderTarget> rt = this->onWrapBackendRenderTarget(backendRT);
399     if (backendRT.isFramebufferOnly()) {
400         rt->setFramebufferOnly();
401     }
402     return rt;
403 }
404 
wrapVulkanSecondaryCBAsRenderTarget(const SkImageInfo & imageInfo,const GrVkDrawableInfo & vkInfo)405 sk_sp<GrRenderTarget> GrGpu::wrapVulkanSecondaryCBAsRenderTarget(const SkImageInfo& imageInfo,
406                                                                  const GrVkDrawableInfo& vkInfo) {
407     return this->onWrapVulkanSecondaryCBAsRenderTarget(imageInfo, vkInfo);
408 }
409 
onWrapVulkanSecondaryCBAsRenderTarget(const SkImageInfo & imageInfo,const GrVkDrawableInfo & vkInfo)410 sk_sp<GrRenderTarget> GrGpu::onWrapVulkanSecondaryCBAsRenderTarget(const SkImageInfo& imageInfo,
411                                                                    const GrVkDrawableInfo& vkInfo) {
412     // This is only supported on Vulkan so we default to returning nullptr here
413     return nullptr;
414 }
415 
createBuffer(size_t size,GrGpuBufferType intendedType,GrAccessPattern accessPattern,const void * data)416 sk_sp<GrGpuBuffer> GrGpu::createBuffer(size_t size, GrGpuBufferType intendedType,
417                                        GrAccessPattern accessPattern, const void* data) {
418     TRACE_EVENT0("skia.gpu", TRACE_FUNC);
419     this->handleDirtyContext();
420     sk_sp<GrGpuBuffer> buffer = this->onCreateBuffer(size, intendedType, accessPattern, data);
421     if (!this->caps()->reuseScratchBuffers()) {
422         buffer->resourcePriv().removeScratchKey();
423     }
424     return buffer;
425 }
426 
copySurface(GrSurface * dst,GrSurface * src,const SkIRect & srcRect,const SkIPoint & dstPoint)427 bool GrGpu::copySurface(GrSurface* dst, GrSurface* src, const SkIRect& srcRect,
428                         const SkIPoint& dstPoint) {
429     TRACE_EVENT0("skia.gpu", TRACE_FUNC);
430     SkASSERT(dst && src);
431     SkASSERT(!src->framebufferOnly());
432 
433     if (dst->readOnly()) {
434         return false;
435     }
436 
437     this->handleDirtyContext();
438 
439     return this->onCopySurface(dst, src, srcRect, dstPoint);
440 }
441 
readPixels(GrSurface * surface,SkIRect rect,GrColorType surfaceColorType,GrColorType dstColorType,void * buffer,size_t rowBytes)442 bool GrGpu::readPixels(GrSurface* surface,
443                        SkIRect rect,
444                        GrColorType surfaceColorType,
445                        GrColorType dstColorType,
446                        void* buffer,
447                        size_t rowBytes) {
448     TRACE_EVENT0("skia.gpu", TRACE_FUNC);
449     SkASSERT(surface);
450     SkASSERT(!surface->framebufferOnly());
451     SkASSERT(this->caps()->areColorTypeAndFormatCompatible(surfaceColorType,
452                                                            surface->backendFormat()));
453 
454     if (!SkIRect::MakeSize(surface->dimensions()).contains(rect)) {
455         return false;
456     }
457 
458     size_t minRowBytes = SkToSizeT(GrColorTypeBytesPerPixel(dstColorType) * rect.width());
459     if (!this->caps()->readPixelsRowBytesSupport()) {
460         if (rowBytes != minRowBytes) {
461             return false;
462         }
463     } else {
464         if (rowBytes < minRowBytes) {
465             return false;
466         }
467         if (rowBytes % GrColorTypeBytesPerPixel(dstColorType)) {
468             return false;
469         }
470     }
471 
472     this->handleDirtyContext();
473 
474     return this->onReadPixels(surface, rect, surfaceColorType, dstColorType, buffer, rowBytes);
475 }
476 
writePixels(GrSurface * surface,SkIRect rect,GrColorType surfaceColorType,GrColorType srcColorType,const GrMipLevel texels[],int mipLevelCount,bool prepForTexSampling)477 bool GrGpu::writePixels(GrSurface* surface,
478                         SkIRect rect,
479                         GrColorType surfaceColorType,
480                         GrColorType srcColorType,
481                         const GrMipLevel texels[],
482                         int mipLevelCount,
483                         bool prepForTexSampling) {
484     TRACE_EVENT0("skia.gpu", TRACE_FUNC);
485     ATRACE_ANDROID_FRAMEWORK_ALWAYS("Texture upload(%u) %ix%i",
486                                     surface->uniqueID().asUInt(), rect.width(), rect.height());
487     SkASSERT(surface);
488     SkASSERT(!surface->framebufferOnly());
489 
490     if (surface->readOnly()) {
491         return false;
492     }
493 
494     if (mipLevelCount == 0) {
495         return false;
496     } else if (mipLevelCount == 1) {
497         // We require that if we are not mipped, then the write region is contained in the surface
498         if (!SkIRect::MakeSize(surface->dimensions()).contains(rect)) {
499             return false;
500         }
501     } else if (rect != SkIRect::MakeSize(surface->dimensions())) {
502         // We require that if the texels are mipped, than the write region is the entire surface
503         return false;
504     }
505 
506     if (!validate_texel_levels(rect.size(), srcColorType, texels, mipLevelCount, this->caps())) {
507         return false;
508     }
509 
510     this->handleDirtyContext();
511     if (this->onWritePixels(surface,
512                             rect,
513                             surfaceColorType,
514                             srcColorType,
515                             texels,
516                             mipLevelCount,
517                             prepForTexSampling)) {
518         this->didWriteToSurface(surface, kTopLeft_GrSurfaceOrigin, &rect, mipLevelCount);
519         fStats.incTextureUploads();
520         return true;
521     }
522     return false;
523 }
524 
transferPixelsTo(GrTexture * texture,SkIRect rect,GrColorType textureColorType,GrColorType bufferColorType,sk_sp<GrGpuBuffer> transferBuffer,size_t offset,size_t rowBytes)525 bool GrGpu::transferPixelsTo(GrTexture* texture,
526                              SkIRect rect,
527                              GrColorType textureColorType,
528                              GrColorType bufferColorType,
529                              sk_sp<GrGpuBuffer> transferBuffer,
530                              size_t offset,
531                              size_t rowBytes) {
532     TRACE_EVENT0("skia.gpu", TRACE_FUNC);
533     SkASSERT(texture);
534     SkASSERT(transferBuffer);
535 
536     if (texture->readOnly()) {
537         return false;
538     }
539 
540     // We require that the write region is contained in the texture
541     if (!SkIRect::MakeSize(texture->dimensions()).contains(rect)) {
542         return false;
543     }
544 
545     size_t bpp = GrColorTypeBytesPerPixel(bufferColorType);
546     if (this->caps()->writePixelsRowBytesSupport()) {
547         if (rowBytes < SkToSizeT(bpp*rect.width())) {
548             return false;
549         }
550         if (rowBytes % bpp) {
551             return false;
552         }
553     } else {
554         if (rowBytes != SkToSizeT(bpp*rect.width())) {
555             return false;
556         }
557     }
558 
559     this->handleDirtyContext();
560     if (this->onTransferPixelsTo(texture,
561                                  rect,
562                                  textureColorType,
563                                  bufferColorType,
564                                  std::move(transferBuffer),
565                                  offset,
566                                  rowBytes)) {
567         this->didWriteToSurface(texture, kTopLeft_GrSurfaceOrigin, &rect);
568         fStats.incTransfersToTexture();
569 
570         return true;
571     }
572     return false;
573 }
574 
transferPixelsFrom(GrSurface * surface,SkIRect rect,GrColorType surfaceColorType,GrColorType bufferColorType,sk_sp<GrGpuBuffer> transferBuffer,size_t offset)575 bool GrGpu::transferPixelsFrom(GrSurface* surface,
576                                SkIRect rect,
577                                GrColorType surfaceColorType,
578                                GrColorType bufferColorType,
579                                sk_sp<GrGpuBuffer> transferBuffer,
580                                size_t offset) {
581     TRACE_EVENT0("skia.gpu", TRACE_FUNC);
582     SkASSERT(surface);
583     SkASSERT(transferBuffer);
584     SkASSERT(this->caps()->areColorTypeAndFormatCompatible(surfaceColorType,
585                                                            surface->backendFormat()));
586 
587 #ifdef SK_DEBUG
588     auto supportedRead = this->caps()->supportedReadPixelsColorType(
589             surfaceColorType, surface->backendFormat(), bufferColorType);
590     SkASSERT(supportedRead.fOffsetAlignmentForTransferBuffer);
591     SkASSERT(offset % supportedRead.fOffsetAlignmentForTransferBuffer == 0);
592 #endif
593 
594     // We require that the write region is contained in the texture
595     if (!SkIRect::MakeSize(surface->dimensions()).contains(rect)) {
596         return false;
597     }
598 
599     this->handleDirtyContext();
600     if (this->onTransferPixelsFrom(surface,
601                                    rect,
602                                    surfaceColorType,
603                                    bufferColorType,
604                                    std::move(transferBuffer),
605                                    offset)) {
606         fStats.incTransfersFromSurface();
607         return true;
608     }
609     return false;
610 }
611 
regenerateMipMapLevels(GrTexture * texture)612 bool GrGpu::regenerateMipMapLevels(GrTexture* texture) {
613     TRACE_EVENT0("skia.gpu", TRACE_FUNC);
614     SkASSERT(texture);
615     SkASSERT(this->caps()->mipmapSupport());
616     SkASSERT(texture->mipmapped() == GrMipmapped::kYes);
617     if (!texture->mipmapsAreDirty()) {
618         // This can happen when the proxy expects mipmaps to be dirty, but they are not dirty on the
619         // actual target. This may be caused by things that the drawingManager could not predict,
620         // i.e., ops that don't draw anything, aborting a draw for exceptional circumstances, etc.
621         // NOTE: This goes away once we quit tracking mipmap state on the actual texture.
622         return true;
623     }
624     if (texture->readOnly()) {
625         return false;
626     }
627     if (this->onRegenerateMipMapLevels(texture)) {
628         texture->markMipmapsClean();
629         return true;
630     }
631     return false;
632 }
633 
resetTextureBindings()634 void GrGpu::resetTextureBindings() {
635     this->handleDirtyContext();
636     this->onResetTextureBindings();
637 }
638 
resolveRenderTarget(GrRenderTarget * target,const SkIRect & resolveRect)639 void GrGpu::resolveRenderTarget(GrRenderTarget* target, const SkIRect& resolveRect) {
640     SkASSERT(target);
641     this->handleDirtyContext();
642     this->onResolveRenderTarget(target, resolveRect);
643 }
644 
didWriteToSurface(GrSurface * surface,GrSurfaceOrigin origin,const SkIRect * bounds,uint32_t mipLevels) const645 void GrGpu::didWriteToSurface(GrSurface* surface, GrSurfaceOrigin origin, const SkIRect* bounds,
646                               uint32_t mipLevels) const {
647     SkASSERT(surface);
648     SkASSERT(!surface->readOnly());
649     // Mark any MIP chain and resolve buffer as dirty if and only if there is a non-empty bounds.
650     if (nullptr == bounds || !bounds->isEmpty()) {
651         GrTexture* texture = surface->asTexture();
652         if (texture) {
653             if (mipLevels == 1) {
654                 texture->markMipmapsDirty();
655             } else {
656                 texture->markMipmapsClean();
657             }
658         }
659     }
660 }
661 
executeFlushInfo(SkSpan<GrSurfaceProxy * > proxies,SkSurface::BackendSurfaceAccess access,const GrFlushInfo & info,const GrBackendSurfaceMutableState * newState)662 void GrGpu::executeFlushInfo(SkSpan<GrSurfaceProxy*> proxies,
663                              SkSurface::BackendSurfaceAccess access,
664                              const GrFlushInfo& info,
665                              const GrBackendSurfaceMutableState* newState) {
666     TRACE_EVENT0("skia.gpu", TRACE_FUNC);
667 
668     GrResourceProvider* resourceProvider = fContext->priv().resourceProvider();
669 
670     std::unique_ptr<std::unique_ptr<GrSemaphore>[]> semaphores(
671             new std::unique_ptr<GrSemaphore>[info.fNumSemaphores]);
672     if (this->caps()->semaphoreSupport() && info.fNumSemaphores) {
673         for (size_t i = 0; i < info.fNumSemaphores; ++i) {
674             if (info.fSignalSemaphores[i].isInitialized()) {
675                 semaphores[i] = resourceProvider->wrapBackendSemaphore(
676                     info.fSignalSemaphores[i],
677                     GrSemaphoreWrapType::kWillSignal,
678                     kBorrow_GrWrapOwnership);
679                 // If we failed to wrap the semaphore it means the client didn't give us a valid
680                 // semaphore to begin with. Therefore, it is fine to not signal it.
681                 if (semaphores[i]) {
682                     this->insertSemaphore(semaphores[i].get());
683                 }
684             } else {
685                 semaphores[i] = resourceProvider->makeSemaphore(false);
686                 if (semaphores[i]) {
687                     this->insertSemaphore(semaphores[i].get());
688                     info.fSignalSemaphores[i] = semaphores[i]->backendSemaphore();
689                 }
690             }
691         }
692     }
693 
694     if (info.fFinishedProc) {
695         this->addFinishedProc(info.fFinishedProc, info.fFinishedContext);
696     }
697 
698     if (info.fSubmittedProc) {
699         fSubmittedProcs.emplace_back(info.fSubmittedProc, info.fSubmittedContext);
700     }
701 
702     // We currently don't support passing in new surface state for multiple proxies here. The only
703     // time we have multiple proxies is if we are flushing a yuv SkImage which won't have state
704     // updates anyways.
705     SkASSERT(!newState || proxies.size() == 1);
706     SkASSERT(!newState || access == SkSurface::BackendSurfaceAccess::kNoAccess);
707     this->prepareSurfacesForBackendAccessAndStateUpdates(proxies, access, newState);
708 }
709 
getOpsRenderPass(GrRenderTarget * renderTarget,bool useMSAASurface,GrAttachment * stencil,GrSurfaceOrigin origin,const SkIRect & bounds,const GrOpsRenderPass::LoadAndStoreInfo & colorInfo,const GrOpsRenderPass::StencilLoadAndStoreInfo & stencilInfo,const SkTArray<GrSurfaceProxy *,true> & sampledProxies,GrXferBarrierFlags renderPassXferBarriers)710 GrOpsRenderPass* GrGpu::getOpsRenderPass(
711         GrRenderTarget* renderTarget,
712         bool useMSAASurface,
713         GrAttachment* stencil,
714         GrSurfaceOrigin origin,
715         const SkIRect& bounds,
716         const GrOpsRenderPass::LoadAndStoreInfo& colorInfo,
717         const GrOpsRenderPass::StencilLoadAndStoreInfo& stencilInfo,
718         const SkTArray<GrSurfaceProxy*, true>& sampledProxies,
719         GrXferBarrierFlags renderPassXferBarriers) {
720 #if SK_HISTOGRAMS_ENABLED
721     fCurrentSubmitRenderPassCount++;
722 #endif
723     fStats.incRenderPasses();
724     return this->onGetOpsRenderPass(renderTarget, useMSAASurface, stencil, origin, bounds,
725                                     colorInfo, stencilInfo, sampledProxies, renderPassXferBarriers);
726 }
727 
submitToGpu(bool syncCpu)728 bool GrGpu::submitToGpu(bool syncCpu) {
729     this->stats()->incNumSubmitToGpus();
730 
731     if (auto manager = this->stagingBufferManager()) {
732         manager->detachBuffers();
733     }
734 
735     if (auto uniformsBuffer = this->uniformsRingBuffer()) {
736         uniformsBuffer->startSubmit(this);
737     }
738 
739     bool submitted = this->onSubmitToGpu(syncCpu);
740 
741     this->callSubmittedProcs(submitted);
742 
743     this->reportSubmitHistograms();
744 
745     return submitted;
746 }
747 
reportSubmitHistograms()748 void GrGpu::reportSubmitHistograms() {
749 #if SK_HISTOGRAMS_ENABLED
750     // The max allowed value for SK_HISTOGRAM_EXACT_LINEAR is 100. If we want to support higher
751     // values we can add SK_HISTOGRAM_CUSTOM_COUNTS but this has a number of buckets that is less
752     // than the number of actual values
753     static constexpr int kMaxRenderPassBucketValue = 100;
754     SK_HISTOGRAM_EXACT_LINEAR("SubmitRenderPasses",
755                               std::min(fCurrentSubmitRenderPassCount, kMaxRenderPassBucketValue),
756                               kMaxRenderPassBucketValue);
757     fCurrentSubmitRenderPassCount = 0;
758 #endif
759 
760     this->onReportSubmitHistograms();
761 }
762 
checkAndResetOOMed()763 bool GrGpu::checkAndResetOOMed() {
764     if (fOOMed) {
765         fOOMed = false;
766         return true;
767     }
768     return false;
769 }
770 
callSubmittedProcs(bool success)771 void GrGpu::callSubmittedProcs(bool success) {
772     for (int i = 0; i < fSubmittedProcs.count(); ++i) {
773         fSubmittedProcs[i].fProc(fSubmittedProcs[i].fContext, success);
774     }
775     fSubmittedProcs.reset();
776 }
777 
778 #ifdef SK_ENABLE_DUMP_GPU
779 #include "src/utils/SkJSONWriter.h"
780 
dumpJSON(SkJSONWriter * writer) const781 void GrGpu::dumpJSON(SkJSONWriter* writer) const {
782     writer->beginObject();
783 
784     // TODO: Is there anything useful in the base class to dump here?
785 
786     this->onDumpJSON(writer);
787 
788     writer->endObject();
789 }
790 #else
dumpJSON(SkJSONWriter * writer) const791 void GrGpu::dumpJSON(SkJSONWriter* writer) const { }
792 #endif
793 
794 #if GR_TEST_UTILS
795 
796 #if GR_GPU_STATS
797 
dump(SkString * out)798 void GrGpu::Stats::dump(SkString* out) {
799     out->appendf("Textures Created: %d\n", fTextureCreates);
800     out->appendf("Texture Uploads: %d\n", fTextureUploads);
801     out->appendf("Transfers to Texture: %d\n", fTransfersToTexture);
802     out->appendf("Transfers from Surface: %d\n", fTransfersFromSurface);
803     out->appendf("Stencil Buffer Creates: %d\n", fStencilAttachmentCreates);
804     out->appendf("MSAA Attachment Creates: %d\n", fMSAAAttachmentCreates);
805     out->appendf("Number of draws: %d\n", fNumDraws);
806     out->appendf("Number of Scratch Textures reused %d\n", fNumScratchTexturesReused);
807     out->appendf("Number of Scratch MSAA Attachments reused %d\n",
808                  fNumScratchMSAAAttachmentsReused);
809     out->appendf("Number of Render Passes: %d\n", fRenderPasses);
810     out->appendf("Reordered DAGs Over Budget: %d\n", fNumReorderedDAGsOverBudget);
811 
812     // enable this block to output CSV-style stats for program pre-compilation
813 #if 0
814     SkASSERT(fNumInlineCompilationFailures == 0);
815     SkASSERT(fNumPreCompilationFailures == 0);
816     SkASSERT(fNumCompilationFailures == 0);
817     SkASSERT(fNumPartialCompilationSuccesses == 0);
818 
819     SkDebugf("%d, %d, %d, %d, %d\n",
820              fInlineProgramCacheStats[(int) Stats::ProgramCacheResult::kHit],
821              fInlineProgramCacheStats[(int) Stats::ProgramCacheResult::kMiss],
822              fPreProgramCacheStats[(int) Stats::ProgramCacheResult::kHit],
823              fPreProgramCacheStats[(int) Stats::ProgramCacheResult::kMiss],
824              fNumCompilationSuccesses);
825 #endif
826 }
827 
dumpKeyValuePairs(SkTArray<SkString> * keys,SkTArray<double> * values)828 void GrGpu::Stats::dumpKeyValuePairs(SkTArray<SkString>* keys, SkTArray<double>* values) {
829     keys->push_back(SkString("render_passes"));
830     values->push_back(fRenderPasses);
831     keys->push_back(SkString("reordered_dags_over_budget"));
832     values->push_back(fNumReorderedDAGsOverBudget);
833 }
834 
835 #endif // GR_GPU_STATS
836 #endif // GR_TEST_UTILS
837 
CompressedDataIsCorrect(SkISize dimensions,SkImage::CompressionType compressionType,GrMipmapped mipMapped,const void * data,size_t length)838 bool GrGpu::CompressedDataIsCorrect(SkISize dimensions,
839                                     SkImage::CompressionType compressionType,
840                                     GrMipmapped mipMapped,
841                                     const void* data,
842                                     size_t length) {
843     size_t computedSize = SkCompressedDataSize(compressionType,
844                                                dimensions,
845                                                nullptr,
846                                                mipMapped == GrMipmapped::kYes);
847     return computedSize == length;
848 }
849 
createBackendTexture(SkISize dimensions,const GrBackendFormat & format,GrRenderable renderable,GrMipmapped mipMapped,GrProtected isProtected)850 GrBackendTexture GrGpu::createBackendTexture(SkISize dimensions,
851                                              const GrBackendFormat& format,
852                                              GrRenderable renderable,
853                                              GrMipmapped mipMapped,
854                                              GrProtected isProtected) {
855     const GrCaps* caps = this->caps();
856 
857     if (!format.isValid()) {
858         return {};
859     }
860 
861     if (caps->isFormatCompressed(format)) {
862         // Compressed formats must go through the createCompressedBackendTexture API
863         return {};
864     }
865 
866     if (dimensions.isEmpty() || dimensions.width()  > caps->maxTextureSize() ||
867                                 dimensions.height() > caps->maxTextureSize()) {
868         return {};
869     }
870 
871     if (mipMapped == GrMipmapped::kYes && !this->caps()->mipmapSupport()) {
872         return {};
873     }
874 
875     return this->onCreateBackendTexture(dimensions, format, renderable, mipMapped, isProtected);
876 }
877 
clearBackendTexture(const GrBackendTexture & backendTexture,sk_sp<GrRefCntedCallback> finishedCallback,std::array<float,4> color)878 bool GrGpu::clearBackendTexture(const GrBackendTexture& backendTexture,
879                                 sk_sp<GrRefCntedCallback> finishedCallback,
880                                 std::array<float, 4> color) {
881     if (!backendTexture.isValid()) {
882         return false;
883     }
884 
885     if (backendTexture.hasMipmaps() && !this->caps()->mipmapSupport()) {
886         return false;
887     }
888 
889     return this->onClearBackendTexture(backendTexture, std::move(finishedCallback), color);
890 }
891 
createCompressedBackendTexture(SkISize dimensions,const GrBackendFormat & format,GrMipmapped mipMapped,GrProtected isProtected)892 GrBackendTexture GrGpu::createCompressedBackendTexture(SkISize dimensions,
893                                                        const GrBackendFormat& format,
894                                                        GrMipmapped mipMapped,
895                                                        GrProtected isProtected) {
896     const GrCaps* caps = this->caps();
897 
898     if (!format.isValid()) {
899         return {};
900     }
901 
902     SkImage::CompressionType compressionType = GrBackendFormatToCompressionType(format);
903     if (compressionType == SkImage::CompressionType::kNone) {
904         // Uncompressed formats must go through the createBackendTexture API
905         return {};
906     }
907 
908     if (dimensions.isEmpty() ||
909         dimensions.width()  > caps->maxTextureSize() ||
910         dimensions.height() > caps->maxTextureSize()) {
911         return {};
912     }
913 
914     if (mipMapped == GrMipmapped::kYes && !this->caps()->mipmapSupport()) {
915         return {};
916     }
917 
918     return this->onCreateCompressedBackendTexture(dimensions, format, mipMapped, isProtected);
919 }
920 
updateCompressedBackendTexture(const GrBackendTexture & backendTexture,sk_sp<GrRefCntedCallback> finishedCallback,const void * data,size_t length)921 bool GrGpu::updateCompressedBackendTexture(const GrBackendTexture& backendTexture,
922                                            sk_sp<GrRefCntedCallback> finishedCallback,
923                                            const void* data,
924                                            size_t length) {
925     SkASSERT(data);
926 
927     if (!backendTexture.isValid()) {
928         return false;
929     }
930 
931     GrBackendFormat format = backendTexture.getBackendFormat();
932 
933     SkImage::CompressionType compressionType = GrBackendFormatToCompressionType(format);
934     if (compressionType == SkImage::CompressionType::kNone) {
935         // Uncompressed formats must go through the createBackendTexture API
936         return false;
937     }
938 
939     if (backendTexture.hasMipmaps() && !this->caps()->mipmapSupport()) {
940         return false;
941     }
942 
943     GrMipmapped mipMapped = backendTexture.hasMipmaps() ? GrMipmapped::kYes : GrMipmapped::kNo;
944 
945     if (!CompressedDataIsCorrect(backendTexture.dimensions(),
946                                  compressionType,
947                                  mipMapped,
948                                  data,
949                                  length)) {
950         return false;
951     }
952 
953     return this->onUpdateCompressedBackendTexture(backendTexture,
954                                                   std::move(finishedCallback),
955                                                   data,
956                                                   length);
957 }
958