7#ifdef MAYAFLUX_USE_SHADERC
8#include <shaderc/shaderc.hpp>
11#include <spirv_cross/spirv_cross.hpp>
16 std::vector<std::string> get_shader_search_paths()
19 SHADER_BUILD_OUTPUT_DIR,
27 std::string resolve_shader_path(
const std::string& filename)
29 namespace fs = std::filesystem;
31 if (fs::path(filename).is_absolute() || fs::exists(filename)) {
35 for (
const auto& search_path : get_shader_search_paths()) {
36 fs::path full_path = fs::path(search_path) / filename;
37 if (fs::exists(full_path)) {
39 "Resolved shader '{}' -> '{}'", filename, full_path.string());
40 return full_path.string();
47 vk::DescriptorType spirv_to_vk_descriptor_type(spirv_cross::SPIRType::BaseType base_type,
48 const spirv_cross::SPIRType& type,
51 if (type.image.dim != spv::DimMax) {
52 if (type.image.sampled == 2) {
53 return vk::DescriptorType::eStorageImage;
56 if (type.image.sampled == 1) {
57 return is_storage ? vk::DescriptorType::eSampledImage
58 : vk::DescriptorType::eCombinedImageSampler;
63 return vk::DescriptorType::eStorageBuffer;
66 return vk::DescriptorType::eUniformBuffer;
78 "VKShaderModule destroyed without cleanup() - potential leak");
83 : m_module(other.m_module)
84 , m_stage(other.m_stage)
85 , m_entry_point(std::move(other.m_entry_point))
86 , m_reflection(std::move(other.m_reflection))
87 , m_spirv_code(std::move(other.m_spirv_code))
88 , m_preserve_spirv(other.m_preserve_spirv)
89 , m_specialization_map(std::move(other.m_specialization_map))
90 , m_specialization_entries(std::move(other.m_specialization_entries))
91 , m_specialization_data(std::move(other.m_specialization_data))
92 , m_specialization_info(other.m_specialization_info)
94 other.m_module =
nullptr;
102 "VKShaderModule move-assigned without cleanup() - potential leak");
105 m_module = other.m_module;
106 m_stage = other.m_stage;
107 m_entry_point = std::move(other.m_entry_point);
108 m_reflection = std::move(other.m_reflection);
109 m_spirv_code = std::move(other.m_spirv_code);
110 m_preserve_spirv = other.m_preserve_spirv;
111 m_specialization_map = std::move(other.m_specialization_map);
112 m_specialization_entries = std::move(other.m_specialization_entries);
113 m_specialization_data = std::move(other.m_specialization_data);
114 m_specialization_info = other.m_specialization_info;
116 other.m_module =
nullptr;
124 device.destroyShaderModule(
m_module);
128 "Shader module cleaned up ({} stage)", vk::to_string(
m_stage));
144 const std::vector<uint32_t>& spirv_code,
145 vk::ShaderStageFlagBits stage,
146 const std::string& entry_point,
147 bool enable_reflection)
149 if (spirv_code.empty()) {
151 "Cannot create shader module from empty SPIR-V code");
155 if (spirv_code[0] != 0x07230203) {
157 "Invalid SPIR-V magic number: 0x{:08X} (expected 0x07230203)",
162 vk::ShaderModuleCreateInfo create_info;
163 create_info.codeSize = spirv_code.size() *
sizeof(uint32_t);
164 create_info.pCode = spirv_code.data();
167 m_module = device.createShaderModule(create_info);
168 }
catch (
const vk::SystemError& e) {
170 "Failed to create shader module: {}", e.what());
181 if (enable_reflection) {
184 "Shader reflection failed - descriptor layouts must be manually specified");
189 "Shader module created ({} stage, {} bytes SPIR-V, entry='{}')",
190 vk::to_string(stage), spirv_code.size() * 4, entry_point);
197 const std::string& spirv_path,
198 vk::ShaderStageFlagBits stage,
199 const std::string& entry_point,
200 bool enable_reflection)
202 std::string resolved_path = resolve_shader_path(spirv_path);
205 if (spirv_code.empty()) {
207 "Failed to read SPIR-V file: '{}'", spirv_path);
212 "Loaded SPIR-V from file: '{}'", spirv_path);
214 return create_from_spirv(device, spirv_code, stage, entry_point, enable_reflection);
223 const std::string& glsl_source,
224 vk::ShaderStageFlagBits stage,
225 const std::string& entry_point,
226 bool enable_reflection,
227 const std::vector<std::string>& include_directories,
228 const std::unordered_map<std::string, std::string>& defines)
231 if (spirv_code.empty()) {
233 "Failed to compile GLSL to SPIR-V ({} stage)", vk::to_string(stage));
238 "Compiled GLSL to SPIR-V ({} stage, {} bytes)",
239 vk::to_string(stage), spirv_code.size() * 4);
241 return create_from_spirv(device, spirv_code, stage, entry_point, enable_reflection);
246 const std::string& glsl_path,
247 std::optional<vk::ShaderStageFlagBits> stage,
248 const std::string& entry_point,
249 bool enable_reflection,
250 const std::vector<std::string>& include_directories,
251 const std::unordered_map<std::string, std::string>& defines)
253 std::string resolved_path = resolve_shader_path(glsl_path);
255 if (!stage.has_value()) {
257 if (!stage.has_value()) {
259 "Cannot auto-detect shader stage from file extension: '{}'", glsl_path);
263 "Auto-detected {} stage from file extension", vk::to_string(*stage));
267 if (glsl_source.empty()) {
269 "Failed to read GLSL file: '{}'", glsl_path);
274 "Loaded GLSL from file: '{}' ({} bytes)", glsl_path, glsl_source.size());
277 enable_reflection, include_directories, defines);
288 "Cannot get stage create info from invalid shader module");
292 vk::PipelineShaderStageCreateInfo stage_info;
310 const std::unordered_map<uint32_t, uint32_t>& constants)
315 "Set {} specialization constants for {} stage",
316 constants.size(), vk::to_string(
m_stage));
336 vk::SpecializationMapEntry entry;
337 entry.constantID = constant_id;
338 entry.offset = offset;
339 entry.size =
sizeof(uint32_t);
343 offset +=
sizeof(uint32_t);
359 spirv_cross::Compiler compiler(spirv_code);
360 spirv_cross::ShaderResources resources = compiler.get_shader_resources();
362 auto reflect_resources = [&](
const spirv_cross::SmallVector<spirv_cross::Resource>& res_vec,
363 bool is_storage =
false) {
364 for (
const auto& resource : res_vec) {
366 desc.
set = compiler.get_decoration(resource.id, spv::DecorationDescriptorSet);
367 desc.
binding = compiler.get_decoration(resource.id, spv::DecorationBinding);
369 desc.
name = resource.name;
371 const auto& type = compiler.get_type(resource.type_id);
372 desc.
count = type.array.empty() ? 1 : type.array[0];
373 desc.
type = spirv_to_vk_descriptor_type(type.basetype, type, is_storage);
379 reflect_resources(resources.uniform_buffers,
false);
381 reflect_resources(resources.storage_buffers,
true);
383 reflect_resources(resources.sampled_images,
false);
385 reflect_resources(resources.storage_images,
true);
387 reflect_resources(resources.separate_images,
false);
388 reflect_resources(resources.separate_samplers,
false);
395 for (
const auto& pc_buffer : resources.push_constant_buffers) {
396 const auto& type = compiler.get_type(pc_buffer.type_id);
401 range.
size =
static_cast<uint32_t
>(compiler.get_declared_struct_size(type));
411 auto spec_constants = compiler.get_specialization_constants();
412 for (
const auto& spec : spec_constants) {
415 sc.
name = compiler.get_name(spec.id);
417 const auto& type = compiler.get_type(compiler.get_constant(spec.id).constant_type);
418 sc.
size =
static_cast<uint32_t
>(compiler.get_declared_struct_size(type));
425 "Reflected {} specialization constants",
429 if (
m_stage == vk::ShaderStageFlagBits::eCompute) {
430 auto entry_points = compiler.get_entry_points_and_stages();
432 for (
const auto& ep : entry_points) {
433 if (ep.name ==
m_entry_point && ep.execution_model == spv::ExecutionModelGLCompute) {
435 std::array<uint32_t, 3> workgroup_size {
436 compiler.get_execution_mode_argument(spv::ExecutionModeLocalSize, 0),
437 compiler.get_execution_mode_argument(spv::ExecutionModeLocalSize, 1),
438 compiler.get_execution_mode_argument(spv::ExecutionModeLocalSize, 2)
441 if (!workgroup_size.empty() && workgroup_size.size() >= 3) {
449 "Compute shader workgroup size: [{}, {}, {}]",
450 workgroup_size[0], workgroup_size[1], workgroup_size[2]);
457 if (
m_stage == vk::ShaderStageFlagBits::eVertex) {
458 for (
const auto& input : resources.stage_inputs) {
459 uint32_t location = compiler.get_decoration(input.id, spv::DecorationLocation);
460 const auto& type = compiler.get_type(input.type_id);
462 vk::VertexInputAttributeDescription attr;
463 attr.location = location;
473 "Reflected {} vertex input attributes",
480 }
catch (
const spirv_cross::CompilerError& e) {
482 "SPIRV-Cross reflection failed: {}", e.what());
489 using BaseType = spirv_cross::SPIRType::BaseType;
491 if (type.columns > 1) {
493 "Matrix types are not valid vertex attributes (columns={})",
495 return vk::Format::eUndefined;
498 if (type.width != 32) {
500 "Unsupported SPIR-V vertex attribute width {} (only 32-bit supported)",
502 return vk::Format::eUndefined;
505 const uint32_t vec_size = type.vecsize;
506 if (type.basetype == BaseType::Float) {
509 return vk::Format::eR32Sfloat;
511 return vk::Format::eR32G32Sfloat;
513 return vk::Format::eR32G32B32Sfloat;
515 return vk::Format::eR32G32B32A32Sfloat;
517 }
else if (type.basetype == BaseType::Int) {
520 return vk::Format::eR32Sint;
522 return vk::Format::eR32G32Sint;
524 return vk::Format::eR32G32B32Sint;
526 return vk::Format::eR32G32B32A32Sint;
528 }
else if (type.basetype == BaseType::UInt) {
531 return vk::Format::eR32Uint;
533 return vk::Format::eR32G32Uint;
535 return vk::Format::eR32G32B32Uint;
537 return vk::Format::eR32G32B32A32Uint;
542 "Unsupported SPIR-V vertex attribute type (basetype={}, vecsize={})",
543 static_cast<int>(type.basetype), vec_size);
545 return vk::Format::eUndefined;
553 const std::string& filepath)
555 std::filesystem::path path(filepath);
556 std::string ext = path.extension().string();
558 std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower);
560 static const std::unordered_map<std::string, vk::ShaderStageFlagBits> extension_map = {
561 {
".comp", vk::ShaderStageFlagBits::eCompute },
562 {
".vert", vk::ShaderStageFlagBits::eVertex },
563 {
".frag", vk::ShaderStageFlagBits::eFragment },
564 {
".geom", vk::ShaderStageFlagBits::eGeometry },
565 {
".tesc", vk::ShaderStageFlagBits::eTessellationControl },
566 {
".tese", vk::ShaderStageFlagBits::eTessellationEvaluation },
567 {
".rgen", vk::ShaderStageFlagBits::eRaygenKHR },
568 {
".rint", vk::ShaderStageFlagBits::eIntersectionKHR },
569 {
".rahit", vk::ShaderStageFlagBits::eAnyHitKHR },
570 {
".rchit", vk::ShaderStageFlagBits::eClosestHitKHR },
571 {
".rmiss", vk::ShaderStageFlagBits::eMissKHR },
572 {
".rcall", vk::ShaderStageFlagBits::eCallableKHR },
573 {
".mesh", vk::ShaderStageFlagBits::eMeshEXT },
574 {
".task", vk::ShaderStageFlagBits::eTaskEXT }
577 auto it = extension_map.find(ext);
578 if (it != extension_map.end()) {
586 const std::string& glsl_source,
587 vk::ShaderStageFlagBits stage,
588 const std::vector<std::string>& include_directories,
589 const std::unordered_map<std::string, std::string>& defines)
591#ifdef MAYAFLUX_USE_SHADERC
592 shaderc::Compiler compiler;
593 shaderc::CompileOptions options;
595 options.SetOptimizationLevel(shaderc_optimization_level_performance);
597 for (
const auto& dir : include_directories) {
601 for (
const auto& [name, value] : defines) {
602 options.AddMacroDefinition(name, value);
605 shaderc_shader_kind shader_kind;
607 case vk::ShaderStageFlagBits::eVertex:
608 shader_kind = shaderc_glsl_vertex_shader;
610 case vk::ShaderStageFlagBits::eFragment:
611 shader_kind = shaderc_glsl_fragment_shader;
613 case vk::ShaderStageFlagBits::eCompute:
614 shader_kind = shaderc_glsl_compute_shader;
616 case vk::ShaderStageFlagBits::eGeometry:
617 shader_kind = shaderc_glsl_geometry_shader;
619 case vk::ShaderStageFlagBits::eTessellationControl:
620 shader_kind = shaderc_glsl_tess_control_shader;
622 case vk::ShaderStageFlagBits::eTessellationEvaluation:
623 shader_kind = shaderc_glsl_tess_evaluation_shader;
627 "Unsupported shader stage for GLSL compilation: {}", vk::to_string(stage));
631 shaderc::SpvCompilationResult result = compiler.CompileGlslToSpv(
637 if (result.GetCompilationStatus() != shaderc_compilation_status_success) {
639 "GLSL compilation failed:\n{}", result.GetErrorMessage());
643 std::vector<uint32_t> spirv(result.cbegin(), result.cend());
646 "Compiled GLSL ({} stage) -> {} bytes SPIR-V",
647 vk::to_string(stage), spirv.size() * 4);
658 std::ifstream file(filepath, std::ios::binary | std::ios::ate);
659 if (!file.is_open()) {
661 "Failed to open SPIR-V file: '{}'", filepath);
665 size_t file_size =
static_cast<size_t>(file.tellg());
666 if (file_size == 0) {
668 "SPIR-V file is empty: '{}'", filepath);
672 if (file_size %
sizeof(uint32_t) != 0) {
674 "SPIR-V file size ({} bytes) is not multiple of 4: '{}'",
675 file_size, filepath);
679 std::vector<uint32_t> buffer(file_size /
sizeof(uint32_t));
681 file.read(
reinterpret_cast<char*
>(buffer.data()), file_size);
685 "Failed to read SPIR-V file: '{}'", filepath);
694 std::ifstream file(filepath);
695 if (!file.is_open()) {
697 "Failed to open file: '{}'", filepath);
702 (std::istreambuf_iterator<char>(file)),
703 std::istreambuf_iterator<char>());
705 if (content.empty()) {
707 "File is empty: '{}'", filepath);
713#ifndef MAYAFLUX_USE_SHADERC
715 bool is_command_available(
const std::string& command)
717#if defined(MAYAFLUX_PLATFORM_WINDOWS)
718 std::string check_cmd =
"where " + command +
" >nul 2>&1";
720 std::string check_cmd =
"command -v " + command +
" >/dev/null 2>&1";
722 return std::system(check_cmd.c_str()) == 0;
725 std::string get_null_device()
727#if defined(MAYAFLUX_PLATFORM_WINDOWS)
736 const std::string& glsl_source,
737 vk::ShaderStageFlagBits stage,
738 const std::vector<std::string>& include_directories,
739 const std::unordered_map<std::string, std::string>& defines)
741 namespace fs = std::filesystem;
743 if (!is_command_available(
"glslc")) {
745 "glslc compiler not found in PATH. Install Vulkan SDK or enable MAYAFLUX_USE_SHADERC");
749 fs::path temp_dir = fs::temp_directory_path();
750 fs::path glsl_temp = temp_dir /
"mayaflux_shader_temp.glsl";
751 fs::path spirv_temp = temp_dir /
"mayaflux_shader_temp.spv";
754 std::ofstream out(glsl_temp);
755 if (!out.is_open()) {
757 "Failed to create temporary GLSL file: '{}'", glsl_temp.string());
763 std::string stage_flag;
765 case vk::ShaderStageFlagBits::eVertex: stage_flag =
"-fshader-stage=vertex";
break;
766 case vk::ShaderStageFlagBits::eFragment: stage_flag =
"-fshader-stage=fragment";
break;
767 case vk::ShaderStageFlagBits::eCompute: stage_flag =
"-fshader-stage=compute";
break;
768 case vk::ShaderStageFlagBits::eGeometry: stage_flag =
"-fshader-stage=geometry";
break;
769 case vk::ShaderStageFlagBits::eTessellationControl: stage_flag =
"-fshader-stage=tesscontrol";
break;
770 case vk::ShaderStageFlagBits::eTessellationEvaluation: stage_flag =
"-fshader-stage=tesseval";
break;
773 "Unsupported shader stage for external compilation: {}", vk::to_string(stage));
774 fs::remove(glsl_temp);
778#if defined(MAYAFLUX_PLATFORM_WINDOWS)
779 std::string cmd =
"glslc " + stage_flag +
" \"" + glsl_temp.string() +
"\" -o \"" + spirv_temp.string() +
"\"";
781 std::string cmd =
"glslc " + stage_flag +
" '" + glsl_temp.string() +
"' -o '" + spirv_temp.string() +
"'";
784 for (
const auto& dir : include_directories) {
785#if defined(MAYAFLUX_PLATFORM_WINDOWS)
786 cmd +=
" -I\"" + dir +
"\"";
788 cmd +=
" -I'" + dir +
"'";
792 for (
const auto& [name, value] : defines) {
794 if (!value.empty()) {
799 std::string null_device = get_null_device();
802 "Invoking external glslc : {}", cmd);
804 int result = std::system(cmd.c_str());
806 fs::remove(glsl_temp);
810 "External glslc compilation failed (exit code: {})", result);
812 "Make sure Vulkan SDK is installed or enable MAYAFLUX_USE_SHADERC for runtime compilation");
813 fs::remove(spirv_temp);
819 fs::remove(spirv_temp);
821 if (!spirv_code.empty()) {
823 "Compiled GLSL ({} stage) via external glslc -> {} bytes SPIR-V",
824 vk::to_string(stage), spirv_code.size() * 4);
834 case vk::ShaderStageFlagBits::eCompute:
836 case vk::ShaderStageFlagBits::eVertex:
838 case vk::ShaderStageFlagBits::eFragment:
840 case vk::ShaderStageFlagBits::eGeometry:
842 case vk::ShaderStageFlagBits::eTessellationControl:
844 case vk::ShaderStageFlagBits::eTessellationEvaluation:
848 "Unknown shader stage: {}", vk::to_string(
m_stage));
#define MF_INFO(comp, ctx,...)
#define MF_ERROR(comp, ctx,...)
#define MF_WARN(comp, ctx,...)
#define MF_DEBUG(comp, ctx,...)
vk::SpecializationInfo m_specialization_info
bool create_from_glsl_file(vk::Device device, const std::string &glsl_path, std::optional< vk::ShaderStageFlagBits > stage=std::nullopt, const std::string &entry_point="main", bool enable_reflection=true, const std::vector< std::string > &include_directories={}, const std::unordered_map< std::string, std::string > &defines={})
Create shader module from GLSL file.
bool create_from_glsl(vk::Device device, const std::string &glsl_source, vk::ShaderStageFlagBits stage, const std::string &entry_point="main", bool enable_reflection=true, const std::vector< std::string > &include_directories={}, const std::unordered_map< std::string, std::string > &defines={})
Create shader module from GLSL source string.
static std::optional< vk::ShaderStageFlagBits > detect_stage_from_extension(const std::string &filepath)
Auto-detect shader stage from file extension.
bool reflect_spirv(const std::vector< uint32_t > &spirv_code)
Perform reflection on SPIR-V bytecode.
bool create_from_spirv(vk::Device device, const std::vector< uint32_t > &spirv_code, vk::ShaderStageFlagBits stage, const std::string &entry_point="main", bool enable_reflection=true)
Create shader module from SPIR-V binary.
vk::PipelineShaderStageCreateInfo get_stage_create_info() const
Get pipeline shader stage create info.
static std::vector< uint32_t > compile_glsl_to_spirv_external(const std::string &glsl_source, vk::ShaderStageFlagBits stage, const std::vector< std::string > &include_directories={}, const std::unordered_map< std::string, std::string > &defines={})
std::vector< vk::SpecializationMapEntry > m_specialization_entries
VKShaderModule & operator=(const VKShaderModule &)=delete
vk::ShaderStageFlagBits m_stage
bool create_from_spirv_file(vk::Device device, const std::string &spirv_path, vk::ShaderStageFlagBits stage, const std::string &entry_point="main", bool enable_reflection=true)
Create shader module from SPIR-V file.
void update_specialization_info()
Update specialization info from current map Called before get_stage_create_info() to ensure fresh dat...
std::vector< uint32_t > compile_glsl_to_spirv(const std::string &glsl_source, vk::ShaderStageFlagBits stage, const std::vector< std::string > &include_directories, const std::unordered_map< std::string, std::string > &defines)
Compile GLSL to SPIR-V using shaderc.
static std::string read_text_file(const std::string &filepath)
Read text file into string.
void set_specialization_constants(const std::unordered_map< uint32_t, uint32_t > &constants)
Set specialization constants.
ShaderReflection m_reflection
static std::vector< uint32_t > read_spirv_file(const std::string &filepath)
Read binary file into vector.
static vk::Format spirv_type_to_vk_format(const spirv_cross::SPIRType &type)
Convert SPIRV-Cross type to Vulkan vertex attribute format.
std::vector< uint32_t > m_specialization_data
vk::ShaderModule m_module
std::string m_entry_point
void cleanup(vk::Device device)
Cleanup shader module.
std::unordered_map< uint32_t, uint32_t > m_specialization_map
Stage get_stage_type() const
Get shader stage type.
std::vector< uint32_t > m_spirv_code
Preserved SPIR-V (if enabled)
Wrapper for Vulkan shader module with lifecycle and reflection.
@ GraphicsBackend
Graphics/visual rendering backend (Vulkan, OpenGL)
@ Core
Core engine, backend, subsystems.
std::string name
Variable name in shader.
vk::ShaderStageFlags stage
Stage visibility.
uint32_t set
Descriptor set index.
uint32_t count
Array size (1 for non-arrays)
uint32_t binding
Binding point within set.
vk::DescriptorType type
Type (uniform buffer, storage buffer, etc.)
vk::ShaderStageFlags stage
Stage visibility.
uint32_t size
Size in bytes.
uint32_t offset
Offset in push constant block.
uint32_t constant_id
Specialization constant ID.
std::string name
Variable name in shader.
uint32_t size
Size in bytes.
std::vector< SpecializationConstant > specialization_constants
std::vector< DescriptorBinding > bindings
std::vector< PushConstantRange > push_constants
std::vector< vk::VertexInputAttributeDescription > vertex_attributes
std::optional< std::array< uint32_t, 3 > > workgroup_size
local_size_x/y/z
Metadata extracted from shader module.