文章目录
- QT+OpenGL反射与折射
- 反射
- 折射
QT+OpenGL反射与折射
本篇完整工程见gitee:QtOpenGL 对应点的tag,由turbolove提供技术支持,您可以关注博主或者私信博主
反射
反射这个属性表现为物体(或者物体的一部分)反射它周围的环境,即根据观察者的视角,物体的颜色或多或少等于他的环境。
最终的反射向量将会作为索引/采样立方体贴图的方向向量,返回颜色的值。
关键代码:
shader.vert
#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aNormal;
layout (location = 2) in vec2 aTexCoords;out vec3 Normal;
out vec3 FragPos;
out vec2 TexCoords;uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
void main() {TexCoords=aTexCoords;Normal = mat3(transpose(inverse(model))) * aNormal;FragPos=vec3(model * vec4(aPos,1.0));gl_Position = projection * view * model * vec4(aPos, 1.0);
}
shader.frag
#version 330 corestruct Material {sampler2D texture_diffuse1;sampler2D texture_specular1;float shininess;
};struct Light {vec3 direction;vec3 ambient;vec3 diffuse;vec3 specular;
};
uniform Light light;uniform Material material;
out vec4 FragColor;in vec2 TexCoords;
in vec3 Normal;
in vec3 FragPos;uniform vec3 viewPos;void main() {vec3 diffuseTexColor=vec3(texture(material.texture_diffuse1,TexCoords));vec3 specularTexColor=vec3(texture(material.texture_specular1,TexCoords));// ambientvec3 ambient = diffuseTexColor*light.ambient;// diffusevec3 norm = normalize(Normal);vec3 lightDir = normalize(-light.direction);float diff = max(dot(norm, lightDir), 0.0);vec3 diffuse = diff *diffuseTexColor*light.diffuse;// specularvec3 viewDir = normalize(viewPos - FragPos);vec3 reflectDir = reflect(-lightDir, norm);float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);vec3 specular = spec*specularTexColor*light.specular;vec3 result = (ambient + diffuse + specular);FragColor = vec4(result, 1.0);
}
reflection.vert
#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aNormal;
out vec3 Normal;
out vec3 Position;
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
void main() {Normal = mat3(transpose(inverse(model))) * aNormal;Position = vec3(model * vec4(aPos, 1.0));gl_Position = projection * view * vec4(Position, 1.0);
}
reflection.frag
#version 330 core
out vec4 FragColor;
in vec3 Normal;
in vec3 Position;
uniform vec3 viewPos;
uniform samplerCube skybox;
void main() {vec3 I = normalize(Position - viewPos);vec3 R = reflect(I, normalize(Normal));FragColor = vec4(texture(skybox, R).rgb, 1.0);
}
折射
折射是光线由于传播介质的改变而产生的方向变化。折射是通过斯涅尔定律来描述的。
折射可以使用GLSL的内建refract函数来轻松实现,他需要一个法向量、一个观察方向和两个材质之间的折射率。
这里使用反射的shader。
主要代码:
reflection.frag
void main()
{float ratio = 1.00/1.52;vec3 I = normalize(Position - cameraPos);vec3 R = refract(I, normalize(Normal), ratio);FragColor = vec4(texture(skybox, R).rgb, 1.0);
}