Frank Luna Page 1 6/22/2006
Introduction to 3D Game Programming
with DirectX 9.0c: A Shader Approach
FAQ
1. The terrain code takes a long time to load for heightmaps 513 513
×
and higher.
How can I speed it up?
The D3DXComputeNormals function is what takes the most time. The
D3DXComputeNormals is quite generic and needs to find which triangles
share a vertex for the normal averaging. But our terrain topology has a definite
structure, and we can compute the normals much faster ourselves by applying a
simple finite difference scheme. Replacing D3DXComputeNormals with the
code below should shave off several seconds for 513 513
×
sized heightmaps and
below, but it might not be enough for larger heightmaps like 1025 1025× and
above. In these cases, you may want to precompute the normals and store than on
disk so they just need to be read and load time, not calculated.
We approximate the partial derivatives using central difference:
()
()
(
)
(
)
(
)
()
()()
()()
11
11
,,,,
,
22
,,
,,
,
22
ji ji ji ji
ji
ji ji
ji ji
ji
h x xz h x xz h x z h x z
h
xz
xx x
hx z z hx z z
hx z hx z
h
xz
zz z
+−
−+
+∆ − −∆ −
∂
==
∂∆ ∆
−+∆−−∆
−
∂
==
∂∆ ∆
.
(Recall that based on our grid layout, as
i increases,
i
z decreases (i.e., it moves
along negative
z-axis), hence the 1
−
factor in hz
∂
∂ since we want the partial
derivative in the positive
z-axis direction.)
Now, the two tangent vectors at the point
(
)
(
)
,,,
jjii
x
hx z z are given by:
()
()
1, , , 0
0, , , 1
xji
zji
h
Txz
x
h
Txz
z
∂
=
∂
∂
=
∂
G
G
.
And the normal at this point is thus:
zx
zx
TT
n
TT
×
=
×
GG
G
GG
.