Flutter Engine Uber Docs
Docs for the entire Flutter Engine repo.
 
Loading...
Searching...
No Matches
impeller::ContextMTL Class Referencefinal

#include <context_mtl.h>

Inheritance diagram for impeller::ContextMTL:
impeller::Context impeller::BackendCast< ContextMTL, Context >

Public Member Functions

 ~ContextMTL () override
 
BackendType GetBackendType () const override
 Get the graphics backend of an Impeller context.
 
id< MTLDevice > GetMTLDevice () const
 
std::string DescribeGpuModel () const override
 
bool IsValid () const override
 Determines if a context is valid. If the caller ever receives an invalid context, they must discard it and construct a new context. There is no recovery mechanism to repair a bad context.
 
std::shared_ptr< AllocatorGetResourceAllocator () const override
 Returns the allocator used to create textures and buffers on the device.
 
std::shared_ptr< ShaderLibraryGetShaderLibrary () const override
 Returns the library of shaders used to specify the programmable stages of a pipeline.
 
std::shared_ptr< SamplerLibraryGetSamplerLibrary () const override
 Returns the library of combined image samplers used in shaders.
 
std::shared_ptr< PipelineLibraryGetPipelineLibrary () const override
 Returns the library of pipelines used by render or compute commands.
 
std::shared_ptr< CommandBufferCreateCommandBuffer () const override
 Create a new command buffer. Command buffers can be used to encode graphics, blit, or compute commands to be submitted to the device.
 
std::shared_ptr< CommandQueueGetCommandQueue () const override
 Return the graphics queue for submitting command buffers.
 
const std::shared_ptr< const Capabilities > & GetCapabilities () const override
 Get the capabilities of Impeller context. All optionally supported feature of the platform, client-rendering API, and device can be queried using the Capabilities.
 
RuntimeStageBackend GetRuntimeStageBackend () const override
 Retrieve the runtime stage for this context type.
 
void SetCapabilities (const std::shared_ptr< const Capabilities > &capabilities)
 
bool UpdateOffscreenLayerPixelFormat (PixelFormat format) override
 
void Shutdown () override
 Force all pending asynchronous work to finish. This is achieved by deleting all owned concurrent message loops.
 
id< MTLCommandBuffer > CreateMTLCommandBuffer (const std::string &label) const
 
std::shared_ptr< const fml::SyncSwitchGetIsGpuDisabledSyncSwitch () const
 
void StoreTaskForGPU (const fml::closure &task, const fml::closure &failure) override
 
void FlushTasksAwaitingGPU ()
 
bool FinishQueue () override
 Wait until all previously submitted command buffers are processed and displayed by the GPU.
 
- Public Member Functions inherited from impeller::Context
virtual ~Context ()
 Destroys an Impeller context.
 
virtual void InitializeCommonlyUsedShadersIfNeeded () const
 
virtual void DisposeThreadLocalCachedResources ()
 
virtual bool EnqueueCommandBuffer (std::shared_ptr< CommandBuffer > command_buffer)
 Enqueue command_buffer for submission by the end of the frame.
 
virtual bool FlushCommandBuffers ()
 Flush all pending command buffers.
 
virtual bool AddTrackingFence (const std::shared_ptr< Texture > &texture) const
 
virtual std::shared_ptr< const IdleWaiterGetIdleWaiter () const
 
virtual void ResetThreadLocalState () const
 
virtual bool SubmitOnscreen (std::shared_ptr< CommandBuffer > cmd_buffer)
 Submit the command buffer that renders to the onscreen surface.
 
const FlagsGetFlags () const
 

Static Public Member Functions

static std::shared_ptr< ContextMTLCreate (const Flags &flags, const std::vector< std::string > &shader_library_paths, std::shared_ptr< const fml::SyncSwitch > is_gpu_disabled_sync_switch)
 
static std::shared_ptr< ContextMTLCreate (const Flags &flags, const std::vector< std::shared_ptr< fml::Mapping > > &shader_libraries_data, std::shared_ptr< const fml::SyncSwitch > is_gpu_disabled_sync_switch, const std::string &label, std::optional< PixelFormat > pixel_format_override=std::nullopt)
 
static std::shared_ptr< ContextMTLCreate (const Flags &flags, id< MTLDevice > device, id< MTLCommandQueue > command_queue, const std::vector< std::shared_ptr< fml::Mapping > > &shader_libraries_data, std::shared_ptr< const fml::SyncSwitch > is_gpu_disabled_sync_switch, const std::string &label)
 
- Static Public Member Functions inherited from impeller::BackendCast< ContextMTL, Context >
static ContextMTLCast (Context &base)
 
static const ContextMTLCast (const Context &base)
 
static ContextMTLCast (Context *base)
 
static const ContextMTLCast (const Context *base)
 

Additional Inherited Members

- Public Types inherited from impeller::Context
enum class  BackendType {
  kMetal ,
  kOpenGLES ,
  kVulkan
}
 
- Static Public Attributes inherited from impeller::Context
static constexpr int32_t kMaxTasksAwaitingGPU = 1024
 
- Protected Member Functions inherited from impeller::Context
 Context (const Flags &flags)
 
- Protected Attributes inherited from impeller::Context
Flags flags_
 
std::vector< std::function< void()> > per_frame_task_
 

Detailed Description

Definition at line 65 of file context_mtl.h.

Constructor & Destructor Documentation

◆ ~ContextMTL()

impeller::ContextMTL::~ContextMTL ( )
override

Definition at line 327 of file context_mtl.mm.

327 {
328 is_gpu_disabled_sync_switch_->RemoveObserver(sync_switch_observer_.get());
329}

Member Function Documentation

◆ Create() [1/3]

std::shared_ptr< ContextMTL > impeller::ContextMTL::Create ( const Flags flags,
const std::vector< std::shared_ptr< fml::Mapping > > &  shader_libraries_data,
std::shared_ptr< const fml::SyncSwitch is_gpu_disabled_sync_switch,
const std::string &  label,
std::optional< PixelFormat pixel_format_override = std::nullopt 
)
static

Definition at line 285 of file context_mtl.mm.

290 {
291 auto device = CreateMetalDevice();
292 auto command_queue = CreateMetalCommandQueue(device);
293 if (!command_queue) {
294 return nullptr;
295 }
296 auto context = std::shared_ptr<ContextMTL>(new ContextMTL(
297 flags, device, command_queue,
298 MTLShaderLibraryFromFileData(device, shader_libraries_data,
299 library_label),
300 std::move(is_gpu_disabled_sync_switch), pixel_format_override));
301 if (!context->IsValid()) {
302 FML_LOG(ERROR) << "Could not create Metal context.";
303 return nullptr;
304 }
305 return context;
306}
VkDevice device
Definition main.cc:69
#define FML_LOG(severity)
Definition logging.h:101
static id< MTLCommandQueue > CreateMetalCommandQueue(id< MTLDevice > device)
static id< MTLDevice > CreateMetalDevice()
static NSArray< id< MTLLibrary > > * MTLShaderLibraryFromFileData(id< MTLDevice > device, const std::vector< std::shared_ptr< fml::Mapping > > &libraries_data, const std::string &label)
std::shared_ptr< ContextGLES > context

References context, impeller::CreateMetalCommandQueue(), impeller::CreateMetalDevice(), device, FML_LOG, and impeller::MTLShaderLibraryFromFileData().

◆ Create() [2/3]

std::shared_ptr< ContextMTL > impeller::ContextMTL::Create ( const Flags flags,
const std::vector< std::string > &  shader_library_paths,
std::shared_ptr< const fml::SyncSwitch is_gpu_disabled_sync_switch 
)
static

Definition at line 265 of file context_mtl.mm.

268 {
269 auto device = CreateMetalDevice();
270 auto command_queue = CreateMetalCommandQueue(device);
271 if (!command_queue) {
272 return nullptr;
273 }
274 auto context = std::shared_ptr<ContextMTL>(new ContextMTL(
275 flags, device, command_queue,
276 MTLShaderLibraryFromFilePaths(device, shader_library_paths),
277 std::move(is_gpu_disabled_sync_switch)));
278 if (!context->IsValid()) {
279 FML_LOG(ERROR) << "Could not create Metal context.";
280 return nullptr;
281 }
282 return context;
283}
static NSArray< id< MTLLibrary > > * MTLShaderLibraryFromFilePaths(id< MTLDevice > device, const std::vector< std::string > &libraries_paths)

References context, impeller::CreateMetalCommandQueue(), impeller::CreateMetalDevice(), device, FML_LOG, and impeller::MTLShaderLibraryFromFilePaths().

Referenced by impeller::interop::ContextMTL::Create(), FlutterDarwinContextMetalImpeller::createExternalTextureWithIdentifier:texture:, flutter::testing::CreateImpellerContext(), CreateImpellerContext(), flutter::EmbedderSurfaceMetalImpeller::EmbedderSurfaceMetalImpeller(), flutter::TesterContextMTL::Initialize(), and impeller::PlaygroundImplMTL::PlaygroundImplMTL().

◆ Create() [3/3]

std::shared_ptr< ContextMTL > impeller::ContextMTL::Create ( const Flags flags,
id< MTLDevice >  device,
id< MTLCommandQueue >  command_queue,
const std::vector< std::shared_ptr< fml::Mapping > > &  shader_libraries_data,
std::shared_ptr< const fml::SyncSwitch is_gpu_disabled_sync_switch,
const std::string &  label 
)
static

Definition at line 308 of file context_mtl.mm.

314 {
315 auto context = std::shared_ptr<ContextMTL>(
316 new ContextMTL(flags, device, command_queue,
317 MTLShaderLibraryFromFileData(device, shader_libraries_data,
318 library_label),
319 std::move(is_gpu_disabled_sync_switch)));
320 if (!context->IsValid()) {
321 FML_LOG(ERROR) << "Could not create Metal context.";
322 return nullptr;
323 }
324 return context;
325}

References context, device, FML_LOG, and impeller::MTLShaderLibraryFromFileData().

◆ CreateCommandBuffer()

std::shared_ptr< CommandBuffer > impeller::ContextMTL::CreateCommandBuffer ( ) const
overridevirtual

Create a new command buffer. Command buffers can be used to encode graphics, blit, or compute commands to be submitted to the device.

A command buffer can only be used on a single thread. Multi-threaded render, blit, or compute passes must create a new command buffer on each thread.

Returns
A new command buffer.

Implements impeller::Context.

Definition at line 361 of file context_mtl.mm.

361 {
362 return CreateCommandBufferInQueue(command_queue_);
363}

Referenced by impeller::SurfaceMTL::PreparePresent().

◆ CreateMTLCommandBuffer()

id< MTLCommandBuffer > impeller::ContextMTL::CreateMTLCommandBuffer ( const std::string &  label) const

Definition at line 416 of file context_mtl.mm.

417 {
418 auto buffer = [command_queue_ commandBuffer];
419 if (!label.empty()) {
420 [buffer setLabel:@(label.data())];
421 }
422 return buffer;
423}
DEF_SWITCHES_START aot vmservice shared library Name of the *so containing AOT compiled Dart assets for launching the service isolate vm snapshot The VM snapshot data that will be memory mapped as read only SnapshotAssetPath must be present isolate snapshot The isolate snapshot data that will be memory mapped as read only SnapshotAssetPath must be present cache dir Path to the cache directory This is different from the persistent_cache_path in embedder which is used for Skia shader cache icu native lib Path to the library file that exports the ICU data vm service The hostname IP address on which the Dart VM Service should be served If not defaults to or::depending on whether ipv6 is specified disable vm Disable the Dart VM Service The Dart VM Service is never available in release mode Bind to the IPv6 localhost address for the Dart VM Service Ignored if vm service host is set profile Make the profiler discard new samples once the profiler sample buffer is full When this flag is not the profiler sample buffer is used as a ring buffer
Definition switch_defs.h:98

Referenced by impeller::SurfaceMTL::Present().

◆ DescribeGpuModel()

std::string impeller::ContextMTL::DescribeGpuModel ( ) const
overridevirtual

Implements impeller::Context.

Definition at line 336 of file context_mtl.mm.

336 {
337 return std::string([[device_ name] UTF8String]);
338}
const char * name
Definition fuchsia.cc:50

References name.

◆ FinishQueue()

bool impeller::ContextMTL::FinishQueue ( )
overridevirtual

Wait until all previously submitted command buffers are processed and displayed by the GPU.

WARNING: This method call is unnecessary for nearly all use cases since asynchronous workloads are the expected norm and calling this method can negatively affect application performance. Its only use is for cases like benchmarking where proper performance metrics can only be collected by including all background processing of the GPU.

Outstanding unflushed command buffers are not committed, submitted, or enqueued by this method and such buffers should have already been flushed before this method is called. The method will only wait for work to be done that has already been submitted to the GPU.

Returns
True if the queue was successfully processed, otherwise false if there was an error or if the backend does not support synchronous reporting of completion. Implementations intended entirely for testing might simply return false, but they would not be used for benchmarking or other situations where we might measure GPU performance.

Implements impeller::Context.

Definition at line 480 of file context_mtl.mm.

480 {
481 id<MTLCommandBuffer> command_buffer =
482 ContextMTL::Cast(this)->CreateMTLCommandBuffer("Finish Queue Waiter");
483 [command_buffer commit];
484 // clang-format off
485 // This isn't documented in the method, but there are places where they
486 // imply that they will wait even for an empty buffer...
487 //
488 // See https://developer.apple.com/documentation/metalperformanceshaders/tuning-hints
489 // clang-format on
490 [command_buffer waitUntilCompleted];
491 return true;
492}
static ContextMTL & Cast(Context &base)
id< MTLCommandBuffer > CreateMTLCommandBuffer(const std::string &label) const
std::shared_ptr< CommandBuffer > command_buffer

References command_buffer.

◆ FlushTasksAwaitingGPU()

void impeller::ContextMTL::FlushTasksAwaitingGPU ( )

Definition at line 451 of file context_mtl.mm.

451 {
452 std::deque<PendingTasks> tasks_awaiting_gpu;
453 {
454 Lock lock(tasks_awaiting_gpu_mutex_);
455 std::swap(tasks_awaiting_gpu, tasks_awaiting_gpu_);
456 }
457 std::vector<PendingTasks> tasks_to_queue;
458 for (const auto& task : tasks_awaiting_gpu) {
459 is_gpu_disabled_sync_switch_->Execute(fml::SyncSwitch::Handlers()
460 .SetIfFalse([&] { task.task(); })
461 .SetIfTrue([&] {
462 // Lost access to the GPU
463 // immediately after it was
464 // activated. This may happen if
465 // the app was quickly
466 // foregrounded/backgrounded
467 // from a push notification.
468 // Store the tasks on the
469 // context again.
470 tasks_to_queue.push_back(task);
471 }));
472 }
473 if (!tasks_to_queue.empty()) {
474 Lock lock(tasks_awaiting_gpu_mutex_);
475 tasks_awaiting_gpu_.insert(tasks_awaiting_gpu_.end(),
476 tasks_to_queue.begin(), tasks_to_queue.end());
477 }
478}
Represents the 2 code paths available when calling |SyncSwitchExecute|.
Definition sync_switch.h:35

References fml::SyncSwitch::Handlers::SetIfFalse().

◆ GetBackendType()

Context::BackendType impeller::ContextMTL::GetBackendType ( ) const
overridevirtual

Get the graphics backend of an Impeller context.

        This is useful for cases where a renderer needs to track and
        lookup backend-specific resources, like shaders or uniform
        layout information.

        It's not recommended to use this as a substitute for
        per-backend capability checking. Instead, check for specific
        capabilities via `GetCapabilities()`.
Returns
The graphics backend of the Context.

Implements impeller::Context.

Definition at line 331 of file context_mtl.mm.

◆ GetCapabilities()

const std::shared_ptr< const Capabilities > & impeller::ContextMTL::GetCapabilities ( ) const
overridevirtual

Get the capabilities of Impeller context. All optionally supported feature of the platform, client-rendering API, and device can be queried using the Capabilities.

Returns
The capabilities. Can never be nullptr for a valid context.

Implements impeller::Context.

Definition at line 401 of file context_mtl.mm.

401 {
402 return device_capabilities_;
403}

◆ GetCommandQueue()

std::shared_ptr< CommandQueue > impeller::ContextMTL::GetCommandQueue ( ) const
overridevirtual

Return the graphics queue for submitting command buffers.

Implements impeller::Context.

Definition at line 504 of file context_mtl.mm.

504 {
505 return command_queue_ip_;
506}

◆ GetIsGpuDisabledSyncSwitch()

std::shared_ptr< const fml::SyncSwitch > impeller::ContextMTL::GetIsGpuDisabledSyncSwitch ( ) const

Definition at line 374 of file context_mtl.mm.

375 {
376 return is_gpu_disabled_sync_switch_;
377}

◆ GetMTLDevice()

id< MTLDevice > impeller::ContextMTL::GetMTLDevice ( ) const

Definition at line 397 of file context_mtl.mm.

397 {
398 return device_;
399}

Referenced by impeller::PlaygroundImplMTL::PlaygroundImplMTL().

◆ GetPipelineLibrary()

std::shared_ptr< PipelineLibrary > impeller::ContextMTL::GetPipelineLibrary ( ) const
overridevirtual

Returns the library of pipelines used by render or compute commands.

Returns
The pipeline library. Can never be nullptr for a valid context.

Implements impeller::Context.

Definition at line 351 of file context_mtl.mm.

351 {
352 return pipeline_library_;
353}

◆ GetResourceAllocator()

std::shared_ptr< Allocator > impeller::ContextMTL::GetResourceAllocator ( ) const
overridevirtual

Returns the allocator used to create textures and buffers on the device.

Returns
The resource allocator. Can never be nullptr for a valid context.

Implements impeller::Context.

Definition at line 393 of file context_mtl.mm.

393 {
394 return resource_allocator_;
395}

◆ GetRuntimeStageBackend()

RuntimeStageBackend impeller::ContextMTL::GetRuntimeStageBackend ( ) const
overridevirtual

Retrieve the runtime stage for this context type.

This is used by the engine shell and other subsystems for loading the correct shader types.

Implements impeller::Context.

Definition at line 509 of file context_mtl.mm.

References impeller::kMetal.

◆ GetSamplerLibrary()

std::shared_ptr< SamplerLibrary > impeller::ContextMTL::GetSamplerLibrary ( ) const
overridevirtual

Returns the library of combined image samplers used in shaders.

Returns
The sampler library. Can never be nullptr for a valid context.

Implements impeller::Context.

Definition at line 356 of file context_mtl.mm.

356 {
357 return sampler_library_;
358}

◆ GetShaderLibrary()

std::shared_ptr< ShaderLibrary > impeller::ContextMTL::GetShaderLibrary ( ) const
overridevirtual

Returns the library of shaders used to specify the programmable stages of a pipeline.

Returns
The shader library. Can never be nullptr for a valid context.

Implements impeller::Context.

Definition at line 346 of file context_mtl.mm.

346 {
347 return shader_library_;
348}

◆ IsValid()

bool impeller::ContextMTL::IsValid ( ) const
overridevirtual

Determines if a context is valid. If the caller ever receives an invalid context, they must discard it and construct a new context. There is no recovery mechanism to repair a bad context.

It is convention in Impeller to never return an invalid context from a call that returns an pointer to a context. The call implementation performs validity checks itself and return a null context instead of a pointer to an invalid context.

How a context goes invalid is backend specific. It could happen due to device loss, or any other unrecoverable error.

Returns
If the context is valid.

Implements impeller::Context.

Definition at line 341 of file context_mtl.mm.

341 {
342 return is_valid_;
343}

◆ SetCapabilities()

void impeller::ContextMTL::SetCapabilities ( const std::shared_ptr< const Capabilities > &  capabilities)

Definition at line 405 of file context_mtl.mm.

406 {
407 device_capabilities_ = capabilities;
408}

◆ Shutdown()

void impeller::ContextMTL::Shutdown ( )
overridevirtual

Force all pending asynchronous work to finish. This is achieved by deleting all owned concurrent message loops.

Implements impeller::Context.

Definition at line 366 of file context_mtl.mm.

366{}

◆ StoreTaskForGPU()

void impeller::ContextMTL::StoreTaskForGPU ( const fml::closure task,
const fml::closure failure 
)
overridevirtual

Stores a task on the ContextMTL that is awaiting access for the GPU.

The task will be executed in the event that the GPU access has changed to being available or that the task has been canceled. The task should operate with the SyncSwitch to make sure the GPU is accessible.

If the queue of pending tasks is cleared without GPU access, then the failure callback will be invoked and the primary task function will not

Threadsafe.

task will be executed on the platform thread.

Reimplemented from impeller::Context.

Definition at line 425 of file context_mtl.mm.

426 {
427 std::vector<PendingTasks> failed_tasks;
428 {
429 Lock lock(tasks_awaiting_gpu_mutex_);
430 tasks_awaiting_gpu_.push_back(PendingTasks{task, failure});
431 int32_t failed_task_count =
432 tasks_awaiting_gpu_.size() - kMaxTasksAwaitingGPU;
433 if (failed_task_count > 0) {
434 failed_tasks.reserve(failed_task_count);
435 failed_tasks.insert(failed_tasks.end(),
436 std::make_move_iterator(tasks_awaiting_gpu_.begin()),
437 std::make_move_iterator(tasks_awaiting_gpu_.begin() +
438 failed_task_count));
439 tasks_awaiting_gpu_.erase(
440 tasks_awaiting_gpu_.begin(),
441 tasks_awaiting_gpu_.begin() + failed_task_count);
442 }
443 }
444 for (const PendingTasks& task : failed_tasks) {
445 if (task.failure) {
446 task.failure();
447 }
448 }
449}
static constexpr int32_t kMaxTasksAwaitingGPU
Definition context.h:83

◆ UpdateOffscreenLayerPixelFormat()

bool impeller::ContextMTL::UpdateOffscreenLayerPixelFormat ( PixelFormat  format)
overridevirtual

Reimplemented from impeller::Context.

Definition at line 411 of file context_mtl.mm.

411 {
412 device_capabilities_ = InferMetalCapabilities(device_, format);
413 return true;
414}
static std::unique_ptr< Capabilities > InferMetalCapabilities(id< MTLDevice > device, PixelFormat color_format)

References format, and impeller::InferMetalCapabilities().


The documentation for this class was generated from the following files: