forked from microsoft/Xbox-ATG-Samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRaytracingAOPC12.cpp
575 lines (468 loc) · 15.1 KB
/
RaytracingAOPC12.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
//--------------------------------------------------------------------------------------
// D3D12RaytracingAO.cpp
//
// Advanced Technology Group (ATG)
// Copyright (C) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
#include "pch.h"
#include "RaytracingAOPC12.h"
#include "ATGColors.h"
#include "FindMedia.h"
#include "RayTracingHelper.h"
extern void ExitSample();
using namespace DX;
using namespace DirectX;
using Microsoft::WRL::ComPtr;
Sample::Sample() noexcept(false)
{
m_deviceResources = std::make_unique<DX::DeviceResources>();
m_deviceResources->RegisterDeviceNotify(this);
}
Sample::~Sample()
{
if (m_deviceResources)
{
m_deviceResources->WaitForGpu();
}
// Force cleanup.
OnDeviceLost();
}
// Initialize the Direct3D resources required to run.
void Sample::Initialize(HWND window, int width, int height)
{
m_gamePad = std::make_unique<GamePad>();
m_keyboard = std::make_unique<Keyboard>();
m_mouse = std::make_unique<Mouse>();
m_mouse->SetWindow(window);
m_menus = std::make_unique<Menus>();
m_deviceResources->SetWindow(window, width, height);
m_deviceResources->InitializeDXGIAdapter();
if (!CheckRaytracingSupported(m_deviceResources->GetDXRAdapter()))
{
ThrowIfFalse(false,L"This demo requires DXR support\n");
}
m_deviceResources->CreateDeviceResources();
m_deviceResources->CreateRaytracingInterfaces();
CreateDeviceDependentResources();
m_deviceResources->CreateWindowSizeDependentResources();
CreateWindowSizeDependentResources();
}
// Update camera matrices passed into the shader.
void Sample::UpdateCameraMatrices()
{
auto frameIndex = m_deviceResources->GetCurrentFrameIndex();
auto screenWidth = m_deviceResources->GetScreenWidth() * (m_isSplit ? .5f : 1.f);
auto screenHeight = m_deviceResources->GetScreenHeight();
float fovAngleY = 45.0f;
XMVECTOR updatedEye = { 0, 0, m_radius, 1 };
XMMATRIX view = XMMatrixLookAtLH(updatedEye, m_at, m_up);
float aspectRatio = static_cast<float>(screenWidth) / static_cast<float>(screenHeight);
XMMATRIX proj = XMMatrixPerspectiveFovLH(XMConvertToRadians(fovAngleY), aspectRatio, NEAR_PLANE, FAR_PLANE);
XMMATRIX viewProj = view * proj;
m_sceneCB[frameIndex].cameraPosition = updatedEye;
m_sceneCB[frameIndex].projectionToWorld = XMMatrixInverse(nullptr, viewProj);
m_sceneCB[frameIndex].worldView = XMMatrixTranspose(view);
m_sceneCB[frameIndex].worldViewProjection = XMMatrixTranspose(viewProj);
// Update frustum.
{
BoundingFrustum bf;
BoundingFrustum::CreateFromMatrix(bf, proj);
XMMATRIX viewToWorld = XMMatrixInverse(nullptr, view);
XMFLOAT3 corners[BoundingFrustum::CORNER_COUNT];
bf.GetCorners(corners);
auto lowerLeft = XMVector3Transform(
XMLoadFloat3(&corners[7]),
viewToWorld
);
auto lowerRight = XMVector3Transform(
XMLoadFloat3(&corners[6]),
viewToWorld
);
auto topLeft = XMVector3Transform(
XMLoadFloat3(&corners[4]),
viewToWorld
);
XMVECTOR point = XMVectorSubtract(topLeft, updatedEye);
XMVECTOR horizDelta = XMVectorSubtract(lowerRight, lowerLeft);
XMVECTOR vertDelta = XMVectorSubtract(lowerLeft, topLeft);
m_sceneCB[frameIndex].frustumPoint = point;
m_sceneCB[frameIndex].frustumHDelta = horizDelta;
m_sceneCB[frameIndex].frustumVDelta = vertDelta;
}
DirectX::XMMATRIX identityMatrix = DirectX::XMMatrixIdentity();
if (m_ao)
m_ao->OnCameraChanged(identityMatrix, view, proj);
if (m_ssao)
m_ssao->OnCameraChanged(identityMatrix, view, proj);
}
// Initialize scene rendering parameters.
void Sample::InitializeScene()
{
auto frameIndex = m_deviceResources->GetCurrentFrameIndex();
auto frameCount = m_deviceResources->GetBackBufferCount();
auto screenWidth = m_deviceResources->GetScreenWidth() * (m_isSplit ? .5 : 1.f);
auto screenHeight = m_deviceResources->GetScreenHeight();
// Setup camera.
{
// Allocate for the frame size.
m_sceneCB.resize(frameCount);
// Initialize the view and projection inverse matrices.
m_at = { 0.0f, 0.0f, 0.0f, 1.0f };
m_up = { 0.0f, 1.0f, 0.0f, 0.0f };
UpdateCameraMatrices();
}
// Setup noise tile.
{
m_sceneCB[frameIndex].noiseTile = {
float(screenWidth) / float(NOISE_W),
float(screenHeight) / float(NOISE_W),
0,
0
};
}
// Apply the initial values to all of the frames' buffer instances.
for (auto& sceneCB : m_sceneCB)
{
sceneCB = m_sceneCB[frameIndex];
}
// Assign split.
{
m_isSplit = true;
m_isSplitMode = false;
}
}
// Create constant buffers.
void Sample::CreateConstantBuffers()
{
auto device = m_deviceResources->GetD3DDevice();
auto frameCount = m_deviceResources->GetBackBufferCount();
// Create a constant buffer for each frame to solve read and write conflicts.
{
m_mappedSceneConstantResource.resize(frameCount);
m_mappedSceneConstantData.resize(frameCount);
for (unsigned int i = 0; i < frameCount; i++)
{
AllocateUploadBuffer(device, nullptr, sizeof(*m_mappedSceneConstantData[i]), &m_mappedSceneConstantResource[i]);
// Map the constant buffer and cache its heap pointers.
// We don't unmap this until the app closes. Keeping buffer mapped for the lifetime of the resource is okay.
m_mappedSceneConstantResource[i]->Map(0, nullptr, reinterpret_cast<void**>(&m_mappedSceneConstantData[i]));
}
}
}
void Sample::SetupLighting()
{
// Setup the lighting model.
m_ao->Setup(m_deviceResources);
m_ssao->Setup(m_deviceResources);
// Send mesh to the lighting model.
m_ao->SetMesh(m_mesh);
m_ssao->SetMesh(m_mesh);
}
#pragma region Frame Update
// Executes basic render loop.
void Sample::Tick()
{
m_timer.Tick([&]()
{
Update(m_timer);
});
Render();
}
// Updates the world.
void Sample::Update(DX::StepTimer const& timer)
{
UNREFERENCED_PARAMETER(timer);
auto device = m_deviceResources->GetD3DDevice();
auto commandQueue = m_deviceResources->GetCommandQueue();
auto frameIndex = m_deviceResources->GetCurrentFrameIndex();
auto screenWidth =
m_deviceResources->GetScreenWidth()
* (m_isSplit ? .5 : 1.f);
auto screenHeight =
m_deviceResources->GetScreenHeight()
* (m_isSplit ? .5 : 1.f);
PIXBeginEvent(PIX_COLOR_DEFAULT, L"Update");
auto pad = m_gamePad->GetState(0);
if (pad.IsConnected())
{
m_gamePadButtons.Update(pad);
if (pad.IsViewPressed())
{
ExitSample();
}
}
else
{
m_gamePadButtons.Reset();
}
auto kb = m_keyboard->GetState();
m_keyboardButtons.Update(kb);
if (kb.Escape)
{
ExitSample();
}
else if (kb.A)
{
m_radius += m_camStep;
}
else if (kb.D)
{
m_radius -= m_camStep;
}
else if (m_keyboardButtons.IsKeyPressed(Keyboard::Space))
{
m_meshIndex++;
if (m_meshFiles.size() <= m_meshIndex)
m_meshIndex = 0;
// Wait for frames to finish to change the model.
m_deviceResources->WaitForGpu();
// Clear all references to mesh to free memory before the load.
m_ao->SetMesh({ nullptr });
m_ssao->SetMesh({ nullptr });
m_mesh.reset();
// Load in mesh.
m_mesh = std::make_shared<Mesh>(
Mesh(
device,
commandQueue,
std::wstring(m_meshFiles[m_meshIndex].begin(),
m_meshFiles[m_meshIndex].end()).c_str())
);
// Send mesh to the lighting model.
m_ao->SetMesh(m_mesh);
m_ssao->SetMesh(m_mesh);
}
else if (m_keyboardButtons.IsKeyPressed(Keyboard::S))
{
m_isSplit = !m_isSplit;
}
bool update = m_menus->ProcessKeys(m_keyboardButtons);
// Update AO and SSAO CBVs.
if (update)
{
// Wait on GPU to finish.
m_deviceResources->WaitForGpu();
// Update options.
m_ao->OnOptionUpdate(m_menus);
m_ssao->OnOptionUpdate(m_menus);
// Wait on upload.
m_deviceResources->WaitForGpu();
}
auto mouse = m_mouse->GetState();
// Update world.
{
m_sceneCB[frameIndex].noiseTile = {
float(screenWidth) / float(NOISE_W),
float(screenHeight) / float(NOISE_W),
0,
0
};
UpdateCameraMatrices();
}
PIXEndEvent();
}
#pragma endregion
#pragma region Frame Render
// Draws the scene.
void Sample::Render()
{
auto frameIndex = m_deviceResources->GetCurrentFrameIndex();
// 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();
// Copy the updated scene constant buffer to the GPU.
{
memcpy(&m_mappedSceneConstantData[frameIndex]->constants, &m_sceneCB[frameIndex], sizeof(m_sceneCB[frameIndex]));
}
// Process split.
if (m_isSplit && !m_isSplitMode)
{
m_isSplitMode = true;
m_ssao->ChangeScreenScale(.5f);
m_ao->ChangeScreenScale(.5f);
}
else if (!m_isSplit && m_isSplitMode)
{
m_isSplitMode = false;
m_ssao->ChangeScreenScale(1.f);
m_ao->ChangeScreenScale(1.f);
}
// Apply lighting model.
if (m_isSplit)
{
m_ao->Run(m_mappedSceneConstantResource[frameIndex]);
m_ssao->Run(m_mappedSceneConstantResource[frameIndex]);
}
else if (m_menus->m_lightingModel == MenuLightingModel::AO)
{
m_ao->Run(m_mappedSceneConstantResource[frameIndex]);
}
else if (m_menus->m_lightingModel == MenuLightingModel::SSAO)
{
m_ssao->Run(m_mappedSceneConstantResource[frameIndex]);
}
// Draw HUD.
m_menus->Draw(m_timer.GetFramesPerSecond(), m_isSplit);
// Show the new frame.
PIXBeginEvent(m_deviceResources->GetCommandQueue(), PIX_COLOR_DEFAULT, L"Present");
m_deviceResources->Present();
m_graphicsMemory->Commit(m_deviceResources->GetCommandQueue());
PIXEndEvent(m_deviceResources->GetCommandQueue());
}
// Helper method to clear the back buffers.
void Sample::Clear()
{
auto commandList = m_deviceResources->GetCommandList();
PIXBeginEvent(commandList, PIX_COLOR_DEFAULT, L"Clear");
// Clear the views.
auto rtvDescriptor = m_deviceResources->GetRenderTargetView();
auto dsvDescriptor = m_deviceResources->GetDepthStencilView();
commandList->OMSetRenderTargets(1, &rtvDescriptor, FALSE, &dsvDescriptor);
commandList->ClearDepthStencilView(dsvDescriptor, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, nullptr);
// Set the viewport and scissor rect.
auto viewport = m_deviceResources->GetScreenViewport();
auto scissorRect = m_deviceResources->GetScissorRect();
commandList->RSSetViewports(1, &viewport);
commandList->RSSetScissorRects(1, &scissorRect);
PIXEndEvent(commandList);
}
#pragma endregion
#pragma region Message Handlers
// Message handlers
void Sample::OnActivated()
{
}
void Sample::OnDeactivated()
{
}
void Sample::OnSuspending()
{
}
void Sample::OnResuming()
{
m_timer.ResetElapsedTime();
m_gamePadButtons.Reset();
m_keyboardButtons.Reset();
}
void Sample::OnWindowMoved()
{
auto r = m_deviceResources->GetOutputSize();
m_deviceResources->WindowSizeChanged(r.right, r.bottom);
}
void Sample::OnWindowSizeChanged(int width, int height)
{
if (!m_deviceResources->WindowSizeChanged(width, height))
return;
CreateWindowSizeDependentResources();
}
// Properties
void Sample::GetDefaultSize(int& width, int& height) const
{
width = 1280;
height = 720;
}
#pragma endregion
#pragma region Direct3D Resources
// These are the resources that depend on the device.
void Sample::CreateDeviceDependentResources()
{
auto device = m_deviceResources->GetD3DDevice();
auto commandQueue = m_deviceResources->GetCommandQueue();
// Set graphics memory
{
m_graphicsMemory = std::make_unique<GraphicsMemory>(device);
}
// Get mesh.
{
std::vector<wchar_t> buff(MAX_PATH);
for (auto& el : m_assetList)
{
DX::FindMediaFile(buff.data(), MAX_PATH, el);
m_meshFiles.emplace_back(std::string(buff.begin(), buff.end()));
}
ThrowIfFalse(0 < m_meshFiles.size(), L"No available assets.");
m_meshIndex = 0;
m_mesh = std::make_shared<Mesh>(
Mesh(
device,
commandQueue,
std::wstring(m_meshFiles[m_meshIndex].begin(), m_meshFiles[m_meshIndex].end()).c_str()
)
);
}
// Create constant buffers for the geometry and the scene.
CreateConstantBuffers();
// Create scene variables.
InitializeScene();
// Setup initial lighting model.
{
// Init lighting var.
m_ao = std::make_unique<AO>();
m_ssao = std::make_unique<SSAO>();
// Send over information to the lighting model.
SetupLighting();
}
// Setup menus.
{
m_menus->Setup(m_deviceResources);
}
}
// Allocate all memory resources that change on a window SizeChanged event.
void Sample::CreateWindowSizeDependentResources()
{
// Inform lighting.
m_ao->OnSizeChanged();
m_ssao->OnSizeChanged();
// Force update.
m_ao->OnOptionUpdate(m_menus);
m_ssao->OnOptionUpdate(m_menus);
// Inform menus.
m_menus->OnSizeChanged();
// Broadcast camera information.
UpdateCameraMatrices();
}
void Sample::OnDeviceLost()
{
// Direct3D resource cleanup.
m_graphicsMemory.reset();
m_mappedSceneConstantData.clear();
m_mappedSceneConstantResource.clear();
m_sceneCB.clear();
m_ssao.reset();
m_ao.reset();
m_meshFiles.clear();
m_mesh.reset();
m_menus.reset();
}
void Sample::OnDeviceRestored()
{
CreateDeviceDependentResources();
CreateWindowSizeDependentResources();
}
bool Sample::CheckRaytracingSupported(IDXGIAdapter1* adapter)
{
m_deviceResources->m_isDxrNativelySupported = IsDirectXRaytracingSupported(adapter);
if (!m_deviceResources->m_isDxrNativelySupported)
{
OutputDebugString(L"Warning: DirectX Raytracing is not natively supported by your GPU and driver.\n\n");
}
else
{
// Fallback Layer uses an experimental feature and needs to be enabled before creating a D3D12 device.
bool isFallbackSupported = EnableComputeRaytracingFallback(adapter);
if (!isFallbackSupported)
{
OutputDebugString(
L"Warning: Could not enable Compute Raytracing Fallback (D3D12EnableExperimentalFeatures() failed).\n" \
L" Possible reasons: your OS is not in developer mode.\n\n");
return false;
}
}
return true;
}
#pragma endregion