那么HeightMap是怎么转化成NormalMap的呢? 其实并不难,在《3D游戏与计算机图形学方法》中,提供了一种由
高度图生成法向图的方法。其思想是根据高度图中的象素与其周围象素的高度差,在切空间构造S
向量和T向量,由SXT得到法线向量。设H(i,j)表示在height map上(i,j)象素点的高度值,则在切线空间S和T
方向的切向量可以表示成:S(i,j) = (1,0,H(i+1,j) - H(i-1,j) ) T(i,j) = (0,1,H(i,j+1) - H(i,j-1) ) Normal(i,j) = S(i,j) X T(i,j) H(i+1,j) – H(i-1,j)为沿S方向的高度差,也就是S方向的坡度,H(i,j+1) - H(i,j-1)为沿T方向的高度差,也就是T方向的坡度。VS_OUTPUT main(float4 Pos: POSITION){ VS_OUTPUT Out// Clean up inaccuracies Pos.xy = sign(Pos.xy)Out.Pos = float4(Pos.xy, 0, 1)// Image-space Out.texCoord.x = 0.5 * (1 + Pos.x)Out.texCoord.y = 0.5 * (1 - Pos.y)return Out} float4 main(float2 texCoord: TEXCOORD) : COLOR { float2 off = 1.0 / HeightMapSizefloat Scale = 1// Sample teh neighbor float s0 = tex2D(Heightmap, texCoord + float2(-off.x,0)).rfloat s1 = tex2D(Heightmap, texCoord + float2( off.x,0)).rfloat s2 = tex2D(Heightmap, texCoord + float2( 0,-off.y)).rfloat s3 = tex2D(Heightmap, texCoord + float2(0,off.y)).rfloat3 U = float3(1,0,s1 - s0)float3 V = float3(0,1,s3 - s2)float3 normal = normalize(Scale * cross(U,V))// Pack [-1, 1] into [0, 1] return float4(normal * 0.5 + 0.5,1)}void LoadRawFile(string name, int size)
{
FileStream fs = new FileStream(name, FileMode.Open, FileAccess.Read, FileShare.Read)
BinaryReader r = new BinaryReader(fs)
heightMap = r.ReadBytes(size)
r.Close()
fs.Dispose()
}
LoadRawFile( "Terrain.raw", MAP_SIZE * MAP_SIZE)读取
灰度信息在 heightMap里
评论列表(0条)