我在尝试在运行时将我的glsl着色器编译为spirv时遇到此错误。在这一点上,我很沮丧,我不知道是什么原因导致了错误,也无法在线找到任何内容。
该错误仅发生在我的顶点着色器中,我的片段着色器编译时没有问题(尽管它们都可以“编译”,但是在创建不使用shaderc编译的vulkan模块时会发生错误)。另外,当我从命令行编译并仅读取那些已经编译的文件时,着色器模块的创建就没有问题。
这是我的顶点着色器:
# version 450
# extension GL_ARB_separate_shader_objects : enable
layout(location = 0) in vec2 aPos;
layout(location = 1) in vec3 aColor;
layout(location = 0) out vec3 fragColor;
void main()
{
gl_Position = vec4(aPos, 1.0, 1.0);
fragColor = aColor;
}
这是我用来读取和编译.vert文件的代码
std::vector<char> readFile(const std::string& filename)
{
std::ifstream file(filename, std::ios::ate | std::ios::binary);
if (!file.is_open())
{
throw std::runtime_error("failed to open file!");
}
size_t fileSize = (size_t) file.tellg();
std::vector<char> buffer(fileSize);
file.seekg(0);
file.read(buffer.data(), fileSize);
file.close();
return buffer;
}
std::vector<uint32_t> compileToSPIRV(const char* sPath, const shaderc_shader_kind kind)
{
auto shaderVect = readFile(sPath);
std::string shaderText(shaderVect.begin(), shaderVect.end());
shaderc::Compiler compiler;
shaderc::CompileOptions options;
options.AddMacroDefinition("MY_DEFINE", "1");
options.SetOptimizationLevel(shaderc_optimization_level_size);
auto assembly = compiler.CompileGlslToSpvAssembly(shaderText, kind, sPath, options);
std::string ass(assembly.cbegin(), assembly.cend());
auto compile = compiler.AssembleToSpv(ass.c_str(), ass.size());
std::vector<uint32_t> comp(compile.cbegin(), compile.cend());
return comp;
}
感谢您的帮助。如果您要包含其他代码,请告诉我。
编辑:创建着色器模块:
VkShaderModule createShaderModule(const std::vector<uint32_t>& code)
{
VkShaderModuleCreateInfo moduleInfo = {};
moduleInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
moduleInfo.codeSize = code.size();
moduleInfo.pCode = code.data();
VkShaderModule shaderModule;
if (vkCreateShaderModule(device, &moduleInfo, nullptr, &shaderModule) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create shader module");
}
return shaderModule;
}
VkShaderModuleCreateInfo::codeSize
的大小以字节为单位,而不是uint32_t
s。因此应该是4*code.size()
。