xref: /aosp_15_r20/external/skia/src/gpu/graphite/mtl/MtlBuffer.mm (revision c8dee2aa9b3f27cf6c858bd81872bdeb2c07ed17)
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 "src/gpu/graphite/mtl/MtlBuffer.h"
9
10#include "include/private/base/SkAlign.h"
11#include "src/gpu/graphite/mtl/MtlSharedContext.h"
12
13namespace skgpu::graphite {
14
15sk_sp<Buffer> MtlBuffer::Make(const MtlSharedContext* sharedContext,
16                              size_t size,
17                              BufferType type,
18                              AccessPattern accessPattern) {
19    if (size <= 0) {
20        return nullptr;
21    }
22
23    NSUInteger options = 0;
24    if (@available(macOS 10.11, iOS 9.0, tvOS 9.0, *)) {
25        if (accessPattern == AccessPattern::kHostVisible) {
26#ifdef SK_BUILD_FOR_MAC
27            const MtlCaps& mtlCaps = sharedContext->mtlCaps();
28            if (mtlCaps.isMac()) {
29                options |= MTLResourceStorageModeManaged;
30            } else {
31                SkASSERT(mtlCaps.isApple());
32                options |= MTLResourceStorageModeShared;
33            }
34#else
35            options |= MTLResourceStorageModeShared;
36#endif
37        } else {
38            options |= MTLResourceStorageModePrivate;
39        }
40    }
41
42    sk_cfp<id<MTLBuffer>> buffer([sharedContext->device() newBufferWithLength:size
43                                                                      options:options]);
44
45    return sk_sp<Buffer>(new MtlBuffer(sharedContext, size, std::move(buffer)));
46}
47
48MtlBuffer::MtlBuffer(const MtlSharedContext* sharedContext,
49                     size_t size,
50                     sk_cfp<id<MTLBuffer>> buffer)
51        : Buffer(sharedContext,
52                 size,
53                 Protected::kNo)  // Metal doesn't support protected memory
54        , fBuffer(std::move(buffer)) {}
55
56void MtlBuffer::onMap() {
57    SkASSERT(fBuffer);
58    SkASSERT(!this->isMapped());
59
60    if ((*fBuffer).storageMode == MTLStorageModePrivate) {
61        return;
62    }
63
64    fMapPtr = static_cast<char*>((*fBuffer).contents);
65}
66
67void MtlBuffer::onUnmap() {
68    SkASSERT(fBuffer);
69    SkASSERT(this->isMapped());
70#ifdef SK_BUILD_FOR_MAC
71    if ((*fBuffer).storageMode == MTLStorageModeManaged) {
72        [*fBuffer didModifyRange: NSMakeRange(0, this->size())];
73    }
74#endif
75    fMapPtr = nullptr;
76}
77
78void MtlBuffer::freeGpuData() {
79    fBuffer.reset();
80}
81
82void MtlBuffer::setBackendLabel(char const* label) {
83    SkASSERT(label);
84#ifdef SK_ENABLE_MTL_DEBUG_INFO
85    NSString* labelStr = @(label);
86    this->mtlBuffer().label = labelStr;
87#endif
88}
89
90} // namespace skgpu::graphite
91