[KGC2014] DX9에서DX11로의이행경험공유

H
Hwan MinEngineer
DirectX9에서 DirectX11 
으로의 이행 경험 공유 
민 환 
CyberConnect2 / 기술개발실
세션 개요 
 세션에서 다루는 내용 
• CyberConnect2의 DirectX11엔진 이야기 
• DirectX11 API설계 
• 게임 내용, 최신 테크닉은 다루지 않습니다 
 세션의 대상 
• DirectX9세대의 Graphics API를 사용해 본 적이 있는 분 
• 앞으로 DirectX11를 사용하실 분
Company 
CyberConnect2 
福岡県福岡市博多区博多駅前1丁目 
東京都品川区大井1丁目 
1996年2月16日 
본사134명 동경25명 
40,000,000 円 
가정용 게임소프트의 제작 및 개발 
회사명 
본사 
동경지사 
설립일 
사원수 
자본금 
사업내용
Company 
.hack series NARUTO SHIPPUDEN 
NARUTO SHIPPUDEN™: Ultimate Ninja® STORM Revolution 
game software ©2014 BANDAI NAMCO Games Inc. 
NARUTO artwork and elements © 2002 MASASHI KISHIMOTO / 2007 SHIPPUDEN All Rights Reserved. 
©Drecom Co., Ltd. powered by CyberConnect2 Co., Ltd. 
series 
JoJo's Bizarre Adventure 
All Star Battle
Speaker 
• CyberConnect2 기술개발실 
• Engine Programmer 
• 현재 내부 엔진 제작중 
• h_min@cc2.co.jp
Contents 
 Engine 소개 
 이행시 주의점 
• DirectX11 변경점 
• Constant Buffer 
• VertexInputLayout 
• State Management 
• Multithread 
• Shader 
• Etc. 
 결론
Contents 
 Engine 소개 
 이행시 주의점 
• DirectX11 변경점 
• Constant Buffer 
• VertexInputLayout 
• State Management 
• Multithread 
• Shader 
• Etc. 
 결론
History 
Engine 소개 
 2013년 3월부터 내부엔진 제작 시작 
 3~4명으로 제작중
방향성 
Engine 소개 
 멀티 플랫폼, 멀티 코어 대응 
• 기본적으로 Windows, PlayStation4, XBOX ONE 대응 
• 멀티코어를 고려한 설계 
 Engine 규모 
• 프로젝트 규모상 상용엔진 수준은 무리 
• 필요한 기능만 최소한으로 제작중
방향성 
Engine 소개 
 기능 
• 최소한 지금까지 가능했던 일은 구현 가능하도록 설계 
• 기존 엔진에서 불편했던 부분은 개선, 좋았던 부분은 채용, 가능하면 
코드 재사용 
 차세대 대비 
• 차세대를 준비하기 위한 최소한의 환경 구축
제작 이유 
Engine 소개 
 기존 엔진의 문제점 
• PlayStation2 시절의 낡은 설계 
• 리소스 파이프라인에 불필요한 작업이 많았음 
• 부족한 기능을 구현하기 위해 game에서 억지로 구현한 부분이 점차 
많아지기 시작함 
• 외부 엔진이라 대응이 늦거나 불가능한 일이 잦았음 
 콘솔 개발킷의 부족 
• 기존 엔진 및 각종 툴이 콘솔기기에서 밖에 동작하지 않아 콘솔 개 
발킷이 없으면 디버깅이 불가능 
• Windows에서 개발하고 싶다는 요청이 많아짐
제작 이유 
Engine 소개 
 내부 기술력 강화 
• 외부 엔진만 사용해서는 노하우 쌓기가 쉽지 않다고 판단 
 차세대기로 갈아타기 위한 좋은 타이밍 
• 차세대기 발매 
• 하드웨어의 진화 
• 지금까지의 설계로는 하드웨어의 스펙을 전부 활용하기 힘들어짐
Engine 소개
Engine 소개
구성 
Engine 소개 
 기본적으로 C++라이브러리 
 콘솔 툴은 python이 많음 
 기타 툴은 C++, 일부는 C#검토중
구성 
Engine 소개 
Rendering 
Core 
Effect 
Animation 
Particle 
… 
60% 
System 
Math 
Memory 
File 
Thread 
… 
90% 
Tool 
Exporter 
Resource manager 
Parameter - 
Configuration 
… 
20%
Rendering 
Core 
Effect 
Animation 
Particle 
… 
60% 
System 
Math 
Memory 
File 
Thread 
… 
90% 
Tool 
Exporter 
Resource manager 
Parameter – 
Configuration 
… 
20% 
구성 
Engine 소개 
오늘의 주제
Rendering Core 
Engine 소개 
 Multithread 대응 구조 
 각 플랫폼의 저레벨API 추상화 
• 차후 대응 플랫폼 추가를 고려하여 설계 
 DirectX11 기반
Contents 
 Engine 소개 
 이행시 주의점 
• DirectX11 변경점 
• Constant Buffer 
• VertexInputLayout 
• State Management 
• Multithread 
• Shader 
• Etc. 
 결론
DirectX11변경점 
 고정 파이프라인 삭제 
 Device 분리 
 CAPS비트 삭제 
 새로운 shader stage 추가 
 Multithread Rendering 
 Dynamic Shader Linkage 
 Tesselation, OIT 
 BC6, BC7 texture format 
 Etc.
DirectX11변경점 
 이 중 DirectX11 을 사용하여 rendering하기 위해 반드시 필 
요한 부분을 DirectX9과 비교 
 독자적으로 대응한 방법에 대한 소개도 있습니다만 정답은 
아니므로 어디까지나 참고
Device 분리 
DirectX11변경점 
 DirectX9의 IDirect3DDevice9 은 DirectX11에서부터 ID3D11Device 와 
ID3D11DeviceContext 로 분리되었음 
 ID3D11Device은 주로 resource 생성을 담당 
• thread-safe 
 ID3D11DeviceContext은 주로 rendering을 담당 
• thread-unsafe 
 자료 소스코드 중 pDevice 는 IDirect3DDevice9, pImmediateContext 은 
ID3D11DeviceContext 의 객체이므로 참고
Contents 
 Engine 소개 
 이행시 주의점 
• DirectX11 변경점 
• Constant Buffer 
• VertexInputLayout 
• State Management 
• Multithread 
• Shader 
• Etc. 
 결론
Constant Buffer? 
Constant Buffer 
 DirectX10부터 추가된 shader parameter 설정을 위한 버퍼 
 DirectX9에서는 개별적으로 설정했지만 DirectX11에서는 버 
퍼 단위의 오브젝트로 변경 
 DirectX11에서 shader 에 값을 전달하기 위해 반드시 필요
DirectX9 
Constant Buffer 
 HLSL(sm3.0)까지의 shader 변수정의 
• C++ global variable 처럼 정의 
HLSL 
float3 g_vLightPos; 
float3 g_vLightDir; 
float4x4 g_mView; 
float4x4 g_mProj; 
float4x4 g_mWorld; 
float4x4 g_mBone[128]; 
float4 g_vMaterial;
DirectX9 
Constant Buffer 
 Parameter 전달 방법 
• Set[datatype](“variable”, &data) 
float3 g_vLightPos; 
float3 g_vLightDir; 
float4x4 g_mView; 
float4x4 g_mProj; 
float4x4 g_mWorld; 
float4x4 g_mBone[128]; 
float4 g_vMaterial; 
Application 
SetVector("g_vLightPos",&lightPos); 
SetMatrix("g_mWorld",&worldMatrix); 
HLSL
DirectX11 
Constant Buffer 
 cbuffer키워드 안에 변수를 묶어서 정의. C언어의 구조체와 비슷 
한 형태 
 선언 뒤에 바인드될 레지스터의 번호를 설정. 16번까지 설정 가 
능 
- 설정하지 않을 경우, 0번부터 차례대로 부여됨 
cbuffer CB : register(b0) 
{ 
float3 vLightPos; 
float3 vLightDir; 
float4x4 mView; 
float4x4 mProj; 
float4x4 mWorld; 
float4x4 mBone[128]; 
float4 vMaterial; 
}; 
HLSL
DirectX11 
Constant Buffer 
1. CreateBuffer로 constant buffer용 버퍼 생성 
2. UpdateSubresource(Map)로 버퍼의 내용을 update 
• 한번의 update로 constant buffer 내용 전부를 덮어씌우므로 주의 
3. XXSetconstantBuffers로 레지스터에 바인드 
ex) VSSetConstantBuffers, PSSetConstantBuffer 등
주의점 
Constant Buffer 
 update 사이즈와 호출회수를 최대한으로 줄여야 함 
• 성능 저하에 민감함 
 가장 실수하기 쉬운 부분 
world matrix만 덮어씌워도 
8424bytes update해야함 
cbuffer CB : register(b0) 
{ 
float3 vLightPos; 
float3 vLightDir; 
float4x4 mView; 
float4x4 mProj; 
float4x4 mWorld; 
float4x4 mBone[128]; 
float4 vMaterial; 
}; 
HLSL
Constant Buffer 
 shader로 전달할 데이터 크기 이상의 constant buffer 를 
update 하는 것은 잘못된 설계 
 필요한 부분만 update 할 수 있도록 constant buffer 를 나 
누어 설계. update 빈도에 따라 나누길 추천 
 한 번 update 한 constant buffer는 최대한 돌려쓰거나 모아 
서 rendering
Constant Buffer 
Application HLSL 
Global 
cbuffer CB : register(b0) 
{ 
float3 vLightPos; 
float3 vLightDir; 
float4x4 mView; 
float4x4 mProj; 
float4x4 mWorld; 
float4x4 mBone[128]; 
float4 vMaterial; 
}; 
Camera 
Object 
Material
Constant Buffer 
Application HLSL 
Global 
Camera 
cbuffer CB : register(b0) 
{ 
float3 vLightPos; 
float3 vLightDir; 
float4x4 mView; 
float4x4 mProj; 
float4x4 mWorld; 
float4x4 mBone[128]; 
float4 vMaterial; 
}; 
8424bytes 
25272bytes 
Object 
Material 
Material 
Material
Constant Buffer 
Application HLSL 
cbuffer perGlobalCB : register(b0) 
{ 
float3 vLightPos; 
float3 vLightDir; 
}; 
cbuffer perCameraCB : register(b1) 
{ 
float4x4 mView; 
float4x4 mProj; 
}; 
cbuffer perObjectCB : register(b2) 
{ 
float4x4 mWorld; 
float4x4 mBone[128]; 
}; 
cbuffer perMaterialCB : register(b3) 
{ 
float4 vMaterial; 
}; 
24bytes 
128bytes 
8256bytes 
16bytes 
Global 
Camera 
Object 
Material 
Material 
Material 
8456bytes
Constant Buffer 
 처음부터 constant buffer의 
update 빈도에 따라 sorting 
하여 rendering 할 수 있도 
록 설계 하는 것이 중요 
 내부 엔진에서는 다음의 4개 
의 빈도로 나누어서 설계 
- Global 
- Camera 
- Object 
- Material 
Global 
Camera 
Object 
Material 
Object 
Material 
Material 
Camera 
Object 
Material
Contents 
 Engine 소개 
 이행시 주의점 
• DirectX11 변경점 
• Constant Buffer 
• VertexInputLayout 
• State Management 
• Multithread 
• Shader 
• Etc. 
 결론
VertexInputLayout 
VertexInputLayout? 
 vertex buffer가 어떤 내용으로 구성되어 있는지 GPU에 알 
려주기 위한 DirectX11 오브젝트 
 DirectX9의 IDirect3DVertexDeclaration9과 비슷
VertexInputLayout 
vertex buffer 1.0f 1.0f 1.0f 1.0f 1.0f 1.0f 1.0f 
GPU 
?
DirectX9 
VertexInputLayout 
position color 
vertex buffer 1.0f 1.0f 1.0f 1.0f 1.0f 1.0f 1.0f 
D3DVERTEXELEMENT9 decl[] = 
{ 
{ 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, 
{ 0, 12, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 0 }, 
D3DDECL_END() 
}; 
pd3dDevice->CreateVertexDeclaration(decl, &pVertexDeclaration); 
pd3dDevice->SetVertexDeclaration(pVertexDeclaration);
DirectX11 
VertexInputLayout 
position color 
vertex buffer 1.0f 1.0f 1.0f 1.0f 1.0f 1.0f 1.0f 
D3D11_INPUT_ELEMENT_DESC decl[] = 
{ 
{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0}, 
{"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0}, 
}; 
UINT numElements = ARRAYSIZE( layout ); 
pd3dDevice->CreateInputLayout( decl, numElements, pVSBlob->GetBufferPointer(), 
pVSBlob->GetBufferSize(), &pVertexLayout ); 
pImmediateContext->IASetInputLayout( pVertexLayout );
VertexInputLayout 
HRESULT CreateInputLayout( 
[in] const D3D11_INPUT_ELEMENT_DESC *pInputElementDescs, 
[in] UINT NumElements, 
[in] const void *pShaderBytecodeWithInputSignature, 
[in] SIZE_T BytecodeLength, 
[out] ID3D11InputLayout **ppInputLayout 
); 
pShaderBytecodeWithInputSignature [in] 
void 
A pointer to the compiled shader. The compiled shader code contains a input signature which 
is validated against the array of elements. 
BytecodeLength [in] 
SIZE_T 
Size of the compiled shader.
VertexInputLayout 
 CreateInputLayout 에서 D3D11_INPUT_ELEMENT_DESC 
과 vertex shader semantic 의 매칭이 이루어짐 
 구조가 일치할 경우 success, 불일치할 경우 fail
VertexInputLayout 
vertex buffer position color 
CreateInputLayout 성공 
D3D11_INPUT_ELEMENT_DESC decl[] = 
{ 
{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0}, 
{"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0}, 
}; 
struct VS_INPUT 
{ 
float3 position : POSITION; 
float4 color : COLOR0; 
}; 
HLSL
VertexInputLayout 
CreateInputLayout 실패 
vertex buffer position color 
D3D11_INPUT_ELEMENT_DESC decl[] = 
{ 
{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0}, 
{"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0}, 
}; 
struct VS_INPUT 
{ 
float3 position : POSITION; 
float3 normal : NORMAL; 
}; 
HLSL
VertexInputLayout 
vertex buffer 1.0f 1.0f 1.0f 1.0f 1.0f 1.0f 1.0f 
D3D11_INPUT_ELEMENT_DESC decl[] = 
{ 
{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0}, 
{"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0}, 
}; 
UINT numElements = ARRAYSIZE( layout ); 
pd3dDevice->CreateInputLayout( decl, numElements, pVSBlob->GetBufferPointer(), 
pVSBlob->GetBufferSize(), &pVertexLayout ); 
pImmediateContext->IASetInputLayout( pVertexLayout ); 
struct VS_INPUT 
{ 
float3 position : POSITION; 
float4 color : COLOR0; 
}; 
HLSL 
position color
VertexInputLayout 
 vertex buffer 의 구성을 알고 있어도 같은 구성의 semantic 
을 가지고 있는 vertex shader를 컴파일 하지 않으면 
VertexInputLayout 생성이 불가능 
 vertex buffer 의 구성만으로 생성이 가능 했던 DirectX9에 
비해 엄격해졌음
VertexInputLayout 
 vertex buffer 와 vertex shader semantic 의 binding이 결정 
된 시점에 VertexInputLayout 동적생성 
한번 생성된 객체는 vertex buffer 와 vertex shader 
semantic 을 key로 가지는 hash table 관리 
⇒ 동적 생성, hash table 검색이 느리고, rendering 할때마 
다 체크하지 않으면 안되기 때문에 비효율적
VertexInputLayout 
 DirectX11에서는 shader reflection기능이 대폭 강화됨 
• semantic 의 type, num, offset 이외에도 constant buffer 의 name, 
variable type 등 대부분의 정보를 프로그램에서 얻어 낼 수 있음 
 vertex shader를 reflection하여 semantic과 일치하는 
VertexInputLayout를 미리 생성. 즉, vertex buffer 기준이 아 
닌 shader semantic기준으로VertexInputLayout를 생성
VertexInputLayout 
HLSL 
struct VS_INPUT 
{ 
float3 position : POSITION; 
float4 color : COLOR0; 
}; 
shader reflection 
D3D11_INPUT_ELEMENT_DESC decl[] = 
{ 
vertex buffer position color 
{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0}, 
{"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0}, 
}; 
UINT numElements = ARRAYSIZE( layout ); 
pd3dDevice->CreateInputLayout( decl, numElements, pVSBlob->GetBufferPointer(), 
pVSBlob->GetBufferSize(), &pVertexLayout ); 
pImmediateContext->IASetInputLayout( pVertexLayout );
VertexInputLayout 
 vertex buffer 와 상관없이 미리 VertexInputLayout 을 생성하기 
때문에 vertex buffer 와의 불일치가 발생하는 경우가 있음 
VertexInputLayout vertex buffer 
position color 문제 없음 
assert 
normal position normal color 
position normal 
position normal color assert ? 
position normal color 
position color
VertexInputLayout 
 vertex buffer 가 GPU에 binding될 때 VertexInputLayout 
정보를 참조하여 필요한 semantic 만 binding 
VertexInputLayout position color 
vertex buffer position normal color 
GPU
VertexInputLayout 
vertex buffer binding 
 vertex buffer 를 나누어 생성 
GPU 
1.0f 1.0f 1.0f 
normal 1.0f 1.0f 1.0f 
1.0f 1.0f 1.0f 1.0f 
position 
color 
UINT posStride = sizeof(float)*3; 
UINT posOffset = 0; 
pImmediateContext->IASetVertexBuffers( 0, 1, &posVB, &posStride, &posOffset ); 
UINT colorStride = sizeof(float)*4; 
UINT colorOffset = 0; 
pImmediateContext->IASetVertexBuffers( 1, 1, &colorVB, &colorStride, &colorOffset );
VertexInputLayout 
vertex buffer binding 
 stride와 offset을 적절히 설정하여 binding 
position normal 
color 
vertex buffer 1.0f 1.0f 1.0f 1.0f 1.0f 1.0f 
1.0f 1.0f 1.0f 1.0f 
GPU 
UINT posStride = sizeof(float)*3; 
UINT posOffset = 0; 
pImmediateContext->IASetVertexBuffers( 0, 1, &VB, &posStride, &posOffset ); 
UINT colorStride = sizeof(float)*4; 
UINT colorOffset = 24; 
pImmediateContext->IASetVertexBuffers( 1, 1, &VB, &colorStride, &colorOffset );
Contents 
 Engine 소개 
 이행시 주의점 
• DirectX11 변경점 
• Constant Buffer 
• VertexInputLayout 
• State Management 
• Multithread 
• Shader 
• Etc. 
 결론
DirectX9 
State Management 
 개별적으로 설정 
 한번 설정된 값은 변경하지 않는 이상 지속됨 
pDevice->SetRenderState( D3DRS_ZENABLE, D3DZB_TRUE ); 
Render(); // z enable – On 
pDevice->SetRenderState( D3DRS_ZWRITEENABLE, FALSE ); 
Render(); // z enable – On, z write - Off
DirectX11 
State Management 
 CreateXXXState 함수로 생성하며 오브젝트로 변경됨 
 개별 설정 불가능. 오브젝트 단위로 설정 
 state를 변경하는 경우 오브젝트를 재생성할 필요가 있음 
 texture sampler도 render state와 동일한 설계로 변경됨
DirectX11 
State Management 
data create set 
Rasterizer D3D11_RASTERIZER_DESC CreateRasterizerState RSSetState 
Blend D3D11_BLEND_DESC CreateBlendState OMSetBlendState 
DepthStencil D3D11_DEPTH_STENCIL_DESC CreateDepthStencilState OMSetDepthStencilState
DirectX11 
State Management 
 생성 예 
D3D11_DEPTH_STENCIL_DESC desc; 
ZeroMemory( &desc, sizeof( D3D11_DEPTH_STENCIL_DESC ) ); 
desc.DepthEnable = TRUE; 
desc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; 
desc.DepthFunc = D3D11_COMPARISON_LESS; 
desc.StencilEnable = FALSE; 
/* set desc.... */ 
ID3D11DepthStencilState* depthStencilState = NULL; 
pDevice->CreateDepthStencilState(&desc, &depthStencilState); 
pImmediateContext->OMSetDepthStencilState( depthStencilState );
DirectX11 
State Management 
 변경 예 
1. z enable – on 
2. z enable – on, z write – off 
pDevice->SetRenderState( D3DRS_ZENABLE, D3DZB_TRUE ); 
Render(); // z enable – On 
pDevice->SetRenderState( D3DRS_ZWRITEENABLE, FALSE ); 
Render(); // z enable – On, z write - Off
DirectX11 
State Management 
ID3D11DepthStencilState* depthStencilState = NULL; 
D3D11_DEPTH_STENCIL_DESC desc; 
desc.DepthEnable = TRUE; 
desc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; 
/* set desc.... */ 
device->CreateDepthStencilState(&desc, &depthStencilState); 
pImmediateContext->OMSetDepthStencilState( depthStencilState ); 
Render(); // z enable – On 
SAFE_RELEASE( depthStencilState ); 
desc.DepthEnable = TRUE; 
desc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ZERO; 
/* set desc.... */ 
pDevice->CreateDepthStencilState(&desc, &depthStencilState); 
pImmediateContext->OMSetDepthStencilState( depthStencilState ); 
Render(); // z enable – On, z write - Off
State Management 
 DirectX9 처럼 global render state 에 모든 설정을 한 후, rendering 직 
전에 오브젝트 생성 
⇒ 동적생성으로 인한 속도저하, multithread 대응 불가능, release 타이 
밍을 잡기 쉽지 않음 
 사전에 사용될 가능성이 있는 render state를 전부 미리 생성해 둠 
⇒ program에서 동적으로 생성되는 타입의 render state에 대응하기 쉽 
지 않음 
ex) wireframe, blend 등
State Management 
 DirectX11은 한번 생성되었던 render state 오브젝트를 내부적으로 관리 
하고 있음 
 2번째 생성하는 경우에 이전에 생성된 render state 오브젝트의 
reference count를 올리고 해당 오브젝트의 pointer를 반환함 
 즉, 한번 생성된 오브젝트를 해제하지 않고 놔두면 2번째 부터는 고속으 
로 생성 가능
State Management 
 한번 생성된 render state는 해제하지 않고 stl set 에 저장. 
2번째 같은 오브젝트가 생성된 경우 reference count를 1로 
유지하기 위해 Release호출 
Create - solid 
Create – wireframe 
solid 
1 
solid 
1 
wireframe 
1 
render state 
count 
render state 
count
State Management 
Create – alpha 
solid wireframe 
1 1 
alpha 
1 
Create – wireframe 
solid wireframe 
1 2 
alpha 
1 
solid wireframe 
1 1 
alpha 
1 
Release 
render state 
count 
render state 
count 
render state 
count
State Management 
 차후 CreateXXXState 하기 위한 copy연산을 줄이기 위해 
render state parameter를 hash key로 관리하는 시스템 
도입 검토중 
D3D11_DEPTH_STENCIL_DESC desc; 
ZeroMemory( &desc, sizeof( D3D11_DEPTH_STENCIL_DESC ) ); 
desc.DepthEnable = EngineToDX11(ENGINE_DEPTH_ON); 
desc.DepthWriteMask = EngineToDX11(ENGINE_ZWRITE_ON); 
desc.DepthFunc = EngineToDX11(ENGINE_COMPARISON_LESS); 
desc.StencilEnable = EngineToDX11(ENGINE_STENCIL_ON); 
/* set desc.... */
Contents 
 Engine 소개 
 이행시 주의점 
• DirectX11 변경점 
• Constant Buffer 
• VertexInputLayout 
• State Management 
• Multithread 
• Shader 
• Etc. 
 결론
Multithread 
 코어수의 증가와 더불어, 멀티코어 대응 프로그래밍은 선택 
이 아닌 필수!
Multithread
Multithread
ID3D11DeviceContext 
Multithread 
 immediate context 
• rendering 명령을 실행하는 오브젝트 
• 1개만 생성 가능하며 thread unsafe 
 deferred context 
• immediate context의 multithread 대응 오브젝트. 여러 개 생성 가능 
하며 각 thread 에서 rendering 명령을 실행 
• immediate context와 사용가능한 함수는 완전 일치 
• 각 thread에서 모든 rendering 명령의 실행이 끝난 후에 
FinishCommandList 를 호출하여 command list 를 얻어옴. 이후 
command list를 immediate context 에서 실행
Deferred Context 
Multithread 
1. 생성 
ID3D11DeviceContext* pImmediateContext; 
ID3D11DeviceContext* pDeferredContext; 
/* pImmediateContext생성 후 */ 
pDevice->CreateDeferredContext( 0, &pDeferredContext ); 
2. 각 thread 마지막에 실행 
/* pDeferredContext를 이용한 rendering 완료후 */ 
pDeferredContext->FinishCommandList( FALSE, &pCommandList ); 
3. immediate context에서 command list 실행 
pImmediateContext->ExecuteCommandList( pCommandList, FALSE );
Deferred Context 
Multithread
Draw Command 
Multithread 
 내부 엔진에서는 중간 단계 rendering command 를 자체적 
으로 구현 
 모든 command 에는 priority 를 붙여서 생성 
 각 thread에서 생성된 command 를 sorting 한 후 
rendering thread 에 전달 
 rendering thread에서 각각의 command를 merge sort 한 
후 이를 순차적으로 실행
Multithread 
Draw Command 
Secondary thread#1 
60 SetShader 
61 BindBuffer 
10 Clear 
60 SetShader 
61 BindBuffer 
Secondary thread#2 Secondary thread#3 
10 Clear 
50 SetRenderState 
21 SetRenderState 
22 SetShader 
21 SetRenderState 
22 SetShader 
50 SetRenderState 
40 Clear 
30 RenderPolygon 
23 BindTexture 
23 BindTexture 
30 RenderPolygon 
40 Clear
Multithread 
Draw Command 
Render thread 
10 Clear 
60 SetShader 
10 Clear 
21 SetRenderState 
22 SetShader 
21 SetRenderState 
22 SetShader 
23 BindTexture 
30 RenderPolygon 
40 Clear 
23 BindTexture 
30 RenderPolygon 
50 SetRenderState 
60 SetShader 
61 BindBuffer 
61 BindBuffer 
50 SetRenderState 
40 Clear
Draw Command 
Multithread 
 장점 
• priority를 이용해 유연성있게 rendering 순서를 조절 가능 
• Graphics API에서 multithread를 대응하지 않는 경우 대응이 쉬움 
• Draw Command의 기록을 남겨 replay나 디버깅에 활용 
 단점 
• Graphics API단에서의 병렬화가 아니므로, 일부 명령어는 병렬화 되 
지 않을 가능성이 있음
Multithread 
 처음부터 multithread를 고려하여 설계하는 것이 중요 
• Single-thread기준으로 작성된 프로젝트를 multithread 구조로 변경 
하기 매우 힘듦 
 Multithread를 고려하지 않으면 속도 올리기가 쉽지 않음 
 하드웨어의 스펙을 100% 활용합시다!
Contents 
 Engine 소개 
 이행시 주의점 
• DirectX11 변경점 
• Constant Buffer 
• VertexInputLayout 
• State Management 
• Multithread 
• Shader 
• Etc. 
 결론
shader model 
Shader 
 DirectX9 – 1.0, 2.0, 3.0 
 DirectX10 – 4.0, 4.1 
 DirectX11 – 5.0
constant buffer 
Shader 
 program에서 값을 받을 필요가 있는 parameter는 constant 
buffer로 정의 
cbuffer perGlobalCB : register(b0) 
{ 
float3 vLightPos; 
float3 vLightDir; 
}; 
cbuffer perCameraCB : register(b1) 
{ 
float4x4 mView; 
float4x4 mProj; 
}; 
cbuffer perObjectCB : register(b2) 
{ 
float4x4 mWorld; 
float4x4 mBone[128]; 
}; 
cbuffer perMaterialCB : register(b3) 
{ 
float4 vMaterial; 
}; 
float3 g_vLightPos; 
float3 g_vLightDir; 
float4x4 g_mView; 
float4x4 g_mProj; 
float4x4 g_mWorld; 
float4x4 g_mBone[128]; 
float4 g_vMaterial;
Texture, Sampler 의 Binding 
Shader 
 DirectX9에서는 sampler선언 시에 binding 
texture g_texture; 
sampler2D g_sampler = sampler_state 
{ 
Texture = <g_texture>; 
MinFilter = Point; 
MagFilter = Linear; 
MipFilter = Linear; 
}; 
float4 PS( PS_INPUT input ) : COLOR 
{ 
return tex2D( g_sampler, input.texCoord ); 
}
Texture, Sampler 의 Binding 
Shader 
 DirectX11에서는 sampling 함수를 호출하는 시점에 binding 
texture2D g_texture; 
SamplerState g_sampler; 
float4 PS( PS_INPUT input ) : SV_Target 
{ 
return g_texture.Sample( g_sampler, input.texCoord ); 
}
Sampler 정의 
Shader 
 DirectX11의 경우, shader에 적힌 sampler 속성은 effect를 사용 
하지 않는 한 적용되지 않으므로 주의 
 effect를 사용하지 않는 경우는 프로그램에서 설정 
DirectX9 
sampler2D g_sampler = sampler_state 
{ 
Texture = <g_texture>; 
MinFilter = Point; 
MagFilter = Linear; 
MipFilter = Linear; 
}; 
SamplerState g_sampler 
{ 
Filter = MIN_MAG_MIP_LINEAR; 
}; 
DirectX11
Effect 
Shader 
 shader 설정, render state의 정의하는 방법이 변경 되었으 
니 주의 
BlendState NoBlend 
{ 
BlendEnbale[0] = False; 
}; 
DepthStencilState DepthTestOn 
{ 
DepthEnable = True; 
DepthWriteMask = All; 
DepthFunc = LESS; 
}; 
RasterizerState rsWireframe 
{ 
FillMode = Solid; 
CullMode = Back; 
FrontCounterClockwise = False; 
}; 
VertexShader vs_main = CompileShader( vs_5_0, VS() ); 
PixelShader ps_main = CompileShader( ps_5_0, PS() ); 
technique11 t0 
{ 
pass p0 
{ 
SetBlendState( NoBlend, float4(0.0f,0.0f,0.0f,0.0f), 
0xFFFFFFFF ); 
SetDepthStencilState( DepthTestOn, 0 ); 
SetRasterizerState( rsWireframe ); 
SetVertexShader( vs_main ); 
SetGeometryShader( NULL ); 
SetPixelShader( ps_main ); 
} 
}
Intrinsic Functions 
Shader
Contents 
 Engine 소개 
 이행시 주의점 
• DirectX11 변경점 
• Constant Buffer 
• VertexInputLayout 
• State Management 
• Multithread 
• Shader 
• Etc. 
 결론
Texture Array 
Etc. 
 다수의 texture를 한번에 shader로 전달하는 것이 가능해짐 
 Texture이외의 material parameter가 같은 경우, texture 변경 없이 한번 
에 rendering 할 수 있음 
 리소스 파이프라인 변경 없이 texture atlas의 효과를 얻을 수 있음
Format 
Etc. 
 D3DFMT_XXX가 DXGI_FORMAT_XXX로 변경 
 D3DFMT_XXX에서 추가, 변경, 삭제 된 포맷이 있 
으므로 주의 
 지원되지 않는 포맷을 리소스에서 사용하고 있는 
경우 차후 문제가 생길 여지가 있으므로 주의
Primitive 
Etc. 
 D3DPT_TRIANGLEFAN가 삭제됨 
 프로그램에서 geometry를 생성하는 타입은 소스코드 수정 
 리소스에서 사용되는 경우 지원되는 primitive 포맷으로 export를 다시 
하거나 로딩 시에 변환
Contents 
 Engine 소개 
 이행시 주의점 
• DirectX11 변경점 
• Constant Buffer 
• VertexInputLayout 
• State Management 
• Multithread 
• Shader 
• Etc. 
 결론
결론 
 DirectX11 은 DirectX9 과 비교하여 많은 점이 변경 되었음. 
기존 엔진&라이브러리를 이식하는 경우 생각보다 쉽지 않 
음 
 단, 그만큼 차세대에 어울리는 설계가 되어 있으므로, 
application에서도 graphics API를 이해하고 그 성능을 십 
분 활용할 수 있는 설계가 필요함
결론 
Q&A
WE’RE HIRING 
결론 
 엔지니어 채용중 
 inq_rec@cc2.co.jp
결론 
 References 
• Game fest2007 : Windows to Reality: Getting the Most out of Direct3D 10 Graphics in Your Games 
• GDC 2013 : D3D11 Deferred Contexts 
• CEDEC 2006 : 次世代機に向けたゲームエンジンの設計 
• GDC 2011 : DX11 Performance Gems 
• CEDEC 2014 : 「世代間マルチプラットフォーム平行開発」~PlayStation4版「龍が如く維新!」開発の一年~ 
• http://msdn.microsoft.com/ko-kr/library/windows/apps/bb943991.aspx#File_Layout1 
• http://msdn.microsoft.com/ko-kr/library/windows/desktop/ff476892%28v=vs.85%29.aspx 
• http://msdn.microsoft.com/en-us/library/windows/desktop/ff471376%28v=vs.85%29.aspx 
• http://www.gamedev.net/topic/542778-samplerstate-within-shader-snt-working-in-d3d10/ 
• http://en.wikipedia.org/wiki/High-level_shader_language 
• http://msdn.microsoft.com/en-us/library/windows/desktop/hh404586%28v=vs.85%29.aspx 
 Images 
• http://btoのパソコン.com/mametisiki/cpu.php 
• http://www.virtuaniz.com/2013/12/playstation-4-vs-playstation-3-heres-the-comparison-is-ps4-worth-buying-or-sit-back-with-ps3/ 
• http://prohardver.hu/tudastar/direct3d_deferred_context.html 
• http://lukasz.dk/2011/04/18/texture-atlas-generator/ 
• http://www.codesampler.com/d3dbook/chapter_05/chapter_05.htm 
• http://volkansahin.net/oyunlarda-grafik/
1 of 93

Recommended

Direct x 11 입문 by
Direct x 11 입문Direct x 11 입문
Direct x 11 입문Jin Woo Lee
5.4K views51 slides
Compute shader DX11 by
Compute shader DX11Compute shader DX11
Compute shader DX11민웅 이
4K views24 slides
멀티스레드 렌더링 (Multithreaded rendering) by
멀티스레드 렌더링 (Multithreaded rendering)멀티스레드 렌더링 (Multithreaded rendering)
멀티스레드 렌더링 (Multithreaded rendering)Bongseok Cho
1.1K views61 slides
NDC2016 프로젝트 A1의 AAA급 캐릭터 렌더링 기술 by
NDC2016 프로젝트 A1의 AAA급 캐릭터 렌더링 기술NDC2016 프로젝트 A1의 AAA급 캐릭터 렌더링 기술
NDC2016 프로젝트 A1의 AAA급 캐릭터 렌더링 기술Ki Hyunwoo
12K views94 slides
[NHN_NEXT] DirectX Tutorial 강의 자료 by
[NHN_NEXT] DirectX Tutorial 강의 자료[NHN_NEXT] DirectX Tutorial 강의 자료
[NHN_NEXT] DirectX Tutorial 강의 자료MinGeun Park
5.9K views40 slides
IndirectDraw with unity by
IndirectDraw with unityIndirectDraw with unity
IndirectDraw with unityJung Suk Ko
1.9K views18 slides

More Related Content

What's hot

빠른 렌더링을 위한 오브젝트 제외 기술 by
빠른 렌더링을 위한 오브젝트 제외 기술빠른 렌더링을 위한 오브젝트 제외 기술
빠른 렌더링을 위한 오브젝트 제외 기술YEONG-CHEON YOU
1.4K views89 slides
Tips and experience of DX12 Engine development . by
Tips and experience of DX12 Engine development .Tips and experience of DX12 Engine development .
Tips and experience of DX12 Engine development .YEONG-CHEON YOU
2.6K views53 slides
Ndc2010 전형규 마비노기2 캐릭터 렌더링 기술 by
Ndc2010 전형규   마비노기2 캐릭터 렌더링 기술Ndc2010 전형규   마비노기2 캐릭터 렌더링 기술
Ndc2010 전형규 마비노기2 캐릭터 렌더링 기술henjeon
10.7K views71 slides
Hierachical z Map Occlusion Culling by
Hierachical z Map Occlusion CullingHierachical z Map Occlusion Culling
Hierachical z Map Occlusion CullingYEONG-CHEON YOU
2.9K views35 slides
나만의 엔진 개발하기 by
나만의 엔진 개발하기나만의 엔진 개발하기
나만의 엔진 개발하기YEONG-CHEON YOU
1.3K views91 slides
김혁, <드래곤 하운드>의 PBR과 레이트레이싱 렌더링 기법, NDC2019 by
김혁, <드래곤 하운드>의 PBR과 레이트레이싱 렌더링 기법, NDC2019김혁, <드래곤 하운드>의 PBR과 레이트레이싱 렌더링 기법, NDC2019
김혁, <드래곤 하운드>의 PBR과 레이트레이싱 렌더링 기법, NDC2019devCAT Studio, NEXON
1.8K views96 slides

What's hot(20)

빠른 렌더링을 위한 오브젝트 제외 기술 by YEONG-CHEON YOU
빠른 렌더링을 위한 오브젝트 제외 기술빠른 렌더링을 위한 오브젝트 제외 기술
빠른 렌더링을 위한 오브젝트 제외 기술
YEONG-CHEON YOU1.4K views
Tips and experience of DX12 Engine development . by YEONG-CHEON YOU
Tips and experience of DX12 Engine development .Tips and experience of DX12 Engine development .
Tips and experience of DX12 Engine development .
YEONG-CHEON YOU2.6K views
Ndc2010 전형규 마비노기2 캐릭터 렌더링 기술 by henjeon
Ndc2010 전형규   마비노기2 캐릭터 렌더링 기술Ndc2010 전형규   마비노기2 캐릭터 렌더링 기술
Ndc2010 전형규 마비노기2 캐릭터 렌더링 기술
henjeon10.7K views
Hierachical z Map Occlusion Culling by YEONG-CHEON YOU
Hierachical z Map Occlusion CullingHierachical z Map Occlusion Culling
Hierachical z Map Occlusion Culling
YEONG-CHEON YOU2.9K views
나만의 엔진 개발하기 by YEONG-CHEON YOU
나만의 엔진 개발하기나만의 엔진 개발하기
나만의 엔진 개발하기
YEONG-CHEON YOU1.3K views
김혁, <드래곤 하운드>의 PBR과 레이트레이싱 렌더링 기법, NDC2019 by devCAT Studio, NEXON
김혁, <드래곤 하운드>의 PBR과 레이트레이싱 렌더링 기법, NDC2019김혁, <드래곤 하운드>의 PBR과 레이트레이싱 렌더링 기법, NDC2019
김혁, <드래곤 하운드>의 PBR과 레이트레이싱 렌더링 기법, NDC2019
게임프로젝트에 적용하는 GPGPU by YEONG-CHEON YOU
게임프로젝트에 적용하는 GPGPU게임프로젝트에 적용하는 GPGPU
게임프로젝트에 적용하는 GPGPU
YEONG-CHEON YOU5.4K views
FrameGraph: Extensible Rendering Architecture in Frostbite by Electronic Arts / DICE
FrameGraph: Extensible Rendering Architecture in FrostbiteFrameGraph: Extensible Rendering Architecture in Frostbite
FrameGraph: Extensible Rendering Architecture in Frostbite
리플렉션과 가비지 컬렉션 by QooJuice
리플렉션과 가비지 컬렉션리플렉션과 가비지 컬렉션
리플렉션과 가비지 컬렉션
QooJuice652 views
AAA게임_UI_최적화_및_빌드하기.pptx by TonyCms
AAA게임_UI_최적화_및_빌드하기.pptxAAA게임_UI_최적화_및_빌드하기.pptx
AAA게임_UI_최적화_및_빌드하기.pptx
TonyCms524 views
Unite2019 HLOD를 활용한 대규모 씬 제작 방법 by 장규 서
Unite2019 HLOD를 활용한 대규모 씬 제작 방법Unite2019 HLOD를 활용한 대규모 씬 제작 방법
Unite2019 HLOD를 활용한 대규모 씬 제작 방법
장규 서1.9K views
C++20에서 리플렉션 기능 구현 by Bongseok Cho
C++20에서 리플렉션 기능 구현C++20에서 리플렉션 기능 구현
C++20에서 리플렉션 기능 구현
Bongseok Cho1.6K views
[NDC2017] 뛰는 프로그래머 나는 언리얼 엔진 - 언알못에서 커미터까지 by Minjung Ko
[NDC2017] 뛰는 프로그래머 나는 언리얼 엔진 - 언알못에서 커미터까지[NDC2017] 뛰는 프로그래머 나는 언리얼 엔진 - 언알못에서 커미터까지
[NDC2017] 뛰는 프로그래머 나는 언리얼 엔진 - 언알못에서 커미터까지
Minjung Ko3.6K views
[Kgc2012] deferred forward 이창희 by changehee lee
[Kgc2012] deferred forward 이창희[Kgc2012] deferred forward 이창희
[Kgc2012] deferred forward 이창희
changehee lee11.4K views
[Ndc11 박민근] deferred shading by MinGeun Park
[Ndc11 박민근] deferred shading[Ndc11 박민근] deferred shading
[Ndc11 박민근] deferred shading
MinGeun Park15.8K views
Clipmap 논문 요약 by JK K
Clipmap 논문 요약Clipmap 논문 요약
Clipmap 논문 요약
JK K2.2K views
NDC2017 언리얼엔진4 디버깅 101 - 게임 기획자, 프로그래머가 버그와 만났을 때 사용할 수 있는 지침들 by 영욱 오
NDC2017 언리얼엔진4 디버깅 101 - 게임 기획자, 프로그래머가 버그와 만났을 때 사용할 수 있는 지침들NDC2017 언리얼엔진4 디버깅 101 - 게임 기획자, 프로그래머가 버그와 만났을 때 사용할 수 있는 지침들
NDC2017 언리얼엔진4 디버깅 101 - 게임 기획자, 프로그래머가 버그와 만났을 때 사용할 수 있는 지침들
영욱 오6.8K views
전형규, 가성비 좋은 렌더링 테크닉 10선, NDC2012 by devCAT Studio, NEXON
전형규, 가성비 좋은 렌더링 테크닉 10선, NDC2012전형규, 가성비 좋은 렌더링 테크닉 10선, NDC2012
전형규, 가성비 좋은 렌더링 테크닉 10선, NDC2012
송창규, unity build로 빌드타임 반토막내기, NDC2010 by devCAT Studio, NEXON
송창규, unity build로 빌드타임 반토막내기, NDC2010송창규, unity build로 빌드타임 반토막내기, NDC2010
송창규, unity build로 빌드타임 반토막내기, NDC2010
devCAT Studio, NEXON32.1K views
[KGC2011_박민근] 신입 게임 개발자가 알아야 할 것들 by MinGeun Park
[KGC2011_박민근] 신입 게임 개발자가 알아야 할 것들[KGC2011_박민근] 신입 게임 개발자가 알아야 할 것들
[KGC2011_박민근] 신입 게임 개발자가 알아야 할 것들
MinGeun Park16.6K views

Viewers also liked

Windows to reality getting the most out of direct3 d 10 graphics in your games by
Windows to reality   getting the most out of direct3 d 10 graphics in your gamesWindows to reality   getting the most out of direct3 d 10 graphics in your games
Windows to reality getting the most out of direct3 d 10 graphics in your gameschangehee lee
7.1K views53 slides
[0312 조진현] good bye dx9 by
[0312 조진현] good bye dx9[0312 조진현] good bye dx9
[0312 조진현] good bye dx9진현 조
1.4K views166 slides
[0602 박민근] Direct2D by
[0602 박민근] Direct2D[0602 박민근] Direct2D
[0602 박민근] Direct2D흥배 최
9.5K views133 slides
전형규, M2 클라이언트 스레딩 아키텍쳐, NDC2013 by
전형규, M2 클라이언트 스레딩 아키텍쳐, NDC2013전형규, M2 클라이언트 스레딩 아키텍쳐, NDC2013
전형규, M2 클라이언트 스레딩 아키텍쳐, NDC2013devCAT Studio, NEXON
4.1K views88 slides
C++ 프로젝트에 단위 테스트 도입하기 by
C++ 프로젝트에 단위 테스트 도입하기C++ 프로젝트에 단위 테스트 도입하기
C++ 프로젝트에 단위 테스트 도입하기Heo Seungwook
15.2K views55 slides
KGC2010 - 낡은 코드에 단위테스트 넣기 by
KGC2010 - 낡은 코드에 단위테스트 넣기KGC2010 - 낡은 코드에 단위테스트 넣기
KGC2010 - 낡은 코드에 단위테스트 넣기Ryan Park
5.1K views125 slides

Viewers also liked(18)

Windows to reality getting the most out of direct3 d 10 graphics in your games by changehee lee
Windows to reality   getting the most out of direct3 d 10 graphics in your gamesWindows to reality   getting the most out of direct3 d 10 graphics in your games
Windows to reality getting the most out of direct3 d 10 graphics in your games
changehee lee7.1K views
[0312 조진현] good bye dx9 by 진현 조
[0312 조진현] good bye dx9[0312 조진현] good bye dx9
[0312 조진현] good bye dx9
진현 조1.4K views
[0602 박민근] Direct2D by 흥배 최
[0602 박민근] Direct2D[0602 박민근] Direct2D
[0602 박민근] Direct2D
흥배 최9.5K views
전형규, M2 클라이언트 스레딩 아키텍쳐, NDC2013 by devCAT Studio, NEXON
전형규, M2 클라이언트 스레딩 아키텍쳐, NDC2013전형규, M2 클라이언트 스레딩 아키텍쳐, NDC2013
전형규, M2 클라이언트 스레딩 아키텍쳐, NDC2013
C++ 프로젝트에 단위 테스트 도입하기 by Heo Seungwook
C++ 프로젝트에 단위 테스트 도입하기C++ 프로젝트에 단위 테스트 도입하기
C++ 프로젝트에 단위 테스트 도입하기
Heo Seungwook15.2K views
KGC2010 - 낡은 코드에 단위테스트 넣기 by Ryan Park
KGC2010 - 낡은 코드에 단위테스트 넣기KGC2010 - 낡은 코드에 단위테스트 넣기
KGC2010 - 낡은 코드에 단위테스트 넣기
Ryan Park5.1K views
모바일 게임 최적화 by tartist
모바일 게임 최적화 모바일 게임 최적화
모바일 게임 최적화
tartist12.1K views
NDC 2015 박주은,최재혁 물리기반렌더링 지난1년간의 경험 by Jooeun Park
NDC 2015 박주은,최재혁 물리기반렌더링 지난1년간의 경험NDC 2015 박주은,최재혁 물리기반렌더링 지난1년간의 경험
NDC 2015 박주은,최재혁 물리기반렌더링 지난1년간의 경험
Jooeun Park11.1K views
[C++ Korea 2nd Seminar] C++17 Key Features Summary by Chris Ohk
[C++ Korea 2nd Seminar] C++17 Key Features Summary[C++ Korea 2nd Seminar] C++17 Key Features Summary
[C++ Korea 2nd Seminar] C++17 Key Features Summary
Chris Ohk10.5K views
물리 기반 셰이더의 이해 by tartist
물리 기반 셰이더의 이해물리 기반 셰이더의 이해
물리 기반 셰이더의 이해
tartist12.5K views
NDC2015 유니티 정적 라이팅 이게 최선인가요 by Wuwon Yu
NDC2015 유니티 정적 라이팅 이게 최선인가요  NDC2015 유니티 정적 라이팅 이게 최선인가요
NDC2015 유니티 정적 라이팅 이게 최선인가요
Wuwon Yu16.2K views
[C++ Korea 3rd Seminar] 새 C++은 새 Visual Studio에, 좌충우돌 마이그레이션 이야기 by Chris Ohk
[C++ Korea 3rd Seminar] 새 C++은 새 Visual Studio에, 좌충우돌 마이그레이션 이야기[C++ Korea 3rd Seminar] 새 C++은 새 Visual Studio에, 좌충우돌 마이그레이션 이야기
[C++ Korea 3rd Seminar] 새 C++은 새 Visual Studio에, 좌충우돌 마이그레이션 이야기
Chris Ohk11.8K views
이승재, M2 AI코드 개발 생산성 향상 사례, NDC2013 by devCAT Studio, NEXON
이승재, M2 AI코드 개발 생산성 향상 사례, NDC2013이승재, M2 AI코드 개발 생산성 향상 사례, NDC2013
이승재, M2 AI코드 개발 생산성 향상 사례, NDC2013
[160402_데브루키_박민근] UniRx 소개 by MinGeun Park
[160402_데브루키_박민근] UniRx 소개[160402_데브루키_박민근] UniRx 소개
[160402_데브루키_박민근] UniRx 소개
MinGeun Park36.2K views
물리 기반 셰이더의 허와 실:물리기반 셰이더를 가르쳐 봤습니다 공개용 by JP Jung
물리 기반 셰이더의 허와 실:물리기반 셰이더를 가르쳐 봤습니다  공개용물리 기반 셰이더의 허와 실:물리기반 셰이더를 가르쳐 봤습니다  공개용
물리 기반 셰이더의 허와 실:물리기반 셰이더를 가르쳐 봤습니다 공개용
JP Jung30.1K views
유니티의 툰셰이딩을 사용한 3D 애니메이션 표현 by MinGeun Park
유니티의 툰셰이딩을 사용한 3D 애니메이션 표현유니티의 툰셰이딩을 사용한 3D 애니메이션 표현
유니티의 툰셰이딩을 사용한 3D 애니메이션 표현
MinGeun Park46.4K views
Modern gpu optimize blog by ozlael ozlael
Modern gpu optimize blogModern gpu optimize blog
Modern gpu optimize blog
ozlael ozlael3.6K views
게임수학 강의노트 1부 by Young-Min kang
게임수학 강의노트 1부게임수학 강의노트 1부
게임수학 강의노트 1부
Young-Min kang9.3K views

Similar to [KGC2014] DX9에서DX11로의이행경험공유

Introduction to DirectX 12 Programming , Ver 1.5 by
Introduction to DirectX 12 Programming , Ver 1.5Introduction to DirectX 12 Programming , Ver 1.5
Introduction to DirectX 12 Programming , Ver 1.5YEONG-CHEON YOU
840 views74 slides
2015 제2회 동아리 해커 세미나 - 병렬컴퓨팅 소개 (16기 김정현) by
2015 제2회 동아리 해커 세미나 - 병렬컴퓨팅 소개 (16기 김정현)2015 제2회 동아리 해커 세미나 - 병렬컴퓨팅 소개 (16기 김정현)
2015 제2회 동아리 해커 세미나 - 병렬컴퓨팅 소개 (16기 김정현)khuhacker
1.9K views44 slides
Remote-debugging-based-on-notrace32-20130619-1900 by
Remote-debugging-based-on-notrace32-20130619-1900Remote-debugging-based-on-notrace32-20130619-1900
Remote-debugging-based-on-notrace32-20130619-1900Samsung Electronics
121 views25 slides
[조진현] [Kgc2011]direct x11 이야기 by
[조진현] [Kgc2011]direct x11 이야기[조진현] [Kgc2011]direct x11 이야기
[조진현] [Kgc2011]direct x11 이야기진현 조
3.2K views118 slides
[조진현]Kgc2012 c++amp by
[조진현]Kgc2012 c++amp[조진현]Kgc2012 c++amp
[조진현]Kgc2012 c++amp진현 조
1.4K views70 slides
CDVS/CDVA by
CDVS/CDVACDVS/CDVA
CDVS/CDVAJongmin Park
111 views50 slides

Similar to [KGC2014] DX9에서DX11로의이행경험공유(20)

Introduction to DirectX 12 Programming , Ver 1.5 by YEONG-CHEON YOU
Introduction to DirectX 12 Programming , Ver 1.5Introduction to DirectX 12 Programming , Ver 1.5
Introduction to DirectX 12 Programming , Ver 1.5
YEONG-CHEON YOU840 views
2015 제2회 동아리 해커 세미나 - 병렬컴퓨팅 소개 (16기 김정현) by khuhacker
2015 제2회 동아리 해커 세미나 - 병렬컴퓨팅 소개 (16기 김정현)2015 제2회 동아리 해커 세미나 - 병렬컴퓨팅 소개 (16기 김정현)
2015 제2회 동아리 해커 세미나 - 병렬컴퓨팅 소개 (16기 김정현)
khuhacker1.9K views
Remote-debugging-based-on-notrace32-20130619-1900 by Samsung Electronics
Remote-debugging-based-on-notrace32-20130619-1900Remote-debugging-based-on-notrace32-20130619-1900
Remote-debugging-based-on-notrace32-20130619-1900
[조진현] [Kgc2011]direct x11 이야기 by 진현 조
[조진현] [Kgc2011]direct x11 이야기[조진현] [Kgc2011]direct x11 이야기
[조진현] [Kgc2011]direct x11 이야기
진현 조3.2K views
[조진현]Kgc2012 c++amp by 진현 조
[조진현]Kgc2012 c++amp[조진현]Kgc2012 c++amp
[조진현]Kgc2012 c++amp
진현 조1.4K views
Tips and experience_of_dx12_engine_development._ver_1.2 by YEONG-CHEON YOU
Tips and experience_of_dx12_engine_development._ver_1.2Tips and experience_of_dx12_engine_development._ver_1.2
Tips and experience_of_dx12_engine_development._ver_1.2
YEONG-CHEON YOU594 views
[NDC2015] 언제 어디서나 프로파일링 가능한 코드네임 JYP 작성기 - 라이브 게임 배포 후에도 프로파일링 하기 by Jaeseung Ha
[NDC2015] 언제 어디서나 프로파일링 가능한 코드네임 JYP 작성기 - 라이브 게임 배포 후에도 프로파일링 하기[NDC2015] 언제 어디서나 프로파일링 가능한 코드네임 JYP 작성기 - 라이브 게임 배포 후에도 프로파일링 하기
[NDC2015] 언제 어디서나 프로파일링 가능한 코드네임 JYP 작성기 - 라이브 게임 배포 후에도 프로파일링 하기
Jaeseung Ha3.4K views
NDC 2017 하재승 NEXON ZERO (넥슨 제로) 점검없이 실시간으로 코드 수정 및 게임 정보 수집하기 by Jaeseung Ha
NDC 2017 하재승 NEXON ZERO (넥슨 제로) 점검없이 실시간으로 코드 수정 및 게임 정보 수집하기NDC 2017 하재승 NEXON ZERO (넥슨 제로) 점검없이 실시간으로 코드 수정 및 게임 정보 수집하기
NDC 2017 하재승 NEXON ZERO (넥슨 제로) 점검없이 실시간으로 코드 수정 및 게임 정보 수집하기
Jaeseung Ha4.8K views
[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기 by 현철 조
[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기
[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기
현철 조10.7K views
Quick & Dirty Tips for x64 hooks by 용환 노
Quick & Dirty Tips for x64 hooksQuick & Dirty Tips for x64 hooks
Quick & Dirty Tips for x64 hooks
용환 노1.3K views
Ndc2011 성능 향상을_위한_데이터베이스_아키텍쳐_구축_및_개발_가이드 by cranbe95
Ndc2011 성능 향상을_위한_데이터베이스_아키텍쳐_구축_및_개발_가이드Ndc2011 성능 향상을_위한_데이터베이스_아키텍쳐_구축_및_개발_가이드
Ndc2011 성능 향상을_위한_데이터베이스_아키텍쳐_구축_및_개발_가이드
cranbe953.4K views
NDC14 범용 게임 서버 프레임워크 디자인 및 테크닉 by iFunFactory Inc.
NDC14 범용 게임 서버 프레임워크 디자인 및 테크닉NDC14 범용 게임 서버 프레임워크 디자인 및 테크닉
NDC14 범용 게임 서버 프레임워크 디자인 및 테크닉
iFunFactory Inc.6.7K views
덤프 파일을 통한 사후 디버깅 실용 테크닉 NDC2012 by Esun Kim
덤프 파일을 통한 사후 디버깅 실용 테크닉 NDC2012덤프 파일을 통한 사후 디버깅 실용 테크닉 NDC2012
덤프 파일을 통한 사후 디버깅 실용 테크닉 NDC2012
Esun Kim21.2K views
Jnetpcap quickguide by Sukjin Yun
Jnetpcap quickguideJnetpcap quickguide
Jnetpcap quickguide
Sukjin Yun1.6K views
개발자가 알아야 할 .NET Framework 하이라이트 2.0 에서 3.5 SP1 까지… by 준일 엄
개발자가 알아야 할 .NET Framework 하이라이트 2.0 에서 3.5 SP1 까지… 개발자가 알아야 할 .NET Framework 하이라이트 2.0 에서 3.5 SP1 까지…
개발자가 알아야 할 .NET Framework 하이라이트 2.0 에서 3.5 SP1 까지…
준일 엄707 views
[아이펀팩토리]2017 NDC 강연 자료_아이펀 엔진 개발 노트 by iFunFactory Inc.
[아이펀팩토리]2017 NDC 강연 자료_아이펀 엔진 개발 노트[아이펀팩토리]2017 NDC 강연 자료_아이펀 엔진 개발 노트
[아이펀팩토리]2017 NDC 강연 자료_아이펀 엔진 개발 노트
iFunFactory Inc.1.5K views
NDC15 - 사례로 살펴보는 MSVC 빌드 최적화 팁 by Yi-kwon Hwang
NDC15 - 사례로 살펴보는 MSVC 빌드 최적화 팁NDC15 - 사례로 살펴보는 MSVC 빌드 최적화 팁
NDC15 - 사례로 살펴보는 MSVC 빌드 최적화 팁
Yi-kwon Hwang2.8K views

[KGC2014] DX9에서DX11로의이행경험공유

  • 1. DirectX9에서 DirectX11 으로의 이행 경험 공유 민 환 CyberConnect2 / 기술개발실
  • 2. 세션 개요  세션에서 다루는 내용 • CyberConnect2의 DirectX11엔진 이야기 • DirectX11 API설계 • 게임 내용, 최신 테크닉은 다루지 않습니다  세션의 대상 • DirectX9세대의 Graphics API를 사용해 본 적이 있는 분 • 앞으로 DirectX11를 사용하실 분
  • 3. Company CyberConnect2 福岡県福岡市博多区博多駅前1丁目 東京都品川区大井1丁目 1996年2月16日 본사134명 동경25명 40,000,000 円 가정용 게임소프트의 제작 및 개발 회사명 본사 동경지사 설립일 사원수 자본금 사업내용
  • 4. Company .hack series NARUTO SHIPPUDEN NARUTO SHIPPUDEN™: Ultimate Ninja® STORM Revolution game software ©2014 BANDAI NAMCO Games Inc. NARUTO artwork and elements © 2002 MASASHI KISHIMOTO / 2007 SHIPPUDEN All Rights Reserved. ©Drecom Co., Ltd. powered by CyberConnect2 Co., Ltd. series JoJo's Bizarre Adventure All Star Battle
  • 5. Speaker • CyberConnect2 기술개발실 • Engine Programmer • 현재 내부 엔진 제작중 • h_min@cc2.co.jp
  • 6. Contents  Engine 소개  이행시 주의점 • DirectX11 변경점 • Constant Buffer • VertexInputLayout • State Management • Multithread • Shader • Etc.  결론
  • 7. Contents  Engine 소개  이행시 주의점 • DirectX11 변경점 • Constant Buffer • VertexInputLayout • State Management • Multithread • Shader • Etc.  결론
  • 8. History Engine 소개  2013년 3월부터 내부엔진 제작 시작  3~4명으로 제작중
  • 9. 방향성 Engine 소개  멀티 플랫폼, 멀티 코어 대응 • 기본적으로 Windows, PlayStation4, XBOX ONE 대응 • 멀티코어를 고려한 설계  Engine 규모 • 프로젝트 규모상 상용엔진 수준은 무리 • 필요한 기능만 최소한으로 제작중
  • 10. 방향성 Engine 소개  기능 • 최소한 지금까지 가능했던 일은 구현 가능하도록 설계 • 기존 엔진에서 불편했던 부분은 개선, 좋았던 부분은 채용, 가능하면 코드 재사용  차세대 대비 • 차세대를 준비하기 위한 최소한의 환경 구축
  • 11. 제작 이유 Engine 소개  기존 엔진의 문제점 • PlayStation2 시절의 낡은 설계 • 리소스 파이프라인에 불필요한 작업이 많았음 • 부족한 기능을 구현하기 위해 game에서 억지로 구현한 부분이 점차 많아지기 시작함 • 외부 엔진이라 대응이 늦거나 불가능한 일이 잦았음  콘솔 개발킷의 부족 • 기존 엔진 및 각종 툴이 콘솔기기에서 밖에 동작하지 않아 콘솔 개 발킷이 없으면 디버깅이 불가능 • Windows에서 개발하고 싶다는 요청이 많아짐
  • 12. 제작 이유 Engine 소개  내부 기술력 강화 • 외부 엔진만 사용해서는 노하우 쌓기가 쉽지 않다고 판단  차세대기로 갈아타기 위한 좋은 타이밍 • 차세대기 발매 • 하드웨어의 진화 • 지금까지의 설계로는 하드웨어의 스펙을 전부 활용하기 힘들어짐
  • 15. 구성 Engine 소개  기본적으로 C++라이브러리  콘솔 툴은 python이 많음  기타 툴은 C++, 일부는 C#검토중
  • 16. 구성 Engine 소개 Rendering Core Effect Animation Particle … 60% System Math Memory File Thread … 90% Tool Exporter Resource manager Parameter - Configuration … 20%
  • 17. Rendering Core Effect Animation Particle … 60% System Math Memory File Thread … 90% Tool Exporter Resource manager Parameter – Configuration … 20% 구성 Engine 소개 오늘의 주제
  • 18. Rendering Core Engine 소개  Multithread 대응 구조  각 플랫폼의 저레벨API 추상화 • 차후 대응 플랫폼 추가를 고려하여 설계  DirectX11 기반
  • 19. Contents  Engine 소개  이행시 주의점 • DirectX11 변경점 • Constant Buffer • VertexInputLayout • State Management • Multithread • Shader • Etc.  결론
  • 20. DirectX11변경점  고정 파이프라인 삭제  Device 분리  CAPS비트 삭제  새로운 shader stage 추가  Multithread Rendering  Dynamic Shader Linkage  Tesselation, OIT  BC6, BC7 texture format  Etc.
  • 21. DirectX11변경점  이 중 DirectX11 을 사용하여 rendering하기 위해 반드시 필 요한 부분을 DirectX9과 비교  독자적으로 대응한 방법에 대한 소개도 있습니다만 정답은 아니므로 어디까지나 참고
  • 22. Device 분리 DirectX11변경점  DirectX9의 IDirect3DDevice9 은 DirectX11에서부터 ID3D11Device 와 ID3D11DeviceContext 로 분리되었음  ID3D11Device은 주로 resource 생성을 담당 • thread-safe  ID3D11DeviceContext은 주로 rendering을 담당 • thread-unsafe  자료 소스코드 중 pDevice 는 IDirect3DDevice9, pImmediateContext 은 ID3D11DeviceContext 의 객체이므로 참고
  • 23. Contents  Engine 소개  이행시 주의점 • DirectX11 변경점 • Constant Buffer • VertexInputLayout • State Management • Multithread • Shader • Etc.  결론
  • 24. Constant Buffer? Constant Buffer  DirectX10부터 추가된 shader parameter 설정을 위한 버퍼  DirectX9에서는 개별적으로 설정했지만 DirectX11에서는 버 퍼 단위의 오브젝트로 변경  DirectX11에서 shader 에 값을 전달하기 위해 반드시 필요
  • 25. DirectX9 Constant Buffer  HLSL(sm3.0)까지의 shader 변수정의 • C++ global variable 처럼 정의 HLSL float3 g_vLightPos; float3 g_vLightDir; float4x4 g_mView; float4x4 g_mProj; float4x4 g_mWorld; float4x4 g_mBone[128]; float4 g_vMaterial;
  • 26. DirectX9 Constant Buffer  Parameter 전달 방법 • Set[datatype](“variable”, &data) float3 g_vLightPos; float3 g_vLightDir; float4x4 g_mView; float4x4 g_mProj; float4x4 g_mWorld; float4x4 g_mBone[128]; float4 g_vMaterial; Application SetVector("g_vLightPos",&lightPos); SetMatrix("g_mWorld",&worldMatrix); HLSL
  • 27. DirectX11 Constant Buffer  cbuffer키워드 안에 변수를 묶어서 정의. C언어의 구조체와 비슷 한 형태  선언 뒤에 바인드될 레지스터의 번호를 설정. 16번까지 설정 가 능 - 설정하지 않을 경우, 0번부터 차례대로 부여됨 cbuffer CB : register(b0) { float3 vLightPos; float3 vLightDir; float4x4 mView; float4x4 mProj; float4x4 mWorld; float4x4 mBone[128]; float4 vMaterial; }; HLSL
  • 28. DirectX11 Constant Buffer 1. CreateBuffer로 constant buffer용 버퍼 생성 2. UpdateSubresource(Map)로 버퍼의 내용을 update • 한번의 update로 constant buffer 내용 전부를 덮어씌우므로 주의 3. XXSetconstantBuffers로 레지스터에 바인드 ex) VSSetConstantBuffers, PSSetConstantBuffer 등
  • 29. 주의점 Constant Buffer  update 사이즈와 호출회수를 최대한으로 줄여야 함 • 성능 저하에 민감함  가장 실수하기 쉬운 부분 world matrix만 덮어씌워도 8424bytes update해야함 cbuffer CB : register(b0) { float3 vLightPos; float3 vLightDir; float4x4 mView; float4x4 mProj; float4x4 mWorld; float4x4 mBone[128]; float4 vMaterial; }; HLSL
  • 30. Constant Buffer  shader로 전달할 데이터 크기 이상의 constant buffer 를 update 하는 것은 잘못된 설계  필요한 부분만 update 할 수 있도록 constant buffer 를 나 누어 설계. update 빈도에 따라 나누길 추천  한 번 update 한 constant buffer는 최대한 돌려쓰거나 모아 서 rendering
  • 31. Constant Buffer Application HLSL Global cbuffer CB : register(b0) { float3 vLightPos; float3 vLightDir; float4x4 mView; float4x4 mProj; float4x4 mWorld; float4x4 mBone[128]; float4 vMaterial; }; Camera Object Material
  • 32. Constant Buffer Application HLSL Global Camera cbuffer CB : register(b0) { float3 vLightPos; float3 vLightDir; float4x4 mView; float4x4 mProj; float4x4 mWorld; float4x4 mBone[128]; float4 vMaterial; }; 8424bytes 25272bytes Object Material Material Material
  • 33. Constant Buffer Application HLSL cbuffer perGlobalCB : register(b0) { float3 vLightPos; float3 vLightDir; }; cbuffer perCameraCB : register(b1) { float4x4 mView; float4x4 mProj; }; cbuffer perObjectCB : register(b2) { float4x4 mWorld; float4x4 mBone[128]; }; cbuffer perMaterialCB : register(b3) { float4 vMaterial; }; 24bytes 128bytes 8256bytes 16bytes Global Camera Object Material Material Material 8456bytes
  • 34. Constant Buffer  처음부터 constant buffer의 update 빈도에 따라 sorting 하여 rendering 할 수 있도 록 설계 하는 것이 중요  내부 엔진에서는 다음의 4개 의 빈도로 나누어서 설계 - Global - Camera - Object - Material Global Camera Object Material Object Material Material Camera Object Material
  • 35. Contents  Engine 소개  이행시 주의점 • DirectX11 변경점 • Constant Buffer • VertexInputLayout • State Management • Multithread • Shader • Etc.  결론
  • 36. VertexInputLayout VertexInputLayout?  vertex buffer가 어떤 내용으로 구성되어 있는지 GPU에 알 려주기 위한 DirectX11 오브젝트  DirectX9의 IDirect3DVertexDeclaration9과 비슷
  • 37. VertexInputLayout vertex buffer 1.0f 1.0f 1.0f 1.0f 1.0f 1.0f 1.0f GPU ?
  • 38. DirectX9 VertexInputLayout position color vertex buffer 1.0f 1.0f 1.0f 1.0f 1.0f 1.0f 1.0f D3DVERTEXELEMENT9 decl[] = { { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, { 0, 12, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 0 }, D3DDECL_END() }; pd3dDevice->CreateVertexDeclaration(decl, &pVertexDeclaration); pd3dDevice->SetVertexDeclaration(pVertexDeclaration);
  • 39. DirectX11 VertexInputLayout position color vertex buffer 1.0f 1.0f 1.0f 1.0f 1.0f 1.0f 1.0f D3D11_INPUT_ELEMENT_DESC decl[] = { {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0}, {"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0}, }; UINT numElements = ARRAYSIZE( layout ); pd3dDevice->CreateInputLayout( decl, numElements, pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), &pVertexLayout ); pImmediateContext->IASetInputLayout( pVertexLayout );
  • 40. VertexInputLayout HRESULT CreateInputLayout( [in] const D3D11_INPUT_ELEMENT_DESC *pInputElementDescs, [in] UINT NumElements, [in] const void *pShaderBytecodeWithInputSignature, [in] SIZE_T BytecodeLength, [out] ID3D11InputLayout **ppInputLayout ); pShaderBytecodeWithInputSignature [in] void A pointer to the compiled shader. The compiled shader code contains a input signature which is validated against the array of elements. BytecodeLength [in] SIZE_T Size of the compiled shader.
  • 41. VertexInputLayout  CreateInputLayout 에서 D3D11_INPUT_ELEMENT_DESC 과 vertex shader semantic 의 매칭이 이루어짐  구조가 일치할 경우 success, 불일치할 경우 fail
  • 42. VertexInputLayout vertex buffer position color CreateInputLayout 성공 D3D11_INPUT_ELEMENT_DESC decl[] = { {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0}, {"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0}, }; struct VS_INPUT { float3 position : POSITION; float4 color : COLOR0; }; HLSL
  • 43. VertexInputLayout CreateInputLayout 실패 vertex buffer position color D3D11_INPUT_ELEMENT_DESC decl[] = { {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0}, {"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0}, }; struct VS_INPUT { float3 position : POSITION; float3 normal : NORMAL; }; HLSL
  • 44. VertexInputLayout vertex buffer 1.0f 1.0f 1.0f 1.0f 1.0f 1.0f 1.0f D3D11_INPUT_ELEMENT_DESC decl[] = { {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0}, {"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0}, }; UINT numElements = ARRAYSIZE( layout ); pd3dDevice->CreateInputLayout( decl, numElements, pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), &pVertexLayout ); pImmediateContext->IASetInputLayout( pVertexLayout ); struct VS_INPUT { float3 position : POSITION; float4 color : COLOR0; }; HLSL position color
  • 45. VertexInputLayout  vertex buffer 의 구성을 알고 있어도 같은 구성의 semantic 을 가지고 있는 vertex shader를 컴파일 하지 않으면 VertexInputLayout 생성이 불가능  vertex buffer 의 구성만으로 생성이 가능 했던 DirectX9에 비해 엄격해졌음
  • 46. VertexInputLayout  vertex buffer 와 vertex shader semantic 의 binding이 결정 된 시점에 VertexInputLayout 동적생성 한번 생성된 객체는 vertex buffer 와 vertex shader semantic 을 key로 가지는 hash table 관리 ⇒ 동적 생성, hash table 검색이 느리고, rendering 할때마 다 체크하지 않으면 안되기 때문에 비효율적
  • 47. VertexInputLayout  DirectX11에서는 shader reflection기능이 대폭 강화됨 • semantic 의 type, num, offset 이외에도 constant buffer 의 name, variable type 등 대부분의 정보를 프로그램에서 얻어 낼 수 있음  vertex shader를 reflection하여 semantic과 일치하는 VertexInputLayout를 미리 생성. 즉, vertex buffer 기준이 아 닌 shader semantic기준으로VertexInputLayout를 생성
  • 48. VertexInputLayout HLSL struct VS_INPUT { float3 position : POSITION; float4 color : COLOR0; }; shader reflection D3D11_INPUT_ELEMENT_DESC decl[] = { vertex buffer position color {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0}, {"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0}, }; UINT numElements = ARRAYSIZE( layout ); pd3dDevice->CreateInputLayout( decl, numElements, pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), &pVertexLayout ); pImmediateContext->IASetInputLayout( pVertexLayout );
  • 49. VertexInputLayout  vertex buffer 와 상관없이 미리 VertexInputLayout 을 생성하기 때문에 vertex buffer 와의 불일치가 발생하는 경우가 있음 VertexInputLayout vertex buffer position color 문제 없음 assert normal position normal color position normal position normal color assert ? position normal color position color
  • 50. VertexInputLayout  vertex buffer 가 GPU에 binding될 때 VertexInputLayout 정보를 참조하여 필요한 semantic 만 binding VertexInputLayout position color vertex buffer position normal color GPU
  • 51. VertexInputLayout vertex buffer binding  vertex buffer 를 나누어 생성 GPU 1.0f 1.0f 1.0f normal 1.0f 1.0f 1.0f 1.0f 1.0f 1.0f 1.0f position color UINT posStride = sizeof(float)*3; UINT posOffset = 0; pImmediateContext->IASetVertexBuffers( 0, 1, &posVB, &posStride, &posOffset ); UINT colorStride = sizeof(float)*4; UINT colorOffset = 0; pImmediateContext->IASetVertexBuffers( 1, 1, &colorVB, &colorStride, &colorOffset );
  • 52. VertexInputLayout vertex buffer binding  stride와 offset을 적절히 설정하여 binding position normal color vertex buffer 1.0f 1.0f 1.0f 1.0f 1.0f 1.0f 1.0f 1.0f 1.0f 1.0f GPU UINT posStride = sizeof(float)*3; UINT posOffset = 0; pImmediateContext->IASetVertexBuffers( 0, 1, &VB, &posStride, &posOffset ); UINT colorStride = sizeof(float)*4; UINT colorOffset = 24; pImmediateContext->IASetVertexBuffers( 1, 1, &VB, &colorStride, &colorOffset );
  • 53. Contents  Engine 소개  이행시 주의점 • DirectX11 변경점 • Constant Buffer • VertexInputLayout • State Management • Multithread • Shader • Etc.  결론
  • 54. DirectX9 State Management  개별적으로 설정  한번 설정된 값은 변경하지 않는 이상 지속됨 pDevice->SetRenderState( D3DRS_ZENABLE, D3DZB_TRUE ); Render(); // z enable – On pDevice->SetRenderState( D3DRS_ZWRITEENABLE, FALSE ); Render(); // z enable – On, z write - Off
  • 55. DirectX11 State Management  CreateXXXState 함수로 생성하며 오브젝트로 변경됨  개별 설정 불가능. 오브젝트 단위로 설정  state를 변경하는 경우 오브젝트를 재생성할 필요가 있음  texture sampler도 render state와 동일한 설계로 변경됨
  • 56. DirectX11 State Management data create set Rasterizer D3D11_RASTERIZER_DESC CreateRasterizerState RSSetState Blend D3D11_BLEND_DESC CreateBlendState OMSetBlendState DepthStencil D3D11_DEPTH_STENCIL_DESC CreateDepthStencilState OMSetDepthStencilState
  • 57. DirectX11 State Management  생성 예 D3D11_DEPTH_STENCIL_DESC desc; ZeroMemory( &desc, sizeof( D3D11_DEPTH_STENCIL_DESC ) ); desc.DepthEnable = TRUE; desc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; desc.DepthFunc = D3D11_COMPARISON_LESS; desc.StencilEnable = FALSE; /* set desc.... */ ID3D11DepthStencilState* depthStencilState = NULL; pDevice->CreateDepthStencilState(&desc, &depthStencilState); pImmediateContext->OMSetDepthStencilState( depthStencilState );
  • 58. DirectX11 State Management  변경 예 1. z enable – on 2. z enable – on, z write – off pDevice->SetRenderState( D3DRS_ZENABLE, D3DZB_TRUE ); Render(); // z enable – On pDevice->SetRenderState( D3DRS_ZWRITEENABLE, FALSE ); Render(); // z enable – On, z write - Off
  • 59. DirectX11 State Management ID3D11DepthStencilState* depthStencilState = NULL; D3D11_DEPTH_STENCIL_DESC desc; desc.DepthEnable = TRUE; desc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; /* set desc.... */ device->CreateDepthStencilState(&desc, &depthStencilState); pImmediateContext->OMSetDepthStencilState( depthStencilState ); Render(); // z enable – On SAFE_RELEASE( depthStencilState ); desc.DepthEnable = TRUE; desc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ZERO; /* set desc.... */ pDevice->CreateDepthStencilState(&desc, &depthStencilState); pImmediateContext->OMSetDepthStencilState( depthStencilState ); Render(); // z enable – On, z write - Off
  • 60. State Management  DirectX9 처럼 global render state 에 모든 설정을 한 후, rendering 직 전에 오브젝트 생성 ⇒ 동적생성으로 인한 속도저하, multithread 대응 불가능, release 타이 밍을 잡기 쉽지 않음  사전에 사용될 가능성이 있는 render state를 전부 미리 생성해 둠 ⇒ program에서 동적으로 생성되는 타입의 render state에 대응하기 쉽 지 않음 ex) wireframe, blend 등
  • 61. State Management  DirectX11은 한번 생성되었던 render state 오브젝트를 내부적으로 관리 하고 있음  2번째 생성하는 경우에 이전에 생성된 render state 오브젝트의 reference count를 올리고 해당 오브젝트의 pointer를 반환함  즉, 한번 생성된 오브젝트를 해제하지 않고 놔두면 2번째 부터는 고속으 로 생성 가능
  • 62. State Management  한번 생성된 render state는 해제하지 않고 stl set 에 저장. 2번째 같은 오브젝트가 생성된 경우 reference count를 1로 유지하기 위해 Release호출 Create - solid Create – wireframe solid 1 solid 1 wireframe 1 render state count render state count
  • 63. State Management Create – alpha solid wireframe 1 1 alpha 1 Create – wireframe solid wireframe 1 2 alpha 1 solid wireframe 1 1 alpha 1 Release render state count render state count render state count
  • 64. State Management  차후 CreateXXXState 하기 위한 copy연산을 줄이기 위해 render state parameter를 hash key로 관리하는 시스템 도입 검토중 D3D11_DEPTH_STENCIL_DESC desc; ZeroMemory( &desc, sizeof( D3D11_DEPTH_STENCIL_DESC ) ); desc.DepthEnable = EngineToDX11(ENGINE_DEPTH_ON); desc.DepthWriteMask = EngineToDX11(ENGINE_ZWRITE_ON); desc.DepthFunc = EngineToDX11(ENGINE_COMPARISON_LESS); desc.StencilEnable = EngineToDX11(ENGINE_STENCIL_ON); /* set desc.... */
  • 65. Contents  Engine 소개  이행시 주의점 • DirectX11 변경점 • Constant Buffer • VertexInputLayout • State Management • Multithread • Shader • Etc.  결론
  • 66. Multithread  코어수의 증가와 더불어, 멀티코어 대응 프로그래밍은 선택 이 아닌 필수!
  • 69. ID3D11DeviceContext Multithread  immediate context • rendering 명령을 실행하는 오브젝트 • 1개만 생성 가능하며 thread unsafe  deferred context • immediate context의 multithread 대응 오브젝트. 여러 개 생성 가능 하며 각 thread 에서 rendering 명령을 실행 • immediate context와 사용가능한 함수는 완전 일치 • 각 thread에서 모든 rendering 명령의 실행이 끝난 후에 FinishCommandList 를 호출하여 command list 를 얻어옴. 이후 command list를 immediate context 에서 실행
  • 70. Deferred Context Multithread 1. 생성 ID3D11DeviceContext* pImmediateContext; ID3D11DeviceContext* pDeferredContext; /* pImmediateContext생성 후 */ pDevice->CreateDeferredContext( 0, &pDeferredContext ); 2. 각 thread 마지막에 실행 /* pDeferredContext를 이용한 rendering 완료후 */ pDeferredContext->FinishCommandList( FALSE, &pCommandList ); 3. immediate context에서 command list 실행 pImmediateContext->ExecuteCommandList( pCommandList, FALSE );
  • 72. Draw Command Multithread  내부 엔진에서는 중간 단계 rendering command 를 자체적 으로 구현  모든 command 에는 priority 를 붙여서 생성  각 thread에서 생성된 command 를 sorting 한 후 rendering thread 에 전달  rendering thread에서 각각의 command를 merge sort 한 후 이를 순차적으로 실행
  • 73. Multithread Draw Command Secondary thread#1 60 SetShader 61 BindBuffer 10 Clear 60 SetShader 61 BindBuffer Secondary thread#2 Secondary thread#3 10 Clear 50 SetRenderState 21 SetRenderState 22 SetShader 21 SetRenderState 22 SetShader 50 SetRenderState 40 Clear 30 RenderPolygon 23 BindTexture 23 BindTexture 30 RenderPolygon 40 Clear
  • 74. Multithread Draw Command Render thread 10 Clear 60 SetShader 10 Clear 21 SetRenderState 22 SetShader 21 SetRenderState 22 SetShader 23 BindTexture 30 RenderPolygon 40 Clear 23 BindTexture 30 RenderPolygon 50 SetRenderState 60 SetShader 61 BindBuffer 61 BindBuffer 50 SetRenderState 40 Clear
  • 75. Draw Command Multithread  장점 • priority를 이용해 유연성있게 rendering 순서를 조절 가능 • Graphics API에서 multithread를 대응하지 않는 경우 대응이 쉬움 • Draw Command의 기록을 남겨 replay나 디버깅에 활용  단점 • Graphics API단에서의 병렬화가 아니므로, 일부 명령어는 병렬화 되 지 않을 가능성이 있음
  • 76. Multithread  처음부터 multithread를 고려하여 설계하는 것이 중요 • Single-thread기준으로 작성된 프로젝트를 multithread 구조로 변경 하기 매우 힘듦  Multithread를 고려하지 않으면 속도 올리기가 쉽지 않음  하드웨어의 스펙을 100% 활용합시다!
  • 77. Contents  Engine 소개  이행시 주의점 • DirectX11 변경점 • Constant Buffer • VertexInputLayout • State Management • Multithread • Shader • Etc.  결론
  • 78. shader model Shader  DirectX9 – 1.0, 2.0, 3.0  DirectX10 – 4.0, 4.1  DirectX11 – 5.0
  • 79. constant buffer Shader  program에서 값을 받을 필요가 있는 parameter는 constant buffer로 정의 cbuffer perGlobalCB : register(b0) { float3 vLightPos; float3 vLightDir; }; cbuffer perCameraCB : register(b1) { float4x4 mView; float4x4 mProj; }; cbuffer perObjectCB : register(b2) { float4x4 mWorld; float4x4 mBone[128]; }; cbuffer perMaterialCB : register(b3) { float4 vMaterial; }; float3 g_vLightPos; float3 g_vLightDir; float4x4 g_mView; float4x4 g_mProj; float4x4 g_mWorld; float4x4 g_mBone[128]; float4 g_vMaterial;
  • 80. Texture, Sampler 의 Binding Shader  DirectX9에서는 sampler선언 시에 binding texture g_texture; sampler2D g_sampler = sampler_state { Texture = <g_texture>; MinFilter = Point; MagFilter = Linear; MipFilter = Linear; }; float4 PS( PS_INPUT input ) : COLOR { return tex2D( g_sampler, input.texCoord ); }
  • 81. Texture, Sampler 의 Binding Shader  DirectX11에서는 sampling 함수를 호출하는 시점에 binding texture2D g_texture; SamplerState g_sampler; float4 PS( PS_INPUT input ) : SV_Target { return g_texture.Sample( g_sampler, input.texCoord ); }
  • 82. Sampler 정의 Shader  DirectX11의 경우, shader에 적힌 sampler 속성은 effect를 사용 하지 않는 한 적용되지 않으므로 주의  effect를 사용하지 않는 경우는 프로그램에서 설정 DirectX9 sampler2D g_sampler = sampler_state { Texture = <g_texture>; MinFilter = Point; MagFilter = Linear; MipFilter = Linear; }; SamplerState g_sampler { Filter = MIN_MAG_MIP_LINEAR; }; DirectX11
  • 83. Effect Shader  shader 설정, render state의 정의하는 방법이 변경 되었으 니 주의 BlendState NoBlend { BlendEnbale[0] = False; }; DepthStencilState DepthTestOn { DepthEnable = True; DepthWriteMask = All; DepthFunc = LESS; }; RasterizerState rsWireframe { FillMode = Solid; CullMode = Back; FrontCounterClockwise = False; }; VertexShader vs_main = CompileShader( vs_5_0, VS() ); PixelShader ps_main = CompileShader( ps_5_0, PS() ); technique11 t0 { pass p0 { SetBlendState( NoBlend, float4(0.0f,0.0f,0.0f,0.0f), 0xFFFFFFFF ); SetDepthStencilState( DepthTestOn, 0 ); SetRasterizerState( rsWireframe ); SetVertexShader( vs_main ); SetGeometryShader( NULL ); SetPixelShader( ps_main ); } }
  • 85. Contents  Engine 소개  이행시 주의점 • DirectX11 변경점 • Constant Buffer • VertexInputLayout • State Management • Multithread • Shader • Etc.  결론
  • 86. Texture Array Etc.  다수의 texture를 한번에 shader로 전달하는 것이 가능해짐  Texture이외의 material parameter가 같은 경우, texture 변경 없이 한번 에 rendering 할 수 있음  리소스 파이프라인 변경 없이 texture atlas의 효과를 얻을 수 있음
  • 87. Format Etc.  D3DFMT_XXX가 DXGI_FORMAT_XXX로 변경  D3DFMT_XXX에서 추가, 변경, 삭제 된 포맷이 있 으므로 주의  지원되지 않는 포맷을 리소스에서 사용하고 있는 경우 차후 문제가 생길 여지가 있으므로 주의
  • 88. Primitive Etc.  D3DPT_TRIANGLEFAN가 삭제됨  프로그램에서 geometry를 생성하는 타입은 소스코드 수정  리소스에서 사용되는 경우 지원되는 primitive 포맷으로 export를 다시 하거나 로딩 시에 변환
  • 89. Contents  Engine 소개  이행시 주의점 • DirectX11 변경점 • Constant Buffer • VertexInputLayout • State Management • Multithread • Shader • Etc.  결론
  • 90. 결론  DirectX11 은 DirectX9 과 비교하여 많은 점이 변경 되었음. 기존 엔진&라이브러리를 이식하는 경우 생각보다 쉽지 않 음  단, 그만큼 차세대에 어울리는 설계가 되어 있으므로, application에서도 graphics API를 이해하고 그 성능을 십 분 활용할 수 있는 설계가 필요함
  • 92. WE’RE HIRING 결론  엔지니어 채용중  inq_rec@cc2.co.jp
  • 93. 결론  References • Game fest2007 : Windows to Reality: Getting the Most out of Direct3D 10 Graphics in Your Games • GDC 2013 : D3D11 Deferred Contexts • CEDEC 2006 : 次世代機に向けたゲームエンジンの設計 • GDC 2011 : DX11 Performance Gems • CEDEC 2014 : 「世代間マルチプラットフォーム平行開発」~PlayStation4版「龍が如く維新!」開発の一年~ • http://msdn.microsoft.com/ko-kr/library/windows/apps/bb943991.aspx#File_Layout1 • http://msdn.microsoft.com/ko-kr/library/windows/desktop/ff476892%28v=vs.85%29.aspx • http://msdn.microsoft.com/en-us/library/windows/desktop/ff471376%28v=vs.85%29.aspx • http://www.gamedev.net/topic/542778-samplerstate-within-shader-snt-working-in-d3d10/ • http://en.wikipedia.org/wiki/High-level_shader_language • http://msdn.microsoft.com/en-us/library/windows/desktop/hh404586%28v=vs.85%29.aspx  Images • http://btoのパソコン.com/mametisiki/cpu.php • http://www.virtuaniz.com/2013/12/playstation-4-vs-playstation-3-heres-the-comparison-is-ps4-worth-buying-or-sit-back-with-ps3/ • http://prohardver.hu/tudastar/direct3d_deferred_context.html • http://lukasz.dk/2011/04/18/texture-atlas-generator/ • http://www.codesampler.com/d3dbook/chapter_05/chapter_05.htm • http://volkansahin.net/oyunlarda-grafik/