-
Notifications
You must be signed in to change notification settings - Fork 1
/
Terrain.cpp
504 lines (397 loc) · 12.1 KB
/
Terrain.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
#include "terrain.h"
Terrain::Terrain(
std::string heightmapFileName,
int numVertsPerRow,
int numVertsPerCol,
int cellSpacing,
float heightScale)
{
_numVertsPerRow = numVertsPerRow;
_numVertsPerCol = numVertsPerCol;
_cellSpacing = cellSpacing;
_numCellsPerRow = _numVertsPerRow - 1;
_numCellsPerCol = _numVertsPerCol - 1;
_width = _numCellsPerRow * _cellSpacing;
_depth = _numCellsPerCol * _cellSpacing;
_numVertices = _numVertsPerRow * _numVertsPerCol;
_numTriangles = _numCellsPerRow * _numCellsPerCol * 2;
_heightScale = heightScale;
// load heightmap
if (!readRawFile(heightmapFileName))
{
::MessageBox(0, "readRawFile - FAILED", 0, 0);
::PostQuitMessage(0);
}
// scale heights
for (int i = (int)_heightmap.size() - 1; i >= 0; i--)
_heightmap[i] = (int)(_heightmap[i] * heightScale);
// compute the vertices
if (!computeVertices())
{
::MessageBox(0, "computeVertices - FAILED", 0, 0);
::PostQuitMessage(0);
}
// compute the indices
if (!computeIndices())
{
::MessageBox(0, "computeIndices - FAILED", 0, 0);
::PostQuitMessage(0);
}
}
Terrain::~Terrain()
{
D3D::Release<IDirect3DVertexBuffer9*>(_vb);
D3D::Release<IDirect3DIndexBuffer9*>(_ib);
D3D::Release<IDirect3DTexture9*>(_tex);
}
int Terrain::getHeightmapEntry(int row, int col)
{
unsigned int index = row * _numVertsPerRow + col;
if (index >= 0 && index < _heightmap.size()) {
return _heightmap[index];
}
else {
return 0;
}
}
void Terrain::setHeightmapEntry(int row, int col, int value)
{
_heightmap[row * _numVertsPerRow + col] = value;
}
bool Terrain::computeVertices()
{
HRESULT hr = 0;
// IDirect3DDevice9* Device = graphics.GetDevice();
hr = Device->CreateVertexBuffer(
_numVertices * sizeof(D3D::EVertex),
D3DUSAGE_WRITEONLY,
D3D::EVertex::FVF,
D3DPOOL_MANAGED,
&_vb,
0);
if (FAILED(hr))
return false;
// coordinates to start generating vertices at
int startX = -_width / 2;
int startZ = _depth / 2;
// coordinates to end generating vertices at
int endX = _width / 2;
int endZ = -_depth / 2;
// compute the increment size of the texture coordinates
// from one vertex to the next.
float uCoordIncrementSize = 1.0f / (float)_numCellsPerRow;
float vCoordIncrementSize = 1.0f / (float)_numCellsPerCol;
D3D::EVertex* v = 0;
_vb->Lock(0, 0, (void**)&v, 0);
int i = 0;
for (int z = startZ; z >= endZ; z -= _cellSpacing)
{
int j = 0;
for (int x = startX; x <= endX; x += _cellSpacing)
{
// compute the correct index into the vertex buffer and heightmap
// based on where we are in the nested loop.
int index = i * _numVertsPerRow + j;
v[index] = D3D::EVertex(
(float)x,
(float)_heightmap[index],
(float)z,
(float)j * uCoordIncrementSize,
(float)i * vCoordIncrementSize);
j++; // next column
}
i++; // next row
}
_vb->Unlock();
return true;
}
bool Terrain::computeIndices()
{
HRESULT hr = 0;
// IDirect3DDevice9* Device = graphics.GetDevice();
hr = Device->CreateIndexBuffer(
_numTriangles * 3 * sizeof(DWORD), // 3 indices per triangle
D3DUSAGE_WRITEONLY,
D3DFMT_INDEX32,
D3DPOOL_MANAGED,
&_ib,
0);
if (FAILED(hr))
return false;
DWORD* indices = 0;
_ib->Lock(0, 0, (void**)&indices, 0);
// index to start of a group of 6 indices that describe the
// two triangles that make up a quad
int baseIndex = 0;
// loop through and compute the triangles of each quad
for (int i = 0; i < _numCellsPerCol; i++)
{
for (int j = 0; j < _numCellsPerRow; j++)
{
indices[baseIndex] = i * _numVertsPerRow + j;
indices[baseIndex + 1] = i * _numVertsPerRow + j + 1;
indices[baseIndex + 2] = (i + 1) * _numVertsPerRow + j;
indices[baseIndex + 3] = (i + 1) * _numVertsPerRow + j;
indices[baseIndex + 4] = i * _numVertsPerRow + j + 1;
indices[baseIndex + 5] = (i + 1) * _numVertsPerRow + j + 1;
// next quad
baseIndex += 6;
}
}
_ib->Unlock();
return true;
}
bool Terrain::loadTexture(std::string fileName)
{
HRESULT hr = 0;
// IDirect3DDevice9* Device = graphics.GetDevice();
hr = D3DXCreateTextureFromFile(
Device,
fileName.c_str(),
&_tex);
if (FAILED(hr))
return false;
return true;
}
bool Terrain::genTexture(D3DXVECTOR3* directionToLight)
{
// Method fills the top surface of a texture procedurally. Then
// lights the top surface. Finally, it fills the other mipmap
// surfaces based on the top surface data using D3DXFilterTexture.
HRESULT hr = 0;
// texel for each quad cell
int texWidth = _numCellsPerRow;
int texHeight = _numCellsPerCol;
// IDirect3DDevice9* Device = graphics.GetDevice();
// create an empty texture
hr = D3DXCreateTexture(
Device,
texWidth, texHeight,
0, // create a complete mipmap chain
0, // usage
D3DFMT_X8R8G8B8,// 32 bit XRGB format
D3DPOOL_MANAGED, &_tex);
if (FAILED(hr))
return false;
D3DSURFACE_DESC textureDesc;
_tex->GetLevelDesc(0 /*level*/, &textureDesc);
// make sure we got the requested format because our code
// that fills the texture is hard coded to a 32 bit pixel depth.
if (textureDesc.Format != D3DFMT_X8R8G8B8)
return false;
D3DLOCKED_RECT lockedRect;
_tex->LockRect(0/*lock top surface*/, &lockedRect,
0 /* lock entire tex*/, 0/*flags*/);
DWORD* imageData = (DWORD*)lockedRect.pBits;
for (int i = 0; i < texHeight; i++)
{
for (int j = 0; j < texWidth; j++)
{
D3DXCOLOR c;
// get height of upper left vertex of quad.
float height = (float)getHeightmapEntry(i, j) / _heightScale;
if ((height) < 42.5f) c = D3D::RED;
else if ((height) < 85.0f) c = D3D::YELLOW;
else if ((height) < 127.5f) c = D3D::GREEN;
else if ((height) < 170.0f) c = D3D::GREEN;
else if ((height) < 212.5f) c = D3D::BLACK;
else c = D3D::WHITE;
// fill locked data, note we divide the pitch by four because the
// pitch is given in bytes and there are 4 bytes per DWORD.
imageData[i * lockedRect.Pitch / 4 + j] = (D3DCOLOR)c;
}
}
_tex->UnlockRect(0);
if (!lightTerrain(directionToLight))
{
::MessageBox(0, "lightTerrain() - FAILED", 0, 0);
return false;
}
hr = D3DXFilterTexture(
_tex,
0, // default palette
0, // use top level as source level
D3DX_DEFAULT); // default filter
if (FAILED(hr))
{
::MessageBox(0, "D3DXFilterTexture() - FAILED", 0, 0);
return false;
}
return true;
}
bool Terrain::lightTerrain(D3DXVECTOR3* directionToLight)
{
HRESULT hr = 0;
D3DSURFACE_DESC textureDesc;
_tex->GetLevelDesc(0 /*level*/, &textureDesc);
// make sure we got the requested format because our code that fills the
// texture is hard coded to a 32 bit pixel depth.
if (textureDesc.Format != D3DFMT_X8R8G8B8)
return false;
D3DLOCKED_RECT lockedRect;
_tex->LockRect(
0, // lock top surface level in mipmap chain
&lockedRect,// pointer to receive locked data
0, // lock entire texture image
0); // no lock flags specified
DWORD* imageData = (DWORD*)lockedRect.pBits;
for (unsigned int i = 0; i < textureDesc.Height; i++)
{
for (unsigned int j = 0; j < textureDesc.Width; j++)
{
// index into texture, note we use the pitch and divide by
// four since the pitch is given in bytes and there are
// 4 bytes per DWORD.
int index = i * lockedRect.Pitch / 4 + j;
// get current color of quad
D3DXCOLOR c(imageData[index]);
// shade current quad
//c *= computeShade(i, j, directionToLight);;
// save shaded color
//imageData[index] = (D3DCOLOR)c;
float s = computeShade(i, j, directionToLight);
imageData[index] = D3DXCOLOR(s, s, s, 1.0f);
}
}
_tex->UnlockRect(0);
return true;
}
float Terrain::computeShade(int cellRow, int cellCol, D3DXVECTOR3* directionToLight)
{
// get heights of three vertices on the quad
float heightA = (float)(getHeightmapEntry(cellRow, cellCol));
float heightB = (float)(getHeightmapEntry(cellRow, cellCol + 1));
float heightC = (float)(getHeightmapEntry(cellRow + 1, cellCol));
// build two vectors on the quad
D3DXVECTOR3 u((FLOAT)_cellSpacing, (FLOAT)heightB - (FLOAT)heightA, 0.0f);
D3DXVECTOR3 v(0.0f, (FLOAT)(heightC - heightA), (FLOAT)-_cellSpacing);
// find the normal by taking the cross product of two
// vectors on the quad.
D3DXVECTOR3 n;
D3DXVec3Cross(&n, &u, &v);
D3DXVec3Normalize(&n, &n);
float cosine = D3DXVec3Dot(&n, directionToLight);
if (cosine < 0.0f)
cosine = 0.0f;
return cosine;
}
bool Terrain::readRawFile(std::string fileName)
{
// Restriction: RAW file dimensions must be >= to the
// dimensions of the terrain. That is a 128x128 RAW file
// can only be used with a terrain constructed with at most
// 128x128 vertices.
// A height for each vertex
std::vector<BYTE> in(_numVertices);
std::ifstream inF(fileName.c_str(), std::ios_base::binary);
if (!inF)
return false;
inF.read(
(char*)&in[0], // buffer
in.size());// number of bytes to read into buffer
inF.close();
// copy BYTE vector to int vector
_heightmap.resize(_numVertices);
for (int i = 0; i < in.size(); i++)
_heightmap[i] = in[i];
return true;
}
float Terrain::getHeight(float x, float z)
{
// Translate on xz-plane by the transformation that takes
// the terrain START point to the origin.
x = ((float)_width / 2.0f) + x;
z = ((float)_depth / 2.0f) - z;
// Scale down by the transformation that makes the
// cellspacing equal to one. This is given by
// 1 / cellspacing since; cellspacing * 1 / cellspacing = 1.
x /= (float)_cellSpacing;
z /= (float)_cellSpacing;
// From now on, we will interpret our positive z-axis as
// going in the 'down' direction, rather than the 'up' direction.
// This allows to extract the row and column simply by 'flooring'
// x and z:
float col = ::floorf(x);
float row = ::floorf(z);
// get the heights of the quad we're in:
//
// A B
// *---*
// | / |
// *---*
// C D
float A = (float)getHeightmapEntry( (int)row, (int)col);
float B = (float)getHeightmapEntry( (int)row, (int)col + 1);
float C = (float)getHeightmapEntry( (int)row + 1, (int)col);
float D = (float)getHeightmapEntry( (int)row + 1, (int)col + 1);
//
// Find the triangle we are in:
//
// Translate by the transformation that takes the upper-left
// corner of the cell we are in to the origin. Recall that our
// cellspacing was nomalized to 1. Thus we have a unit square
// at the origin of our +x -> 'right' and +z -> 'down' system.
float dx = x - col;
float dz = z - row;
// Note the below compuations of u and v are unneccessary, we really
// only need the height, but we compute the entire vector to emphasis
// the books discussion.
float height = 0.0f;
if (dz < 1.0f - dx) // upper triangle ABC
{
float uy = B - A; // A->B
float vy = C - A; // A->C
// Linearly interpolate on each vector. The height is the vertex
// height the vectors u and v originate from {A}, plus the heights
// found by interpolating on each vector u and v.
height = A + D3D::Lerp(0.0f, uy, dx) + D3D::Lerp(0.0f, vy, dz);
}
else // lower triangle DCB
{
float uy = C - D; // D->C
float vy = B - D; // D->B
// Linearly interpolate on each vector. The height is the vertex
// height the vectors u and v originate from {D}, plus the heights
// found by interpolating on each vector u and v.
height = D + D3D::Lerp(0.0f, uy, 1.0f - dx) + D3D::Lerp(0.0f, vy, 1.0f - dz);
}
return height;
}
bool Terrain::draw(D3DXMATRIX* world, bool drawTris)
{
HRESULT hr = 0;
// IDirect3DDevice9* Device = graphics.GetDevice();
if (Device)
{
Device->SetTransform(D3DTS_WORLD, world);
Device->SetStreamSource(0, _vb, 0, sizeof(D3D::EVertex));
Device->SetFVF(D3D::EVertex::FVF);
Device->SetIndices(_ib);
Device->SetTexture(0, _tex);
// turn off lighting since we're lighting it ourselves
Device->SetRenderState(D3DRS_LIGHTING, false);
hr = Device->DrawIndexedPrimitive(
D3DPT_TRIANGLELIST,
0,
0,
_numVertices,
0,
_numTriangles);
Device->SetRenderState(D3DRS_LIGHTING, true);
if (drawTris)
{
Device->SetRenderState(D3DRS_FILLMODE, D3DFILL_WIREFRAME);
hr = Device->DrawIndexedPrimitive(
D3DPT_TRIANGLELIST,
0,
0,
_numVertices,
0,
_numTriangles);
Device->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
}
if (FAILED(hr))
return false;
}
return true;
}