./
Coverage:
low: ≥ 0%
medium: ≥ 75.0%
high: ≥ 90.0%
Lines:
2 / 10
20.0%
Branches:
1 / 3
33.3%
Functions:
1 / 6
16.7%

src/gpu/metal.cpp
Line Branch Exec Source
1 // SPDX-License-Identifier: BSD-3-Clause
2
3 #include "gpu/metal.h"
4
5 #include <stdexcept>
6 #include <utility>
7
8 // On Apple platforms CMake compiles this file as Objective-C++ (with ARC) against the system Metal
9 // framework; elsewhere it is C++ and only the stub below, which reports Metal unavailable, builds.
10 #if defined(__APPLE__)
11
12 #import <Foundation/Foundation.h>
13 #import <Metal/Metal.h>
14
15 #include <algorithm>
16 #include <cstring>
17 #include <map>
18 #include <mutex>
19 #include <vector>
20
21 namespace terraingen {
22
23 /// The device, its command queue and the pipelines of compiled sources. Compiled with ARC, so the
24 /// Objective-C objects are released with the state.
25 struct MetalCompute::State {
26 id<MTLDevice> device = nil;
27 id<MTLCommandQueue> queue = nil;
28 std::string name;
29 std::mutex mutex;
30 /// Pipelines keyed by their source, which lives for the whole process.
31 std::map<const char*, id<MTLComputePipelineState>> pipelines;
32
33 /// Opens the system's default device and a command queue.
34 void Open() {
35 device = MTLCreateSystemDefaultDevice();
36 if (device == nil) {
37 throw std::runtime_error("no Metal device");
38 }
39 queue = [device newCommandQueue];
40 if (queue == nil) {
41 throw std::runtime_error("Metal command queue creation failed");
42 }
43 name = [[device name] UTF8String];
44 }
45
46 /// IEEE math with precise library functions. Metal's default fast math reassociates
47 /// arithmetic, which drops the low halves of split floats (`SplitDifference`) and moves
48 /// craters on a body by tenths of a meter.
49 static MTLCompileOptions* CompileOptions() {
50 MTLCompileOptions* options = [[MTLCompileOptions alloc] init];
51 options.mathMode = MTLMathModeSafe;
52 options.mathFloatingPointFunctions = MTLMathFloatingPointFunctionsPrecise;
53 return options;
54 }
55
56 /// The pipeline of `source`, compiled on first use.
57 id<MTLComputePipelineState> CachedPipeline(Span<const char> source) {
58 const auto found = pipelines.find(source.data());
59 if (found != pipelines.end()) {
60 return found->second;
61 }
62 NSString* text = [[NSString alloc] initWithBytes:source.data()
63 length:source.size()
64 encoding:NSUTF8StringEncoding];
65 NSError* error = nil;
66 id<MTLLibrary> library =
67 [device newLibraryWithSource:text options:CompileOptions() error:&error];
68 if (library == nil) {
69 throw std::runtime_error(std::string("Metal kernel compilation failed: ") +
70 [[error localizedDescription] UTF8String]);
71 }
72 id<MTLFunction> function = [library newFunctionWithName:@"main_0"];
73 if (function == nil) {
74 throw std::runtime_error("The Metal kernel has no main_0");
75 }
76 id<MTLComputePipelineState> pipeline =
77 [device newComputePipelineStateWithFunction:function error:&error];
78 if (pipeline == nil) {
79 throw std::runtime_error(std::string("Metal pipeline creation failed: ") +
80 [[error localizedDescription] UTF8String]);
81 }
82 return pipelines.emplace(source.data(), pipeline).first->second;
83 }
84
85 /// A shared device buffer holding a copy of each host buffer.
86 std::vector<id<MTLBuffer>> Upload(Span<const DeviceBuffer> buffers) const {
87 std::vector<id<MTLBuffer>> deviceBuffers;
88 for (const DeviceBuffer& buffer : buffers) {
89 id<MTLBuffer> deviceBuffer =
90 [device newBufferWithBytes:buffer.bytes.data()
91 length:std::max<std::size_t>(buffer.bytes.size(), 4)
92 options:MTLResourceStorageModeShared];
93 if (deviceBuffer == nil) {
94 throw std::runtime_error("Metal buffer allocation failed");
95 }
96 deviceBuffers.push_back(deviceBuffer);
97 }
98 return deviceBuffers;
99 }
100
101 /// Encodes the dispatch, binding the buffers in order and the push constants after them,
102 /// and waits for it to complete.
103 void DispatchAndWait(id<MTLComputePipelineState> pipeline,
104 const std::vector<id<MTLBuffer>>& deviceBuffers,
105 Span<const std::byte> pushConstants, const Dispatch& dispatch) const {
106 const auto& [groups, size] = dispatch;
107 id<MTLCommandBuffer> command = [queue commandBuffer];
108 id<MTLComputeCommandEncoder> encoder = [command computeCommandEncoder];
109 [encoder setComputePipelineState:pipeline];
110 for (std::size_t i = 0; i < deviceBuffers.size(); ++i) {
111 [encoder setBuffer:deviceBuffers[i] offset:0 atIndex:i];
112 }
113 [encoder setBytes:pushConstants.data()
114 length:pushConstants.size()
115 atIndex:deviceBuffers.size()];
116 [encoder dispatchThreadgroups:MTLSizeMake(groups[0], groups[1], groups[2])
117 threadsPerThreadgroup:MTLSizeMake(size[0], size[1], size[2])];
118 [encoder endEncoding];
119 [command commit];
120 [command waitUntilCompleted];
121 if ([command status] != MTLCommandBufferStatusCompleted) {
122 throw std::runtime_error("The Metal kernel failed");
123 }
124 }
125 };
126
127 std::unique_ptr<MetalCompute> MetalCompute::Open() {
128 auto state = std::make_unique<State>();
129 state->Open();
130 return std::unique_ptr<MetalCompute>(new MetalCompute(std::move(state)));
131 }
132
133 const std::string& MetalCompute::DeviceName() const {
134 return m_state->name;
135 }
136
137 void MetalCompute::Run(const KernelProgram& program, Span<const DeviceBuffer> buffers,
138 Span<const std::byte> pushConstants, const Dispatch& dispatch) {
139 if (!CanRun(program)) {
140 throw std::runtime_error("The kernel has no Metal source");
141 }
142 State& s = *m_state;
143 const std::lock_guard lock(s.mutex);
144 @autoreleasepool {
145 id<MTLComputePipelineState> pipeline = s.CachedPipeline(program.metal);
146 const std::vector<id<MTLBuffer>> deviceBuffers = s.Upload(buffers);
147 s.DispatchAndWait(pipeline, deviceBuffers, pushConstants, dispatch);
148 for (std::size_t i = 0; i < buffers.size(); ++i) {
149 if (buffers[i].output != nullptr) {
150 std::memcpy(buffers[i].output, [deviceBuffers[i] contents],
151 buffers[i].bytes.size());
152 }
153 }
154 }
155 }
156
157 } // namespace terraingen
158
159 #else
160
161 namespace terraingen {
162
163 struct MetalCompute::State {};
164
165 24 std::unique_ptr<MetalCompute> MetalCompute::Open() {
166
1/1
✓ Branch 2 taken 24 times.
24 throw std::runtime_error("Metal runs only on Apple platforms");
167 }
168
169 ✗ const std::string& MetalCompute::DeviceName() const {
170
0/1
✗ Branch 2 not taken.
✗ throw std::runtime_error("Metal is unavailable on this platform");
171 }
172
173 ✗ void MetalCompute::Run(const KernelProgram& /*program*/, Span<const DeviceBuffer> /*buffers*/,
174 Span<const std::byte> /*pushConstants*/, const Dispatch& /*dispatch*/) {
175
0/1
✗ Branch 2 not taken.
✗ throw std::runtime_error("Metal is unavailable on this platform");
176 }
177
178 } // namespace terraingen
179
180 #endif
181
182 namespace terraingen {
183
184 ✗ MetalCompute::MetalCompute(std::unique_ptr<State> state) : m_state(std::move(state)) {}
185
186 ✗ MetalCompute::~MetalCompute() = default;
187
188 ✗ bool MetalCompute::CanRun(const KernelProgram& program) const {
189 ✗ return !program.metal.empty();
190 }
191
192 } // namespace terraingen
193