-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathGame.cpp
356 lines (280 loc) · 10.4 KB
/
Game.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
//
// Game.cpp
//
#include "pch.h"
#include "Game.h"
extern void ExitGame() noexcept;
using namespace DirectX;
using Microsoft::WRL::ComPtr;
#define DRAW_TRIANGLE
namespace
{
const DirectX::XMVECTORF32 c_Background = { { { 0.254901975f, 0.254901975f, 0.254901975f, 1.f } } }; // #414141
#ifdef DRAW_TRIANGLE
struct Vertex
{
XMFLOAT4 position;
XMFLOAT4 color;
};
inline std::vector<uint8_t> ReadData(_In_z_ const wchar_t* name)
{
std::ifstream inFile(name, std::ios::in | std::ios::binary | std::ios::ate);
#ifdef _GAMING_DESKTOP
if (!inFile)
{
wchar_t moduleName[_MAX_PATH];
if (!GetModuleFileNameW(nullptr, moduleName, _MAX_PATH))
throw std::exception("GetModuleFileName");
wchar_t drive[_MAX_DRIVE];
wchar_t path[_MAX_PATH];
if (_wsplitpath_s(moduleName, drive, _MAX_DRIVE, path, _MAX_PATH, nullptr, 0, nullptr, 0))
throw std::exception("_wsplitpath_s");
wchar_t filename[_MAX_PATH];
if (_wmakepath_s(filename, _MAX_PATH, drive, path, name, nullptr))
throw std::exception("_wmakepath_s");
inFile.open(filename, std::ios::in | std::ios::binary | std::ios::ate);
}
#endif
if (!inFile)
throw std::exception("ReadData");
const std::streampos len = inFile.tellg();
if (!inFile)
throw std::exception("ReadData");
std::vector<uint8_t> blob;
blob.resize(size_t(len));
inFile.seekg(0, std::ios::beg);
if (!inFile)
throw std::exception("ReadData");
inFile.read(reinterpret_cast<char*>(blob.data()), len);
if (!inFile)
throw std::exception("ReadData");
inFile.close();
return blob;
}
#endif // DRAW_TRIANGLE
}
Game::Game() noexcept(false) :
m_frame(0),
m_vertexBufferView{}
{
m_deviceResources = std::make_unique<DX::DeviceResources>();
m_deviceResources->SetClearColor(c_Background);
m_deviceResources->RegisterDeviceNotify(this);
}
Game::~Game()
{
if (m_deviceResources)
{
m_deviceResources->WaitForGpu();
}
}
// Initialize the Direct3D resources required to run.
void Game::Initialize(HWND window, int width, int height)
{
m_deviceResources->SetWindow(window, width, height);
m_deviceResources->CreateDeviceResources();
CreateDeviceDependentResources();
m_deviceResources->CreateWindowSizeDependentResources();
CreateWindowSizeDependentResources();
}
#pragma region Frame Update
// Executes the basic game loop.
void Game::Tick()
{
PIXBeginEvent(PIX_COLOR_DEFAULT, L"Frame %llu", m_frame);
#ifdef _GAMING_XBOX
m_deviceResources->WaitForOrigin();
#endif
m_timer.Tick([&]()
{
Update(m_timer);
});
Render();
PIXEndEvent();
m_frame++;
}
// Updates the world.
void Game::Update(DX::StepTimer const&)
{
PIXBeginEvent(PIX_COLOR_DEFAULT, L"Update");
// Game logic here.
PIXEndEvent();
}
#pragma endregion
#pragma region Frame Render
// Draws the scene.
void Game::Render()
{
// Don't try to render anything before the first Update.
if (m_timer.GetFrameCount() == 0)
{
return;
}
// Prepare the command list to render a new frame.
m_deviceResources->Prepare();
Clear();
auto commandList = m_deviceResources->GetCommandList();
PIXBeginEvent(commandList, PIX_COLOR_DEFAULT, L"Render");
#ifdef DRAW_TRIANGLE
commandList->SetGraphicsRootSignature(m_rootSignature.Get());
commandList->SetPipelineState(m_pipelineState.Get());
// Set necessary state.
commandList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
commandList->IASetVertexBuffers(0, 1, &m_vertexBufferView);
// Draw triangle.
commandList->DrawInstanced(3, 1, 0, 0);
#endif // DRAW_TRIANGLE
PIXEndEvent(commandList);
// Show the new frame.
PIXBeginEvent(PIX_COLOR_DEFAULT, L"Present");
m_deviceResources->Present();
PIXEndEvent();
}
// Helper method to clear the back buffers.
void Game::Clear()
{
auto commandList = m_deviceResources->GetCommandList();
PIXBeginEvent(commandList, PIX_COLOR_DEFAULT, L"Clear");
// Clear the views.
auto const rtvDescriptor = m_deviceResources->GetRenderTargetView();
auto const dsvDescriptor = m_deviceResources->GetDepthStencilView();
commandList->OMSetRenderTargets(1, &rtvDescriptor, FALSE, &dsvDescriptor);
commandList->ClearRenderTargetView(rtvDescriptor, c_Background, 0, nullptr);
commandList->ClearDepthStencilView(dsvDescriptor, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, nullptr);
// Set the viewport and scissor rect.
auto const viewport = m_deviceResources->GetScreenViewport();
auto const scissorRect = m_deviceResources->GetScissorRect();
commandList->RSSetViewports(1, &viewport);
commandList->RSSetScissorRects(1, &scissorRect);
PIXEndEvent(commandList);
}
#pragma endregion
#pragma region Message Handlers
// Message handlers
void Game::OnSuspending()
{
m_deviceResources->Suspend();
}
void Game::OnResuming()
{
m_deviceResources->Resume();
m_timer.ResetElapsedTime();
}
void Game::OnWindowMoved()
{
auto const r = m_deviceResources->GetOutputSize();
m_deviceResources->WindowSizeChanged(r.right, r.bottom);
}
void Game::OnWindowSizeChanged(int width, int height)
{
if (!m_deviceResources->WindowSizeChanged(width, height))
return;
CreateWindowSizeDependentResources();
// Game window is being resized.
}
// Properties
void Game::GetDefaultSize(int& width, int& height) const noexcept
{
width = 1280;
height = 720;
}
#pragma endregion
#pragma region Direct3D Resources
// These are the resources that depend on the device.
void Game::CreateDeviceDependentResources()
{
auto device = m_deviceResources->GetD3DDevice();
#ifdef _GAMING_DESKTOP
D3D12_FEATURE_DATA_SHADER_MODEL shaderModel = { D3D_SHADER_MODEL_6_0 };
if (FAILED(device->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &shaderModel, sizeof(shaderModel)))
|| (shaderModel.HighestShaderModel < D3D_SHADER_MODEL_6_0))
{
throw std::runtime_error("Shader Model 6.0 is not supported!");
}
#endif
#ifdef DRAW_TRIANGLE
// Create root signature.
auto const vertexShaderBlob = ReadData(L"VertexShader.cso");
// Xbox best practice is to use HLSL-based root signatures to support shader precompilation.
DX::ThrowIfFailed(
device->CreateRootSignature(0, vertexShaderBlob.data(), vertexShaderBlob.size(),
IID_GRAPHICS_PPV_ARGS(m_rootSignature.ReleaseAndGetAddressOf())));
// Create the pipeline state, which includes loading shaders.
auto const pixelShaderBlob = ReadData(L"PixelShader.cso");
static const D3D12_INPUT_ELEMENT_DESC s_inputElementDesc[2] =
{
{ "SV_Position", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
{ "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 16, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA , 0 },
};
// Describe and create the graphics pipeline state object (PSO).
D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {};
psoDesc.InputLayout = { s_inputElementDesc, static_cast<UINT>(std::size(s_inputElementDesc)) };
psoDesc.pRootSignature = m_rootSignature.Get();
psoDesc.VS = { vertexShaderBlob.data(), vertexShaderBlob.size() };
psoDesc.PS = { pixelShaderBlob.data(), pixelShaderBlob.size() };
psoDesc.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT);
psoDesc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT);
psoDesc.DepthStencilState.DepthEnable = FALSE;
psoDesc.DepthStencilState.StencilEnable = FALSE;
psoDesc.DSVFormat = m_deviceResources->GetDepthBufferFormat();
psoDesc.SampleMask = UINT_MAX;
psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
psoDesc.NumRenderTargets = 1;
psoDesc.RTVFormats[0] = m_deviceResources->GetBackBufferFormat();
psoDesc.SampleDesc.Count = 1;
DX::ThrowIfFailed(
device->CreateGraphicsPipelineState(&psoDesc,
IID_GRAPHICS_PPV_ARGS(m_pipelineState.ReleaseAndGetAddressOf())));
// Create vertex buffer.
{
static const Vertex s_vertexData[3] =
{
{ { 0.0f, 0.5f, 0.5f, 1.0f },{ 1.0f, 0.0f, 0.0f, 1.0f } }, // Top / Red
{ { 0.5f, -0.5f, 0.5f, 1.0f },{ 0.0f, 1.0f, 0.0f, 1.0f } }, // Right / Green
{ { -0.5f, -0.5f, 0.5f, 1.0f },{ 0.0f, 0.0f, 1.0f, 1.0f } } // Left / Blue
};
// Note: using upload heaps to transfer static data like vert buffers is not
// recommended. Every time the GPU needs it, the upload heap will be marshalled
// over. Please read up on Default Heap usage. An upload heap is used here for
// code simplicity and because there are very few verts to actually transfer.
const CD3DX12_HEAP_PROPERTIES heapProps(D3D12_HEAP_TYPE_UPLOAD);
auto const resDesc = CD3DX12_RESOURCE_DESC::Buffer(sizeof(s_vertexData));
DX::ThrowIfFailed(
device->CreateCommittedResource(&heapProps,
D3D12_HEAP_FLAG_NONE,
&resDesc,
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_GRAPHICS_PPV_ARGS(m_vertexBuffer.ReleaseAndGetAddressOf())));
// Copy the triangle data to the vertex buffer.
UINT8* pVertexDataBegin;
const CD3DX12_RANGE readRange(0, 0); // We do not intend to read from this resource on the CPU.
DX::ThrowIfFailed(
m_vertexBuffer->Map(0, &readRange, reinterpret_cast<void**>(&pVertexDataBegin)));
memcpy(pVertexDataBegin, s_vertexData, sizeof(s_vertexData));
m_vertexBuffer->Unmap(0, nullptr);
// Initialize the vertex buffer view.
m_vertexBufferView.BufferLocation = m_vertexBuffer->GetGPUVirtualAddress();
m_vertexBufferView.StrideInBytes = sizeof(Vertex);
m_vertexBufferView.SizeInBytes = sizeof(s_vertexData);
}
// Wait until assets have been uploaded to the GPU.
m_deviceResources->WaitForGpu();
#endif // DRAW_TRIANGLE
}
// Allocate all memory resources that change on a window SizeChanged event.
void Game::CreateWindowSizeDependentResources()
{
}
void Game::OnDeviceLost()
{
m_rootSignature.Reset();
m_pipelineState.Reset();
m_vertexBuffer.Reset();
}
void Game::OnDeviceRestored()
{
CreateDeviceDependentResources();
CreateWindowSizeDependentResources();
}
#pragma endregion