Flutter Impeller
context.h
Go to the documentation of this file.
1 // Copyright 2013 The Flutter Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef FLUTTER_IMPELLER_RENDERER_CONTEXT_H_
6 #define FLUTTER_IMPELLER_RENDERER_CONTEXT_H_
7 
8 #include <memory>
9 #include <string>
10 
11 #include "fml/closure.h"
12 #include "impeller/base/flags.h"
14 #include "impeller/core/formats.h"
18 
19 namespace impeller {
20 
21 class ShaderLibrary;
22 class CommandBuffer;
23 class PipelineLibrary;
24 
25 //------------------------------------------------------------------------------
26 /// @brief To do anything rendering related with Impeller, you need a
27 /// context.
28 ///
29 /// Contexts are expensive to construct and typically you only need
30 /// one in the process. The context represents a connection to a
31 /// graphics or compute accelerator on the device.
32 ///
33 /// If there are multiple context in a process, it would typically
34 /// be for separation of concerns (say, use with multiple engines in
35 /// Flutter), talking to multiple accelerators, or talking to the
36 /// same accelerator using different client APIs (Metal, Vulkan,
37 /// OpenGL ES, etc..).
38 ///
39 /// Contexts are thread-safe. They may be created, used, and
40 /// collected (though not from a thread used by an internal pool) on
41 /// any thread. They may also be accessed simultaneously from
42 /// multiple threads.
43 ///
44 /// Contexts are abstract and a concrete instance must be created
45 /// using one of the subclasses of `Context` in
46 /// `//impeller/renderer/backend`.
47 class Context {
48  public:
49  enum class BackendType {
50  kMetal,
51  kOpenGLES,
52  kVulkan,
53  };
54 
55  /// The maximum number of tasks that should ever be stored for
56  /// `StoreTaskForGPU`.
57  ///
58  /// This number was arbitrarily chosen. The idea is that this is a somewhat
59  /// rare situation where tasks happen to get executed in that tiny amount of
60  /// time while an app is being backgrounded but still executing.
61  static constexpr int32_t kMaxTasksAwaitingGPU = 64;
62 
63  //----------------------------------------------------------------------------
64  /// @brief Destroys an Impeller context.
65  ///
66  virtual ~Context();
67 
68  //----------------------------------------------------------------------------
69  /// @brief Get the graphics backend of an Impeller context.
70  ///
71  /// This is useful for cases where a renderer needs to track and
72  /// lookup backend-specific resources, like shaders or uniform
73  /// layout information.
74  ///
75  /// It's not recommended to use this as a substitute for
76  /// per-backend capability checking. Instead, check for specific
77  /// capabilities via `GetCapabilities()`.
78  ///
79  /// @return The graphics backend of the `Context`.
80  ///
81  virtual BackendType GetBackendType() const = 0;
82 
83  // TODO(129920): Refactor and move to capabilities.
84  virtual std::string DescribeGpuModel() const = 0;
85 
86  //----------------------------------------------------------------------------
87  /// @brief Determines if a context is valid. If the caller ever receives
88  /// an invalid context, they must discard it and construct a new
89  /// context. There is no recovery mechanism to repair a bad
90  /// context.
91  ///
92  /// It is convention in Impeller to never return an invalid
93  /// context from a call that returns an pointer to a context. The
94  /// call implementation performs validity checks itself and return
95  /// a null context instead of a pointer to an invalid context.
96  ///
97  /// How a context goes invalid is backend specific. It could
98  /// happen due to device loss, or any other unrecoverable error.
99  ///
100  /// @return If the context is valid.
101  ///
102  virtual bool IsValid() const = 0;
103 
104  //----------------------------------------------------------------------------
105  /// @brief Get the capabilities of Impeller context. All optionally
106  /// supported feature of the platform, client-rendering API, and
107  /// device can be queried using the `Capabilities`.
108  ///
109  /// @return The capabilities. Can never be `nullptr` for a valid context.
110  ///
111  virtual const std::shared_ptr<const Capabilities>& GetCapabilities()
112  const = 0;
113 
114  // TODO(129920): Refactor and move to capabilities.
115  virtual bool UpdateOffscreenLayerPixelFormat(PixelFormat format);
116 
117  //----------------------------------------------------------------------------
118  /// @brief Returns the allocator used to create textures and buffers on
119  /// the device.
120  ///
121  /// @return The resource allocator. Can never be `nullptr` for a valid
122  /// context.
123  ///
124  virtual std::shared_ptr<Allocator> GetResourceAllocator() const = 0;
125 
126  //----------------------------------------------------------------------------
127  /// @brief Returns the library of shaders used to specify the
128  /// programmable stages of a pipeline.
129  ///
130  /// @return The shader library. Can never be `nullptr` for a valid
131  /// context.
132  ///
133  virtual std::shared_ptr<ShaderLibrary> GetShaderLibrary() const = 0;
134 
135  //----------------------------------------------------------------------------
136  /// @brief Returns the library of combined image samplers used in
137  /// shaders.
138  ///
139  /// @return The sampler library. Can never be `nullptr` for a valid
140  /// context.
141  ///
142  virtual std::shared_ptr<SamplerLibrary> GetSamplerLibrary() const = 0;
143 
144  //----------------------------------------------------------------------------
145  /// @brief Returns the library of pipelines used by render or compute
146  /// commands.
147  ///
148  /// @return The pipeline library. Can never be `nullptr` for a valid
149  /// context.
150  ///
151  virtual std::shared_ptr<PipelineLibrary> GetPipelineLibrary() const = 0;
152 
153  //----------------------------------------------------------------------------
154  /// @brief Create a new command buffer. Command buffers can be used to
155  /// encode graphics, blit, or compute commands to be submitted to
156  /// the device.
157  ///
158  /// A command buffer can only be used on a single thread.
159  /// Multi-threaded render, blit, or compute passes must create a
160  /// new command buffer on each thread.
161  ///
162  /// @return A new command buffer.
163  ///
164  virtual std::shared_ptr<CommandBuffer> CreateCommandBuffer() const = 0;
165 
166  /// @brief Return the graphics queue for submitting command buffers.
167  virtual std::shared_ptr<CommandQueue> GetCommandQueue() const = 0;
168 
169  //----------------------------------------------------------------------------
170  /// @brief Force all pending asynchronous work to finish. This is
171  /// achieved by deleting all owned concurrent message loops.
172  ///
173  virtual void Shutdown() = 0;
174 
175  /// Stores a task on the `ContextMTL` that is awaiting access for the GPU.
176  ///
177  /// The task will be executed in the event that the GPU access has changed to
178  /// being available or that the task has been canceled. The task should
179  /// operate with the `SyncSwitch` to make sure the GPU is accessible.
180  ///
181  /// If the queue of pending tasks is cleared without GPU access, then the
182  /// failure callback will be invoked and the primary task function will not
183  ///
184  /// Threadsafe.
185  ///
186  /// `task` will be executed on the platform thread.
187  virtual void StoreTaskForGPU(const fml::closure& task,
188  const fml::closure& failure) {
189  FML_CHECK(false && "not supported in this context");
190  }
191 
192  /// Run backend specific additional setup and create common shader variants.
193  ///
194  /// This bootstrap is intended to improve the performance of several
195  /// first frame benchmarks that are tracked in the flutter device lab.
196  /// The workload includes initializing commonly used but not default
197  /// shader variants, as well as forcing driver initialization.
199 
200  /// Dispose resources that are cached on behalf of the current thread.
201  ///
202  /// Some backends such as Vulkan may cache resources that can be reused while
203  /// executing a rendering operation. This API can be called after the
204  /// operation completes in order to clear the cache.
206 
207  /// @brief Enqueue command_buffer for submission by the end of the frame.
208  ///
209  /// Certain backends may immediately flush the command buffer if batch
210  /// submission is not supported. This functionality is not thread safe
211  /// and should only be used via the ContentContext for rendering a
212  /// 2D workload.
213  ///
214  /// Returns true if submission has succeeded. If the buffer is enqueued
215  /// then no error may be returned until FlushCommandBuffers is called.
216  [[nodiscard]] virtual bool EnqueueCommandBuffer(
217  std::shared_ptr<CommandBuffer> command_buffer);
218 
219  /// @brief Flush all pending command buffers.
220  ///
221  /// Returns whether or not submission was successful. This functionality
222  /// is not threadsafe and should only be used via the ContentContext for
223  /// rendering a 2D workload.
224  [[nodiscard]] virtual bool FlushCommandBuffers();
225 
226  virtual bool AddTrackingFence(const std::shared_ptr<Texture>& texture) const;
227 
228  virtual std::shared_ptr<const IdleWaiter> GetIdleWaiter() const;
229 
230  //----------------------------------------------------------------------------
231  /// Resets any thread local state that may interfere with embedders.
232  ///
233  /// Today, only the OpenGL backend can trample on thread local state that the
234  /// embedder can access. This call puts the GL state in a sane "clean" state.
235  ///
236  /// Impeller itself is resilient to a dirty thread local state table.
237  ///
238  virtual void ResetThreadLocalState() const;
239 
240  /// @brief Retrieve the runtime stage for this context type.
241  ///
242  /// This is used by the engine shell and other subsystems for loading the
243  /// correct shader types.
245 
246  /// @brief Submit the command buffer that renders to the onscreen surface.
247  virtual bool SubmitOnscreen(std::shared_ptr<CommandBuffer> cmd_buffer);
248 
249  const Flags& GetFlags() const { return flags_; }
250 
251  protected:
252  explicit Context(const Flags& flags);
253 
255  std::vector<std::function<void()>> per_frame_task_;
256 
257  private:
258  Context(const Context&) = delete;
259 
260  Context& operator=(const Context&) = delete;
261 };
262 
263 } // namespace impeller
264 
265 #endif // FLUTTER_IMPELLER_RENDERER_CONTEXT_H_
To do anything rendering related with Impeller, you need a context.
Definition: context.h:47
virtual std::shared_ptr< const IdleWaiter > GetIdleWaiter() const
Definition: context.cc:28
virtual bool AddTrackingFence(const std::shared_ptr< Texture > &texture) const
Definition: context.cc:36
virtual std::shared_ptr< SamplerLibrary > GetSamplerLibrary() const =0
Returns the library of combined image samplers used in shaders.
virtual std::shared_ptr< CommandBuffer > CreateCommandBuffer() const =0
Create a new command buffer. Command buffers can be used to encode graphics, blit,...
virtual std::shared_ptr< PipelineLibrary > GetPipelineLibrary() const =0
Returns the library of pipelines used by render or compute commands.
virtual bool SubmitOnscreen(std::shared_ptr< CommandBuffer > cmd_buffer)
Submit the command buffer that renders to the onscreen surface.
Definition: context.cc:40
virtual std::shared_ptr< ShaderLibrary > GetShaderLibrary() const =0
Returns the library of shaders used to specify the programmable stages of a pipeline.
const Flags & GetFlags() const
Definition: context.h:249
static constexpr int32_t kMaxTasksAwaitingGPU
Definition: context.h:61
virtual const std::shared_ptr< const Capabilities > & GetCapabilities() const =0
Get the capabilities of Impeller context. All optionally supported feature of the platform,...
std::vector< std::function< void()> > per_frame_task_
Definition: context.h:255
virtual bool UpdateOffscreenLayerPixelFormat(PixelFormat format)
Definition: context.cc:15
virtual BackendType GetBackendType() const =0
Get the graphics backend of an Impeller context.
virtual void Shutdown()=0
Force all pending asynchronous work to finish. This is achieved by deleting all owned concurrent mess...
Context(const Flags &flags)
Definition: context.cc:13
virtual void DisposeThreadLocalCachedResources()
Definition: context.h:205
virtual bool FlushCommandBuffers()
Flush all pending command buffers.
Definition: context.cc:24
virtual std::shared_ptr< CommandQueue > GetCommandQueue() const =0
Return the graphics queue for submitting command buffers.
virtual RuntimeStageBackend GetRuntimeStageBackend() const =0
Retrieve the runtime stage for this context type.
virtual void StoreTaskForGPU(const fml::closure &task, const fml::closure &failure)
Definition: context.h:187
virtual void InitializeCommonlyUsedShadersIfNeeded() const
Definition: context.h:198
virtual std::shared_ptr< Allocator > GetResourceAllocator() const =0
Returns the allocator used to create textures and buffers on the device.
virtual std::string DescribeGpuModel() const =0
virtual ~Context()
Destroys an Impeller context.
virtual bool IsValid() const =0
Determines if a context is valid. If the caller ever receives an invalid context, they must discard i...
virtual void ResetThreadLocalState() const
Definition: context.cc:32
virtual bool EnqueueCommandBuffer(std::shared_ptr< CommandBuffer > command_buffer)
Enqueue command_buffer for submission by the end of the frame.
Definition: context.cc:19
PixelFormat
The Pixel formats supported by Impeller. The naming convention denotes the usage of the component,...
Definition: formats.h:99