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