使用emscripten和OpenGL着色器

4
我遇到了一些问题,无法让emscripten与openGL着色器一起工作。该项目在使用emscripten和gcc编译时都能够成功,但在尝试运行emscripten输出时失败了。
从编译顶点着色器时我得到的错误信息如下:
ERROR: 0:1: 'core' : invalid version directive 
ERROR: 0:3: 'layout' : syntax error 

编译片元着色器时出现的错误:
ERROR: 0:1: 'core' : invalid version directive 
ERROR: 0:3: 'in' : storage qualifier supported in GLSL ES 3.00 only  
ERROR: 0:3: '' : No precision specified for (float) 
ERROR: 0:5: 'out' : storage qualifier supported in GLSL ES 3.00 only   
ERROR: 0:5: '' : No precision specified for (float) 

我正在使用以下命令编译该项目:

em++ src/*.cpp -Iinclude/ -o test.html -std=c++11 -s USE_GLFW=3 -s FULL_ES3=1

顶点着色器源代码:

#version 330 core

layout (location = 0) in vec3 position; 
layout (location = 1) in vec3 in_color;

uniform mat4 model; 
uniform mat4 projection;

out vec3 out_color;

void main()
{
    gl_Position = projection * model * vec4(position, 1.0f);
    out_color = in_color;
}

片段着色器源代码:

#version 330 core

in vec3 out_color;

out vec4 color;

void main()
{
      color = vec4(out_color, 1.0);
}

着色器以char数组的形式从xxd -i生成的输出中加载。我在Linux上使用c++11开发。当我在本地运行程序时,它运行得非常好。我已经尝试在Firefox和Chromium中运行emscripten输出,但好像存在版本冲突问题。
是否有方法使emscripten能够与我当前的环境兼容?或者我必须用不同的方式编写我的着色器?如果我需要重写我的着色器,应该如何编写?

尝试从#version中删除core;反正它默认就是这样的。 - Colonel Thirty Two
我移除了core,这样就消除了关于core的错误,但是其余的错误仍然存在。 - jmoggr
2个回答

7
着色器代码必须是WebGL着色器代码,才能在浏览器上运行。我认为emscripten不会将着色器代码(在这种情况下为GLSL 3.3)转换为与webGL兼容的GLSL ES 1.0代码。
您需要在顶点着色器中使用attribute而不是in,在顶点/片段着色器中使用varying进行输出/输入,并将gl_FragColor用作片段着色器的输出变量。此外,layout也不被支持,变量需要精度定义。请查看WebGL速查表here

1
在当前的 Emscripten 中,您可以使用 WebGL2 和 GLSL ES 3.00。您需要将您的 #version 行更改为:
#version 300 es

你还需要在片元着色器中添加默认精度。
如果是我,我会将我的代码包装到glShaderSource中,像这样。
GLint shaderSourceWrapper(GLint shader, const std::string src) {
  #ifdef __EMSCRIPTEN__
    // replace '#version.*' with '#version 300 es' 
    // if it's a fragment shader add 'precision highp float'
    // do anything else relevant like warn if there are
    // unsupported #extension directives
  #endif
  glShaderSource(shader, ... )

甚至可以在JavaScript级别进行此操作,就像这样


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接