Visual Studio 2022에서 작성하였습니다.

 

해당글은 다음 블로그를 참조하였습니다.

http://www.rastertek.com/tutdx11.html

https://ppparkje.tistory.com/category/%EA%B0%95%EC%A2%8C%EB%B2%88%EC%97%AD/DirectX%2011?page=2 
https://copynull.tistory.com/category/DirectX%2011/Basic

 

 

Tutorial-1 에 이어서 작성하였음.

 

<D3dclass.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
#pragma once
 
#ifndef _D3DCLASS_H_
#define _D3DCLASS_H_
 
class D3DClass
{
public:
    D3DClass();
    D3DClass(const D3DClass&);
    ~D3DClass();
 
    bool Initialize(int screenWidth, int screenHeight, bool vsync, HWND hwnd, bool fullscreen, float screenDepth, float screenNear);
    void Shutdown();
 
 
    void BeginScene(float red, float green, float blue, float alpha);
    void EndScene();
 
    ID3D11Device* GetDevice();
    ID3D11DeviceContext* GetDeviceContext();
 
    void GetProjectionMatrix(XMMATRIX& projectionMatrix);
    void GetWorldMatrix(XMMATRIX& worldMatrix);
    void GetOrthoMatrix(XMMATRIX& orthoMatrix);
 
    void GetVideoCardInfo(char* cardname, int& memory);
 
private:
    bool m_vsync_enabled = false;
    int m_videoCardMemory = 0;
    char m_videoCardDescription[128= { 0, };
    IDXGISwapChain* m_swapChain = nullptr;
    ID3D11Device* m_device = nullptr;
    ID3D11DeviceContext* m_deviceContext = nullptr;
    ID3D11RenderTargetView* m_renderTargetView = nullptr;
    ID3D11Texture2D* m_depthStencilBuffer = nullptr;
    ID3D11DepthStencilState* m_depthStencilState = nullptr;
    ID3D11DepthStencilView* m_depthStencilView = nullptr;
    ID3D11RasterizerState* m_rasterState = nullptr;
    XMMATRIX m_projectionMatrix;
    XMMATRIX m_worldMatrix;
    XMMATRIX m_orthoMatrix;
 
};
 
 
 
 
 
#endif // _D3DCLASS_H_
cs

<D3dclass.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
#include "stdafx.h"
#include "D3dclass.h"
 
#include <iostream>
 
D3DClass::D3DClass()
{
}
 
D3DClass::D3DClass(const D3DClass&)
{
}
 
D3DClass::~D3DClass()
{
}
 
bool D3DClass::Initialize(int screenWidth, int screenHeight, bool vsync, HWND hwnd, bool fullscreen, float screenDepth, float screenNear)
{
 
    // 수직동기화 상태를 저장한다.
    m_vsync_enabled = vsync;
 
    // DirectX 그래픽 인터페이스 팩토리를 생성한다.
    IDXGIFactory* factory = nullptr;
    if (FAILED(CreateDXGIFactory(__uuidof(IDXGIFactory), reinterpret_cast<void**>(&factory))))
    {
        return false;
    }
 
 
    // 팩토리 객체를 사용하여 첫번째 그래픽 카드 인터페이스 어뎁터를 생성한다.
    IDXGIAdapter* adapter = nullptr;
    if (FAILED(factory->EnumAdapters(0&adapter)))  // 0 은 첫번째 그래픽카드 // 컴퓨터에 따라 0번이 내장 그래픽일수 도 있고 외장일 수 도 있다.
    {
        return false;
    }
 
    // 출력(모니터)에 대한 첫번째 어뎁터를 지정한다.
    IDXGIOutput* adapterOutput = nullptr;
    if (FAILED(adapter->EnumOutputs(0&adapterOutput)))
    {
        return false;
    }
 
    // 출력(모니터)에 대한 DXGI_FORMAT_R8G8B8A8_UNORM 표시 형식에 맞는 모드수를 가져옵니다.
    unsigned int numModes = 0;
    if (FAILED(adapterOutput->GetDisplayModeList(DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL)))
    {
        return false;
    }
 
    // 가능한 모든 모니터와 그래픽카드 조합을 저장할 리스트를 생성한다.
    DXGI_MODE_DESC* displayModeList = new DXGI_MODE_DESC[numModes];
    if (!displayModeList)
    {
        return false;
    }
 
    // 이제 디스플레이 모드에 대한 리스트를 채운다.
    if (FAILED(adapterOutput->GetDisplayModeList(DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList)))
    {
        return false;
    }
 
 
    // 이제 모든 디스플레이 모드에 대해 화면 너비/높이에 맞는 디스플레이 모드를 찾는다.
    // 적합한 것을 찾으면 모니터의 새로고침 비율의 분모와 분자값을 저장한다.
    unsigned int numerator = 0;
    unsigned int denominator = 0;
    for (unsigned int i = 0; i < numModes; i++)
    {
        if (displayModeList[i].Width == static_cast<unsigned>(screenWidth))
        {
            if (displayModeList[i].Height == static_cast<unsigned>(screenHeight))
            {
                numerator = displayModeList[i].RefreshRate.Numerator;
                denominator = displayModeList[i].RefreshRate.Denominator;
            }
        }
    }
 
    // 비디오카드의 구조체를 얻는다.
    DXGI_ADAPTER_DESC adapterDesc;
    if (FAILED(adapter->GetDesc(&adapterDesc)))
    {
        return false;
    }
 
    // 비디오카드 메모리 용량 단위를 메가바이트 단위로 저장한다.
    m_videoCardMemory = static_cast<int>(adapterDesc.DedicatedVideoMemory / 1024 / 1024);
 
 
    // 비디오카드의 이름을 저장합니다.
    size_t stringLength = 0;
    if (wcstombs_s(&stringLength, m_videoCardDescription, 128, adapterDesc.Description, 128!= 0)
    {
        return false;
    }
 
 
    // 그래픽 카드 확인 용도.
    const WCHAR* pwcsName; //LPCWSTR
 
    // required size
    int size = MultiByteToWideChar(CP_ACP, 0, m_videoCardDescription, -1NULL0);
    // allocate it
    pwcsName = new WCHAR[stringLength];
    MultiByteToWideChar(CP_ACP, 0, m_videoCardDescription, -1, (LPWSTR)pwcsName, size);
    // use it....
 
    OutputDebugString(pwcsName);
    // delete it
    delete[] pwcsName;
    
    
 
    // 디스플레이 모드 리스트를 해제한다.
    delete[] displayModeList;
    displayModeList = nullptr;
 
    // 출력 어뎁터를 해제한다.
    adapterOutput->Release();
    adapterOutput = nullptr;
 
    // 어뎁터를 해제한다.
    adapter->Release();
    adapter = nullptr;
 
 
    // 스왑체인 구조체를 초기환한다.
    DXGI_SWAP_CHAIN_DESC swapChainDesc;
    ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));
 
    // 백버퍼를 1개만 사용하도록 지정한다.
    swapChainDesc.BufferCount = 1;
 
    // 백버퍼의 넓이와 높이를 지정한다.
    swapChainDesc.BufferDesc.Width = screenWidth;
    swapChainDesc.BufferDesc.Height = screenHeight;
 
    // 33bit 서피스를 설정한다.
    swapChainDesc.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
 
    // 백버퍼의 새로고침 비율을 설정한다.
    if (m_vsync_enabled)
    {
        swapChainDesc.BufferDesc.RefreshRate.Numerator = numerator;
        swapChainDesc.BufferDesc.RefreshRate.Denominator = denominator;
    }
    else
    {
        swapChainDesc.BufferDesc.RefreshRate.Numerator = 0;
        swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
    }
 
 
    // 백버퍼의 사용용도를 지정한다.
    swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
 
    // 랜더링에 사용될 윈도우 핸들을 지정한다.
    swapChainDesc.OutputWindow = hwnd;
 
    // 멀티샘플링을 끈다.
    swapChainDesc.SampleDesc.Count = 1;
    swapChainDesc.SampleDesc.Quality = 0;
 
    // 창모드 or 풀스크린 모드를 설정한다.
    if (fullscreen)
    {
        swapChainDesc.Windowed = false;
    }
    else
    {
        swapChainDesc.Windowed = true;
    }
 
    // 스캔 라인 순서 및 크기를 지정하지 않음으로 설정한다.
    swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
    swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
 
    // 출력된 다음 백버퍼를 비우도록 지정한다.
    swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
 
    // 추가 옵션 플래그를 사용하지 않는다.
    swapChainDesc.Flags = 0;
 
    // 피처레벨을 DirectX11로 설정한다.
    D3D_FEATURE_LEVEL featureLevel = D3D_FEATURE_LEVEL_11_0;
 
    // 스왑 체인, Direct3D 장치 및 Direct3D 장치 컨텍스트를 만든다.
    if (FAILED(D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL0&featureLevel, 1,
        D3D11_SDK_VERSION, &swapChainDesc, &m_swapChain, &m_device, NULL&m_deviceContext)))
    {
        return false;
    }
 
 
    // 백버퍼 포인터를 얻어온다.
    ID3D11Texture2D* backBufferPtr = nullptr;
    if (FAILED(m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D),reinterpret_cast<LPVOID*>(&(backBufferPtr)))))
    {
        return false;
    }
 
 
    // 백 버퍼 포인터로 랜더 타겟 뷰를 생성한다.
    if(FAILED(m_device->CreateRenderTargetView(backBufferPtr, NULL&m_renderTargetView)))
    {
        return false;
    }
 
 
    // 백버퍼 포인터를 해제한다.
    backBufferPtr->Release();
    backBufferPtr = nullptr;
 
 
    // 깊이 버퍼 구조체를 초기화 합니다.
    D3D11_TEXTURE2D_DESC depthBufferDesc;
    ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));
 
    // 깊이 버퍼 구조체를 작성합니다.
    depthBufferDesc.Width = screenWidth;
    depthBufferDesc.Height = screenHeight;
    depthBufferDesc.MipLevels = 1;
    depthBufferDesc.ArraySize = 1;
    depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
    depthBufferDesc.SampleDesc.Count = 1;
    depthBufferDesc.SampleDesc.Quality = 0;
    depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
    depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
    depthBufferDesc.CPUAccessFlags = 0;
    depthBufferDesc.MiscFlags = 0;
 
    // 설정된 깊이버퍼 구조체를 사용하여 깊이 버퍼 텍스쳐를 생성한다.
    if (FAILED(m_device->CreateTexture2D(&depthBufferDesc, NULL& m_depthStencilBuffer)))
    {
        return false;
    }
 
    // 스텐실 상태 구조체를 초기화 합니다.
    D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
    ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));
 
    // 스텐실 상태 구조체를 작성합니다.
    depthStencilDesc.DepthEnable = true;
    depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
    depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
 
    depthStencilDesc.StencilEnable = true;
    depthStencilDesc.StencilReadMask = 0xFF;
    depthStencilDesc.StencilWriteMask = 0xFF;
 
    // 픽셀 정면의 스텐실 설정입니다.
    depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
    depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
    depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
    depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
 
    // 픽셀 뒷면의 스텐실 설정입니다.
    depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
    depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
    depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
    depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
 
    // 깊이 스텐실 상태를 설정합니다.
    m_deviceContext->OMSetDepthStencilState(m_depthStencilState, 1);
 
 
    // 깊이 스텐실 뷰의 구조체를 초기화합니다.
    D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
    ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));
 
    // 깊이 스텐실 뷰 구조체를 설정한다.
    depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
    depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
    depthStencilViewDesc.Texture2D.MipSlice = 0;
 
    // 깊이 스텐실 뷰를 생성한다.
    if(FAILED(m_device->CreateDepthStencilView(m_depthStencilBuffer, &depthStencilViewDesc, &m_depthStencilView)))
    {
        return false;
    }
 
    // 랜더링 대상 뷰와 깊이 스텐실 버퍼를  출력 렌더 파이프 라인에 바인딩 한다.
    m_deviceContext->OMSetRenderTargets(1&m_renderTargetView, m_depthStencilView);
 
    // 그려지는 폴리곤과 방법을 결정할 레스터 구조체를 설정한다.
    D3D11_RASTERIZER_DESC rasterDesc;
    rasterDesc.AntialiasedLineEnable = false;
    rasterDesc.CullMode = D3D11_CULL_BACK;
    rasterDesc.DepthBias = 0;
    rasterDesc.DepthBiasClamp = 0.0f;
    rasterDesc.DepthClipEnable = true;
    rasterDesc.FillMode = D3D11_FILL_SOLID;
    rasterDesc.FrontCounterClockwise = false;
    rasterDesc.MultisampleEnable = false;
    rasterDesc.ScissorEnable = false;
    rasterDesc.SlopeScaledDepthBias = 0.0f;
 
    // 방금 작성한 구조체에서 레스터 라이저 상태를 만든다.
    if (FAILED(m_device->CreateRasterizerState(&rasterDesc, &m_rasterState)))
    {
        return false;
    }
 
    // 이제 레스터 라이저 상태를 설정한다.
    m_deviceContext->RSSetState(m_rasterState);
 
    // 렌더링을 위해 뷰포트를 설정한다.
    D3D11_VIEWPORT viewport;
    viewport.Width = static_cast<float>(screenWidth);
    viewport.Height = static_cast<float>(screenHeight);
    viewport.MinDepth = 0.0f;
    viewport.MaxDepth = 1.0f;
    viewport.TopLeftX = 0.0f;
    viewport.TopLeftY = 0.0f;
 
    // 뷰포트를 생성한다.
    m_deviceContext->RSSetViewports(1&viewport);
 
    // 투영 행렬을 설정한다.
    float fieldOfView = 3.141592654 / 4.0f;
    float screenAspect = static_cast<float>(screenWidth) / static_cast<float>(screenHeight);
 
    // 3D 렌더링을 위핸 투영 행렬을 만든다.
    m_projectionMatrix = XMMatrixPerspectiveFovLH(fieldOfView, screenAspect, screenNear, screenDepth);
 
    // 세계 행렬을 항동 행렬로 초기화 한다.
    m_worldMatrix = XMMatrixIdentity();
 
    // 2D렌더링을위한 직교 투영 행렬을 만든다.
    m_orthoMatrix = XMMatrixOrthographicLH(static_cast<float>(screenWidth), static_cast<float>(screenHeight), screenNear, screenDepth);
 
    return true;
}
 
void D3DClass::Shutdown()
{
    // 종료하기 전에 이렇게 윈도우 모드로 바꾸지 않으면 스왑체인을 할당 해제할 때 예외가 발생합니다.
    if (m_swapChain)
    {
        m_swapChain->SetFullscreenState(false, nullptr);
    }
 
    if (m_rasterState)
    {
        m_rasterState->Release();
        m_rasterState = nullptr;
    }
 
    if (m_depthStencilView)
    {
        m_depthStencilView->Release();
        m_depthStencilView = nullptr;
    }
 
    if (m_depthStencilState)
    {
        m_depthStencilState->Release();
        m_depthStencilState = nullptr;
    }
 
    if (m_depthStencilBuffer)
    {
        m_depthStencilBuffer->Release();
        m_depthStencilBuffer = nullptr;
    }
 
    if (m_renderTargetView)
    {
        m_renderTargetView->Release();
        m_renderTargetView = nullptr;
    }
 
    if (m_deviceContext)
    {
        m_deviceContext->Release();
        m_deviceContext = nullptr;
    }
 
    if (m_device)
    {
        m_device->Release();
        m_device = nullptr;
    }
 
    if (m_swapChain)
    {
        m_swapChain->Release();
        m_swapChain = nullptr;
    }
 
}
 
void D3DClass::BeginScene(float red, float green, float blue, float alpha)
{
 
    // 버퍼를 지울 색을 설정한다.
    float color[4= { red, green, blue, alpha };
 
    // 백버퍼를 지운다.
    m_deviceContext->ClearRenderTargetView(m_renderTargetView, color);
 
    // 깊이 버퍼를 지운다.
    m_deviceContext->ClearDepthStencilView(m_depthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0);
}
 
void D3DClass::EndScene()
{
    // 렌더링이 완료되었으므로 화면에 백 버퍼를 표시한다.
    if(m_vsync_enabled)
    {
        // 화면 새로 고침 비율을 고정한다.
        m_swapChain->Present(10);
    }
    else
    {
        // 가능한 빠르게 출력한다.
        m_swapChain->Present(00);
    }
}
 
ID3D11Device* D3DClass::GetDevice()
{
    return m_device;
}
 
ID3D11DeviceContext* D3DClass::GetDeviceContext()
{
    return m_deviceContext;
}
 
void D3DClass::GetProjectionMatrix(XMMATRIX& projectionMatrix)
{
    // 이번 예제에서는 사용 안함.
    projectionMatrix = m_projectionMatrix;
}
 
void D3DClass::GetWorldMatrix(XMMATRIX& worldMatrix)
{
    // 이번 예제에서는 사용 안함.
    worldMatrix = m_worldMatrix;
}
 
void D3DClass::GetOrthoMatrix(XMMATRIX& orthoMatrix)
{
    // 이번 예제에서는 사용 안함.
    orthoMatrix = m_orthoMatrix;
}
 
void D3DClass::GetVideoCardInfo(char* cardname, int& memory)
{
    strcpy_s(cardname, 128, m_videoCardDescription);
    memory = m_videoCardMemory;
}
 
cs

 

<graphicalclass.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
#pragma once
#ifndef _GRAPHICSCLASS_H_
#define _GRAPHICSCLASS_H_
 
// 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 GraphicsClass
{
public:
    GraphicsClass();
    GraphicsClass(const GraphicsClass& other);
    ~GraphicsClass();
 
 
    bool Initialize(int screenWidth, int screenHeight, HWND hwnd);
    void Shutdown();
    bool Frame();
 
private:
    bool Render();
 
private:
    D3DClass* m_D3D;
};
 
#endif // _GRAPHICSCLASS_H_
cs

<graphicalclass.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
#include "stdafx.h"
#include "graphicsclass.h"
#include "D3dclass.h"
 
GraphicsClass::GraphicsClass()
{
    m_D3D = nullptr;
}
 
GraphicsClass::GraphicsClass(const GraphicsClass& other)
{
}
 
GraphicsClass::~GraphicsClass()
{
}
 
bool GraphicsClass::Initialize(int screenWidth, int screenHeight, HWND hwnd)
{
    // Direct3D 객체 생성
    m_D3D = new D3DClass;
    if (!m_D3D)
    {
        return false;
    }
 
    // Direct3D 객체를 초기화 한다.
    if (!m_D3D->Initialize(screenWidth, screenHeight, VSYNC_ENABLED, hwnd, FULL_SCREEN, SCREEN_DEPTH, SCREEN_NEAR))
    {
        return false;
    }
 
    return true;
}
 
void GraphicsClass::Shutdown()
{
    // D3D 객체를 반환합니다.
    if (m_D3D)
    {
        m_D3D->Shutdown();
        delete m_D3D;
        m_D3D = nullptr;
    }
}
 
bool GraphicsClass::Frame()
{
 
    //그래픽 렌더링을 수행합니다.
    if (!Render())
    {
        return false;
    }
    return true;
}
 
bool GraphicsClass::Render()
{
    // 씬 그리기를 시작하기 위해 버퍼의 내용을 지웁니다.
    m_D3D->BeginScene(1.0f, 1.0f, 0.0f, 1.0f);
 
    // 버퍼에 그려진 씬을 화면에 표시합니다.
    m_D3D->EndScene();
 
    return true;
}
 
cs

 

<DxDefine.h>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#pragma once
#pragma once
 
// 라이브러리 링크
#pragma comment(lib, "d3d11.lib")
#pragma comment(lib, "dxgi.lib")
#pragma comment(lib, "d3dcompiler.lib")
 
 
// include
#include <d3d11.h>
#include <d3dcompiler.h>
#include <directxmath.h>
using namespace DirectX;
 
 
cs

 

<결과>

 

 

<소스코드>

https://github.com/woonhak-kong/DirectX_11_Tutorial/releases/tag/Tutorial_2

 

Visual Studio 2022에서 작성하였습니다.

 

 

해당글은 다음 블로그를 참조하였습니다.

http://www.rastertek.com/tutdx11.html

https://ppparkje.tistory.com/category/%EA%B0%95%EC%A2%8C%EB%B2%88%EC%97%AD/DirectX%2011?page=2 

https://copynull.tistory.com/category/DirectX%2011/Basic

<main.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
#include "stdafx.h"
#include "systemclass.h"
 
 
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pScmdline, int iCmdShow)
{
    SystemClass* System;
    bool result;
 
    // System 객체 생성
    System = new SystemClass;
    if(!System)
    {
        return 0;
    }
 
    // system 객체 초기화하고 run을 호출한다.
    result = System->Initialize();
    if(result)
    {
        System->Run();
    }
 
    // system 객체를 종료하고 메모리를 반환한다.
    System->Shutdown();
    delete System;
    System = nullptr;
 
    return 0;
}
cs

<systemclass.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
#pragma once
#ifndef _SYSTEMCLASS_H_
#define _SYSTEMCLASS_H_
 
 
//#include <windows.h>
 
#include "inputclass.h"
#include "graphicsclass.h"
 
class SystemClass
{
public:
    SystemClass();
    SystemClass(const SystemClass&);
    ~SystemClass();
 
    bool Initialize();
    void Shutdown();
    void Run();
 
    LRESULT CALLBACK MessageHandler(HWND, UINT, WPARAM, LPARAM);
 
 
private:
    bool Frame();
    void InitializeWindows(int&int&);
    void ShutdownWindows();
 
 
private:
    LPCWSTR m_applicationName;
    HINSTANCE m_hinstance;
    HWND m_hwnd;
 
    InputClass* m_Input;
    GraphicsClass* m_Graphics;
    
};
 
static LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
 
static SystemClass* ApplicationHandle = 0;
 
 
 
 
#endif
 
cs

<systemclass.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
#include "stdafx.h"
#include "systemclass.h"
 
SystemClass::SystemClass()
{
    m_Input = nullptr;
    m_Graphics = nullptr;
}
 
SystemClass::SystemClass(const SystemClass&)
{
}
 
SystemClass::~SystemClass()
{
}
 
bool SystemClass::Initialize()
{
    int screenWidth, screenHeight;
    bool result;
 
    // 함수에 높이와 너비를 전달하기 전에 변수를 0으로 초기화한다.
    screenWidth = 0;
    screenHeight = 0;
 
    // 윈도우즈 api를 사용하여 초기화한다.
    InitializeWindows(screenWidth, screenHeight);
 
    // input 객체를 생성한다.
    // 이 객체는 유저로부터 들어오는 키보드 입력을 처리하기위해 사용된다.
    m_Input = new InputClass;
    if (!m_Input)
    {
        return false;
    }
 
    // Input 객체를 초기화한다.
    m_Input->Initialize();
 
    // graphics 객체를 생성한다.
    // 이 객체는 이 어플리케이션의 모든 그래픽 요소를 그리는 일을 한다.
    m_Graphics = new GraphicsClass;
    if (!m_Graphics)
    {
        return false;
    }
 
    // graphics 객체를 초기화 한다.
    result = m_Graphics->Initialize(screenWidth, screenHeight, m_hwnd);
    if (!result)
    {
        return false;
    }
 
    return true;
}
 
void SystemClass::Shutdown()
{
 
    // Graphics 객체를 반환합니다.
    if (m_Graphics)
    {
        m_Graphics->Shutdown();
        delete m_Graphics;
        m_Graphics = nullptr;
    }
 
    // Input 객체를 반환합니다.
    if (m_Input)
    {
        delete m_Input;
        m_Input = nullptr;
    }
 
    // 창을 종료시킵니다.
    ShutdownWindows();
    return;
}
 
void SystemClass::Run()
{
    MSG msg;
    bool done, result;
 
    // 메세지 구조체를 초기화합니다.
    ZeroMemory(&msg, sizeof(MSG));
 
    // 유저로부터 종료 메시지를 받을 때까지 루프를 돈다.
    done = false;
    while (!done)
    {
        // 윈도우 메시지를 처리합니다.
        if (PeekMessage(&msg, nullptr, 00, PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
 
        // 윈도우에서 어플리케이션의 종료를 요청하는 경우 빠져나갑니다.
        if (msg.message == WM_QUIT)
        {
            done = true;
        }
        else
        {
            // 그 외에는 Frame 함수를 처리합니다.
            result = Frame();
            if (!result)
            {
                done = true;
            }
        }
    }
}
 
LRESULT SystemClass::MessageHandler(HWND hwnd, UINT umsg, WPARAM wparam, LPARAM lparam)
{
    switch (umsg)
    {
        // 키보드키가 눌렸는지 확인
        case WM_KEYDOWN:
        {
            m_Input->KeyDown(static_cast<unsigned int>(wparam));
            return 0;
        }
 
        // 키보드의 눌린 키가 떼어졌는지 확인
        case WM_KEYUP:
        {
            // 키가 떼어졌다면 input 객체에 이 사실을 전달하여 이 키를 해제토록 한다.
            m_Input->KeyUp(static_cast<unsigned int>(wparam));
            return 0;
        }
 
        // 다른 메세지들은 사용하지 않으므로 기본 메세지 처리기에 전달
        default:
        {
            return DefWindowProc(hwnd, umsg, wparam, lparam);
        }
    }
}
 
bool SystemClass::Frame()
{
 
    bool result;
 
    // 유저가 Esc키를 누를시 종료.
    if (m_Input->IsKeyDown(VK_ESCAPE))
    {
        return false;
    }
 
    // graphics 객체의 작업을 처리합니다.
    result = m_Graphics->Frame();
    if (!result)
    {
        return false;
    }
 
    return true;
}
 
void SystemClass::InitializeWindows(int& screenWidth, int& screenHeight)
{
    WNDCLASSEX wc;
    DEVMODE dmScreenSettings;
    int posX, posY;
 
    // 외부 포인터를 이 객체로 설정
    ApplicationHandle = this;
 
    // 이 어플리케이션의 인스턴스 가져오기.
    m_hinstance = GetModuleHandle(nullptr);
 
    // 엎플리케이션의 이름 설정
    m_applicationName = L"Engine";
 
    // 윈도우 클래스를 기본 설정으로 설정.
    wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
    wc.lpfnWndProc = WndProc;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hInstance = m_hinstance;
    wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
    wc.hIconSm = wc.hIcon;
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
    wc.lpszMenuName = NULL;
    wc.lpszClassName = m_applicationName;
    wc.cbSize = sizeof(WNDCLASSEX);
 
    // 윈도우 클래스 등록
    RegisterClassEx(&wc);
 
    // 모니터 화면의 해상도 가져오기
    screenWidth = GetSystemMetrics(SM_CXSCREEN);
    screenHeight = GetSystemMetrics(SM_CYSCREEN);
 
    if (FULL_SCREEN)
    {
        memset(&dmScreenSettings, 0sizeof(dmScreenSettings));
        dmScreenSettings.dmSize = sizeof(dmScreenSettings);
        dmScreenSettings.dmPelsWidth = static_cast<unsigned long>(screenWidth);
        dmScreenSettings.dmPelsHeight = static_cast<unsigned long>(screenHeight);
        dmScreenSettings.dmBitsPerPel = 32;
        dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
 
        // 풀스크린에 맞는 디스플레이 설정을 합니다.
        ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN);
 
        // 윈도우의 위치를 화면의 왼쪽 위로 맞춥니다.
        posX = posY = 0;
 
    }
    else
    {
        // 윈도우 모드라면 800X600으로 크기 설정
        screenWidth = 800;
        screenHeight = 600;
 
        // 창을 모니터의 중앙에 오도록 설정
        posX = (GetSystemMetrics(SM_CXSCREEN) - screenWidth) / 2;
        posY = (GetSystemMetrics(SM_CYSCREEN) - screenHeight) / 2;
    }
 
    // 설정한 것을 가지고 창을 만들고 그 핸들을 가져옵니다.
    m_hwnd = CreateWindowEx(WS_EX_APPWINDOW, m_applicationName, m_applicationName,
        WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_POPUP,
        posX, posY, screenWidth, screenHeight, nullptr, nullptr, m_hinstance, nullptr);
 
    // 윈도우를 화면에 표시하고 포커스를 줍니다.
    ShowWindow(m_hwnd, SW_SHOW);
    SetForegroundWindow(m_hwnd);
    SetFocus(m_hwnd);
 
    // 마우스 커서 표시하지 않기
    ShowCursor(false);
 
    return;
 
}
 
void SystemClass::ShutdownWindows()
{
    // 마우스 커서를 표시합니다.
    ShowCursor(true);
 
    // 풀스크린 모드를 빠져나올 때 디스플레이 설정을 바꿉니다.
    if (FULL_SCREEN)
    {
        ChangeDisplaySettings(nullptr, 0);
    }
 
    // 창을 제거합니다.
    DestroyWindow(m_hwnd);
    m_hwnd = nullptr;
 
    // 어플리케이션 인스턴스를 제거한다.
    UnregisterClass(m_applicationName, m_hinstance);
    m_hinstance = nullptr;
 
    // 이 클래스에 대한 외부포인터 참조를 제거
    ApplicationHandle = nullptr;
 
}
 
LRESULT WndProc(HWND hwnd, UINT umessage, WPARAM wparam, LPARAM lparam)
{
    switch (umessage)
    {
        // 윈도우가 제거되었는지 확인
        case WM_DESTROY:
        {
            PostQuitMessage(0);
            return 0;
        }
 
        // 윈도우가 닫히는지 확인한다.
        case WM_CLOSE:
        {
            PostQuitMessage(0);
        }
 
        // 다른 모든 메세지들은 system 클래스의 메세지 처리기에 전달합니다.
        default:
        {
            return ApplicationHandle->MessageHandler(hwnd, umessage, wparam, lparam);
        }
    }
}
 
cs

 

<graphicsclass.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
#pragma once
#ifndef _GRAPHICSCLASS_H_
#define _GRAPHICSCLASS_H_
 
// GLOBALS //
const bool FULL_SCREEN = false;
const bool VSYNC_ENABLED = true;
const float SCREEN_DEPTH = 1000.0f;
const float SCREEN_NEAR = 0.1f;
 
 
 
class GraphicsClass
{
public:
    GraphicsClass();
    GraphicsClass(const GraphicsClass&);
    ~GraphicsClass();
 
 
    bool Initialize(intint, HWND);
    void Shutdown();
    bool Frame();
 
private:
    bool Render();
 
private:
 
};
 
#endif // _GRAPHICSCLASS_H_
cs

<graphicsclass.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
#include "stdafx.h"
#include "graphicsclass.h"
 
GraphicsClass::GraphicsClass()
{
}
 
GraphicsClass::GraphicsClass(const GraphicsClass&)
{
}
 
GraphicsClass::~GraphicsClass()
{
}
 
bool GraphicsClass::Initialize(intint, HWND)
{
    return true;
}
 
void GraphicsClass::Shutdown()
{
}
 
bool GraphicsClass::Frame()
{
    return true;
}
 
bool GraphicsClass::Render()
{
    return true;
}
 
cs

 

<inputclass.h>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#pragma once
#ifndef _INPUTCLASS_H_
#define _INPUTCLASS_H_
 
class InputClass
{
public:
    InputClass();
    InputClass(const InputClass&);
    ~InputClass();
 
    void Initialize();
    bool IsKeyDown(unsigned int);
    void KeyDown(unsigned int);
    void KeyUp(unsigned int);
 
private:
    bool m_keys[256];
};
 
#endif // _INPUTCLASS_H_
cs

<inputclass.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
#include "stdafx.h"
#include "inputclass.h"
 
InputClass::InputClass()
{
}
 
InputClass::InputClass(const InputClass&)
{
}
 
InputClass::~InputClass()
{
}
 
void InputClass::Initialize()
{
    int i;
 
    // 모든 키들을 눌리지 않은 상태로 초기화 한다.
    for(i = 0; i < 256; i++)
    {
        m_keys[i] = false;
    }
 
    return;
}
 
 
bool InputClass::IsKeyDown(unsigned int key)
{
    // 현재키 상태 반환
    return m_keys[key];
}
 
void InputClass::KeyDown(unsigned int input)
{
    // 키가 눌렸다면 그 상태를 배열에 저장
    m_keys[input] = true;
}
 
void InputClass::KeyUp(unsigned int input)
{
    // 키가 떼어졌다면 그 상태를 배열에 저장
    m_keys[input] = false;
}
 
cs

 

 

<stdafx.h>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#pragma once
 
 
#define WIN32_LEAN_AND_MEAN
 
#include <windows.h>
 
#include <stdlib.h>
#include <malloc.h>
#include <memory.h>
#include <tchar.h>
 
 
#include "DxDefine.h"
cs

<stdafx.cpp>

1
#include "stdafx.h"
cs

 

<DxDefine.h>

DxDefine.h는 이번 예제에는 내용이 없음.

 

 

 

<소스코드>

https://github.com/woonhak-kong/DirectX_11_Tutorial/releases/tag/Tutorial_1

이번 게시물을 저번 게시물을 이어서, AI의 시야에 따른 행동을 구현한다.

https://gamdekong.tistory.com/211

 

Character AI Behavior Tree

https://gamdekong.tistory.com/category/%EC%96%B8%EB%A6%AC%EC%96%BC%20%EC%97%94%EC%A7%84 '언리얼 엔진' 카테고리의 글 목록 배움. gamdekong.tistory.com 작업은 위 게시물을 이어서 한다. 우선 Behavior Tre..

gamdekong.tistory.com

 

우선 Enemy가 패트롤을 하면서 총알을 볼 경우 인식하기 위한 총알 Actor를 생성한다.

생성후, 해당 Actor를 AI가 인식하게 하기 위해서, Actor에 AIStimuliSourceComponent를 붙여준다.

Static Mesh또한 추가하여 원하는 매쉬로 설정한다. 여기서는, 총알을 사용하였다.

Detail tap 다음과 같이 설정을 바꿔준다.

- Auto Register as Source는 자동적으로 이 엑터를 소스로 등록시켜주고,

- Source for Senses는 AIPerseption의 어떠한 센스에 인식될것인지를 설정해준다.

 

 

다음은 EnemyController를 수정하여 AIPerception을 사용할수 있도록, AIPerceptionComponent를 EnemyController에 추가한다.

 

먼저 기존에 만든 EnemyController C++파일을 상속하여 블루프린트를 만들어준다.

 

그리고 만든 BP_EnemyController를 사용하기 위해서 Enemy 의 컨트롤러를 변경한다.

 

컨트롤러에 다음과 같이 AIPerception을 추가한다.

 

추가후, 다음과 같이 수정한다.

 

Senses Config에 AI SIght config를 추가하여 Sight를 인식할수 있게 변경하고,

시야 거리와 시야각을 설정한다.

 

또한, Detection By Affiliation을 수정한다. 기본적으로 모든 중립체를 인식할 수 있도록 Detect Neutrals를 채크한다.

따로 설정하지 않으면 모든 Entity들은 중립이다.

(이부분은 따로 공부를 해야한다. 기본적으로 255개의 팀이 있고, 디폴트로 모든 Entity는 255팀에 속한다.

또한, 이 255팀에 속한 Entity는 중립이다.)

 

 

다음은, EnemyController가 무언가를 인식했을때 불러지는 이벤트를 작성하자.

EnemyController 블루프린트를 열어 다음과 같이 수정한다.

 

AIPerceprion 의 이벤트를 구현한다.

 

컴파일후 총알을 맵에 생성후, Enemy가 총알을 본다면 I SEE SOME AMMO가 프린트 되는것을 알 수 있다.

 

 

 

다음은 Enemy가 플레이어를 볼 경우를 추가해보자.

EnemyController를 다음과 같이 수정한다.

 

기존에 총알과 다르게 Pawn은 자동으로 Detection 되기 때문에 따로 AIStimuliSourceComponent를 추가하지 않아도 된다.

 

위와같이 추가하면, Enemy가 Player를 보면 I SEE YOU가 출력된다.

 

 

 

다음은 Sound를 감지 할 수 있도록 EnemyController를 수정한다.

 

다음은, Player가 총을쏠때 사운드와 노이즈를 발생시켜보자.

 

기존의 총알 발사 로직에 추가로 붙여 넣는다.

 

 

컴파일후 게임을 실켜 총알 을 발사하면 사운드와 글자출력을 볼 수 있다.

 

+ Recent posts