【问题标题】:Per fragment lighting on heightmap and generating normals高度图上的每个片段照明并生成法线
【发布时间】:2014-05-08 06:39:26
【问题描述】:

我正在尝试在高度图上实现每帧照明。我将高度图作为纹理上传到着色器,并根据各自的像素调整顶点高度。为了生成法线,我取四个相邻像素的值,制作它们的向量并计算叉积,如下所示:

vec3 offset = vec3(-1.0/mapSize, 0, 1.0/mapSize);
float s1 = texture2D(sampler, texCoord + offset.xy).x;
float s2 = texture2D(sampler, texCoord + offset.zy).x;
float s3 = texture2D(sampler, texCoord + offset.yx).x;
float s4 = texture2D(sampler, texCoord + offset.yz).x;
vec3 va = normalize(vec3(1.0, 0.0, s2 - s1));
vec3 vb = normalize(vec3(0.0, 1.0, s3 - s4));
vec3 n = normalize(cross(va, vb));

这是我的照明功能

vec4 directional(Light light){
    vec4 ret = vec4(0.0);
    vec3 lPos = (V * vec4(light.position, 0.0)).xyz;
    vec3 normal = normalize(vNormal);
    vec3 lightDir = normalize(lPos);
    vec3 reflectDir = reflect(-lightDir, normal);    
    vec3 viewDir = normalize(-vPosition);

    float lambertTerm = max(dot(lightDir, normal), 0.0);
    float specular = 0.0;

    if(lambertTerm > 0.0){
        float specAngle = max(dot(reflectDir, viewDir), 0.0);
        specular = pow(specAngle, material.shininess);
    }
    ret = vec4(light.ambient * material.ambient + light.diffuse * material.diffuse * lambertTerm + light.specular * material.specular * specular, 1.0);
    return ret;
} 

这有点工作。只有 y 和 z 轴似乎被翻转了。如果我沿着 y 轴移动灯光,它看起来就像沿着 z 轴移动,反之亦然。

我还应该指出,该函数在常规 3D 模型上完美运行,所以我认为问题在于法线的生成。

【问题讨论】:

  • 顺便说一下,您不需要对 va 和 vb 进行归一化 - 无论它们的大小如何,它们的叉积仍将指向同一方向。

标签: graphics opengl-es glsl webgl shader


【解决方案1】:

如果您使用的是 y-up 坐标系,那么您希望在 y 分量而不是 z 分量上进行增量。

vec3 va = normalize(vec3(1.0, s2 - s1, 0.0));
vec3 vb = normalize(vec3(0.0, s4 - s3, 0.0));

还要确认是s3 - s4还是s4 - s3。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-25
    • 1970-01-01
    • 2010-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-24
    相关资源
    最近更新 更多