OpenGL - 如何计算地形高度网格中的法线? [英] OpenGL - How to calculate normals in a terrain height grid?
问题描述
切线向量由跨越两个最近段中点的线给出,如下所示图片。
我想知道是否有更直接的计算,或者说CPU周期更便宜。
其实它足够快,我用它来计算顶点着色器中的法线。
/ /#P.xy存储我们想要计算法线的位置
//#height()这里是一个函数,它返回地形中某点的高度
//阅读neightbor高度使用任意小o ffset
vec3 off = vec3(1.0,1.0,0.0);
float hL = height(P.xy - off.xz);
float hR = height(P.xy + off.xz);
float hD = height(P.xy - off.zy);
float hU = height(P.xy + off.zy);
//推断地形正常
N.x = hL - hR;
N.y = hD - hU;
N.z = 2.0;
N = normalize(N);
My approach is to calculate two tangent vectors parallel to axis X and Y respectively. Then calculate the cross product to find the normal vector.
The tangent vector is given by the line that crosses the middle point on the two nearest segments as is shown in the following picture.
I was wondering whether there is a more direct calculation, or less expensive in terms of CPU cycles.
You can actually calculate it without a cross product, by using the "finite difference method" (or at least I think it is called in this way).
Actually it is fast enough that I use it to calculate the normals on the fly in a vertex shader.
// # P.xy store the position for which we want to calculate the normals
// # height() here is a function that return the height at a point in the terrain
// read neightbor heights using an arbitrary small offset
vec3 off = vec3(1.0, 1.0, 0.0);
float hL = height(P.xy - off.xz);
float hR = height(P.xy + off.xz);
float hD = height(P.xy - off.zy);
float hU = height(P.xy + off.zy);
// deduce terrain normal
N.x = hL - hR;
N.y = hD - hU;
N.z = 2.0;
N = normalize(N);
这篇关于OpenGL - 如何计算地形高度网格中的法线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!