Add support for rendering using Metal on macOS (flutter/engine#23599)

This commit is contained in:
Kaushik Iska
2021-01-14 14:47:21 -08:00
committed by GitHub
parent fa72fff62d
commit e7be1a1cf4
30 changed files with 943 additions and 164 deletions

View File

@@ -1062,6 +1062,8 @@ FILE: ../../../flutter/shell/platform/darwin/macos/framework/Headers/FlutterPlug
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Headers/FlutterViewController.h
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Info.plist
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterAppDelegate.mm
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterBackingStore.h
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterBackingStore.mm
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterBackingStoreData.h
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterBackingStoreData.mm
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterDartProject.mm
@@ -1080,11 +1082,18 @@ FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterIOSur
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterIOSurfaceHolder.mm
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterIntermediateKeyResponder.h
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterIntermediateKeyResponder.mm
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterMetalRenderer.h
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterMetalRenderer.mm
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterMetalRendererTest.mm
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterMetalSurfaceManagerTest.mm
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterMouseCursorPlugin.h
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterMouseCursorPlugin.mm
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterOpenGLRenderer.h
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterOpenGLRenderer.mm
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterOpenGLRendererTest.mm
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterRenderer.h
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterResizableBackingStoreProvider.h
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterResizableBackingStoreProvider.mm
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterResizeSynchronizer.h
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterResizeSynchronizer.mm
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterSurfaceManager.h

View File

@@ -26,19 +26,19 @@ NS_ASSUME_NONNULL_BEGIN
/**
* Initializes a FlutterDarwinContextMetal with provided MTLDevice and MTLCommandQueue.
*/
- (instancetype)initWithMTLDevice:(id<MTLDevice>)mtlDevice
- (instancetype)initWithMTLDevice:(id<MTLDevice>)device
commandQueue:(id<MTLCommandQueue>)commandQueue;
/**
* MTLDevice that is backing this context.s
*/
@property(nonatomic, readonly) id<MTLDevice> mtlDevice;
@property(nonatomic, readonly) id<MTLDevice> device;
/**
* MTLCommandQueue that is acquired from the `mtlDevice`. This queue is used both for rendering and
* MTLCommandQueue that is acquired from the `device`. This queue is used both for rendering and
* resource related commands.
*/
@property(nonatomic, readonly) id<MTLCommandQueue> mtlCommandQueue;
@property(nonatomic, readonly) id<MTLCommandQueue> commandQueue;
/**
* Skia GrContext that is used for rendering.

View File

@@ -21,40 +21,40 @@ static GrContextOptions CreateMetalGrContextOptions() {
@implementation FlutterDarwinContextMetal
- (instancetype)initWithDefaultMTLDevice {
id<MTLDevice> mtlDevice = MTLCreateSystemDefaultDevice();
return [self initWithMTLDevice:mtlDevice commandQueue:[mtlDevice newCommandQueue]];
id<MTLDevice> device = MTLCreateSystemDefaultDevice();
return [self initWithMTLDevice:device commandQueue:[device newCommandQueue]];
}
- (instancetype)initWithMTLDevice:(id<MTLDevice>)mtlDevice
- (instancetype)initWithMTLDevice:(id<MTLDevice>)device
commandQueue:(id<MTLCommandQueue>)commandQueue {
self = [super init];
if (self != nil) {
_mtlDevice = mtlDevice;
_device = device;
if (!_mtlDevice) {
if (!_device) {
FML_DLOG(ERROR) << "Could not acquire Metal device.";
[self release];
return nil;
}
_mtlCommandQueue = commandQueue;
_commandQueue = commandQueue;
if (!_mtlCommandQueue) {
if (!_commandQueue) {
FML_DLOG(ERROR) << "Could not create Metal command queue.";
[self release];
return nil;
}
[_mtlCommandQueue setLabel:@"Flutter Main Queue"];
[_commandQueue setLabel:@"Flutter Main Queue"];
auto contextOptions = CreateMetalGrContextOptions();
// Skia expect arguments to `MakeMetal` transfer ownership of the reference in for release later
// when the GrDirectContext is collected.
_mainContext =
GrDirectContext::MakeMetal([_mtlDevice retain], [_mtlCommandQueue retain], contextOptions);
GrDirectContext::MakeMetal([_device retain], [_commandQueue retain], contextOptions);
_resourceContext =
GrDirectContext::MakeMetal([_mtlDevice retain], [_mtlCommandQueue retain], contextOptions);
GrDirectContext::MakeMetal([_device retain], [_commandQueue retain], contextOptions);
if (!_mainContext || !_resourceContext) {
FML_DLOG(ERROR) << "Could not create Skia Metal contexts.";

View File

@@ -20,12 +20,12 @@ IOSContextMetal::IOSContextMetal() {
return;
}
main_command_queue_.reset([darwin_context_metal_.get().mtlCommandQueue retain]);
main_command_queue_.reset([darwin_context_metal_.get().commandQueue retain]);
CVMetalTextureCacheRef texture_cache_raw = NULL;
auto cv_return = CVMetalTextureCacheCreate(kCFAllocatorDefault, // allocator
NULL, // cache attributes (NULL default)
darwin_context_metal_.get().mtlDevice, // metal device
darwin_context_metal_.get().device, // metal device
NULL, // texture attributes (NULL default)
&texture_cache_raw // [out] cache
);

View File

@@ -22,8 +22,8 @@ IOSSurfaceMetal::IOSSurfaceMetal(fml::scoped_nsobject<CAMetalLayer> layer,
is_valid_ = layer_;
auto metal_context = CastToMetalContext(GetContext());
auto darwin_context = metal_context->GetDarwinContext().get();
command_queue_ = darwin_context.mtlCommandQueue;
device_ = darwin_context.mtlDevice;
command_queue_ = darwin_context.commandQueue;
device_ = darwin_context.device;
}
// |IOSSurface|

View File

@@ -5,11 +5,18 @@
assert(is_mac)
import("//build/config/mac/mac_sdk.gni")
import("//flutter/common/config.gni")
import("//flutter/shell/gpu/gpu.gni")
import("//flutter/shell/platform/darwin/common/framework_shared.gni")
import("//flutter/shell/platform/glfw/config.gni")
import("//flutter/testing/testing.gni")
shell_gpu_configuration("macos_gpu_configuration") {
enable_software = true
enable_gl = true
enable_vulkan = false
enable_metal = shell_enable_metal
}
group("macos") {
deps = [ ":flutter_framework" ]
if (build_glfw_shell) {
@@ -46,6 +53,8 @@ source_set("flutter_framework_source") {
sources = [
"framework/Source/FlutterAppDelegate.mm",
"framework/Source/FlutterBackingStore.h",
"framework/Source/FlutterBackingStore.mm",
"framework/Source/FlutterBackingStoreData.h",
"framework/Source/FlutterBackingStoreData.mm",
"framework/Source/FlutterDartProject.mm",
@@ -62,10 +71,15 @@ source_set("flutter_framework_source") {
"framework/Source/FlutterIOSurfaceHolder.mm",
"framework/Source/FlutterIntermediateKeyResponder.h",
"framework/Source/FlutterIntermediateKeyResponder.mm",
"framework/Source/FlutterMetalRenderer.h",
"framework/Source/FlutterMetalRenderer.mm",
"framework/Source/FlutterMouseCursorPlugin.h",
"framework/Source/FlutterMouseCursorPlugin.mm",
"framework/Source/FlutterOpenGLRenderer.h",
"framework/Source/FlutterOpenGLRenderer.mm",
"framework/Source/FlutterRenderer.h",
"framework/Source/FlutterResizableBackingStoreProvider.h",
"framework/Source/FlutterResizableBackingStoreProvider.mm",
"framework/Source/FlutterResizeSynchronizer.h",
"framework/Source/FlutterResizeSynchronizer.mm",
"framework/Source/FlutterSurfaceManager.h",
@@ -85,6 +99,7 @@ source_set("flutter_framework_source") {
sources += _flutter_framework_headers
deps = [
":macos_gpu_configuration",
"//flutter/flow:flow",
"//flutter/fml",
"//flutter/shell/platform/common/cpp:common_cpp_switches",
@@ -106,6 +121,7 @@ source_set("flutter_framework_source") {
"Cocoa.framework",
"CoreVideo.framework",
"IOSurface.framework",
"Metal.framework",
"QuartzCore.framework",
]
}
@@ -131,12 +147,20 @@ executable("flutter_desktop_darwin_unittests") {
sources = [
"framework/Source/FlutterEngineTest.mm",
"framework/Source/FlutterGLCompositorUnittests.mm",
"framework/Source/FlutterOpenGLRendererTest.mm",
"framework/Source/FlutterViewControllerTest.mm",
"framework/Source/FlutterViewControllerTestUtils.h",
"framework/Source/FlutterViewControllerTestUtils.mm",
]
if (shell_enable_metal) {
sources += [
"framework/Source/FlutterMetalRendererTest.mm",
"framework/Source/FlutterMetalSurfaceManagerTest.mm",
]
} else {
sources += [ "framework/Source/FlutterOpenGLRendererTest.mm" ]
}
cflags_objcc = [ "-fobjc-arc" ]
ldflags = [ "-ObjC" ]

View File

@@ -0,0 +1,48 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <Cocoa/Cocoa.h>
#import <Metal/Metal.h>
/**
* Interface for backing store handles. Typically contain references to the buffers that
* are handed by the `FlutterView` to the `FlutterRenderer`.
*/
@interface FlutterRenderBackingStore : NSObject
@end
/**
* Wraps an OpenGL frame buffer.
*/
@interface FlutterOpenGLRenderBackingStore : FlutterRenderBackingStore
/**
* Frame buffer ID referenced by this backing store instance.
*/
@property(nonatomic, readonly) uint32_t frameBufferID;
/**
* Initializes a backing store with the specified frame buffer id.
*/
- (nonnull instancetype)initWithFrameBufferID:(uint32_t)fboID;
@end
/**
* Wraps a Metal texture.
*/
@interface FlutterMetalRenderBackingStore : FlutterRenderBackingStore
/**
* MTLTexture referenced by this backing store instance.
*/
@property(nonnull, nonatomic, readonly) id<MTLTexture> texture;
/**
* Initializes a backing store with the specified MTLTexture.
*/
- (nonnull instancetype)initWithTexture:(nonnull id<MTLTexture>)texture;
@end

View File

@@ -0,0 +1,32 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterBackingStore.h"
@implementation FlutterRenderBackingStore
@end
@implementation FlutterOpenGLRenderBackingStore
- (instancetype)initWithFrameBufferID:(uint32_t)fboID {
self = [super init];
if (self) {
_frameBufferID = fboID;
}
return self;
}
@end
@implementation FlutterMetalRenderBackingStore
- (instancetype)initWithTexture:(id<MTLTexture>)texture {
self = [super init];
if (self) {
_texture = texture;
}
return self;
}
@end

View File

@@ -3,11 +3,12 @@
// found in the LICENSE file.
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterBackingStoreData.h"
#import <OpenGL/gl.h>
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterFrameBufferProvider.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterIOSurfaceHolder.h"
#include <OpenGL/gl.h>
@implementation FlutterBackingStoreData
- (nullable instancetype)initWithLayerId:(size_t)layerId

View File

@@ -11,6 +11,7 @@
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterDartProject_Internal.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterExternalTextureGL.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterGLCompositor.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterMetalRenderer.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterOpenGLRenderer.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h"
#import "flutter/shell/platform/embedder/embedder.h"
@@ -89,7 +90,7 @@ static FlutterLocale FlutterLocaleFromNSLocale(NSLocale* locale) {
}
- (id<FlutterTextureRegistry>)textures {
return _flutterEngine.openGLRenderer;
return _flutterEngine.renderer;
}
- (NSView*)view {
@@ -130,6 +131,10 @@ static void OnPlatformMessage(const FlutterPlatformMessage* message, FlutterEngi
// Pointer to the Dart AOT snapshot and instruction data.
_FlutterEngineAOTData* _aotData;
// If set to true, engine will render using metal. This is controlled by SHELL_ENABLE_METAL
// for now, intent is to be made default in the future.
BOOL _enableMetalRendering;
// _macOSGLCompositor is created when the engine is created and
// it's destruction is handled by ARC when the engine is destroyed.
std::unique_ptr<flutter::FlutterGLCompositor> _macOSGLCompositor;
@@ -151,9 +156,19 @@ static void OnPlatformMessage(const FlutterPlatformMessage* message, FlutterEngi
_project = project ?: [[FlutterDartProject alloc] init];
_messageHandlers = [[NSMutableDictionary alloc] init];
_allowHeadlessExecution = allowHeadlessExecution;
#ifdef SHELL_ENABLE_METAL
_enableMetalRendering = YES;
#endif
_embedderAPI.struct_size = sizeof(FlutterEngineProcTable);
FlutterEngineGetProcAddresses(&_embedderAPI);
_openGLRenderer = [[FlutterOpenGLRenderer alloc] initWithFlutterEngine:self];
if (_enableMetalRendering) {
_renderer = [[FlutterMetalRenderer alloc] initWithFlutterEngine:self];
} else {
_renderer = [[FlutterOpenGLRenderer alloc] initWithFlutterEngine:self];
}
NSNotificationCenter* notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter addObserver:self
@@ -181,8 +196,6 @@ static void OnPlatformMessage(const FlutterPlatformMessage* message, FlutterEngi
return NO;
}
const FlutterRendererConfig rendererConfig = [_openGLRenderer createRendererConfig];
// TODO(stuartmorgan): Move internal channel registration from FlutterViewController to here.
// FlutterProjectArgs is expecting a full argv, so when processing it for
@@ -237,6 +250,7 @@ static void OnPlatformMessage(const FlutterPlatformMessage* message, FlutterEngi
flutterArguments.compositor = [self createFlutterCompositor];
FlutterRendererConfig rendererConfig = [_renderer createRendererConfig];
FlutterEngineResult result = _embedderAPI.Initialize(
FLUTTER_ENGINE_VERSION, &rendererConfig, &flutterArguments, (__bridge void*)(self), &_engine);
if (result != kSuccess) {
@@ -284,7 +298,7 @@ static void OnPlatformMessage(const FlutterPlatformMessage* message, FlutterEngi
- (void)setViewController:(FlutterViewController*)controller {
_viewController = controller;
[_openGLRenderer setFlutterView:controller.flutterView];
[_renderer setFlutterView:controller.flutterView];
if (!controller && !_allowHeadlessExecution) {
[self shutDownEngine];
@@ -292,17 +306,23 @@ static void OnPlatformMessage(const FlutterPlatformMessage* message, FlutterEngi
}
- (FlutterCompositor*)createFlutterCompositor {
// When rendering with metal do not support platform views.
if (_enableMetalRendering) {
return nil;
}
// TODO(richardjcai): Add support for creating a FlutterGLCompositor
// with a nil _viewController for headless engines.
// https://github.com/flutter/flutter/issues/71606
if (_viewController == nullptr) {
return nullptr;
if (!_viewController) {
return nil;
}
[_openGLRenderer.openGLContext makeCurrentContext];
FlutterOpenGLRenderer* openGLRenderer = reinterpret_cast<FlutterOpenGLRenderer*>(_renderer);
[openGLRenderer.openGLContext makeCurrentContext];
_macOSGLCompositor = std::make_unique<flutter::FlutterGLCompositor>(
_viewController, _openGLRenderer.openGLContext);
_macOSGLCompositor =
std::make_unique<flutter::FlutterGLCompositor>(_viewController, openGLRenderer.openGLContext);
_compositor = {};
_compositor.struct_size = sizeof(FlutterCompositor);
@@ -331,9 +351,12 @@ static void OnPlatformMessage(const FlutterPlatformMessage* message, FlutterEngi
layers_count);
};
__weak FlutterEngine* weak_self = self;
_macOSGLCompositor->SetPresentCallback(
[weak_self]() { return [weak_self.openGLRenderer glPresent]; });
__weak FlutterEngine* weakSelf = self;
_macOSGLCompositor->SetPresentCallback([weakSelf]() {
FlutterOpenGLRenderer* openGLRenderer =
reinterpret_cast<FlutterOpenGLRenderer*>(weakSelf.renderer);
return [openGLRenderer glPresent];
});
_compositor.avoid_backing_store_cache = true;
@@ -559,7 +582,7 @@ static void OnPlatformMessage(const FlutterPlatformMessage* message, FlutterEngi
#pragma mark - FlutterTextureRegistrar
- (int64_t)registerTexture:(id<FlutterTexture>)texture {
return [_openGLRenderer registerTexture:texture];
return [_renderer registerTexture:texture];
}
- (BOOL)registerTextureWithID:(int64_t)textureId {
@@ -567,7 +590,7 @@ static void OnPlatformMessage(const FlutterPlatformMessage* message, FlutterEngi
}
- (void)textureFrameAvailable:(int64_t)textureID {
[_openGLRenderer textureFrameAvailable:textureID];
[_renderer textureFrameAvailable:textureID];
}
- (BOOL)markTextureFrameAvailable:(int64_t)textureID {
@@ -575,7 +598,7 @@ static void OnPlatformMessage(const FlutterPlatformMessage* message, FlutterEngi
}
- (void)unregisterTexture:(int64_t)textureID {
[_openGLRenderer unregisterTexture:textureID];
[_renderer unregisterTexture:textureID];
}
- (BOOL)unregisterTextureWithID:(int64_t)textureID {

View File

@@ -6,7 +6,7 @@
#import <Cocoa/Cocoa.h>
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterOpenGLRenderer.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterRenderer.h"
#include "flutter/shell/platform/embedder/embedder.h"
@interface FlutterEngine ()
@@ -17,10 +17,10 @@
@property(nonatomic, readonly) BOOL running;
/**
* Provides the renderer config needed to initialize the engine and also handles external texture
* management.
* Provides the renderer config needed to initialize the engine and also handles external
* texture management.
*/
@property(nonatomic, readonly, nonnull) FlutterOpenGLRenderer* openGLRenderer;
@property(nonatomic, readonly, nullable) id<FlutterRenderer> renderer;
/**
* Function pointers for interacting with the embedder.h API.

View File

@@ -9,7 +9,7 @@
*/
@interface FlutterFrameBufferProvider : NSObject
- (nullable instancetype)initWithOpenGLContext:(nonnull const NSOpenGLContext*)opengLContext;
- (nullable instancetype)initWithOpenGLContext:(nonnull const NSOpenGLContext*)openGLContext;
/**
* Returns the id of the framebuffer.

View File

@@ -4,7 +4,7 @@
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterFrameBufferProvider.h"
#include <OpenGL/gl.h>
#import <OpenGL/gl.h>
#import "flutter/shell/platform/darwin/macos/framework/Source/MacOSGLContextSwitch.h"

View File

@@ -8,11 +8,10 @@
#include "flutter/fml/logging.h"
#include "flutter/fml/platform/darwin/cf_utils.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterBackingStore.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterBackingStoreData.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterFrameBufferProvider.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterIOSurfaceHolder.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkSurface.h"
#include "third_party/skia/include/gpu/gl/GrGLAssembleInterface.h"
@@ -35,8 +34,10 @@ bool FlutterGLCompositor::CreateBackingStore(const FlutterBackingStoreConfig* co
StartFrame();
// If the backing store is for the first layer, return the fbo for the
// FlutterView.
auto fbo = [view_controller_.flutterView frameBufferIDForSize:size];
backing_store_out->open_gl.framebuffer.name = fbo;
FlutterOpenGLRenderBackingStore* backingStore =
reinterpret_cast<FlutterOpenGLRenderBackingStore*>(
[view_controller_.flutterView backingStoreForSize:size]);
backing_store_out->open_gl.framebuffer.name = backingStore.frameBufferID;
} else {
FlutterFrameBufferProvider* fb_provider =
[[FlutterFrameBufferProvider alloc] initWithOpenGLContext:open_gl_context_];

View File

@@ -4,7 +4,7 @@
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterIOSurfaceHolder.h"
#include <OpenGL/gl.h>
#import <OpenGL/gl.h>
@interface FlutterIOSurfaceHolder () {
IOSurfaceRef _ioSurface;

View File

@@ -0,0 +1,37 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <Cocoa/Cocoa.h>
#import <Metal/Metal.h>
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterRenderer.h"
/**
* Provides the renderer config needed to initialize the embedder engine. This is initialized during
* FlutterEngine creation and then attached to the FlutterView once the FlutterViewController is
* initialized.
*/
@interface FlutterMetalRenderer : NSObject <FlutterRenderer>
/**
* Interface to the system GPU. Used to issue all the rendering commands.
*/
@property(nonatomic, readonly, nonnull) id<MTLDevice> device;
/**
* Used to get the command buffers for the MTLDevice to render to.
*/
@property(nonatomic, readonly, nonnull) id<MTLCommandQueue> commandQueue;
/**
* Creates a Metal texture for the given size.
*/
- (FlutterMetalTexture)createTextureForSize:(CGSize)size;
/**
* Presents the texture specified by the texture id.
*/
- (BOOL)present:(int64_t)textureID;
@end

View File

@@ -0,0 +1,111 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterMetalRenderer.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterView.h"
#include "flutter/shell/platform/embedder/embedder.h"
#pragma mark - Static callbacks that require the engine.
static FlutterMetalTexture OnGetNextDrawable(FlutterEngine* engine,
const FlutterFrameInfo* frameInfo) {
CGSize size = CGSizeMake(frameInfo->size.width, frameInfo->size.height);
FlutterMetalRenderer* metalRenderer = reinterpret_cast<FlutterMetalRenderer*>(engine.renderer);
return [metalRenderer createTextureForSize:size];
}
static bool OnPresentDrawable(FlutterEngine* engine, const FlutterMetalTexture* texture) {
FlutterMetalRenderer* metalRenderer = reinterpret_cast<FlutterMetalRenderer*>(engine.renderer);
return [metalRenderer present:texture->texture_id];
}
#pragma mark - FlutterMetalRenderer implementation
@implementation FlutterMetalRenderer {
FlutterEngine* _engine;
FlutterView* _flutterView;
}
- (instancetype)initWithFlutterEngine:(nonnull FlutterEngine*)flutterEngine {
self = [super init];
if (self) {
_engine = flutterEngine;
_device = MTLCreateSystemDefaultDevice();
if (!_device) {
NSLog(@"Could not acquire Metal device.");
return nil;
}
_commandQueue = [_device newCommandQueue];
if (!_commandQueue) {
NSLog(@"Could not create Metal command queue.");
return nil;
}
}
return self;
}
- (void)setFlutterView:(FlutterView*)view {
_flutterView = view;
}
- (FlutterRendererConfig)createRendererConfig {
FlutterRendererConfig config = {
.type = FlutterRendererType::kMetal,
.metal.struct_size = sizeof(FlutterMetalRendererConfig),
.metal.device = (__bridge FlutterMetalDeviceHandle)_device,
.metal.present_command_queue = (__bridge FlutterMetalCommandQueueHandle)_commandQueue,
.metal.get_next_drawable_callback =
reinterpret_cast<FlutterMetalTextureCallback>(OnGetNextDrawable),
.metal.present_drawable_callback =
reinterpret_cast<FlutterMetalPresentCallback>(OnPresentDrawable),
};
return config;
}
#pragma mark - Embedder callback implementations.
- (FlutterMetalTexture)createTextureForSize:(CGSize)size {
FlutterMetalRenderBackingStore* backingStore =
(FlutterMetalRenderBackingStore*)[_flutterView backingStoreForSize:size];
id<MTLTexture> texture = backingStore.texture;
FlutterMetalTexture embedderTexture;
embedderTexture.struct_size = sizeof(FlutterMetalTexture);
embedderTexture.texture = (__bridge void*)texture;
embedderTexture.texture_id = reinterpret_cast<int64_t>(texture);
return embedderTexture;
}
- (BOOL)present:(int64_t)textureID {
if (!_flutterView) {
return NO;
}
[_flutterView present];
return YES;
}
#pragma mark - FlutterTextureRegistrar methods.
- (int64_t)registerTexture:(id<FlutterTexture>)texture {
NSAssert(NO, @"External textures aren't yet supported when using Metal on macOS."
" See: https://github.com/flutter/flutter/issues/73826");
return 0;
}
- (void)textureFrameAvailable:(int64_t)textureID {
NSAssert(NO, @"External textures aren't yet supported when using Metal on macOS."
" See: https://github.com/flutter/flutter/issues/73826");
}
- (void)unregisterTexture:(int64_t)textureID {
NSAssert(NO, @"External textures aren't yet supported when using Metal on macOS."
" See: https://github.com/flutter/flutter/issues/73826");
}
@end

View File

@@ -0,0 +1,54 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <OCMock/OCMock.h>
#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterDartProject_Internal.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterMetalRenderer.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterView.h"
#include "flutter/shell/platform/embedder/embedder.h"
#include "flutter/shell/platform/embedder/test_utils/proc_table_replacement.h"
#include "flutter/testing/testing.h"
namespace flutter::testing {
namespace {
// Returns an engine configured for the test fixture resource configuration.
FlutterEngine* CreateTestEngine() {
NSString* fixtures = @(testing::GetFixturesPath());
FlutterDartProject* project = [[FlutterDartProject alloc]
initWithAssetsPath:fixtures
ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]];
return [[FlutterEngine alloc] initWithName:@"test" project:project allowHeadlessExecution:true];
}
} // namespace
TEST(FlutterMetalRenderer, PresentDelegatesToFlutterView) {
FlutterEngine* engine = CreateTestEngine();
FlutterMetalRenderer* renderer = [[FlutterMetalRenderer alloc] initWithFlutterEngine:engine];
id mockFlutterView = OCMClassMock([FlutterView class]);
[[mockFlutterView expect] present];
[renderer setFlutterView:mockFlutterView];
[renderer present:1];
}
TEST(FlutterMetalRenderer, TextureReturnedByFlutterView) {
FlutterEngine* engine = CreateTestEngine();
FlutterMetalRenderer* renderer = [[FlutterMetalRenderer alloc] initWithFlutterEngine:engine];
id mockFlutterView = OCMClassMock([FlutterView class]);
FlutterFrameInfo frameInfo;
frameInfo.struct_size = sizeof(FlutterFrameInfo);
FlutterUIntSize dimensions;
dimensions.width = 100;
dimensions.height = 200;
frameInfo.size = dimensions;
CGSize size = CGSizeMake(dimensions.width, dimensions.height);
[[mockFlutterView expect] backingStoreForSize:size];
[renderer setFlutterView:mockFlutterView];
[renderer createTextureForSize:size];
}
} // namespace flutter::testing

View File

@@ -0,0 +1,71 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <Cocoa/Cocoa.h>
#import <OCMock/OCMock.h>
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterSurfaceManager.h"
#include "flutter/testing/testing.h"
#include "gtest/gtest.h"
@interface TestMetalView : NSView
- (nonnull instancetype)init;
@end
@implementation TestMetalView
- (instancetype)init {
self = [super initWithFrame:NSZeroRect];
if (self) {
[self setWantsLayer:YES];
}
return self;
}
- (CALayer*)makeBackingLayer {
return [CAMetalLayer layer];
}
+ (Class)layerClass {
return [CAMetalLayer class];
}
@end
namespace flutter::testing {
static FlutterMetalSurfaceManager* CreateSurfaceManager() {
id<MTLDevice> device = MTLCreateSystemDefaultDevice();
id<MTLCommandQueue> commandQueue = [device newCommandQueue];
TestMetalView* metalView = [[TestMetalView alloc] init];
CAMetalLayer* layer = reinterpret_cast<CAMetalLayer*>(metalView.layer);
return [[FlutterMetalSurfaceManager alloc] initWithDevice:device
commandQueue:commandQueue
metalLayer:layer];
}
TEST(FlutterMetalSurfaceManager, EnsureSizeUpdatesSize) {
FlutterMetalSurfaceManager* surfaceManager = CreateSurfaceManager();
CGSize size = CGSizeMake(100, 50);
[surfaceManager ensureSurfaceSize:size];
id<MTLTexture> texture =
(reinterpret_cast<FlutterMetalRenderBackingStore*>([surfaceManager renderBuffer])).texture;
CGSize textureSize = CGSizeMake(texture.width, texture.height);
ASSERT_TRUE(CGSizeEqualToSize(size, textureSize));
}
TEST(FlutterMetalSurfaceManager, EnsureSizeUpdatesSizeForBackBuffer) {
FlutterMetalSurfaceManager* surfaceManager = CreateSurfaceManager();
CGSize size = CGSizeMake(100, 50);
[surfaceManager ensureSurfaceSize:size];
[surfaceManager swapBuffers];
id<MTLTexture> texture =
(reinterpret_cast<FlutterMetalRenderBackingStore*>([surfaceManager renderBuffer])).texture;
CGSize textureSize = CGSizeMake(texture.width, texture.height);
ASSERT_TRUE(CGSizeEqualToSize(size, textureSize));
}
} // namespace flutter::testing

View File

@@ -4,16 +4,14 @@
#import <Cocoa/Cocoa.h>
#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterView.h"
#import "flutter/shell/platform/embedder/embedder.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterRenderer.h"
/**
* Provides the renderer config needed to initialize the embedder engine and also handles external
* texture management. This is initialized during FlutterEngine creation and then attached to the
* FlutterView once the FlutterViewController is initializer.
*/
@interface FlutterOpenGLRenderer : NSObject <FlutterTextureRegistry>
@interface FlutterOpenGLRenderer : NSObject <FlutterRenderer>
/**
* The resource context used by the engine for texture uploads. FlutterViews associated with this
@@ -26,17 +24,6 @@
*/
@property(readwrite, nonatomic, nonnull) NSOpenGLContext* openGLContext;
/**
* Intializes the renderer with the given FlutterEngine.
*/
- (nullable instancetype)initWithFlutterEngine:(nonnull FlutterEngine*)flutterEngine;
/**
* Sets the FlutterView and the corresponding rendering OpenGL context. Unsets the resource context
* if the view is nil.
*/
- (void)setFlutterView:(nullable FlutterView*)view;
/**
* Called by the engine to make the context the engine should draw into current.
*/
@@ -68,10 +55,4 @@
- (BOOL)populateTextureWithIdentifier:(int64_t)textureID
openGLTexture:(nonnull FlutterOpenGLTexture*)openGLTexture;
/**
* Creates a FlutterRendererConfig that renders using OpenGL context(s) held
* by this class.
*/
- (FlutterRendererConfig)createRendererConfig;
@end

View File

@@ -3,8 +3,6 @@
// found in the LICENSE file.
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterOpenGLRenderer.h"
#include "flutter/shell/platform/darwin/macos/framework/Source/FlutterView.h"
#include "flutter/shell/platform/embedder/embedder.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterExternalTextureGL.h"
@@ -12,23 +10,28 @@
#pragma mark - Static methods for openGL callbacks that require the engine.
static bool OnMakeCurrent(FlutterEngine* engine) {
return [engine.openGLRenderer makeCurrent];
FlutterOpenGLRenderer* openGLRenderer = reinterpret_cast<FlutterOpenGLRenderer*>(engine.renderer);
return [openGLRenderer makeCurrent];
}
static bool OnClearCurrent(FlutterEngine* engine) {
return [engine.openGLRenderer clearCurrent];
FlutterOpenGLRenderer* openGLRenderer = reinterpret_cast<FlutterOpenGLRenderer*>(engine.renderer);
return [openGLRenderer clearCurrent];
}
static bool OnPresent(FlutterEngine* engine) {
return [engine.openGLRenderer glPresent];
FlutterOpenGLRenderer* openGLRenderer = reinterpret_cast<FlutterOpenGLRenderer*>(engine.renderer);
return [openGLRenderer glPresent];
}
static uint32_t OnFBO(FlutterEngine* engine, const FlutterFrameInfo* info) {
return [engine.openGLRenderer fboForFrameInfo:info];
FlutterOpenGLRenderer* openGLRenderer = reinterpret_cast<FlutterOpenGLRenderer*>(engine.renderer);
return [openGLRenderer fboForFrameInfo:info];
}
static bool OnMakeResourceCurrent(FlutterEngine* engine) {
return [engine.openGLRenderer makeResourceCurrent];
FlutterOpenGLRenderer* openGLRenderer = reinterpret_cast<FlutterOpenGLRenderer*>(engine.renderer);
return [openGLRenderer makeResourceCurrent];
}
static bool OnAcquireExternalTexture(FlutterEngine* engine,
@@ -36,8 +39,9 @@ static bool OnAcquireExternalTexture(FlutterEngine* engine,
size_t width,
size_t height,
FlutterOpenGLTexture* openGlTexture) {
return [engine.openGLRenderer populateTextureWithIdentifier:textureIdentifier
openGLTexture:openGlTexture];
FlutterOpenGLRenderer* openGLRenderer = reinterpret_cast<FlutterOpenGLRenderer*>(engine.renderer);
return [openGLRenderer populateTextureWithIdentifier:textureIdentifier
openGLTexture:openGlTexture];
}
#pragma mark - FlutterOpenGLRenderer implementation.
@@ -98,7 +102,9 @@ static bool OnAcquireExternalTexture(FlutterEngine* engine,
- (uint32_t)fboForFrameInfo:(const FlutterFrameInfo*)info {
CGSize size = CGSizeMake(info->size.width, info->size.height);
return [_flutterView frameBufferIDForSize:size];
FlutterOpenGLRenderBackingStore* backingStore =
reinterpret_cast<FlutterOpenGLRenderBackingStore*>([_flutterView backingStoreForSize:size]);
return backingStore.frameBufferID;
}
- (NSOpenGLContext*)resourceContext {
@@ -163,8 +169,6 @@ static bool OnAcquireExternalTexture(FlutterEngine* engine,
}
}
#pragma mark - Private methods
- (FlutterRendererConfig)createRendererConfig {
const FlutterRendererConfig rendererConfig = {
.type = kOpenGL,

View File

@@ -40,7 +40,8 @@ TEST(FlutterOpenGLRenderer, RegisterExternalTexture) {
return kSuccess;
});
[engine.openGLRenderer registerTexture:flutterTexture];
FlutterOpenGLRenderer* openGLRenderer = reinterpret_cast<FlutterOpenGLRenderer*>(engine.renderer);
[openGLRenderer registerTexture:flutterTexture];
EXPECT_TRUE(called);
[engine shutDownEngine];
@@ -53,7 +54,8 @@ TEST(FlutterOpenGLRenderer, UnregisterExternalTexture) {
id<FlutterTexture> flutterTexture = OCMProtocolMock(@protocol(FlutterTexture));
bool called = false;
int64_t registeredTextureId = [engine.openGLRenderer registerTexture:flutterTexture];
FlutterOpenGLRenderer* openGLRenderer = reinterpret_cast<FlutterOpenGLRenderer*>(engine.renderer);
int64_t registeredTextureId = [openGLRenderer registerTexture:flutterTexture];
engine.embedderAPI.UnregisterExternalTexture =
MOCK_ENGINE_PROC(UnregisterExternalTexture, [&](auto engine, int64_t textureIdentifier) {
called = true;
@@ -61,7 +63,7 @@ TEST(FlutterOpenGLRenderer, UnregisterExternalTexture) {
return kSuccess;
});
[engine.openGLRenderer unregisterTexture:registeredTextureId];
[openGLRenderer unregisterTexture:registeredTextureId];
EXPECT_TRUE(called);
[engine shutDownEngine];
@@ -74,7 +76,8 @@ TEST(FlutterOpenGLRenderer, MarkExternalTextureFrameAvailable) {
id<FlutterTexture> flutterTexture = OCMProtocolMock(@protocol(FlutterTexture));
bool called = false;
int64_t registeredTextureId = [engine.openGLRenderer registerTexture:flutterTexture];
FlutterOpenGLRenderer* openGLRenderer = reinterpret_cast<FlutterOpenGLRenderer*>(engine.renderer);
int64_t registeredTextureId = [openGLRenderer registerTexture:flutterTexture];
engine.embedderAPI.MarkExternalTextureFrameAvailable = MOCK_ENGINE_PROC(
MarkExternalTextureFrameAvailable, [&](auto engine, int64_t textureIdentifier) {
called = true;
@@ -82,7 +85,7 @@ TEST(FlutterOpenGLRenderer, MarkExternalTextureFrameAvailable) {
return kSuccess;
});
[engine.openGLRenderer textureFrameAvailable:registeredTextureId];
[openGLRenderer textureFrameAvailable:registeredTextureId];
EXPECT_TRUE(called);
[engine shutDownEngine];
@@ -109,7 +112,7 @@ TEST(FlutterOpenGLRenderer, FBOReturnedByFlutterView) {
dimensions.height = 200;
frameInfo.size = dimensions;
CGSize size = CGSizeMake(dimensions.width, dimensions.height);
[[mockFlutterView expect] frameBufferIDForSize:size];
[[mockFlutterView expect] backingStoreForSize:size];
[renderer setFlutterView:mockFlutterView];
[renderer openGLContext];
[renderer fboForFrameInfo:&frameInfo];

View File

@@ -0,0 +1,31 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <Cocoa/Cocoa.h>
#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterView.h"
#import "flutter/shell/platform/embedder/embedder.h"
/**
* Rendering backend agnostic FlutterRendererConfig provider to be used by the embedder API.
*/
@protocol FlutterRenderer <FlutterTextureRegistry>
/**
* Intializes the renderer with the given FlutterEngine.
*/
- (nullable instancetype)initWithFlutterEngine:(nonnull FlutterEngine*)flutterEngine;
/**
* Sets the FlutterView to render to.
*/
- (void)setFlutterView:(nullable FlutterView*)view;
/**
* Creates a FlutterRendererConfig that renders using the appropriate backend.
*/
- (FlutterRendererConfig)createRendererConfig;
@end

View File

@@ -0,0 +1,58 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <Cocoa/Cocoa.h>
#import <Metal/Metal.h>
#import <QuartzCore/CAMetalLayer.h>
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterBackingStore.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterResizeSynchronizer.h"
/**
* Represents a buffer that can be resized.
*/
@protocol FlutterResizableBackingStoreProvider <FlutterResizeSynchronizerDelegate>
/**
* Notify of the required backing store size updates. Called during window resize.
*/
- (void)onBackingStoreResized:(CGSize)size;
/**
* Returns the FlutterBackingStore corresponding to the latest size.
*/
- (nonnull FlutterRenderBackingStore*)backingStore;
@end
/**
* OpenGL-backed FlutterResizableBackingStoreProvider. Backing store in this context implies a frame
* buffer.
*/
@interface FlutterOpenGLResizableBackingStoreProvider
: NSObject <FlutterResizableBackingStoreProvider>
/**
* Creates a resizable backing store provider for the given CALayer.
*/
- (nonnull instancetype)initWithMainContext:(nonnull NSOpenGLContext*)mainContext
layer:(nonnull CALayer*)layer;
@end
/**
* Metal-backed FlutterResizableBackingStoreProvider. Backing store in this context implies a
* MTLTexture.
*/
@interface FlutterMetalResizableBackingStoreProvider
: NSObject <FlutterResizableBackingStoreProvider>
/**
* Creates a resizable backing store provider for the given CAMetalLayer.
*/
- (nonnull instancetype)initWithDevice:(nonnull id<MTLDevice>)device
commandQueue:(nonnull id<MTLCommandQueue>)commandQueue
metalLayer:(nonnull CAMetalLayer*)layer;
@end

View File

@@ -0,0 +1,91 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterResizableBackingStoreProvider.h"
#import <OpenGL/gl.h>
#import <QuartzCore/QuartzCore.h>
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterSurfaceManager.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/MacOSGLContextSwitch.h"
@implementation FlutterOpenGLResizableBackingStoreProvider {
NSOpenGLContext* _mainContext;
id<FlutterSurfaceManager> _surfaceManager;
}
- (instancetype)initWithMainContext:(NSOpenGLContext*)mainContext layer:(CALayer*)layer {
self = [super init];
if (self) {
_mainContext = mainContext;
_surfaceManager = [[FlutterGLSurfaceManager alloc] initWithLayer:layer
openGLContext:_mainContext];
}
return self;
}
- (void)onBackingStoreResized:(CGSize)size {
[_surfaceManager ensureSurfaceSize:size];
}
- (FlutterRenderBackingStore*)backingStore {
return [_surfaceManager renderBuffer];
}
- (void)resizeSynchronizerFlush:(nonnull FlutterResizeSynchronizer*)synchronizer {
MacOSGLContextSwitch context_switch(_mainContext);
glFlush();
}
- (void)resizeSynchronizerCommit:(nonnull FlutterResizeSynchronizer*)synchronizer {
[CATransaction begin];
[CATransaction setDisableActions:YES];
[_surfaceManager swapBuffers];
[CATransaction commit];
}
@end
@implementation FlutterMetalResizableBackingStoreProvider {
id<MTLDevice> _device;
id<MTLCommandQueue> _commandQueue;
id<FlutterSurfaceManager> _surfaceManager;
}
- (instancetype)initWithDevice:(id<MTLDevice>)device
commandQueue:(id<MTLCommandQueue>)commandQueue
metalLayer:(CAMetalLayer*)layer {
self = [super init];
if (self) {
_device = device;
_commandQueue = commandQueue;
_surfaceManager = [[FlutterMetalSurfaceManager alloc] initWithDevice:device
commandQueue:commandQueue
metalLayer:layer];
}
return self;
}
- (void)onBackingStoreResized:(CGSize)size {
[_surfaceManager ensureSurfaceSize:size];
}
- (FlutterRenderBackingStore*)backingStore {
return [_surfaceManager renderBuffer];
}
- (void)resizeSynchronizerFlush:(nonnull FlutterResizeSynchronizer*)synchronizer {
// TODO (kaushikiska): Support smooth resizing on Metal.
}
- (void)resizeSynchronizerCommit:(nonnull FlutterResizeSynchronizer*)synchronizer {
id<MTLCommandBuffer> commandBuffer = [_commandQueue commandBuffer];
[commandBuffer commit];
[commandBuffer waitUntilScheduled];
[_surfaceManager swapBuffers];
}
@end

View File

@@ -3,16 +3,103 @@
// found in the LICENSE file.
#import <Cocoa/Cocoa.h>
#import <QuartzCore/CAMetalLayer.h>
// Manages the IOSurfaces for FlutterView
@interface FlutterSurfaceManager : NSObject
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterBackingStore.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterIOSurfaceHolder.h"
- (nullable instancetype)initWithLayer:(nonnull CALayer*)containingLayer
openGLContext:(nonnull NSOpenGLContext*)opengLContext;
/**
* Manages the render surfaces and their corresponding backing stores.
*/
@protocol FlutterSurfaceManager
/**
* Updates the backing store size of the managed IOSurfaces to `size`. If the surfaces are already
* of the same size, this is a no-op.
*/
- (void)ensureSurfaceSize:(CGSize)size;
/**
* Swaps the front and the back buffer.
*/
- (void)swapBuffers;
- (uint32_t)glFrameBufferId;
/**
* Returns the backing store for the back buffer.
*/
- (nonnull FlutterRenderBackingStore*)renderBuffer;
@end
/**
* Methods for managing the IOSurfaces held by FlutterIOSurfaceManager.
*/
@protocol FlutterIOSurfaceManagerDelegate
/**
* Tells the delegate that the front and back IOSurfaces are swapped.
*/
- (void)onSwapBuffers;
/**
* Tells the delegate that the IOSurfaces have been resized. `bufferIndex` is to indicate the front
* vs back buffer. `size` is the new size of the IOSurface.
*/
- (void)onUpdateSurface:(nonnull FlutterIOSurfaceHolder*)surface
bufferIndex:(size_t)index
size:(CGSize)size;
@end
/**
* Manages IOSurfaces for the FlutterEngine to render to.
*
* The backing store when rendering with OpenGL is a frame buffer backed by a texture, on Metal its
* a Metal texture. There are two IOSurfaces created during initialization, FlutterSurfaceManager
* manages the lifecycle of these.
*/
@interface FlutterIOSurfaceManager : NSObject <FlutterSurfaceManager>
/**
* The object that acts as the delegate for the FlutterIOSurfaceManager. See:
* FlutterIOSurfaceManagerDelegate.
*/
@property(nullable, nonatomic, weak) id<FlutterIOSurfaceManagerDelegate> delegate;
/**
* Initializes and returns an IOSurface manager that renders to a child layer (refered to as the
* content layer) of the containing layer and applies the transform to the contents of the content
* layer.
*/
- (nullable instancetype)initWithLayer:(nonnull CALayer*)containingLayer
contentTransform:(CATransform3D)transform;
@end
/**
* FlutterSurfaceManager implementation where the IOSurfaces managed are backed by a frame buffers
* which are bound to offscreen textures.
*/
@interface FlutterGLSurfaceManager : FlutterIOSurfaceManager <FlutterIOSurfaceManagerDelegate>
/**
* Creates two IOSurfaces backed by frame buffers and their backing textures.
*/
- (nullable instancetype)initWithLayer:(nonnull CALayer*)containingLayer
openGLContext:(nonnull NSOpenGLContext*)openGLContext;
@end
/**
* FlutterSurfaceManager implementation where the IOSurfaces managed are backed by a Metal textures.
*/
@interface FlutterMetalSurfaceManager : FlutterIOSurfaceManager <FlutterIOSurfaceManagerDelegate>
/**
* Creates two IOSurfaces backed by Metal textures.
*/
- (nullable instancetype)initWithDevice:(nonnull id<MTLDevice>)device
commandQueue:(nonnull id<MTLCommandQueue>)commandQueue
metalLayer:(nonnull CAMetalLayer*)layer;
@end

View File

@@ -3,11 +3,12 @@
// found in the LICENSE file.
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterSurfaceManager.h"
#import <Metal/Metal.h>
#import <OpenGL/gl.h>
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterFrameBufferProvider.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterIOSurfaceHolder.h"
#include <OpenGL/gl.h>
#import "flutter/shell/platform/darwin/macos/framework/Source/MacOSGLContextSwitch.h"
enum {
@@ -16,36 +17,25 @@ enum {
kFlutterSurfaceManagerBufferCount,
};
@interface FlutterSurfaceManager () {
CGSize _surfaceSize;
@implementation FlutterIOSurfaceManager {
CALayer* _containingLayer; // provided (parent layer)
CALayer* _contentLayer;
CATransform3D _contentTransform;
NSOpenGLContext* _openGLContext;
CGSize _surfaceSize;
FlutterIOSurfaceHolder* _ioSurfaces[kFlutterSurfaceManagerBufferCount];
FlutterFrameBufferProvider* _frameBuffers[kFlutterSurfaceManagerBufferCount];
}
@end
@implementation FlutterSurfaceManager
- (instancetype)initWithLayer:(CALayer*)containingLayer
openGLContext:(NSOpenGLContext*)openGLContext {
if (self = [super init]) {
- (instancetype)initWithLayer:(CALayer*)containingLayer contentTransform:(CATransform3D)transform {
self = [super init];
if (self) {
_containingLayer = containingLayer;
_openGLContext = openGLContext;
// Layer for content. This is separate from provided layer, because it needs to be flipped
// vertically if we render to OpenGL texture
_contentTransform = transform;
_contentLayer = [[CALayer alloc] init];
[_containingLayer addSublayer:_contentLayer];
_frameBuffers[0] = [[FlutterFrameBufferProvider alloc] initWithOpenGLContext:_openGLContext];
_frameBuffers[1] = [[FlutterFrameBufferProvider alloc] initWithOpenGLContext:_openGLContext];
_ioSurfaces[0] = [FlutterIOSurfaceHolder alloc];
_ioSurfaces[1] = [FlutterIOSurfaceHolder alloc];
_ioSurfaces[0] = [[FlutterIOSurfaceHolder alloc] init];
_ioSurfaces[1] = [[FlutterIOSurfaceHolder alloc] init];
}
return self;
}
@@ -55,35 +45,116 @@ enum {
return;
}
_surfaceSize = size;
MacOSGLContextSwitch context_switch(_openGLContext);
for (int i = 0; i < kFlutterSurfaceManagerBufferCount; ++i) {
[_ioSurfaces[i] recreateIOSurfaceWithSize:size];
GLuint fbo = [_frameBuffers[i] glFrameBufferId];
GLuint texture = [_frameBuffers[i] glTextureId];
[_ioSurfaces[i] bindSurfaceToTexture:texture fbo:fbo size:size];
[_delegate onUpdateSurface:_ioSurfaces[i] bufferIndex:i size:size];
}
}
- (void)swapBuffers {
_contentLayer.frame = _containingLayer.bounds;
// The surface is an OpenGL texture, which means it has origin in bottom left corner
// and needs to be flipped vertically
_contentLayer.transform = CATransform3DMakeScale(1, -1, 1);
_contentLayer.transform = _contentTransform;
IOSurfaceRef contentIOSurface = [_ioSurfaces[kFlutterSurfaceManagerBackBuffer] ioSurface];
[_contentLayer setContents:(__bridge id)contentIOSurface];
std::swap(_ioSurfaces[kFlutterSurfaceManagerBackBuffer],
_ioSurfaces[kFlutterSurfaceManagerFrontBuffer]);
[_delegate onSwapBuffers];
}
- (nonnull FlutterRenderBackingStore*)renderBuffer {
@throw([NSException exceptionWithName:@"Sub-classes FlutterIOSurfaceManager of"
" must override renderBuffer."
reason:nil
userInfo:nil]);
}
@end
@implementation FlutterGLSurfaceManager {
NSOpenGLContext* _openGLContext;
FlutterFrameBufferProvider* _frameBuffers[kFlutterSurfaceManagerBufferCount];
}
- (instancetype)initWithLayer:(CALayer*)containingLayer
openGLContext:(NSOpenGLContext*)openGLContext {
self = [super initWithLayer:containingLayer contentTransform:CATransform3DMakeScale(1, -1, 1)];
if (self) {
super.delegate = self;
_openGLContext = openGLContext;
_frameBuffers[0] = [[FlutterFrameBufferProvider alloc] initWithOpenGLContext:_openGLContext];
_frameBuffers[1] = [[FlutterFrameBufferProvider alloc] initWithOpenGLContext:_openGLContext];
}
return self;
}
- (FlutterRenderBackingStore*)renderBuffer {
uint32_t fboID = [_frameBuffers[kFlutterSurfaceManagerBackBuffer] glFrameBufferId];
return [[FlutterOpenGLRenderBackingStore alloc] initWithFrameBufferID:fboID];
}
- (void)onSwapBuffers {
std::swap(_frameBuffers[kFlutterSurfaceManagerBackBuffer],
_frameBuffers[kFlutterSurfaceManagerFrontBuffer]);
}
- (uint32_t)glFrameBufferId {
return [_frameBuffers[kFlutterSurfaceManagerBackBuffer] glFrameBufferId];
- (void)onUpdateSurface:(FlutterIOSurfaceHolder*)surface
bufferIndex:(size_t)index
size:(CGSize)size {
MacOSGLContextSwitch context_switch(_openGLContext);
GLuint fbo = [_frameBuffers[index] glFrameBufferId];
GLuint texture = [_frameBuffers[index] glTextureId];
[surface bindSurfaceToTexture:texture fbo:fbo size:size];
}
@end
@implementation FlutterMetalSurfaceManager {
id<MTLDevice> _device;
id<MTLCommandQueue> _commandQueue;
id<MTLTexture> _textures[kFlutterSurfaceManagerBufferCount];
}
- (nullable instancetype)initWithDevice:(nonnull id<MTLDevice>)device
commandQueue:(nonnull id<MTLCommandQueue>)commandQueue
metalLayer:(nonnull CAMetalLayer*)layer {
self = [super initWithLayer:layer contentTransform:CATransform3DIdentity];
if (self) {
super.delegate = self;
_device = device;
_commandQueue = commandQueue;
}
return self;
}
- (FlutterRenderBackingStore*)renderBuffer {
id<MTLTexture> texture = _textures[kFlutterSurfaceManagerBackBuffer];
return [[FlutterMetalRenderBackingStore alloc] initWithTexture:texture];
}
- (void)onSwapBuffers {
std::swap(_textures[kFlutterSurfaceManagerBackBuffer],
_textures[kFlutterSurfaceManagerFrontBuffer]);
}
- (void)onUpdateSurface:(FlutterIOSurfaceHolder*)surface
bufferIndex:(size_t)index
size:(CGSize)size {
MTLTextureDescriptor* textureDescriptor =
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
width:size.width
height:size.height
mipmapped:NO];
textureDescriptor.usage =
MTLTextureUsageShaderRead | MTLTextureUsageRenderTarget | MTLTextureUsageShaderWrite;
// plane = 0 for BGRA.
_textures[index] = [_device newTextureWithDescriptor:textureDescriptor
iosurface:[surface ioSurface]
plane:0];
}
@end

View File

@@ -4,6 +4,8 @@
#import <Cocoa/Cocoa.h>
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterResizableBackingStoreProvider.h"
/**
* Listener for view resizing.
*/
@@ -20,6 +22,14 @@
*/
@interface FlutterView : NSView
/**
* Initialize a FlutterView that will be rendered to using Metal rendering apis.
*/
- (nullable instancetype)initWithMTLDevice:(nonnull id<MTLDevice>)device
commandQueue:(nonnull id<MTLCommandQueue>)commandQueue
reshapeListener:(nonnull id<FlutterViewReshapeListener>)reshapeListener
NS_DESIGNATED_INITIALIZER;
- (nullable instancetype)initWithFrame:(NSRect)frame
mainContext:(nonnull NSOpenGLContext*)mainContext
reshapeListener:(nonnull id<FlutterViewReshapeListener>)reshapeListener
@@ -41,9 +51,9 @@
- (void)present;
/**
* Ensures that framebuffer with requested size exists and returns the ID. Expected to be called on
* raster thread.
* Ensures that a backing store with requested size exists and returns the descriptor. Expected to
* be called on raster thread.
*/
- (int)frameBufferIDForSize:(CGSize)size;
- (nonnull FlutterRenderBackingStore*)backingStoreForSize:(CGSize)size;
@end

View File

@@ -11,17 +11,43 @@
#import <OpenGL/gl.h>
#import <QuartzCore/QuartzCore.h>
@interface FlutterView () <FlutterResizeSynchronizerDelegate> {
@interface FlutterView () {
__weak id<FlutterViewReshapeListener> _reshapeListener;
FlutterResizeSynchronizer* _resizeSynchronizer;
FlutterSurfaceManager* _surfaceManager;
NSOpenGLContext* _openGLContext;
id<FlutterResizableBackingStoreProvider> _resizableBackingStoreProvider;
}
@end
@implementation FlutterView
- (instancetype)initWithMTLDevice:(id<MTLDevice>)device
commandQueue:(id<MTLCommandQueue>)commandQueue
reshapeListener:(id<FlutterViewReshapeListener>)reshapeListener {
self = [super initWithFrame:NSZeroRect];
if (self) {
[self setWantsLayer:YES];
_reshapeListener = reshapeListener;
_resizableBackingStoreProvider = [[FlutterMetalResizableBackingStoreProvider alloc]
initWithDevice:device
commandQueue:commandQueue
metalLayer:reinterpret_cast<CAMetalLayer*>(self.layer)];
_resizeSynchronizer =
[[FlutterResizeSynchronizer alloc] initWithDelegate:_resizableBackingStoreProvider];
}
return self;
}
#ifdef SHELL_ENABLE_METAL
+ (Class)layerClass {
return [CAMetalLayer class];
}
- (CALayer*)makeBackingLayer {
return [CAMetalLayer layer];
}
#endif
- (instancetype)initWithMainContext:(NSOpenGLContext*)mainContext
reshapeListener:(id<FlutterViewReshapeListener>)reshapeListener {
return [self initWithFrame:NSZeroRect mainContext:mainContext reshapeListener:reshapeListener];
@@ -32,37 +58,22 @@
reshapeListener:(id<FlutterViewReshapeListener>)reshapeListener {
self = [super initWithFrame:frame];
if (self) {
_openGLContext = mainContext;
[self setWantsLayer:YES];
_resizeSynchronizer = [[FlutterResizeSynchronizer alloc] initWithDelegate:self];
_surfaceManager = [[FlutterSurfaceManager alloc] initWithLayer:self.layer
openGLContext:_openGLContext];
_reshapeListener = reshapeListener;
_resizableBackingStoreProvider =
[[FlutterOpenGLResizableBackingStoreProvider alloc] initWithMainContext:mainContext
layer:self.layer];
_resizeSynchronizer =
[[FlutterResizeSynchronizer alloc] initWithDelegate:_resizableBackingStoreProvider];
}
return self;
}
- (void)resizeSynchronizerFlush:(FlutterResizeSynchronizer*)synchronizer {
MacOSGLContextSwitch context_switch(_openGLContext);
glFlush();
}
- (void)resizeSynchronizerCommit:(FlutterResizeSynchronizer*)synchronizer {
[CATransaction begin];
[CATransaction setDisableActions:YES];
[_surfaceManager swapBuffers];
[CATransaction commit];
}
- (int)frameBufferIDForSize:(CGSize)size {
- (FlutterRenderBackingStore*)backingStoreForSize:(CGSize)size {
if ([_resizeSynchronizer shouldEnsureSurfaceForSize:size]) {
[_surfaceManager ensureSurfaceSize:size];
[_resizableBackingStoreProvider onBackingStoreResized:size];
}
return [_surfaceManager glFrameBufferId];
return [_resizableBackingStoreProvider backingStore];
}
- (void)present {

View File

@@ -9,7 +9,9 @@
#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterCodecs.h"
#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterMetalRenderer.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterMouseCursorPlugin.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterOpenGLRenderer.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputPlugin.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterView.h"
#import "flutter/shell/platform/embedder/embedder.h"
@@ -275,13 +277,32 @@ static void CommonInit(FlutterViewController* controller) {
}
- (void)loadView {
NSOpenGLContext* mainContext = _engine.openGLRenderer.openGLContext;
if (!mainContext) {
NSLog(@"Unable to create FlutterView; no GL context available.");
return;
FlutterView* flutterView;
BOOL enableMetalRendering = NO;
#ifdef SHELL_ENABLE_METAL
enableMetalRendering = YES;
#endif
if (enableMetalRendering) {
FlutterMetalRenderer* metalRenderer = reinterpret_cast<FlutterMetalRenderer*>(_engine.renderer);
id<MTLDevice> device = metalRenderer.device;
id<MTLCommandQueue> commandQueue = metalRenderer.commandQueue;
if (!device || !commandQueue) {
NSLog(@"Unable to create FlutterView; no MTLDevice or MTLCommandQueue available.");
return;
}
flutterView = [[FlutterView alloc] initWithMTLDevice:device
commandQueue:commandQueue
reshapeListener:self];
} else {
FlutterOpenGLRenderer* openGLRenderer =
reinterpret_cast<FlutterOpenGLRenderer*>(_engine.renderer);
NSOpenGLContext* mainContext = openGLRenderer.openGLContext;
if (!mainContext) {
NSLog(@"Unable to create FlutterView; no GL context available.");
return;
}
flutterView = [[FlutterView alloc] initWithMainContext:mainContext reshapeListener:self];
}
FlutterView* flutterView = [[FlutterView alloc] initWithMainContext:mainContext
reshapeListener:self];
self.view = flutterView;
}