6 #include <Metal/Metal.h>
10 #include "flutter/fml/concurrent_message_loop.h"
11 #include "flutter/fml/file.h"
12 #include "flutter/fml/logging.h"
13 #include "flutter/fml/paths.h"
14 #include "flutter/fml/synchronization/sync_switch.h"
26 #if FML_OS_IOS_SIMULATOR
30 if (@available(macOS 10.15, iOS 13, tvOS 13, *)) {
31 return [device supportsFamily:MTLGPUFamilyApple2];
37 return [device supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily2_v1];
45 bool supports_subgroups =
false;
48 if (@available(ios 13.0, tvos 13.0, macos 10.15, *)) {
49 supports_subgroups = [device supportsFamily:MTLGPUFamilyApple7] ||
50 [device supportsFamily:MTLGPUFamilyMac2];
52 return supports_subgroups;
77 ContextMTL::ContextMTL(
79 id<MTLCommandQueue> command_queue,
80 NSArray<id<MTLLibrary>>* shader_libraries,
81 std::shared_ptr<const fml::SyncSwitch> is_gpu_disabled_sync_switch,
82 std::optional<PixelFormat> pixel_format_override)
84 command_queue_(command_queue),
85 is_gpu_disabled_sync_switch_(
std::move(is_gpu_disabled_sync_switch)) {
92 sync_switch_observer_.reset(
new SyncSwitchObserver(*
this));
93 is_gpu_disabled_sync_switch_->AddObserver(sync_switch_observer_.get());
97 if (shader_libraries == nil) {
103 auto library = std::shared_ptr<ShaderLibraryMTL>(
104 new ShaderLibraryMTL(shader_libraries));
105 if (!library->IsValid()) {
109 shader_library_ = std::move(library);
115 std::shared_ptr<PipelineLibraryMTL>(
new PipelineLibraryMTL(device_));
121 std::shared_ptr<SamplerLibraryMTL>(
new SamplerLibraryMTL(device_));
126 resource_allocator_ = std::shared_ptr<AllocatorMTL>(
127 new AllocatorMTL(device_,
"Impeller Permanents Allocator"));
128 if (!resource_allocator_) {
134 device_capabilities_ =
136 ? pixel_format_override.value()
138 command_queue_ip_ = std::make_shared<CommandQueue>();
139 #ifdef IMPELLER_DEBUG
140 gpu_tracer_ = std::make_shared<GPUTracerMTL>();
141 capture_manager_ = std::make_shared<ImpellerMetalCaptureManager>(device_);
147 id<MTLDevice> device,
148 const std::vector<std::string>& libraries_paths) {
149 NSMutableArray<id<MTLLibrary>>* found_libraries = [NSMutableArray array];
150 for (
const auto& library_path : libraries_paths) {
151 if (!fml::IsFile(library_path)) {
153 << library_path <<
"'";
156 NSError* shader_library_error = nil;
157 auto library = [device newLibraryWithFile:@(library_path.c_str())
158 error:&shader_library_error];
160 FML_LOG(ERROR) <<
"Could not create shader library: "
161 << shader_library_error.localizedDescription.UTF8String;
164 [found_libraries addObject:library];
166 return found_libraries;
170 id<MTLDevice> device,
171 const std::vector<std::shared_ptr<fml::Mapping>>& libraries_data,
172 const std::string& label) {
173 NSMutableArray<id<MTLLibrary>>* found_libraries = [NSMutableArray array];
174 for (
const auto& library_data : libraries_data) {
175 if (library_data ==
nullptr) {
176 FML_LOG(ERROR) <<
"Shader library data was null.";
180 __block
auto data = library_data;
183 ::dispatch_data_create(library_data->GetMapping(),
184 library_data->GetSize(),
185 dispatch_get_main_queue(),
191 if (!dispatch_data) {
192 FML_LOG(ERROR) <<
"Could not wrap shader data in dispatch data.";
196 NSError* shader_library_error = nil;
197 auto library = [device newLibraryWithData:dispatch_data
198 error:&shader_library_error];
200 FML_LOG(ERROR) <<
"Could not create shader library: "
201 << shader_library_error.localizedDescription.UTF8String;
204 if (!label.empty()) {
205 library.label = @(label.c_str());
207 [found_libraries addObject:library];
209 return found_libraries;
213 return ::MTLCreateSystemDefaultDevice();
217 auto command_queue = device.newCommandQueue;
218 if (!command_queue) {
222 command_queue.label =
@"Impeller Command Queue";
223 return command_queue;
227 const std::vector<std::string>& shader_library_paths,
228 std::shared_ptr<const fml::SyncSwitch> is_gpu_disabled_sync_switch) {
231 if (!command_queue) {
234 auto context = std::shared_ptr<ContextMTL>(
new ContextMTL(
235 device, command_queue,
237 std::move(is_gpu_disabled_sync_switch)));
238 if (!context->IsValid()) {
239 FML_LOG(ERROR) <<
"Could not create Metal context.";
246 const std::vector<std::shared_ptr<fml::Mapping>>& shader_libraries_data,
247 std::shared_ptr<const fml::SyncSwitch> is_gpu_disabled_sync_switch,
248 const std::string& library_label,
249 std::optional<PixelFormat> pixel_format_override) {
252 if (!command_queue) {
255 auto context = std::shared_ptr<ContextMTL>(
new ContextMTL(
256 device, command_queue,
259 std::move(is_gpu_disabled_sync_switch), pixel_format_override));
260 if (!context->IsValid()) {
261 FML_LOG(ERROR) <<
"Could not create Metal context.";
268 id<MTLDevice> device,
269 id<MTLCommandQueue> command_queue,
270 const std::vector<std::shared_ptr<fml::Mapping>>& shader_libraries_data,
271 std::shared_ptr<const fml::SyncSwitch> is_gpu_disabled_sync_switch,
272 const std::string& library_label) {
273 auto context = std::shared_ptr<ContextMTL>(
277 std::move(is_gpu_disabled_sync_switch)));
278 if (!context->IsValid()) {
279 FML_LOG(ERROR) <<
"Could not create Metal context.";
285 ContextMTL::~ContextMTL() {
286 is_gpu_disabled_sync_switch_->RemoveObserver(sync_switch_observer_.get());
290 return Context::BackendType::kMetal;
294 std::string ContextMTL::DescribeGpuModel()
const {
295 return std::string([[device_ name] UTF8String]);
299 bool ContextMTL::IsValid()
const {
304 std::shared_ptr<ShaderLibrary> ContextMTL::GetShaderLibrary()
const {
305 return shader_library_;
309 std::shared_ptr<PipelineLibrary> ContextMTL::GetPipelineLibrary()
const {
310 return pipeline_library_;
314 std::shared_ptr<SamplerLibrary> ContextMTL::GetSamplerLibrary()
const {
315 return sampler_library_;
320 return CreateCommandBufferInQueue(command_queue_);
324 void ContextMTL::Shutdown() {}
326 #ifdef IMPELLER_DEBUG
327 std::shared_ptr<GPUTracerMTL> ContextMTL::GetGPUTracer()
const {
332 std::shared_ptr<const fml::SyncSwitch> ContextMTL::GetIsGpuDisabledSyncSwitch()
334 return is_gpu_disabled_sync_switch_;
337 std::shared_ptr<CommandBuffer> ContextMTL::CreateCommandBufferInQueue(
338 id<MTLCommandQueue> queue)
const {
343 auto buffer = std::shared_ptr<CommandBufferMTL>(
344 new CommandBufferMTL(weak_from_this(), device_, queue));
345 if (!buffer->IsValid()) {
351 std::shared_ptr<Allocator> ContextMTL::GetResourceAllocator()
const {
352 return resource_allocator_;
355 id<MTLDevice> ContextMTL::GetMTLDevice()
const {
359 const std::shared_ptr<const Capabilities>& ContextMTL::GetCapabilities()
const {
360 return device_capabilities_;
363 void ContextMTL::SetCapabilities(
364 const std::shared_ptr<const Capabilities>& capabilities) {
365 device_capabilities_ = capabilities;
369 bool ContextMTL::UpdateOffscreenLayerPixelFormat(
PixelFormat format) {
374 id<MTLCommandBuffer> ContextMTL::CreateMTLCommandBuffer(
375 const std::string& label)
const {
376 auto buffer = [command_queue_ commandBuffer];
377 if (!label.empty()) {
378 [buffer setLabel:@(label.data())];
383 void ContextMTL::StoreTaskForGPU(
const fml::closure& task,
384 const fml::closure& failure) {
385 std::vector<PendingTasks> failed_tasks;
387 Lock lock(tasks_awaiting_gpu_mutex_);
388 tasks_awaiting_gpu_.push_back(PendingTasks{task, failure});
389 int32_t failed_task_count =
390 tasks_awaiting_gpu_.size() - kMaxTasksAwaitingGPU;
391 if (failed_task_count > 0) {
392 failed_tasks.reserve(failed_task_count);
393 failed_tasks.insert(failed_tasks.end(),
394 std::make_move_iterator(tasks_awaiting_gpu_.begin()),
395 std::make_move_iterator(tasks_awaiting_gpu_.begin() +
397 tasks_awaiting_gpu_.erase(
398 tasks_awaiting_gpu_.begin(),
399 tasks_awaiting_gpu_.begin() + failed_task_count);
402 for (
const PendingTasks& task : failed_tasks) {
409 void ContextMTL::FlushTasksAwaitingGPU() {
410 std::deque<PendingTasks> tasks_awaiting_gpu;
412 Lock lock(tasks_awaiting_gpu_mutex_);
413 std::swap(tasks_awaiting_gpu, tasks_awaiting_gpu_);
415 for (
const auto& task : tasks_awaiting_gpu) {
420 ContextMTL::SyncSwitchObserver::SyncSwitchObserver(ContextMTL& parent)
423 void ContextMTL::SyncSwitchObserver::OnSyncSwitchUpdate(
bool new_is_disabled) {
424 if (!new_is_disabled) {
425 parent_.FlushTasksAwaitingGPU();
431 return command_queue_ip_;
439 #ifdef IMPELLER_DEBUG
440 const std::shared_ptr<ImpellerMetalCaptureManager>
441 ContextMTL::GetCaptureManager()
const {
442 return capture_manager_;
447 current_capture_scope_ = [[MTLCaptureManager sharedCaptureManager]
448 newCaptureScopeWithDevice:device];
449 [current_capture_scope_ setLabel:
@"Impeller Frame"];
453 return scope_active_;
460 scope_active_ =
true;
461 [current_capture_scope_ beginScope];
465 FML_DCHECK(scope_active_);
466 [current_capture_scope_ endScope];
467 scope_active_ =
false;
CapabilitiesBuilder & SetDefaultColorFormat(PixelFormat value)
CapabilitiesBuilder & SetSupportsComputeSubgroups(bool value)
CapabilitiesBuilder & SetSupportsTextureToTextureBlits(bool value)
CapabilitiesBuilder & SetDefaultStencilFormat(PixelFormat value)
CapabilitiesBuilder & SetSupportsDeviceTransientTextures(bool value)
CapabilitiesBuilder & SetSupportsTriangleFan(bool value)
CapabilitiesBuilder & SetSupportsFramebufferFetch(bool value)
CapabilitiesBuilder & SetSupportsDecalSamplerAddressMode(bool value)
CapabilitiesBuilder & SetSupportsOffscreenMSAA(bool value)
CapabilitiesBuilder & SetSupportsSSBO(bool value)
CapabilitiesBuilder & SetMaximumRenderPassAttachmentSize(ISize size)
CapabilitiesBuilder & SetDefaultGlyphAtlasFormat(PixelFormat value)
CapabilitiesBuilder & SetSupportsCompute(bool value)
std::unique_ptr< Capabilities > Build()
CapabilitiesBuilder & SetDefaultDepthStencilFormat(PixelFormat value)
CapabilitiesBuilder & SetSupportsReadFromResolve(bool value)
std::shared_ptr< CommandQueue > GetCommandQueue() const override
Return the graphics queue for submitting command buffers.
RuntimeStageBackend GetRuntimeStageBackend() const override
Retrieve the runtime stage for this context type.
ScopedObject< Object > Create(CtorArgs &&... args)
static NSArray< id< MTLLibrary > > * MTLShaderLibraryFromFileData(id< MTLDevice > device, const std::vector< std::shared_ptr< fml::Mapping >> &libraries_data, const std::string &label)
static id< MTLDevice > CreateMetalDevice()
PixelFormat
The Pixel formats supported by Impeller. The naming convention denotes the usage of the component,...
ISize DeviceMaxTextureSizeSupported(id< MTLDevice > device)
static id< MTLCommandBuffer > CreateCommandBuffer(id< MTLCommandQueue > queue)
static NSArray< id< MTLLibrary > > * MTLShaderLibraryFromFilePaths(id< MTLDevice > device, const std::vector< std::string > &libraries_paths)
static id< MTLCommandQueue > CreateMetalCommandQueue(id< MTLDevice > device)
static std::unique_ptr< Capabilities > InferMetalCapabilities(id< MTLDevice > device, PixelFormat color_format)
static bool DeviceSupportsComputeSubgroups(id< MTLDevice > device)
static bool DeviceSupportsFramebufferFetch(id< MTLDevice > device)
std::shared_ptr< const fml::Mapping > data