| Flutter Impeller |

context_vk.cc
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 #include "impeller/renderer/backend/vulkan/context_vk.h"
6 #include <thread>
7 #include <unordered_map>
8
9 #include "fml/concurrent_message_loop.h"
10 #include "impeller/core/formats.h"
11 #include "impeller/core/runtime_types.h"
12 #include "impeller/renderer/backend/vulkan/command_queue_vk.h"
13 #include "impeller/renderer/backend/vulkan/descriptor_pool_vk.h"
14 #include "impeller/renderer/backend/vulkan/render_pass_builder_vk.h"
15 #include "impeller/renderer/backend/vulkan/workarounds_vk.h"
16 #include "impeller/renderer/render_target.h"
17
18 #ifdef FML_OS_ANDROID
19 #include <pthread.h>
20 #include <sys/resource.h>
21 #include <sys/time.h>
22 #endif // FML_OS_ANDROID
23
24 #include <map>
25 #include <memory>
26 #include <optional>
27 #include <string>
28 #include <vector>
29
30 #include "flutter/fml/cpu_affinity.h"
31 #include "flutter/fml/trace_event.h"
32 #include "impeller/base/validation.h"
33 #include "impeller/renderer/backend/vulkan/allocator_vk.h"
34 #include "impeller/renderer/backend/vulkan/capabilities_vk.h"
35 #include "impeller/renderer/backend/vulkan/command_buffer_vk.h"
36 #include "impeller/renderer/backend/vulkan/command_pool_vk.h"
37 #include "impeller/renderer/backend/vulkan/command_queue_vk.h"
38 #include "impeller/renderer/backend/vulkan/debug_report_vk.h"
39 #include "impeller/renderer/backend/vulkan/descriptor_pool_vk.h"
40 #include "impeller/renderer/backend/vulkan/fence_waiter_vk.h"
41 #include "impeller/renderer/backend/vulkan/gpu_tracer_vk.h"
42 #include "impeller/renderer/backend/vulkan/resource_manager_vk.h"
43 #include "impeller/renderer/backend/vulkan/surface_context_vk.h"
44 #include "impeller/renderer/backend/vulkan/yuv_conversion_library_vk.h"
45 #include "impeller/renderer/capabilities.h"
46
47 VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE
48
49 namespace impeller {
50
51 static bool gHasValidationLayers = false;
52
53 bool HasValidationLayers() {
54 return gHasValidationLayers;
55 }
56
57 static std::optional<vk::PhysicalDevice> PickPhysicalDevice(
58 const CapabilitiesVK& caps,
59 const vk::Instance& instance) {
60 for (const auto& device : instance.enumeratePhysicalDevices().value) {
61 if (caps.GetEnabledDeviceFeatures(device).has_value()) {
62 return device;
63 }
64 }
65 return std::nullopt;
66 }
67
68 static std::vector<vk::DeviceQueueCreateInfo> GetQueueCreateInfos(
69 std::initializer_list<QueueIndexVK> queues) {
70 std::map<size_t /* family */, size_t /* index */> family_index_map;
71 for (const auto& queue : queues) {
72 family_index_map[queue.family] = 0;
73 }
74 for (const auto& queue : queues) {
75 auto value = family_index_map[queue.family];
76 family_index_map[queue.family] = std::max(value, queue.index);
77 }
78
79 static float kQueuePriority = 1.0f;
80 std::vector<vk::DeviceQueueCreateInfo> infos;
81 for (const auto& item : family_index_map) {
82 vk::DeviceQueueCreateInfo info;
83 info.setQueueFamilyIndex(item.first);
84 info.setQueueCount(item.second + 1);
85 info.setQueuePriorities(kQueuePriority);
86 infos.push_back(info);
87 }
88 return infos;
89 }
90
91 static std::optional<QueueIndexVK> PickQueue(const vk::PhysicalDevice& device,
92 vk::QueueFlagBits flags) {
93 // This can be modified to ensure that dedicated queues are returned for each
94 // queue type depending on support.
95 const auto families = device.getQueueFamilyProperties();
96 for (size_t i = 0u; i < families.size(); i++) {
97 if (!(families[i].queueFlags & flags)) {
98 continue;
99 }
100 return QueueIndexVK{.family = i, .index = 0};
101 }
102 return std::nullopt;
103 }
104
105 std::shared_ptr<ContextVK> ContextVK::Create(Settings settings) {
106 auto context = std::shared_ptr<ContextVK>(new ContextVK(settings.flags));
107 context->Setup(std::move(settings));
108 if (!context->IsValid()) {
109 return nullptr;
110 }
111 return context;
112 }
113
114 // static
115 size_t ContextVK::ChooseThreadCountForWorkers(size_t hardware_concurrency) {
116 // Never create more than 4 worker threads. Attempt to use up to
117 // half of the available concurrency.
118 return std::clamp(hardware_concurrency / 2ull, /*lo=*/1ull, /*hi=*/4ull);
119 }
120
121 namespace {
122 thread_local uint64_t tls_context_count = 0;
123 uint64_t CalculateHash(void* ptr) {
124 // You could make a context once per nanosecond for 584 years on one thread
125 // before this overflows.
126 return ++tls_context_count;
127 }
128 } // namespace
129
130 ContextVK::ContextVK(const Flags& flags)
131 : Context(flags), hash_(CalculateHash(this)) {}
132
133 ContextVK::~ContextVK() {
134 if (device_holder_ && device_holder_->device) {
135 [[maybe_unused]] auto result = device_holder_->device->waitIdle();
136 }
137 if (command_pool_recycler_) {
138 command_pool_recycler_->DestroyThreadLocalPools();
139 }
140 }
141
142 Context::BackendType ContextVK::GetBackendType() const {
143 return Context::BackendType::kVulkan;
144 }
145
146 void ContextVK::Setup(Settings settings) {
147 TRACE_EVENT0("impeller", "ContextVK::Setup");
148
149 if (!settings.proc_address_callback) {
150 VALIDATION_LOG << "Missing proc address callback.";
151 return;
152 }
153
154 raster_message_loop_ = fml::ConcurrentMessageLoop::Create(
155 ChooseThreadCountForWorkers(std::thread::hardware_concurrency()));
156
157 auto& dispatcher = VULKAN_HPP_DEFAULT_DISPATCHER;
158 dispatcher.init(settings.proc_address_callback);
159
160 std::vector<std::string> embedder_instance_extensions;
161 std::vector<std::string> embedder_device_extensions;
162 if (settings.embedder_data.has_value()) {
163 embedder_instance_extensions = settings.embedder_data->instance_extensions;
164 embedder_device_extensions = settings.embedder_data->device_extensions;
165 }
166 auto caps = std::shared_ptr<CapabilitiesVK>(new CapabilitiesVK(
167 settings.enable_validation, //
168 settings.fatal_missing_validations, //
169 /*use_embedder_extensions=*/settings.embedder_data.has_value(), //
170 embedder_instance_extensions, //
171 embedder_device_extensions //
172 ));
173
174 if (!caps->IsValid()) {
175 VALIDATION_LOG << "Could not determine device capabilities.";
176 return;
177 }
178
179 gHasValidationLayers = caps->AreValidationsEnabled();
180
181 auto enabled_layers = caps->GetEnabledLayers();
182 auto enabled_extensions = caps->GetEnabledInstanceExtensions();
183
184 if (!enabled_layers.has_value() || !enabled_extensions.has_value()) {
185 VALIDATION_LOG << "Device has insufficient capabilities.";
186 return;
187 }
188
189 vk::InstanceCreateFlags instance_flags = {};
190
191 if (std::find(enabled_extensions.value().begin(),
192 enabled_extensions.value().end(),
193 "VK_KHR_portability_enumeration") !=
194 enabled_extensions.value().end()) {
195 instance_flags |= vk::InstanceCreateFlagBits::eEnumeratePortabilityKHR;
196 }
197
198 std::vector<const char*> enabled_layers_c;
199 std::vector<const char*> enabled_extensions_c;
200
201 for (const auto& layer : enabled_layers.value()) {
202 enabled_layers_c.push_back(layer.c_str());
203 }
204
205 for (const auto& ext : enabled_extensions.value()) {
206 enabled_extensions_c.push_back(ext.c_str());
207 }
208
209 vk::ApplicationInfo application_info;
210
211 // Use the same encoding macro as vulkan versions, but otherwise application
212 // version is intended to be the version of the Impeller engine. This version
213 // information, along with the application name below is provided to allow
214 // IHVs to make optimizations and/or disable functionality based on knowledge
215 // of the engine version (for example, to work around bugs). We don't tie this
216 // to the overall Flutter version as that version is not yet defined when the
217 // engine is compiled. Instead we can manually bump it occassionally.
218 //
219 // variant, major, minor, patch
220 application_info.setApplicationVersion(
221 VK_MAKE_API_VERSION(0, 2, 0, 0) /*version 2.0.0*/);
222 application_info.setApiVersion(VK_API_VERSION_1_1);
223 application_info.setEngineVersion(VK_API_VERSION_1_0);
224 application_info.setPEngineName("Impeller");
225 application_info.setPApplicationName("Impeller");
226
227 vk::StructureChain<vk::InstanceCreateInfo, vk::ValidationFeaturesEXT>
228 instance_chain;
229
230 if (!caps->AreValidationsEnabled()) {
231 instance_chain.unlink<vk::ValidationFeaturesEXT>();
232 }
233
234 std::vector<vk::ValidationFeatureEnableEXT> enabled_validations = {
235 vk::ValidationFeatureEnableEXT::eSynchronizationValidation,
236 };
237
238 auto validation = instance_chain.get<vk::ValidationFeaturesEXT>();
239 validation.setEnabledValidationFeatures(enabled_validations);
240
241 auto instance_info = instance_chain.get<vk::InstanceCreateInfo>();
242 instance_info.setPEnabledLayerNames(enabled_layers_c);
243 instance_info.setPEnabledExtensionNames(enabled_extensions_c);
244 instance_info.setPApplicationInfo(&application_info);
245 instance_info.setFlags(instance_flags);
246
247 auto device_holder = std::make_shared<DeviceHolderImpl>();
248 if (!settings.embedder_data.has_value()) {
249 auto instance = vk::createInstanceUnique(instance_info);
250 if (instance.result != vk::Result::eSuccess) {
251 VALIDATION_LOG << "Could not create Vulkan instance: "
252 << vk::to_string(instance.result);
253 return;
254 }
255 device_holder->instance = std::move(instance.value);
256 } else {
257 device_holder->instance.reset(settings.embedder_data->instance);
258 device_holder->owned = false;
259 }
260 dispatcher.init(device_holder->instance.get());
261
262 //----------------------------------------------------------------------------
263 /// Setup the debug report.
264 ///
265 /// Do this as early as possible since we could use the debug report from
266 /// initialization issues.
267 ///
268 auto debug_report =
269 std::make_unique<DebugReportVK>(*caps, device_holder->instance.get());
270
271 if (!debug_report->IsValid()) {
272 VALIDATION_LOG << "Could not set up debug report.";
273 return;
274 }
275
276 //----------------------------------------------------------------------------
277 /// Pick the physical device.
278 ///
279 if (!settings.embedder_data.has_value()) {
280 auto physical_device =
281 PickPhysicalDevice(*caps, device_holder->instance.get());
282 if (!physical_device.has_value()) {
283 VALIDATION_LOG << "No valid Vulkan device found.";
284 return;
285 }
286 device_holder->physical_device = physical_device.value();
287 } else {
288 device_holder->physical_device = settings.embedder_data->physical_device;
289 }
290
291 //----------------------------------------------------------------------------
292 /// Pick device queues.
293 ///
294 auto graphics_queue =
295 PickQueue(device_holder->physical_device, vk::QueueFlagBits::eGraphics);
296 auto transfer_queue =
297 PickQueue(device_holder->physical_device, vk::QueueFlagBits::eTransfer);
298 auto compute_queue =
299 PickQueue(device_holder->physical_device, vk::QueueFlagBits::eCompute);
300
301 if (!graphics_queue.has_value()) {
302 VALIDATION_LOG << "Could not pick graphics queue.";
303 return;
304 }
305 if (!transfer_queue.has_value()) {
306 transfer_queue = graphics_queue.value();
307 }
308 if (!compute_queue.has_value()) {
309 VALIDATION_LOG << "Could not pick compute queue.";
310 return;
311 }
312
313 //----------------------------------------------------------------------------
314 /// Create the logical device.
315 ///
316 auto enabled_device_extensions =
317 caps->GetEnabledDeviceExtensions(device_holder->physical_device);
318 if (!enabled_device_extensions.has_value()) {
319 // This shouldn't happen since we already did device selection. But
320 // doesn't hurt to check again.
321 return;
322 }
323
324 std::vector<const char*> enabled_device_extensions_c;
325 for (const auto& ext : enabled_device_extensions.value()) {
326 enabled_device_extensions_c.push_back(ext.c_str());
327 }
328
329 const auto queue_create_infos = GetQueueCreateInfos(
330 {graphics_queue.value(), compute_queue.value(), transfer_queue.value()});
331
332 const auto enabled_features =
333 caps->GetEnabledDeviceFeatures(device_holder->physical_device);
334 if (!enabled_features.has_value()) {
335 // This shouldn't happen since the device can't be picked if this was not
336 // true. But doesn't hurt to check.
337 return;
338 }
339
340 vk::DeviceCreateInfo device_info;
341
342 device_info.setPNext(&enabled_features.value().get());
343 device_info.setQueueCreateInfos(queue_create_infos);
344 device_info.setPEnabledExtensionNames(enabled_device_extensions_c);
345 // Device layers are deprecated and ignored.
346
347 if (!settings.embedder_data.has_value()) {
348 auto device_result =
349 device_holder->physical_device.createDeviceUnique(device_info);
350 if (device_result.result != vk::Result::eSuccess) {
351 VALIDATION_LOG << "Could not create logical device.";
352 return;
353 }
354 device_holder->device = std::move(device_result.value);
355 } else {
356 device_holder->device.reset(settings.embedder_data->device);
357 }
358
359 if (!caps->SetPhysicalDevice(device_holder->physical_device,
360 *enabled_features)) {
361 VALIDATION_LOG << "Capabilities could not be updated.";
362 return;
363 }
364
365 //----------------------------------------------------------------------------
366 /// Create the allocator.
367 ///
368 auto allocator = std::shared_ptr<AllocatorVK>(new AllocatorVK(
369 weak_from_this(), //
370 application_info.apiVersion, //
371 device_holder->physical_device, //
372 device_holder, //
373 device_holder->instance.get(), //
374 *caps //
375 ));
376
377 if (!allocator->IsValid()) {
378 VALIDATION_LOG << "Could not create memory allocator.";
379 return;
380 }
381
382 //----------------------------------------------------------------------------
383 /// Setup the pipeline library.
384 ///
385 auto pipeline_library = std::shared_ptr<PipelineLibraryVK>(
386 new PipelineLibraryVK(device_holder, //
387 caps, //
388 std::move(settings.cache_directory), //
389 raster_message_loop_->GetTaskRunner() //
390 ));
391
392 if (!pipeline_library->IsValid()) {
393 VALIDATION_LOG << "Could not create pipeline library.";
394 return;
395 }
396
397 auto sampler_library =
398 std::shared_ptr<SamplerLibraryVK>(new SamplerLibraryVK(device_holder));
399
400 auto shader_library = std::shared_ptr<ShaderLibraryVK>(
401 new ShaderLibraryVK(device_holder, //
402 settings.shader_libraries_data) //
403 );
404
405 if (!shader_library->IsValid()) {
406 VALIDATION_LOG << "Could not create shader library.";
407 return;
408 }
409
410 //----------------------------------------------------------------------------
411 /// Create the fence waiter.
412 ///
413 auto fence_waiter =
414 std::shared_ptr<FenceWaiterVK>(new FenceWaiterVK(device_holder));
415
416 //----------------------------------------------------------------------------
417 /// Create the resource manager and command pool recycler.
418 ///
419 auto resource_manager = ResourceManagerVK::Create();
420 if (!resource_manager) {
421 VALIDATION_LOG << "Could not create resource manager.";
422 return;
423 }
424
425 auto command_pool_recycler =
426 std::make_shared<CommandPoolRecyclerVK>(shared_from_this());
427 if (!command_pool_recycler) {
428 VALIDATION_LOG << "Could not create command pool recycler.";
429 return;
430 }
431
432 auto descriptor_pool_recycler =
433 std::make_shared<DescriptorPoolRecyclerVK>(weak_from_this());
434 if (!descriptor_pool_recycler) {
435 VALIDATION_LOG << "Could not create descriptor pool recycler.";
436 return;
437 }
438
439 //----------------------------------------------------------------------------
440 /// Fetch the queues.
441 ///
442 QueuesVK queues;
443 if (!settings.embedder_data.has_value()) {
444 queues = QueuesVK::FromQueueIndices(device_holder->device.get(), //
445 graphics_queue.value(), //
446 compute_queue.value(), //
447 transfer_queue.value() //
448 );
449 } else {
450 queues =
451 QueuesVK::FromEmbedderQueue(settings.embedder_data->queue,
452 settings.embedder_data->queue_family_index);
453 }
454 if (!queues.IsValid()) {
455 VALIDATION_LOG << "Could not fetch device queues.";
456 return;
457 }
458
459 VkPhysicalDeviceProperties physical_device_properties;
460 dispatcher.vkGetPhysicalDeviceProperties(device_holder->physical_device,
461 &physical_device_properties);
462
463 //----------------------------------------------------------------------------
464 /// All done!
465 ///
466
467 // Apply workarounds for broken drivers.
468 auto driver_info =
469 std::make_unique<DriverInfoVK>(device_holder->physical_device);
470 workarounds_ = GetWorkaroundsFromDriverInfo(*driver_info);
471 caps->ApplyWorkarounds(workarounds_);
472 sampler_library->ApplyWorkarounds(workarounds_);
473
474 device_holder_ = std::move(device_holder);
475 idle_waiter_vk_ = std::make_shared<IdleWaiterVK>(device_holder_);
476 driver_info_ = std::move(driver_info);
477 debug_report_ = std::move(debug_report);
478 allocator_ = std::move(allocator);
479 shader_library_ = std::move(shader_library);
480 sampler_library_ = std::move(sampler_library);
481 pipeline_library_ = std::move(pipeline_library);
482 yuv_conversion_library_ = std::shared_ptr<YUVConversionLibraryVK>(
483 new YUVConversionLibraryVK(device_holder_));
484 queues_ = std::move(queues);
485 device_capabilities_ = std::move(caps);
486 fence_waiter_ = std::move(fence_waiter);
487 resource_manager_ = std::move(resource_manager);
488 command_pool_recycler_ = std::move(command_pool_recycler);
489 descriptor_pool_recycler_ = std::move(descriptor_pool_recycler);
490 device_name_ = std::string(physical_device_properties.deviceName);
491 command_queue_vk_ = std::make_shared<CommandQueueVK>(weak_from_this());
492 should_enable_surface_control_ = settings.enable_surface_control;
493 should_batch_cmd_buffers_ = !workarounds_.batch_submit_command_buffer_timeout;
494 is_valid_ = true;
495
496 // Create the GPU Tracer later because it depends on state from
497 // the ContextVK.
498 gpu_tracer_ = std::make_shared<GPUTracerVK>(weak_from_this(),
499 settings.enable_gpu_tracing);
500 gpu_tracer_->InitializeQueryPool(*this);
501
502 //----------------------------------------------------------------------------
503 /// Label all the relevant objects. This happens after setup so that the
504 /// debug messengers have had a chance to be set up.
505 ///
506 SetDebugName(GetDevice(), device_holder_->device.get(), "ImpellerDevice");
507 }
508
509 void ContextVK::SetOffscreenFormat(PixelFormat pixel_format) {
510 CapabilitiesVK::Cast(*device_capabilities_).SetOffscreenFormat(pixel_format);
511 }
512
513 // |Context|
514 std::string ContextVK::DescribeGpuModel() const {
515 return device_name_;
516 }
517
518 bool ContextVK::IsValid() const {
519 return is_valid_;
520 }
521
522 std::shared_ptr<Allocator> ContextVK::GetResourceAllocator() const {
523 return allocator_;
524 }
525
526 std::shared_ptr<ShaderLibrary> ContextVK::GetShaderLibrary() const {
527 return shader_library_;
528 }
529
530 std::shared_ptr<SamplerLibrary> ContextVK::GetSamplerLibrary() const {
531 return sampler_library_;
532 }
533
534 std::shared_ptr<PipelineLibrary> ContextVK::GetPipelineLibrary() const {
535 return pipeline_library_;
536 }
537
538 std::shared_ptr<CommandBuffer> ContextVK::CreateCommandBuffer() const {
539 const auto& recycler = GetCommandPoolRecycler();
540 auto tls_pool = recycler->Get();
541 if (!tls_pool) {
542 return nullptr;
543 }
544
545 // look up a cached descriptor pool for the current frame and reuse it
546 // if it exists, otherwise create a new pool.
547 std::shared_ptr<DescriptorPoolVK> descriptor_pool;
548 {
549 Lock lock(desc_pool_mutex_);
550 DescriptorPoolMap::iterator current_pool =
551 cached_descriptor_pool_.find(std::this_thread::get_id());
552 if (current_pool == cached_descriptor_pool_.end()) {
553 descriptor_pool = (cached_descriptor_pool_[std::this_thread::get_id()] =
554 descriptor_pool_recycler_->GetDescriptorPool());
555 } else {
556 descriptor_pool = current_pool->second;
557 }
558 }
559
560 auto tracked_objects = std::make_shared<TrackedObjectsVK>(
561 weak_from_this(), std::move(tls_pool), std::move(descriptor_pool),
562 GetGPUTracer()->CreateGPUProbe());
563 auto queue = GetGraphicsQueue();
564
565 if (!tracked_objects || !tracked_objects->IsValid() || !queue) {
566 return nullptr;
567 }
568
569 vk::CommandBufferBeginInfo begin_info;
570 begin_info.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit;
571 if (tracked_objects->GetCommandBuffer().begin(begin_info) !=
572 vk::Result::eSuccess) {
573 VALIDATION_LOG << "Could not begin command buffer.";
574 return nullptr;
575 }
576
577 tracked_objects->GetGPUProbe().RecordCmdBufferStart(
578 tracked_objects->GetCommandBuffer());
579
580 return std::shared_ptr<CommandBufferVK>(new CommandBufferVK(
581 shared_from_this(), //
582 GetDeviceHolder(), //
583 std::move(tracked_objects) //
584 ));
585 }
586
587 vk::Instance ContextVK::GetInstance() const {
588 return *device_holder_->instance;
589 }
590
591 const vk::Device& ContextVK::GetDevice() const {
592 return device_holder_->device.get();
593 }
594
595 const std::shared_ptr<fml::ConcurrentTaskRunner>
596 ContextVK::GetConcurrentWorkerTaskRunner() const {
597 return raster_message_loop_->GetTaskRunner();
598 }
599
600 void ContextVK::Shutdown() {
601 // There are multiple objects, for example |CommandPoolVK|, that in their
602 // destructors make a strong reference to |ContextVK|. Resetting these shared
603 // pointers ensures that cleanup happens in a correct order.
604 //
605 // tl;dr: Without it, we get thread::join failures on shutdown.
606 fence_waiter_.reset();
607 resource_manager_.reset();
608
609 raster_message_loop_->Terminate();
610 }
611
612 std::shared_ptr<SurfaceContextVK> ContextVK::CreateSurfaceContext() {
613 return std::make_shared<SurfaceContextVK>(shared_from_this());
614 }
615
616 const std::shared_ptr<const Capabilities>& ContextVK::GetCapabilities() const {
617 return device_capabilities_;
618 }
619
620 const std::shared_ptr<QueueVK>& ContextVK::GetGraphicsQueue() const {
621 return queues_.graphics_queue;
622 }
623
624 vk::PhysicalDevice ContextVK::GetPhysicalDevice() const {
625 return device_holder_->physical_device;
626 }
627
628 std::shared_ptr<FenceWaiterVK> ContextVK::GetFenceWaiter() const {
629 return fence_waiter_;
630 }
631
632 std::shared_ptr<ResourceManagerVK> ContextVK::GetResourceManager() const {
633 return resource_manager_;
634 }
635
636 std::shared_ptr<CommandPoolRecyclerVK> ContextVK::GetCommandPoolRecycler()
637 const {
638 return command_pool_recycler_;
639 }
640
641 std::shared_ptr<GPUTracerVK> ContextVK::GetGPUTracer() const {
642 return gpu_tracer_;
643 }
644
645 std::shared_ptr<DescriptorPoolRecyclerVK> ContextVK::GetDescriptorPoolRecycler()
646 const {
647 return descriptor_pool_recycler_;
648 }
649
650 std::shared_ptr<CommandQueue> ContextVK::GetCommandQueue() const {
651 return command_queue_vk_;
652 }
653
654 bool ContextVK::EnqueueCommandBuffer(
655 std::shared_ptr<CommandBuffer> command_buffer) {
656 if (should_batch_cmd_buffers_) {
657 pending_command_buffers_.push_back(std::move(command_buffer));
658 return true;
659 } else {
660 return GetCommandQueue()->Submit({command_buffer}).ok();
661 }
662 }
663
664 bool ContextVK::FlushCommandBuffers() {
665 if (pending_command_buffers_.empty()) {
666 return true;
667 }
668
669 if (should_batch_cmd_buffers_) {
670 bool result = GetCommandQueue()->Submit(pending_command_buffers_).ok();
671 pending_command_buffers_.clear();
672 return result;
673 } else {
674 return true;
675 }
676 }
677
678 // Creating a render pass is observed to take an additional 6ms on a Pixel 7
679 // device as the driver will lazily bootstrap and compile shaders to do so.
680 // The render pass does not need to be begun or executed.
681 void ContextVK::InitializeCommonlyUsedShadersIfNeeded() const {
682 RenderTargetAllocator rt_allocator(GetResourceAllocator());
683 RenderTarget render_target =
684 rt_allocator.CreateOffscreenMSAA(*this, {1, 1}, 1);
685
686 RenderPassBuilderVK builder;
687
688 render_target.IterateAllColorAttachments(
689 [&builder](size_t index, const ColorAttachment& attachment) -> bool {
690 builder.SetColorAttachment(
691 index, //
692 attachment.texture->GetTextureDescriptor().format, //
693 attachment.texture->GetTextureDescriptor().sample_count, //
694 attachment.load_action, //
695 attachment.store_action //
696 );
697 return true;
698 });
699
700 if (auto depth = render_target.GetDepthAttachment(); depth.has_value()) {
701 builder.SetDepthStencilAttachment(
702 depth->texture->GetTextureDescriptor().format, //
703 depth->texture->GetTextureDescriptor().sample_count, //
704 depth->load_action, //
705 depth->store_action //
706 );
707 } else if (auto stencil = render_target.GetStencilAttachment();
708 stencil.has_value()) {
709 builder.SetStencilAttachment(
710 stencil->texture->GetTextureDescriptor().format, //
711 stencil->texture->GetTextureDescriptor().sample_count, //
712 stencil->load_action, //
713 stencil->store_action //
714 );
715 }
716
717 auto pass = builder.Build(GetDevice());
718 }
719
720 void ContextVK::DisposeThreadLocalCachedResources() {
721 {
722 Lock lock(desc_pool_mutex_);
723 cached_descriptor_pool_.erase(std::this_thread::get_id());
724 }
725 command_pool_recycler_->Dispose();
726 }
727
728 const std::shared_ptr<YUVConversionLibraryVK>&
729 ContextVK::GetYUVConversionLibrary() const {
730 return yuv_conversion_library_;
731 }
732
733 const std::unique_ptr<DriverInfoVK>& ContextVK::GetDriverInfo() const {
734 return driver_info_;
735 }
736
737 bool ContextVK::GetShouldEnableSurfaceControlSwapchain() const {
738 return should_enable_surface_control_ &&
739 CapabilitiesVK::Cast(*device_capabilities_)
740 .SupportsExternalSemaphoreExtensions();
741 }
742
743 RuntimeStageBackend ContextVK::GetRuntimeStageBackend() const {
744 return RuntimeStageBackend::kVulkan;
745 }
746
747 bool ContextVK::SubmitOnscreen(std::shared_ptr<CommandBuffer> cmd_buffer) {
748 return EnqueueCommandBuffer(std::move(cmd_buffer));
749 }
750
751 const WorkaroundsVK& ContextVK::GetWorkarounds() const {
752 return workarounds_;
753 }
754
755 } // namespace impeller
allocator_vk.h
capabilities.h
capabilities_vk.h
impeller::BackendCast< CapabilitiesVK, Capabilities >::Cast
static CapabilitiesVK & Cast(Capabilities &base)
Definition: backend_cast.h:13
impeller::CapabilitiesVK
The Vulkan layers and extensions wrangler.
Definition: capabilities_vk.h:181
impeller::CapabilitiesVK::SupportsExternalSemaphoreExtensions
bool SupportsExternalSemaphoreExtensions() const
Definition: capabilities_vk.cc:811
impeller::CapabilitiesVK::SetOffscreenFormat
void SetOffscreenFormat(PixelFormat pixel_format) const
Definition: capabilities_vk.cc:510
impeller::CapabilitiesVK::GetEnabledDeviceFeatures
std::optional< PhysicalDeviceFeatures > GetEnabledDeviceFeatures(const vk::PhysicalDevice &physical_device) const
Definition: capabilities_vk.cc:395
impeller::CommandBufferVK
Definition: command_buffer_vk.h:27
impeller::Context::BackendType
BackendType
Definition: context.h:49
impeller::Context::BackendType::kVulkan
@ kVulkan
impeller::ContextVK
Definition: context_vk.h:66
impeller::ContextVK::SetOffscreenFormat
void SetOffscreenFormat(PixelFormat pixel_format)
Definition: context_vk.cc:509
impeller::ContextVK::GetResourceAllocator
std::shared_ptr< Allocator > GetResourceAllocator() const override
Returns the allocator used to create textures and buffers on the device.
Definition: context_vk.cc:522
impeller::ContextVK::GetResourceManager
std::shared_ptr< ResourceManagerVK > GetResourceManager() const
Definition: context_vk.cc:632
impeller::ContextVK::GetPhysicalDevice
vk::PhysicalDevice GetPhysicalDevice() const
Definition: context_vk.cc:624
impeller::ContextVK::GetYUVConversionLibrary
const std::shared_ptr< YUVConversionLibraryVK > & GetYUVConversionLibrary() const
Definition: context_vk.cc:729
impeller::ContextVK::SetDebugName
bool SetDebugName(T handle, std::string_view label) const
Definition: context_vk.h:151
impeller::ContextVK::EnqueueCommandBuffer
bool EnqueueCommandBuffer(std::shared_ptr< CommandBuffer > command_buffer) override
Enqueue command_buffer for submission by the end of the frame.
Definition: context_vk.cc:654
impeller::ContextVK::GetDevice
const vk::Device & GetDevice() const
Definition: context_vk.cc:591
impeller::ContextVK::FlushCommandBuffers
bool FlushCommandBuffers() override
Flush all pending command buffers.
Definition: context_vk.cc:664
impeller::ContextVK::IsValid
bool IsValid() const override
Determines if a context is valid. If the caller ever receives an invalid context, they must discard i...
Definition: context_vk.cc:518
impeller::ContextVK::GetDriverInfo
const std::unique_ptr< DriverInfoVK > & GetDriverInfo() const
Definition: context_vk.cc:733
impeller::ContextVK::DisposeThreadLocalCachedResources
void DisposeThreadLocalCachedResources() override
Definition: context_vk.cc:720
impeller::ContextVK::CreateCommandBuffer
std::shared_ptr< CommandBuffer > CreateCommandBuffer() const override
Create a new command buffer. Command buffers can be used to encode graphics, blit,...
Definition: context_vk.cc:538
impeller::ContextVK::SubmitOnscreen
virtual bool SubmitOnscreen(std::shared_ptr< CommandBuffer > cmd_buffer) override
Submit the command buffer that renders to the onscreen surface.
Definition: context_vk.cc:747
impeller::ContextVK::GetSamplerLibrary
std::shared_ptr< SamplerLibrary > GetSamplerLibrary() const override
Returns the library of combined image samplers used in shaders.
Definition: context_vk.cc:530
impeller::ContextVK::Create
static std::shared_ptr< ContextVK > Create(Settings settings)
Definition: context_vk.cc:105
impeller::ContextVK::GetPipelineLibrary
std::shared_ptr< PipelineLibrary > GetPipelineLibrary() const override
Returns the library of pipelines used by render or compute commands.
Definition: context_vk.cc:534
impeller::ContextVK::GetGraphicsQueue
const std::shared_ptr< QueueVK > & GetGraphicsQueue() const
Definition: context_vk.cc:620
impeller::ContextVK::GetCapabilities
const std::shared_ptr< const Capabilities > & GetCapabilities() const override
Get the capabilities of Impeller context. All optionally supported feature of the platform,...
Definition: context_vk.cc:616
impeller::ContextVK::GetRuntimeStageBackend
RuntimeStageBackend GetRuntimeStageBackend() const override
Retrieve the runtime stage for this context type.
Definition: context_vk.cc:743
impeller::ContextVK::GetCommandPoolRecycler
std::shared_ptr< CommandPoolRecyclerVK > GetCommandPoolRecycler() const
Definition: context_vk.cc:636
impeller::ContextVK::GetCommandQueue
std::shared_ptr< CommandQueue > GetCommandQueue() const override
Return the graphics queue for submitting command buffers.
Definition: context_vk.cc:650
impeller::ContextVK::InitializeCommonlyUsedShadersIfNeeded
void InitializeCommonlyUsedShadersIfNeeded() const override
Definition: context_vk.cc:681
impeller::ContextVK::GetFenceWaiter
std::shared_ptr< FenceWaiterVK > GetFenceWaiter() const
Definition: context_vk.cc:628
impeller::ContextVK::GetShouldEnableSurfaceControlSwapchain
bool GetShouldEnableSurfaceControlSwapchain() const
Whether the Android Surface control based swapchain should be enabled.
Definition: context_vk.cc:737
impeller::ContextVK::GetGPUTracer
std::shared_ptr< GPUTracerVK > GetGPUTracer() const
Definition: context_vk.cc:641
impeller::ContextVK::GetBackendType
BackendType GetBackendType() const override
Get the graphics backend of an Impeller context.
Definition: context_vk.cc:142
impeller::ContextVK::~ContextVK
~ContextVK() override
Definition: context_vk.cc:133
impeller::ContextVK::DescribeGpuModel
std::string DescribeGpuModel() const override
Definition: context_vk.cc:514
impeller::ContextVK::GetWorkarounds
const WorkaroundsVK & GetWorkarounds() const
Definition: context_vk.cc:751
impeller::ContextVK::GetConcurrentWorkerTaskRunner
const std::shared_ptr< fml::ConcurrentTaskRunner > GetConcurrentWorkerTaskRunner() const
Definition: context_vk.cc:596
impeller::ContextVK::ChooseThreadCountForWorkers
static size_t ChooseThreadCountForWorkers(size_t hardware_concurrency)
Definition: context_vk.cc:115
impeller::ContextVK::GetShaderLibrary
std::shared_ptr< ShaderLibrary > GetShaderLibrary() const override
Returns the library of shaders used to specify the programmable stages of a pipeline.
Definition: context_vk.cc:526
impeller::ContextVK::GetInstance
vk::Instance GetInstance() const
Definition: context_vk.cc:587
impeller::ContextVK::GetDeviceHolder
std::shared_ptr< DeviceHolderVK > GetDeviceHolder() const
Definition: context_vk.h:191
impeller::ContextVK::Shutdown
void Shutdown() override
Force all pending asynchronous work to finish. This is achieved by deleting all owned concurrent mess...
Definition: context_vk.cc:600
impeller::ContextVK::GetDescriptorPoolRecycler
std::shared_ptr< DescriptorPoolRecyclerVK > GetDescriptorPoolRecycler() const
Definition: context_vk.cc:645
impeller::ContextVK::CreateSurfaceContext
std::shared_ptr< SurfaceContextVK > CreateSurfaceContext()
Definition: context_vk.cc:612
impeller::Lock
Definition: thread.h:72
impeller::RenderPassBuilderVK
Definition: render_pass_builder_vk.h:21
impeller::RenderPassBuilderVK::SetDepthStencilAttachment
RenderPassBuilderVK & SetDepthStencilAttachment(PixelFormat format, SampleCount sample_count, LoadAction load_action, StoreAction store_action)
Definition: render_pass_builder_vk.cc:86
impeller::RenderPassBuilderVK::SetStencilAttachment
RenderPassBuilderVK & SetStencilAttachment(PixelFormat format, SampleCount sample_count, LoadAction load_action, StoreAction store_action)
Definition: render_pass_builder_vk.cc:104
impeller::RenderPassBuilderVK::SetColorAttachment
RenderPassBuilderVK & SetColorAttachment(size_t index, PixelFormat format, SampleCount sample_count, LoadAction load_action, StoreAction store_action, vk::ImageLayout current_layout=vk::ImageLayout::eUndefined, bool is_swapchain=false)
Definition: render_pass_builder_vk.cc:38
impeller::RenderPassBuilderVK::Build
vk::UniqueRenderPass Build(const vk::Device &device) const
Definition: render_pass_builder_vk.cc:122
impeller::RenderTargetAllocator
a wrapper around the impeller [Allocator] instance that can be used to provide caching of allocated r...
Definition: render_target.h:149
impeller::RenderTargetAllocator::CreateOffscreenMSAA
virtual RenderTarget CreateOffscreenMSAA(const Context &context, ISize size, int mip_count, std::string_view label="Offscreen MSAA", RenderTarget::AttachmentConfigMSAA color_attachment_config=RenderTarget::kDefaultColorAttachmentConfigMSAA, std::optional< RenderTarget::AttachmentConfig > stencil_attachment_config=RenderTarget::kDefaultStencilAttachmentConfig, const std::shared_ptr< Texture > &existing_color_msaa_texture=nullptr, const std::shared_ptr< Texture > &existing_color_resolve_texture=nullptr, const std::shared_ptr< Texture > &existing_depth_stencil_texture=nullptr)
Definition: render_target.cc:376
impeller::RenderTarget
Definition: render_target.h:38
impeller::RenderTarget::IterateAllColorAttachments
bool IterateAllColorAttachments(const std::function< bool(size_t index, const ColorAttachment &attachment)> &iterator) const
Definition: render_target.cc:96
impeller::RenderTarget::GetDepthAttachment
const std::optional< DepthAttachment > & GetDepthAttachment() const
Definition: render_target.cc:247
impeller::RenderTarget::GetStencilAttachment
const std::optional< StencilAttachment > & GetStencilAttachment() const
Definition: render_target.cc:251
impeller::ResourceManagerVK::Create
static std::shared_ptr< ResourceManagerVK > Create()
Creates a shared resource manager (a dedicated thread).
Definition: resource_manager_vk.cc:14
command_buffer_vk.h
command_pool_vk.h
command_queue_vk.h
formats.h
debug_report_vk.h
descriptor_pool_vk.h
value
int32_t value
Definition: dl_golden_unittests.cc:459
fence_waiter_vk.h
gpu_tracer_vk.h
impeller::interop::Create
ScopedObject< Object > Create(CtorArgs &&... args)
Definition: object.h:161
impeller
Definition: allocation.cc:12
impeller::RuntimeStageBackend
RuntimeStageBackend
Definition: runtime_types.h:16
impeller::RuntimeStageBackend::kVulkan
@ kVulkan
impeller::HasValidationLayers
bool HasValidationLayers()
Definition: context_vk.cc:53
impeller::PickQueue
static std::optional< QueueIndexVK > PickQueue(const vk::PhysicalDevice &device, vk::QueueFlagBits flags)
Definition: context_vk.cc:91
impeller::PickPhysicalDevice
static std::optional< vk::PhysicalDevice > PickPhysicalDevice(const CapabilitiesVK &caps, const vk::Instance &instance)
Definition: context_vk.cc:57
impeller::PixelFormat
PixelFormat
The Pixel formats supported by Impeller. The naming convention denotes the usage of the component,...
Definition: formats.h:99
impeller::gHasValidationLayers
static bool gHasValidationLayers
Definition: context_vk.cc:51
impeller::GetWorkaroundsFromDriverInfo
WorkaroundsVK GetWorkaroundsFromDriverInfo(DriverInfoVK &driver_info)
Definition: workarounds_vk.cc:10
impeller::GetQueueCreateInfos
static std::vector< vk::DeviceQueueCreateInfo > GetQueueCreateInfos(std::initializer_list< QueueIndexVK > queues)
Definition: context_vk.cc:68
render_pass_builder_vk.h
render_target.h
context_vk.h
resource_manager_vk.h
runtime_types.h
impeller::Attachment::load_action
LoadAction load_action
Definition: formats.h:659
impeller::Attachment::texture
std::shared_ptr< Texture > texture
Definition: formats.h:657
impeller::Attachment::store_action
StoreAction store_action
Definition: formats.h:660
impeller::ColorAttachment
Definition: formats.h:665
impeller::ContextVK::Settings
Definition: context_vk.h:79
impeller::ContextVK::Settings::flags
Flags flags
Definition: context_vk.h:88
impeller::QueueIndexVK
Definition: queue_vk.h:15
impeller::QueueIndexVK::family
size_t family
Definition: queue_vk.h:16
impeller::QueuesVK::FromEmbedderQueue
static QueuesVK FromEmbedderQueue(vk::Queue queue, uint32_t queue_family_index)
Definition: queue_vk.cc:58
impeller::QueuesVK::FromQueueIndices
static QueuesVK FromQueueIndices(const vk::Device &device, QueueIndexVK graphics, QueueIndexVK compute, QueueIndexVK transfer)
Definition: queue_vk.cc:67
impeller::QueuesVK::graphics_queue
std::shared_ptr< QueueVK > graphics_queue
Definition: queue_vk.h:64
impeller::WorkaroundsVK
A non-exhaustive set of driver specific workarounds.
Definition: workarounds_vk.h:13
impeller::WorkaroundsVK::batch_submit_command_buffer_timeout
bool batch_submit_command_buffer_timeout
Definition: workarounds_vk.h:24
surface_context_vk.h
validation.h
VALIDATION_LOG
#define VALIDATION_LOG
Definition: validation.h:91
workarounds_vk.h
yuv_conversion_library_vk.h