如何在C++项目中组合着色器源?

How do you compose your shader source in a C++ project?

本文关键字:组合 C++ 项目      更新时间:2023-10-16

在Javascript中使用WebGL,我可以像这样编写一个片段着色器:

protected getShader(textureFunc: string, opline: string): string {
return `
float getTexel() {
return getColorAsFloat(${textureFunc}(A, TexCoords));
}
void main() {
setFragColor(${opline});
}
`;
}

在这里,我使用一堆直接粘贴在代码中的动态参数构建我的源代码。如何在C++项目中做到这一点?我正在寻找构建动态字符串而不是sprintf()std::cout <<的新方法。OpenGL程序员是否使用库或技术来促进这种组合?

C++在语言中缺少字符串插值功能。类似的C++代码是:

std::string getShader(const std::string &textureFunc, const std::string &opline) const {
return R"(
float getTexel() {
return getColorAsFloat()" + textureFunc + R"((A, TexCoords));
}
void main() {
setFragColor()" + opline + R"();
}
)";
}

或者,您可以使用一些类似snprintf格式库:

std::string getShader(const char *textureFunc, const char *opline) const {
return Sn::sprintf(R"(
float getTexel() {
return getColorAsFloat(%1$s(A, TexCoords));
}
void main() {
setFragColor(%2$s);
}
)", textureFunc, opline);
}

这里我使用我自己的printf包装器,它返回一个std::string,带有POSIX位置参数语法。但是您可以找到适合该工作的任何其他格式库。

C++,核心语言,因此对着色器一无所知。您几乎总是会使用库。各种可用的库不同。

我在做着色器时使用的库是SFML,它有一个方便的sf::Shader类。其他库将有其他类。或者原始OpenGL将采用原始字符串作为着色器源(通常通过库访问(。