QT OpenGL shader基础光照

用cube那个工程 自己去把顶点补充一个QVector3D的顶点法向量 然后把需要传入的uniform补上

摄像机位置 灯颜色 灯位置 model矩阵 MVP矩阵

VERT


#ifdef GL_ES
// Set default precision to medium
precision mediump int;
precision mediump float;
#endif


uniform mat4 mvp_matrix;
uniform mat4 model;
uniform mat3 transpose_inverse_model;//出问题了。这个可以不要


attribute vec4 a_position;//顶点位置信息
attribute vec2 a_texcoord;//纹理
attribute vec3 a_normal;//法向量


varying vec2 v_texcoord;//传给frag
varying vec3 fragPos;//片段位置*model再传给fragment
varying vec3 normal;//法线矩阵处理过后的法线




void main()
{
    // Calculate vertex position in screen space
    gl_Position = mvp_matrix * a_position;


    fragPos=vec3(model*a_position);
    normal=mat3(transpose(inverse(model)))*a_normal;//model的逆矩阵的转置的左上角3x3矩阵
   
    v_texcoord = a_texcoord;
}










FRAG
#ifdef GL_ES
// Set default precision to medium
precision mediump int;
precision mediump float;
#endif


uniform sampler2D texture;
uniform vec3 viewPos;
uniform vec3 lightPos;
uniform vec3 lightColor;






varying vec2 v_texcoord;
varying vec3 fragPos;
varying vec3 normal;


//! [0]
void main()
{
    vec4 ans;
    float ambientStrength=0.1;//环境光因子
    vec3 ambient = ambientStrength * lightColor;//环境光


    // diffuse
    vec3 norm = normalize(normal);
    vec3 lightDir = normalize(lightPos - fragPos);
    float diff = max(dot(norm, lightDir), 0.0);
    vec3 diffuse = diff * lightColor;//漫反射


    // specular
    float specularStrength = 0.5;
    vec3 viewDir = normalize(viewPos - fragPos);
    vec3 reflectDir = reflect(-lightDir, norm);
    float spec = pow(max(dot(viewDir, reflectDir), 0.0), 32);//反射向量
    vec3 specular = specularStrength * spec * lightColor;


    vec3 result = (ambient + diffuse + specular) *texture2D(texture, v_texcoord).rgb;


    
    gl_FragColor = vec4(result,1.0);
}
//! [0]


猜你喜欢

转载自blog.csdn.net/qq_35158695/article/details/80244821