upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/src/vulkan_backend.h
diff options
context:
space:
mode:
authorIlyassRS <ilyassroussi2000@gmail.com>2026-11-25 11:47:40 +0100
committerIlyassRS <ilyassroussi2000@gmail.com>2026-11-25 13:15:02 +0100
commit3ab657b058f1c130b4d554d5ecfcd5dc4d86a0cc (patch)
tree51c9f541cf524e3aece6c9c63cf7b9210e843988 /runtime/src/vulkan_backend.h
parent0d80bc5df7c873f40965f34f185cb96913786765 (diff)
runtime: unlock resource_mutex while compiling unbuilt pipelines
Diffstat (limited to 'runtime/src/vulkan_backend.h')
-rw-r--r--runtime/src/vulkan_backend.h434
1 files changed, 247 insertions, 187 deletions
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h
index 145fa11ee..9a6027787 100644
--- a/runtime/src/vulkan_backend.h
+++ b/runtime/src/vulkan_backend.h
@@ -1545,32 +1545,34 @@ public:
1545 } 1545 }
1546 1546
1547 // Pipelines are registered by an opaque id (the PSO object) for as long as the PSO lives. 1547 // Pipelines are registered by an opaque id (the PSO object) for as long as the PSO lives.
1548 // Guarded by pipeline_mutex_ (separate from resource_mutex_) so shader compilation on one queue does not block
1549 // resource registration or destruction on the render thread.
1548 void add_pipeline(std::uintptr_t id, const ComputePipeline& pipeline, const char* shader = nullptr) { 1550 void add_pipeline(std::uintptr_t id, const ComputePipeline& pipeline, const char* shader = nullptr) {
1549 std::unique_lock lock(resource_mutex_); 1551 std::unique_lock lock(pipeline_mutex_);
1550 pipelines_[id] = pipeline; 1552 pipelines_[id] = pipeline;
1551 if (shader && device_fault_) device_fault_->pipeline_names[id] = {shader}; 1553 if (shader && device_fault_) device_fault_->pipeline_names[id] = {shader};
1552 } 1554 }
1553 void remove_pipeline(std::uintptr_t id) { 1555 void remove_pipeline(std::uintptr_t id) {
1554 std::unique_lock lock(resource_mutex_); 1556 std::unique_lock lock(pipeline_mutex_);
1555 pipelines_.erase(id); 1557 pipelines_.erase(id);
1556 graphics_pipelines_.erase(id); 1558 graphics_pipelines_.erase(id);
1557 if (device_fault_) device_fault_->pipeline_names.erase(id); 1559 if (device_fault_) device_fault_->pipeline_names.erase(id);
1558 } 1560 }
1559 void add_graphics_pipeline(std::uintptr_t id, const GraphicsPipeline& pipeline, 1561 void add_graphics_pipeline(std::uintptr_t id, const GraphicsPipeline& pipeline,
1560 const CheckpointShaders* shaders = nullptr) { 1562 const CheckpointShaders* shaders = nullptr) {
1561 std::unique_lock lock(resource_mutex_); 1563 std::unique_lock lock(pipeline_mutex_);
1562 graphics_pipelines_[id] = pipeline; 1564 graphics_pipelines_[id] = pipeline;
1563 if (shaders && device_fault_) device_fault_->pipeline_names[id] = *shaders; 1565 if (shaders && device_fault_) device_fault_->pipeline_names[id] = *shaders;
1564 } 1566 }
1565 // Workers for the pipelines a submission needs and that are not built yet. Null (the default): each is built where 1567 // Workers for the pipelines a submission needs and that are not built yet. Null (the default): compiled serially on
1566 // prepare() meets it, on the submitting thread. Replacing it waits for submissions that are compiling, and ends the 1568 // the submitting thread once resource_mutex_ is released. Replacing it waits for submissions that are compiling, and
1567 // workers it had. 1569 // ends the workers it had.
1568 void set_pipeline_workers(std::unique_ptr<PipelineWorkers> workers) { 1570 void set_pipeline_workers(std::unique_ptr<PipelineWorkers> workers) {
1569 std::unique_lock lock(resource_mutex_); 1571 std::unique_lock lock(pipeline_mutex_);
1570 pipeline_workers_.swap(workers); 1572 pipeline_workers_.swap(workers);
1571 } 1573 }
1572 PipelineWorkers::Stats pipeline_worker_stats() { 1574 PipelineWorkers::Stats pipeline_worker_stats() {
1573 std::shared_lock lock(resource_mutex_); 1575 std::shared_lock lock(pipeline_mutex_);
1574 return pipeline_workers_ ? pipeline_workers_->stats() : PipelineWorkers::Stats{}; 1576 return pipeline_workers_ ? pipeline_workers_->stats() : PipelineWorkers::Stats{};
1575 } 1577 }
1576 // Configure before queue creation, when the selected queue family supports compute. 1578 // Configure before queue creation, when the selected queue family supports compute.
@@ -1774,7 +1776,7 @@ public:
1774 return true; 1776 return true;
1775 } 1777 }
1776 const char* diagnostic_compute_name(std::uintptr_t id) { 1778 const char* diagnostic_compute_name(std::uintptr_t id) {
1777 std::shared_lock lock(resource_mutex_); 1779 std::shared_lock lock(pipeline_mutex_);
1778 if (!device_fault_) return nullptr; 1780 if (!device_fault_) return nullptr;
1779 const auto it = device_fault_->pipeline_names.find(id); 1781 const auto it = device_fault_->pipeline_names.find(id);
1780 return it == device_fault_->pipeline_names.end() ? nullptr : it->second[0]; 1782 return it == device_fault_->pipeline_names.end() ? nullptr : it->second[0];
@@ -2166,6 +2168,7 @@ private:
2166 bool ray_tracing_ = false; 2168 bool ray_tracing_ = false;
2167 std::unique_ptr<XdxrBuilder> xdxr_; // set: acceleration structures are XDXR BVH4 records 2169 std::unique_ptr<XdxrBuilder> xdxr_; // set: acceleration structures are XDXR BVH4 records
2168 std::atomic<bool> device_lost_{false}; 2170 std::atomic<bool> device_lost_{false};
2171 alignas(64) std::shared_mutex pipeline_mutex_; // shared for prepare/compile/emit pipeline lookups, unique for add/remove/workers
2169 alignas(64) std::shared_mutex resource_mutex_; // shared for prepare lookups, unique for add/remove 2172 alignas(64) std::shared_mutex resource_mutex_; // shared for prepare lookups, unique for add/remove
2170 alignas(64) std::mutex tracker_mutex_; 2173 alignas(64) std::mutex tracker_mutex_;
2171 alignas(64) std::mutex views_mutex_; 2174 alignas(64) std::mutex views_mutex_;
@@ -2899,11 +2902,15 @@ private:
2899 } 2902 }
2900 } khr_guard{this}; 2903 } khr_guard{this};
2901 std::function<void(bool)> bindless_commit; 2904 std::function<void(bool)> bindless_commit;
2902 // Lock hierarchy: resource_mutex_ -> tracker_mutex_ -> submit_mutex_. 2905 // Lock hierarchy: state_mutex_ -> pipeline_mutex_ -> resource_mutex_ -> tracker_mutex_ -> submit_mutex_.
2903 // Shared read-lock allows concurrent prepare() across queues; tracker_mutex_ is acquired lazily during 2906 // Shared pipeline_lock keeps registered pipelines, pipeline_names, and pipeline_workers_ alive across
2904 // prepare() only if a list actually converts a depth24_as_float copy, and otherwise right before 2907 // preparation, compilation, and emit. Shared resource_lock allows concurrent prepare() across queues and is
2905 // bindless_prepare_/emit() through submit() so bindless flushes, layout emits, and submissions stay in order. 2908 // released while unbuilt pipelines compile so add_resource()/remove_resource() never stall behind shader
2906 std::shared_lock resource_lock(context_.resource_mutex_); 2909 // compiles; tracker_mutex_ is acquired lazily during prepare() only if a list uses a shared helper, and
2910 // otherwise right before bindless_prepare_/emit() through submit() so bindless flushes, layout emits, and
2911 // submissions stay in order.
2912 std::shared_lock pipeline_lock(context_.pipeline_mutex_);
2913 std::shared_lock resource_lock(context_.resource_mutex_, std::defer_lock);
2907 std::unique_lock tracker_lock(context_.tracker_mutex_, std::defer_lock); 2914 std::unique_lock tracker_lock(context_.tracker_mutex_, std::defer_lock);
2908 // Declared after tracker_lock so any early return after depth24_->prepare() retires uncommitted scratch/pools 2915 // Declared after tracker_lock so any early return after depth24_->prepare() retires uncommitted scratch/pools
2909 // with ticket 0 while tracker_lock is still held. 2916 // with ticket 0 while tracker_lock is still held.
@@ -2914,7 +2921,7 @@ private:
2914 ~Depth24Guard() { 2921 ~Depth24Guard() {
2915 if (active && d24) d24->retire(progress, 0); 2922 if (active && d24) d24->retire(progress, 0);
2916 } 2923 }
2917 } depth24_guard{context_.depth24_.get(), progress_, false}; 2924 } depth24_guard{nullptr, progress_, false};
2918 struct ScratchGuard { // the same for the copy scratch 2925 struct ScratchGuard { // the same for the copy scratch
2919 ScratchBuffers* scratch = nullptr; 2926 ScratchBuffers* scratch = nullptr;
2920 VkSemaphore progress = VK_NULL_HANDLE; 2927 VkSemaphore progress = VK_NULL_HANDLE;
@@ -2922,7 +2929,7 @@ private:
2922 ~ScratchGuard() { 2929 ~ScratchGuard() {
2923 if (active && scratch) scratch->retire(progress, 0); 2930 if (active && scratch) scratch->retire(progress, 0);
2924 } 2931 }
2925 } scratch_guard{context_.scratch_.get(), progress_, false}; 2932 } scratch_guard{nullptr, progress_, false};
2926 struct ClampGuard { // and for the ExecuteIndirect clamp's record scratch 2933 struct ClampGuard { // and for the ExecuteIndirect clamp's record scratch
2927 IndirectArgumentClamp* clamp = nullptr; 2934 IndirectArgumentClamp* clamp = nullptr;
2928 VkSemaphore progress = VK_NULL_HANDLE; 2935 VkSemaphore progress = VK_NULL_HANDLE;
@@ -2930,9 +2937,8 @@ private:
2930 ~ClampGuard() { 2937 ~ClampGuard() {
2931 if (active && clamp) clamp->retire(progress, 0); 2938 if (active && clamp) clamp->retire(progress, 0);
2932 } 2939 }
2933 } clamp_guard{context_.indirect_clamp_.get(), progress_, false}; 2940 } clamp_guard{nullptr, progress_, false};
2934 const bool transfer_only = family_ == context_.transfer_only_family_; 2941 const bool transfer_only = family_ == context_.transfer_only_family_;
2935 if (!transfer_only) bindless_commit = context_.bindless_commit_;
2936 // Kept between executions: prepare refills each list's entries in the storage the last execution left, where 2942 // Kept between executions: prepare refills each list's entries in the storage the last execution left, where
2937 // making them fresh for every command was about half the layer's CPU cost per command (replay_cpu_bench). 2943 // making them fresh for every command was about half the layer's CPU cost per command (replay_cpu_bench).
2938 auto& prepared = prepared_; 2944 auto& prepared = prepared_;
@@ -2940,42 +2946,9 @@ private:
2940 // a queue that sees 8 lists and then 1 in every frame would rebuild them on each execution. The loops below 2946 // a queue that sees 8 lists and then 1 in every frame would rebuild them on each execution. The loops below
2941 // use only the first lists.size() entries, so stale entries are never prepared, queried or emitted. 2947 // use only the first lists.size() entries, so stale entries are never prepared, queried or emitted.
2942 if (prepared.size() < lists.size()) prepared.resize(lists.size()); 2948 if (prepared.size() < lists.size()) prepared.resize(lists.size());
2943 ReplayFunctions replay = context_.replay_; 2949 ReplayFunctions replay{};
2944 unsigned mesh_draws = 0; 2950 unsigned mesh_draws = 0;
2945 if (pipeline_profile::enabled()) replay.mesh_draw_count = &mesh_draws;
2946 std::vector<VulkanContext::GeometryUpload> geometry; 2951 std::vector<VulkanContext::GeometryUpload> geometry;
2947 if (context_.geometry_provider_) {
2948 replay.title_memory = [&](std::uint64_t va, std::uint64_t bytes, VkBuffer& buffer, VkDeviceSize& offset) {
2949 if (!va || !bytes || bytes>UINT64_MAX-va) return false;
2950 for (const auto& upload : geometry) {
2951 if (va < upload.source || va-upload.source > upload.size || bytes > upload.size-(va-upload.source)) continue;
2952 buffer=upload.buffer; offset=upload.offset+(va-upload.source);
2953 return true;
2954 }
2955 VulkanContext::GeometryUpload upload;
2956 if (!context_.geometry_provider_(va,bytes,upload)) return false;
2957 buffer=upload.buffer;offset=upload.offset;
2958 geometry.push_back(std::move(upload));
2959 return true;
2960 };
2961 }
2962 replay.graphics_family = family_ == context_.graphics_family_;
2963 replay.queue_stages = kind_ == QueueKind::copy ? detail::queue_stages_copy
2964 : kind_ == QueueKind::compute ? detail::queue_stages_compute
2965 : 0;
2966 replay.prepare_khr_instances = [this, &replay, &khr_guard](const BuildAccelerationStructure& build,
2967 VkDeviceAddress& address) {
2968 return stage_khr_instances(replay, build, khr_guard.stages, address);
2969 };
2970 replay.prepare_xdxr_table = [this, &khr_guard](VkDeviceAddress& address, std::uint32_t& count) {
2971 return stage_xdxr_table(khr_guard.stages, address, count);
2972 };
2973 if (replay.write_acceleration_structures_properties) {
2974 replay.prepare_khr_postbuild = [this, &khr_guard](std::uint32_t count, VkQueryPool& pool,
2975 std::uint32_t& first) {
2976 return allocate_khr_as_queries(count, khr_guard.as_queries, pool, first);
2977 };
2978 }
2979 std::uint64_t captures = 0; 2952 std::uint64_t captures = 0;
2980 for (const auto* list : lists) 2953 for (const auto* list : lists)
2981 for (const auto& command : list->commands()) 2954 for (const auto& command : list->commands())
@@ -2984,149 +2957,233 @@ private:
2984 std::unique_ptr<PredicatedBufferCopier::Batch> copy_batch; 2957 std::unique_ptr<PredicatedBufferCopier::Batch> copy_batch;
2985 std::unique_ptr<IndirectDispatchCounter::Batch> counted_batch; 2958 std::unique_ptr<IndirectDispatchCounter::Batch> counted_batch;
2986 std::unique_ptr<IndirectArgumentClamp::Batch> clamp_batch; 2959 std::unique_ptr<IndirectArgumentClamp::Batch> clamp_batch;
2987 if (captures) { 2960 const auto& occlusion_memory = context_.occlusion_resolve_memory_;
2988 if (kind_ == QueueKind::copy || !context_.predicate_reducer_ || family_ != context_.predicate_family_) 2961 const bool can_resolve_occlusion = occlusion_memory.memoryTypeCount != 0;
2989 return queue_unsupported(__LINE__); 2962 const auto resolve = [this](ResourceId id) { return context_.resolve(id); };
2990 // The helper's lazy pipeline is shared by queues. Serialize preparation with the tracker lock, 2963 std::uint32_t segments = 0, statistics_segments = 0;
2991 // retaining main's resource -> tracker -> submit lock order through emit and submission. 2964 bool has_queries = false;
2992 if (!tracker_lock.owns_lock()) tracker_lock.lock(); 2965 const auto run_compiles = [this](std::size_t count, const std::function<void(std::size_t)>& job) {
2993 batch = context_.predicate_reducer_->batch(captures); 2966 if (context_.pipeline_workers_) {
2994 if (!batch) return queue_unsupported(__LINE__); 2967 context_.pipeline_workers_->run(count, job);
2995 replay.prepare_predicate = [&](VkBuffer buffer, VkDeviceSize offset, PredicateCapture& out) { 2968 } else {
2996 return batch->prepare(buffer, offset, out); 2969 for (std::size_t i = 0; i < count; ++i) job(i);
2970 }
2971 };
2972 PipelineCompiles prior_compiles;
2973 bool has_prior_compiles = false;
2974 for (int pass = 0;; ++pass) {
2975 resource_lock.lock();
2976 bindless_commit = !transfer_only ? context_.bindless_commit_ : std::function<void(bool)>{};
2977 replay = context_.replay_;
2978 mesh_draws = 0;
2979 if (pipeline_profile::enabled()) replay.mesh_draw_count = &mesh_draws;
2980 if (context_.geometry_provider_) {
2981 replay.title_memory = [&](std::uint64_t va, std::uint64_t bytes, VkBuffer& buffer, VkDeviceSize& offset) {
2982 if (!va || !bytes || bytes>UINT64_MAX-va) return false;
2983 for (const auto& upload : geometry) {
2984 if (va < upload.source || va-upload.source > upload.size || bytes > upload.size-(va-upload.source)) continue;
2985 buffer=upload.buffer; offset=upload.offset+(va-upload.source);
2986 return true;
2987 }
2988 VulkanContext::GeometryUpload upload;
2989 if (!context_.geometry_provider_(va,bytes,upload)) return false;
2990 buffer=upload.buffer;offset=upload.offset;
2991 geometry.push_back(std::move(upload));
2992 return true;
2993 };
2994 }
2995 replay.graphics_family = family_ == context_.graphics_family_;
2996 replay.queue_stages = kind_ == QueueKind::copy ? detail::queue_stages_copy
2997 : kind_ == QueueKind::compute ? detail::queue_stages_compute
2998 : 0;
2999 replay.prepare_khr_instances = [this, &replay, &khr_guard](const BuildAccelerationStructure& build,
3000 VkDeviceAddress& address) {
3001 return stage_khr_instances(replay, build, khr_guard.stages, address);
2997 }; 3002 };
2998 replay.capture_predicate = [&](VkCommandBuffer cb, const PredicateCapture& p) { 3003 replay.prepare_xdxr_table = [this, &khr_guard](VkDeviceAddress& address, std::uint32_t& count) {
2999 context_.predicate_reducer_->capture(cb, p); 3004 return stage_xdxr_table(khr_guard.stages, address, count);
3000 }; 3005 };
3001 if (context_.predicated_copier_) { 3006 if (replay.write_acceleration_structures_properties) {
3002 copy_batch = context_.predicated_copier_->batch(); 3007 replay.prepare_khr_postbuild = [this, &khr_guard](std::uint32_t count, VkQueryPool& pool,
3003 replay.prepare_predicated_copy = [&](VkBuffer source, VkBuffer destination, VkDeviceSize src, 3008 std::uint32_t& first) {
3004 VkDeviceSize dst, VkDeviceSize size, 3009 return allocate_khr_as_queries(count, khr_guard.as_queries, pool, first);
3005 std::vector<PredicatedCopyDispatch>& out) {
3006 return copy_batch->prepare(source, destination, src, dst, size, out);
3007 };
3008 replay.emit_predicated_copy = [&](VkCommandBuffer cb, const std::vector<PredicatedCopyDispatch>& jobs) {
3009 context_.predicated_copier_->emit(cb, jobs);
3010 }; 3010 };
3011 } 3011 }
3012 } 3012 if (captures) {
3013 if (context_.scratch_) { 3013 if (kind_ == QueueKind::copy || !context_.predicate_reducer_ || family_ != context_.predicate_family_)
3014 replay.copy_scratch = [this, &tracker_lock, &scratch_guard](VkDeviceSize bytes, VkBuffer& buffer, 3014 return queue_unsupported(__LINE__);
3015 VkDeviceSize& offset) { 3015 // The helper's lazy pipeline is shared by queues. Serialize preparation with the tracker lock,
3016 // retaining pipeline -> resource -> tracker -> submit lock order through emit and submission.
3016 if (!tracker_lock.owns_lock()) tracker_lock.lock(); 3017 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3017 if (!scratch_guard.active) { 3018 batch = context_.predicate_reducer_->batch(captures);
3018 context_.scratch_->collect(); 3019 if (!batch) return queue_unsupported(__LINE__);
3019 scratch_guard.active = true; 3020 replay.prepare_predicate = [&](VkBuffer buffer, VkDeviceSize offset, PredicateCapture& out) {
3021 return batch->prepare(buffer, offset, out);
3022 };
3023 replay.capture_predicate = [&](VkCommandBuffer cb, const PredicateCapture& p) {
3024 context_.predicate_reducer_->capture(cb, p);
3025 };
3026 if (context_.predicated_copier_) {
3027 copy_batch = context_.predicated_copier_->batch();
3028 replay.prepare_predicated_copy = [&](VkBuffer source, VkBuffer destination, VkDeviceSize src,
3029 VkDeviceSize dst, VkDeviceSize size,
3030 std::vector<PredicatedCopyDispatch>& out) {
3031 return copy_batch->prepare(source, destination, src, dst, size, out);
3032 };
3033 replay.emit_predicated_copy = [&](VkCommandBuffer cb, const std::vector<PredicatedCopyDispatch>& jobs) {
3034 context_.predicated_copier_->emit(cb, jobs);
3035 };
3020 } 3036 }
3021 return context_.scratch_->get(bytes, buffer, offset); 3037 }
3022 }; 3038 if (context_.scratch_) {
3023 } 3039 replay.copy_scratch = [this, &tracker_lock, &scratch_guard](VkDeviceSize bytes, VkBuffer& buffer,
3024 if (kind_ != QueueKind::copy && context_.indirect_clamp_) { 3040 VkDeviceSize& offset) {
3025 // The record scratch belongs to this submission: collected here, retired below with its ticket. The 3041 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3026 // counter slots are read back once that ticket completes (the batch's destructor). 3042 if (!scratch_guard.active) {
3027 replay.prepare_indirect_clamp = [this, &tracker_lock, &clamp_batch, &clamp_guard]( 3043 scratch_guard.scratch = context_.scratch_.get();
3028 VkBuffer arguments, VkDeviceSize argument_offset, VkBuffer count, 3044 context_.scratch_->collect();
3029 VkDeviceSize count_offset, std::uint32_t kind, std::uint32_t stride, 3045 scratch_guard.active = true;
3030 std::uint32_t max_count, ClampedIndirect& out) { 3046 }
3031 // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation. 3047 return context_.scratch_->get(bytes, buffer, offset);
3032 if (!tracker_lock.owns_lock()) tracker_lock.lock(); 3048 };
3033 if (!clamp_batch) clamp_batch = context_.indirect_clamp_->batch(); 3049 }
3034 if (!clamp_guard.active) { 3050 if (kind_ != QueueKind::copy && context_.indirect_clamp_) {
3035 context_.indirect_clamp_->collect(); 3051 // The record scratch belongs to this submission: collected here, retired below with its ticket. The
3036 clamp_guard.active = true; 3052 // counter slots are read back once that ticket completes (the batch's destructor).
3053 replay.prepare_indirect_clamp = [this, &tracker_lock, &clamp_batch, &clamp_guard](
3054 VkBuffer arguments, VkDeviceSize argument_offset, VkBuffer count,
3055 VkDeviceSize count_offset, std::uint32_t kind, std::uint32_t stride,
3056 std::uint32_t max_count, ClampedIndirect& out) {
3057 // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation.
3058 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3059 if (!clamp_batch) clamp_batch = context_.indirect_clamp_->batch();
3060 if (!clamp_guard.active) {
3061 clamp_guard.clamp = context_.indirect_clamp_.get();
3062 context_.indirect_clamp_->collect();
3063 clamp_guard.active = true;
3064 }
3065 return clamp_batch->prepare(arguments, argument_offset, count, count_offset, kind, stride,
3066 max_count, out);
3067 };
3068 }
3069 if (kind_ != QueueKind::copy && context_.counted_dispatch_) {
3070 replay.prepare_counted_dispatch = [this, &tracker_lock, &counted_batch](
3071 VkBuffer args, VkDeviceSize args_offset, VkBuffer count, VkDeviceSize count_offset,
3072 std::uint32_t stride, std::uint32_t maximum, CountedDispatch& out) {
3073 // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation.
3074 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3075 if (!counted_batch) counted_batch = context_.counted_dispatch_->batch();
3076 return counted_batch->prepare(args, args_offset, count, count_offset, stride, maximum, out);
3077 };
3078 replay.emit_counted_dispatch = [this](VkCommandBuffer cb, const CountedDispatch& job) {
3079 context_.counted_dispatch_->emit(cb, job);
3080 };
3081 }
3082 if (kind_ != QueueKind::copy && context_.quad_indices_ && context_.scratch_) {
3083 replay.prepare_quad_indices = [this, &tracker_lock](
3084 VkBuffer indices, VkDeviceSize offset, VkIndexType type, std::uint64_t readable, std::uint32_t quads,
3085 VkBuffer scratch, VkDeviceSize scratch_offset, QuadIndexExpansion& out) {
3086 // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation.
3087 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3088 return context_.quad_indices_->prepare(indices, offset, type, readable, quads, scratch,
3089 scratch_offset, out);
3090 };
3091 replay.emit_quad_indices = [this](VkCommandBuffer cb, const QuadIndexExpansion& job) {
3092 context_.quad_indices_->emit(cb, job);
3093 };
3094 }
3095 if (context_.depth24_ && !transfer_only) {
3096 replay.depth24_prepare = [this, &tracker_lock, &depth24_guard](Depth24Job& job,
3097 std::vector<Depth24Job>& parts) {
3098 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3099 if (!depth24_guard.active) {
3100 depth24_guard.d24 = context_.depth24_.get();
3101 context_.depth24_->collect();
3102 depth24_guard.active = true;
3103 }
3104 return context_.depth24_->prepare(job, parts);
3105 };
3106 }
3107 if (can_resolve_occlusion) {
3108 replay.sum_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first,
3109 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) {
3110 occlusion_resolve_->sum(cb, pool, first, count, dst, offset);
3111 };
3112 replay.resolve_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first,
3113 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) {
3114 occlusion_resolve_->normalize(cb, pool, first, count, dst, offset);
3115 };
3116 replay.sum_statistics = [this](VkCommandBuffer cb, VkQueryPool pool, VkQueryPool mesh_pool,
3117 VkQueryPool primitives_pool, const std::uint8_t* mesh,
3118 std::uint32_t first, std::uint32_t count, VkBuffer dst,
3119 VkDeviceSize offset) {
3120 occlusion_resolve_->sum_statistics(cb, pool, mesh_pool, primitives_pool, mesh, first, count, dst,
3121 offset);
3122 };
3123 replay.sum_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first,
3124 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) {
3125 occlusion_resolve_->sum_binary(cb, pool, first, count, dst, offset);
3126 };
3127 }
3128 segments = 0;
3129 statistics_segments = 0;
3130 has_queries = false;
3131 // Collect unbuilt pipelines via PipelineCompiles (whether pipeline_workers_ is enabled or serial).
3132 // On pass 0, if any pipeline must be compiled, release pass-0 transient state along with tracker_lock
3133 // and resource_lock before invoking the compiler (keeping pipeline_lock so registered pipelines and
3134 // workers stay alive), then re-prepare on pass 1 against current resources.
3135 PipelineCompiles compiles;
3136 replay.compiles = &compiles;
3137 ReplayResult prepare_result = ReplayResult::success;
3138 for (std::size_t i = 0; i < lists.size(); ++i) {
3139 const auto result = prepare(*lists[i], resolve, replay, prepared[i], can_resolve_occlusion);
3140 if (result != ReplayResult::success) {
3141 prepare_result = result;
3142 break;
3037 } 3143 }
3038 return clamp_batch->prepare(arguments, argument_offset, count, count_offset, kind, stride, max_count, 3144 if (prepared[i].segment_count > UINT32_MAX - segments ||
3039 out); 3145 prepared[i].statistics_segment_count > UINT32_MAX - statistics_segments)
3040 }; 3146 return queue_unsupported(__LINE__);
3041 } 3147 segments += prepared[i].segment_count;
3042 if (kind_ != QueueKind::copy && context_.counted_dispatch_) { 3148 statistics_segments += prepared[i].statistics_segment_count;
3043 replay.prepare_counted_dispatch = [this, &tracker_lock, &counted_batch]( 3149 has_queries = has_queries || !prepared[i].queries.empty();
3044 VkBuffer args, VkDeviceSize args_offset, VkBuffer count, VkDeviceSize count_offset, 3150 }
3045 std::uint32_t stride, std::uint32_t maximum, CountedDispatch& out) { 3151 if (pass == 0 && !compiles.empty()) {
3046 // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation. 3152 if (depth24_guard.active) {
3047 if (!tracker_lock.owns_lock()) tracker_lock.lock(); 3153 context_.depth24_->retire(progress_, 0);
3048 if (!counted_batch) counted_batch = context_.counted_dispatch_->batch(); 3154 depth24_guard.active = false;
3049 return counted_batch->prepare(args, args_offset, count, count_offset, stride, maximum, out);
3050 };
3051 replay.emit_counted_dispatch = [this](VkCommandBuffer cb, const CountedDispatch& job) {
3052 context_.counted_dispatch_->emit(cb, job);
3053 };
3054 }
3055 if (kind_ != QueueKind::copy && context_.quad_indices_ && context_.scratch_) {
3056 replay.prepare_quad_indices = [this, &tracker_lock](
3057 VkBuffer indices, VkDeviceSize offset, VkIndexType type, std::uint64_t readable, std::uint32_t quads,
3058 VkBuffer scratch, VkDeviceSize scratch_offset, QuadIndexExpansion& out) {
3059 // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation.
3060 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3061 return context_.quad_indices_->prepare(indices, offset, type, readable, quads, scratch,
3062 scratch_offset, out);
3063 };
3064 replay.emit_quad_indices = [this](VkCommandBuffer cb, const QuadIndexExpansion& job) {
3065 context_.quad_indices_->emit(cb, job);
3066 };
3067 }
3068 if (context_.depth24_ && !transfer_only) {
3069 replay.depth24_prepare = [this, &tracker_lock, &depth24_guard](Depth24Job& job,
3070 std::vector<Depth24Job>& parts) {
3071 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3072 if (!depth24_guard.active) {
3073 context_.depth24_->collect();
3074 depth24_guard.active = true;
3075 } 3155 }
3076 return context_.depth24_->prepare(job, parts); 3156 if (scratch_guard.active) {
3077 }; 3157 context_.scratch_->retire(progress_, 0);
3078 } 3158 scratch_guard.active = false;
3079 const auto& occlusion_memory = context_.occlusion_resolve_memory_; 3159 }
3080 const bool can_resolve_occlusion = occlusion_memory.memoryTypeCount != 0; 3160 if (clamp_guard.active) {
3081 if (can_resolve_occlusion) { 3161 context_.indirect_clamp_->retire(progress_, 0);
3082 replay.sum_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, 3162 clamp_guard.active = false;
3083 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { 3163 }
3084 occlusion_resolve_->sum(cb, pool, first, count, dst, offset); 3164 batch.reset();
3085 }; 3165 copy_batch.reset();
3086 replay.resolve_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, 3166 counted_batch.reset();
3087 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { 3167 clamp_batch.reset();
3088 occlusion_resolve_->normalize(cb, pool, first, count, dst, offset); 3168 if (tracker_lock.owns_lock()) tracker_lock.unlock();
3089 }; 3169 resource_lock.unlock();
3090 replay.sum_statistics = [this](VkCommandBuffer cb, VkQueryPool pool, VkQueryPool mesh_pool, 3170 recycle_khr_stages(khr_guard.stages);
3091 VkQueryPool primitives_pool, const std::uint8_t* mesh, 3171 recycle_khr_as_queries(khr_guard.as_queries);
3092 std::uint32_t first, std::uint32_t count, VkBuffer dst, 3172 geometry.clear();
3093 VkDeviceSize offset) { 3173
3094 occlusion_resolve_->sum_statistics(cb, pool, mesh_pool, primitives_pool, mesh, first, count, dst, 3174 compiles.build(run_compiles);
3095 offset); 3175 const ReplayResult compile_result = check_compiled_pipelines(compiles, prepare_result);
3096 }; 3176 if (compile_result != ReplayResult::success) return compile_result;
3097 replay.sum_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, 3177 prior_compiles = std::move(compiles);
3098 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { 3178 has_prior_compiles = true;
3099 occlusion_resolve_->sum_binary(cb, pool, first, count, dst, offset); 3179 continue;
3100 };
3101 }
3102 const auto resolve = [this](ResourceId id) { return context_.resolve(id); };
3103 std::uint32_t segments = 0, statistics_segments = 0;
3104 bool has_queries = false;
3105 // With workers, the pipelines the lists need and that are not built yet are compiled together below instead of
3106 // one after another in prepare(). resource_lock is held until they are all built, which keeps the pipeline
3107 // states that own them alive (remove_pipeline takes it uniquely).
3108 PipelineCompiles compiles;
3109 if (context_.pipeline_workers_) replay.compiles = &compiles;
3110 ReplayResult prepare_result = ReplayResult::success;
3111 for (std::size_t i = 0; i < lists.size(); ++i) {
3112 const auto result = prepare(*lists[i], resolve, replay, prepared[i], can_resolve_occlusion);
3113 if (result != ReplayResult::success) {
3114 prepare_result = result;
3115 break;
3116 } 3180 }
3117 if (prepared[i].segment_count > UINT32_MAX - segments || 3181 prepare_result = build_pipelines(compiles, std::span(prepared).first(lists.size()), prepare_result,
3118 prepared[i].statistics_segment_count > UINT32_MAX - statistics_segments) 3182 run_compiles, has_prior_compiles ? &prior_compiles : nullptr);
3119 return queue_unsupported(__LINE__); 3183 replay.compiles = nullptr;
3120 segments += prepared[i].segment_count; 3184 if (prepare_result != ReplayResult::success) return prepare_result;
3121 statistics_segments += prepared[i].statistics_segment_count; 3185 break;
3122 has_queries = has_queries || !prepared[i].queries.empty();
3123 } 3186 }
3124 prepare_result = build_pipelines(
3125 compiles, std::span(prepared).first(lists.size()), prepare_result,
3126 [this](std::size_t count, const std::function<void(std::size_t)>& job) {
3127 context_.pipeline_workers_->run(count, job);
3128 });
3129 if (prepare_result != ReplayResult::success) return prepare_result;
3130 const auto segment_pool = [this](VkQueryType type, std::uint32_t count, 3187 const auto segment_pool = [this](VkQueryType type, std::uint32_t count,
3131 std::shared_ptr<OcclusionSegmentPool>& out) { 3188 std::shared_ptr<OcclusionSegmentPool>& out) {
3132 const auto& vk = context_.vk; 3189 const auto& vk = context_.vk;
@@ -3253,6 +3310,7 @@ private:
3253 const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer), 3310 const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer),
3254 "vkEndCommandBuffer") == VK_SUCCESS; 3311 "vkEndCommandBuffer") == VK_SUCCESS;
3255 resource_lock.unlock(); 3312 resource_lock.unlock();
3313 pipeline_lock.unlock();
3256 const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); 3314 const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0);
3257 if (!submitted) discard(); 3315 if (!submitted) discard();
3258 if (depth24_guard.active) { 3316 if (depth24_guard.active) {
@@ -3386,7 +3444,8 @@ private:
3386 } 3444 }
3387 const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer), 3445 const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer),
3388 "vkEndCommandBuffer") == VK_SUCCESS; 3446 "vkEndCommandBuffer") == VK_SUCCESS;
3389 resource_lock.unlock(); // release resource_mutex_ before vkQueueSubmit while keeping tracker_lock held 3447 resource_lock.unlock(); // release resource_mutex_ and pipeline_mutex_ before vkQueueSubmit while keeping tracker_lock held
3448 pipeline_lock.unlock();
3390 const bool wait_previous = ordered_timestamps && submitted_; 3449 const bool wait_previous = ordered_timestamps && submitted_;
3391 if (wait_previous) { 3450 if (wait_previous) {
3392 waits_.push_back(progress_); 3451 waits_.push_back(progress_);
@@ -4071,7 +4130,8 @@ private:
4071 std::vector<PreparedList> prepared_; 4130 std::vector<PreparedList> prepared_;
4072 std::uint32_t open_labels_ = 0; // queue labels begun and not ended 4131 std::uint32_t open_labels_ = 0; // queue labels begun and not ended
4073 bool ok_ = false; 4132 bool ok_ = false;
4074 // Wait-before-Signal. state_mutex_ is outermost (before resource_mutex_ -> tracker_mutex_ -> submit_mutex_) and 4133 // Wait-before-Signal. state_mutex_ is outermost (before pipeline_mutex_ -> resource_mutex_ -> tracker_mutex_ ->
4134 // submit_mutex_) and
4075 // guards the members above that execute, signal, wait and marker touch. 4135 // guards the members above that execute, signal, wait and marker touch.
4076 std::mutex state_mutex_; 4136 std::mutex state_mutex_;
4077 std::deque<Deferred> held_; 4137 std::deque<Deferred> held_;