Thinking Different




Terrain 05 - 쿼드 트리



원문 : http://www.rastertek.com/tertut05.html



 이 튜토리얼에서는 DirectX 11 및 C ++를 사용하여 쿼드 트리를 구현하는 방법에 대해 설명합니다. 이 듀토리얼의 코드는 이전 듀토리얼을 기반으로 합니다.


지금까지 지형을 렌더링하기 위해 우리는 전체 지형 정보를 단일 버퍼에 넣었으며, 모든 것을 볼 수 있는지 여부에 관계없이 그래픽 카드가 전체 지형을 각 프레임으로 렌더링하도록 했습니다. 이것은 분명히 비효율적이며 응용 프로그램의 성능을 저해할 수 있으므로 사용자가 현재 보고 있는 것만 그리는 방법을 찾아야 합니다. 다행스럽게도 우리가 각 프레임을 그리는 다각형의 수를 줄이는데 도움이 되는 많은 다른 공간 분할 알고리즘이 존재합니다. 대부분의 공간 분할 알고리즘은 장면을 더 작은 섹션으로 나누고 사용자가 볼 수 있는 섹션만 렌더링함으로써 작동합니다. 지형 데이터와 함께 잘 작동하는 더 나은 공간 분할 방법 중 하나는 Quad Tree Partitioning (쿼드 트리 분할)입니다.


쿼드 트리가 작동하는 방식은 지형을 4개의 사각 구역으로 나눕니다. 그런 다음 각 쿼드는 4개의 더 균등 한 크기의 쿼드로 나뉩니다. 이 부문은 우리가 정한 기준을 충족할 때까지 계속됩니다. 이 튜토리얼에서 기준은 쿼드 내에서 허용되는 최대 삼각형 수입니다. 최대값은 10,000으로 설정되므로 각 쿼드는 마침내 그 안에 10,000 개의 삼각형이 없을때까지 계속 분할됩니다.


쿼드 트리 알고리즘이 어떻게 작동하는지 설명하기 위해 먼저 전체 지형을 포함하는 쿼드로 시작합니다.




그런 다음 네 개의 쿼드로 나누고 각각의 쿼드에 10,000 개의 삼각형이 있는지 확인합니다.




쿼드에 10,000 개 이상의 삼각형이 있는 경우 해당 쿼드를 균등하게 크기가 조정된 4개의 쿼드로 나누고 새로운 4개의 쿼드 각각에 10,000 개의 삼각형이 있는지 확인합니다.




전체 쿼드 트리의 쿼드에 10,000 개의 삼각형이 없으면 지형을 섹션으로 나누는 작업이 완료됩니다. 이제 각 쿼드에 대해 어떤 삼각형이 그 내부에 속해 있는지 파악하고 각 쿼드에 대한 버텍스 버퍼를 만들고 그 쿼드에 대한 버텍스 버퍼를 삼각형으로 채웁니다. 최종 결과는 전체적으로 단일 버텍스 버퍼를 사용하는 대신 지형을 기본적으로 다수의 버텍스 버퍼로 나눈 것입니다. 각 쿼드는 위치와 크기가 알려진 큐브이기 때문에 FrustumClass를 사용하여 볼 수 없는 큐브를 제거할 수 있습니다. 이 원리를 통해 지형 렌더링의 성능을 개선할 수 있습니다.


쿼드 트리 알고리즘의 다음 측면은 쿼드가 다음과 같은 부모 자식 관계에서 서로 연결되도록 트리 구조를 유지한다는 것입니다.




다이어그램 위의 3개의 지형 그림과 마찬가지로 트리의 상단 노드를 사용하여 전체 지형을 나타냅니다. 하위 노드의 두 번째 계층은 부모 지형이 분할된 처음 4개의 쿼드를 나타냅니다. 세 번째 계층은 4개의 부모 쿼드가 분할 된 4개의 자식 쿼드를 나타냅니다. 그리고 거기에서 나무는 각 쿼드를 분할하지 않을 때 (이 예에서는 쿼드 당 최대 10,000 개의 삼각형)까지 기준을 충족 할 때까지 동일한 방식으로 계속 성장할 것입니다.


이제는 부모 자식 관계가 있는 트리 구조이기 때문에 이를 사용하여 지형을 도려낼 때 더 빠른 속도를 얻을 수 있습니다. 예를 들어 첫 번째 노드에서 시작하여 노드가 보이는지 여부를 확인합니다. 첫 번째 노드를 볼 수 없다면 지형을 볼 수 없고 아무것도 렌더링하지 않습니다. 이것은 매우 빠른 검사로 전체 지형을 비디오 카드로 렌더링하는 것을 제외할 수 있었습니다. 그러나 우리가 첫번째 노드를 볼 수 있다면 우리는 트리 아래로 내려갑니다.


다음으로 우리는 지형이 분할 된 처음 네 개의 쿼드를 나타내는 4개의 자식 노드 중 하나를 볼 수 있는지 확인합니다. 각 쿼드에 대해 자식 노드 검사를 제외할 수는 없습니다. 노드 트리가 빠른 제거 방법을 통해 엄청난 속도를 제공합니다. 볼 수 있는 쿼드는 트리의 맨 아래에 있는 자식 노드 목록이 표시 될 때까지 자식 노드를 확인하고 트리의 표시 가능한 부분을 계속 표시합니다. 그런 다음 최종 노드 목록을 줄입니다.


마지막으로 쿼드 트리에서는 높이가 중요하지 않습니다.



프레임워크


이 듀토리얼의 프레임워크는 QuadTreeClass 및 FrustumClass 객체를 추가한다는 점만 제외하면 이전 듀토리얼와 동일합니다. FrustumClass는 [DirectX 11] Tutorial 16 - 프러스텀 컬링 듀토리얼과 동일합니다. 새로운 QuadTreeClass를 먼저 살펴 보겠습니다.



Quadtreeclass.h


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
#pragma once
 
 
/////////////
// GLOBALS //
/////////////
const int MAX_TRIANGLES = 10000;
 
 
class TerrainClass;
class FrustumClass;
class TerrainShaderClass;
 
 
class QuadTreeClass
{
private:
    struct VertexType
    {
        XMFLOAT3 position;
        XMFLOAT2 texture;
        XMFLOAT3 normal;
    };
 
    struct NodeType
    {
        float positionX, positionZ, width;
        int triangleCount;
        ID3D11Buffer *vertexBuffer, *indexBuffer;
        NodeType* nodes[4];
    };
 
public:
    QuadTreeClass();
    QuadTreeClass(const QuadTreeClass&);
    ~QuadTreeClass();
 
    bool Initialize(TerrainClass*, ID3D11Device*);
    void Shutdown();
    void Render(FrustumClass*, ID3D11DeviceContext*, TerrainShaderClass*);
 
    int GetDrawCount();
 
private:
    void CalculateMeshDimensions(intfloat&float&float&);
    void CreateTreeNode(NodeType*floatfloatfloat, ID3D11Device*);
    int CountTriangles(floatfloatfloat);
    bool IsTriangleContained(intfloatfloatfloat);
    void ReleaseNode(NodeType*);
    void RenderNode(NodeType*, FrustumClass*, ID3D11DeviceContext*, TerrainShaderClass*);
 
private:
    int m_triangleCount, m_drawCount;
    VertexType* m_vertexList = nullptr;
    NodeType* m_parentNode = nullptr;
};
cs



Quadtreeclass.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
#include "stdafx.h"
#include "terrainclass.h"
#include "frustumclass.h"
#include "terrainshaderclass.h"
#include "quadtreeclass.h"
 
 
QuadTreeClass::QuadTreeClass()
{
}
 
 
QuadTreeClass::QuadTreeClass(const QuadTreeClass& other)
{
}
 
 
QuadTreeClass::~QuadTreeClass()
{
}
 
 
bool QuadTreeClass::Initialize(TerrainClass* terrain, ID3D11Device* device)
{
    float centerX = 0.0f;
    float centerZ = 0.0f;
    float width = 0.0f;
    
    // 지형 정점 배열의 정점 수를 가져옵니다.
    int vertexCount = terrain->GetVertexCount();
 
    // 정점리스트의 총 삼각형 수를 저장합니다.
    m_triangleCount = vertexCount / 3;
 
    // 모든 지형 정점을 포함하는 정점 배열을 만듭니다.
    m_vertexList = new VertexType[vertexCount];
    if(!m_vertexList)
    {
        return false;
    }
 
    // 지형 정점을 정점 목록에 복사합니다.
    terrain->CopyVertexArray((void*)m_vertexList);
 
    // 중심 x, z와 메쉬의 너비를 계산합니다.
    CalculateMeshDimensions(vertexCount, centerX, centerZ, width);
 
    // 쿼드 트리의 부모 노드를 만듭니다.
    m_parentNode = new NodeType;
    if(!m_parentNode)
    {
        return false;
    }
 
    // 정점 목록 데이터와 메쉬 차원을 기반으로 쿼드 트리를 재귀 적으로 빌드합니다.
    CreateTreeNode(m_parentNode, centerX, centerZ, width, device);
 
    // 쿼드 트리가 각 노드에 정점을 갖기 때문에 정점 목록을 놓습니다.
    if(m_vertexList)
    {
        delete [] m_vertexList;
        m_vertexList = 0;
    }
 
    return true;
}
 
 
void QuadTreeClass::Shutdown()
{
    // 쿼드 트리 데이터를 재귀 적으로 해제합니다.
    if(m_parentNode)
    {
        ReleaseNode(m_parentNode);
        delete m_parentNode;
        m_parentNode = 0;
    }
}
 
 
void QuadTreeClass::Render(FrustumClass* frustum, ID3D11DeviceContext* deviceContext, TerrainShaderClass* shader)
{
    // 이 프레임에 대해 그려지는 삼각형의 수를 초기화합니다.
    m_drawCount = 0;
 
    // 부모 노드에서 시작하여 트리 아래로 이동하여 보이는 각 노드를 렌더링합니다.
    RenderNode(m_parentNode, frustum, deviceContext, shader);
}
 
 
int QuadTreeClass::GetDrawCount()
{
    return m_drawCount;
}
 
 
void QuadTreeClass::CalculateMeshDimensions(int vertexCount, float& centerX, float& centerZ, float& meshWidth)
{
    // 메쉬의 중심 위치를 0으로 초기화합니다.
    centerX = 0.0f;
    centerZ = 0.0f;
 
    // 메쉬의 모든 정점을 합친다.
    for(int i=0; i<vertexCount; i++)
    {
        centerX += m_vertexList[i].position.x;
        centerZ += m_vertexList[i].position.z;
    }
 
    // 그리고 메쉬의 중간 점을 찾기 위해 정점의 수로 나눕니다.
    centerX = centerX / (float)vertexCount;
    centerZ = centerZ / (float)vertexCount;
 
    // 메쉬의 최대 및 최소 크기를 초기화합니다.
    float maxWidth = 0.0f;
    float maxDepth = 0.0f;
 
    float minWidth = fabsf(m_vertexList[0].position.x - centerX);
    float minDepth = fabsf(m_vertexList[0].position.z - centerZ);
 
    // 모든 정점을 살펴보고 메쉬의 최대 너비와 최소 너비와 깊이를 찾습니다.
    for(int i=0; i<vertexCount; i++)
    {
        float width = fabsf(m_vertexList[i].position.x - centerX);    
        float depth = fabsf(m_vertexList[i].position.z - centerZ);    
 
        if(width > maxWidth) { maxWidth = width; }
        if(depth > maxDepth) { maxDepth = depth; }
        if(width < minWidth) { minWidth = width; }
        if(depth < minDepth) { minDepth = depth; }
    }
 
    // 최소와 최대 깊이와 너비 사이의 절대 최대 값을 찾습니다.
    float maxX = (float)max(fabs(minWidth), fabs(maxWidth));
    float maxZ = (float)max(fabs(minDepth), fabs(maxDepth));
    
    // 메쉬의 최대 직경을 계산합니다.
    meshWidth = max(maxX, maxZ) * 2.0f;
}
 
 
void QuadTreeClass::CreateTreeNode(NodeType* node, float positionX, float positionZ, float width, ID3D11Device* device)
{
    // 노드의 위치와 크기를 저장한다.
    node->positionX = positionX;
    node->positionZ = positionZ;
    node->width = width;
 
    // 노드의 삼각형 수를 0으로 초기화합니다.
    node->triangleCount = 0;
 
    //정점 및 인덱스 버퍼를 null로 초기화합니다.
    node->vertexBuffer = 0;
    node->indexBuffer = 0;
 
    // 이 노드의 자식 노드를 null로 초기화합니다.
    node->nodes[0= 0;
    node->nodes[1= 0;
    node->nodes[2= 0;
    node->nodes[3= 0;
 
    // 이 노드 안에 있는 삼각형 수를 센다.
    int numTriangles = CountTriangles(positionX, positionZ, width);
 
    // 사례 1: 이 노드에 삼각형이 없으면 비어있는 상태로 돌아가서 처리할 필요가 없습니다.
    if(numTriangles == 0)
    {
        return;
    }
 
    // 사례 2: 이 노드에 너무 많은 삼각형이 있는 경우 4 개의 동일한 크기의 더 작은 트리 노드로 분할합니다.
    if(numTriangles > MAX_TRIANGLES)
    {
        for(int i=0; i<4; i++)
        {
            // 새로운 자식 노드에 대한 위치 오프셋을 계산합니다.
            float offsetX = (((i % 2< 1) ? -1.0f : 1.0f) * (width / 4.0f);
            float offsetZ = (((i % 4< 2) ? -1.0f : 1.0f) * (width / 4.0f);
 
            // 새 노드에 삼각형이 있는지 확인합니다.
            int count = CountTriangles((positionX + offsetX), (positionZ + offsetZ), (width / 2.0f));
            if(count > 0)
            {
                // 이 새 노드가있는 삼각형이있는 경우 자식 노드를 만듭니다.
                node->nodes[i] = new NodeType;
 
                // 이제이 새 자식 노드에서 시작하는 트리를 확장합니다.
                CreateTreeNode(node->nodes[i], (positionX + offsetX), (positionZ + offsetZ), (width / 2.0f), device);
            }
        }
        return;
    }
 
    // 사례 3: 이 노드가 비어 있지않고 그 노드의 삼각형 수가 최대 값보다 작으면 
    // 이 노드는 트리의 맨 아래에 있으므로 저장할 삼각형 목록을 만듭니다.
    node->triangleCount = numTriangles;
 
    // 정점의 수를 계산합니다.
    int vertexCount = numTriangles * 3;
 
    // 정점 배열을 만듭니다.
    VertexType* vertices = new VertexType[vertexCount];
 
    // 인덱스 배열을 만듭니다.
    unsigned long* indices = new unsigned long[vertexCount];
 
    // 이 새로운 정점 및 인덱스 배열의 인덱스를 초기화합니다.
    int index = 0;
    int vertexIndex = 0;
 
    // 정점 목록의 모든 삼각형을 살펴 봅니다.
    for(int i=0; i<m_triangleCount; i++)
    {
        // 삼각형이이 노드 안에 있으면 꼭지점 배열에 추가합니다.
        if(IsTriangleContained(i, positionX, positionZ, width) == true)
        {
            // 지형 버텍스 목록에 인덱스를 계산합니다.
            vertexIndex = i * 3;
 
            // 정점 목록에서 이 삼각형의 세 꼭지점을 가져옵니다.
            vertices[index].position = m_vertexList[vertexIndex].position;
            vertices[index].texture = m_vertexList[vertexIndex].texture;
            vertices[index].normal = m_vertexList[vertexIndex].normal;
            indices[index] = index;
            index++;
 
            vertexIndex++;
            vertices[index].position = m_vertexList[vertexIndex].position;
            vertices[index].texture = m_vertexList[vertexIndex].texture;
            vertices[index].normal = m_vertexList[vertexIndex].normal;
            indices[index] = index;
            index++;
 
            vertexIndex++;
            vertices[index].position = m_vertexList[vertexIndex].position;
            vertices[index].texture = m_vertexList[vertexIndex].texture;
            vertices[index].normal = m_vertexList[vertexIndex].normal;
            indices[index] = index;
            index++;
        }
    }
 
    // 정점 버퍼의 구조체를 설정합니다.
    D3D11_BUFFER_DESC vertexBufferDesc;
    vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
    vertexBufferDesc.ByteWidth = sizeof(VertexType) * vertexCount;
    vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    vertexBufferDesc.CPUAccessFlags = 0;
    vertexBufferDesc.MiscFlags = 0;
    vertexBufferDesc.StructureByteStride = 0;
 
    // subresource 구조에 정점 데이터에 대한 포인터를 제공합니다.
    D3D11_SUBRESOURCE_DATA vertexData;
    vertexData.pSysMem = vertices;
    vertexData.SysMemPitch = 0;
    vertexData.SysMemSlicePitch = 0;
 
    // 이제 마침내 정점 버퍼를 만듭니다.
    device->CreateBuffer(&vertexBufferDesc, &vertexData, &node->vertexBuffer);
 
    // 인덱스 버퍼의 설명을 설정합니다.
    D3D11_BUFFER_DESC indexBufferDesc;
    indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
    indexBufferDesc.ByteWidth = sizeof(unsigned long* vertexCount;
    indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
    indexBufferDesc.CPUAccessFlags = 0;
    indexBufferDesc.MiscFlags = 0;
    indexBufferDesc.StructureByteStride = 0;
 
    // 하위 리소스 구조에 인덱스 데이터에 대한 포인터를 제공합니다.
    D3D11_SUBRESOURCE_DATA indexData;
    indexData.pSysMem = indices;
    indexData.SysMemPitch = 0;
    indexData.SysMemSlicePitch = 0;
 
    // 인덱스 버퍼를 만듭니다.
    device->CreateBuffer(&indexBufferDesc, &indexData, &node->indexBuffer);
 
    // 이제 노드의 버퍼에 데이터가 저장되므로 꼭지점과 인덱스 배열을 해제합니다.
    delete [] vertices;
    vertices = 0;
 
    delete [] indices;
    indices = 0;
}
 
 
int QuadTreeClass::CountTriangles(float positionX, float positionZ, float width)
{
    // 카운트를 0으로 초기화한다.
    int count = 0;
 
    // 전체 메쉬의 모든 삼각형을 살펴보고 어떤 노드가 이 노드 안에 있어야 하는지 확인합니다.
    for(int i=0; i<m_triangleCount; i++)
    {
        // 삼각형이 노드 안에 있으면 1씩 증가시킵니다.
        if(IsTriangleContained(i, positionX, positionZ, width) == true)
        {
            count++;
        }
    }
 
    return count;
}
 
 
bool QuadTreeClass::IsTriangleContained(int index, float positionX, float positionZ, float width)
{
    // 이 노드의 반경을 계산합니다.
    float radius = width / 2.0f;
 
    // 인덱스를 정점 목록으로 가져옵니다.
    int vertexIndex = index * 3;
 
    // 정점 목록에서 이 삼각형의 세 꼭지점을 가져옵니다.
    float x1 = m_vertexList[vertexIndex].position.x;
    float z1 = m_vertexList[vertexIndex].position.z;
    vertexIndex++;
    
    float x2 = m_vertexList[vertexIndex].position.x;
    float z2 = m_vertexList[vertexIndex].position.z;
    vertexIndex++;
 
    float x3 = m_vertexList[vertexIndex].position.x;
    float z3 = m_vertexList[vertexIndex].position.z;
 
    // 삼각형의 x 좌표의 최소값이 노드 안에 있는지 확인하십시오.
    float minimumX = min(x1, min(x2, x3));
    if(minimumX > (positionX + radius))
    {
        return false;
    }
 
    // 삼각형의 x 좌표의 최대 값이 노드 안에 있는지 확인하십시오.
    float maximumX = max(x1, max(x2, x3));
    if(maximumX < (positionX - radius))
    {
        return false;
    }
 
    // 삼각형의 z 좌표의 최소값이 노드 안에 있는지 확인하십시오.
    float minimumZ = min(z1, min(z2, z3));
    if(minimumZ > (positionZ + radius))
    {
        return false;
    }
 
    // 삼각형의 z 좌표의 최대 값이 노드 안에 있는지 확인하십시오.
    float maximumZ = max(z1, max(z2, z3));
    if(maximumZ < (positionZ - radius))
    {
        return false;
    }
 
    return true;
}
 
 
void QuadTreeClass::ReleaseNode(NodeType* node)
{
    // 재귀 적으로 트리 아래로 내려와 맨 아래 노드를 먼저 놓습니다.
    for(int i=0; i<4; i++)
    {
        if(node->nodes[i] != 0)
        {
            ReleaseNode(node->nodes[i]);
        }
    }
 
    // 이 노드의 버텍스 버퍼를 해제한다.
    if(node->vertexBuffer)
    {
        node->vertexBuffer->Release();
        node->vertexBuffer = 0;
    }
 
    // 이 노드의 인덱스 버퍼를 해제합니다.
    if(node->indexBuffer)
    {
        node->indexBuffer->Release();
        node->indexBuffer = 0;
    }
 
    // 네 개의 자식 노드를 해제합니다.
    for(int i=0; i<4; i++)
    {
        if(node->nodes[i])
        {
            delete node->nodes[i];
            node->nodes[i] = 0;
        }
    }
}
 
 
void QuadTreeClass::RenderNode(NodeType* node, FrustumClass* frustum, ID3D11DeviceContext* deviceContext,
 TerrainShaderClass* shader)
{
    // 노드를 볼 수 있는지, 높이는 쿼드 트리에서 중요하지 않은지 확인합니다.
    // 보이지 않는 경우 자식 중 하나도 트리 아래로 계속 진행할 수 없으며 속도가 증가한 곳입니다.
    if(!frustum->CheckCube(node->positionX, 0.0f, node->positionZ, (node->width / 2.0f)))
    {
        return;
    }
 
    // 볼 수 있는 경우 네 개의 자식 노드를 모두 확인하여 볼 ​​수 있는지 확인합니다.
    int count = 0;
    for(int i=0; i<4; i++)
    {
        if(node->nodes[i] != 0)
        {
            count++;
            RenderNode(node->nodes[i], frustum, deviceContext, shader);
        }
    }
 
    // 자식 노드가 있는 경우 부모 노드가 렌더링 할 삼각형을 포함하지 않으므로 계속할 필요가 없습니다.
    if(count != 0)
    {
        return;
    }
 
    // 그렇지 않으면 이 노드를 볼 수 있고 그 안에 삼각형이 있으면 이 삼각형을 렌더링합니다.
 
    // 정점 버퍼 보폭 및 오프셋을 설정합니다.
    unsigned int stride = sizeof(VertexType); 
    unsigned int offset = 0;
 
    // 렌더링 할 수 있도록 입력 어셈블러에서 정점 버퍼를 활성으로 설정합니다.
    deviceContext->IASetVertexBuffers(01&node->vertexBuffer, &stride, &offset);
 
    // 렌더링 할 수 있도록 입력 어셈블러에서 인덱스 버퍼를 활성으로 설정합니다.
    deviceContext->IASetIndexBuffer(node->indexBuffer, DXGI_FORMAT_R32_UINT, 0);
 
    // 이 꼭지점 버퍼에서 렌더링 되어야 하는 프리미티브 유형을 설정합니다. 이 경우에는 삼각형입니다.
    deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
 
    // 이 노드에서 인덱스의 수를 결정합니다.
    int indexCount = node->triangleCount * 3;
 
    // 지형 셰이더를 호출하여 이 노드의 다각형을 렌더링합니다.
    shader->RenderShader(deviceContext, indexCount);
 
    // 이 프레임 동안 렌더링 된 폴리곤의 수를 늘립니다.
    m_drawCount += node->triangleCount;
}
cs



TerrainClass가 이전에 가지고 있던 렌더링 측면을 제거하도록 수정되었습니다. 이제 QuadTreeClass가 모든 렌더링을 처리합니다.


Terrainclass.h


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
#pragma once
 
 
 
/////////////
// GLOBALS //
/////////////
const int TEXTURE_REPEAT = 8;
 
class TextureClass;
 
 
class TerrainClass
{
private:
    struct VertexType
    {
        XMFLOAT3 position;
        XMFLOAT2 texture;
        XMFLOAT3 normal;
    };
 
    struct HeightMapType 
    { 
        float x, y, z;
        float tu, tv;
        float nx, ny, nz;
    };
 
    struct VectorType 
    { 
        float x, y, z;
    };
 
public:
    TerrainClass();
    TerrainClass(const TerrainClass&);
    ~TerrainClass();
 
    bool Initialize(ID3D11Device*const char*const WCHAR*);
    void Shutdown();
 
    ID3D11ShaderResourceView* GetTexture();
 
    int GetVertexCount();
    void CopyVertexArray(void*);
 
private:
    bool LoadHeightMap(const char*);
    void NormalizeHeightMap();
    bool CalculateNormals();
    void ShutdownHeightMap();
 
    void CalculateTextureCoordinates();
    bool LoadTexture(ID3D11Device*const WCHAR*);
    void ReleaseTexture();
 
    bool InitializeBuffers(ID3D11Device*);
    void ShutdownBuffers();
    
private:
    int m_terrainWidth = 0;
    int m_terrainHeight = 0;
    HeightMapType* m_heightMap = nullptr;
    TextureClass* m_Texture = nullptr;
    int m_vertexCount = 0;
    VertexType* m_vertices = nullptr;
};
cs



Terrainclass.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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
#include "stdafx.h"
#include "textureclass.h"
#include "terrainclass.h"
#include <stdio.h>
 
 
TerrainClass::TerrainClass()
{
}
 
 
TerrainClass::TerrainClass(const TerrainClass& other)
{
}
 
 
TerrainClass::~TerrainClass()
{
}
 
 
bool TerrainClass::Initialize(ID3D11Device* device, const char* heightMapFilename, const WCHAR* textureFilename)
{
    // 지형의 높이 맵을 로드합니다.
    if(!LoadHeightMap(heightMapFilename))
    {
        return false;
    }
 
    // 높이 맵의 높이를 표준화합니다.
    NormalizeHeightMap();
 
    // 지형 데이터의 법선을 계산합니다.
    if(!CalculateNormals())
    {
        return false;
    }
 
    // 텍스처 좌표를 계산합니다.
    CalculateTextureCoordinates();
 
    // 텍스처를 로드합니다.
    if(!LoadTexture(device, textureFilename))
    {
        return false;
    }
 
    // 지형에 대한 지오 메트릭을 포함하는 정점 및 인덱스 버퍼를 초기화합니다.
    return InitializeBuffers(device);
}
 
 
void TerrainClass::Shutdown()
{
    // 텍스처를 해제합니다.
    ReleaseTexture();
 
    // 버텍스와 인덱스 버퍼를 해제합니다.
    ShutdownBuffers();
 
    // 높이맵 데이터를 해제합니다.
    ShutdownHeightMap();
}
 
 
ID3D11ShaderResourceView* TerrainClass::GetTexture()
{
    return m_Texture->GetTexture();
}
 
 
bool TerrainClass::LoadHeightMap(const char* filename)
{
    // 바이너리 모드로 높이맵 파일을 엽니다.
    FILE* filePtr = nullptr;
    if(fopen_s(&filePtr, filename, "rb"!= 0)
    {
        return false;
    }
 
    // 파일 헤더를 읽습니다.
    BITMAPFILEHEADER bitmapFileHeader;
    if(fread(&bitmapFileHeader, sizeof(BITMAPFILEHEADER), 1, filePtr) != 1)
    {
        return false;
    }
 
    // 비트맵 정보 헤더를 읽습니다.
    BITMAPINFOHEADER bitmapInfoHeader;
    if(fread(&bitmapInfoHeader, sizeof(BITMAPINFOHEADER), 1, filePtr) != 1)
    {
        return false;
    }
 
    // 지형의 크기를 저장합니다.
    m_terrainWidth = bitmapInfoHeader.biWidth;
    m_terrainHeight = bitmapInfoHeader.biHeight;
 
    // 비트맵 이미지 데이터의 크기를 계산합니다.
    int imageSize = m_terrainWidth * m_terrainHeight * 3;
 
    // 비트맵 이미지 데이터에 메모리를 할당합니다.
    unsigned char* bitmapImage = new unsigned char[imageSize];
    if(!bitmapImage)
    {
        return false;
    }
 
    // 비트맵 데이터의 시작 부분으로 이동합니다.
    fseek(filePtr, bitmapFileHeader.bfOffBits, SEEK_SET);
 
    // 비트맵 이미지 데이터를 읽습니다.
    if(fread(bitmapImage, 1, imageSize, filePtr) != imageSize)
    {
        return false;
    }
 
    // 파일을 닫습니다.
    if(fclose(filePtr) != 0)
    {
        return false;
    }
 
    // 높이 맵 데이터를 저장할 구조체를 만듭니다.
    m_heightMap = new HeightMapType[m_terrainWidth * m_terrainHeight];
    if(!m_heightMap)
    {
        return false;
    }
 
    // 이미지 데이터 버퍼의 위치를 ​​초기화합니다.
    int k = 0;
 
    // 이미지 데이터를 높이 맵으로 읽어들입니다.
    for(int j=0; j<m_terrainHeight; j++)
    {
        for(int i=0; i<m_terrainWidth; i++)
        {
            unsigned char height = bitmapImage[k];
            
            int index = (m_terrainHeight * j) + i;
 
            m_heightMap[index].x = (float)i;
            m_heightMap[index].y = (float)height;
            m_heightMap[index].z = (float)j;
 
            k+=3;
        }
    }
 
    // 비트맵 이미지 데이터를 해제합니다.
    delete [] bitmapImage;
    bitmapImage = 0;
 
    return true;
}
 
 
void TerrainClass::NormalizeHeightMap()
{
    for(int j=0; j<m_terrainHeight; j++)
    {
        for(int i=0; i<m_terrainWidth; i++)
        {
            m_heightMap[(m_terrainHeight * j) + i].y /= 15.0f;
        }
    }
}
 
 
bool TerrainClass::CalculateNormals()
{
    int index1 = 0;
    int index2 = 0;
    int index3 = 0;
    int index = 0;
    int count = 0;
    float vertex1[3= { 0.f, 0.f, 0.f };
    float vertex2[3= { 0.f, 0.f, 0.f };
    float vertex3[3= { 0.f, 0.f, 0.f };
    float vector1[3= { 0.f, 0.f, 0.f };
    float vector2[3= { 0.f, 0.f, 0.f };
    float sum[3= { 0.f, 0.f, 0.f };
    float length = 0.0f;
 
 
    // 정규화되지 않은 법선 벡터를 저장할 임시 배열을 만듭니다.
    VectorType* normals = new VectorType[(m_terrainHeight-1* (m_terrainWidth-1)];
    if(!normals)
    {
        return false;
    }
 
    // 메쉬의 모든면을 살펴보고 법선을 계산합니다.
    for(int j=0; j<(m_terrainHeight-1); j++)
    {
        for(int i=0; i<(m_terrainWidth-1); i++)
        {
            index1 = (j * m_terrainHeight) + i;
            index2 = (j * m_terrainHeight) + (i+1);
            index3 = ((j+1* m_terrainHeight) + i;
 
            // 표면에서 세 개의 꼭지점을 가져옵니다.
            vertex1[0= m_heightMap[index1].x;
            vertex1[1= m_heightMap[index1].y;
            vertex1[2= m_heightMap[index1].z;
        
            vertex2[0= m_heightMap[index2].x;
            vertex2[1= m_heightMap[index2].y;
            vertex2[2= m_heightMap[index2].z;
        
            vertex3[0= m_heightMap[index3].x;
            vertex3[1= m_heightMap[index3].y;
            vertex3[2= m_heightMap[index3].z;
 
            // 표면의 두 벡터를 계산합니다.
            vector1[0= vertex1[0- vertex3[0];
            vector1[1= vertex1[1- vertex3[1];
            vector1[2= vertex1[2- vertex3[2];
            vector2[0= vertex3[0- vertex2[0];
            vector2[1= vertex3[1- vertex2[1];
            vector2[2= vertex3[2- vertex2[2];
 
            index = (j * (m_terrainHeight-1)) + i;
 
            // 이 두 법선에 대한 정규화되지 않은 값을 얻기 위해 두 벡터의 외적을 계산합니다.
            normals[index].x = (vector1[1* vector2[2]) - (vector1[2* vector2[1]);
            normals[index].y = (vector1[2* vector2[0]) - (vector1[0* vector2[2]);
            normals[index].z = (vector1[0* vector2[1]) - (vector1[1* vector2[0]);
        }
    }
 
    // 이제 모든 정점을 살펴보고 각면의 평균을 취합니다.     
    // 정점이 닿아 그 정점에 대한 평균 평균값을 얻는다.
    for(int j=0; j<m_terrainHeight; j++)
    {
        for(int i=0; i<m_terrainWidth; i++)
        {
            // 합계를 초기화합니다.
            sum[0= 0.0f;
            sum[1= 0.0f;
            sum[2= 0.0f;
 
            // 카운트를 초기화합니다.
            count = 0;
 
            // 왼쪽 아래면.
            if(((i-1>= 0&& ((j-1>= 0))
            {
                index = ((j-1* (m_terrainHeight-1)) + (i-1);
 
                sum[0+= normals[index].x;
                sum[1+= normals[index].y;
                sum[2+= normals[index].z;
                count++;
            }
 
            // 오른쪽 아래 면.
            if((i < (m_terrainWidth-1)) && ((j-1>= 0))
            {
                index = ((j-1* (m_terrainHeight-1)) + i;
 
                sum[0+= normals[index].x;
                sum[1+= normals[index].y;
                sum[2+= normals[index].z;
                count++;
            }
 
            // 왼쪽 위 면.
            if(((i-1>= 0&& (j < (m_terrainHeight-1)))
            {
                index = (j * (m_terrainHeight-1)) + (i-1);
 
                sum[0+= normals[index].x;
                sum[1+= normals[index].y;
                sum[2+= normals[index].z;
                count++;
            }
 
            // 오른쪽 위 면.
            if((i < (m_terrainWidth-1)) && (j < (m_terrainHeight-1)))
            {
                index = (j * (m_terrainHeight-1)) + i;
 
                sum[0+= normals[index].x;
                sum[1+= normals[index].y;
                sum[2+= normals[index].z;
                count++;
            }
            
            // 이 정점에 닿는면의 평균을 취합니다.
            sum[0= (sum[0/ (float)count);
            sum[1= (sum[1/ (float)count);
            sum[2= (sum[2/ (float)count);
 
            // 이 법선의 길이를 계산합니다.
            length = (float)sqrt((sum[0* sum[0]) + (sum[1* sum[1]) + (sum[2* sum[2]));
            
            // 높이 맵 배열의 정점 위치에 대한 인덱스를 가져옵니다.
            index = (j * m_terrainHeight) + i;
 
            // 이 정점의 최종 공유 법선을 표준화하여 높이 맵 배열에 저장합니다.
            m_heightMap[index].nx = (sum[0/ length);
            m_heightMap[index].ny = (sum[1/ length);
            m_heightMap[index].nz = (sum[2/ length);
        }
    }
 
    // 임시 법선을 해제합니다.
    delete [] normals;
    normals = 0;
 
    return true;
}
 
 
void TerrainClass::ShutdownHeightMap()
{
    if(m_heightMap)
    {
        delete [] m_heightMap;
        m_heightMap = 0;
    }
}
 
 
void TerrainClass::CalculateTextureCoordinates()
{
    // 텍스처 좌표를 얼마나 많이 증가 시킬지 계산합니다.
    float incrementValue = (float)TEXTURE_REPEAT / (float)m_terrainWidth;
 
    // 텍스처를 반복 할 횟수를 계산합니다.
    int incrementCount = m_terrainWidth / TEXTURE_REPEAT;
 
    // tu 및 tv 좌표 값을 초기화합니다.
    float tuCoordinate = 0.0f;
    float tvCoordinate = 1.0f;
 
    //  tu 및 tv 좌표 인덱스를 초기화합니다.
    int tuCount = 0;
    int tvCount = 0;
 
    // 전체 높이 맵을 반복하고 각 꼭지점의 tu 및 tv 텍스처 좌표를 계산합니다.
    for(int j=0; j<m_terrainHeight; j++)
    {
        for(int i=0; i<m_terrainWidth; i++)
        {
            // 높이 맵에 텍스처 좌표를 저장한다.
            m_heightMap[(m_terrainHeight * j) + i].tu = tuCoordinate;
            m_heightMap[(m_terrainHeight * j) + i].tv = tvCoordinate;
 
            // tu 텍스처 좌표를 증가 값만큼 증가시키고 인덱스를 1 씩 증가시킨다.
            tuCoordinate += incrementValue;
            tuCount++;
 
            // 텍스처의 오른쪽 끝에 있는지 확인하고, 그렇다면 처음부터 다시 시작하십시오.
            if(tuCount == incrementCount)
            {
                tuCoordinate = 0.0f;
                tuCount = 0;
            }
        }
 
        // tv 텍스처 좌표를 증가 값만큼 증가시키고 인덱스를 1 씩 증가시킵니다.
        tvCoordinate -= incrementValue;
        tvCount++;
 
        // 텍스처의 상단에 있는지 확인하고, 그렇다면 하단에서 다시 시작합니다.
        if(tvCount == incrementCount)
        {
            tvCoordinate = 1.0f;
            tvCount = 0;
        }
    }
}
 
 
bool TerrainClass::LoadTexture(ID3D11Device* device, const WCHAR* filename)
{
    // 텍스처 객체를 생성합니다.
    m_Texture = new TextureClass;
    if(!m_Texture)
    {
        return false;
    }
 
    // 텍스처 오브젝트를 초기화한다.
    return m_Texture->Initialize(device, filename);
}
 
 
void TerrainClass::ReleaseTexture()
{
    //텍스처 객체를 해제합니다.
    if(m_Texture)
    {
        m_Texture->Shutdown();
        delete m_Texture;
        m_Texture = 0;
    }
}
 
 
bool TerrainClass::InitializeBuffers(ID3D11Device* device)
{
    float tu = 0.0f;
    float tv = 0.0f;
 
    // 지형 메쉬의 정점 수를 계산합니다.
    m_vertexCount = (m_terrainWidth - 1* (m_terrainHeight - 1* 6;
 
    // 정점 배열을 만듭니다.
    m_vertices = new VertexType[m_vertexCount];
    if(!m_vertices)
    {
        return false;
    }
 
    // 정점 배열에 대한 인덱스를 초기화합니다.
    int index = 0;
 
    // 지형 데이터로 정점 및 인덱스 배열을 로드합니다.
    for(int j=0; j<(m_terrainHeight-1); j++)
    {
        for(int i=0; i<(m_terrainWidth-1); i++)
        {
            int index1 = (m_terrainHeight * j) + i;          // 왼쪽 아래.
            int index2 = (m_terrainHeight * j) + (i+1);      // 오른쪽 아래.
            int index3 = (m_terrainHeight * (j+1)) + i;      // 왼쪽 위.
            int index4 = (m_terrainHeight * (j+1)) + (i+1);  // 오른쪽 위.
 
            // 왼쪽 위.
            tv = m_heightMap[index3].tv;
 
            // 상단 가장자리를 덮도록 텍스처 좌표를 수정합니다.
            if(tv == 1.0f) { tv = 0.0f; }
 
            m_vertices[index].position = XMFLOAT3(m_heightMap[index3].x, m_heightMap[index3].y, m_heightMap[index3].z);
            m_vertices[index].texture = XMFLOAT2(m_heightMap[index3].tu, tv);
            m_vertices[index].normal = XMFLOAT3(m_heightMap[index3].nx, m_heightMap[index3].ny, m_heightMap[index3].nz);
            index++;
 
            // 오른쪽 위.
            tu = m_heightMap[index4].tu;
            tv = m_heightMap[index4].tv;
 
            // 위쪽과 오른쪽 가장자리를 덮도록 텍스처 좌표를 수정합니다.
            if(tu == 0.0f) { tu = 1.0f; }
            if(tv == 1.0f) { tv = 0.0f; }
 
            m_vertices[index].position = XMFLOAT3(m_heightMap[index4].x, m_heightMap[index4].y, m_heightMap[index4].z);
            m_vertices[index].texture = XMFLOAT2(tu, tv);
            m_vertices[index].normal = XMFLOAT3(m_heightMap[index4].nx, m_heightMap[index4].ny, m_heightMap[index4].nz);
            index++;
 
            // 왼쪽 아래.
            m_vertices[index].position = XMFLOAT3(m_heightMap[index1].x, m_heightMap[index1].y, m_heightMap[index1].z);
            m_vertices[index].texture = XMFLOAT2(m_heightMap[index1].tu, m_heightMap[index1].tv);
            m_vertices[index].normal = XMFLOAT3(m_heightMap[index1].nx, m_heightMap[index1].ny, m_heightMap[index1].nz);
            index++;
 
            // 왼쪽 아래.
            m_vertices[index].position = XMFLOAT3(m_heightMap[index1].x, m_heightMap[index1].y, m_heightMap[index1].z);
            m_vertices[index].texture = XMFLOAT2(m_heightMap[index1].tu, m_heightMap[index1].tv);
            m_vertices[index].normal = XMFLOAT3(m_heightMap[index1].nx, m_heightMap[index1].ny, m_heightMap[index1].nz);
            index++;
 
            // 오른쪽 위.
            tu = m_heightMap[index4].tu;
            tv = m_heightMap[index4].tv;
 
            // 위쪽과 오른쪽 가장자리를 덮도록 텍스처 좌표를 수정합니다.
            if(tu == 0.0f) { tu = 1.0f; }
            if(tv == 1.0f) { tv = 0.0f; }
 
            m_vertices[index].position = XMFLOAT3(m_heightMap[index4].x, m_heightMap[index4].y, m_heightMap[index4].z);
            m_vertices[index].texture = XMFLOAT2(tu, tv);
            m_vertices[index].normal = XMFLOAT3(m_heightMap[index4].nx, m_heightMap[index4].ny, m_heightMap[index4].nz);
            index++;
 
            // 오른쪽 아래.
            tu = m_heightMap[index2].tu;
 
            // 오른쪽 가장자리를 덮도록 텍스처 좌표를 수정합니다.
            if(tu == 0.0f) { tu = 1.0f; }
 
            m_vertices[index].position = XMFLOAT3(m_heightMap[index2].x, m_heightMap[index2].y, m_heightMap[index2].z);
            m_vertices[index].texture = XMFLOAT2(tu, m_heightMap[index2].tv);
            m_vertices[index].normal = XMFLOAT3(m_heightMap[index2].nx, m_heightMap[index2].ny, m_heightMap[index2].nz);
            index++;            
        }
    }
 
    return true;
}
 
 
void TerrainClass::ShutdownBuffers()
{
    // 버텍스 배열을 해제합니다.
    if(m_vertices)
    {
        delete [] m_vertices;
        m_vertices = 0;
    }
}
 
 
int TerrainClass::GetVertexCount()
{
    return m_vertexCount;
}
 
 
void TerrainClass::CopyVertexArray(void* vertexList)
{
    memcpy(vertexList, m_vertices, sizeof(VertexType) * m_vertexCount);
}
cs




TerrainShaderClass의 헤더 파일만 변경되었습니다. SetShaderParameters 및 RenderShader 함수가 private 함수 대신 public 함수로 변경되었습니다. 이유는 TerrainShaderClass 객체가 수많은 개별 버퍼를 렌더링해야하지만 셰이더 매개 변수를 한번만 설정해야 하기 때문입니다. 일반 Render 함수를 사용하는 것만으로도 쿼드 트리에서 제대로 작동하지 않는 셰이더 매개 변수를 렌더링 할 필요가 있습니다. 그리고 이 때문에 우리는 더 이상 어떤 목적으로도 사용되지 않으므로 원래의 Render 기능을 제거했습니다.


Terrainshaderclass.h


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
#pragma once
 
class TerrainShaderClass : public AlignedAllocationPolicy<16>
{
private:
    struct MatrixBufferType
    {
        XMMATRIX world;
        XMMATRIX view;
        XMMATRIX projection;
    };
 
    struct LightBufferType
    {
        XMFLOAT4 ambientColor;
        XMFLOAT4 diffuseColor;
        XMFLOAT3 lightDirection;
        float padding;
    };
 
public:
    TerrainShaderClass();
    TerrainShaderClass(const TerrainShaderClass&);
    ~TerrainShaderClass();
 
    bool Initialize(ID3D11Device*, HWND);
    void Shutdown();
    bool SetShaderParameters(ID3D11DeviceContext*, XMMATRIX, XMMATRIX, XMMATRIX, XMFLOAT4, XMFLOAT4, XMFLOAT3,
 ID3D11ShaderResourceView*);
    void RenderShader(ID3D11DeviceContext*int);
 
private:
    bool InitializeShader(ID3D11Device*, HWND, const WCHAR*const WCHAR*);
    void ShutdownShader();
    void OutputShaderErrorMessage(ID3D10Blob*, HWND, const WCHAR*);
 
private:
    ID3D11VertexShader* m_vertexShader = nullptr;
    ID3D11PixelShader* m_pixelShader = nullptr;
    ID3D11InputLayout* m_layout = nullptr;
    ID3D11SamplerState* m_sampleState = nullptr;
    ID3D11Buffer* m_matrixBuffer = nullptr;
    ID3D11Buffer* m_lightBuffer = nullptr;
};
cs



TextClass는 각 프레임에 그려지는 지형 삼각형의 수를 포함하는 추가 문장을 렌더링하도록 수정되었습니다.


Textclass.h


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
#pragma once
 
class FontClass;
class FontShaderClass;
 
class TextClass : public AlignedAllocationPolicy<16>
{
private:
    struct SentenceType
    {
        ID3D11Buffer *vertexBuffer, *indexBuffer;
        int vertexCount, indexCount, maxLength;
        float red, green, blue;
    };
 
    struct VertexType
    {
        XMFLOAT3 position;
        XMFLOAT2 texture;
    };
 
public:
    TextClass();
    TextClass(const TextClass&);
    ~TextClass();
 
    bool Initialize(ID3D11Device*, ID3D11DeviceContext*, HWND, intint, XMMATRIX);
    void Shutdown();
    bool Render(ID3D11DeviceContext*, FontShaderClass*, XMMATRIX, XMMATRIX);
 
    bool SetVideoCardInfo(const char*int, ID3D11DeviceContext*);
    bool SetFps(int, ID3D11DeviceContext*);
    bool SetCpu(int, ID3D11DeviceContext*);
    bool SetCameraPosition(XMFLOAT3, ID3D11DeviceContext*);
    bool SetCameraRotation(XMFLOAT3, ID3D11DeviceContext*);
    bool SetRenderCount(int, ID3D11DeviceContext*);
 
private:
    bool InitializeSentence(SentenceType**int, ID3D11Device*);
    bool UpdateSentence(SentenceType*const char*intintfloatfloatfloat, ID3D11DeviceContext*);
    void ReleaseSentence(SentenceType**);
    bool RenderSentence(SentenceType*, ID3D11DeviceContext*, FontShaderClass*, XMMATRIX, XMMATRIX);
 
private:
    int m_screenWidth = 0;
    int m_screenHeight = 0;
    
    XMMATRIX m_baseViewMatrix;
    
    FontClass* m_Font = nullptr;
 
    SentenceType* m_sentence1 = nullptr;
    SentenceType* m_sentence2 = nullptr;
    SentenceType* m_sentence3 = nullptr;
    SentenceType* m_sentence4 = nullptr;
    SentenceType* m_sentence5 = nullptr;
    SentenceType* m_sentence6 = nullptr;
    SentenceType* m_sentence7 = nullptr;
    SentenceType* m_sentence8 = nullptr;
    SentenceType* m_sentence9 = nullptr;
    SentenceType* m_sentence10 = nullptr;
    SentenceType* m_sentence11 = nullptr;
};
cs



Textclass.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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
#include "stdafx.h"
#include "FontClass.h"
#include "FontShaderClass.h"
#include "TextClass.h"
 
 
TextClass::TextClass()
{
}
 
TextClass::TextClass(const TextClass& other)
{
}
 
TextClass::~TextClass()
{
}
 
bool TextClass::Initialize(ID3D11Device* device, ID3D11DeviceContext* deviceContext, HWND hwnd, int screenWidth,
 int screenHeight, XMMATRIX baseViewMatrix)
{
    // 화면 너비와 높이를 저장합니다.
    m_screenWidth = screenWidth;
    m_screenHeight = screenHeight;
 
    // 기본 뷰 매트릭스를 저장합니다.
    m_baseViewMatrix = baseViewMatrix;
 
    // 폰트 객체를 생성합니다.
    m_Font = new FontClass;
    if (!m_Font)
    {
        return false;
    }
 
    // 폰트 객체를 초기화 합니다.
    bool result = m_Font->Initialize(device, "../Dx11Terrain_05/data/fontdata.txt", L"../Dx11Terrain_05/data/font.dds");
    if (!result)
    {
        MessageBox(hwnd, L"Could not initialize the font object.", L"Error", MB_OK);
        return false;
    }
 
    // 첫 번째 문장을 초기화합니다
    result = InitializeSentence(&m_sentence1, 150, device);
    if(!result)
    {
        return false;
    }
 
    // 두 번째 문장을 초기화합니다
    result = InitializeSentence(&m_sentence2, 32, device);
    if(!result)
    {
        return false;
    }
 
    // 세 번째 문장을 초기화합니다
    result = InitializeSentence(&m_sentence3, 16, device);
    if(!result)
    {
        return false;
    }
 
    // 네 번째 문장을 초기화합니다
    result = InitializeSentence(&m_sentence4, 16, device);
    if(!result)
    {
        return false;
    }
 
    // 다섯 번째 문장을 초기화합니다
    result = InitializeSentence(&m_sentence5, 16, device);
    if(!result)
    {
        return false;
    }
 
    // 여섯 번째 문장을 초기화합니다
    result = InitializeSentence(&m_sentence6, 16, device);
    if(!result)
    {
        return false;
    }
 
    // 일곱 번째 문장을 초기화합니다
    result = InitializeSentence(&m_sentence7, 16, device);
    if(!result)
    {
        return false;
    }
 
    // 여덟 번째 문장을 초기화합니다
    result = InitializeSentence(&m_sentence8, 16, device);
    if(!result)
    {
        return false;
    }
 
    // 아홉 번째 문장을 초기화합니다
    result = InitializeSentence(&m_sentence9, 16, device);
    if(!result)
    {
        return false;
    }
 
    // 열 번째 문장을 초기화합니다
    result = InitializeSentence(&m_sentence10, 16, device);
    if(!result)
    {
        return false;
    }
 
    // 열한 번째 문장을 초기화합니다
    result = InitializeSentence(&m_sentence11, 32, device);
    if(!result)
    {
        return false;
    }
 
    return true;
}
 
 
void TextClass::Shutdown()
{
    // 폰트 객체를 해제합니다.
    if(m_Font)
    {
        m_Font->Shutdown();
        delete m_Font;
        m_Font = 0;
    }
 
    // 문장들을 해제합니다.
    ReleaseSentence(&m_sentence1);
    ReleaseSentence(&m_sentence2);
    ReleaseSentence(&m_sentence3);
    ReleaseSentence(&m_sentence4);
    ReleaseSentence(&m_sentence5);
    ReleaseSentence(&m_sentence6);
    ReleaseSentence(&m_sentence7);
    ReleaseSentence(&m_sentence8);
    ReleaseSentence(&m_sentence9);
    ReleaseSentence(&m_sentence10);
    ReleaseSentence(&m_sentence11);
}
 
 
bool TextClass::Render(ID3D11DeviceContext* deviceContext, FontShaderClass* FontShader, XMMATRIX worldMatrix,
 XMMATRIX orthoMatrix)
{
    // 문장을 그립니다.
    bool result = RenderSentence(m_sentence1, deviceContext, FontShader, worldMatrix, orthoMatrix);
    if(!result)
    {
        return false;
    }
 
    result = RenderSentence(m_sentence2, deviceContext, FontShader, worldMatrix, orthoMatrix);
    if(!result)
    {
        return false;
    }
 
    result = RenderSentence(m_sentence3, deviceContext, FontShader, worldMatrix, orthoMatrix);
    if(!result)
    {
        return false;
    }
 
    result = RenderSentence(m_sentence4, deviceContext, FontShader, worldMatrix, orthoMatrix);
    if(!result)
    {
        return false;
    }
 
    result = RenderSentence(m_sentence5, deviceContext, FontShader, worldMatrix, orthoMatrix);
    if(!result)
    {
        return false;
    }
 
    result = RenderSentence(m_sentence6, deviceContext, FontShader, worldMatrix, orthoMatrix);
    if(!result)
    {
        return false;
    }
 
    result = RenderSentence(m_sentence7, deviceContext, FontShader, worldMatrix, orthoMatrix);
    if(!result)
    {
        return false;
    }
 
    result = RenderSentence(m_sentence8, deviceContext, FontShader, worldMatrix, orthoMatrix);
    if(!result)
    {
        return false;
    }
 
    result = RenderSentence(m_sentence9, deviceContext, FontShader, worldMatrix, orthoMatrix);
    if(!result)
    {
        return false;
    }
 
    result = RenderSentence(m_sentence10, deviceContext, FontShader, worldMatrix, orthoMatrix);
    if(!result)
    {
        return false;
    }
 
    result = RenderSentence(m_sentence11, deviceContext, FontShader, worldMatrix, orthoMatrix);
    if(!result)
    {
        return false;
    }
 
    return true;
}
 
 
bool TextClass::InitializeSentence(SentenceType** sentence, int maxLength, ID3D11Device* device)
{
    // 새로운 문장 개체를 만듭니다.
    *sentence = new SentenceType;
    if (!*sentence)
    {
        return false;
    }
 
    // 문장 버퍼를 null로 초기화합니다.
    (*sentence)->vertexBuffer = 0;
    (*sentence)->indexBuffer = 0;
 
    // 문장의 최대 길이를 설정합니다.
    (*sentence)->maxLength = maxLength;
 
    // 정점 배열의 정점 수를 설정합니다.
    (*sentence)->vertexCount = 6 * maxLength;
 
    // 인덱스 배열의 인덱스 수를 설정합니다.
    (*sentence)->indexCount = (*sentence)->vertexCount;
 
    // 정점 배열을 만듭니다.
    VertexType* vertices = new VertexType[(*sentence)->vertexCount];
    if (!vertices)
    {
        return false;
    }
 
    // 인덱스 배열을 만듭니다.
    unsigned long* indices = new unsigned long[(*sentence)->indexCount];
    if (!indices)
    {
        return false;
    }
 
    // 처음에는 정점 배열을 0으로 초기화합니다.
    memset(vertices, 0, (sizeof(VertexType) * (*sentence)->vertexCount));
 
    // 인덱스 배열을 초기화합니다.
    for (int i = 0; i<(*sentence)->indexCount; i++)
    {
        indices[i] = i;
    }
 
    // 동적 인 정점 버퍼의 설명을 설정한다.
    D3D11_BUFFER_DESC vertexBufferDesc;
    vertexBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
    vertexBufferDesc.ByteWidth = sizeof(VertexType) * (*sentence)->vertexCount;
    vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    vertexBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    vertexBufferDesc.MiscFlags = 0;
    vertexBufferDesc.StructureByteStride = 0;
 
    // subresource 구조에 정점 데이터에 대한 포인터를 제공합니다.
    D3D11_SUBRESOURCE_DATA vertexData;
    vertexData.pSysMem = vertices;
    vertexData.SysMemPitch = 0;
    vertexData.SysMemSlicePitch = 0;
 
    // 정점 버퍼를 만든다.
    if (FAILED(device->CreateBuffer(&vertexBufferDesc, &vertexData, &(*sentence)->vertexBuffer)))
    {
        return false;
    }
 
    // 정적 인덱스 버퍼의 설명을 설정합니다.
    D3D11_BUFFER_DESC indexBufferDesc;
    
    indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
    indexBufferDesc.ByteWidth = sizeof(unsigned long* (*sentence)->indexCount;
    indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
    indexBufferDesc.CPUAccessFlags = 0;
    indexBufferDesc.MiscFlags = 0;
    indexBufferDesc.StructureByteStride = 0;
 
    // 하위 리소스 구조에 인덱스 데이터에 대한 포인터를 제공합니다.
    D3D11_SUBRESOURCE_DATA indexData;
    indexData.pSysMem = indices;
    indexData.SysMemPitch = 0;
    indexData.SysMemSlicePitch = 0;
 
    // 인덱스 버퍼를 만듭니다.
    if (FAILED(device->CreateBuffer(&indexBufferDesc, &indexData, &(*sentence)->indexBuffer)))
    {
        return false;
    }
 
    // 더 이상 필요하지 않은 정점 배열을 해제합니다.
    delete[] vertices;
    vertices = 0;
 
    // 더 이상 필요하지 않은 인덱스 배열을 해제합니다.
    delete[] indices;
    indices = 0;
 
    return true;
}
 
 
bool TextClass::UpdateSentence(SentenceType* sentence, const char* text, int positionX, int positionY, float red,
 float green, float blue, ID3D11DeviceContext* deviceContext)
{
    // 문장의 색을 저장한다.
    sentence->red = red;
    sentence->green = green;
    sentence->blue = blue;
 
    // 가능한 버퍼 오버 플로우를 확인합니다.
    if ((int)strlen(text) > sentence->maxLength)
    {
        return false;
    }
 
    // 정점 배열을 만듭니다.
    VertexType* vertices = new VertexType[sentence->vertexCount];
    if (!vertices)
    {
        return false;
    }
 
    // 처음에는 정점 배열을 0으로 초기화합니다.
    memset(vertices, 0, (sizeof(VertexType) * sentence->vertexCount));
 
    // 그리기를 시작할 화면에서 X 및 Y 픽셀 위치를 계산합니다.
    float drawX = (float)(((m_screenWidth / 2* -1+ positionX);
    float drawY = (float)((m_screenHeight / 2- positionY);
 
    // 폰트 클래스를 사용하여 문장 텍스트와 문장 그리기 위치에서 정점 배열을 만듭니다.
    m_Font->BuildVertexArray((void*)vertices, text, drawX, drawY);
 
    // 버텍스 버퍼를 쓸 수 있도록 잠급니다.
    D3D11_MAPPED_SUBRESOURCE mappedResource;
    if (FAILED(deviceContext->Map(sentence->vertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0&mappedResource)))
    {
        return false;
    }
 
    // 정점 버퍼의 데이터를 가리키는 포인터를 얻는다.
    VertexType* verticesPtr = (VertexType*)mappedResource.pData;
 
    // 데이터를 정점 버퍼에 복사합니다.
    memcpy(verticesPtr, (void*)vertices, (sizeof(VertexType) * sentence->vertexCount));
 
    // 정점 버퍼의 잠금을 해제합니다.
    deviceContext->Unmap(sentence->vertexBuffer, 0);
 
    // 더 이상 필요하지 않은 정점 배열을 해제합니다.
    delete[] vertices;
    vertices = 0;
 
    return true;
}
 
 
void TextClass::ReleaseSentence(SentenceType** sentence)
{
    if (*sentence)
    {
        // 문장 버텍스 버퍼를 해제합니다.
        if ((*sentence)->vertexBuffer)
        {
            (*sentence)->vertexBuffer->Release();
            (*sentence)->vertexBuffer = 0;
        }
 
        // 문장 인덱스 버퍼를 해제합니다.
        if ((*sentence)->indexBuffer)
        {
            (*sentence)->indexBuffer->Release();
            (*sentence)->indexBuffer = 0;
        }
 
        // 문장을 해제합니다.
        delete *sentence;
        *sentence = 0;
    }
}
 
 
bool TextClass::RenderSentence(SentenceType* sentence, ID3D11DeviceContext* deviceContext, FontShaderClass* FontShader,
 XMMATRIX worldMatrix, XMMATRIX orthoMatrix)
{
    // 정점 버퍼 간격 및 오프셋을 설정합니다.
    unsigned int stride = sizeof(VertexType);
    unsigned int offset = 0;
 
    // 렌더링 할 수 있도록 입력 어셈블러에서 정점 버퍼를 활성으로 설정합니다.
    deviceContext->IASetVertexBuffers(01&sentence->vertexBuffer, &stride, &offset);
 
    // 렌더링 할 수 있도록 입력 어셈블러에서 인덱스 버퍼를 활성으로 설정합니다.
    deviceContext->IASetIndexBuffer(sentence->indexBuffer, DXGI_FORMAT_R32_UINT, 0);
 
    // 이 정점 버퍼에서 렌더링 되어야 하는 프리미티브 유형을 설정합니다.이 경우에는 삼각형입니다.
    deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
 
    // 입력 된 문장 색상으로 픽셀 색상 벡터를 만듭니다.
    XMFLOAT4 pixelColor = XMFLOAT4(sentence->red, sentence->green, sentence->blue, 1.0f);
 
    // 폰트 셰이더를 사용하여 텍스트를 렌더링합니다.
    return FontShader->Render(deviceContext, sentence->indexCount, worldMatrix, m_baseViewMatrix, orthoMatrix,
 m_Font->GetTexture(), pixelColor);
}
 
 
bool TextClass::SetVideoCardInfo(const char* videoCardName, int videoCardMemory, ID3D11DeviceContext* deviceContext)
{
    char dataString[150= { 0, };
    char tempString[16= { 0, };
    char memoryString[32= { 0, };
 
    // 비디오 카드 이름 문자열을 설정합니다.
    strcpy_s(dataString, "Video Card: ");
    strcat_s(dataString, videoCardName);
 
    // 문장 정점 버퍼를 새 문자열 정보로 업데이트합니다.
    if(!UpdateSentence(m_sentence1, dataString, 10101.0f, 1.0f, 1.0f, deviceContext))
    {
        return false;
    }
 
    // 버퍼 오버플로우를 막기 위해 메모리 값을 자릅니다.
    if(videoCardMemory > 9999999)
    {
        videoCardMemory = 9999999;
    }
 
    // 비디오 메모리 정수 값을 문자열 형식으로 변환합니다.
    _itoa_s(videoCardMemory, tempString, 10);
 
    // 비디오 메모리 문자열을 설정합니다.
    strcpy_s(memoryString, "Video Memory: ");
    strcat_s(memoryString, tempString);
    strcat_s(memoryString, " MB");
 
    // 문장 정점 버퍼를 새 문자열 정보로 업데이트합니다.
    if(!UpdateSentence(m_sentence2, memoryString, 10301.0f, 1.0f, 1.0f, deviceContext))
    {
        return false;
    }
 
    return true;
}
 
 
bool TextClass::SetFps(int fps, ID3D11DeviceContext* deviceContext)
{
    char tempString[16= { 0, };
    char fpsString[16= { 0, };
 
    // 버퍼 오버플로우를 방지하기 위해 fps를 자릅니다.
    if(fps > 9999)
    {
        fps = 9999;
    }
 
    // fps 정수를 문자열 형식으로 변환합니다.
    _itoa_s(fps, tempString, 10);
 
    // fps 문자열을 설정합니다.
    strcpy_s(fpsString, "Fps: ");
    strcat_s(fpsString, tempString);
 
    // 문장 정점 버퍼를 새 문자열 정보로 업데이트합니다.
    if(!UpdateSentence(m_sentence3, fpsString, 10700.0f, 1.0f, 0.0f, deviceContext))
    {
        return false;
    }
 
    return true;
}
 
 
bool TextClass::SetCpu(int cpu, ID3D11DeviceContext* deviceContext)
{
    char tempString[16= { 0, };
    char cpuString[16= { 0, };
 
    // cpu 정수를 문자열 형식으로 변환합니다.
    _itoa_s(cpu, tempString, 10);
 
    // cpu 문자열을 설정합니다.
    strcpy_s(cpuString, "Cpu: ");
    strcat_s(cpuString, tempString);
    strcat_s(cpuString, "%");
 
    // 문장 정점 버퍼를 새 문자열 정보로 업데이트합니다.
    if(!UpdateSentence(m_sentence4, cpuString, 10900.0f, 1.0f, 0.0f, deviceContext))
    {
        return false;
    }
 
    return true;
}
 
 
bool TextClass::SetCameraPosition(XMFLOAT3 pos, ID3D11DeviceContext* deviceContext)
{
    char tempString[16= { 0, };
    char dataString[16= { 0, };
 
    // 부동 소수점에서 정수로 위치를 변환합니다.
    int positionX = (int)pos.x;
    int positionY = (int)pos.y;
    int positionZ = (int)pos.z;
 
    // 9999 또는 -9999를 초과하면 위치를 자릅니다.
    if(positionX > 9999) { positionX = 9999; }
    if(positionY > 9999) { positionY = 9999; }
    if(positionZ > 9999) { positionZ = 9999; }
 
    if(positionX < -9999) { positionX = -9999; }
    if(positionY < -9999) { positionY = -9999; }
    if(positionZ < -9999) { positionZ = -9999; }
 
    // X 위치 문자열을 설정합니다.
    _itoa_s(positionX, tempString, 10);
    strcpy_s(dataString, "X: ");
    strcat_s(dataString, tempString);
 
    if(!UpdateSentence(m_sentence5, dataString, 101300.0f, 1.0f, 0.0f, deviceContext))
    {
        return false;
    }
    
    // Y 위치 문자열을 설정합니다.
    _itoa_s(positionY, tempString, 10);
    strcpy_s(dataString, "Y: ");
    strcat_s(dataString, tempString);
    
    if(!UpdateSentence(m_sentence6, dataString, 101500.0f, 1.0f, 0.0f, deviceContext))
    {
        return false;
    }
 
    // Z 위치 문자열을 설정합니다.
    _itoa_s(positionZ, tempString, 10);
    strcpy_s(dataString, "Z: ");
    strcat_s(dataString, tempString);
    
    if(!UpdateSentence(m_sentence7, dataString, 101700.0f, 1.0f, 0.0f, deviceContext))
    {
        return false;
    }
 
    return true;
}
 
 
bool TextClass::SetCameraRotation(XMFLOAT3 rot, ID3D11DeviceContext* deviceContext)
{
    char tempString[16= { 0, };
    char dataString[16= { 0, };
 
    // 회전값을 정수로 변환합니다.
    int rotationX = (int)rot.x;
    int rotationY = (int)rot.y;
    int rotationZ = (int)rot.z;
 
    // X 회전 문자열을 설정합니다.
    _itoa_s(rotationX, tempString, 10);
    strcpy_s(dataString, "rX: ");
    strcat_s(dataString, tempString);
    
    if(!UpdateSentence(m_sentence8, dataString, 102100.0f, 1.0f, 0.0f, deviceContext))
    {
        return false;
    }
 
    // Y 회전 문자열을 설정합니다.
    _itoa_s(rotationY, tempString, 10);
    strcpy_s(dataString, "rY: ");
    strcat_s(dataString, tempString);
 
    if(!UpdateSentence(m_sentence9, dataString, 102300.0f, 1.0f, 0.0f, deviceContext))
    {
        return false;
    }
 
    // Z 회전 문자열을 설정합니다.
    _itoa_s(rotationZ, tempString, 10);
    strcpy_s(dataString, "rZ: ");
    strcat_s(dataString, tempString);
 
    // 문장 정점 버퍼를 새 문자열 정보로 업데이트 합니다.
    return UpdateSentence(m_sentence10, dataString, 102500.0f, 1.0f, 0.0f, deviceContext);
}
 
 
bool TextClass::SetRenderCount(int count, ID3D11DeviceContext* deviceContext)
{
    char tempString[16= { 0, };
    char renderString[32= { 0, };
 
    // 버퍼 오버플로를 방지하기 위해 커지면 렌더링 카운트를 자릅니다.
    if(count > 999999999)
    {
        count = 999999999;
    }
 
    // cpu 정수를 문자열 형식으로 변환합니다.
    _itoa_s(count, tempString, 10);
 
    // cpu 문자열을 설정합니다.
    strcpy_s(renderString, "Render Count: ");
    strcat_s(renderString, tempString);
 
    // 문장 정점 버퍼를 새 문자열 정보로 업데이트 합니다.
    return UpdateSentence(m_sentence11, renderString, 102900.0f, 1.0f, 0.0f, deviceContext);
}
cs



Applicationclass.h


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
#pragma once
 
/////////////
// GLOBALS //
/////////////
const bool FULL_SCREEN = false;
const bool VSYNC_ENABLED = true;
const float SCREEN_DEPTH = 1000.0f;
const float SCREEN_NEAR = 0.1f;
 
 
class D3DClass;
class InputClass;
class CameraClass;
class TerrainClass;
 
class TimerClass;
class PositionClass;
class FpsClass;
class CpuClass;
class FontShaderClass;
class TextClass;
class TerrainShaderClass;
class LightClass;
class FrustumClass;
class QuadTreeClass;
 
 
class ApplicationClass
{
public:
    ApplicationClass();
    ApplicationClass(const ApplicationClass&);
    ~ApplicationClass();
 
    bool Initialize(HINSTANCE, HWND, intint);
    void Shutdown();
    bool Frame();
 
private:
    bool HandleInput(float);
    bool RenderGraphics();
 
private:
    InputClass* m_Input = nullptr;
    D3DClass* m_Direct3D = nullptr;
    CameraClass* m_Camera = nullptr;
    TerrainClass* m_Terrain = nullptr;
    TimerClass* m_Timer = nullptr;
    PositionClass* m_Position = nullptr;
    FpsClass* m_Fps = nullptr;
    CpuClass* m_Cpu = nullptr;
    FontShaderClass* m_FontShader = nullptr;
    TextClass* m_Text = nullptr;
    TerrainShaderClass* m_TerrainShader = nullptr;
    LightClass* m_Light = nullptr;
    FrustumClass* m_Frustum = nullptr;
    QuadTreeClass* m_QuadTree = nullptr;
};
cs



Applicationclass.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
#include "stdafx.h"
#include "inputclass.h"
#include "d3dclass.h"
#include "cameraclass.h"
#include "terrainclass.h"
#include "timerclass.h"
#include "positionclass.h"
#include "fpsclass.h"
#include "cpuclass.h"
#include "fontshaderclass.h"
#include "textclass.h"
#include "terrainshaderclass.h"
#include "lightclass.h"
#include "frustumclass.h"
#include "quadtreeclass.h"
#include "ApplicationClass.h"
 
 
ApplicationClass::ApplicationClass()
{
}
 
 
ApplicationClass::ApplicationClass(const ApplicationClass& other)
{
}
 
 
ApplicationClass::~ApplicationClass()
{
}
 
 
bool ApplicationClass::Initialize(HINSTANCE hinstance, HWND hwnd, int screenWidth, int screenHeight)
{
    // 입력 개체를 생성합니다.
    m_Input = new InputClass;
    if(!m_Input)
    {
        return false;
    }
 
    // 입력 개체를 초기화 합니다.
    bool result = m_Input->Initialize(hinstance, hwnd, screenWidth, screenHeight);
    if(!result)
    {
        MessageBox(hwnd, L"Could not initialize the input object.", L"Error", MB_OK);
        return false;
    }
 
    // Direct3D 개체를 생성합니다.
    m_Direct3D = new D3DClass;
    if(!m_Direct3D)
    {
        return false;
    }
 
    // Direct3D 개체를 초기화 합니다.
    result = m_Direct3D->Initialize(screenWidth, screenHeight, VSYNC_ENABLED, hwnd, FULL_SCREEN, SCREEN_DEPTH, SCREEN_NEAR);
    if(!result)
    {
        MessageBox(hwnd, L"Could not initialize DirectX 11.", L"Error", MB_OK);
        return false;
    }
 
    // 카메라 객체를 생성합니다.
    m_Camera = new CameraClass;
    if(!m_Camera)
    {
        return false;
    }
 
    // 2D 사용자 인터페이스 렌더링을 위해 카메라로 기본 뷰 행렬을 초기화 합니다.
    XMMATRIX baseViewMatrix;
    m_Camera->SetPosition(XMFLOAT3(0.0f, 0.0f, -1.0f));
    m_Camera->Render();
    m_Camera->GetViewMatrix(baseViewMatrix);
 
    // 카메라의 초기 위치를 설정합니다.
    XMFLOAT3 camera = XMFLOAT3(50.0f, 2.0f, -7.0f);
    m_Camera->SetPosition(camera);
 
    // 지형 객체를 생성합니다.
    m_Terrain = new TerrainClass;
    if(!m_Terrain)
    {
        return false;
    }
 
    // 지형 객체를 초기화 합니다.
    result = m_Terrain->Initialize(m_Direct3D->GetDevice(), "../Dx11Terrain_05/data/heightmap01.bmp",
 L"../Dx11Terrain_05/data/dirt01.dds");
    if(!result)
    {
        MessageBox(hwnd, L"Could not initialize the terrain object.", L"Error", MB_OK);
        return false;
    }
 
    // 타이머 객체를 생성합니다.
    m_Timer = new TimerClass;
    if(!m_Timer)
    {
        return false;
    }
 
    // 타이머 객체를 초기화 합니다.
    result = m_Timer->Initialize();
    if(!result)
    {
        MessageBox(hwnd, L"Could not initialize the timer object.", L"Error", MB_OK);
        return false;
    }
 
    // 위치 개체를 생성합니다.
    m_Position = new PositionClass;
    if(!m_Position)
    {
        return false;
    }
 
    // 뷰어의 초기 위치를 초기 카메라 위치와 동일하게 설정합니다.
    m_Position->SetPosition(camera);
 
    // fps 객체를 생성합니다.
    m_Fps = new FpsClass;
    if(!m_Fps)
    {
        return false;
    }
 
    // fps 객체를 초기화 합니다.
    m_Fps->Initialize();
 
    // cpu 객체를 생성합니다.
    m_Cpu = new CpuClass;
    if(!m_Cpu)
    {
        return false;
    }
 
    // cpu 객체를 초기화 합니다.
    m_Cpu->Initialize();
 
    // 폰트 셰이더 객체를 생성합니다.
    m_FontShader = new FontShaderClass;
    if(!m_FontShader)
    {
        return false;
    }
 
    // 폰트 셰이더 객체를 초기화 합니다.
    result = m_FontShader->Initialize(m_Direct3D->GetDevice(), hwnd);
    if(!result)
    {
        MessageBox(hwnd, L"Could not initialize the font shader object.", L"Error", MB_OK);
        return false;
    }
 
    // 텍스트 객체를 생성합니다.
    m_Text = new TextClass;
    if(!m_Text)
    {
        return false;
    }
 
    // 텍스트 객체를 초기화 합니다.
    result = m_Text->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), hwnd, screenWidth,
 screenHeight, baseViewMatrix);
    if(!result)
    {
        MessageBox(hwnd, L"Could not initialize the text object.", L"Error", MB_OK);
        return false;
    }
 
    // 비디오 카드 정보를 가져옵니다.
    char videoCard[128= { 0, };
    int videoMemory = 0;
    m_Direct3D->GetVideoCardInfo(videoCard, videoMemory);
 
    // 텍스트 객체에 비디오 카드 정보를 설정합니다.
    result = m_Text->SetVideoCardInfo(videoCard, videoMemory, m_Direct3D->GetDeviceContext());
    if(!result)
    {
        MessageBox(hwnd, L"Could not set video card info in the text object.", L"Error", MB_OK);
        return false;
    }
 
    // 지형 쉐이더 객체를 생성합니다.
    m_TerrainShader = new TerrainShaderClass;
    if(!m_TerrainShader)
    {
        return false;
    }
 
    // 지형 쉐이더 객체를 초기화 합니다.
    result = m_TerrainShader->Initialize(m_Direct3D->GetDevice(), hwnd);
    if(!result)
    {
        MessageBox(hwnd, L"Could not initialize the terrain shader object.", L"Error", MB_OK);
        return false;
    }
 
    // 조명 객체를 생성합니다.
    m_Light = new LightClass;
    if(!m_Light)
    {
        return false;
    }
 
    // 조명 객체를 초기화 합니다.
    m_Light->SetAmbientColor(XMFLOAT4(0.05f, 0.05f, 0.05f, 1.0f));
    m_Light->SetDiffuseColor(XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f));
    m_Light->SetDirection(XMFLOAT3(-0.5f, -1.0f, 0.0f));
 
    // frustum 객체를 생성합니다.
    m_Frustum = new FrustumClass;
    if(!m_Frustum)
    {
        return false;
    }
 
    // 쿼드 트리 객체를 생성합니다.
    m_QuadTree = new QuadTreeClass;
    if(!m_QuadTree)
    {
        return false;
    }
 
    // 쿼드 트리 객체를 초기화 합니다.
    result = m_QuadTree->Initialize(m_Terrain, m_Direct3D->GetDevice());
    if(!result)
    {
        MessageBox(hwnd, L"Could not initialize the quad tree object.", L"Error", MB_OK);
        return false;
    }
    
    return true;
}
 
 
void ApplicationClass::Shutdown()
{
    // 쿼드 트리 객체를 해제합니다.
    if(m_QuadTree)
    {
        m_QuadTree->Shutdown();
        delete m_QuadTree;
        m_QuadTree = 0;
    }
 
    // frustum 객체를 해제합니다.
    if(m_Frustum)
    {
        delete m_Frustum;
        m_Frustum = 0;
    }
 
    // 조명 객체를 해제합니다.
    if(m_Light)
    {
        delete m_Light;
        m_Light = 0;
    }
 
    // 지형 쉐이더 객체를 해제합니다.
    if(m_TerrainShader)
    {
        m_TerrainShader->Shutdown();
        delete m_TerrainShader;
        m_TerrainShader = 0;
    }
 
    // 텍스트 객체를 해제합니다.
    if(m_Text)
    {
        m_Text->Shutdown();
        delete m_Text;
        m_Text = 0;
    }
 
    // 폰트 쉐이더 객체를 해제합니다..
    if(m_FontShader)
    {
        m_FontShader->Shutdown();
        delete m_FontShader;
        m_FontShader = 0;
    }
 
    // cpu 객체를 해제합니다.
    if(m_Cpu)
    {
        m_Cpu->Shutdown();
        delete m_Cpu;
        m_Cpu = 0;
    }
 
    // fps 객체를 해제합니다.
    if(m_Fps)
    {
        delete m_Fps;
        m_Fps = 0;
    }
 
    // 위치 객체를 해제합니다.
    if(m_Position)
    {
        delete m_Position;
        m_Position = 0;
    }
 
    // 타이머 객체를 해제합니다.
    if(m_Timer)
    {
        delete m_Timer;
        m_Timer = 0;
    }
 
    // 지형 객체를 해제합니다.
    if(m_Terrain)
    {
        m_Terrain->Shutdown();
        delete m_Terrain;
        m_Terrain = 0;
    }
 
    // 카메라 객체를 해제합니다.
    if(m_Camera)
    {
        delete m_Camera;
        m_Camera = 0;
    }
 
    // D3D 객체를 해제합니다.
    if (m_Direct3D)
    {
        m_Direct3D->Shutdown();
        delete m_Direct3D;
        m_Direct3D = 0;
    }
 
    // 입력 객체를 해제합니다.
    if(m_Input)
    {
        m_Input->Shutdown();
        delete m_Input;
        m_Input = 0;
    }
}
 
 
bool ApplicationClass::Frame()
{
    // 사용자 입력을 읽습니다.
    bool result = m_Input->Frame();
    if(!result)
    {
        return false;
    }
    
    // 사용자가 ESC를 눌렀을 때 응용 프로그램을 종료 할 것인지 확인합니다.
    if(m_Input->IsEscapePressed() == true)
    {
        return false;
    }
 
    // 시스템 통계를 업데이트 합니다.
    m_Timer->Frame();
    m_Fps->Frame();
    m_Cpu->Frame();
 
    // 텍스트 개체에서 FPS 값을 업데이트 합니다.
    result = m_Text->SetFps(m_Fps->GetFps(), m_Direct3D->GetDeviceContext());
    if(!result)
    {
        return false;
    }
    
    // 텍스트 개체의 CPU 사용값을 업데이트 합니다.
    result = m_Text->SetCpu(m_Cpu->GetCpuPercentage(), m_Direct3D->GetDeviceContext());
    if(!result)
    {
        return false;
    }
 
    // 프레임 입력 처리를 수행합니다.
    result = HandleInput(m_Timer->GetTime());
    if(!result)
    {
        return false;
    }
 
    // 그래픽을 렌더링 합니다.
    result = RenderGraphics();
    if(!result)
    {
        return false;
    }
 
    return result;
}
 
 
bool ApplicationClass::HandleInput(float frameTime)
{
    XMFLOAT3 pos = XMFLOAT3(0.0f, 0.0f, 0.0f);
    XMFLOAT3 rot = XMFLOAT3(0.0f, 0.0f, 0.0f);
 
 
    // 갱신된 위치를 계산하기 위한 프레임 시간을 설정합니다.
    m_Position->SetFrameTime(frameTime);
 
    // 입력을 처리합니다.
    m_Position->TurnLeft(m_Input->IsLeftPressed());
    m_Position->TurnRight(m_Input->IsRightPressed());
    m_Position->MoveForward(m_Input->IsUpPressed());
    m_Position->MoveBackward(m_Input->IsDownPressed());
    m_Position->MoveUpward(m_Input->IsAPressed());
    m_Position->MoveDownward(m_Input->IsZPressed());
    m_Position->LookUpward(m_Input->IsPgUpPressed());
    m_Position->LookDownward(m_Input->IsPgDownPressed());
    
    // 시점 위치 / 회전을 가져옵니다.
    m_Position->GetPosition(pos);
    m_Position->GetRotation(rot);
 
    // 카메라의 위치를 ​​설정합니다.
    m_Camera->SetPosition(pos);
    m_Camera->SetRotation(rot);
 
    // 텍스트 개체의 위치 값을 업데이트 합니다.
    if(!m_Text->SetCameraPosition(pos, m_Direct3D->GetDeviceContext()))
    {
        return false;
    }
 
    // 텍스트 객체의 회전 값을 업데이트 합니다.
    if(!m_Text->SetCameraRotation(rot, m_Direct3D->GetDeviceContext()))
    {
        return false;
    }
 
    return true;
}
 
 
bool ApplicationClass::RenderGraphics()
{
    XMMATRIX worldMatrix, viewMatrix, projectionMatrix, orthoMatrix;
 
    // 장면을 지웁니다.
    m_Direct3D->BeginScene(0.0f, 0.0f, 0.0f, 1.0f);
 
    // 카메라의 위치에 따라 뷰 행렬을 생성합니다.
    m_Camera->Render();
 
    // 카메라 및 Direct3D 객체에서 월드, 뷰, 투영 및 ortho 행렬을 가져옵니다.
    m_Direct3D->GetWorldMatrix(worldMatrix);
    m_Camera->GetViewMatrix(viewMatrix);
    m_Direct3D->GetProjectionMatrix(projectionMatrix);
    m_Direct3D->GetOrthoMatrix(orthoMatrix);
 
    // 절두체를 만듭니다.
    m_Frustum->ConstructFrustum(SCREEN_DEPTH, projectionMatrix, viewMatrix);
 
    // 렌더링에 사용할 터 레인 셰이더 매개 변수를 설정합니다.
    if(!m_TerrainShader->SetShaderParameters(m_Direct3D->GetDeviceContext(), worldMatrix, viewMatrix, projectionMatrix,
 m_Light->GetAmbientColor(), m_Light->GetDiffuseColor(), m_Light->GetDirection(), m_Terrain->GetTexture()))
    {
        return false;
    }
 
    // 쿼드 트리 및 지형 셰이더를 사용하여 지형을 렌더링합니다.
    m_QuadTree->Render(m_Frustum, m_Direct3D->GetDeviceContext(), m_TerrainShader);
 
    // 일부가 제거 된 이후에 렌더링 된 터 레인 삼각형의 수를 설정합니다.
    if(!m_Text->SetRenderCount(m_QuadTree->GetDrawCount(), m_Direct3D->GetDeviceContext()))
    {
        return false;
    }
 
    // 모든 2D 렌더링을 시작하려면 Z 버퍼를 끕니다.
    m_Direct3D->TurnZBufferOff();
        
    // 텍스트를 렌더링하기 전에 알파 블렌딩을 켭니다.
    m_Direct3D->TurnOnAlphaBlending();
 
    // 텍스트 사용자 인터페이스 요소를 렌더링 합니다.
    if(!m_Text->Render(m_Direct3D->GetDeviceContext(), m_FontShader, worldMatrix, orthoMatrix))
    {
        return false;
    }
 
    // 텍스트를 렌더링 한 후 알파 블렌딩을 끕니다.
    m_Direct3D->TurnOffAlphaBlending();
 
    // 모든 2D 렌더링이 완료되었으므로 Z 버퍼를 다시 켭니다.
    m_Direct3D->TurnZBufferOn();
 
    // 렌더링 된 장면을 화면에 표시합니다.
    m_Direct3D->EndScene();
 
    return true;
}
cs



출력 화면




마치면서


이제 지형의 보이는 부분만 렌더링되고 나머지는 쿼드 트리를 사용하여 도려냅니다. 렌더링 된 삼각형의 갯수도 표시됩니다.



연습문제


1. 프로그램을 컴파일하고 실행하십시오. 지형을 따라 이동할때 지형의 가시적인 삼각형만 그려지기 때문에 렌더링 횟수가 줄어듭니다.


2. 렌더 횟수를 렌더 / 컬 비율로 변경하십시오.


3. 튜토리얼 상단의 그림과 같이 개별 선을 나타내는 노란색 선을 그리는 DebugTree 객체를 만듭니다.


4. 전역 변수값인 MAX_TRIANGLES 을 수정하십시오.


5. oct 나무, BSP 나무 및 포털과 같은 공간 분할의 다른 방법을 수정해서 적용해 보십시오.



소스코드


소스코드 : Dx11Terrain_05.zip