Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
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
Archives
Today
Total
관리 메뉴

codingfarm

22. 삼각형 그리기 2 본문

computer graphics/DirectX12

22. 삼각형 그리기 2

scarecrow1992 2021. 8. 5. 23:05

 

 

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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
//***************************************************************************************
// color.hlsl by Frank Luna (C) 2015 All Rights Reserved.
//
// Transforms and colors geometry.
//***************************************************************************************
 
// color.hlsl
 
cbuffer cbPosition : register(b0) {
    float2 worldPos;
}
 
cbuffer cbSize : register(b1) {
    float worldSize;
}
 
cbuffer cbRot : register(b2) {
    float worldRotation;
}
 
struct VertexIn
{
    float3 PosL  : POSITION;
    float4 Color : COLOR;
};
 
struct VertexOut
{
    float4 PosH  : SV_POSITION;
    float4 Color : COLOR;
};
 
 
 
VertexOut VS(VertexIn vin)
{
    VertexOut vout = (VertexOut)0;
 
    // Transform to homogeneous clip space.
    vout.PosH = float4(vin.PosL, 1.0f);
 
    vout.PosH.x *= worldSize;
    vout.PosH.y *= worldSize;
 
    float tmpX = vout.PosH.x, tmpY = vout.PosH.y;
    vout.PosH.x = (tmpX * cos(worldRotation)) + (tmpY * sin(worldRotation));
    vout.PosH.y = -(tmpX * sin(worldRotation)) + (tmpY * cos(worldRotation));
    
 
    vout.PosH.x += worldPos.x;
    vout.PosH.y += worldPos.y;
 
 
    // Just pass vertex color into the pixel shader.
    vout.Color = vin.Color;
 
    return vout;
}
 
float4 PS(VertexOut pin) : SV_Target
{
    return pin.Color;
}
 
 
 
 
// source.cpp
 
#include <windows.h>
#include "d3dx12.h"
#include <DirectXMath.h>
#include <DirectXColors.h>
#include <vector>
#include <array>
#include <wrl.h>
#include <dxgi.h>
#include <dxgi1_4.h>
#include <memory>
#include <d3dcompiler.h>
#include <vector>
#include <utility>
#include <cmath>
 
#define SWAP_CHAIN_BUFFER_COUNT 2
#define WIDTH 1000
#define HEIGHT 1000
#define IDC_CLIENT            109
 
#pragma comment(lib, "d3d12")
#pragma comment(lib, "dxgi")
#pragma comment(lib, "dxguid")
#pragma comment(lib, "d3dcompiler")
 
struct Vertex {
    DirectX::XMFLOAT3 pos;
    DirectX::XMFLOAT4 color;
};
 
struct ObjectConstants {
public:
    DirectX::XMFLOAT2 pos;
    ObjectConstants() : pos(00) {}
};
 
 
DirectX::XMFLOAT2 mousePos;
 
HWND hWnd;
HACCEL hAccelTable;
MSG msg;
WNDCLASS WndClass;
 
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
HINSTANCE g_hInst;
LPCTSTR lpszClass = TEXT("First");
 
Microsoft::WRL::ComPtr<IDXGIFactory> mdxgiFactory;
Microsoft::WRL::ComPtr<ID3D12Device> md3dDevice;
Microsoft::WRL::ComPtr<ID3D12Fence>  mFence;
 
UINT mRtvDescriptorSize = 0;
UINT mCbvSrvUavDescriptorSize = 0;
 
Microsoft::WRL::ComPtr<ID3D12CommandQueue>          mCommandQueue;
Microsoft::WRL::ComPtr<ID3D12CommandAllocator>      mDirectCmdListAlloc;
Microsoft::WRL::ComPtr<ID3D12GraphicsCommandList>   mCommandList;
 
Microsoft::WRL::ComPtr<IDXGISwapChain> mSwapChain;
DXGI_FORMAT mBackBufferFormat = DXGI_FORMAT_R8G8B8A8_UNORM;
const int SwapChainBufferCount = 2;
 
Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> mRtvHeap;
Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> mCbvHeap;
 
UINT64 mCurrentFence = 0;
 
Microsoft::WRL::ComPtr<ID3D12Resource> mSwapChainBuffer[SwapChainBufferCount];
 
int mCurrBackBuffer = 0;
 
D3D12_VIEWPORT mScreenViewport;
D3D12_RECT mScissorRect;
 
Microsoft::WRL::ComPtr<ID3D12RootSignature> mRootSignature = nullptr;
 
Microsoft::WRL::ComPtr<ID3DBlob> mvsByteCode = nullptr;
Microsoft::WRL::ComPtr<ID3DBlob> mpsByteCode = nullptr;
 
UINT vbByteSize, ibByteSize;
std::vector<D3D12_INPUT_ELEMENT_DESC> mInputLayout;
 
Microsoft::WRL::ComPtr<ID3DBlob> VertexBufferCPU = nullptr;
Microsoft::WRL::ComPtr<ID3DBlob> IndexBufferCPU = nullptr;
 
Microsoft::WRL::ComPtr<ID3D12Resource> VertexBufferGPU = nullptr;
Microsoft::WRL::ComPtr<ID3D12Resource> IndexBufferGPU = nullptr;
Microsoft::WRL::ComPtr<ID3D12Resource> mObjectCBPos = nullptr;
Microsoft::WRL::ComPtr<ID3D12Resource> mObjectCBSize = nullptr;
 
Microsoft::WRL::ComPtr<ID3D12PipelineState> mPSO = nullptr;
 
 
ObjectConstants objectConstants;
float sizeConstants = .2;
float rotationConstants = 0;
 
void FlushCommandQueue()
{
    // Advance the fence value to mark commands up to this fence point.
    mCurrentFence++;
 
    // Add an instruction to the command queue to set a new fence point.  Because we 
    // are on the GPU timeline, the new fence point won't be set until the GPU finishes
    // processing all the commands prior to this Signal().
    mCommandQueue->Signal(mFence.Get(), mCurrentFence);
 
    // Wait until the GPU has completed commands up to this fence point.
    if (mFence->GetCompletedValue() < mCurrentFence)
    {
        HANDLE eventHandle = CreateEventEx(nullptr, falsefalse, EVENT_ALL_ACCESS);
 
        // Fire event when GPU hits current fence.  
        mFence->SetEventOnCompletion(mCurrentFence, eventHandle);
 
        // Wait until the GPU hits current fence event is fired.
        WaitForSingleObject(eventHandle, INFINITE);
        CloseHandle(eventHandle);
    }
}
 
 
void Init() {
    // 1. Init direct3D
    CreateDXGIFactory1(IID_PPV_ARGS(&mdxgiFactory));
    D3D12CreateDevice(nullptr,             // default adapter
        D3D_FEATURE_LEVEL_11_0,
        IID_PPV_ARGS(&md3dDevice));
 
    md3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE,
        IID_PPV_ARGS(&mFence));
 
    mRtvDescriptorSize          = md3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
    mCbvSrvUavDescriptorSize    = md3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
 
    // 1-1. Create Command Objects
    D3D12_COMMAND_QUEUE_DESC queueDesc = {};
    queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
    queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
    md3dDevice->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&mCommandQueue));
 
    md3dDevice->CreateCommandAllocator(
        D3D12_COMMAND_LIST_TYPE_DIRECT,
        IID_PPV_ARGS(mDirectCmdListAlloc.GetAddressOf()));
 
    md3dDevice->CreateCommandList(
        0,
        D3D12_COMMAND_LIST_TYPE_DIRECT,
        mDirectCmdListAlloc.Get(), // Associated command allocator
        nullptr,                   // Initial PipelineStateObject
        IID_PPV_ARGS(mCommandList.GetAddressOf()));
 
    // 1-2. Create Swap Chain
    // Release the previous swapchain we will be recreating.
    mSwapChain.Reset();
 
    DXGI_SWAP_CHAIN_DESC sd;
    sd.BufferDesc.Width = WIDTH;
    sd.BufferDesc.Height = HEIGHT;
    sd.BufferDesc.RefreshRate.Numerator = 60;
    sd.BufferDesc.RefreshRate.Denominator = 1;
    sd.BufferDesc.Format = mBackBufferFormat;
    sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
    sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
    sd.SampleDesc.Count = 1;
    sd.SampleDesc.Quality = 0;
    sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    sd.BufferCount = SwapChainBufferCount;
    sd.OutputWindow = hWnd;
    sd.Windowed = true;
    sd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
    sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
 
    // Note: Swap chain uses queue to perform flush.
    mdxgiFactory->CreateSwapChain(
        mCommandQueue.Get(),
        &sd,
        mSwapChain.GetAddressOf());
 
 
    // 1-3. Create Rtv And Dsv DescriptorHeaps
    D3D12_DESCRIPTOR_HEAP_DESC rtvHeapDesc;
    rtvHeapDesc.NumDescriptors = SwapChainBufferCount;
    rtvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
    rtvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
    rtvHeapDesc.NodeMask = 0;
    md3dDevice->CreateDescriptorHeap(
        &rtvHeapDesc, IID_PPV_ARGS(mRtvHeap.GetAddressOf()));
 
    // Flush before changing any resources.
    FlushCommandQueue();
 
    // Release the previous resources we will be recreating.
    for (int i = 0; i < SwapChainBufferCount; ++i)
        mSwapChainBuffer[i].Reset();
 
    // Resize the swap chain.
    mSwapChain->ResizeBuffers(
        SwapChainBufferCount,
        WIDTH, HEIGHT,
        mBackBufferFormat,
        DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH);
 
    mCurrBackBuffer = 0;
 
    CD3DX12_CPU_DESCRIPTOR_HANDLE rtvHeapHandle(mRtvHeap->GetCPUDescriptorHandleForHeapStart());
    for (UINT i = 0; i < SwapChainBufferCount; i++) {
        mSwapChain->GetBuffer(i, IID_PPV_ARGS(&mSwapChainBuffer[i]));
        md3dDevice->CreateRenderTargetView(mSwapChainBuffer[i].Get(), nullptr, rtvHeapHandle);
        rtvHeapHandle.Offset(1, mRtvDescriptorSize);
    }
 
    // Update the viewport transform to cover the client area.
    mScreenViewport.TopLeftX = 0;
    mScreenViewport.TopLeftY = 0;
    mScreenViewport.Width = static_cast<float>(WIDTH);
    mScreenViewport.Height = static_cast<float>(HEIGHT);
    mScreenViewport.MinDepth = 0.0f;
    mScreenViewport.MaxDepth = 1.0f;
 
    mScissorRect = { 00, WIDTH, HEIGHT };
    
    std::array<Vertex, 3> vertices = {
        Vertex({ DirectX::XMFLOAT3(0.f, 1.0f, .0f), DirectX::XMFLOAT4(DirectX::Colors::Blue) }),
        Vertex({ DirectX::XMFLOAT3(cos(DirectX::XM_PI / 6.0f), -sin(DirectX::XM_PI / 6.0f), .0f), DirectX::XMFLOAT4(DirectX::Colors::Red) }),
        Vertex({ DirectX::XMFLOAT3(-cos(DirectX::XM_PI / 6.0f), -sin(DirectX::XM_PI / 6.0f), .0f), DirectX::XMFLOAT4(DirectX::Colors::Green) }),
    };
 
    std::array<std::uint16_t, 3> indices = { 012 };
 
    vbByteSize = (UINT)vertices.size() * sizeof(Vertex);
    ibByteSize = (UINT)indices.size() * sizeof(std::uint16_t);
 
    md3dDevice->CreateCommittedResource(
        &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),
        D3D12_HEAP_FLAG_NONE,
        &CD3DX12_RESOURCE_DESC::Buffer(vbByteSize),
        D3D12_RESOURCE_STATE_GENERIC_READ,
        nullptr,
        IID_PPV_ARGS(VertexBufferGPU.GetAddressOf()));
 
    // 생성된 리소스에 vertices의 정보를 넣어야 한다.
    // Copy the triangle data to the vertex buffer.
    void* vertexDataBuffer = nullptr;
    CD3DX12_RANGE vertexReadRange(00); // We do not intend to read from this resource on the CPU.
    VertexBufferGPU->Map(0&vertexReadRange, &vertexDataBuffer);
    ::memcpy(vertexDataBuffer, &vertices[0], vbByteSize);
    VertexBufferGPU->Unmap(0, nullptr);
 
    md3dDevice->CreateCommittedResource(
        &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),
        D3D12_HEAP_FLAG_NONE,
        &CD3DX12_RESOURCE_DESC::Buffer(ibByteSize),
        D3D12_RESOURCE_STATE_GENERIC_READ,
        nullptr,
        IID_PPV_ARGS(IndexBufferGPU.GetAddressOf()));
 
    // 생성된 리소스에 indexes의 정보를 넣어야 한다.
    // Copy the triangle data to the index buffer.
    void* indexDataBuffer = nullptr;
    CD3DX12_RANGE indexReadRange(00); // We do not intend to read from this resource on the CPU.
    IndexBufferGPU->Map(0&indexReadRange, &indexDataBuffer);
    ::memcpy(indexDataBuffer, &indices[0], ibByteSize);
    IndexBufferGPU->Unmap(0, nullptr);
 
       
    
    // 3. Build Constant Buffers
    UINT objCBByteSize = (sizeof(ObjectConstants) + 255& ~255;
    md3dDevice->CreateCommittedResource(
        &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),
        D3D12_HEAP_FLAG_NONE,
        &CD3DX12_RESOURCE_DESC::Buffer(objCBByteSize),
        D3D12_RESOURCE_STATE_GENERIC_READ,
        nullptr,
        IID_PPV_ARGS(&mObjectCBPos));   
 
    D3D12_DESCRIPTOR_HEAP_DESC cbvHeapDesc;
    cbvHeapDesc.NumDescriptors = 1;
    cbvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
    cbvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
    cbvHeapDesc.NodeMask = 0;
    md3dDevice->CreateDescriptorHeap(&cbvHeapDesc,
        IID_PPV_ARGS(&mCbvHeap));
 
    D3D12_GPU_VIRTUAL_ADDRESS cbAddress = mObjectCBPos->GetGPUVirtualAddress();
    // Offset to the ith object constant buffer in the buffer.
 
    D3D12_CONSTANT_BUFFER_VIEW_DESC cbvDesc;
    cbvDesc.BufferLocation = cbAddress;
    cbvDesc.SizeInBytes = objCBByteSize;
    
    md3dDevice->CreateConstantBufferView(
        &cbvDesc,
        mCbvHeap->GetCPUDescriptorHandleForHeapStart());    
 
    objCBByteSize = (sizeof(float+ 255& ~255;
    md3dDevice->CreateCommittedResource(
        &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),
        D3D12_HEAP_FLAG_NONE,
        &CD3DX12_RESOURCE_DESC::Buffer(objCBByteSize),
        D3D12_RESOURCE_STATE_GENERIC_READ,
        nullptr,
        IID_PPV_ARGS(&mObjectCBSize));
 
 
    // 4. Build Root Signature
    // Shader programs typically require resources as input (constant buffers,
    // textures, samplers).  The root signature defines the resources the shader
    // programs expect.  If we think of the shader programs as a function, and
    // the input resources as function parameters, then the root signature can be
    // thought of as defining the function signature.  
 
    // Root parameter can be a table, root descriptor or root constants.   
 
    D3D12_ROOT_PARAMETER slotRootParameter[3];
 
    D3D12_DESCRIPTOR_RANGE descRange[1];
    descRange[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_CBV;
    descRange[0].NumDescriptors = 1;
    descRange[0].BaseShaderRegister = 0;
    descRange[0].RegisterSpace = 0;
    descRange[0].OffsetInDescriptorsFromTableStart = 0;
 
    slotRootParameter[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
    slotRootParameter[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
    slotRootParameter[0].DescriptorTable.NumDescriptorRanges = 1;
    slotRootParameter[0].DescriptorTable.pDescriptorRanges = descRange;
 
    slotRootParameter[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
    slotRootParameter[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
    slotRootParameter[1].Descriptor.ShaderRegister = 1;
    slotRootParameter[1].Descriptor.RegisterSpace = 0;
 
    slotRootParameter[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
    slotRootParameter[2].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
    slotRootParameter[2].Constants.ShaderRegister = 2;
    slotRootParameter[2].Constants.RegisterSpace = 0;
    slotRootParameter[2].Constants.Num32BitValues = 1;
 
    D3D12_ROOT_SIGNATURE_DESC rootSigDesc;
    rootSigDesc.NumParameters = 3;
    rootSigDesc.pParameters = slotRootParameter;
    rootSigDesc.NumStaticSamplers = 0;
    rootSigDesc.pStaticSamplers = nullptr;
    rootSigDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
 
    // create a root signature with a single slot which points to a descriptor range consisting of a single constant buffer
    Microsoft::WRL::ComPtr<ID3DBlob> serializedRootSig = nullptr;
    Microsoft::WRL::ComPtr<ID3DBlob> errorBlob = nullptr;
    D3D12SerializeRootSignature(&rootSigDesc, D3D_ROOT_SIGNATURE_VERSION_1,
        serializedRootSig.GetAddressOf(), errorBlob.GetAddressOf());
 
    if (errorBlob != nullptr)
    {
        ::OutputDebugStringA((char*)errorBlob->GetBufferPointer());
    }
 
    md3dDevice->CreateRootSignature(
        0,
        serializedRootSig->GetBufferPointer(),
        serializedRootSig->GetBufferSize(),
        IID_PPV_ARGS(&mRootSignature));
 
 
    // 5. Build Shaders And Input Layout
    UINT compileFlags = 0;
#if defined(DEBUG) || defined(_DEBUG)  
    compileFlags = D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION;
#endif
    Microsoft::WRL::ComPtr<ID3DBlob> errors;
    HRESULT hr1 = D3DCompileFromFile(L"Shaders\\color.hlsl", nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE,
        "VS""vs_5_0", compileFlags, 0&mvsByteCode, &errors);
    HRESULT hr2 = D3DCompileFromFile(L"Shaders\\color.hlsl", nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE,
        "PS""ps_5_0", compileFlags, 0&mpsByteCode, &errors);
 
    if (errors != nullptr)
        OutputDebugStringA((char*)errors->GetBufferPointer());
 
    mInputLayout =
    {
        { "POSITION"0, DXGI_FORMAT_R32G32B32_FLOAT, 00, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
        { "COLOR"0, DXGI_FORMAT_R32G32B32A32_FLOAT, 012, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }
    };
 
    
    // 7. Build PSO    
    D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc;
    ZeroMemory(&psoDesc, sizeof(D3D12_GRAPHICS_PIPELINE_STATE_DESC));
    psoDesc.InputLayout = { mInputLayout.data(), (UINT)mInputLayout.size() };
    psoDesc.pRootSignature = mRootSignature.Get();
    psoDesc.DepthStencilState.DepthEnable = FALSE;
    psoDesc.DepthStencilState.StencilEnable = FALSE;
    psoDesc.VS =
    {
        reinterpret_cast<BYTE*>(mvsByteCode->GetBufferPointer()),
        mvsByteCode->GetBufferSize()
    };
    psoDesc.PS =
    {
        reinterpret_cast<BYTE*>(mpsByteCode->GetBufferPointer()),
        mpsByteCode->GetBufferSize()
    };
    psoDesc.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT);
    psoDesc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT);
    psoDesc.SampleMask = UINT_MAX;
    psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
    psoDesc.NumRenderTargets = 1;
    psoDesc.RTVFormats[0= mBackBufferFormat;
    psoDesc.SampleDesc.Count = 1;
    md3dDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&mPSO));
    
 
    // Execute the initialization commands.
    mCommandList->Close();
    ID3D12CommandList* cmdsLists_[] = { mCommandList.Get() };
    mCommandQueue->ExecuteCommandLists(_countof(cmdsLists_), cmdsLists_);
 
    // Wait until initialization is complete.
    FlushCommandQueue();
}
 
 
void Update() {
    void* mappingDataBuffer = nullptr;
    D3D12_RANGE dataReadRange;
    dataReadRange.Begin = 0;
    dataReadRange.End = 0;
    mObjectCBPos->Map(0&dataReadRange, &mappingDataBuffer);
    ::memcpy(mappingDataBuffer, &objectConstants, sizeof(ObjectConstants)); 
    mObjectCBPos->Unmap(0, nullptr);
 
    mObjectCBSize->Map(0&dataReadRange, &mappingDataBuffer);
    memcpy(mappingDataBuffer, &sizeConstants, sizeof(float));
    mObjectCBSize->Unmap(0, nullptr);
 
    // 1. Update
 
    // 2. Draw
 
    // Reuse the memory associated with command recording.
    // We can only reset when the associated command lists have finished execution on the GPU.
    mDirectCmdListAlloc->Reset();
 
    // A command list can be reset after it has been added to the command queue via ExecuteCommandList.
    // Reusing the command list reuses memory.
    mCommandList->Reset(mDirectCmdListAlloc.Get(), mPSO.Get());
 
    mCommandList->SetGraphicsRootSignature(mRootSignature.Get());
 
    ID3D12DescriptorHeap* descriptorHeaps[] = { mCbvHeap.Get() };
    mCommandList->SetDescriptorHeaps(_countof(descriptorHeaps), descriptorHeaps);
 
    mCommandList->SetGraphicsRootDescriptorTable(0, mCbvHeap->GetGPUDescriptorHandleForHeapStart());
    mCommandList->SetGraphicsRootConstantBufferView(1, mObjectCBSize->GetGPUVirtualAddress());
    mCommandList->SetGraphicsRoot32BitConstants(21&rotationConstants, 0);
 
    mCommandList->RSSetViewports(1&mScreenViewport);
    mCommandList->RSSetScissorRects(1&mScissorRect);
 
    // Indicate a state transition on the resource usage.
    mCommandList->ResourceBarrier(1&CD3DX12_RESOURCE_BARRIER::Transition(mSwapChainBuffer[mCurrBackBuffer].Get(),
        D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET));
 
    // Clear the back buffer and depth buffer.
    CD3DX12_CPU_DESCRIPTOR_HANDLE cBackBufferViewHandle(
        mRtvHeap->GetCPUDescriptorHandleForHeapStart(),
        mCurrBackBuffer,
        mRtvDescriptorSize);
    mCommandList->ClearRenderTargetView(cBackBufferViewHandle, DirectX::Colors::LightSteelBlue, 0, nullptr);
    // Specify the buffers we are going to render to.
    mCommandList->OMSetRenderTargets(1&cBackBufferViewHandle, false, nullptr);
 
    D3D12_VERTEX_BUFFER_VIEW vbv;
    vbv.BufferLocation = VertexBufferGPU->GetGPUVirtualAddress();
    vbv.StrideInBytes = sizeof(Vertex);
    vbv.SizeInBytes = vbByteSize;
    mCommandList->IASetVertexBuffers(01&vbv);
    D3D12_INDEX_BUFFER_VIEW ibv;
    ibv.BufferLocation = IndexBufferGPU->GetGPUVirtualAddress();
    ibv.Format = DXGI_FORMAT_R16_UINT;
    ibv.SizeInBytes = ibByteSize;
    mCommandList->IASetIndexBuffer(&ibv);
    mCommandList->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
 
    mCommandList->DrawIndexedInstanced(31000);
 
    // Indicate a state transition on the resource usage.
    mCommandList->ResourceBarrier(1&CD3DX12_RESOURCE_BARRIER::Transition(mSwapChainBuffer[mCurrBackBuffer].Get(),
        D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT));
 
    // Done recording commands.
    mCommandList->Close();
 
    // Add the command list to the queue for execution.
    ID3D12CommandList* cmdsLists[] = { mCommandList.Get() };
    mCommandQueue->ExecuteCommandLists(_countof(cmdsLists), cmdsLists);
 
    // swap the back and front buffers
    mSwapChain->Present(00);
    mCurrBackBuffer = (mCurrBackBuffer + 1) % SwapChainBufferCount;
 
    // Wait until frame commands are complete.  This waiting is inefficient and is
    // done for simplicity.  Later we will show how to organize our rendering code
    // so we do not have to wait per frame.
    FlushCommandQueue();
}
 
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance
    , LPSTR lpszCmdParam, int nCmdShow)
{
    g_hInst = hInstance;
 
    WndClass.cbClsExtra = 0;
    WndClass.cbWndExtra = 0;
    WndClass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
    WndClass.hCursor = LoadCursor(NULL, IDC_ARROW);
    WndClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    WndClass.hInstance = hInstance;
    WndClass.lpfnWndProc = (WNDPROC)WndProc;
    WndClass.lpszClassName = lpszClass;
    WndClass.lpszMenuName = NULL;
    WndClass.style = CS_HREDRAW | CS_VREDRAW;
    RegisterClass(&WndClass);
 
    RECT rt = { 0,0,WIDTH,HEIGHT };
    AdjustWindowRect(&rt, WS_OVERLAPPEDWINDOW, FALSE);
 
    int width, height;
    width = rt.right - rt.left;
    height = rt.bottom - rt.top;
 
    hWnd = CreateWindow(lpszClass, lpszClass, WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT, CW_USEDEFAULT, width, height,
        NULL, (HMENU)NULL, hInstance, NULL);
    ShowWindow(hWnd, nCmdShow);
 
    Init();
 
    hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_CLIENT));
 
    while (true) {
        if (PeekMessage(&msg, 000, PM_REMOVE)) {
            if (msg.message == WM_QUIT)
                break;
 
            if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) {
                TranslateMessage(&msg);
                DispatchMessage(&msg);
            }
        }
        else
            Update();
    }
    return msg.wParam;
}
 
int x, y;
LRESULT CALLBACK WndProc(HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam)
{
    switch (iMessage) {
    case WM_LBUTTONDOWN:
        x = 2 * LOWORD(lParam) - WIDTH;
        y = -2 * HIWORD(lParam) + HEIGHT;
 
        objectConstants.pos.x = (float)x / (float)WIDTH;
        objectConstants.pos.y = (float)y / (float)HEIGHT;
 
        return 0;
    case WM_KEYDOWN:
        switch (wParam) {
        case VK_LEFT:
            rotationConstants -= DirectX::XM_PI / 12;
            break;
        case VK_RIGHT:
            rotationConstants += DirectX::XM_PI / 12;
            break;
        case VK_ADD:
            sizeConstants += .1;
            break;
        case VK_SUBTRACT:
            sizeConstants -= .1;
            break;
        }
 
        return 0;
 
    case WM_DESTROY:
        PostQuitMessage(0);
        return 0;
    }
    return(DefWindowProc(hWnd, iMessage, wParam, lParam));
}
cs

 

 

좌클릭 : 삼각형 이동

좌우 방향키 : 삼각형 회전

숫자패드 +, - : 삼각형 크기

 

 

 

'computer graphics > DirectX12' 카테고리의 다른 글

24. 색이 변하는 구  (0) 2021.08.19
23. Cube 그리기  (0) 2021.08.10
20. 삼각형 그리기  (0) 2021.07.27
18. 상수 버퍼  (0) 2021.07.18
16. 정점 버퍼(Vertex Buffer)  (0) 2021.07.04
Comments