gpt4 book ai didi

c++ - Phong 照明模型实际上并没有照亮任何东西

转载 作者:太空宇宙 更新时间:2023-11-04 14:19:53 26 4
gpt4 key购买 nike

我目前有一项任务是在 openGL/GLSL 中实现 Phong 光照模型。我目前正在使用的两个着色器如下。问题是,在片段着色器中,如果我不将 vColor 添加到 gl_FragColor,那么整个形状都是黑色的。但是,如果我确实添加了 vColor,那么整个形状就是完全没有光照的那种颜色。我已经尝试解决这个问题几个小时了,但没有成功。这是什么原因?是我的着色器有问题,还是 openGL 代码有问题?我正在使用一种 Material 和一个点光源,我将在着色器之后展示它们。

编辑:如果我设置 gl_FragColor = vec4(N, 1.0) 那么对象看起来像这样:

enter image description here

顶点着色器:

#version 150

in vec4 vPosition;
in vec3 vNormal;

uniform mat4 vMatrix;
uniform vec4 LightPosition;

out vec3 fNorm;
out vec3 fEye;
out vec3 fLight;

void main() {
fNorm = vNormal;
fEye = vPosition.xyz;
fLight = LightPosition.xyz;

if(LightPosition.w != 0.0) {
fLight = LightPosition.xyz - vPosition.xyz;
}

gl_Position = vMatrix * vPosition;
}

片段着色器:

#version 150

in vec3 fNorm;
in vec3 fLight;
in vec3 fEye;

uniform vec4 vColor;
uniform vec4 AmbientProduct, DiffuseProduct, SpecularProduct;
uniform mat4 vMatrix;
uniform vec4 LightPosition;
uniform float Shininess;

void main(){
vec3 N = normalize(fNorm);
vec3 E = normalize(fEye);
vec3 L = normalize(fLight);
vec3 H = normalize(L + E);

vec4 ambient = AmbientProduct;

float Kd = max(dot(L, N), 0.0);
vec4 diffuse = Kd * DiffuseProduct;

float Ks = pow(max(dot(N, H), 0.0), Shininess);
vec4 specular = Ks * SpecularProduct;
if(dot(L,N) < 0.0)
specular = vec4(0.0, 0.0, 0.0, 1.0);

gl_FragColor = vColor + ambient + diffuse + specular;
}

设置 Material 和灯光:

void init() {

setMaterials(vec4(1.0, 0.0, 0.0, 0.0), //ambient
vec4(1.0, 0.8, 0.0, 1.0), //diffuse
vec4(1.0, 1.0, 1.0, 1.0), //specular
100.0); //shine

setLightSource(vec4(1.0, 0.0, 0.0, 1.0), //ambient
vec4(1.0, 0.0, 0.0, 1.0), //diffuse
vec4(1.0, 0.0, 0.0, 1.0), //specular
vec4(1.0, 2.0, 3.0, 1.0)); //position

setProducts();

....
}

/*
* Sets the material properties for Phong lighting model.
*/
void setMaterials(vec4 amb, vec4 dif, vec4 spec, GLfloat s) {
ambient = amb;
diffuse = dif;
specular = spec;
shine = s;

glUniform1f(vShininess, shine);
}

/*
* Set light source properties.
*/
void setLightSource(vec4 amb, vec4 dif, vec4 spec, vec4 pos) {
ambient0 = amb;
diffuse0 = dif;
specular0 = spec;
light0_pos = pos;

glUniform4fv(vLightPosition, 1, light0_pos);
}

/*
* Find the products of materials components and light components.
*/
void setProducts(){
vec4 ambientProduct = ambient * ambient0;
vec4 diffuseProduct = diffuse * diffuse0;
vec4 specularProduct = specular * specular0;

glUniform4fv(vAmbientProduct, 1, ambientProduct);
glUniform4fv(vDiffuseProduct, 1, diffuseProduct);
glUniform4fv(vSpecularProduct, 1, specularProduct);

}

最佳答案

您的最终光照组合看起来不正确:

gl_FragColor = vColor + ambient + diffuse + specular;

应该是这样的

gl_FragColor = vColor * (ambient + diffuse) + specular;

即由物体反照率调制的光照。

关于c++ - Phong 照明模型实际上并没有照亮任何东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8411227/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com