1/* 2 * Copyright 2021 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#include "experimental/graphite/src/mtl/MtlBuffer.h" 9 10#include "experimental/graphite/src/mtl/MtlGpu.h" 11 12namespace skgpu::mtl { 13 14#ifdef SK_ENABLE_MTL_DEBUG_INFO 15NSString* kBufferTypeNames[kBufferTypeCount] = { 16 @"Vertex", 17 @"Index", 18 @"Xfer CPU to GPU", 19 @"Xfer GPU to CPU", 20 @"Uniform", 21}; 22#endif 23 24sk_sp<Buffer> Buffer::Make(const Gpu* gpu, 25 size_t size, 26 BufferType type, 27 PrioritizeGpuReads prioritizeGpuReads) { 28 if (size <= 0) { 29 return nullptr; 30 } 31 32 const Caps& mtlCaps = gpu->mtlCaps(); 33 34 NSUInteger options = 0; 35 if (@available(macOS 10.11, iOS 9.0, *)) { 36 if (prioritizeGpuReads == PrioritizeGpuReads::kNo) { 37#ifdef SK_BUILD_FOR_MAC 38 if (mtlCaps.isMac()) { 39 options |= MTLResourceStorageModeManaged; 40 } else { 41 SkASSERT(mtlCaps.isApple()); 42 options |= MTLResourceStorageModeShared; 43 } 44#else 45 options |= MTLResourceStorageModeShared; 46#endif 47 } else { 48 options |= MTLResourceStorageModePrivate; 49 } 50 } 51 52 size = SkAlignTo(size, mtlCaps.getMinBufferAlignment()); 53 sk_cfp<id<MTLBuffer>> buffer([gpu->device() newBufferWithLength: size options: options]); 54#ifdef SK_ENABLE_MTL_DEBUG_INFO 55 (*buffer).label = kBufferTypeNames[(int)type]; 56#endif 57 58 return sk_sp<Buffer>(new Buffer(size, type, prioritizeGpuReads, std::move(buffer))); 59} 60 61Buffer::Buffer(size_t size, 62 BufferType type, 63 PrioritizeGpuReads prioritizeGpuReads, 64 sk_cfp<id<MTLBuffer>> buffer) 65 : skgpu::Buffer(size, type, prioritizeGpuReads) 66 , fBuffer(std::move(buffer)) {} 67 68void Buffer::onMap() { 69 SkASSERT(fBuffer); 70 SkASSERT(!this->isMapped()); 71 72 if ((*fBuffer).storageMode == MTLStorageModePrivate) { 73 return; 74 } 75 76 fMapPtr = static_cast<char*>((*fBuffer).contents); 77} 78 79void Buffer::onUnmap() { 80 SkASSERT(fBuffer); 81 SkASSERT(this->isMapped()); 82#ifdef SK_BUILD_FOR_MAC 83 if ((*fBuffer).storageMode == MTLStorageModeManaged) { 84 [*fBuffer didModifyRange: NSMakeRange(0, this->size())]; 85 } 86#endif 87 fMapPtr = nullptr; 88} 89 90} // namespace skgpu::mtl 91 92