【OpenGL】GLSL中的函数和子程序(subroutines)

本文介绍了GLSL中如何使用函数和子程序(subroutines)。GLSL函数支持常量(const)标识符、函数重载及传递数组或结构体。子程序允许根据变量值选择不同函数调用,类似于C++的函数指针,可提高性能,避免条件判断或shader更换。文中还给出了使用子程序的示例代码。
摘要由CSDN通过智能技术生成

这篇文章里讲一下在GLSL如何使用函数和子程序(subroutines)。


在GLSL中使用函数

GLSL支持函数,它们的语法结构和C很相似。但是调用约定会有所不同。下面,我们以一个普通的ADS(ambient,diffuse,specular)shader为例,熟悉一下GLSL中函数的用法。

Vertex Shader:

#version 400
layout (location = 0)in vec3 VertexPosition;
layout (location = 1)in vec3 VertexNormal;
out vec3LightIntensity;
struct LightInfo {
    vec4 Position; // Light position in eyecoords.
    vec3 La; // Ambient light intensity
    vec3 Ld; // Diffuse light intensity
    vec3 Ls; // Specular light intensity
};
uniform LightInfoLight;
struct MaterialInfo {
    vec3 Ka; // Ambient reflectivity
    vec3 Kd; // Diffuse reflectivity
    vec3 Ks; // Specular reflectivity
    float Shininess; // Specular shininessfactor
};
uniform MaterialInfoMaterial;
uniform mat4ModelViewMatrix;
uniform mat3NormalMatrix;
uniform mat4ProjectionMatrix;
uniform mat4 MVP;
void getEyeSpace( outvec3 norm, out vec4 position )
{
    norm = normalize( NormalMatrix *VertexNormal);
    position = ModelViewMatrix *vec4(VertexPosition,1.0);
}
vec3 phongModel( vec4position, vec3 norm )
{
    vec3 s = normalize(vec3(Light.Position -position));
    vec3 v = normalize(-position.xyz);
    vec3 r = reflect( -s, norm );
    vec3 ambient = Light.La * Material.Ka;
    float sDotN = max( dot(s,norm), 0.0 );
    vec3 diffuse = Light.Ld * Material.Kd *sDotN;
    vec3 spec = vec3(0.0);
    if( sDotN > 0.0 )
        spec = Light.Ls * Material.Ks *
            pow( max( dot(r,v), 0.0 ),Material.Shininess );
    return ambient + diffuse + spec;
}
void main()
{
    vec3 eyeNorm;
    vec4 eyePosition;
    // Get the position and normal in eye space
    getEyeSpace(eyeNorm, eyePosition);
    // Evaluate the lighting equation.
    LightIntensity = phongModel( eyePosition,eyeNorm );
    gl_Position = MVP * vec4(VertexPosition,1.0);
}


上面的shader略微有点长……没事,我们一点一点来看。

layout (location = 0)in vec3 VertexPosition;
layout (location = 1)in vec3 VertexNormal;
out vec3LightIntensity;
struct LightInfo {
    vec4 Position; // Light position in eyecoords.
    vec3 La; // Ambient light intensity
    vec3 Ld; // Diffuse light intensity
    vec3 Ls; // Specular light intensity
};
uniform LightInfoLight;
struct MaterialInfo {
    vec3 Ka; // Ambient reflectivity
    vec3 Kd; // Diffuse reflectivi
  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值