화면에 2D 이미지를 그리는 것은 정말 유용합니다. 예를 들어 대부분의 유저 인터페이스(UI), 스프라이트 시스템, 텍스트 엔진들은 2D 이미지들로 만들어져 있습니다. DirectX 11 에서는 도형에 2D 이미지들을 매핑하고 정사영 행렬을 이용하는 방식으로 2D 이미지를 그릴 수 있게 해 줍니다.
2D 화면 좌표계
2D 이미지를 화면에 그리기 위해서는 화면의 X,Y 좌표를 계산해야 합니다. DirectX에서는 스크린의 중앙이 (0, 0) 입니다. 그리고 중앙을 기준으로 왼쪽과 아래쪽 화면이 음수 좌표가 되고, 오른쪽과 위쪽 화면 좌표는 양수 방향이 됩니다. 예를 들어 1024 x 768 해상도의 화면이 있다면 화면 경계의 좌표는 다음과 같습니다.
올바르게 2D 렌더링을 하기 위해서는 이 화면의 좌표계를 기준으로 이루어진다는 것, 그리고 유저의 윈도우/스크린 크기를 알아야 합니다!
DirectX 11 에서 Z 버퍼 해제하기
2D 화면을 그리기 위해서는 Z버퍼를 사용하지 않아야 합니다. 그래야 해당 픽셀에 올바로 새로운 색상을 덮어쓰는 것이 가능해집니다. 뒤쪽부터 그리기 시작해서 맨 앞을 나중에 그리는 화가 알고리즘(Painter's Algorithm)에 따라 여러분이 원하는 결과물을 그릴 수 있을 것입니다. 일단 2D 홤년을 다 그렸다면 Z버퍼를 켜서 다시 3D 객체를 그릴 수 있습니다.
Z 버퍼를 키고 끄기 위해ㅔ서는 이전의 깊이 스텐실 상태와 같지만 DepthEnable 변수만 false로 지정된 두번째 깊이 스텐실 상태를 만들어야 합니다. 그 다음에는 OMSetDepthStencilState 함수를 사용하여 두 상태를 바꿔치기 함으로 Z버퍼를 켜고 끌 수 있게 됩니다.
동점 정점 버퍼(Dynamic Vertex Buffer)
새로 소개하게 될 또 다른 컨셉은 바로 동적 정점 버퍼입니다. 지금까지의 튜토리얼에서는 정적 정점 버퍼(Static Vertex Buffer)만을 사용했었습니다. 정적 정점 버퍼의 문제점은 버퍼 내부의 값을 바꿀 수 없다는 것입니다. 동적 정점 버퍼는 필요하다면 매 프레임마다 정점 버퍼의 내용을 바꿀 수 있게 해 줍니다. 정적 정점 버퍼보다는 속도가 떨어지지만 이전에는 할 수 없었던 추가 기능이 지원된다는 이점이 있는 것입니다.
2D 렌더링에서 동점 정적 버퍼를 사용하는 이유는 종종 이미지를 화면 내 다양한 위치로 옮겨야 하는 경우가 있기 때문입니다. 좋은 예로 마우스 포인터가 있습니다. 마우스 포인터는 수시로 움직이기 때문에 위치를 표시하는 정점 데이터 역시 그 값이 자주 바뀌어야 합니다.
기억해야 할 두 가지 점이 있습니다. 동적 정점 버퍼는 정적인 것보다 속도가 뒤쳐지기 때문에 필요한 경우에만 사용해야 합니다. 그리고 매 프레임마다 정적 정점 버퍼를 없애고 다시 생성하는 것 역시 지양해야 합니다. 이렇게 되면 그래픽 카드를 저의 완전히 잠그는 표과가 있기 때문에 동적 정점 버퍼르 쓰는 것보다 성능이 현저히 떨어지게 됩니다.
DirectX 11에서의 정사영(Orthographic Projection)
2D 이지를 그리기 위해 필요한 마지막 컨셉은 바로 일반 3D 투영 행렬이 아닌 정사영 행렬을 사용하는 것입니다. 이를 통해 2D 화면의 좌표에 그릴 수 있게 됩니다.
_orthoMatrix = XMMatrixOrthographicLH((float)screenWidth, (float)screenHeight, screenNear, screenDepth);
프레임워크
이번 2D 렌더링의 가장 큰 차이점은 ModelClass 가 BitmapClass로 교체되었고 LightShaderClass 대신 TextureShaderClass를 다시 사용한다는 것입니다.
BitmapClass는 화면에 그리는데 필요한 각 이미지를 표현하는 데 사용될 것입니다. 따라서 모든 2D 이미지에 대해 각각 BitmapClass를 만들어 주어야 합니다. 이 클래스는 3D 객체 대신 2D 이미지를 다루는 ModelClass의 변형이라는 것을 참고하시기 바랍니다.
BitmapClass
BitmapClass.h
#pragma once
class TextureClass;
class BitmapClass
{
private:
struct VertexType
{
XMFLOAT3 position;
XMFLOAT2 texture;
};
public:
BitmapClass();
BitmapClass(const BitmapClass& other);
~BitmapClass();
bool Initialize(ID3D11Device* device, int screenWidth, int screenHeight, WCHAR* textureFileName, int bitmapWidth, int bitmapHeight);
void ShutDown();
bool Render(ID3D11DeviceContext* deviceContext, int positionX, int positionY);
int GetIndexCount();
ID3D11ShaderResourceView* GetTexture();
private:
bool InitializeBuffers(ID3D11Device* device);
void ShutdownBuffers();
bool UpdateBuffers(ID3D11DeviceContext* deviceContext, int positionX, int positionY);
void RenderBuffers(ID3D11DeviceContext* deviceContext);
bool LoadTexture(ID3D11Device* device, WCHAR* textureFileName);
void ReleaseTexture();
private:
ID3D11Buffer* _vertexBuffer = nullptr;
ID3D11Buffer* _indexBuffer = nullptr;
int _vertexCount = 0;
int _indexCount = 0;
TextureClass* _texture = nullptr;
각 비트맵 이미지는 여전히 3D 객체처럼 그려지는 도형입니다. 2D 이미지에는 단지 위치 벡터와 텍스쳐 좌표만 필요합니다.
int _screenWidth = 0;
int _screenHeight = 0;
int _bitmapWidth = 0;
int _bitmapHeight = 0;
int _previousPosX = 0;
int _previousPosY = 0;
};
3D 모델과는 달리 BitmapClass에서는 화면 크기, 이미지 크기, 이전에 그려졌던 위치를 기억해야 합니다. 따라서 이 정보들을 추적하는 전용 변수를 더합니다.
BitmapClass.cpp
#include "stdafx.h"
#include "Textureclass.h"
#include "BitmapClass.h"
BitmapClass::BitmapClass()
{
_vertexBuffer = 0;
_indexBuffer = 0;
_texture = 0;
}
BitmapClass::BitmapClass(const BitmapClass& other)
{
}
BitmapClass::~BitmapClass()
{
}
bool BitmapClass::Initialize(ID3D11Device* device, int screenWidth, int screenHeight, WCHAR* textureFileName, int bitmapWidth, int bitmapHeight)
{
// 화면 크기를 멤버 변수에 저장
_screenWidth = screenWidth;
_screenHeight = screenHeight;
// 렌더링할 비트맵의 픽셀 크기를 저장
_bitmapWidth = bitmapWidth;
_bitmapHeight = bitmapHeight;
// 이전 렌더링 위치를 음수로 초기화 합니다.
_previousPosX = -1;
_previousPosY = -1;
// 정점 및 인덱스 버퍼를 초기화 합니다.
if (InitializeBuffers(device) == false)
{
return false;
}
// 이 모델의 텍스쳐를 로드 합니다.
return LoadTexture(device, textureFileName);
}
void BitmapClass::ShutDown()
{
// 모델 텍스처를 해제 합니다.
ReleaseTexture();
// 버텍스 및 인덱스 버퍼를 종료 합니다.
ShutdownBuffers();
}
bool BitmapClass::Render(ID3D11DeviceContext* deviceContext, int positionX, int positionY)
{
// 화면의 다른 위치로 렌더링 하기 위해 동적 정점 버퍼를 다시 빌드합니다.
if (UpdateBuffers(deviceContext, positionX, positionY) == false)
{
return false;
}
// 그리기를 준비하기 위해 그래픽 파이프 라인에 꼭지점과 인덱스 버퍼를 놓습니다.
RenderBuffers(deviceContext);
return true;
}
int BitmapClass::GetIndexCount()
{
return _indexCount;
}
ID3D11ShaderResourceView* BitmapClass::GetTexture()
{
return _texture->GetTexture();
}
bool BitmapClass::InitializeBuffers(ID3D11Device* device)
{
// 정점 배열의 정점의 수와 인덱스 배열의 인덱스 수를 지정합니다.
_indexCount = _vertexCount = 6;
// 정점 배열을 만듭니다.
VertexType* vertices = new VertexType[_vertexCount];
if (vertices == false)
{
return false;
}
// 정점 배열을 0으로 초기화합니다.
memset(vertices, 0, (sizeof(VertexType) * _vertexCount));
// 인덱스 배열을 만듭니다.
unsigned long* indices = new unsigned long[_indexCount];
if (indices == false)
{
return false;
}
// 데이터로 인덱스 배열을 로드합니다.
for(int i = 0 ; i < _indexCount; i++)
{
indices[i] = i;
}
// 정적 정점 버퍼의 구조체를 설정합니다.
D3D11_BUFFER_DESC vertexBufferDesc;
vertexBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
vertexBufferDesc.ByteWidth = sizeof(VertexType) * _vertexCount;
vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertexBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
vertexBufferDesc.MiscFlags = 0;
vertexBufferDesc.StructureByteStride = 0;
// subresource 구조에 정점 데이터에 대한 포인터를 제공합니다.
D3D11_SUBRESOURCE_DATA vertexData;
vertexData.pSysMem = vertices;
vertexData.SysMemPitch = 0;
vertexData.SysMemSlicePitch = 0;
// 정점 버퍼를 만듭니다.
if (FAILED(device->CreateBuffer(&vertexBufferDesc, &vertexData, &_vertexBuffer)))
{
return false;
}
// 정적 인덱스 버퍼의 구조체를 설정합니다.
D3D11_BUFFER_DESC indexBufferDesc;
indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
indexBufferDesc.ByteWidth = sizeof(unsigned long) * _indexCount;
indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
indexBufferDesc.CPUAccessFlags = 0;
indexBufferDesc.MiscFlags = 0;
indexBufferDesc.StructureByteStride = 0;
// 인덱서 데이터를 가리키는 보조 리소스 구조체를 작성합니다.
D3D11_SUBRESOURCE_DATA indexData;
indexData.pSysMem = indices;
indexData.SysMemPitch = 0;
indexData.SysMemSlicePitch = 0;
// 인덱스 버퍼를 만듭니다.
if (FAILED(device->CreateBuffer(&indexBufferDesc, &indexData, &_indexBuffer)))
{
return false;
}
// 생성되고 값이 할당된 정점 버퍼와 인덱스 버퍼를 해제합니다.
delete[] vertices;
vertices = 0;
delete[] indices;
indices = 0;
return true;
}
void BitmapClass::ShutdownBuffers()
{
if (_indexBuffer)
{
_indexBuffer->Release();
_indexBuffer = nullptr;
}
if (_vertexBuffer)
{
_vertexBuffer->Release();
_vertexBuffer = nullptr;
}
}
bool BitmapClass::UpdateBuffers(ID3D11DeviceContext* deviceContext, int positionX, int positionY)
{
float left, right, top, bottom;
VertexType* vertices;
D3D11_MAPPED_SUBRESOURCE mappedResource;
VertexType* verticesPtr;
HRESULT result;
// 이 비트맵을 렌더링 할 위치가 변경되지 않은 경우 정점 버퍼를 업데이트하지 마세요
if ((positionX == _previousPosX) && (positionY == _previousPosY))
{
return true;
}
// 변경된 경우 렌더링 되는 위치를 업데이트 합니다.
_previousPosX = positionX;
_previousPosY = positionY;
// 비트 맵 왼쪽의 화면 좌표를 계산합니다.
left = (float)((_screenWidth / 2) * -1) + (float)positionX;
// 비트 맵 오른쪽의 화면 좌표를 계산합니다.
right = left + (float)_bitmapWidth;
// 비트 맵 상단의 화면 좌표를 계산합니다.
top = (float)(_screenHeight / 2) - (float)positionY;
// 비트 맵 아래쪽의 화면 좌표를 계산합니다.
bottom = top - (float)_bitmapHeight;
// 정점 배열을 만듭니다.
vertices = new VertexType[_vertexCount];
if (vertices == false)
{
return false;
}
// 정점 배열에 데이터를 로드합니다.
// 첫번째 삼각형
vertices[0].position = XMFLOAT3(left, top, 0.0f); // Top left
vertices[0].texture = XMFLOAT2(0.0f, 0.0f);
vertices[1].position = XMFLOAT3(right, bottom, 0.0f); // Bottom right
vertices[1].texture = XMFLOAT2(1.0f, 1.0f);
vertices[2].position = XMFLOAT3(left, bottom, 0.0f); // Bottom left
vertices[2].texture = XMFLOAT2(0.0f, 1.0f);
// 두번째 삼각형
vertices[3].position = XMFLOAT3(left, top, 0.0f); // Top left
vertices[3].texture = XMFLOAT2(0.0f, 0.0f);
vertices[4].position = XMFLOAT3(right, top, 0.0f); // Top right
vertices[4].texture = XMFLOAT2(1.0f, 0.0f);
vertices[5].position = XMFLOAT3(right, bottom, 0.0f); // Bottom right
vertices[5].texture = XMFLOAT2(1.0f, 1.0f);
// 버텍스 버퍼를 쓸 수 있도록 잠급니다.
result = deviceContext->Map(_vertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
if (FAILED(result))
{
return false;
}
// 정점 버퍼의 데이터를 가리키는 포인터를 얻는다.
verticesPtr = (VertexType*)mappedResource.pData;
// 데이터를 정점 버퍼에 복사합니다.
memcpy(verticesPtr, (void*)vertices, (sizeof(VertexType) * _vertexCount));
// 정점 버퍼의 잠금을 해제합니다.
deviceContext->Unmap(_vertexBuffer, 0);
// 더 이상 필요하지 않은 꼭지점 배열을 해제합니다.
delete [] vertices;
vertices = nullptr;
return true;
}
void BitmapClass::RenderBuffers(ID3D11DeviceContext* deviceContext)
{
// 정점 버퍼의 단위와 오프셋을 설정합니다.
UINT stride = sizeof(VertexType);
UINT offset = 0;
// 렌더링 할 수 있도록 입력 어셈블러에서 정점 버퍼를 활성으로 설정합니다.
deviceContext->IASetVertexBuffers(0, 1, &_vertexBuffer, &stride, &offset);
// 렌더링 할 수 있도록 입력 어셈블러에서 인덱스 버퍼를 활성으로 설정합니다.
deviceContext->IASetIndexBuffer(_indexBuffer, DXGI_FORMAT_R32_UINT, 0);
// 정점 버퍼로 그릴 기본형을 설정합니다. 여기서는 삼각형으로 설정합니다.
deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
}
bool BitmapClass::LoadTexture(ID3D11Device* device, WCHAR* textureFileName)
{
// 텍스쳐 오브젝트를 생성합니다.
_texture = new TextureClass();
if (_texture == nullptr)
{
return false;
}
// 텍스쳐 오브젝트를 초기화 합니다.
return _texture->Initialize(device, textureFileName);
}
void BitmapClass::ReleaseTexture()
{
if (_texture)
{
_texture->Shutdown();
delete _texture;
_texture = nullptr;
}
}
bool BitmapClass::Initialize(ID3D11Device* device, int screenWidth, int screenHeight, WCHAR* textureFileName, int bitmapWidth, int bitmapHeight)
{
// 화면 크기를 멤버 변수에 저장
_screenWidth = screenWidth;
_screenHeight = screenHeight;
// 렌더링할 비트맵의 픽셀 크기를 저장
_bitmapWidth = bitmapWidth;
_bitmapHeight = bitmapHeight;
// 이전 렌더링 위치를 음수로 초기화 합니다.
_previousPosX = -1;
_previousPosY = -1;
// 정점 및 인덱스 버퍼를 초기화 합니다.
if (InitializeBuffers(device) == false)
{
return false;
}
// 이 모델의 텍스쳐를 로드 합니다.
return LoadTexture(device, textureFileName);
}
Initialze함수에서 화면 크기와 이미지 크기를 저장합니다. 렌더링을 할 정확한 정점 위치가 필요하기 때문입니다. 이미지의 픽셀들은 텍스쳐의 그것처럼 정확하게 일치할 필요는 없습니다. 아무 크기나 지정할 수 있고 어떤 크기의 텍스쳐든지 지정할 수 있습니다.
// 이전 렌더링 위치를 음수로 초기화 합니다.
_previousPosX = -1;
_previousPosY = -1;
이전 렌더링 위치 변수는 -1로 초기화 합니다. 이 변수는 이전 위치를 기넉하는 용도이기 때문에 중요합니다. 만약, 이전 프레임과 비교하여 위치가 변하지 않았다면 동점 정적 버퍼를 바꾸지 않기 때문에 성능의 향상을 꾀할 수 있습니다.
bool BitmapClass::Render(ID3D11DeviceContext* deviceContext, int positionX, int positionY)
{
// 화면의 다른 위치로 렌더링 하기 위해 동적 정점 버퍼를 다시 빌드합니다.
if (UpdateBuffers(deviceContext, positionX, positionY) == false)
{
return false;
}
// 그리기를 준비하기 위해 그래픽 파이프 라인에 꼭지점과 인덱스 버퍼를 놓습니다.
RenderBuffers(deviceContext);
return true;
}
Render 함수에서는 2D 이미지의 버퍼를 그래픽 카드에 넣습니다. 또한 입력으로 이미지가 화면에 그려질 위치를 받습니다. UpdateBuffer 함수가 위치를 지정하는 데 사용됩니다. 이전 프레임과 위치가 바뀌었다면 동적 정점 버퍼의 정점들의 위치를 새로운 위치로 갱신합니다. 그렇지 않으면 UpdateBuffers 함수를 그냥 지나칩니다. RenderBuffers 함수를 수행한 뒤 최종적으로 그릴 정점/인덱스 버퍼를 준비합니다.
ID3D11ShaderResourceView* BitmapClass::GetTexture()
{
return _texture->GetTexture();
}
GetTexture 함수는 2D 이미지에 사용하는 텍스쳐 자원에 대한 포인터를 반환합니다. 쉐이더에서는 이 함수를 호출하여 버퍼를 그릴 때 이미지에 접근합니다.
bool BitmapClass::InitializeBuffers(ID3D11Device* device)
{
// 정점 배열의 정점의 수와 인덱스 배열의 인덱스 수를 지정합니다.
_indexCount = _vertexCount = 6;
// 정점 배열을 만듭니다.
VertexType* vertices = new VertexType[_vertexCount];
if (vertices == false)
{
return false;
}
// 정점 배열을 0으로 초기화합니다.
memset(vertices, 0, (sizeof(VertexType) * _vertexCount));
// 인덱스 배열을 만듭니다.
unsigned long* indices = new unsigned long[_indexCount];
if (indices == false)
{
return false;
}
// 데이터로 인덱스 배열을 로드합니다.
for(int i = 0 ; i < _indexCount; i++)
{
indices[i] = i;
}
InitializeBuffer 함수는 2D 이미지를 그리는데 사용하는 정점/인덱스 버퍼를 만드는 데 사용됩니다.
두개의 삼각형을 만들어야 하기 때문에 정점 수를 6으로 설정합니다. 인덱스 역시 같습니다.
// 정적 정점 버퍼의 구조체를 설정합니다.
D3D11_BUFFER_DESC vertexBufferDesc;
vertexBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
vertexBufferDesc.ByteWidth = sizeof(VertexType) * _vertexCount;
vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertexBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
vertexBufferDesc.MiscFlags = 0;
vertexBufferDesc.StructureByteStride = 0;
// subresource 구조에 정점 데이터에 대한 포인터를 제공합니다.
D3D11_SUBRESOURCE_DATA vertexData;
vertexData.pSysMem = vertices;
vertexData.SysMemPitch = 0;
vertexData.SysMemSlicePitch = 0;
// 정점 버퍼를 만듭니다.
if (FAILED(device->CreateBuffer(&vertexBufferDesc, &vertexData, &_vertexBuffer)))
{
return false;
}
여기서 ModelClass와 큰 차이가 생깁니다. 여기서 동점 정점 버퍼를 생성하여 필요하다면 정점 버퍼 내부의 값을 수정할 수 있게 합니다. 동적이라는 속서을 지정하기 위하여 description의 Usage변수를 D3D11_USAGE_DYNAMIC으로 하고 CPUAccessFlags를 D3D11_CPU_ACCESS_WRITE로 합니다.
// 정적 인덱스 버퍼의 구조체를 설정합니다.
D3D11_BUFFER_DESC indexBufferDesc;
indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
indexBufferDesc.ByteWidth = sizeof(unsigned long) * _indexCount;
indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
indexBufferDesc.CPUAccessFlags = 0;
indexBufferDesc.MiscFlags = 0;
indexBufferDesc.StructureByteStride = 0;
// 인덱서 데이터를 가리키는 보조 리소스 구조체를 작성합니다.
D3D11_SUBRESOURCE_DATA indexData;
indexData.pSysMem = indices;
indexData.SysMemPitch = 0;
indexData.SysMemSlicePitch = 0;
// 인덱스 버퍼를 만듭니다.
if (FAILED(device->CreateBuffer(&indexBufferDesc, &indexData, &_indexBuffer)))
{
return false;
}
// 생성되고 값이 할당된 정점 버퍼와 인덱스 버퍼를 해제합니다.
delete[] vertices;
vertices = 0;
delete[] indices;
indices = 0;
return true;
}
인덱서 버퍼의 내용은 정점의 위치가 바뀌어도 언제나 같ㄴ은 여섯개의 정점을 가리키기 떄문에 인덱스 버퍼를 동적 버퍼로 만들지는 않습니다.
bool BitmapClass::UpdateBuffers(ID3D11DeviceContext* deviceContext, int positionX, int positionY)
{
float left, right, top, bottom;
VertexType* vertices;
D3D11_MAPPED_SUBRESOURCE mappedResource;
VertexType* verticesPtr;
HRESULT result;
UpdateBuffers 함수는 매 프레임마다 불려 필요할 경우 동적 정점 버퍼의 내용을 새 위치로 변경합니다.
// 이 비트맵을 렌더링 할 위치가 변경되지 않은 경우 정점 버퍼를 업데이트하지 마세요
if ((positionX == _previousPosX) && (positionY == _previousPosY))
{
return true;
}
이미지의 위치가 이전과 비교하여 달라졌는지 확인합니다. 바뀌지 않았다면 버퍼를 수정할 필요가 없으므로 그냥 빠져나갑니다. 이 확인과정은 많은 연산을 경감시켜줍니다.
// 변경된 경우 렌더링 되는 위치를 업데이트 합니다.
_previousPosX = positionX;
_previousPosY = positionY;
만약 이미지 위치가 바뀌었다면 다음번에 그려질 위치를 위해 새로운 위치를 기록합니다.
// 비트 맵 왼쪽의 화면 좌표를 계산합니다.
left = (float)((_screenWidth / 2) * -1) + (float)positionX;
// 비트 맵 오른쪽의 화면 좌표를 계산합니다.
right = left + (float)_bitmapWidth;
// 비트 맵 상단의 화면 좌표를 계산합니다.
top = (float)(_screenHeight / 2) - (float)positionY;
// 비트 맵 아래쪽의 화면 좌표를 계산합니다.
bottom = top - (float)_bitmapHeight;
이미지의 네 변의 위치가 계산됩니다.
// 정점 배열을 만듭니다.
vertices = new VertexType[_vertexCount];
if (vertices == false)
{
return false;
}
// 정점 배열에 데이터를 로드합니다.
// 첫번째 삼각형
vertices[0].position = XMFLOAT3(left, top, 0.0f); // Top left
vertices[0].texture = XMFLOAT2(0.0f, 0.0f);
vertices[1].position = XMFLOAT3(right, bottom, 0.0f); // Bottom right
vertices[1].texture = XMFLOAT2(1.0f, 1.0f);
vertices[2].position = XMFLOAT3(left, bottom, 0.0f); // Bottom left
vertices[2].texture = XMFLOAT2(0.0f, 1.0f);
// 두번째 삼각형
vertices[3].position = XMFLOAT3(left, top, 0.0f); // Top left
vertices[3].texture = XMFLOAT2(0.0f, 0.0f);
vertices[4].position = XMFLOAT3(right, top, 0.0f); // Top right
vertices[4].texture = XMFLOAT2(1.0f, 0.0f);
vertices[5].position = XMFLOAT3(right, bottom, 0.0f); // Bottom right
vertices[5].texture = XMFLOAT2(1.0f, 1.0f);
좌표가 계산되면 임시로 정점 배열을 만들고 새로운 정점 위치를 채워넣습니다.
// 버텍스 버퍼를 쓸 수 있도록 잠급니다.
result = deviceContext->Map(_vertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
if (FAILED(result))
{
return false;
}
// 정점 버퍼의 데이터를 가리키는 포인터를 얻는다.
verticesPtr = (VertexType*)mappedResource.pData;
// 데이터를 정점 버퍼에 복사합니다.
memcpy(verticesPtr, (void*)vertices, (sizeof(VertexType) * _vertexCount));
// 정점 버퍼의 잠금을 해제합니다.
deviceContext->Unmap(_vertexBuffer, 0);
// 더 이상 필요하지 않은 꼭지점 배열을 해제합니다.
delete [] vertices;
vertices = nullptr;
return true;
}
Map과 memcpy함수를 사용하여 정점 배열의 내요을 정점 버퍼로 복사합니다.
void BitmapClass::RenderBuffers(ID3D11DeviceContext* deviceContext)
{
// 정점 버퍼의 단위와 오프셋을 설정합니다.
UINT stride = sizeof(VertexType);
UINT offset = 0;
// 렌더링 할 수 있도록 입력 어셈블러에서 정점 버퍼를 활성으로 설정합니다.
deviceContext->IASetVertexBuffers(0, 1, &_vertexBuffer, &stride, &offset);
// 렌더링 할 수 있도록 입력 어셈블러에서 인덱스 버퍼를 활성으로 설정합니다.
deviceContext->IASetIndexBuffer(_indexBuffer, DXGI_FORMAT_R32_UINT, 0);
// 정점 버퍼로 그릴 기본형을 설정합니다. 여기서는 삼각형으로 설정합니다.
deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
}
RenderBuffer함수는 쉐이더가 GPU에서 정점/인덱스 버퍼를 사용할 수 있도록 설정합니다.
D3DClass
D3DClass.h
#pragma once
class D3DClass
{
public:
D3DClass();
D3DClass(const D3DClass& other);
~D3DClass();
bool Initialize(int screenWidth, int screenHieght, bool vsync, HWND hwnd, bool fullScreen, float screenDepth, float screenNear);
void Shutdown();
void BeginScene(float red, float green, float blue, float alpha);
void EndScene();
ID3D11Device* GetDevice();
ID3D11DeviceContext* GetDeviceContext();
void GetProjectionMatrix(XMMATRIX& projectionMatrix);
void GetWorldMatrix(XMMATRIX& worldMatrix);
void GetOrthoMatrix(XMMATRIX& orthoMatrix);
void GetVideoCardInfo(char* cardName, int& memory);
void TurnZBufferOn();
void TurnZBufferOff();
private:
bool _vsyncEnabled = false;
int _videoCardMemory = 0;
char _videoCardDescription[128] = {0,};
IDXGISwapChain* _swapChain = nullptr;
ID3D11Device* _device = nullptr;
ID3D11DeviceContext* _deviceContext = nullptr;
ID3D11RenderTargetView* _renderTargetView = nullptr;
ID3D11Texture2D* _depthStencilBuffer = nullptr;
ID3D11DepthStencilState* _depthStencilState = nullptr;
ID3D11DepthStencilView* _depthStencilView = nullptr;
ID3D11RasterizerState* _rasterState = nullptr;
XMMATRIX _projectionMatrix;
XMMATRIX _worldMatrix;
XMMATRIX _orthoMatrix;
ID3D11DepthStencilState* _depthDisabledStencilState = nullptr;
};
D3DClass 는 Z버퍼를 켜고 끌 수 있도록 수정했습니다.
void TurnZBufferOn();
void TurnZBufferOff();
private:
bool _vsyncEnabled = false;
int _videoCardMemory = 0;
char _videoCardDescription[128] = {0,};
IDXGISwapChain* _swapChain = nullptr;
ID3D11Device* _device = nullptr;
ID3D11DeviceContext* _deviceContext = nullptr;
ID3D11RenderTargetView* _renderTargetView = nullptr;
ID3D11Texture2D* _depthStencilBuffer = nullptr;
ID3D11DepthStencilState* _depthStencilState = nullptr;
ID3D11DepthStencilView* _depthStencilView = nullptr;
ID3D11RasterizerState* _rasterState = nullptr;
XMMATRIX _projectionMatrix;
XMMATRIX _worldMatrix;
XMMATRIX _orthoMatrix;
ID3D11DepthStencilState* _depthDisabledStencilState = nullptr;
Z버퍼를 켜고 끄는 함수를 만듭니다. 그리고 2D 렌더링을 위한 새로운 깊이 스텐실 상태 변수를만듭니다.
D3DClass.cpp
#include "stdafx.h"
#include "D3DClass.h"
D3DClass::D3DClass()
{
}
D3DClass::D3DClass(const D3DClass& other)
{
}
D3DClass::~D3DClass()
{
}
bool D3DClass::Initialize(int screenWidth, int screenHeight, bool vsync, HWND hwnd, bool fullScreen, float screenDepth, float screenNear)
{
// 수직동기화 상태를 저장
_vsyncEnabled = vsync;
// DirectX 그래픽 인터페이스 펙토리 생성
IDXGIFactory* factory = nullptr;
if (FAILED(CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory)))
{
return false;
}
// 팩토리 객체를 사용하여 첫번째 그래픽 카드 인터페이스 어뎁터를 생성
IDXGIAdapter* adapter = nullptr;
if (FAILED(factory->EnumAdapters(0, &adapter)))
{
return false;
}
// 출력(모니터)에 대한 첫번째 어뎁터를 지정
IDXGIOutput* adapterOutput = nullptr;
if (FAILED(adapter->EnumOutputs(0, &adapterOutput)))
{
return false;
}
// 출력(모니터)에 대한 DXGI_FORMAT_R8G8B8A8_UNORM 표시 형식에 맞는 모드 수를 가져옴
unsigned int numModes = 0;
if (FAILED(adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL)))
{
return false;
}
// 가능한 모든 모니터와 그래픽 카드 조합을 저장할 리스트를 생성
DXGI_MODE_DESC* displayModeList = new DXGI_MODE_DESC[numModes];
if (!displayModeList)
{
return false;
}
// 모든 디스플레이 모드에 대한 리스트를 채움
if (FAILED(adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList)))
{
return false;
}
// 이제 모든 디스플레이 모드에 대해 화면 너비/노퓨이에 맞는 디스플레이 모드를 찾음
// 적합한 것을 찾으면, 모니터의 새로고침 비율의 분모와 분자 값을 저장
unsigned int numerator = 0;
unsigned int denominator = 0;
for (unsigned int i = 0; i < numModes; i++)
{
if (displayModeList[i].Width == (unsigned int)screenWidth)
{
if (displayModeList[i].Height == (unsigned int)screenHeight)
{
numerator = displayModeList[i].RefreshRate.Numerator;
denominator = displayModeList[i].RefreshRate.Denominator;
}
}
}
// 비디오카드의 구조체를 얻음
DXGI_ADAPTER_DESC adapterDesc;
if (FAILED(adapter->GetDesc(&adapterDesc)))
{
return false;
}
// 비디오카드 메모리 용량 단위를 메가바이트 단위로 저장
_videoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024);
// 비디오카드의 이름을 저장
size_t stringLength = 0;
if(wcstombs_s(&stringLength, _videoCardDescription, 128, adapterDesc.Description, 128) != 0)
{
return false;
}
// 디스플레이 모드 리스트를 해제
SAFE_DELETE_ARRAY(displayModeList);
displayModeList = 0;
// 출력 어뎁터를 해제
adapterOutput->Release();
adapterOutput = 0;
// 어댑터를 해제
adapter->Release();
adapter = 0;
// 팩토리 객체를 해제
factory->Release();
factory = 0;
// 스왑체인 구조체를 초기화
DXGI_SWAP_CHAIN_DESC swapChainDesc;
ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));
// 백버퍼를 한개만 사용하도록 저장
swapChainDesc.BufferCount = 1;
// 백버퍼의 넓이와 높이를 지정
swapChainDesc.BufferDesc.Width = screenWidth;
swapChainDesc.BufferDesc.Height = screenHeight;
// 32bit 서페이스 설정
swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
// 백버퍼의 새로고침 비율을 설정
if (_vsyncEnabled)
{
swapChainDesc.BufferDesc.RefreshRate.Numerator = numerator;
swapChainDesc.BufferDesc.RefreshRate.Denominator = denominator;
}
else
{
swapChainDesc.BufferDesc.RefreshRate.Numerator = 0;
swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
}
// 백버퍼의 사용 용도 지정
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
// 랜더링에 사용될 윈도우 핸들을 지정
swapChainDesc.OutputWindow = hwnd;
// 멀티샘플링을 끔
swapChainDesc.SampleDesc.Count = 1;
swapChainDesc.SampleDesc.Quality = 0;
// 창모드 or 풀스크린 모드 설정
if (fullScreen)
{
swapChainDesc.Windowed = false;
}
else
{
swapChainDesc.Windowed = true;
}
// 스캔 라인 순서 및 크기를 지정하지 않음으로 설정
swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
// 출력된 다음 백버퍼를 비우도록 지정
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
// 추가 옵션 플래그를 사용하지 않음
swapChainDesc.Flags = 0;
// 피처레벨을 DirectX 11로 설정
D3D_FEATURE_LEVEL featureLevel = D3D_FEATURE_LEVEL_11_0;
// 스왑 체인, Direct3D 장치 및 Direct3D 장치 컨텍스트를 만듦
if (FAILED(D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0, &featureLevel, 1,
D3D11_SDK_VERSION, &swapChainDesc, &_swapChain, &_device, NULL, &_deviceContext)))
{
return false;
}
// 백버퍼 포인터를 얻어옴
ID3D11Texture2D* backBufferPtr = nullptr;
if (FAILED(_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr)))
{
return false;
}
// 백버퍼 포인터로 랜더 타겟 뷰를 생성
if (FAILED(_device->CreateRenderTargetView(backBufferPtr, NULL, &_renderTargetView)))
{
return false;
}
// 백버퍼 포인터를 해제
backBufferPtr->Release();
backBufferPtr = 0;
// 깊이 버퍼 구조체를 초기화
D3D11_TEXTURE2D_DESC depthBufferDesc;
ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));
// 깊이 버퍼 구조체 작성
depthBufferDesc.Width = screenWidth;
depthBufferDesc.Height = screenHeight;
depthBufferDesc.MipLevels = 1;
depthBufferDesc.ArraySize = 1;
depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthBufferDesc.SampleDesc.Count = 1;
depthBufferDesc.SampleDesc.Quality = 0;
depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
depthBufferDesc.CPUAccessFlags = 0;
depthBufferDesc.MiscFlags = 0;
// 설정된 깊이버퍼 구조체를 사용하여 깊이 버퍼 텍스쳐를 생성
if (FAILED(_device->CreateTexture2D(&depthBufferDesc, NULL, &_depthStencilBuffer)))
{
return false;
}
// 스텐실 상태 구조체를 초기화
D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));
// 스텐실 상태 구조체를 작성
depthStencilDesc.DepthEnable = true;
depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
depthStencilDesc.StencilEnable = true;
depthStencilDesc.StencilReadMask = 0xFF;
depthStencilDesc.StencilWriteMask = 0xFF;
// 픽셀 정면의 스텐실 설정
depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
// 픽셀 뒷면의 스텐실 설정
depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
// 깊이 스텐실 상태를 생성
if (FAILED(_device->CreateDepthStencilState(&depthStencilDesc, &_depthStencilState)))
{
return false;
}
// 깊이 스텐실 상태를 설정
_deviceContext->OMSetDepthStencilState(_depthStencilState, 1);
// 깊이 스텐실 뷰의 구조체를 초기화
D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));
// 깊이 스텐실 뷰 구조체를 설정
depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
depthStencilViewDesc.Texture2D.MipSlice = 0;
// 깊이 스텐실 뷰를 생성
if (FAILED(_device->CreateDepthStencilView(_depthStencilBuffer, &depthStencilViewDesc, &_depthStencilView)))
{
return false;
}
// 랜더링 대상 뷰와 깊이 스텐실 버퍼를 출력, 출력 렌터더 파이프 라인에 바인딩
_deviceContext->OMSetRenderTargets(1, &_renderTargetView, _depthStencilView);
// 그려지는 폴리곤과 방법을 결정할 래스터 구조체를 설정
D3D11_RASTERIZER_DESC rasterDesc;
rasterDesc.AntialiasedLineEnable = false;
rasterDesc.CullMode = D3D11_CULL_BACK;
rasterDesc.DepthBias = 0;
rasterDesc.DepthBiasClamp = 0.0f;
rasterDesc.DepthClipEnable = true;
rasterDesc.FillMode = D3D11_FILL_SOLID;
rasterDesc.FrontCounterClockwise = false;
rasterDesc.MultisampleEnable = false;
rasterDesc.ScissorEnable = false;
rasterDesc.SlopeScaledDepthBias = 0.0f;
// 방금 작성한 구조체에서 래스터 라이저 상태를 만듦
if (FAILED(_device->CreateRasterizerState(&rasterDesc, &_rasterState)))
{
return false;
}
// 이제 래스터 라이저 상태를 설정
_deviceContext->RSSetState(_rasterState);
// 랜더링을 위해 뷰포트를 설정
D3D11_VIEWPORT viewport;
viewport.Width = (float)screenWidth;
viewport.Height = (float)screenHeight;
viewport.MinDepth = 0.0f;
viewport.MaxDepth = 1.0f;
viewport.TopLeftX = 0.0f;
viewport.TopLeftY = 0.0f;
// 뷰포트를 생성
_deviceContext->RSSetViewports(1, &viewport);
// 투영 행렬을 설정합니다
float fieldOfView = 3.141592654f / 4.0f;
float screenAspect = (float)screenWidth/(float)screenHeight;
// 3D 랜더링을 위한 투영 행렬을 만듦
_projectionMatrix = XMMatrixPerspectiveFovLH(fieldOfView, screenAspect, screenNear, screenDepth);
// 월드 행렬을 항등 행렬로 초기화
_worldMatrix = XMMatrixIdentity();
// 2D 랜더링을 위한 직교 투영 행렬을 만듦
_orthoMatrix = XMMatrixOrthographicLH((float)screenWidth, (float)screenHeight, screenNear, screenDepth);
// 이제 2D 렌더링을 위한 Z 버퍼를 끄는 두번째 깊이 스텐실 상태를 만듭니다. 유일한 차이점은
// DepthEnable을 false로 설정하면 다름ㄴ 모든 매개 변수는 다른 깊이 스텐실 상태와 동일합니다.
D3D11_DEPTH_STENCIL_DESC depthDisabledStencilDesc;
ZeroMemory(&depthDisabledStencilDesc, sizeof(depthDisabledStencilDesc));
depthDisabledStencilDesc.DepthEnable = false;
depthDisabledStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
depthDisabledStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
depthDisabledStencilDesc.StencilEnable = true;
depthDisabledStencilDesc.StencilReadMask = 0xFF;
depthDisabledStencilDesc.StencilWriteMask = 0xFF;
depthDisabledStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthDisabledStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
depthDisabledStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthDisabledStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
depthDisabledStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthDisabledStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
depthDisabledStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthDisabledStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
// 장치를 사용하여 상태를 만듭니다.
if (FAILED(_device->CreateDepthStencilState(&depthDisabledStencilDesc, &_depthDisabledStencilState)))
{
return false;
}
return true;
}
void D3DClass::Shutdown()
{
// 종료 전 윈도우 모드로 설정하지 않으면 스왑 체인을 해제 할 때 예외가 발생
if (_swapChain)
{
_swapChain->SetFullscreenState(false, NULL);
}
SAFE_RELEASE(_depthDisabledStencilState);
SAFE_RELEASE(_rasterState);
SAFE_RELEASE(_depthStencilView);
SAFE_RELEASE(_depthStencilState);
SAFE_RELEASE(_depthStencilBuffer);
SAFE_RELEASE(_renderTargetView);
SAFE_RELEASE(_deviceContext);
SAFE_RELEASE(_device);
SAFE_RELEASE(_swapChain);
}
void D3DClass::BeginScene(float red, float green, float blue, float alpha)
{
// 버퍼를 지울 새을 설정
float color[4] = {red, green, blue, alpha};
// 백버퍼를 지움
_deviceContext->ClearRenderTargetView(_renderTargetView, color);
// 깊이 버퍼를 지움
_deviceContext->ClearDepthStencilView(_depthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0);
}
void D3DClass::EndScene()
{
// 렌더링이 완료되었으므로 화면에 백 버퍼를 표시
if (_vsyncEnabled)
{
// 화면 새로고침 비율을 고정
_swapChain->Present(1, 0);
}
else
{
// 가능한 빠르게 출력
_swapChain->Present(0,0);
}
}
ID3D11Device* D3DClass::GetDevice()
{
return _device;
}
ID3D11DeviceContext* D3DClass::GetDeviceContext()
{
return _deviceContext;
}
void D3DClass::GetProjectionMatrix(XMMATRIX& projectionMatrix)
{
projectionMatrix = _projectionMatrix;
}
void D3DClass::GetWorldMatrix(XMMATRIX& worldMatrix)
{
worldMatrix = _worldMatrix;
}
void D3DClass::GetOrthoMatrix(XMMATRIX& orthoMatrix)
{
orthoMatrix = _orthoMatrix;
}
void D3DClass::GetVideoCardInfo(char* cardName, int& memory)
{
strcpy_s(cardName, 128, _videoCardDescription);
memory = _videoCardMemory;
}
void D3DClass::TurnZBufferOn()
{
_deviceContext->OMSetDepthStencilState(_depthStencilState, 1);
}
void D3DClass::TurnZBufferOff()
{
_deviceContext->OMSetDepthStencilState(_depthDisabledStencilState, 1);
}
// 깊이 버퍼 구조체를 초기화
D3D11_TEXTURE2D_DESC depthBufferDesc;
ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));
// 깊이 버퍼 구조체 작성
depthBufferDesc.Width = screenWidth;
depthBufferDesc.Height = screenHeight;
depthBufferDesc.MipLevels = 1;
depthBufferDesc.ArraySize = 1;
depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthBufferDesc.SampleDesc.Count = 1;
depthBufferDesc.SampleDesc.Quality = 0;
depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
depthBufferDesc.CPUAccessFlags = 0;
depthBufferDesc.MiscFlags = 0;
// 설정된 깊이버퍼 구조체를 사용하여 깊이 버퍼 텍스쳐를 생성
if (FAILED(_device->CreateTexture2D(&depthBufferDesc, NULL, &_depthStencilBuffer)))
{
return false;
}
// 스텐실 상태 구조체를 초기화
D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));
// 스텐실 상태 구조체를 작성
depthStencilDesc.DepthEnable = true;
depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
depthStencilDesc.StencilEnable = true;
depthStencilDesc.StencilReadMask = 0xFF;
depthStencilDesc.StencilWriteMask = 0xFF;
// 픽셀 정면의 스텐실 설정
depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
// 픽셀 뒷면의 스텐실 설정
depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
// 깊이 스텐실 상태를 생성
if (FAILED(_device->CreateDepthStencilState(&depthStencilDesc, &_depthStencilState)))
{
return false;
}
// 깊이 스텐실 상태를 설정
_deviceContext->OMSetDepthStencilState(_depthStencilState, 1);
// 깊이 스텐실 뷰의 구조체를 초기화
D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));
// 깊이 스텐실 뷰 구조체를 설정
depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
depthStencilViewDesc.Texture2D.MipSlice = 0;
// 깊이 스텐실 뷰를 생성
if (FAILED(_device->CreateDepthStencilView(_depthStencilBuffer, &depthStencilViewDesc, &_depthStencilView)))
{
return false;
}
// 랜더링 대상 뷰와 깊이 스텐실 버퍼를 출력, 출력 렌터더 파이프 라인에 바인딩
_deviceContext->OMSetRenderTargets(1, &_renderTargetView, _depthStencilView);
// 그려지는 폴리곤과 방법을 결정할 래스터 구조체를 설정
D3D11_RASTERIZER_DESC rasterDesc;
rasterDesc.AntialiasedLineEnable = false;
rasterDesc.CullMode = D3D11_CULL_BACK;
rasterDesc.DepthBias = 0;
rasterDesc.DepthBiasClamp = 0.0f;
rasterDesc.DepthClipEnable = true;
rasterDesc.FillMode = D3D11_FILL_SOLID;
rasterDesc.FrontCounterClockwise = false;
rasterDesc.MultisampleEnable = false;
rasterDesc.ScissorEnable = false;
rasterDesc.SlopeScaledDepthBias = 0.0f;
// 방금 작성한 구조체에서 래스터 라이저 상태를 만듦
if (FAILED(_device->CreateRasterizerState(&rasterDesc, &_rasterState)))
{
return false;
}
// 이제 래스터 라이저 상태를 설정
_deviceContext->RSSetState(_rasterState);
// 랜더링을 위해 뷰포트를 설정
D3D11_VIEWPORT viewport;
viewport.Width = (float)screenWidth;
viewport.Height = (float)screenHeight;
viewport.MinDepth = 0.0f;
viewport.MaxDepth = 1.0f;
viewport.TopLeftX = 0.0f;
viewport.TopLeftY = 0.0f;
// 뷰포트를 생성
_deviceContext->RSSetViewports(1, &viewport);
// 투영 행렬을 설정합니다
float fieldOfView = 3.141592654f / 4.0f;
float screenAspect = (float)screenWidth/(float)screenHeight;
// 3D 랜더링을 위한 투영 행렬을 만듦
_projectionMatrix = XMMatrixPerspectiveFovLH(fieldOfView, screenAspect, screenNear, screenDepth);
// 월드 행렬을 항등 행렬로 초기화
_worldMatrix = XMMatrixIdentity();
// 2D 랜더링을 위한 직교 투영 행렬을 만듦
_orthoMatrix = XMMatrixOrthographicLH((float)screenWidth, (float)screenHeight, screenNear, screenDepth);
새로운 깊이 스텐실 상태 변수를 설정합니다.
// 이제 2D 렌더링을 위한 Z 버퍼를 끄는 두번째 깊이 스텐실 상태를 만듭니다. 유일한 차이점은
// DepthEnable을 false로 설정하면 다름ㄴ 모든 매개 변수는 다른 깊이 스텐실 상태와 동일합니다.
D3D11_DEPTH_STENCIL_DESC depthDisabledStencilDesc;
ZeroMemory(&depthDisabledStencilDesc, sizeof(depthDisabledStencilDesc));
depthDisabledStencilDesc.DepthEnable = false;
depthDisabledStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
depthDisabledStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
depthDisabledStencilDesc.StencilEnable = true;
depthDisabledStencilDesc.StencilReadMask = 0xFF;
depthDisabledStencilDesc.StencilWriteMask = 0xFF;
depthDisabledStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthDisabledStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
depthDisabledStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthDisabledStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
depthDisabledStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthDisabledStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
depthDisabledStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthDisabledStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
여기서 깊이 스텐실 상태 변수의 Description을 작성합니다. 새 변수 Description은 DepthEnable이 2D 렌더링을 위해 false로 세팅됩니다.
// 장치를 사용하여 상태를 만듭니다.
if (FAILED(_device->CreateDepthStencilState(&depthDisabledStencilDesc, &_depthDisabledStencilState)))
{
return false;
}
return true;
}
깊이 스텐실 상태를 생성합니다.
void D3DClass::TurnZBufferOn()
{
_deviceContext->OMSetDepthStencilState(_depthStencilState, 1);
}
void D3DClass::TurnZBufferOff()
{
_deviceContext->OMSetDepthStencilState(_depthDisabledStencilState, 1);
}
두 함수는 Z 버퍼를 켜고 끄는 일을 합니다. Z버퍼를 켜는 것은 원래의 깊이 스텐실 상태를 사용합니다. 그리고 Z버퍼를 끄는 것은 방금 depthEnable을 false로 설정한 새로운 깊이 스텐실 상태를 사용합니다. 일반적으로 3D 렌더링을 수행한 후에 Z버퍼를 끄고 2D 렌더링을 한 뒤 다시 Z버퍼를 키는 것이 가장 이상적입니다.
GraphicClass
GraphicClass.h
#pragma once
/////////////
// GLOBALS //
/////////////
const bool FULL_SCREEN = false;
const bool VSYNC_ENABLED = true;
const float SCREEN_DEPTH = 1000.0f;
const float SCREEN_NEAR = 0.1f;
class D3DClass;
class CameraClass;
class TextureShaderClass;
class BitmapClass;
class GraphicsClass
{
public:
GraphicsClass();
GraphicsClass(const GraphicsClass& other);
~GraphicsClass();
bool Initialize(int screenWidth, int screenHeight, HWND hwnd);
void Shutdown();
bool Frame();
private:
bool Render(float rotation);
private:
D3DClass* _direct3D = nullptr;
CameraClass* _camera = nullptr;
TextureShaderClass* _textureShader = nullptr;
BitmapClass* _bitmap = nullptr;
};
BitmapClass 변수를 추가 합니다.
BitmapClass.cpp
#include "stdafx.h"
#include "d3dclass.h"
#include "CameraClass.h"
#include "TextureShaderClass.h"
#include "BitmapClass.h"
#include "GraphicsClass.h"
GraphicsClass::GraphicsClass()
{
}
GraphicsClass::GraphicsClass(const GraphicsClass& other)
{
}
GraphicsClass::~GraphicsClass()
{
}
bool GraphicsClass::Initialize(int screenWidth, int screenHeight, HWND hwnd)
{
// Direct3D 객체 생성
//_direct3D = (D3DClass*) SAFE_ALIGNED_NEW(sizeof(D3DClass), 16);
_direct3D = new D3DClass();
if (!_direct3D)
{
return false;
}
// Direct3D 객체 초기화
if (!_direct3D->Initialize(screenWidth, screenHeight, VSYNC_ENABLED, hwnd, FULL_SCREEN, SCREEN_DEPTH, SCREEN_NEAR))
{
MessageBox(hwnd, L"Could not initialze Direct3D", L"Error", MB_OK);
return false;
}
// _camera 객체 생성
_camera = new CameraClass();
if (_camera == nullptr)
{
return false;
}
// 카메라 포지션 변경
_camera->SetPosition(0.0f, 0.0f, -5.0f);
// _textureShader 객체 생성
_textureShader = new TextureShaderClass();
if (_textureShader == nullptr)
{
return false;
}
// _textureShader 객체 초기화
if (_textureShader->Initialize(_direct3D->GetDevice(), hwnd) == false)
{
MessageBox(hwnd, L"Could not initialize the Texture shader object", L"Error", MB_OK);
return false;
}
// 비트맵 객체 생성
_bitmap = new BitmapClass();
if (_bitmap == nullptr)
{
return false;
}
// 비트맵 객체 초기화
if (_bitmap->Initialize(_direct3D->GetDevice(), screenWidth, screenHeight, L"Data/seafloor.dds", 256, 256) == false)
{
MessageBox(hwnd, L"Could not initialize the Bitmap object", L"Error", MB_OK);
return false;
}
return true;
}
void GraphicsClass::Shutdown()
{
if (_bitmap)
{
_bitmap->ShutDown();
SAFE_DELETE(_bitmap);
}
if (_textureShader)
{
_textureShader->ShutDown();
SAFE_DELETE(_textureShader);
}
// _camera 객체 반환
SAFE_DELETE(_camera);
// Direct3D 객체 반환
if (_direct3D)
{
_direct3D->Shutdown();
SAFE_DELETE(_direct3D);
}
}
bool GraphicsClass::Frame()
{
static float rotation = 0.0f;
// 각 프레임의 rotation 변수를 업데이트 합니다.
rotation += (float)XM_PI * 0.005f;
if (rotation > 360.0f)
{
rotation -= 360.0f;
}
// 그래픽 랜더링 처리
return Render(rotation);
}
bool GraphicsClass::Render(float rotation)
{
// 씬을 그리기 위해 버퍼를 지웁니다.
_direct3D->BeginScene(0.0f, 0.0f, 0.0f, 1.0f);
// 카메라의 위치에 따라 뷰 행렬을 생성합니다.
_camera->Render();
// 카메라 및 d3d 객체에서 월드, 뷰 및 투영 행렬을 가져옵니다.
XMMATRIX worldMatrix, viewMatrix, projectionMatrix, orthoMatrix;
_direct3D->GetWorldMatrix(worldMatrix);
_camera->GetViewMatrix(viewMatrix);
_direct3D->GetProjectionMatrix(projectionMatrix);
_direct3D->GetOrthoMatrix(orthoMatrix);
// 모든 2D 렌더링을 시작하려면 Z 버퍼를 끕니다.
_direct3D->TurnZBufferOff();
// 비트 맵 버텍스와 인덱스 버퍼를 그래픽 파이프 라인에 배치하여 그리기르 준비합니다.
if (_bitmap->Render(_direct3D->GetDeviceContext(), 100, 100) == false)
{
return false;
}
// 텍스처 쉐이더로 비트 맵을 렌더링 합니다.
if (_textureShader->Render(_direct3D->GetDeviceContext(), _bitmap->GetIndexCount(), worldMatrix, viewMatrix, orthoMatrix, _bitmap->GetTexture()) == false)
{
return false;
}
// 모든 2D 렌더링이 완료되었으므로 Z버퍼를 다시 킵니다.
_direct3D->TurnZBufferOn();
// 버퍼의 내용을 화면에 출력합니다.
_direct3D->EndScene();
return true;
}
// 비트맵 객체 생성
_bitmap = new BitmapClass();
if (_bitmap == nullptr)
{
return false;
}
// 비트맵 객체 초기화
if (_bitmap->Initialize(_direct3D->GetDevice(), screenWidth, screenHeight, L"Data/seafloor.dds", 256, 256) == false)
{
MessageBox(hwnd, L"Could not initialize the Bitmap object", L"Error", MB_OK);
return false;
}
BitmapClass 객체를 생성하고 초기화합니다. 이때 텍스쳐로 seafloor.dds 파일을 사용하고 크기를 256x256 으로 합니다. 이 크기는 실제 텍스쳐 사이즈와 일치할 필요 없이 자유롭게 바꿀 수 있습니다.
_direct3D->GetOrthoMatrix(orthoMatrix);
2D 렌더링을 하기 위해 정사영 행렬(OrthoMatrix)를 구합니다. 일반 투영 행렬 대신 이 행렬을 전달할 것입니다.
// 모든 2D 렌더링을 시작하려면 Z 버퍼를 끕니다.
_direct3D->TurnZBufferOff();
2D 렌더링을 시작하기 전에 Z버퍼를 끕니다.
// 비트 맵 버텍스와 인덱스 버퍼를 그래픽 파이프 라인에 배치하여 그리기르 준비합니다.
if (_bitmap->Render(_direct3D->GetDeviceContext(), 100, 100) == false)
{
return false;
}
그리고 나서 화면의 (100, 100)위치에 비트맵을 그립니다. 위치는 임의로 바꿀 수 있습니다.
// 텍스처 쉐이더로 비트 맵을 렌더링 합니다.
if (_textureShader->Render(_direct3D->GetDeviceContext(), _bitmap->GetIndexCount(), worldMatrix, viewMatrix, orthoMatrix, _bitmap->GetTexture()) == false)
{
return false;
}
일단 정점/인덱스 버퍼가 준비되었다면 테스쳐 쉐이더을 이용해 그리게 됩니다. 2D 렌더링을 수행하기 위해 PrejectionMatrix대신 OrthoMatrix를 인자로 보냈다는 점을 주의하기 바랍니다. 또한 뷰 행렬의 내용이 계속 바뀌는 것이라면, 2D 렌더링만을 위한 기본 뷰행렬을 따로 만들어 사용해야 합니다. 현재는 카메라가 고정되어 있기 때문에 일반 뷰 행렬을 사용해도 같은 결과가 나옵니다.
// 모든 2D 렌더링이 완료되었으므로 Z버퍼를 다시 킵니다.
_direct3D->TurnZBufferOn();
// 버퍼의 내용을 화면에 출력합니다.
_direct3D->EndScene();
모든 2D 렌더링이 끝났다면 다음 프레임에서 3D 객체를 그리기 위해 다시 Z버퍼를 킵니다.
결과
이것을 활용해서 UI와 글꼴 시스템을 그려내는 기초가 됩니다.
'DirectX' 카테고리의 다른 글
11. 글꼴 엔진 (0) | 2023.03.06 |
---|---|
9. 정반사광 (0) | 2022.12.13 |
8. 주변광 (0) | 2022.12.06 |
7. Maya 2011 모델 불러오기 (2) | 2022.12.05 |
6. 3D 모델 렌더링 (0) | 2022.11.26 |