c++ - 如何在 C++ 项目中编写着色器源代码?

标签 c++ opengl

<分区>

在 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++ - 如何在 C++ 项目中编写着色器源代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52357334/

相关文章:

带有自动工具的 CDT 中的 C++11

c++ - 我应该如何将 C 库包装到 C++ 中

java - glBufferData ARB 还是 glBufferSubData ARB?

c++ - glShaderSource() 上的段错误

c++ - 使用多个 QGLWidgets (QT) 来显示(相同的)3D 纹理?

2个矩阵的C++乘法

c++ - 为什么虚拟分配的行为与相同签名的其他虚拟功能不同?

android - 是否有可能在 Android Studio 中构建一个带有 .so 作为输出的 native 模块

c++ - SDL 无法通过 2.1 Mac OSX Yosemite 加载 OpenGL 上下文

c++ - OpenGL 只显示在方法中加载的纹理?