upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime/src/vulkan_present.h
diff options
context:
space:
mode:
authorlumenpearson <139921639+lumenpearson@users.noreply.github.com>2026-11-22 23:25:25 +0300
committerlumenpearson <139921639+lumenpearson@users.noreply.github.com>2026-11-22 23:25:25 +0300
commitf324bfbc71f0eabf9515bcd7c8b7c9e4b89448bf (patch)
tree2db4ae6fd5412abbbc3e1894f8bc7ed88c8ae514 /runtime/src/vulkan_present.h
parent18380c6d2baf1422109b369860a6e8be5e185b05 (diff)
parentf847748cc76bd3777f9c070c4034eb2fc1c04e64 (diff)
Merge upstream main into SHADER-537
Diffstat (limited to 'runtime/src/vulkan_present.h')
-rw-r--r--runtime/src/vulkan_present.h294
1 files changed, 284 insertions, 10 deletions
diff --git a/runtime/src/vulkan_present.h b/runtime/src/vulkan_present.h
index 9a73d2f82..a2874b4b3 100644
--- a/runtime/src/vulkan_present.h
+++ b/runtime/src/vulkan_present.h
@@ -15,12 +15,18 @@
15// that follows the source (an sRGB source gets an sRGB swapchain, so the blit's decode and encode cancel; every 15// that follows the source (an sRGB source gets an sRGB swapchain, so the blit's decode and encode cancel; every
16// other source gets a UNORM one), and an optional capture that copies each presented frame to host memory. 16// other source gets a UNORM one), and an optional capture that copies each presented frame to host memory.
17// 17//
18// Plane composition (PresentX with placement, a filter, HDR10 or a second plane): present_planes() runs a compute pass
19// (present_compose.comp, vulkan_present_compose.h) over up to two textures into an RGBA16F image and copies that to the
20// swapchain; with an HDR10 plane and a surface that lists an ST.2084 format the swapchain is created in it. The plain
21// blit above is unchanged.
22//
18// Tearing on request (PresentX's ImmediateThresholdPercent): with VK_KHR_swapchain_maintenance1 (or the EXT original) 23// Tearing on request (PresentX's ImmediateThresholdPercent): with VK_KHR_swapchain_maintenance1 (or the EXT original)
19// the vsync swapchain is created with FIFO plus IMMEDIATE (FIFO_RELAXED when the surface cannot switch to IMMEDIATE), 24// the vsync swapchain is created with FIFO plus IMMEDIATE (FIFO_RELAXED when the surface cannot switch to IMMEDIATE),
20// and a present that asks for it is queued in that mode alone. Without the extension, or without either mode, a 25// and a present that asks for it is queued in that mode alone. Without the extension, or without either mode, a
21// request is ignored and the frame waits for the vblank. 26// request is ignored and the frame waits for the vblank.
22 27
23#include "vulkan_backend.h" 28#include "vulkan_backend.h"
29#include "vulkan_present_compose.h"
24 30
25// Use the original EXT spellings. They are aliases of the promoted KHR types and are available in older headers. 31// Use the original EXT spellings. They are aliases of the promoted KHR types and are available in older headers.
26#if defined(VK_EXT_SWAPCHAIN_MAINTENANCE_1_EXTENSION_NAME) && defined(VK_EXT_SURFACE_MAINTENANCE_1_EXTENSION_NAME) 32#if defined(VK_EXT_SWAPCHAIN_MAINTENANCE_1_EXTENSION_NAME) && defined(VK_EXT_SURFACE_MAINTENANCE_1_EXTENSION_NAME)
@@ -29,11 +35,13 @@
29 35
30#include <algorithm> 36#include <algorithm>
31#include <array> 37#include <array>
38#include <cmath>
32#include <cstdint> 39#include <cstdint>
33#include <cstdio> 40#include <cstdio>
34#include <cstring> 41#include <cstring>
35#include <functional> 42#include <functional>
36#include <map> 43#include <map>
44#include <memory>
37#include <vector> 45#include <vector>
38 46
39namespace leonida { 47namespace leonida {
@@ -43,6 +51,22 @@ struct PresentRect {
43 std::int32_t left, top, right, bottom; 51 std::int32_t left, top, right, bottom;
44}; 52};
45 53
54// One plane of present_planes(): a colour texture, the part of it shown, and where in the output it goes.
55struct PresentPlane {
56 ResourceId source{};
57 PresentRect source_rect{}; // texels; used when has_source_rect
58 bool has_source_rect = false;
59 float dest[4] = {0, 0, 1, 1}; // left, top, right, bottom as fractions of the output (0..1)
60 bool point_filter = false; // nearest texel; otherwise bilinear inside the source rectangle
61 bool hdr10 = false; // the texture holds ST.2084 (PQ) Rec.2020 values; otherwise G2.2 Rec.709 ones
62 bool straight_alpha = false; // plane 1 only: alpha is not premultiplied into the colour
63};
64struct PresentPlanes {
65 PresentPlane plane[2];
66 std::uint32_t count = 1;
67 float sdr_white_nits = 203.0f; // what SDR white maps to in an HDR10 output, and what HDR10 is divided by for SDR
68};
69
46namespace detail { 70namespace detail {
47inline bool is_srgb_format(VkFormat format) { 71inline bool is_srgb_format(VkFormat format) {
48 switch (format) { 72 switch (format) {
@@ -140,7 +164,9 @@ public:
140 release(swapchain_); 164 release(swapchain_);
141 swapchain_ = VK_NULL_HANDLE; 165 swapchain_ = VK_NULL_HANDLE;
142 release_capture(); 166 release_capture();
167 composer_.reset();
143 for (Frame& frame : frames_) { 168 for (Frame& frame : frames_) {
169 drop_views(frame);
144 if (frame.done) vkDestroyFence_(device, frame.done, nullptr); 170 if (frame.done) vkDestroyFence_(device, frame.done, nullptr);
145 if (frame.acquired) vk.vkDestroySemaphore(device, frame.acquired, nullptr); 171 if (frame.acquired) vk.vkDestroySemaphore(device, frame.acquired, nullptr);
146 } 172 }
@@ -200,6 +226,47 @@ public:
200 return submit(&binding, source, vsync, source_rect, detail::is_srgb_format(binding.format), tear); 226 return submit(&binding, source, vsync, source_rect, detail::is_srgb_format(binding.format), tear);
201 } 227 }
202 228
229 // PresentX with planes (docs section 4.5): one or two textures, each scaled from its source rectangle to its
230 // destination rectangle of the window, plane 1 blended over plane 0, composed by a compute pass into an RGBA16F image
231 // that is then copied to the swapchain image. Colour spaces are converted to the swapchain's: when a plane is HDR10 and
232 // the surface lists an HDR10 (ST.2084) format the swapchain uses it (hdr_active()), else the HDR10 planes are
233 // converted to SDR by clipping (no tone mapping). The swapchain is always UNORM here; sRGB-format sources are
234 // encoded again by the pass. Sources must be single-sample, sampled (no DENY_SHADER_RESOURCE) float/UNORM/sRGB
235 // colour textures; others are refused (VK_ERROR_FORMAT_NOT_SUPPORTED). Rectangles outside their range give
236 // VK_ERROR_UNKNOWN. vsync and `tear` as for present().
237 VkResult present_planes(const PresentPlanes& planes, bool vsync, bool tear = false) {
238 if (planes.count < 1 || planes.count > 2) return VK_ERROR_UNKNOWN;
239 if (!(planes.sdr_white_nits > 0.0f) || !std::isfinite(planes.sdr_white_nits)) return VK_ERROR_UNKNOWN;
240 for (std::uint32_t i = 0; i < planes.count; ++i) {
241 const PresentPlane& plane = planes.plane[i];
242 ResourceBinding binding;
243 {
244 std::shared_lock lock(context_.resource_mutex_);
245 const ResourceBinding* found = context_.resolve(plane.source);
246 if (!found || !found->image) return VK_ERROR_UNKNOWN;
247 binding = *found;
248 }
249 if (binding.aspects != VK_IMAGE_ASPECT_COLOR_BIT || binding.samples > 1 || !binding.sampled || detail::blit_unsupported_format(binding.format) ||
250 !(format_features(binding.format) & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT))
251 return VK_ERROR_FORMAT_NOT_SUPPORTED;
252 const PresentRect& r = plane.source_rect;
253 if (plane.has_source_rect && (r.left < 0 || r.top < 0 || r.left >= r.right || r.top >= r.bottom ||
254 std::uint32_t(r.right) > binding.width || std::uint32_t(r.bottom) > binding.height))
255 return VK_ERROR_UNKNOWN;
256 const float* d = plane.dest;
257 if (!(d[0] >= 0.0f && d[0] < d[2] && d[2] <= 1.0f && d[1] >= 0.0f && d[1] < d[3] && d[3] <= 1.0f))
258 return VK_ERROR_UNKNOWN; // (also false for NaN)
259 }
260 return submit(nullptr, ResourceId{}, vsync, nullptr, false, tear, &planes);
261 }
262 // The swapchain holds HDR10 (ST.2084) values: a plane asked for it and the surface has the format.
263 bool hdr_active() const { return hdr_active_; }
264 // Presents that went through the compose pass (present_planes); plain blits and blank frames are not counted.
265 std::uint64_t composed_presents() const { return composed_; }
266 // Tests, on surfaces without HDR10: compose as if the output were HDR10 but write the PQ values into the (8-bit,
267 // UNORM) swapchain, so the encoder can be checked on any GPU. Takes effect with the next present_planes().
268 void force_hdr_encoding(bool on) { force_hdr_encoding_ = on; }
269
203 // Polled while a present waits for a swapchain image (every 50 ms): when it returns true the present gives up with 270 // Polled while a present waits for a swapchain image (every 50 ms): when it returns true the present gives up with
204 // VK_NOT_READY, so a caller that is being suspended is never held by a window that stopped taking frames. 271 // VK_NOT_READY, so a caller that is being suspended is never held by a window that stopped taking frames.
205 void set_abort(std::function<bool()> abort) { abort_ = std::move(abort); } 272 void set_abort(std::function<bool()> abort) { abort_ = std::move(abort); }
@@ -216,7 +283,7 @@ public:
216 if (!ok_) return false; 283 if (!ok_) return false;
217 capture_ = true; 284 capture_ = true;
218 stale_ = true; 285 stale_ = true;
219 if (!recreate(vsync_, swapchain_srgb_) || (swapchain_ && !capture_buffer_)) { 286 if (!recreate(vsync_, swapchain_srgb_, swapchain_hdr_req_) || (swapchain_ && !capture_buffer_)) {
220 capture_ = false; 287 capture_ = false;
221 return false; 288 return false;
222 } 289 }
@@ -236,22 +303,32 @@ public:
236 return true; 303 return true;
237 } 304 }
238 305
239 // Shared by present() and present_blank(). `binding` null: clear instead of blit. 306 // Shared by present(), present_blank() and present_planes(). `binding` null and `planes` null: clear instead of blit;
307 // `planes`: compose them (`binding`, `source`, `source_rect` unused).
240 VkResult submit(const ResourceBinding* binding, ResourceId source, bool vsync, const PresentRect* source_rect, 308 VkResult submit(const ResourceBinding* binding, ResourceId source, bool vsync, const PresentRect* source_rect,
241 bool srgb, bool tear = false) { 309 bool srgb, bool tear = false, const PresentPlanes* planes = nullptr) {
242 last_tore_ = false; 310 last_tore_ = false;
243 if (!ok_) return VK_ERROR_INITIALIZATION_FAILED; 311 if (!ok_) return VK_ERROR_INITIALIZATION_FAILED;
244 if (vsync != vsync_ || stale_ || srgb != swapchain_srgb_) { 312 // The swapchain's HDR10 format is only for composed planes that ask for it; a blit of an SDR source or a blank
313 // frame keeps whatever the swapchain has (black is black), except that a blit needs the SDR one.
314 bool want_hdr = swapchain_hdr_req_;
315 if (planes)
316 want_hdr = (planes->plane[0].hdr10) || (planes->count > 1 && planes->plane[1].hdr10);
317 else if (binding)
318 want_hdr = false;
319 if (vsync != vsync_ || stale_ || srgb != swapchain_srgb_ || want_hdr != swapchain_hdr_req_) {
245 // The swapchain's colour encoding is only recorded once the new swapchain exists, so a failed 320 // The swapchain's colour encoding is only recorded once the new swapchain exists, so a failed
246 // recreate is tried again at the next present. 321 // recreate is tried again at the next present.
247 if (!recreate(vsync, srgb)) return VK_ERROR_OUT_OF_DATE_KHR; 322 if (!recreate(vsync, srgb, want_hdr)) return VK_ERROR_OUT_OF_DATE_KHR;
248 } 323 }
249 if (!swapchain_) { // minimised: try again next frame 324 if (!swapchain_) { // minimised: try again next frame
250 stale_ = true; 325 stale_ = true;
251 return VK_SUCCESS; 326 return VK_SUCCESS;
252 } 327 }
253 if (binding && !presentable(source)) return VK_ERROR_UNKNOWN; // checked before an image is acquired for it 328 if (binding && !presentable(source)) return VK_ERROR_UNKNOWN; // checked before an image is acquired for it
254 if (binding && !(format_features(format_) & VK_FORMAT_FEATURE_BLIT_DST_BIT)) return VK_ERROR_FORMAT_NOT_SUPPORTED; 329 if ((binding || planes) && !(format_features(format_) & VK_FORMAT_FEATURE_BLIT_DST_BIT))
330 return VK_ERROR_FORMAT_NOT_SUPPORTED;
331 if (planes && !prepare_compose()) return VK_ERROR_FORMAT_NOT_SUPPORTED;
255 auto& vk = context_.vk; 332 auto& vk = context_.vk;
256 const VkDevice device = context_.device(); 333 const VkDevice device = context_.device();
257 Frame& frame = frames_[frame_index_ % frames_.size()]; 334 Frame& frame = frames_[frame_index_ % frames_.size()];
@@ -261,18 +338,43 @@ public:
261 std::uint32_t image = 0; 338 std::uint32_t image = 0;
262 VkResult acquired = acquire(frame.acquired, &image); 339 VkResult acquired = acquire(frame.acquired, &image);
263 if (acquired == VK_ERROR_OUT_OF_DATE_KHR) { 340 if (acquired == VK_ERROR_OUT_OF_DATE_KHR) {
264 if (!recreate(vsync, swapchain_srgb_)) return acquired; 341 if (!recreate(vsync, swapchain_srgb_, swapchain_hdr_req_)) return acquired;
265 if (!swapchain_) return VK_SUCCESS; 342 if (!swapchain_) return VK_SUCCESS;
266 acquired = acquire(frame.acquired, &image); 343 acquired = acquire(frame.acquired, &image);
267 } 344 }
268 if (acquired != VK_SUCCESS && acquired != VK_SUBOPTIMAL_KHR) return acquired; // nothing was acquired 345 if (acquired != VK_SUCCESS && acquired != VK_SUBOPTIMAL_KHR) return acquired; // nothing was acquired
269 if (acquired == VK_SUBOPTIMAL_KHR) stale_ = true; 346 if (acquired == VK_SUBOPTIMAL_KHR) stale_ = true;
347 // An out-of-date retry above may have given the swapchain another extent: the compose target follows it.
348 if (planes && !prepare_compose()) return give_back(frame, VK_ERROR_FORMAT_NOT_SUPPORTED);
270 349
271 bool recorded = false; 350 bool recorded = false;
272 std::unique_lock tracker_lock(context_.tracker_mutex_, std::defer_lock); 351 std::unique_lock tracker_lock(context_.tracker_mutex_, std::defer_lock);
273 bool rollback_source = false; 352 bool rollback_source = false;
274 VkImageLayout prev_layout = VK_IMAGE_LAYOUT_UNDEFINED; 353 VkImageLayout prev_layout = VK_IMAGE_LAYOUT_UNDEFINED;
275 if (binding) { 354 std::array<RollbackPlane, 2> plane_rollbacks{}; // present_planes(): the same, per plane
355 if (planes) {
356 std::array<ResourceBinding, 2> current{};
357 bool found_all = true;
358 {
359 std::shared_lock resource_lock(context_.resource_mutex_);
360 for (std::uint32_t i = 0; i < planes->count; ++i) {
361 const ResourceBinding* found = context_.resolve(planes->plane[i].source);
362 if (found && found->image && found->aspects == VK_IMAGE_ASPECT_COLOR_BIT && found->sampled)
363 current[i] = *found;
364 else
365 found_all = false;
366 }
367 if (found_all) {
368 tracker_lock.lock();
369 for (std::uint32_t i = 0; i < planes->count; ++i) {
370 plane_rollbacks[i].id = planes->plane[i].source;
371 plane_rollbacks[i].tracked = context_.tracker_.tracked(plane_rollbacks[i].id);
372 if (plane_rollbacks[i].tracked) plane_rollbacks[i].layout = context_.tracker_.layout(plane_rollbacks[i].id, 0);
373 }
374 recorded = record_planes(frame, std::uint32_t(frame_index_ % frames_.size()), current, *planes, image);
375 }
376 }
377 } else if (binding) {
276 // Lock hierarchy: resource_mutex_ -> tracker_mutex_ -> submit_mutex_ (vulkan_backend.h). 378 // Lock hierarchy: resource_mutex_ -> tracker_mutex_ -> submit_mutex_ (vulkan_backend.h).
277 // record() only touches subresource 0 (mip 0, layer 0, color) of `source`, so saving that one layout 379 // record() only touches subresource 0 (mip 0, layer 0, color) of `source`, so saving that one layout
278 // rolls back a failed submit in O(1) without copying the entire LayoutTracker map. 380 // rolls back a failed submit in O(1) without copying the entire LayoutTracker map.
@@ -292,6 +394,11 @@ public:
292 const auto rollback = [&] { 394 const auto rollback = [&] {
293 if (rollback_source) 395 if (rollback_source)
294 context_.tracker_.set(source, {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}, prev_layout); 396 context_.tracker_.set(source, {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}, prev_layout);
397 if (planes)
398 for (std::uint32_t i = 0; i < planes->count; ++i)
399 if (plane_rollbacks[i].tracked)
400 context_.tracker_.set(plane_rollbacks[i].id, {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1},
401 plane_rollbacks[i].layout);
295 }; 402 };
296 if (!recorded) return give_back(frame, VK_ERROR_UNKNOWN); // released by another thread since presentable() 403 if (!recorded) return give_back(frame, VK_ERROR_UNKNOWN); // released by another thread since presentable()
297 if (const VkResult reset = vkResetFences_(device, 1, &frame.done); reset != VK_SUCCESS) { 404 if (const VkResult reset = vkResetFences_(device, 1, &frame.done); reset != VK_SUCCESS) {
@@ -342,6 +449,7 @@ public:
342 // is recreated next time, and the caller sees VK_SUCCESS, since its work was submitted. 449 // is recreated next time, and the caller sees VK_SUCCESS, since its work was submitted.
343 if (result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR) { 450 if (result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR) {
344 ++presented_; 451 ++presented_;
452 if (planes) ++composed_;
345 if (tearing) { 453 if (tearing) {
346 last_tore_ = true; 454 last_tore_ = true;
347 ++tear_presents_; 455 ++tear_presents_;
@@ -364,6 +472,7 @@ private:
364 VkCommandBuffer commands = VK_NULL_HANDLE; 472 VkCommandBuffer commands = VK_NULL_HANDLE;
365 VkFence done = VK_NULL_HANDLE; 473 VkFence done = VK_NULL_HANDLE;
366 VkSemaphore acquired = VK_NULL_HANDLE; 474 VkSemaphore acquired = VK_NULL_HANDLE;
475 std::array<VkImageView, 2> views{}; // the plane views of the last composed present, until the frame is reused
367 }; 476 };
368 477
369 // Whether `source` is a colour texture the device knows, so present() can refuse it before acquiring an image. 478 // Whether `source` is a colour texture the device knows, so present() can refuse it before acquiring an image.
@@ -462,6 +571,139 @@ private:
462 vk.vkEndCommandBuffer(commands); 571 vk.vkEndCommandBuffer(commands);
463 } 572 }
464 573
574 struct RollbackPlane {
575 ResourceId id{};
576 bool tracked = false;
577 VkImageLayout layout = VK_IMAGE_LAYOUT_UNDEFINED;
578 };
579
580 void drop_views(Frame& frame) {
581 for (VkImageView& view : frame.views)
582 if (view) context_.vk.vkDestroyImageView(context_.device(), view, nullptr);
583 frame.views = {};
584 }
585
586 // The compose pass and its target image, for the swapchain's current size.
587 bool prepare_compose() {
588 if (!composer_) {
589 VkPhysicalDeviceMemoryProperties memory{};
590 if (!vkGetPhysicalDeviceMemoryProperties_) return false;
591 vkGetPhysicalDeviceMemoryProperties_(physical_, &memory);
592 composer_ = std::make_unique<PresentComposer>(context_, memory);
593 }
594 if (!composer_->ready()) return false;
595 if (composer_->target() && composer_->extent().width == extent_.width &&
596 composer_->extent().height == extent_.height)
597 return true;
598 {
599 std::lock_guard lock(context_.submit_mutex());
600 context_.vk.vkQueueWaitIdle(queue_); // the old target may still be in use
601 }
602 bool changed = false;
603 return composer_->ensure_target(extent_, changed);
604 }
605
606 // Records the composition of `planes` and its copy to swapchain image `image`. False, with nothing recorded and the
607 // tracker untouched, when a view cannot be made. The caller holds the resource and tracker locks.
608 bool record_planes(Frame& frame, std::uint32_t slot, const std::array<ResourceBinding, 2>& current,
609 const PresentPlanes& planes, std::uint32_t image) {
610 auto& vk = context_.vk;
611 const ReplayFunctions& fn = context_.replay_;
612 if (composer_->target() == VK_NULL_HANDLE || composer_->extent().width != extent_.width ||
613 composer_->extent().height != extent_.height)
614 return false; // the target does not match the swapchain: nothing recorded
615 drop_views(frame);
616 for (std::uint32_t i = 0; i < planes.count; ++i) {
617 VkImageViewCreateInfo view_info{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO};
618 view_info.image = current[i].image;
619 view_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
620 view_info.format = current[i].format;
621 view_info.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
622 if (vk.vkCreateImageView(context_.device(), &view_info, nullptr, &frame.views[i]) != VK_SUCCESS) {
623 drop_views(frame);
624 return false;
625 }
626 }
627 if (planes.count == 1) frame.views[1] = VK_NULL_HANDLE; // the shader never reads it; plane 0's view is bound twice
628
629 VkCommandBuffer commands = frame.commands;
630 vk.vkResetCommandBuffer(commands, 0);
631 VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};
632 begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
633 vk.vkBeginCommandBuffer(commands, &begin);
634
635 constexpr VkAccessFlags any = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
636 const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
637 const bool same = planes.count > 1 && planes.plane[1].source == planes.plane[0].source;
638 std::array<LayoutPieces, 2> pieces;
639 std::array<VkImageLayout, 2> read_layout{};
640 // Each distinct source: its PRESENT (common) layout, then readable by the compute pass. A never-written back buffer
641 // is zero-filled first, as any committed resource is.
642 for (std::uint32_t i = 0; i < planes.count; ++i) {
643 read_layout[i] = image_layout(current[i], VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
644 if (i == 1 && same) continue;
645 const VkImageLayout common = image_layout(current[i], VK_IMAGE_LAYOUT_GENERAL);
646 pieces[i] = detail::current(&context_.tracker_, planes.plane[i].source, range, common);
647 detail::initialize(fn, commands, current[i], planes.plane[i].source, pieces[i], common, &context_.tracker_);
648 for (const auto& piece : pieces[i])
649 detail::image_barrier(fn, commands, current[i], piece.range, piece.layout, read_layout[i],
650 VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
651 VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
652 }
653
654 // The pass: destinations in output pixels, sources in texels.
655 PresentComposePush push{};
656 const float out_w = float(extent_.width), out_h = float(extent_.height);
657 std::uint32_t* flags[2] = {&push.flags0, &push.flags1};
658 float* dest[2] = {push.dest0, push.dest1};
659 float* src[2] = {push.src0, push.src1};
660 for (std::uint32_t i = 0; i < planes.count; ++i) {
661 const PresentPlane& plane = planes.plane[i];
662 dest[i][0] = plane.dest[0] * out_w;
663 dest[i][1] = plane.dest[1] * out_h;
664 dest[i][2] = plane.dest[2] * out_w;
665 dest[i][3] = plane.dest[3] * out_h;
666 const PresentRect whole{0, 0, std::int32_t(current[i].width), std::int32_t(current[i].height)};
667 const PresentRect& r = plane.has_source_rect ? plane.source_rect : whole;
668 src[i][0] = float(r.left);
669 src[i][1] = float(r.top);
670 src[i][2] = float(r.right);
671 src[i][3] = float(r.bottom);
672 *flags[i] = (plane.point_filter ? compose_flag::point : 0u) |
673 (detail::is_srgb_format(current[i].format) ? compose_flag::srgb_source : 0u) |
674 (plane.hdr10 ? compose_flag::hdr10 : 0u) | (plane.straight_alpha ? compose_flag::straight_alpha : 0u);
675 }
676 push.plane_count = planes.count;
677 push.out_hdr = (hdr_active_ || force_hdr_encoding_) ? 1u : 0u;
678 push.sdr_white = planes.sdr_white_nits;
679 push.width = extent_.width;
680 push.height = extent_.height;
681 composer_->record(commands, slot, frame.views[0], read_layout[0], frame.views[1] ? frame.views[1] : frame.views[0],
682 read_layout[1] ? read_layout[1] : read_layout[0], push);
683
684 // The swapchain image, written by a copy of the composed image (same size: no scaling).
685 ResourceBinding target = target_of(image);
686 detail::image_barrier(fn, commands, target, range, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 0,
687 VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
688 VkImageBlit blit{};
689 blit.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
690 blit.srcOffsets[1] = {std::int32_t(extent_.width), std::int32_t(extent_.height), 1};
691 blit.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
692 blit.dstOffsets[1] = {std::int32_t(extent_.width), std::int32_t(extent_.height), 1};
693 vkCmdBlitImage_(commands, composer_->target(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, images_[image],
694 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_NEAREST);
695 finish_image(commands, image);
696 for (std::uint32_t i = 0; i < planes.count; ++i) {
697 if (i == 1 && same) continue;
698 for (const auto& piece : pieces[i])
699 detail::image_barrier(fn, commands, current[i], piece.range, read_layout[i], piece.layout,
700 VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, any,
701 VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
702 }
703 vk.vkEndCommandBuffer(commands);
704 return true;
705 }
706
465 // vkGetPhysicalDeviceFormatProperties, optimal tiling, cached per format. 707 // vkGetPhysicalDeviceFormatProperties, optimal tiling, cached per format.
466 VkFormatFeatureFlags format_features(VkFormat format) { 708 VkFormatFeatureFlags format_features(VkFormat format) {
467 const auto it = features_.find(format); 709 const auto it = features_.find(format);
@@ -595,7 +837,7 @@ private:
595 // (Re)creates the swapchain for the surface's current size. A zero-sized surface (minimised) leaves no 837 // (Re)creates the swapchain for the surface's current size. A zero-sized surface (minimised) leaves no
596 // swapchain and is retried on the next present. Keep the old swapchain until the surface queries succeed and 838 // swapchain and is retried on the next present. Keep the old swapchain until the surface queries succeed and
597 // the replacement can be attempted. An incomplete replacement stays stale so the next present tries again. 839 // the replacement can be attempted. An incomplete replacement stays stale so the next present tries again.
598 bool recreate(bool vsync, bool srgb) { 840 bool recreate(bool vsync, bool srgb, bool hdr = false) {
599 auto& vk = context_.vk; 841 auto& vk = context_.vk;
600 const VkDevice device = context_.device(); 842 const VkDevice device = context_.device();
601 { 843 {
@@ -625,6 +867,8 @@ private:
625 swapchain_ = VK_NULL_HANDLE; 867 swapchain_ = VK_NULL_HANDLE;
626 vsync_ = vsync; 868 vsync_ = vsync;
627 swapchain_srgb_ = srgb; 869 swapchain_srgb_ = srgb;
870 swapchain_hdr_req_ = hdr;
871 hdr_active_ = false;
628 stale_ = false; 872 stale_ = false;
629 return true; 873 return true;
630 } 874 }
@@ -643,8 +887,28 @@ private:
643 // wants UNORM (the bytes go through as they are). BGRA before RGBA, as the surface lists them. 887 // wants UNORM (the bytes go through as they are). BGRA before RGBA, as the surface lists them.
644 VkSurfaceFormatKHR chosen = formats[0]; 888 VkSurfaceFormatKHR chosen = formats[0];
645 bool found = false; 889 bool found = false;
890 bool chose_hdr = false;
891 if (hdr) {
892 // A plane in HDR10 (PQ, Rec.2020): the surface's ST.2084 format, which needs VK_EXT_swapchain_colorspace on
893 // the instance. Without it the composition converts to SDR.
894 for (const VkFormat wanted : {VK_FORMAT_A2B10G10R10_UNORM_PACK32, VK_FORMAT_A2R10G10B10_UNORM_PACK32}) {
895 for (const auto& f : formats)
896 if (f.format == wanted && f.colorSpace == VK_COLOR_SPACE_HDR10_ST2084_EXT) {
897 chosen = f;
898 found = chose_hdr = true;
899 break;
900 }
901 if (found) break;
902 }
903 if (!found && !warned_hdr_) {
904 warned_hdr_ = true;
905 std::fprintf(stderr, "[rt] present: the surface has no HDR10 (ST.2084) format; HDR10 planes are converted to "
906 "SDR by clipping\n");
907 }
908 }
646 for (const VkFormat wanted : srgb ? std::array<VkFormat, 2>{VK_FORMAT_B8G8R8A8_SRGB, VK_FORMAT_R8G8B8A8_SRGB} 909 for (const VkFormat wanted : srgb ? std::array<VkFormat, 2>{VK_FORMAT_B8G8R8A8_SRGB, VK_FORMAT_R8G8B8A8_SRGB}
647 : std::array<VkFormat, 2>{VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM}) { 910 : std::array<VkFormat, 2>{VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM}) {
911 if (chose_hdr) break;
648 for (const auto& f : formats) 912 for (const auto& f : formats)
649 if (f.format == wanted && f.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) { 913 if (f.format == wanted && f.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) {
650 chosen = f; 914 chosen = f;
@@ -739,14 +1003,18 @@ private:
739 ready_ = std::move(ready); 1003 ready_ = std::move(ready);
740 format_ = chosen.format; 1004 format_ = chosen.format;
741 extent_ = extent; 1005 extent_ = extent;
1006 hdr_active_ = chose_hdr;
742 if (capture_) { 1007 if (capture_) {
743 // A capture that cannot be made fails the recreation with the swapchain in place and stale_ still set. 1008 // A capture that cannot be made fails the recreation with the swapchain in place and stale_ still set.
744 const bool four_bytes = format_ == VK_FORMAT_B8G8R8A8_UNORM || format_ == VK_FORMAT_R8G8B8A8_UNORM || 1009 const bool four_bytes = format_ == VK_FORMAT_B8G8R8A8_UNORM || format_ == VK_FORMAT_R8G8B8A8_UNORM ||
745 format_ == VK_FORMAT_B8G8R8A8_SRGB || format_ == VK_FORMAT_R8G8B8A8_SRGB; 1010 format_ == VK_FORMAT_B8G8R8A8_SRGB || format_ == VK_FORMAT_R8G8B8A8_SRGB ||
1011 format_ == VK_FORMAT_A2B10G10R10_UNORM_PACK32 ||
1012 format_ == VK_FORMAT_A2R10G10B10_UNORM_PACK32;
746 if (!four_bytes || !make_capture_buffer()) return false; 1013 if (!four_bytes || !make_capture_buffer()) return false;
747 } 1014 }
748 vsync_ = vsync; 1015 vsync_ = vsync;
749 swapchain_srgb_ = srgb; 1016 swapchain_srgb_ = srgb;
1017 swapchain_hdr_req_ = hdr;
750 stale_ = false; 1018 stale_ = false;
751 return true; 1019 return true;
752 } 1020 }
@@ -836,6 +1104,12 @@ private:
836 bool stale_ = false; 1104 bool stale_ = false;
837 bool ok_ = false; 1105 bool ok_ = false;
838 bool swapchain_srgb_ = false; // the swapchain format follows the source being presented (set once it exists) 1106 bool swapchain_srgb_ = false; // the swapchain format follows the source being presented (set once it exists)
1107 bool swapchain_hdr_req_ = false; // the swapchain was built for an HDR10 request (it has the format only if hdr_active_)
1108 bool hdr_active_ = false;
1109 std::uint64_t composed_ = 0;
1110 bool force_hdr_encoding_ = false;
1111 bool warned_hdr_ = false;
1112 std::unique_ptr<PresentComposer> composer_;
839 std::function<bool()> abort_; 1113 std::function<bool()> abort_;
840 std::function<VkExtent2D()> extent_fn_; 1114 std::function<VkExtent2D()> extent_fn_;
841 std::map<VkFormat, VkFormatFeatureFlags> features_; 1115 std::map<VkFormat, VkFormatFeatureFlags> features_;