Udostępnij za pomocą


Używanie głębokości i efektów na prymitywach

W tym miejscu pokazano, jak używać głębokości, perspektywy, koloru i innych efektów dla elementów pierwotnych.

Objective: Utwórz obiekt 3D i zastosuj do niego podstawowe oświetlenie wierzchołkowe oraz kolorowanie.

Wymagania wstępne

Zakładamy, że znasz język C++. Potrzebujesz również podstawowego doświadczenia z pojęciami programowania graficznego.

Zakładamy również, że przeszedłeś/przeszłaś przez Szybki start: konfigurowanie zasobów DirectX i wyświetlanie obrazu oraz Tworzenie shaderów i rysowanie prymitywów.

Czas do ukończenia: 20 minut.

Instrukcje

1. Definiowanie zmiennych kostki

Najpierw należy zdefiniować struktury SimpleCubeVertex i ConstantBuffer dla sześcianu. Te struktury określają położenie wierzchołka i kolory modułu oraz sposób wyświetlania modułu. Deklarujemy ID3D11DepthStencilView oraz ID3D11Buffer za pomocą ComPtr i deklarujemy instancję ConstantBuffer.

struct SimpleCubeVertex
{
    DirectX::XMFLOAT3 pos;   // Position
    DirectX::XMFLOAT3 color; // Color
};

struct ConstantBuffer
{
    DirectX::XMFLOAT4X4 model;
    DirectX::XMFLOAT4X4 view;
    DirectX::XMFLOAT4X4 projection;
};

// This class defines the application as a whole.
ref class Direct3DTutorialFrameworkView : public IFrameworkView
{
private:
    Platform::Agile<CoreWindow> m_window;
    ComPtr<IDXGISwapChain1> m_swapChain;
    ComPtr<ID3D11Device1> m_d3dDevice;
    ComPtr<ID3D11DeviceContext1> m_d3dDeviceContext;
    ComPtr<ID3D11RenderTargetView> m_renderTargetView;
    ComPtr<ID3D11DepthStencilView> m_depthStencilView;
    ComPtr<ID3D11Buffer> m_constantBuffer;
    ConstantBuffer m_constantBufferData;

2. Tworzenie widoku wzornika głębokości

Oprócz tworzenia widoku render-target tworzymy również widok wzornika głębi. Widok głębokości i szablonu umożliwia Direct3D efektywne renderowanie obiektów znajdujących się bliżej kamery przed obiektami znajdującymi się dalej od kamery. Zanim utworzymy widok dla bufora głębokości-stencila, musimy utworzyć bufor głębokości-stencila. Wypełniamy D3D11_TEXTURE2D_DESC, aby opisać bufor głębokości i szablonu, a następnie wywołujemy ID3D11Device::CreateTexture2D, aby utworzyć bufor głębokości i szablonu. Aby utworzyć widok wzornika głębokości, wypełnimy D3D11_DEPTH_STENCIL_VIEW_DESC opisujący widok wzornika głębokości i przekażemy opis widoku wzornika głębokości oraz bufor wzornika głębokości do ID3D11Device::CreateDepthStencilView.

        // Once the render target view is created, create a depth stencil view.  This
        // allows Direct3D to efficiently render objects closer to the camera in front
        // of objects further from the camera.

        D3D11_TEXTURE2D_DESC backBufferDesc = {0};
        backBuffer->GetDesc(&backBufferDesc);

        D3D11_TEXTURE2D_DESC depthStencilDesc;
        depthStencilDesc.Width = backBufferDesc.Width;
        depthStencilDesc.Height = backBufferDesc.Height;
        depthStencilDesc.MipLevels = 1;
        depthStencilDesc.ArraySize = 1;
        depthStencilDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
        depthStencilDesc.SampleDesc.Count = 1;
        depthStencilDesc.SampleDesc.Quality = 0;
        depthStencilDesc.Usage = D3D11_USAGE_DEFAULT;
        depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
        depthStencilDesc.CPUAccessFlags = 0;
        depthStencilDesc.MiscFlags = 0;
        ComPtr<ID3D11Texture2D> depthStencil;
        DX::ThrowIfFailed(
            m_d3dDevice->CreateTexture2D(
                &depthStencilDesc,
                nullptr,
                &depthStencil
                )
            );

        D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
        depthStencilViewDesc.Format = depthStencilDesc.Format;
        depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
        depthStencilViewDesc.Flags = 0;
        depthStencilViewDesc.Texture2D.MipSlice = 0;
        DX::ThrowIfFailed(
            m_d3dDevice->CreateDepthStencilView(
                depthStencil.Get(),
                &depthStencilViewDesc,
                &m_depthStencilView
                )
            );

3. Aktualizowanie perspektywy za pomocą okna

Aktualizujemy parametry projekcji perspektywy dla buforu stałego w zależności od wymiarów okna. Naprawimy parametry do pola widoku 70 stopni z zakresem głębokości od 0,01 do 100.

        // Finally, update the constant buffer perspective projection parameters
        // to account for the size of the application window.  In this sample,
        // the parameters are fixed to a 70-degree field of view, with a depth
        // range of 0.01 to 100.  For a generalized camera class, see Lesson 5.

        float xScale = 1.42814801f;
        float yScale = 1.42814801f;
        if (backBufferDesc.Width > backBufferDesc.Height)
        {
            xScale = yScale *
                static_cast<float>(backBufferDesc.Height) /
                static_cast<float>(backBufferDesc.Width);
        }
        else
        {
            yScale = xScale *
                static_cast<float>(backBufferDesc.Width) /
                static_cast<float>(backBufferDesc.Height);
        }

        m_constantBufferData.projection = DirectX::XMFLOAT4X4(
            xScale, 0.0f,    0.0f,  0.0f,
            0.0f,   yScale,  0.0f,  0.0f,
            0.0f,   0.0f,   -1.0f, -0.01f,
            0.0f,   0.0f,   -1.0f,  0.0f
            );

4. Tworzenie cieniowania wierzchołków i pikseli z elementami kolorów

W tej aplikacji tworzymy bardziej złożone wierzchołki i cieniowanie pikseli niż to, co opisano w poprzednim samouczku, Tworzenie cieniowania i rysowanie elementów pierwotnych. Shader wierzchołków aplikacji przekształca każdą pozycję wierzchołka w przestrzeni projekcji i przekazuje kolor wierzchołka do shaderu pikseli.

Tablica D3D11_INPUT_ELEMENT_DESC struktur aplikacji opisujących układ kodu cieniowania wierzchołków ma dwa elementy układu: jeden element definiuje położenie wierzchołka, a drugi element definiuje kolor.

Tworzymy bufory wierzchołków, indeksów i stałych, aby zdefiniować orbitujący sześcian.

Aby zdefiniować moduł orbitujący

  1. Najpierw definiujemy sześcian. Każdemu wierzchołkowi przypisujemy zarówno kolor, jak i pozycję. Dzięki temu cieniowanie pikseli może kolorować każdą twarz inaczej, aby można było odróżnić twarz.
  2. Następnie opisujemy bufory wierzchołków i indeksów (D3D11_BUFFER_DESC i D3D11_SUBRESOURCE_DATA) przy użyciu definicji sześcianu. Wywołujemy ID3D11Device::CreateBuffer raz dla każdego buforu.
  3. Następnie utworzymy bufor stały (D3D11_BUFFER_DESC) do przekazywania macierzy modelu, widoku i projekcji do shadera wierzchołków. Później możemy użyć buforu stałego, aby obrócić moduł i zastosować do niego projekcję perspektywy. Wywołujemy ID3D11Device::CreateBuffer, aby utworzyć bufor stały.
  4. Następnie określamy przekształcenie widoku, które odpowiada pozycji aparatu X = 0, Y = 1, Z = 2.
  5. Na koniec deklarujemy zmienną stopnia o nazwie, którą będziemy używać do animowania kostki, obracając ją co każdą klatkę.
        
        auto loadVSTask = DX::ReadDataAsync(L"SimpleVertexShader.cso");
        auto loadPSTask = DX::ReadDataAsync(L"SimplePixelShader.cso");
        
        
        auto createVSTask = loadVSTask.then([this](const std::vector<byte>& vertexShaderBytecode) {        
          ComPtr<ID3D11VertexShader> vertexShader;
          DX::ThrowIfFailed(
              m_d3dDevice->CreateVertexShader(
                  vertexShaderBytecode->Data,
                  vertexShaderBytecode->Length,
                  nullptr,
                  &vertexShader
                  )
              );

          // Create an input layout that matches the layout defined in the vertex shader code.
          // For this lesson, this is simply a DirectX::XMFLOAT3 vector defining the vertex position, and
          // a DirectX::XMFLOAT3 vector defining the vertex color.
          const D3D11_INPUT_ELEMENT_DESC basicVertexLayoutDesc[] =
          {
              { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0,  0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
              { "COLOR",    0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
          };

          ComPtr<ID3D11InputLayout> inputLayout;
          DX::ThrowIfFailed(
              m_d3dDevice->CreateInputLayout(
                  basicVertexLayoutDesc,
                  ARRAYSIZE(basicVertexLayoutDesc),
                  vertexShaderBytecode->Data,
                  vertexShaderBytecode->Length,
                  &inputLayout
                  )
              );
        });
        
        
        // Load the raw pixel shader bytecode from disk and create a pixel shader with it.
        auto createPSTask = loadPSTask.then([this](const std::vector<byte>& pixelShaderBytecode) {
          ComPtr<ID3D11PixelShader> pixelShader;
          DX::ThrowIfFailed(
              m_d3dDevice->CreatePixelShader(
                  pixelShaderBytecode->Data,
                  pixelShaderBytecode->Length,
                  nullptr,
                  &pixelShader
                  )
              );
        });
        
        
        // Create vertex and index buffers that define a simple unit cube.
        auto createCubeTask = (createPSTask && createVSTask).then([this] () {

          // In the array below, which will be used to initialize the cube vertex buffers,
          // each vertex is assigned a color in addition to a position.  This will allow
          // the pixel shader to color each face differently, enabling them to be distinguished.
          SimpleCubeVertex cubeVertices[] =
          {
              { float3(-0.5f, 0.5f, -0.5f), float3(0.0f, 1.0f, 0.0f) }, // +Y (top face)
              { float3( 0.5f, 0.5f, -0.5f), float3(1.0f, 1.0f, 0.0f) },
              { float3( 0.5f, 0.5f,  0.5f), float3(1.0f, 1.0f, 1.0f) },
              { float3(-0.5f, 0.5f,  0.5f), float3(0.0f, 1.0f, 1.0f) },

              { float3(-0.5f, -0.5f,  0.5f), float3(0.0f, 0.0f, 1.0f) }, // -Y (bottom face)
              { float3( 0.5f, -0.5f,  0.5f), float3(1.0f, 0.0f, 1.0f) },
              { float3( 0.5f, -0.5f, -0.5f), float3(1.0f, 0.0f, 0.0f) },
              { float3(-0.5f, -0.5f, -0.5f), float3(0.0f, 0.0f, 0.0f) },
          };

          unsigned short cubeIndices[] =
          {
              0, 1, 2,
              0, 2, 3,

              4, 5, 6,
              4, 6, 7,

              3, 2, 5,
              3, 5, 4,

              2, 1, 6,
              2, 6, 5,

              1, 7, 6,
              1, 0, 7,

              0, 3, 4,
              0, 4, 7
          };

          D3D11_BUFFER_DESC vertexBufferDesc = {0};
          vertexBufferDesc.ByteWidth = sizeof(SimpleCubeVertex) * ARRAYSIZE(cubeVertices);
          vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
          vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
          vertexBufferDesc.CPUAccessFlags = 0;
          vertexBufferDesc.MiscFlags = 0;
          vertexBufferDesc.StructureByteStride = 0;

          D3D11_SUBRESOURCE_DATA vertexBufferData;
          vertexBufferData.pSysMem = cubeVertices;
          vertexBufferData.SysMemPitch = 0;
          vertexBufferData.SysMemSlicePitch = 0;

          ComPtr<ID3D11Buffer> vertexBuffer;
          DX::ThrowIfFailed(
              m_d3dDevice->CreateBuffer(
                  &vertexBufferDesc,
                  &vertexBufferData,
                  &vertexBuffer
                  )
              );

          D3D11_BUFFER_DESC indexBufferDesc;
          indexBufferDesc.ByteWidth = sizeof(unsigned short) * ARRAYSIZE(cubeIndices);
          indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
          indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
          indexBufferDesc.CPUAccessFlags = 0;
          indexBufferDesc.MiscFlags = 0;
          indexBufferDesc.StructureByteStride = 0;

          D3D11_SUBRESOURCE_DATA indexBufferData;
          indexBufferData.pSysMem = cubeIndices;
          indexBufferData.SysMemPitch = 0;
          indexBufferData.SysMemSlicePitch = 0;

          ComPtr<ID3D11Buffer> indexBuffer;
          DX::ThrowIfFailed(
              m_d3dDevice->CreateBuffer(
                  &indexBufferDesc,
                  &indexBufferData,
                  &indexBuffer
                  )
              );


          // Create a constant buffer for passing model, view, and projection matrices
          // to the vertex shader.  This will allow us to rotate the cube and apply
          // a perspective projection to it.

          D3D11_BUFFER_DESC constantBufferDesc = {0};
          constantBufferDesc.ByteWidth = sizeof(m_constantBufferData);
          constantBufferDesc.Usage = D3D11_USAGE_DEFAULT;
          constantBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
          constantBufferDesc.CPUAccessFlags = 0;
          constantBufferDesc.MiscFlags = 0;
          constantBufferDesc.StructureByteStride = 0;
          DX::ThrowIfFailed(
              m_d3dDevice->CreateBuffer(
                  &constantBufferDesc,
                  nullptr,
                  &m_constantBuffer
                  )
              );

          // Specify the view transform corresponding to a camera position of
          // X = 0, Y = 1, Z = 2.  For a generalized camera class, see Lesson 5.

          m_constantBufferData.view = DirectX::XMFLOAT4X4(
              -1.00000000f, 0.00000000f,  0.00000000f,  0.00000000f,
               0.00000000f, 0.89442718f,  0.44721359f,  0.00000000f,
               0.00000000f, 0.44721359f, -0.89442718f, -2.23606800f,
               0.00000000f, 0.00000000f,  0.00000000f,  1.00000000f
              );

        });
        
        // This value will be used to animate the cube by rotating it every frame.
        float degree = 0.0f;
        

5. Obracanie i rysowanie modułu oraz prezentowanie renderowanego obrazu

Uruchamiamy nieskończoną pętlę, aby nieprzerwanie renderować i wyświetlać scenę. Nazywamy wbudowaną funkcję rotationY (BasicMath.h) z wartością rotacji, która ustawi wartości potrzebne do obrotu macierzy modelu sześcianu wokół osi Y. Następnie wywołujemy ID3D11DeviceContext::UpdateSubresource, aby zaktualizować bufor stały i obrócić model sześcianu. Wywołujemy ID3D11DeviceContext::OMSetRenderTargets, aby ustawić docelowy punkt renderowania jako wyjściowy. W tym wywołanie OMSetRenderTargets przekazujemy widok wzornika głębokości. Wywołujemy ID3D11DeviceContext::ClearRenderTargetView, aby wyczyścić element docelowy renderowania na jednolity niebieski kolor, oraz wywołujemy ID3D11DeviceContext::ClearDepthStencilView, aby wyczyścić bufor głębokości.

W nieskończonej pętli rysujemy również sześcian na niebieskiej powierzchni.

Aby narysować sześcian

  1. Najpierw wywołujemy ID3D11DeviceContext::IASetInputLayout, aby opisać sposób przesyłania danych buforu wierzchołka do etapu asemblera wejściowego.
  2. Następnie wywołujemy ID3D11DeviceContext::IASetVertexBuffers i ID3D11DeviceContext::IASetIndexBuffer, aby powiązać bufory wierzchołków i indeksów z etapem input-assembler.
  3. Następnie wywołamy ID3D11DeviceContext::IASetPrimitiveTopology z wartością D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP, aby określić etap wejściowego asemblera do interpretacji danych wierzchołka jako pasmo trójkątów.
  4. Następnie wywołamy ID3D11DeviceContext::VSSetShader w celu zainicjowania etapu cieniowania wierzchołków przy użyciu kodu cieniowania wierzchołków oraz ID3D11DeviceContext::PSSetShader w celu zainicjowania etapu cieniowania pikseli za pomocą kodu cieniowania pikseli.
  5. Następnie wywołamy ID3D11DeviceContext::VSSetConstantBuffers, aby ustawić stały bufor używany przez etap potoku cieniowania wierzchołka.
  6. Na koniec wywołamy ID3D11DeviceContext::DrawIndexed, aby narysować sześcian i przesłać go do potoku renderowania.

Wywołujemy IDXGISwapChain::Present, aby zaprezentować renderowany obraz w oknie.

            // Update the constant buffer to rotate the cube model.
            m_constantBufferData.model = XMMatrixRotationY(-degree);
            degree += 1.0f;

            m_d3dDeviceContext->UpdateSubresource(
                m_constantBuffer.Get(),
                0,
                nullptr,
                &m_constantBufferData,
                0,
                0
                );

            // Specify the render target and depth stencil we created as the output target.
            m_d3dDeviceContext->OMSetRenderTargets(
                1,
                m_renderTargetView.GetAddressOf(),
                m_depthStencilView.Get()
                );

            // Clear the render target to a solid color, and reset the depth stencil.
            const float clearColor[4] = { 0.071f, 0.04f, 0.561f, 1.0f };
            m_d3dDeviceContext->ClearRenderTargetView(
                m_renderTargetView.Get(),
                clearColor
                );

            m_d3dDeviceContext->ClearDepthStencilView(
                m_depthStencilView.Get(),
                D3D11_CLEAR_DEPTH,
                1.0f,
                0
                );

            m_d3dDeviceContext->IASetInputLayout(inputLayout.Get());

            // Set the vertex and index buffers, and specify the way they define geometry.
            UINT stride = sizeof(SimpleCubeVertex);
            UINT offset = 0;
            m_d3dDeviceContext->IASetVertexBuffers(
                0,
                1,
                vertexBuffer.GetAddressOf(),
                &stride,
                &offset
                );

            m_d3dDeviceContext->IASetIndexBuffer(
                indexBuffer.Get(),
                DXGI_FORMAT_R16_UINT,
                0
                );

            m_d3dDeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

            // Set the vertex and pixel shader stage state.
            m_d3dDeviceContext->VSSetShader(
                vertexShader.Get(),
                nullptr,
                0
                );

            m_d3dDeviceContext->VSSetConstantBuffers(
                0,
                1,
                m_constantBuffer.GetAddressOf()
                );

            m_d3dDeviceContext->PSSetShader(
                pixelShader.Get(),
                nullptr,
                0
                );

            // Draw the cube.
            m_d3dDeviceContext->DrawIndexed(
                ARRAYSIZE(cubeIndices),
                0,
                0
                );

            // Present the rendered image to the window.  Because the maximum frame latency is set to 1,
            // the render loop will generally be throttled to the screen refresh rate, typically around
            // 60 Hz, by sleeping the application on Present until the screen is refreshed.
            DX::ThrowIfFailed(
                m_swapChain->Present(1, 0)
                );

Podsumowanie i następne kroki

Użyliśmy głębokości, perspektywy, koloru i innych efektów na prymitywach.

Następnie stosujemy tekstury do elementów pierwotnych.

stosowanie tekstur do elementów pierwotnych