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

24. 색이 변하는 구 본문

computer graphics/DirectX12

24. 색이 변하는 구

scarecrow1992 2021. 8. 19. 00:01

 

 

 

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
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
// color.hlsl
 
//***************************************************************************************
// color.hlsl by Frank Luna (C) 2015 All Rights Reserved.
//
// Transforms and colors geometry.
//***************************************************************************************
 
cbuffer cbPosition : register(b0) {
    float4x4 gWorldViewProj;
}
 
cbuffer cbLighting : register(b1) {
    float3 gWorldLighting;
}
 
struct VertexIn
{
    float3 PosL  : POSITION;
    float4 Color : COLOR;
};
 
struct VertexOut
{
    float4 PosH  : SV_POSITION;
    float4 Color : COLOR;
};
 
 
 
VertexOut VS(VertexIn vin)
{    
    VertexOut vout;
 
    // Transform to homogeneous clip space.
    vout.PosH = mul(float4(vin.PosL, 1.0f), gWorldViewProj);
 
    // Just pass vertex color into the pixel shader.
    vout.Color = vin.Color;
 
    return vout;
}
 
float4 PS(VertexOut pin) : SV_Target{
    float4 ret;
    ret.x = gWorldLighting.x;
    ret.y = gWorldLighting.y;
    ret.z = gWorldLighting.z;
    ret.w = 1.0f;
    return ret;
    
}
 
 
 
// main.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 800
#define HEIGHT 800
#define IDC_CLIENT            109
 
#pragma comment(lib, "d3d12")
#pragma comment(lib, "dxgi")
#pragma comment(lib, "dxguid")
#pragma comment(lib, "d3dcompiler")
 
struct Vertex {
public:
    DirectX::XMFLOAT3 Pos;
    DirectX::XMFLOAT3 Normal;
 
    Vertex() {}
 
    Vertex(float px, float py, float pz, float nx, float ny, float nz) : Pos(px, py, pz), Normal(nx, ny, nz) {}
};
 
 
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;
 
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;
DXGI_FORMAT mDepthStencilFormat = DXGI_FORMAT_D24_UNORM_S8_UINT;
const int SwapChainBufferCount = 2;
 
Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> mRtvHeap;
Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> mDsvHeap;
Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> mCbvHeap;
 
UINT64 mCurrentFence = 0;
 
Microsoft::WRL::ComPtr<ID3D12Resource> mSwapChainBuffer[SwapChainBufferCount];
Microsoft::WRL::ComPtr<ID3D12Resource> mDepthStencilBuffer;
 
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> mCameraViewCB = nullptr;
UINT cameraViewCBByteSize = (sizeof(DirectX::XMFLOAT4X4) + 255& ~255;
 
Microsoft::WRL::ComPtr<ID3D12Resource> mLightingCB = nullptr;
UINT lightingCBByteSize = (sizeof(DirectX::XMFLOAT4X4) + 255& ~255;
 
float timeValue = 0;
 
Microsoft::WRL::ComPtr<ID3D12PipelineState> mPSO = nullptr;
 
 
int width, height;
 
float mPhi = DirectX::XM_PI / 3.0;
float mTheta = DirectX::XM_PI / 4.0;
float mRadius = 7;
 
 
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 CreateSphere(float radius, UINT sliceCount, UINT stackCount, std::vector<Vertex> &vertices, std::vector<std::uint16_t> &indices) {
    //
    // Compute the vertices stating at the top pole and moving down the stacks.
    //
 
    // Poles: note that there will be texture coordinate distortion as there is
    // not a unique point on the texture map to assign to the pole when mapping
    // a rectangular texture onto a sphere.
    Vertex topVertex(0.0f, +radius, 0.0f, 0.0f, +1.0f, 0.0f);
    Vertex bottomVertex(0.0f, -radius, 0.0f, 0.0f, -1.0f, 0.0f);
 
    vertices.push_back(topVertex);
 
    float phiStep = DirectX::XM_PI / stackCount;
    float thetaStep = 2.0f * DirectX::XM_PI / sliceCount;
 
    // Compute vertices for each stack ring (do not count the poles as rings).
    for (UINT i = 1; i <= stackCount - 1++i)
    {
        float phi = i * phiStep;
 
        // Vertices of ring.
        for (UINT j = 0; j <= sliceCount; ++j)
        {
            float theta = j * thetaStep;
 
            Vertex v;
 
            // spherical to cartesian
            v.Pos.x = radius * sinf(phi) * cosf(theta);
            v.Pos.y = radius * cosf(phi);
            v.Pos.z = radius * sinf(phi) * sinf(theta);
 
            DirectX::XMVECTOR p = DirectX::XMLoadFloat3(&v.Pos);
            XMStoreFloat3(&v.Normal, DirectX::XMVector3Normalize(p));
 
 
            vertices.push_back(v);
        }
    }
 
    vertices.push_back(bottomVertex);
 
    //
    // Compute indices for top stack.  The top stack was written first to the vertex buffer
    // and connects the top pole to the first ring.
    //
 
    for (UINT i = 1; i <= sliceCount; ++i)
    {
        indices.push_back(0);
        indices.push_back(i + 1);
        indices.push_back(i);
    }
 
    //
    // Compute indices for inner stacks (not connected to poles).
    //
 
    // Offset the indices to the index of the first vertex in the first ring.
    // This is just skipping the top pole vertex.
    UINT baseIndex = 1;
    UINT ringVertexCount = sliceCount + 1;
    for (UINT i = 0; i < stackCount - 2++i)
    {
        for (UINT j = 0; j < sliceCount; ++j)
        {
            indices.push_back(baseIndex + i * ringVertexCount + j);
            indices.push_back(baseIndex + i * ringVertexCount + j + 1);
            indices.push_back(baseIndex + (i + 1* ringVertexCount + j);
 
            indices.push_back(baseIndex + (i + 1* ringVertexCount + j);
            indices.push_back(baseIndex + i * ringVertexCount + j + 1);
            indices.push_back(baseIndex + (i + 1* ringVertexCount + j + 1);
        }
    }
 
    //
    // Compute indices for bottom stack.  The bottom stack was written last to the vertex buffer
    // and connects the bottom pole to the bottom ring.
    //
 
    // South pole vertex was added last.
    UINT southPoleIndex = vertices.size() - 1;
 
    // Offset the indices to the index of the first vertex in the last ring.
    baseIndex = southPoleIndex - ringVertexCount;
 
    for (UINT i = 0; i < sliceCount; ++i)
    {
        indices.push_back(southPoleIndex);
        indices.push_back(baseIndex + i);
        indices.push_back(baseIndex + i + 1);
    }
}
 
 
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));
 
 
    // 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.
 
    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());
 
    mCurrBackBuffer = 0;
 
    // 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()));
 
    
    D3D12_DESCRIPTOR_HEAP_DESC dsvHeapDesc;
    dsvHeapDesc.NumDescriptors = 1;
    dsvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV;
    dsvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
    dsvHeapDesc.NodeMask = 0;
    md3dDevice->CreateDescriptorHeap(
        &dsvHeapDesc, IID_PPV_ARGS(mDsvHeap.GetAddressOf()));
    
    // Flush before changing any resources.
    // Resize the swap chain.
 
 
    mRtvDescriptorSize = md3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
 
    //CD3DX12_CPU_DESCRIPTOR_HANDLE rtvHeapHandle(mRtvHeap->GetCPUDescriptorHandleForHeapStart());
    D3D12_CPU_DESCRIPTOR_HANDLE rtvHeapHandle;
    rtvHeapHandle.ptr = mRtvHeap->GetCPUDescriptorHandleForHeapStart().ptr;
    for (UINT i = 0; i < SwapChainBufferCount; i++) {
        mSwapChain->GetBuffer(i, IID_PPV_ARGS(&mSwapChainBuffer[i]));
        md3dDevice->CreateRenderTargetView(mSwapChainBuffer[i].Get(), nullptr, rtvHeapHandle);
        rtvHeapHandle.ptr += mRtvDescriptorSize;
    }
    // Create the depth/stencil buffer and view.
    
    D3D12_RESOURCE_DESC depthStencilDesc;
    depthStencilDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
    depthStencilDesc.Alignment = 0;
    depthStencilDesc.Width = WIDTH;
    depthStencilDesc.Height = HEIGHT;
    depthStencilDesc.DepthOrArraySize = 1;
    depthStencilDesc.MipLevels = 1;
 
    // Correction 11/12/2016: SSAO chapter requires an SRV to the depth buffer to read from 
    // the depth buffer.  Therefore, because we need to create two views to the same resource:
    //   1. SRV format: DXGI_FORMAT_R24_UNORM_X8_TYPELESS
    //   2. DSV Format: DXGI_FORMAT_D24_UNORM_S8_UINT
    // we need to create the depth buffer resource with a typeless format.  
    depthStencilDesc.Format = DXGI_FORMAT_R24G8_TYPELESS;
 
    depthStencilDesc.SampleDesc.Count = 1;
    depthStencilDesc.SampleDesc.Quality = 0;
    depthStencilDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
    depthStencilDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
    
    
    D3D12_CLEAR_VALUE optClear;
    optClear.Format = mDepthStencilFormat;
    optClear.DepthStencil.Depth = 1.0f;
    optClear.DepthStencil.Stencil = 0;
    md3dDevice->CreateCommittedResource(
        &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT),
        D3D12_HEAP_FLAG_NONE,
        &depthStencilDesc,
        D3D12_RESOURCE_STATE_COMMON,
        &optClear,
        IID_PPV_ARGS(mDepthStencilBuffer.GetAddressOf()));
    
 
    // Create descriptor to mip level 0 of entire resource using the format of the resource.
    
    D3D12_DEPTH_STENCIL_VIEW_DESC dsvDesc;
    dsvDesc.Flags = D3D12_DSV_FLAG_NONE;
    dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D;
    dsvDesc.Format = mDepthStencilFormat;
    dsvDesc.Texture2D.MipSlice = 0;
    md3dDevice->CreateDepthStencilView(mDepthStencilBuffer.Get(), &dsvDesc, mDsvHeap->GetCPUDescriptorHandleForHeapStart());
    
 
    // Transition the resource from its initial state to be used as a depth buffer.
    mCommandList->ResourceBarrier(1&CD3DX12_RESOURCE_BARRIER::Transition(mDepthStencilBuffer.Get(),
        D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_DEPTH_WRITE));
 
    // Start off in a closed state.  This is because the first time we refer 
    // to the command list we will Reset it, and it needs to be closed before
    // calling Reset.
    mCommandList->Close();
 
    // Execute the resize commands.
    ID3D12CommandList* cmdsLists[] = { mCommandList.Get() };
    mCommandQueue->ExecuteCommandLists(_countof(cmdsLists), cmdsLists);
 
    // Wait until resize is complete.
    FlushCommandQueue();
    
    // 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 };
 
 
    // 6. Build Box Geometry
    std::vector<Vertex> vertices;
    std::vector<std::uint16_t> indices;
    CreateSphere(0.5f, 6060, vertices, indices);
 
    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
    
    md3dDevice->CreateCommittedResource(
        &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),
        D3D12_HEAP_FLAG_NONE,
        &CD3DX12_RESOURCE_DESC::Buffer(sizeof(DirectX::XMFLOAT4X4)),
        D3D12_RESOURCE_STATE_GENERIC_READ,
        nullptr,
        IID_PPV_ARGS(&mCameraViewCB));       
 
    md3dDevice->CreateCommittedResource(
        &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),
        D3D12_HEAP_FLAG_NONE,
        &CD3DX12_RESOURCE_DESC::Buffer(sizeof(DirectX::XMFLOAT3)),
        D3D12_RESOURCE_STATE_GENERIC_READ,
        nullptr,
        IID_PPV_ARGS(&mLightingCB));
 
 
    
    /*/
    BYTE* ConstantDataBuffer = nullptr;
    CD3DX12_RANGE ConstantReadRange(00); // We do not intend to read from this resource on the CPU.
    mObjectCB->Map(0, nullptr, reinterpret_cast<void**>(&ConstantDataBuffer));
 
    DirectX::XMFLOAT4X4 tmp
            (0.2f, 0.4f, 0.6f, 0.8f,
            0.2f, 0.4f, 0.6f, 0.8f,
            0.2f, 0.4f, 0.6f, 0.8f,
            0.2f, 0.4f, 0.6f, 0.8f);
 
    ::memcpy(&ConstantDataBuffer[objCBByteSize], &tmp, sizeof(DirectX::XMFLOAT4X4));
    mObjectCB->Unmap(0, nullptr);
    */
 
    D3D12_DESCRIPTOR_HEAP_DESC cbvHeapDesc;
    cbvHeapDesc.NumDescriptors = 2;
    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;
    // Offset to the ith object constant buffer in the buffer.
 
    D3D12_CONSTANT_BUFFER_VIEW_DESC cbvDesc;
 
    D3D12_CPU_DESCRIPTOR_HANDLE mCbvHeapHandle = mCbvHeap->GetCPUDescriptorHandleForHeapStart();
    mCbvSrvUavDescriptorSize = md3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
 
    cbAddress = mCameraViewCB->GetGPUVirtualAddress();
    cbvDesc.BufferLocation = cbAddress;
    cbvDesc.SizeInBytes = cameraViewCBByteSize;
    md3dDevice->CreateConstantBufferView(
        &cbvDesc,
        mCbvHeapHandle);
 
    mCbvHeapHandle.ptr += mCbvSrvUavDescriptorSize;
 
    cbAddress = mLightingCB->GetGPUVirtualAddress();
    cbvDesc.BufferLocation = cbAddress;
    cbvDesc.SizeInBytes = lightingCBByteSize;
    md3dDevice->CreateConstantBufferView(
        &cbvDesc,
        mCbvHeapHandle);
 
    // 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[1];
 
    D3D12_DESCRIPTOR_RANGE descRange[1];
 
    descRange[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_CBV;
    descRange[0].NumDescriptors = 2;
    descRange[0].BaseShaderRegister = 0;
    descRange[0].RegisterSpace = 0;
    descRange[0].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
 
    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;
 
    D3D12_ROOT_SIGNATURE_DESC rootSigDesc;
    rootSigDesc.NumParameters = 1;
    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);
    if (errors != nullptr)
        OutputDebugStringA((char*)errors->GetBufferPointer());
 
    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.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.RasterizerState.FillMode = D3D12_FILL_MODE_WIREFRAME;
    psoDesc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT);
    psoDesc.DepthStencilState = CD3DX12_DEPTH_STENCIL_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;
    psoDesc.SampleDesc.Quality = 0;
    psoDesc.DSVFormat = mDepthStencilFormat;
    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() {
    // Convert Spherical to Cartesian coordinates.
    float x = mRadius * sinf(mPhi) * sinf(mTheta);
    float z = mRadius * sinf(mPhi) * cosf(mTheta);
    float y = mRadius * cosf(mPhi);
 
    DirectX::XMVECTOR position = DirectX::XMVectorSet(x, y, z, 1.0f);
    DirectX::XMVECTOR org = DirectX::XMVectorZero();
    DirectX::XMVECTOR up = DirectX::XMVectorSet(01.000.0);
 
    DirectX::XMMATRIX world(
        1000,
        0100,
        0010,
        0001);
 
    DirectX::XMMATRIX view = DirectX::XMMatrixLookAtLH(position, org, up);
 
    DirectX::XMMATRIX proj = DirectX::XMMatrixPerspectiveFovLH(0.25f * DirectX::XM_PI, (float)WIDTH / (float)HEIGHT, 0.1f, 50);
 
    DirectX::XMMATRIX worldviewProj = world * view * proj;
    DirectX::XMFLOAT4X4 objectConstants;
    DirectX::XMStoreFloat4x4(&objectConstants, DirectX::XMMatrixTranspose(worldviewProj));
 
    BYTE* mappingDataBuffer = nullptr;
    D3D12_RANGE dataReadRange;
    dataReadRange.Begin = 0;
    dataReadRange.End = 0;
    mCameraViewCB->Map(0, nullptr, reinterpret_cast<void**>(&mappingDataBuffer));
    ::memcpy(mappingDataBuffer, &objectConstants, sizeof(DirectX::XMFLOAT4X4));
    mCameraViewCB->Unmap(0, nullptr);
 
    BYTE* mappingDataBuffer_ = nullptr;
    timeValue += 0.001f;
    if (timeValue <= 0)  timeValue = 0;
    DirectX::XMFLOAT3 color;
    color.x = 0.5f * cosf(0.5f * timeValue) + 0.5f;
    color.y = 0.5f * cosf(0.75f * timeValue) + 0.5f;
    color.z = 0.5f * cosf(timeValue) + 0.5f;
 
 
    mLightingCB->Map(0, nullptr, reinterpret_cast<void**>(&mappingDataBuffer_));
    ::memcpy(mappingDataBuffer_, &color, sizeof(DirectX::XMFLOAT4X4));
    mLightingCB->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);
    
    
    
    D3D12_GPU_DESCRIPTOR_HANDLE mCbvHeapHandle = mCbvHeap->GetGPUDescriptorHandleForHeapStart();
    mCommandList->SetGraphicsRootDescriptorTable(0, mCbvHeapHandle);
    mCbvHeapHandle.ptr += mCbvSrvUavDescriptorSize;
 
 
 
    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);
   
    D3D12_CPU_DESCRIPTOR_HANDLE dsvHandle = mDsvHeap->GetCPUDescriptorHandleForHeapStart();
    mCommandList->ClearDepthStencilView(dsvHandle, D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, 1.0f, 00, nullptr);
 
    // Specify the buffers we are going to render to.
    mCommandList->OMSetRenderTargets(1&cBackBufferViewHandle, true&dsvHandle);
 
 
    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(ibByteSize / sizeof(std::uint16_t), 1000);
 
    // 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 | CS_DBLCLKS;
    RegisterClass(&WndClass);
 
    RECT rt = { 0,0,WIDTH,HEIGHT };
    AdjustWindowRect(&rt, WS_OVERLAPPEDWINDOW, FALSE);
 
    
    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 lastMousePosX, lastMousePosY;
bool isLButtonDown, isRButtonDown;
LRESULT CALLBACK WndProc(HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam)
{
    switch (iMessage) {
    case WM_CREATE:
        isLButtonDown = false;
        isRButtonDown = false;
        return 0;
 
    case WM_LBUTTONDOWN:
        isLButtonDown = true;
        lastMousePosX = LOWORD(lParam);
        lastMousePosY = HIWORD(lParam);
        return 0;
 
 
    case WM_RBUTTONDOWN:
        isRButtonDown = true;
        lastMousePosY = HIWORD(lParam);
        return 0;
 
        
    case WM_LBUTTONUP:
        isLButtonDown = false;
        return 0;
 
 
    case WM_RBUTTONUP:
        isRButtonDown = false;
        return 0;
 
    case WM_MOUSEMOVE: {
        int y = HIWORD(lParam);
        float dy = -DirectX::XMConvertToRadians(0.25f * static_cast<float>(y - lastMousePosY));
 
        if (isLButtonDown == true) {
            int x = LOWORD(lParam);
            float dx = DirectX::XMConvertToRadians(0.25f * static_cast<float>(x - lastMousePosX));
 
            mTheta += dx;
            lastMousePosX = x;
 
            mPhi += dy;
 
            if (mPhi >= DirectX::XM_PI) mPhi = DirectX::XM_PI - 0.001f;
            if (mPhi <= 0)              mPhi = 0.001f;
 
            lastMousePosY = y;
        }
 
        if (isRButtonDown == true) {
            mRadius += -2 * dy;
 
            if (mRadius <= 3.f) mRadius = 3.f;
            if (mRadius >= 10.0f) mRadius = 10.0f;
 
            lastMousePosY = y;
        }
        return 0;
    }
 
 
    case WM_DESTROY:
        PostQuitMessage(0);
        return 0;
    }
    return(DefWindowProc(hWnd, iMessage, wParam, lParam));
}
 
cs

 

 

하나의 descriptor heap에 2개의 CBV를 섞은 후 descriptor table로 서명된 register에 binding 한다.

 

 

 

 

 

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

27. 텍스처 적용(Texturing)  (0) 2021.09.19
26. 좌표 변환  (0) 2021.08.23
23. Cube 그리기  (0) 2021.08.10
22. 삼각형 그리기 2  (0) 2021.08.05
20. 삼각형 그리기  (0) 2021.07.27
Comments