-
Notifications
You must be signed in to change notification settings - Fork 0
/
Graphics.cpp
361 lines (316 loc) · 10.8 KB
/
Graphics.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
#include "MainWindow.h"
#include "Graphics.h"
#include "DXErr.h"
#include "ChiliException.h"
#include <assert.h>
#include <string>
#include <array>
// Ignore the intellisense error "cannot open source file" for .shh files.
// They will be created during the build sequence before the preprocessor runs.
namespace FramebufferShaders
{
#include "FramebufferPS.shh"
#include "FramebufferVS.shh"
}
#pragma comment( lib,"d3d11.lib" )
#define CHILI_GFX_EXCEPTION( hr,note ) Graphics::Exception( hr,note,_CRT_WIDE(__FILE__),__LINE__ )
using Microsoft::WRL::ComPtr;
Graphics::Graphics( HWNDKey& key )
{
assert( key.hWnd != nullptr );
//////////////////////////////////////////////////////
// create device and swap chain/get render target view
DXGI_SWAP_CHAIN_DESC sd = {};
sd.BufferCount = 1;
sd.BufferDesc.Width = Graphics::ScreenWidth;
sd.BufferDesc.Height = Graphics::ScreenHeight;
sd.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
sd.BufferDesc.RefreshRate.Numerator = 1;
sd.BufferDesc.RefreshRate.Denominator = 60;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.OutputWindow = key.hWnd;
sd.SampleDesc.Count = 1;
sd.SampleDesc.Quality = 0;
sd.Windowed = TRUE;
HRESULT hr;
UINT createFlags = 0u;
#ifdef CHILI_USE_D3D_DEBUG_LAYER
#ifdef _DEBUG
createFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
#endif
// create device and front/back buffers
if( FAILED( hr = D3D11CreateDeviceAndSwapChain(
nullptr,
D3D_DRIVER_TYPE_HARDWARE,
nullptr,
createFlags,
nullptr,
0,
D3D11_SDK_VERSION,
&sd,
&pSwapChain,
&pDevice,
nullptr,
&pImmediateContext ) ) )
{
throw CHILI_GFX_EXCEPTION( hr,L"Creating device and swap chain" );
}
// get handle to backbuffer
ComPtr<ID3D11Resource> pBackBuffer;
if( FAILED( hr = pSwapChain->GetBuffer(
0,
__uuidof( ID3D11Texture2D ),
(LPVOID*)&pBackBuffer ) ) )
{
throw CHILI_GFX_EXCEPTION( hr,L"Getting back buffer" );
}
// create a view on backbuffer that we can render to
if( FAILED( hr = pDevice->CreateRenderTargetView(
pBackBuffer.Get(),
nullptr,
&pRenderTargetView ) ) )
{
throw CHILI_GFX_EXCEPTION( hr,L"Creating render target view on backbuffer" );
}
// set backbuffer as the render target using created view
pImmediateContext->OMSetRenderTargets( 1,pRenderTargetView.GetAddressOf(),nullptr );
// set viewport dimensions
D3D11_VIEWPORT vp;
vp.Width = float( Graphics::ScreenWidth );
vp.Height = float( Graphics::ScreenHeight );
vp.MinDepth = 0.0f;
vp.MaxDepth = 1.0f;
vp.TopLeftX = 0.0f;
vp.TopLeftY = 0.0f;
pImmediateContext->RSSetViewports( 1,&vp );
///////////////////////////////////////
// create texture for cpu render target
D3D11_TEXTURE2D_DESC sysTexDesc;
sysTexDesc.Width = Graphics::ScreenWidth;
sysTexDesc.Height = Graphics::ScreenHeight;
sysTexDesc.MipLevels = 1;
sysTexDesc.ArraySize = 1;
sysTexDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
sysTexDesc.SampleDesc.Count = 1;
sysTexDesc.SampleDesc.Quality = 0;
sysTexDesc.Usage = D3D11_USAGE_DYNAMIC;
sysTexDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
sysTexDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
sysTexDesc.MiscFlags = 0;
// create the texture
if( FAILED( hr = pDevice->CreateTexture2D( &sysTexDesc,nullptr,&pSysBufferTexture ) ) )
{
throw CHILI_GFX_EXCEPTION( hr,L"Creating sysbuffer texture" );
}
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
srvDesc.Format = sysTexDesc.Format;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MipLevels = 1;
// create the resource view on the texture
if( FAILED( hr = pDevice->CreateShaderResourceView( pSysBufferTexture.Get(),
&srvDesc,&pSysBufferTextureView ) ) )
{
throw CHILI_GFX_EXCEPTION( hr,L"Creating view on sysBuffer texture" );
}
////////////////////////////////////////////////
// create pixel shader for framebuffer
// Ignore the intellisense error "namespace has no member"
if( FAILED( hr = pDevice->CreatePixelShader(
FramebufferShaders::FramebufferPSBytecode,
sizeof( FramebufferShaders::FramebufferPSBytecode ),
nullptr,
&pPixelShader ) ) )
{
throw CHILI_GFX_EXCEPTION( hr,L"Creating pixel shader" );
}
/////////////////////////////////////////////////
// create vertex shader for framebuffer
// Ignore the intellisense error "namespace has no member"
if( FAILED( hr = pDevice->CreateVertexShader(
FramebufferShaders::FramebufferVSBytecode,
sizeof( FramebufferShaders::FramebufferVSBytecode ),
nullptr,
&pVertexShader ) ) )
{
throw CHILI_GFX_EXCEPTION( hr,L"Creating vertex shader" );
}
//////////////////////////////////////////////////////////////
// create and fill vertex buffer with quad for rendering frame
const FSQVertex vertices[] =
{
{ -1.0f,1.0f,0.5f,0.0f,0.0f },
{ 1.0f,1.0f,0.5f,1.0f,0.0f },
{ 1.0f,-1.0f,0.5f,1.0f,1.0f },
{ -1.0f,1.0f,0.5f,0.0f,0.0f },
{ 1.0f,-1.0f,0.5f,1.0f,1.0f },
{ -1.0f,-1.0f,0.5f,0.0f,1.0f },
};
D3D11_BUFFER_DESC bd = {};
bd.Usage = D3D11_USAGE_DEFAULT;
bd.ByteWidth = sizeof( FSQVertex ) * 6;
bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bd.CPUAccessFlags = 0u;
D3D11_SUBRESOURCE_DATA initData = {};
initData.pSysMem = vertices;
if( FAILED( hr = pDevice->CreateBuffer( &bd,&initData,&pVertexBuffer ) ) )
{
throw CHILI_GFX_EXCEPTION( hr,L"Creating vertex buffer" );
}
//////////////////////////////////////////
// create input layout for fullscreen quad
const D3D11_INPUT_ELEMENT_DESC ied[] =
{
{ "POSITION",0,DXGI_FORMAT_R32G32B32_FLOAT,0,0,D3D11_INPUT_PER_VERTEX_DATA,0 },
{ "TEXCOORD",0,DXGI_FORMAT_R32G32_FLOAT,0,12,D3D11_INPUT_PER_VERTEX_DATA,0 }
};
// Ignore the intellisense error "namespace has no member"
if( FAILED( hr = pDevice->CreateInputLayout( ied,2,
FramebufferShaders::FramebufferVSBytecode,
sizeof( FramebufferShaders::FramebufferVSBytecode ),
&pInputLayout ) ) )
{
throw CHILI_GFX_EXCEPTION( hr,L"Creating input layout" );
}
////////////////////////////////////////////////////
// Create sampler state for fullscreen textured quad
D3D11_SAMPLER_DESC sampDesc = {};
sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT;
sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
sampDesc.MinLOD = 0;
sampDesc.MaxLOD = D3D11_FLOAT32_MAX;
if( FAILED( hr = pDevice->CreateSamplerState( &sampDesc,&pSamplerState ) ) )
{
throw CHILI_GFX_EXCEPTION( hr,L"Creating sampler state" );
}
// allocate memory for sysbuffer (16-byte aligned for faster access)
pSysBuffer = reinterpret_cast<Color*>(
_aligned_malloc( sizeof( Color ) * Graphics::ScreenWidth * Graphics::ScreenHeight,16u ) );
}
Graphics::~Graphics()
{
// free sysbuffer memory (aligned free)
if( pSysBuffer )
{
_aligned_free( pSysBuffer );
pSysBuffer = nullptr;
}
// clear the state of the device context before destruction
if( pImmediateContext ) pImmediateContext->ClearState();
}
void Graphics::EndFrame()
{
HRESULT hr;
// lock and map the adapter memory for copying over the sysbuffer
if( FAILED( hr = pImmediateContext->Map( pSysBufferTexture.Get(),0u,
D3D11_MAP_WRITE_DISCARD,0u,&mappedSysBufferTexture ) ) )
{
throw CHILI_GFX_EXCEPTION( hr,L"Mapping sysbuffer" );
}
// setup parameters for copy operation
Color* pDst = reinterpret_cast<Color*>(mappedSysBufferTexture.pData );
const size_t dstPitch = mappedSysBufferTexture.RowPitch / sizeof( Color );
const size_t srcPitch = Graphics::ScreenWidth;
const size_t rowBytes = srcPitch * sizeof( Color );
// perform the copy line-by-line
for( size_t y = 0u; y < Graphics::ScreenHeight; y++ )
{
memcpy( &pDst[ y * dstPitch ],&pSysBuffer[y * srcPitch],rowBytes );
}
// release the adapter memory
pImmediateContext->Unmap( pSysBufferTexture.Get(),0u );
// render offscreen scene texture to back buffer
pImmediateContext->IASetInputLayout( pInputLayout.Get() );
pImmediateContext->VSSetShader( pVertexShader.Get(),nullptr,0u );
pImmediateContext->PSSetShader( pPixelShader.Get(),nullptr,0u );
pImmediateContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST );
const UINT stride = sizeof( FSQVertex );
const UINT offset = 0u;
pImmediateContext->IASetVertexBuffers( 0u,1u,pVertexBuffer.GetAddressOf(),&stride,&offset );
pImmediateContext->PSSetShaderResources( 0u,1u,pSysBufferTextureView.GetAddressOf() );
pImmediateContext->PSSetSamplers( 0u,1u,pSamplerState.GetAddressOf() );
pImmediateContext->Draw( 6u,0u );
// flip back/front buffers
if( FAILED( hr = pSwapChain->Present( 1u,0u ) ) )
{
if( hr == DXGI_ERROR_DEVICE_REMOVED )
{
throw CHILI_GFX_EXCEPTION( pDevice->GetDeviceRemovedReason(),L"Presenting back buffer [device removed]" );
}
else
{
throw CHILI_GFX_EXCEPTION( hr,L"Presenting back buffer" );
}
}
}
void Graphics::BeginFrame()
{
// clear the sysbuffer
memset( pSysBuffer,0u,sizeof( Color ) * Graphics::ScreenHeight * Graphics::ScreenWidth );
}
void Graphics::PutPixel( int x,int y,Color c )
{
assert( x >= 0 );
assert( x < int( Graphics::ScreenWidth ) );
assert( y >= 0 );
assert( y < int( Graphics::ScreenHeight ) );
pSysBuffer[Graphics::ScreenWidth * y + x] = c;
}
void Graphics::DrawRect( int x0,int y0,int x1,int y1,Color c )
{
if( x0 > x1 )
{
std::swap( x0,x1 );
}
if( y0 > y1 )
{
std::swap( y0,y1 );
}
for( int y = y0; y < y1; ++y )
{
for( int x = x0; x < x1; ++x )
{
PutPixel( x,y,c );
}
}
}
//////////////////////////////////////////////////
// Graphics Exception
Graphics::Exception::Exception( HRESULT hr,const std::wstring& note,const wchar_t* file,unsigned int line )
:
ChiliException( file,line,note ),
hr( hr )
{}
std::wstring Graphics::Exception::GetFullMessage() const
{
const std::wstring empty = L"";
const std::wstring errorName = GetErrorName();
const std::wstring errorDesc = GetErrorDescription();
const std::wstring& note = GetNote();
const std::wstring location = GetLocation();
return (!errorName.empty() ? std::wstring( L"Error: " ) + errorName + L"\n"
: empty)
+ (!errorDesc.empty() ? std::wstring( L"Description: " ) + errorDesc + L"\n"
: empty)
+ (!note.empty() ? std::wstring( L"Note: " ) + note + L"\n"
: empty)
+ (!location.empty() ? std::wstring( L"Location: " ) + location
: empty);
}
std::wstring Graphics::Exception::GetErrorName() const
{
return DXGetErrorString( hr );
}
std::wstring Graphics::Exception::GetErrorDescription() const
{
std::array<wchar_t,512> wideDescription;
DXGetErrorDescription( hr,wideDescription.data(),wideDescription.size() );
return wideDescription.data();
}
std::wstring Graphics::Exception::GetExceptionType() const
{
return L"Chili Graphics Exception";
}