1. 程式人生 > >QT OpenGL shader基礎光照

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]