MayaFlux 0.2.0
Digital-First Multimedia Processing Framework
Loading...
Searching...
No Matches
ShaderFoundry.cpp
Go to the documentation of this file.
1#include "ShaderFoundry.hpp"
2
10
12
14
16 const std::shared_ptr<Core::VulkanBackend>& backend,
17 const ShaderCompilerConfig& config)
18{
19 if (s_initialized) {
21 "ShaderFoundry already initialized (static flag)");
22 return true;
23 }
24
25 if (!backend) {
27 "Cannot initialize ShaderFoundry with null backend");
28 return false;
29 }
30
31 if (m_backend) {
33 "ShaderFoundry already initialized");
34 return true;
35 }
36
37 m_backend = backend;
38 m_config = config;
39
40 m_global_descriptor_manager = std::make_shared<Core::VKDescriptorManager>();
41 m_global_descriptor_manager->initialize(get_device(), 1024);
42
43 m_graphics_queue = m_backend->get_context().get_graphics_queue();
44 m_compute_queue = m_backend->get_context().get_compute_queue();
45 m_transfer_queue = m_backend->get_context().get_transfer_queue();
46
47 s_initialized = true;
48
50 "ShaderFoundry initialized");
51 return true;
52}
53
55{
56 if (!s_initialized || !m_backend) {
57 return;
58 }
59
61 "Stopping ShaderFoundry - freeing command buffers...");
62
63 auto device = get_device();
64
65 device.waitIdle();
66
68
70 "ShaderFoundry stopped - command buffers freed");
71}
72
74{
75 if (!s_initialized) {
76 return;
77 }
78
79 if (!m_backend) {
80 return;
81 }
82
84 "Shutting down ShaderFoundry...");
85
86 if (!m_command_buffers.empty()) {
88 "{} command buffers still exist during shutdown - freeing now",
89 m_command_buffers.size());
91 }
92
94
96
98
99 m_backend = nullptr;
100 s_initialized = false;
101
103 "ShaderFoundry shutdown complete");
104}
105
106//==============================================================================
107// Shader Compilation - Primary API
108//==============================================================================
109
110std::shared_ptr<Core::VKShaderModule> ShaderFoundry::compile_from_file(
111 const std::string& filepath,
112 std::optional<ShaderStage> stage,
113 const std::string& entry_point)
114{
115 if (!is_initialized()) {
117 "ShaderFoundry not initialized");
118 return nullptr;
119 }
120
121 auto it = m_shader_cache.find(filepath);
122 if (it != m_shader_cache.end()) {
124 "Using cached shader: {}", filepath);
125 return it->second;
126 }
127
128 std::optional<vk::ShaderStageFlagBits> vk_stage;
129 if (stage.has_value()) {
130 vk_stage = to_vulkan_stage(*stage);
131 }
132
133 auto shader = create_shader_module();
134
135 if (filepath.ends_with(".spv")) {
136 if (!shader->create_from_spirv_file(
137 get_device(), filepath,
138 vk_stage.value_or(vk::ShaderStageFlagBits::eCompute),
139 entry_point, m_config.enable_reflection)) {
141 "Failed to compile SPIR-V shader: {}", filepath);
142 return nullptr;
143 }
144 } else {
145 if (!shader->create_from_glsl_file(
146 get_device(), filepath, vk_stage, entry_point,
148 m_config.defines)) {
150 "Failed to compile GLSL shader: {}", filepath);
151 return nullptr;
152 }
153 }
154
155 m_shader_cache[filepath] = shader;
157 "Compiled shader: {} ({})", filepath, vk::to_string(shader->get_stage()));
158 return shader;
159}
160
161std::shared_ptr<Core::VKShaderModule> ShaderFoundry::compile_from_source(
162 const std::string& source,
163 ShaderStage stage,
164 const std::string& entry_point)
165{
166 if (!is_initialized()) {
168 "ShaderFoundry not initialized");
169 return nullptr;
170 }
171
172 auto shader = create_shader_module();
173 auto vk_stage = to_vulkan_stage(stage);
174
175 if (!shader->create_from_glsl(
176 get_device(), source, vk_stage, entry_point,
178 m_config.defines)) {
180 "Failed to compile GLSL source");
181 return nullptr;
182 }
183
185 "Compiled shader from source ({})", vk::to_string(vk_stage));
186 return shader;
187}
188
189std::shared_ptr<Core::VKShaderModule> ShaderFoundry::compile_from_source_cached(
190 const std::string& source,
191 ShaderStage stage,
192 const std::string& cache_key,
193 const std::string& entry_point)
194{
195 auto it = m_shader_cache.find(cache_key);
196 if (it != m_shader_cache.end()) {
198 "Using cached shader: {}", cache_key);
199 return it->second;
200 }
201
202 auto shader = compile_from_source(source, stage, entry_point);
203 if (!shader) {
204 return nullptr;
205 }
206
207 m_shader_cache[cache_key] = shader;
208 return shader;
209}
210
211std::shared_ptr<Core::VKShaderModule> ShaderFoundry::compile_from_spirv(
212 const std::string& spirv_path,
213 ShaderStage stage,
214 const std::string& entry_point)
215{
216 if (!is_initialized()) {
218 "ShaderFoundry not initialized");
219 return nullptr;
220 }
221
222 auto it = m_shader_cache.find(spirv_path);
223 if (it != m_shader_cache.end()) {
225 "Using cached SPIR-V shader: {}", spirv_path);
226 return it->second;
227 }
228
229 auto shader = create_shader_module();
230 auto vk_stage = to_vulkan_stage(stage);
231
232 if (!shader->create_from_spirv_file(
233 get_device(), spirv_path, vk_stage, entry_point,
236 "Failed to load SPIR-V shader: {}", spirv_path);
237 return nullptr;
238 }
239
240 m_shader_cache[spirv_path] = shader;
242 "Loaded SPIR-V shader: {}", spirv_path);
243 return shader;
244}
245
246std::shared_ptr<Core::VKShaderModule> ShaderFoundry::compile(const ShaderSource& shader_source)
247{
248 switch (shader_source.type) {
250 return compile_from_file(shader_source.content, shader_source.stage, shader_source.entry_point);
251
253 return compile_from_source(shader_source.content, shader_source.stage, shader_source.entry_point);
254
256 return compile_from_spirv(shader_source.content, shader_source.stage, shader_source.entry_point);
257
258 default:
260 "Unknown shader source type");
261 return nullptr;
262 }
263}
264
266 const std::string& content,
267 std::optional<ShaderStage> stage,
268 const std::string& entry_point)
269{
270 if (!is_initialized()) {
272 "ShaderFoundry not initialized");
273 return INVALID_SHADER;
274 }
275
276 DetectedSourceType source_type = detect_source_type(content);
277
278 std::string cache_key;
279 if (source_type == DetectedSourceType::FILE_GLSL || source_type == DetectedSourceType::FILE_SPIRV) {
280 cache_key = content;
281 } else {
282 cache_key = generate_source_cache_key(content, stage.value_or(ShaderStage::COMPUTE));
283 }
284
285 auto id_it = m_shader_filepath_cache.find(cache_key);
286 if (id_it != m_shader_filepath_cache.end()) {
288 "Using cached shader ID for: {}", cache_key);
289 return id_it->second;
290 }
291
292 if (!stage.has_value()) {
293 if (source_type == DetectedSourceType::FILE_GLSL || source_type == DetectedSourceType::FILE_SPIRV) {
294 if (source_type == DetectedSourceType::FILE_SPIRV) {
295 std::filesystem::path p(content);
296 std::string stem = p.stem().string();
297 stage = detect_stage_from_extension(stem);
298 } else {
299 stage = detect_stage_from_extension(content);
300 }
301 }
302
303 if (!stage.has_value()) {
305 "Cannot auto-detect shader stage from '{}' - must specify explicitly",
306 content);
307 return INVALID_SHADER;
308 }
309 }
310
311 std::shared_ptr<Core::VKShaderModule> shader_module;
312
313 switch (source_type) {
315 shader_module = compile_from_file(content, stage, entry_point);
316 break;
318 shader_module = compile_from_spirv(content, *stage, entry_point);
319 break;
321 shader_module = compile_from_source(content, *stage, entry_point);
322 break;
323 default:
325 "Cannot determine shader source type");
326 return INVALID_SHADER;
327 }
328
329 if (!shader_module) {
330 return INVALID_SHADER;
331 }
332
334
335 ShaderState& state = m_shaders[id];
336 state.module = shader_module;
337 state.filepath = cache_key;
338 state.stage = *stage;
339 state.entry_point = entry_point;
340
341 m_shader_filepath_cache[cache_key] = id;
342
344 "Shader loaded: {} (ID: {}, stage: {})",
345 cache_key, id, static_cast<int>(*stage));
346
347 return id;
348}
349
351{
352 return load_shader(source.content, source.stage, source.entry_point);
353}
354
355std::optional<std::filesystem::path> ShaderFoundry::resolve_shader_path(const std::string& filepath) const
356{
357 namespace fs = std::filesystem;
358
359 fs::path path(filepath);
360
361 if (path.is_absolute() || fs::exists(filepath)) {
362 return path;
363 }
364
365 std::vector<std::string> search_paths = {
366 Core::SHADER_BUILD_OUTPUT_DIR,
367 Core::SHADER_INSTALL_DIR,
368 Core::SHADER_SOURCE_DIR,
369 "./shaders",
370 "../shaders"
371 };
372
373 for (const auto& search_path : search_paths) {
374 fs::path full_path = fs::path(search_path) / filepath;
375 if (fs::exists(full_path)) {
376 return full_path;
377 }
378 }
379
380 return std::nullopt;
381}
382
384{
385 auto resolved_path = resolve_shader_path(content);
386
387 if (resolved_path.has_value()) {
388 std::string ext = resolved_path->extension().string();
389 std::ranges::transform(ext, ext.begin(), ::tolower);
390
391 if (ext == ".spv") {
393 }
394
396 }
397
398 if (content.size() > 1024 || content.find('\n') != std::string::npos) {
400 }
401
403}
404
405std::string ShaderFoundry::generate_source_cache_key(const std::string& source, ShaderStage stage) const
406{
407 std::hash<std::string> hasher;
408 size_t hash = hasher(source + std::to_string(static_cast<int>(stage)));
409 return "source_" + std::to_string(hash);
410}
411
412ShaderID ShaderFoundry::reload_shader(const std::string& filepath)
413{
414 invalidate_cache(filepath);
415
416 auto cache_it = m_shader_filepath_cache.find(filepath);
417 if (cache_it != m_shader_filepath_cache.end()) {
418 destroy_shader(cache_it->second);
419 m_shader_filepath_cache.erase(cache_it);
420 }
421
422 return load_shader(filepath);
423}
424
426{
427 auto it = m_shaders.find(shader_id);
428 if (it != m_shaders.end()) {
429 if (!it->second.filepath.empty()) {
430 m_shader_filepath_cache.erase(it->second.filepath);
431 }
432
433 if (!it->second.filepath.empty()) {
434 m_shader_cache.erase(it->second.filepath);
435 }
436
437 m_shaders.erase(it);
438 }
439}
440
441//==============================================================================
442// Shader Introspection
443//==============================================================================
444
446{
447 auto it = m_shaders.find(shader_id);
448 if (it == m_shaders.end()) {
449 return {};
450 }
451
452 const auto& reflection = it->second.module->get_reflection();
453
455 info.stage = it->second.stage;
456 info.entry_point = it->second.entry_point;
457 info.workgroup_size = reflection.workgroup_size;
458
459 for (const auto& binding : reflection.bindings) {
460 info.descriptor_bindings.push_back({ .set = binding.set,
461 .binding = binding.binding,
462 .type = binding.type,
463 .name = binding.name });
464 }
465
466 for (const auto& pc : reflection.push_constants) {
467 PushConstantRangeInfo pc_info {};
468 pc_info.offset = pc.offset;
469 pc_info.size = pc.size;
470 info.push_constant_ranges.push_back(pc_info);
471 }
472
473 return info;
474}
475
477{
478 auto it = m_shaders.find(shader_id);
479 if (it != m_shaders.end()) {
480 return it->second.stage;
481 }
483}
484
486{
487 auto it = m_shaders.find(shader_id);
488 if (it != m_shaders.end()) {
489 return it->second.entry_point;
490 }
491 return "main";
492}
493
494bool ShaderFoundry::is_cached(const std::string& cache_key) const
495{
496 return m_shader_cache.find(cache_key) != m_shader_cache.end();
497}
498
499std::vector<std::string> ShaderFoundry::get_cached_keys() const
500{
501 std::vector<std::string> keys;
502 keys.reserve(m_shader_cache.size());
503 for (const auto& [key, _] : m_shader_cache) {
504 keys.push_back(key);
505 }
506 return keys;
507}
508
510{
511 auto device = get_device();
512
513 for (auto& [key, shader_module] : m_shader_cache) {
514 if (shader_module) {
515 shader_module->cleanup(device);
516 }
517 }
518
519 m_shader_cache.clear();
520 m_shaders.clear();
522
524 "Cleaned up shader modules");
525}
526
527//==============================================================================
528// Hot-Reload Support
529//==============================================================================
530
531void ShaderFoundry::invalidate_cache(const std::string& cache_key)
532{
533 auto it = m_shader_cache.find(cache_key);
534 if (it != m_shader_cache.end()) {
535 m_shader_cache.erase(it);
537 "Invalidated shader cache: {}", cache_key);
538 }
539}
540
547
548std::shared_ptr<Core::VKShaderModule> ShaderFoundry::hot_reload(const std::string& filepath)
549{
550 invalidate_cache(filepath);
551 return compile_from_file(filepath);
552}
553
554//==============================================================================
555// Configuration
556//==============================================================================
557
559{
560 m_config = config;
562 "Updated shader compiler configuration");
563}
564
565void ShaderFoundry::add_include_directory(const std::string& directory)
566{
567 m_config.include_directories.push_back(directory);
568}
569
570void ShaderFoundry::add_define(const std::string& name, const std::string& value)
571{
572 m_config.defines[name] = value;
573}
574
575//==============================================================================
576// Descriptor Management
577//==============================================================================
578
580{
582
584 state.descriptor_set = m_global_descriptor_manager->allocate_set(get_device(), layout);
585
586 return id;
587}
588
590 DescriptorSetID descriptor_set_id,
591 uint32_t binding,
592 vk::DescriptorType type,
593 vk::Buffer buffer,
594 size_t offset,
595 size_t size)
596{
597 auto it = m_descriptor_sets.find(descriptor_set_id);
598 if (it == m_descriptor_sets.end()) {
599 return;
600 }
601
602 vk::DescriptorBufferInfo buffer_info;
603 buffer_info.buffer = buffer;
604 buffer_info.offset = offset;
605 buffer_info.range = size;
606
607 vk::WriteDescriptorSet write;
608 write.dstSet = it->second.descriptor_set;
609 write.dstBinding = binding;
610 write.dstArrayElement = 0;
611 write.descriptorCount = 1;
612 write.descriptorType = type;
613 write.pBufferInfo = &buffer_info;
614
615 get_device().updateDescriptorSets(1, &write, 0, nullptr);
616}
617
619 DescriptorSetID descriptor_set_id,
620 uint32_t binding,
621 vk::ImageView image_view,
622 vk::Sampler sampler,
623 vk::ImageLayout layout)
624{
625 auto it = m_descriptor_sets.find(descriptor_set_id);
626 if (it == m_descriptor_sets.end()) {
627 return;
628 }
629
630 vk::DescriptorImageInfo image_info;
631 image_info.imageView = image_view;
632 image_info.sampler = sampler;
633 image_info.imageLayout = layout;
634
635 vk::WriteDescriptorSet write;
636 write.dstSet = it->second.descriptor_set;
637 write.dstBinding = binding;
638 write.dstArrayElement = 0;
639 write.descriptorCount = 1;
640 write.descriptorType = vk::DescriptorType::eCombinedImageSampler;
641 write.pImageInfo = &image_info;
642
643 get_device().updateDescriptorSets(1, &write, 0, nullptr);
644}
645
647 DescriptorSetID descriptor_set_id,
648 uint32_t binding,
649 vk::ImageView image_view,
650 vk::ImageLayout layout)
651{
652 auto it = m_descriptor_sets.find(descriptor_set_id);
653 if (it == m_descriptor_sets.end()) {
654 return;
655 }
656
657 vk::DescriptorImageInfo image_info;
658 image_info.imageView = image_view;
659 image_info.imageLayout = layout;
660
661 vk::WriteDescriptorSet write;
662 write.dstSet = it->second.descriptor_set;
663 write.dstBinding = binding;
664 write.dstArrayElement = 0;
665 write.descriptorCount = 1;
666 write.descriptorType = vk::DescriptorType::eStorageImage;
667 write.pImageInfo = &image_info;
668
669 get_device().updateDescriptorSets(1, &write, 0, nullptr);
670}
671
672vk::DescriptorSet ShaderFoundry::get_descriptor_set(DescriptorSetID descriptor_set_id)
673{
674 auto it = m_descriptor_sets.find(descriptor_set_id);
675 if (it == m_descriptor_sets.end()) {
676 error<std::invalid_argument>(
679 std::source_location::current(),
680 "Invalid DescriptorSetID: {}", descriptor_set_id);
681 }
682 return it->second.descriptor_set;
683}
684
686{
687 auto device = get_device();
688
689 m_descriptor_sets.clear();
690
692 m_global_descriptor_manager->cleanup(device);
694 }
695
697 "Cleaned up descriptor resources");
698}
699
700//==============================================================================
701// Command Recording
702//==============================================================================
703
705{
706 auto& cmd_manager = m_backend->get_command_manager();
707
709
711 state.cmd = cmd_manager.begin_single_time_commands();
712 state.type = type;
713 state.is_active = true;
714
715 return id;
716}
717
719{
720 auto& cmd_manager = m_backend->get_command_manager();
721
723
724 vk::CommandBuffer cmd = cmd_manager.allocate_command_buffer(vk::CommandBufferLevel::eSecondary);
725
726 vk::CommandBufferInheritanceRenderingInfo inheritance_rendering;
727 inheritance_rendering.colorAttachmentCount = 1;
728 inheritance_rendering.pColorAttachmentFormats = &color_format;
729 inheritance_rendering.rasterizationSamples = vk::SampleCountFlagBits::e1;
730
731 vk::CommandBufferInheritanceInfo inheritance_info;
732 inheritance_info.pNext = &inheritance_rendering;
733
734 vk::CommandBufferBeginInfo begin_info;
735 begin_info.flags = vk::CommandBufferUsageFlagBits::eRenderPassContinue | vk::CommandBufferUsageFlagBits::eOneTimeSubmit;
736 begin_info.pInheritanceInfo = &inheritance_info;
737
738 cmd.begin(begin_info);
739
741 state.cmd = cmd;
744 state.is_active = true;
745
747 "Began secondary command buffer (ID: {}) for dynamic rendering", id);
748
749 return id;
750}
751
753{
754 auto it = m_command_buffers.find(cmd_id);
755 if (it != m_command_buffers.end()) {
756 return it->second.cmd;
757 }
758 return nullptr;
759}
760
762{
763 auto it = m_command_buffers.find(cmd_id);
764 if (it == m_command_buffers.end() || !it->second.is_active) {
765 return false;
766 }
767
768 it->second.cmd.end();
769 it->second.is_active = false;
770 return true;
771}
772
774{
775 if (!m_backend || !s_initialized) {
776 return;
777 }
778
779 auto& cmd_manager = m_backend->get_command_manager();
780 auto device = get_device();
781 device.waitIdle();
782
783 for (auto& [id, state] : m_command_buffers) {
784 if (state.is_active) {
785 cmd_manager.free_command_buffer(state.cmd);
786 }
787 if (state.timestamp_pool) {
788 device.destroyQueryPool(state.timestamp_pool);
789 }
790 }
791 m_command_buffers.clear();
792
794 "Freed all command buffers");
795}
796
797//==============================================================================
798// Synchronization
799//==============================================================================
800
802{
803 auto it = m_command_buffers.find(cmd_id);
804 if (it == m_command_buffers.end() || !it->second.is_active) {
805 return;
806 }
807
808 auto& cmd_manager = m_backend->get_command_manager();
809
810 it->second.cmd.end();
811
812 vk::SubmitInfo submit_info;
813 submit_info.commandBufferCount = 1;
814 submit_info.pCommandBuffers = &it->second.cmd;
815
816 vk::Queue queue;
817 switch (it->second.type) {
819 queue = m_graphics_queue;
820 break;
822 queue = m_compute_queue;
823 break;
825 queue = m_transfer_queue;
826 break;
827 }
828
829 if (queue.submit(1, &submit_info, nullptr) != vk::Result::eSuccess) {
831 "Failed to submit command buffer");
832 return;
833 }
834 queue.waitIdle();
835
836 cmd_manager.free_command_buffer(it->second.cmd);
837
838 it->second.is_active = false;
839 m_command_buffers.erase(it);
840}
841
843{
844 auto cmd_it = m_command_buffers.find(cmd_id);
845 if (cmd_it == m_command_buffers.end() || !cmd_it->second.is_active) {
846 return INVALID_FENCE;
847 }
848
849 cmd_it->second.cmd.end();
850
851 FenceID fence_id = m_next_fence_id++;
852
853 vk::FenceCreateInfo fence_info;
854 FenceState& fence_state = m_fences[fence_id];
855 fence_state.fence = get_device().createFence(fence_info);
856 fence_state.signaled = false;
857
858 vk::SubmitInfo submit_info;
859 submit_info.commandBufferCount = 1;
860 submit_info.pCommandBuffers = &cmd_it->second.cmd;
861
862 vk::Queue queue;
863 switch (cmd_it->second.type) {
865 queue = m_graphics_queue;
866 break;
868 queue = m_compute_queue;
869 break;
871 queue = m_transfer_queue;
872 break;
873 }
874
875 if (queue.submit(1, &submit_info, fence_state.fence) != vk::Result::eSuccess) {
877 "Failed to submit command buffer");
878 return INVALID_FENCE;
879 }
880
881 cmd_it->second.is_active = false;
882
883 return fence_id;
884}
885
887{
888 auto cmd_it = m_command_buffers.find(cmd_id);
889 if (cmd_it == m_command_buffers.end() || !cmd_it->second.is_active) {
890 return INVALID_SEMAPHORE;
891 }
892
893 cmd_it->second.cmd.end();
894
895 SemaphoreID semaphore_id = m_next_semaphore_id++;
896
897 vk::SemaphoreCreateInfo semaphore_info;
898 SemaphoreState& semaphore_state = m_semaphores[semaphore_id];
899 semaphore_state.semaphore = get_device().createSemaphore(semaphore_info);
900
901 vk::SubmitInfo submit_info;
902 submit_info.commandBufferCount = 1;
903 submit_info.pCommandBuffers = &cmd_it->second.cmd;
904 submit_info.signalSemaphoreCount = 1;
905 submit_info.pSignalSemaphores = &semaphore_state.semaphore;
906
907 vk::Queue queue;
908 switch (cmd_it->second.type) {
910 queue = m_graphics_queue;
911 break;
913 queue = m_compute_queue;
914 break;
916 queue = m_transfer_queue;
917 break;
918 }
919
920 if (queue.submit(1, &submit_info, nullptr) != vk::Result::eSuccess) {
922 "Failed to submit command buffer");
923 return INVALID_SEMAPHORE;
924 }
925
926 cmd_it->second.is_active = false;
927
928 return semaphore_id;
929}
930
932{
933 auto it = m_fences.find(fence_id);
934 if (it == m_fences.end()) {
935 return;
936 }
937
938 if (get_device().waitForFences(1, &it->second.fence, VK_TRUE, UINT64_MAX) != vk::Result::eSuccess) {
940 "Failed to wait for fence: {}", fence_id);
941 return;
942 }
943 it->second.signaled = true;
944}
945
946void ShaderFoundry::wait_for_fences(const std::vector<FenceID>& fence_ids)
947{
948 std::vector<vk::Fence> fences;
949 for (auto fence_id : fence_ids) {
950 auto it = m_fences.find(fence_id);
951 if (it != m_fences.end()) {
952 fences.push_back(it->second.fence);
953 }
954 }
955
956 if (!fences.empty()) {
957 if (get_device().waitForFences(static_cast<uint32_t>(fences.size()), fences.data(), VK_TRUE, UINT64_MAX) != vk::Result::eSuccess) {
959 "Failed to wait for fences");
960 return;
961 }
962 }
963
964 for (auto fence_id : fence_ids) {
965 auto it = m_fences.find(fence_id);
966 if (it != m_fences.end()) {
967 it->second.signaled = true;
968 }
969 }
970}
971
973{
974 auto it = m_fences.find(fence_id);
975 if (it == m_fences.end()) {
976 return false;
977 }
978
979 if (it->second.signaled) {
980 return true;
981 }
982
983 auto result = get_device().getFenceStatus(it->second.fence);
984 it->second.signaled = (result == vk::Result::eSuccess);
985 return it->second.signaled;
986}
987
990 SemaphoreID wait_semaphore,
991 vk::PipelineStageFlags /*wait_stage*/)
992{
993 auto sem_it = m_semaphores.find(wait_semaphore);
994 if (sem_it == m_semaphores.end()) {
996 }
997
998 return begin_commands(type);
999}
1000
1002{
1003 auto it = m_semaphores.find(semaphore_id);
1004 if (it != m_semaphores.end()) {
1005 return it->second.semaphore;
1006 }
1007 return nullptr;
1008}
1009
1011{
1012 auto device = get_device();
1013
1014 for (auto& [id, state] : m_fences) {
1015 if (state.fence) {
1016 device.destroyFence(state.fence);
1017 }
1018 }
1019 m_fences.clear();
1020
1021 for (auto& [id, state] : m_semaphores) {
1022 if (state.semaphore) {
1023 device.destroySemaphore(state.semaphore);
1024 }
1025 }
1026 m_semaphores.clear();
1027
1029 "Cleaned up sync objects");
1030}
1031
1032//==============================================================================
1033// Memory Barriers
1034//==============================================================================
1035
1037 CommandBufferID cmd_id,
1038 vk::Buffer buffer,
1039 vk::AccessFlags src_access,
1040 vk::AccessFlags dst_access,
1041 vk::PipelineStageFlags src_stage,
1042 vk::PipelineStageFlags dst_stage)
1043{
1044 auto it = m_command_buffers.find(cmd_id);
1045 if (it == m_command_buffers.end()) {
1046 return;
1047 }
1048
1049 vk::BufferMemoryBarrier barrier;
1050 barrier.srcAccessMask = src_access;
1051 barrier.dstAccessMask = dst_access;
1052 barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1053 barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1054 barrier.buffer = buffer;
1055 barrier.offset = 0;
1056 barrier.size = VK_WHOLE_SIZE;
1057
1058 it->second.cmd.pipelineBarrier(
1059 src_stage,
1060 dst_stage,
1061 vk::DependencyFlags {},
1062 0, nullptr,
1063 1, &barrier,
1064 0, nullptr);
1065}
1066
1068 CommandBufferID cmd_id,
1069 vk::Image image,
1070 vk::ImageLayout old_layout,
1071 vk::ImageLayout new_layout,
1072 vk::AccessFlags src_access,
1073 vk::AccessFlags dst_access,
1074 vk::PipelineStageFlags src_stage,
1075 vk::PipelineStageFlags dst_stage)
1076{
1077 auto it = m_command_buffers.find(cmd_id);
1078 if (it == m_command_buffers.end()) {
1079 return;
1080 }
1081
1082 vk::ImageMemoryBarrier barrier;
1083 barrier.srcAccessMask = src_access;
1084 barrier.dstAccessMask = dst_access;
1085 barrier.oldLayout = old_layout;
1086 barrier.newLayout = new_layout;
1087 barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1088 barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1089 barrier.image = image;
1090 barrier.subresourceRange.aspectMask = vk::ImageAspectFlagBits::eColor;
1091 barrier.subresourceRange.baseMipLevel = 0;
1092 barrier.subresourceRange.levelCount = 1;
1093 barrier.subresourceRange.baseArrayLayer = 0;
1094 barrier.subresourceRange.layerCount = 1;
1095
1096 it->second.cmd.pipelineBarrier(
1097 src_stage,
1098 dst_stage,
1099 vk::DependencyFlags {},
1100 0, nullptr,
1101 0, nullptr,
1102 1, &barrier);
1103}
1104
1105//==============================================================================
1106// Queue Management
1107//==============================================================================
1108
1112
1113//==============================================================================
1114// Profiling
1115//==============================================================================
1116
1117void ShaderFoundry::begin_timestamp(CommandBufferID cmd_id, const std::string& label)
1118{
1119 auto it = m_command_buffers.find(cmd_id);
1120 if (it == m_command_buffers.end()) {
1121 return;
1122 }
1123
1124 if (!it->second.timestamp_pool) {
1125 vk::QueryPoolCreateInfo pool_info;
1126 pool_info.queryType = vk::QueryType::eTimestamp;
1127 pool_info.queryCount = 128;
1128 it->second.timestamp_pool = get_device().createQueryPool(pool_info);
1129 }
1130
1131 auto query_index = static_cast<uint32_t>(it->second.timestamp_queries.size() * 2);
1132 it->second.timestamp_queries[label] = query_index;
1133
1134 it->second.cmd.resetQueryPool(it->second.timestamp_pool, query_index, 2);
1135 it->second.cmd.writeTimestamp(vk::PipelineStageFlagBits::eTopOfPipe, it->second.timestamp_pool, query_index);
1136}
1137
1138void ShaderFoundry::end_timestamp(CommandBufferID cmd_id, const std::string& label)
1139{
1140 auto it = m_command_buffers.find(cmd_id);
1141 if (it == m_command_buffers.end()) {
1142 return;
1143 }
1144
1145 auto query_it = it->second.timestamp_queries.find(label);
1146 if (query_it == it->second.timestamp_queries.end()) {
1147 return;
1148 }
1149
1150 uint32_t query_index = query_it->second;
1151 it->second.cmd.writeTimestamp(vk::PipelineStageFlagBits::eBottomOfPipe, it->second.timestamp_pool, query_index + 1);
1152}
1153
1155{
1156 auto it = m_command_buffers.find(cmd_id);
1157 if (it == m_command_buffers.end()) {
1158 return { .label = label, .duration_ns = 0, .valid = false };
1159 }
1160
1161 auto query_it = it->second.timestamp_queries.find(label);
1162 if (query_it == it->second.timestamp_queries.end()) {
1163 return { .label = label, .duration_ns = 0, .valid = false };
1164 }
1165
1166 if (!it->second.timestamp_pool) {
1167 return { .label = label, .duration_ns = 0, .valid = false };
1168 }
1169
1170 uint32_t query_index = query_it->second;
1171 uint64_t timestamps[2];
1172
1173 auto result = get_device().getQueryPoolResults(
1174 it->second.timestamp_pool,
1175 query_index,
1176 2,
1177 sizeof(timestamps),
1178 timestamps,
1179 sizeof(uint64_t),
1180 vk::QueryResultFlagBits::e64 | vk::QueryResultFlagBits::eWait);
1181
1182 if (result != vk::Result::eSuccess) {
1183 return { .label = label, .duration_ns = 0, .valid = false };
1184 }
1185
1186 auto props = m_backend->get_context().get_physical_device().getProperties();
1187 float timestamp_period = props.limits.timestampPeriod;
1188
1189 auto duration_ns = static_cast<uint64_t>((timestamps[1] - timestamps[0]) * timestamp_period);
1190
1191 return { .label = label, .duration_ns = duration_ns, .valid = true };
1192}
1193
1194//==============================================================================
1195// Internal Access
1196//==============================================================================
1197
1198std::shared_ptr<Core::VKShaderModule> ShaderFoundry::get_vk_shader_module(ShaderID shader_id)
1199{
1200 auto& foundry = ShaderFoundry::instance();
1201 auto it = foundry.m_shaders.find(shader_id);
1202 if (it != foundry.m_shaders.end()) {
1203 return it->second.module;
1204 }
1205 return nullptr;
1206}
1207
1208//==============================================================================
1209// Utilities
1210//==============================================================================
1211
1212vk::ShaderStageFlagBits ShaderFoundry::to_vulkan_stage(ShaderStage stage)
1213{
1214 switch (stage) {
1216 return vk::ShaderStageFlagBits::eCompute;
1218 return vk::ShaderStageFlagBits::eVertex;
1220 return vk::ShaderStageFlagBits::eFragment;
1222 return vk::ShaderStageFlagBits::eGeometry;
1224 return vk::ShaderStageFlagBits::eTessellationControl;
1226 return vk::ShaderStageFlagBits::eTessellationEvaluation;
1227 default:
1228 return vk::ShaderStageFlagBits::eCompute;
1229 }
1230}
1231
1232std::optional<ShaderStage> ShaderFoundry::detect_stage_from_extension(const std::string& filepath)
1233{
1234 auto vk_stage = Core::VKShaderModule::detect_stage_from_extension(filepath);
1235 if (!vk_stage.has_value()) {
1236 return std::nullopt;
1237 }
1238
1239 switch (*vk_stage) {
1240 case vk::ShaderStageFlagBits::eCompute:
1241 return ShaderStage::COMPUTE;
1242 case vk::ShaderStageFlagBits::eVertex:
1243 return ShaderStage::VERTEX;
1244 case vk::ShaderStageFlagBits::eFragment:
1245 return ShaderStage::FRAGMENT;
1246 case vk::ShaderStageFlagBits::eGeometry:
1247 return ShaderStage::GEOMETRY;
1248 case vk::ShaderStageFlagBits::eTessellationControl:
1250 case vk::ShaderStageFlagBits::eTessellationEvaluation:
1252 default:
1253 return std::nullopt;
1254 }
1255}
1256
1257//==============================================================================
1258// Private Helpers
1259//==============================================================================
1260
1261std::shared_ptr<Core::VKShaderModule> ShaderFoundry::create_shader_module()
1262{
1263 return std::make_shared<Core::VKShaderModule>();
1264}
1265
1267{
1268 return m_backend->get_context().get_device();
1269}
1270
1271} // namespace MayaFlux::Portal::Graphics
#define MF_INFO(comp, ctx,...)
#define MF_ERROR(comp, ctx,...)
#define MF_RT_TRACE(comp, ctx,...)
#define MF_WARN(comp, ctx,...)
#define MF_DEBUG(comp, ctx,...)
static std::optional< vk::ShaderStageFlagBits > detect_stage_from_extension(const std::string &filepath)
Auto-detect shader stage from file extension.
vk::DescriptorSet get_descriptor_set(DescriptorSetID descriptor_set_id)
Get Vulkan descriptor set handle from DescriptorSetID.
vk::Queue get_graphics_queue() const
Get Vulkan graphics queue.
void wait_for_fences(const std::vector< FenceID > &fence_ids)
Wait for multiple fences to be signaled.
static std::optional< ShaderStage > detect_stage_from_extension(const std::string &filepath)
Auto-detect shader stage from file extension.
void shutdown()
Shutdown and cleanup all ShaderFoundry resources.
void wait_for_fence(FenceID fence_id)
Wait for fence to be signaled.
bool is_cached(const std::string &cache_key) const
Check if shader is cached.
std::shared_ptr< Core::VKShaderModule > compile(const ShaderSource &shader_source)
Compile shader from ShaderSource descriptor.
ShaderID reload_shader(const std::string &filepath)
Hot-reload shader (returns new ID)
std::shared_ptr< Core::VKShaderModule > hot_reload(const std::string &filepath)
Hot-reload a shader from file.
void set_config(const ShaderCompilerConfig &config)
Update compiler configuration.
void update_descriptor_storage_image(DescriptorSetID descriptor_set_id, uint32_t binding, vk::ImageView image_view, vk::ImageLayout layout=vk::ImageLayout::eGeneral)
Update descriptor set with storage image binding.
CommandBufferID begin_commands(CommandBufferType type)
Begin recording command buffer.
vk::Semaphore get_semaphore_handle(SemaphoreID semaphore_id)
Get Vulkan fence handle from FenceID.
std::shared_ptr< Core::VKShaderModule > get_vk_shader_module(ShaderID shader_id)
DetectedSourceType
Internal enum for source type detection.
bool initialize(const std::shared_ptr< Core::VulkanBackend > &backend, const ShaderCompilerConfig &config={})
Initialize shader compiler.
std::unordered_map< std::string, ShaderID > m_shader_filepath_cache
DetectedSourceType detect_source_type(const std::string &content) const
std::unordered_map< FenceID, FenceState > m_fences
std::shared_ptr< Core::VKShaderModule > create_shader_module()
void free_all_command_buffers()
Free all allocated command buffers.
void invalidate_cache(const std::string &cache_key)
Invalidate cache for specific shader.
TimestampResult get_timestamp_result(CommandBufferID cmd_id, const std::string &label)
void add_define(const std::string &name, const std::string &value="")
Add preprocessor define for shader compilation.
std::unordered_map< std::string, std::shared_ptr< Core::VKShaderModule > > m_shader_cache
static vk::ShaderStageFlagBits to_vulkan_stage(ShaderStage stage)
Convert Portal ShaderStage to Vulkan ShaderStageFlagBits.
void update_descriptor_buffer(DescriptorSetID descriptor_set_id, uint32_t binding, vk::DescriptorType type, vk::Buffer buffer, size_t offset, size_t size)
Update descriptor set with buffer binding.
CommandBufferID begin_commands_with_wait(CommandBufferType type, SemaphoreID wait_semaphore, vk::PipelineStageFlags wait_stage)
Begin command buffer that waits on a semaphore.
std::optional< std::filesystem::path > resolve_shader_path(const std::string &filepath) const
void stop()
Stop active command recording and free command buffers.
std::unordered_map< DescriptorSetID, DescriptorSetState > m_descriptor_sets
std::unordered_map< CommandBufferID, CommandBufferState > m_command_buffers
SemaphoreID submit_with_signal(CommandBufferID cmd_id)
Submit command buffer asynchronously, returning a semaphore.
std::shared_ptr< Core::VKDescriptorManager > m_global_descriptor_manager
vk::Queue get_compute_queue() const
Get Vulkan compute queue.
FenceID submit_async(CommandBufferID cmd_id)
Submit command buffer asynchronously, returning a fence.
void update_descriptor_image(DescriptorSetID descriptor_set_id, uint32_t binding, vk::ImageView image_view, vk::Sampler sampler, vk::ImageLayout layout=vk::ImageLayout::eShaderReadOnlyOptimal)
Update descriptor set with image binding.
std::string get_shader_entry_point(ShaderID shader_id)
Get entry point name for compiled shader.
std::shared_ptr< Core::VKShaderModule > compile_from_source_cached(const std::string &source, ShaderStage stage, const std::string &cache_key, const std::string &entry_point="main")
bool end_commands(CommandBufferID cmd_id)
End recording command buffer.
bool is_initialized() const
Check if compiler is initialized.
void destroy_shader(ShaderID shader_id)
Destroy shader (cleanup internal state)
void begin_timestamp(CommandBufferID cmd_id, const std::string &label="")
void image_barrier(CommandBufferID cmd_id, vk::Image image, vk::ImageLayout old_layout, vk::ImageLayout new_layout, vk::AccessFlags src_access, vk::AccessFlags dst_access, vk::PipelineStageFlags src_stage, vk::PipelineStageFlags dst_stage)
Insert image memory barrier.
void submit_and_wait(CommandBufferID cmd_id)
Submit command buffer and wait for completion.
vk::CommandBuffer get_command_buffer(CommandBufferID cmd_id)
Get Vulkan command buffer handle from CommandBufferID.
vk::Queue get_transfer_queue() const
Get Vulkan transfer queue.
void add_include_directory(const std::string &directory)
Add include directory for shader compilation.
std::vector< std::string > get_cached_keys() const
Get all cached shader keys.
void clear_cache()
Invalidate entire shader cache.
ShaderReflectionInfo get_shader_reflection(ShaderID shader_id)
Get reflection info for compiled shader.
std::shared_ptr< Core::VKShaderModule > compile_from_source(const std::string &source, ShaderStage stage, const std::string &entry_point="main")
void buffer_barrier(CommandBufferID cmd_id, vk::Buffer buffer, vk::AccessFlags src_access, vk::AccessFlags dst_access, vk::PipelineStageFlags src_stage, vk::PipelineStageFlags dst_stage)
Insert buffer memory barrier.
std::atomic< uint64_t > m_next_descriptor_set_id
std::shared_ptr< Core::VKShaderModule > compile_from_file(const std::string &filepath, std::optional< ShaderStage > stage=std::nullopt, const std::string &entry_point="main")
void end_timestamp(CommandBufferID cmd_id, const std::string &label="")
std::shared_ptr< Core::VKShaderModule > compile_from_spirv(const std::string &spirv_path, ShaderStage stage, const std::string &entry_point="main")
ShaderID load_shader(const std::string &content, std::optional< ShaderStage > stage=std::nullopt, const std::string &entry_point="main")
Universal shader loader - auto-detects source type.
std::string generate_source_cache_key(const std::string &source, ShaderStage stage) const
std::shared_ptr< Core::VulkanBackend > m_backend
bool is_fence_signaled(FenceID fence_id)
Check if fence is signaled.
std::unordered_map< SemaphoreID, SemaphoreState > m_semaphores
ShaderStage get_shader_stage(ShaderID shader_id)
Get shader stage for compiled shader.
CommandBufferID begin_secondary_commands(vk::Format color_format)
Begin recording a secondary command buffer for dynamic rendering.
std::unordered_map< ShaderID, ShaderState > m_shaders
DescriptorSetID allocate_descriptor_set(vk::DescriptorSetLayout layout)
Allocate descriptor set for a pipeline.
@ Rendering
GPU rendering operations (graphics pipeline, frame rendering)
@ ShaderCompilation
Shader compilation tasks (Portal::Graphics::ShaderCompiler)
@ Portal
High-level user-facing API layer.
constexpr ShaderID INVALID_SHADER
ShaderStage
User-friendly shader stage enum.
constexpr FenceID INVALID_FENCE
constexpr SemaphoreID INVALID_SEMAPHORE
constexpr CommandBufferID INVALID_COMMAND_BUFFER
Extracted push constant range from shader reflection.
bool enable_reflection
Extract descriptor bindings and metadata.
std::vector< std::string > include_directories
Paths for #include resolution.
std::unordered_map< std::string, std::string > defines
Preprocessor macros.
Configuration for shader compilation.
std::shared_ptr< Core::VKShaderModule > std::string filepath
std::optional< std::array< uint32_t, 3 > > workgroup_size
std::vector< PushConstantRangeInfo > push_constant_ranges
std::vector< DescriptorBindingInfo > descriptor_bindings
Extracted reflection information from compiled shader.
std::string content
Shader source code or SPIR-V path.
enum MayaFlux::Portal::Graphics::ShaderSource::SourceType type
Shader source descriptor for compilation.