在 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 位置参数语法。但您可以找到适合这项工作的任何其他格式化库。