如何将变量从顶点着色器移动到几何着色器?

How do you move variables from Vertex shader to Geometry shader?

我有以下顶点着色器:

#version 330

layout (location = 0) in ivec4 inOHLC;
layout (location = 1) in int inVolume;
layout (location = 2) in int inTimestamp;

out ivec4 outOHLC;
out int outVolume;
out int outTimestamp;

void main()
{
    outOHLC = inOHLC;
    outVolume= inVolume;
    outTimestamp = inTimestamp;
}

我想在几何着色器中接收 outOHLCoutVolumeoutTimestamp。我这样编码:

#version 330

in ivec4 inOHLC;
in int inVolume;
in int inTimestamp;

layout (line_strip, max_vertices = 2) out;

void main() {  

    float x = (float)inTimestamp / 100.0;
    float y1 = (float)inOHLC[1] / 100.0;
    float y2 = (float)inOHLC[1] / 100.0;
    gl_Position = vec4(x, y1, 0.0, 0.0);
    EmitVertex();    
    gl_Position = vec4(x, y2, 0.0, 0.0);
    EmitVertex();    
    EndPrimitive();

}  

但我收到以下错误:

run:
. . . vertex compilation success.
. . . geometry compilation failed.
Shader Info Log: 
ERROR: 7:1: 'inOHLC' : geometry shader input varying variable must be declared as an array
ERROR: 8:1: 'inVolume' : geometry shader input varying variable must be declared as an array
ERROR: 9:1: 'inTimestamp' : geometry shader input varying variable must be declared as an array
ERROR: 15:1: ')' : syntax error syntax error

根据@Rabbid76的评论,我修改了代码如下:

#version 330

in ivec4 ohlc[];
in int volume[];
in int timestamp[];

layout (line_strip, max_vertices = 2) out;

void main()
{

    float x = (float)timestamp / 100.0;
    float y1 = (float)ohlc[1] / 100.0;
    float y2 = (float)ohlc[2] / 100.0;
    gl_Position = vec4(x, y1, 0.0, 0.0);
    EmitVertex();    
    gl_Position = vec4(x, y2, 0.0, 0.0);
    EmitVertex();    
    EndPrimitive();

} 

现在我只得到一个错误:

run:
. . . vertex compilation success.
. . . geometry compilation failed.
Shader Info Log: 
ERROR: 40:1: ')' : syntax error syntax error

我猜这与 (float) 强制转换(甚至在 GLSL 中是否存在?)或浮点变量定义有关。

仔细阅读留言:

geometry shader input varying variable must be declared as an array

Geometry shader 的输入是原语。这意味着构成图元的顶点着色器的所有输出都已组合。因此几何着色器的输入是数组:

in ivec4 inOHLC[];
in int inVolume[];
in int inTimestamp[];

此外,您必须为几何着色器指定 input primitive type。例如一行:

layout(lines​) in;

基元类型lines意味着几何着色器接收2个顶点(输入的数组大小为2)。


GLSL没有像C那样的强制转换运算符,如果你想把一个int转换成float,那么你必须构造一个新的float。重载的 float 构造函数接受一个 int 参数:

float y1 = (float)ohlc[1] / 100.0;

float y1 = float(ohlc[1]) / 100.0;

索引从 0 开始而不是 1(如 C、C++、C#、Java、JavaScript、Python、...):

float y1 = float(ohlc[0]) / 100.0;
float y2 = float(ohlc[1]) / 100.0;