• 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 #ifdef SKIA_OHOS
485     HITRACE_OHOS_NAME_FMT_LEVEL(DebugTraceLevel::DETAIL, "Texture upload(%u) %ix%i",
486         surface->uniqueID().asUInt(), rect.width(), rect.height());
487 #else
488     TRACE_EVENT0("skia.gpu", TRACE_FUNC);
489     ATRACE_ANDROID_FRAMEWORK_ALWAYS("Texture upload(%u) %ix%i",
490                                     surface->uniqueID().asUInt(), rect.width(), rect.height());
491 #endif
492     SkASSERT(surface);
493     SkASSERT(!surface->framebufferOnly());
494 
495     if (surface->readOnly()) {
496         return false;
497     }
498 
499     if (mipLevelCount == 0) {
500         return false;
501     } else if (mipLevelCount == 1) {
502         // We require that if we are not mipped, then the write region is contained in the surface
503         if (!SkIRect::MakeSize(surface->dimensions()).contains(rect)) {
504             return false;
505         }
506     } else if (rect != SkIRect::MakeSize(surface->dimensions())) {
507         // We require that if the texels are mipped, than the write region is the entire surface
508         return false;
509     }
510 
511     if (!validate_texel_levels(rect.size(), srcColorType, texels, mipLevelCount, this->caps())) {
512         return false;
513     }
514 
515     this->handleDirtyContext();
516     if (this->onWritePixels(surface,
517                             rect,
518                             surfaceColorType,
519                             srcColorType,
520                             texels,
521                             mipLevelCount,
522                             prepForTexSampling)) {
523         this->didWriteToSurface(surface, kTopLeft_GrSurfaceOrigin, &rect, mipLevelCount);
524         fStats.incTextureUploads();
525         return true;
526     }
527     return false;
528 }
529 
transferPixelsTo(GrTexture * texture,SkIRect rect,GrColorType textureColorType,GrColorType bufferColorType,sk_sp<GrGpuBuffer> transferBuffer,size_t offset,size_t rowBytes)530 bool GrGpu::transferPixelsTo(GrTexture* texture,
531                              SkIRect rect,
532                              GrColorType textureColorType,
533                              GrColorType bufferColorType,
534                              sk_sp<GrGpuBuffer> transferBuffer,
535                              size_t offset,
536                              size_t rowBytes) {
537     TRACE_EVENT0("skia.gpu", TRACE_FUNC);
538     SkASSERT(texture);
539     SkASSERT(transferBuffer);
540 
541     if (texture->readOnly()) {
542         return false;
543     }
544 
545     // We require that the write region is contained in the texture
546     if (!SkIRect::MakeSize(texture->dimensions()).contains(rect)) {
547         return false;
548     }
549 
550     size_t bpp = GrColorTypeBytesPerPixel(bufferColorType);
551     if (this->caps()->writePixelsRowBytesSupport()) {
552         if (rowBytes < SkToSizeT(bpp*rect.width())) {
553             return false;
554         }
555         if (rowBytes % bpp) {
556             return false;
557         }
558     } else {
559         if (rowBytes != SkToSizeT(bpp*rect.width())) {
560             return false;
561         }
562     }
563 
564     this->handleDirtyContext();
565     if (this->onTransferPixelsTo(texture,
566                                  rect,
567                                  textureColorType,
568                                  bufferColorType,
569                                  std::move(transferBuffer),
570                                  offset,
571                                  rowBytes)) {
572         this->didWriteToSurface(texture, kTopLeft_GrSurfaceOrigin, &rect);
573         fStats.incTransfersToTexture();
574 
575         return true;
576     }
577     return false;
578 }
579 
transferPixelsFrom(GrSurface * surface,SkIRect rect,GrColorType surfaceColorType,GrColorType bufferColorType,sk_sp<GrGpuBuffer> transferBuffer,size_t offset)580 bool GrGpu::transferPixelsFrom(GrSurface* surface,
581                                SkIRect rect,
582                                GrColorType surfaceColorType,
583                                GrColorType bufferColorType,
584                                sk_sp<GrGpuBuffer> transferBuffer,
585                                size_t offset) {
586     TRACE_EVENT0("skia.gpu", TRACE_FUNC);
587     SkASSERT(surface);
588     SkASSERT(transferBuffer);
589     SkASSERT(this->caps()->areColorTypeAndFormatCompatible(surfaceColorType,
590                                                            surface->backendFormat()));
591 
592 #ifdef SK_DEBUG
593     auto supportedRead = this->caps()->supportedReadPixelsColorType(
594             surfaceColorType, surface->backendFormat(), bufferColorType);
595     SkASSERT(supportedRead.fOffsetAlignmentForTransferBuffer);
596     SkASSERT(offset % supportedRead.fOffsetAlignmentForTransferBuffer == 0);
597 #endif
598 
599     // We require that the write region is contained in the texture
600     if (!SkIRect::MakeSize(surface->dimensions()).contains(rect)) {
601         return false;
602     }
603 
604     this->handleDirtyContext();
605     if (this->onTransferPixelsFrom(surface,
606                                    rect,
607                                    surfaceColorType,
608                                    bufferColorType,
609                                    std::move(transferBuffer),
610                                    offset)) {
611         fStats.incTransfersFromSurface();
612         return true;
613     }
614     return false;
615 }
616 
regenerateMipMapLevels(GrTexture * texture)617 bool GrGpu::regenerateMipMapLevels(GrTexture* texture) {
618     TRACE_EVENT0("skia.gpu", TRACE_FUNC);
619     SkASSERT(texture);
620     SkASSERT(this->caps()->mipmapSupport());
621     SkASSERT(texture->mipmapped() == GrMipmapped::kYes);
622     if (!texture->mipmapsAreDirty()) {
623         // This can happen when the proxy expects mipmaps to be dirty, but they are not dirty on the
624         // actual target. This may be caused by things that the drawingManager could not predict,
625         // i.e., ops that don't draw anything, aborting a draw for exceptional circumstances, etc.
626         // NOTE: This goes away once we quit tracking mipmap state on the actual texture.
627         return true;
628     }
629     if (texture->readOnly()) {
630         return false;
631     }
632     if (this->onRegenerateMipMapLevels(texture)) {
633         texture->markMipmapsClean();
634         return true;
635     }
636     return false;
637 }
638 
resetTextureBindings()639 void GrGpu::resetTextureBindings() {
640     this->handleDirtyContext();
641     this->onResetTextureBindings();
642 }
643 
resolveRenderTarget(GrRenderTarget * target,const SkIRect & resolveRect)644 void GrGpu::resolveRenderTarget(GrRenderTarget* target, const SkIRect& resolveRect) {
645     SkASSERT(target);
646     this->handleDirtyContext();
647     this->onResolveRenderTarget(target, resolveRect);
648 }
649 
didWriteToSurface(GrSurface * surface,GrSurfaceOrigin origin,const SkIRect * bounds,uint32_t mipLevels) const650 void GrGpu::didWriteToSurface(GrSurface* surface, GrSurfaceOrigin origin, const SkIRect* bounds,
651                               uint32_t mipLevels) const {
652     SkASSERT(surface);
653     SkASSERT(!surface->readOnly());
654     // Mark any MIP chain and resolve buffer as dirty if and only if there is a non-empty bounds.
655     if (nullptr == bounds || !bounds->isEmpty()) {
656         GrTexture* texture = surface->asTexture();
657         if (texture) {
658             if (mipLevels == 1) {
659                 texture->markMipmapsDirty();
660             } else {
661                 texture->markMipmapsClean();
662             }
663         }
664     }
665 }
666 
executeFlushInfo(SkSpan<GrSurfaceProxy * > proxies,SkSurface::BackendSurfaceAccess access,const GrFlushInfo & info,const GrBackendSurfaceMutableState * newState)667 void GrGpu::executeFlushInfo(SkSpan<GrSurfaceProxy*> proxies,
668                              SkSurface::BackendSurfaceAccess access,
669                              const GrFlushInfo& info,
670                              const GrBackendSurfaceMutableState* newState) {
671     TRACE_EVENT0("skia.gpu", TRACE_FUNC);
672 
673     GrResourceProvider* resourceProvider = fContext->priv().resourceProvider();
674 
675     std::unique_ptr<std::unique_ptr<GrSemaphore>[]> semaphores(
676             new std::unique_ptr<GrSemaphore>[info.fNumSemaphores]);
677     if (this->caps()->semaphoreSupport() && info.fNumSemaphores) {
678         for (size_t i = 0; i < info.fNumSemaphores; ++i) {
679             if (info.fSignalSemaphores[i].isInitialized()) {
680                 semaphores[i] = resourceProvider->wrapBackendSemaphore(
681                     info.fSignalSemaphores[i],
682                     GrSemaphoreWrapType::kWillSignal,
683                     kBorrow_GrWrapOwnership);
684                 // If we failed to wrap the semaphore it means the client didn't give us a valid
685                 // semaphore to begin with. Therefore, it is fine to not signal it.
686                 if (semaphores[i]) {
687                     this->insertSemaphore(semaphores[i].get());
688                 }
689             } else {
690                 semaphores[i] = resourceProvider->makeSemaphore(false);
691                 if (semaphores[i]) {
692                     this->insertSemaphore(semaphores[i].get());
693                     info.fSignalSemaphores[i] = semaphores[i]->backendSemaphore();
694                 }
695             }
696         }
697     }
698 
699     if (info.fFinishedProc) {
700         this->addFinishedProc(info.fFinishedProc, info.fFinishedContext);
701     }
702 
703     if (info.fSubmittedProc) {
704         fSubmittedProcs.emplace_back(info.fSubmittedProc, info.fSubmittedContext);
705     }
706 
707     // We currently don't support passing in new surface state for multiple proxies here. The only
708     // time we have multiple proxies is if we are flushing a yuv SkImage which won't have state
709     // updates anyways.
710     SkASSERT(!newState || proxies.size() == 1);
711     SkASSERT(!newState || access == SkSurface::BackendSurfaceAccess::kNoAccess);
712     this->prepareSurfacesForBackendAccessAndStateUpdates(proxies, access, newState);
713 }
714 
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)715 GrOpsRenderPass* GrGpu::getOpsRenderPass(
716         GrRenderTarget* renderTarget,
717         bool useMSAASurface,
718         GrAttachment* stencil,
719         GrSurfaceOrigin origin,
720         const SkIRect& bounds,
721         const GrOpsRenderPass::LoadAndStoreInfo& colorInfo,
722         const GrOpsRenderPass::StencilLoadAndStoreInfo& stencilInfo,
723         const SkTArray<GrSurfaceProxy*, true>& sampledProxies,
724         GrXferBarrierFlags renderPassXferBarriers) {
725 #if SK_HISTOGRAMS_ENABLED
726     fCurrentSubmitRenderPassCount++;
727 #endif
728     fStats.incRenderPasses();
729     return this->onGetOpsRenderPass(renderTarget, useMSAASurface, stencil, origin, bounds,
730                                     colorInfo, stencilInfo, sampledProxies, renderPassXferBarriers);
731 }
732 
submitToGpu(bool syncCpu)733 bool GrGpu::submitToGpu(bool syncCpu) {
734     this->stats()->incNumSubmitToGpus();
735 
736     if (auto manager = this->stagingBufferManager()) {
737         manager->detachBuffers();
738     }
739 
740     if (auto uniformsBuffer = this->uniformsRingBuffer()) {
741         uniformsBuffer->startSubmit(this);
742     }
743 
744     bool submitted = this->onSubmitToGpu(syncCpu);
745 
746     this->callSubmittedProcs(submitted);
747 
748     this->reportSubmitHistograms();
749 
750     return submitted;
751 }
752 
reportSubmitHistograms()753 void GrGpu::reportSubmitHistograms() {
754 #if SK_HISTOGRAMS_ENABLED
755     // The max allowed value for SK_HISTOGRAM_EXACT_LINEAR is 100. If we want to support higher
756     // values we can add SK_HISTOGRAM_CUSTOM_COUNTS but this has a number of buckets that is less
757     // than the number of actual values
758     static constexpr int kMaxRenderPassBucketValue = 100;
759     SK_HISTOGRAM_EXACT_LINEAR("SubmitRenderPasses",
760                               std::min(fCurrentSubmitRenderPassCount, kMaxRenderPassBucketValue),
761                               kMaxRenderPassBucketValue);
762     fCurrentSubmitRenderPassCount = 0;
763 #endif
764 
765     this->onReportSubmitHistograms();
766 }
767 
checkAndResetOOMed()768 bool GrGpu::checkAndResetOOMed() {
769     if (fOOMed) {
770         fOOMed = false;
771         return true;
772     }
773     return false;
774 }
775 
callSubmittedProcs(bool success)776 void GrGpu::callSubmittedProcs(bool success) {
777     for (int i = 0; i < fSubmittedProcs.count(); ++i) {
778         fSubmittedProcs[i].fProc(fSubmittedProcs[i].fContext, success);
779     }
780     fSubmittedProcs.reset();
781 }
782 
783 #ifdef SK_ENABLE_DUMP_GPU
784 #include "src/utils/SkJSONWriter.h"
785 
dumpJSON(SkJSONWriter * writer) const786 void GrGpu::dumpJSON(SkJSONWriter* writer) const {
787     writer->beginObject();
788 
789     // TODO: Is there anything useful in the base class to dump here?
790 
791     this->onDumpJSON(writer);
792 
793     writer->endObject();
794 }
795 #else
dumpJSON(SkJSONWriter * writer) const796 void GrGpu::dumpJSON(SkJSONWriter* writer) const { }
797 #endif
798 
799 #if GR_TEST_UTILS
800 
801 #if GR_GPU_STATS
802 
dump(SkString * out)803 void GrGpu::Stats::dump(SkString* out) {
804     out->appendf("Textures Created: %d\n", fTextureCreates);
805     out->appendf("Texture Uploads: %d\n", fTextureUploads);
806     out->appendf("Transfers to Texture: %d\n", fTransfersToTexture);
807     out->appendf("Transfers from Surface: %d\n", fTransfersFromSurface);
808     out->appendf("Stencil Buffer Creates: %d\n", fStencilAttachmentCreates);
809     out->appendf("MSAA Attachment Creates: %d\n", fMSAAAttachmentCreates);
810     out->appendf("Number of draws: %d\n", fNumDraws);
811     out->appendf("Number of Scratch Textures reused %d\n", fNumScratchTexturesReused);
812     out->appendf("Number of Scratch MSAA Attachments reused %d\n",
813                  fNumScratchMSAAAttachmentsReused);
814     out->appendf("Number of Render Passes: %d\n", fRenderPasses);
815     out->appendf("Reordered DAGs Over Budget: %d\n", fNumReorderedDAGsOverBudget);
816 
817     // enable this block to output CSV-style stats for program pre-compilation
818 #if 0
819     SkASSERT(fNumInlineCompilationFailures == 0);
820     SkASSERT(fNumPreCompilationFailures == 0);
821     SkASSERT(fNumCompilationFailures == 0);
822     SkASSERT(fNumPartialCompilationSuccesses == 0);
823 
824     SkDebugf("%d, %d, %d, %d, %d\n",
825              fInlineProgramCacheStats[(int) Stats::ProgramCacheResult::kHit],
826              fInlineProgramCacheStats[(int) Stats::ProgramCacheResult::kMiss],
827              fPreProgramCacheStats[(int) Stats::ProgramCacheResult::kHit],
828              fPreProgramCacheStats[(int) Stats::ProgramCacheResult::kMiss],
829              fNumCompilationSuccesses);
830 #endif
831 }
832 
dumpKeyValuePairs(SkTArray<SkString> * keys,SkTArray<double> * values)833 void GrGpu::Stats::dumpKeyValuePairs(SkTArray<SkString>* keys, SkTArray<double>* values) {
834     keys->push_back(SkString("render_passes"));
835     values->push_back(fRenderPasses);
836     keys->push_back(SkString("reordered_dags_over_budget"));
837     values->push_back(fNumReorderedDAGsOverBudget);
838 }
839 
840 #endif // GR_GPU_STATS
841 #endif // GR_TEST_UTILS
842 
CompressedDataIsCorrect(SkISize dimensions,SkImage::CompressionType compressionType,GrMipmapped mipMapped,const void * data,size_t length)843 bool GrGpu::CompressedDataIsCorrect(SkISize dimensions,
844                                     SkImage::CompressionType compressionType,
845                                     GrMipmapped mipMapped,
846                                     const void* data,
847                                     size_t length) {
848     size_t computedSize = SkCompressedDataSize(compressionType,
849                                                dimensions,
850                                                nullptr,
851                                                mipMapped == GrMipmapped::kYes);
852     return computedSize == length;
853 }
854 
createBackendTexture(SkISize dimensions,const GrBackendFormat & format,GrRenderable renderable,GrMipmapped mipMapped,GrProtected isProtected)855 GrBackendTexture GrGpu::createBackendTexture(SkISize dimensions,
856                                              const GrBackendFormat& format,
857                                              GrRenderable renderable,
858                                              GrMipmapped mipMapped,
859                                              GrProtected isProtected) {
860     const GrCaps* caps = this->caps();
861 
862     if (!format.isValid()) {
863         return {};
864     }
865 
866     if (caps->isFormatCompressed(format)) {
867         // Compressed formats must go through the createCompressedBackendTexture API
868         return {};
869     }
870 
871     if (dimensions.isEmpty() || dimensions.width()  > caps->maxTextureSize() ||
872                                 dimensions.height() > caps->maxTextureSize()) {
873         return {};
874     }
875 
876     if (mipMapped == GrMipmapped::kYes && !this->caps()->mipmapSupport()) {
877         return {};
878     }
879 
880     return this->onCreateBackendTexture(dimensions, format, renderable, mipMapped, isProtected);
881 }
882 
clearBackendTexture(const GrBackendTexture & backendTexture,sk_sp<GrRefCntedCallback> finishedCallback,std::array<float,4> color)883 bool GrGpu::clearBackendTexture(const GrBackendTexture& backendTexture,
884                                 sk_sp<GrRefCntedCallback> finishedCallback,
885                                 std::array<float, 4> color) {
886     if (!backendTexture.isValid()) {
887         return false;
888     }
889 
890     if (backendTexture.hasMipmaps() && !this->caps()->mipmapSupport()) {
891         return false;
892     }
893 
894     return this->onClearBackendTexture(backendTexture, std::move(finishedCallback), color);
895 }
896 
createCompressedBackendTexture(SkISize dimensions,const GrBackendFormat & format,GrMipmapped mipMapped,GrProtected isProtected)897 GrBackendTexture GrGpu::createCompressedBackendTexture(SkISize dimensions,
898                                                        const GrBackendFormat& format,
899                                                        GrMipmapped mipMapped,
900                                                        GrProtected isProtected) {
901     const GrCaps* caps = this->caps();
902 
903     if (!format.isValid()) {
904         return {};
905     }
906 
907     SkImage::CompressionType compressionType = GrBackendFormatToCompressionType(format);
908     if (compressionType == SkImage::CompressionType::kNone) {
909         // Uncompressed formats must go through the createBackendTexture API
910         return {};
911     }
912 
913     if (dimensions.isEmpty() ||
914         dimensions.width()  > caps->maxTextureSize() ||
915         dimensions.height() > caps->maxTextureSize()) {
916         return {};
917     }
918 
919     if (mipMapped == GrMipmapped::kYes && !this->caps()->mipmapSupport()) {
920         return {};
921     }
922 
923     return this->onCreateCompressedBackendTexture(dimensions, format, mipMapped, isProtected);
924 }
925 
updateCompressedBackendTexture(const GrBackendTexture & backendTexture,sk_sp<GrRefCntedCallback> finishedCallback,const void * data,size_t length)926 bool GrGpu::updateCompressedBackendTexture(const GrBackendTexture& backendTexture,
927                                            sk_sp<GrRefCntedCallback> finishedCallback,
928                                            const void* data,
929                                            size_t length) {
930     SkASSERT(data);
931 
932     if (!backendTexture.isValid()) {
933         return false;
934     }
935 
936     GrBackendFormat format = backendTexture.getBackendFormat();
937 
938     SkImage::CompressionType compressionType = GrBackendFormatToCompressionType(format);
939     if (compressionType == SkImage::CompressionType::kNone) {
940         // Uncompressed formats must go through the createBackendTexture API
941         return false;
942     }
943 
944     if (backendTexture.hasMipmaps() && !this->caps()->mipmapSupport()) {
945         return false;
946     }
947 
948     GrMipmapped mipMapped = backendTexture.hasMipmaps() ? GrMipmapped::kYes : GrMipmapped::kNo;
949 
950     if (!CompressedDataIsCorrect(backendTexture.dimensions(),
951                                  compressionType,
952                                  mipMapped,
953                                  data,
954                                  length)) {
955         return false;
956     }
957 
958     return this->onUpdateCompressedBackendTexture(backendTexture,
959                                                   std::move(finishedCallback),
960                                                   data,
961                                                   length);
962 }
963