-
Notifications
You must be signed in to change notification settings - Fork 104
Expand file tree
/
Copy pathTutorial03_Texturing.cpp
More file actions
355 lines (303 loc) · 13.9 KB
/
Copy pathTutorial03_Texturing.cpp
File metadata and controls
355 lines (303 loc) · 13.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
/*
* Copyright 2019-2025 Diligent Graphics LLC
* Copyright 2015-2019 Egor Yusov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* In no event and under no legal theory, whether in tort (including negligence),
* contract, or otherwise, unless required by applicable law (such as deliberate
* and grossly negligent acts) or agreed to in writing, shall any Contributor be
* liable for any damages, including any direct, indirect, special, incidental,
* or consequential damages of any character arising as a result of this License or
* out of the use or inability to use the software (including but not limited to damages
* for loss of goodwill, work stoppage, computer failure or malfunction, or any and
* all other commercial damages or losses), even if such Contributor has been advised
* of the possibility of such damages.
*/
#include "Tutorial03_Texturing.hpp"
#include "MapHelper.hpp"
#include "GraphicsUtilities.h"
#include "TextureUtilities.h"
#include "ColorConversion.h"
namespace Diligent
{
SampleBase* CreateSample()
{
return new Tutorial03_Texturing();
}
void Tutorial03_Texturing::CreatePipelineState()
{
// Pipeline state object encompasses configuration of all GPU stages
GraphicsPipelineStateCreateInfo PSOCreateInfo;
// Pipeline state name is used by the engine to report issues.
// It is always a good idea to give objects descriptive names.
PSOCreateInfo.PSODesc.Name = "Cube PSO";
// This is a graphics pipeline
PSOCreateInfo.PSODesc.PipelineType = PIPELINE_TYPE_GRAPHICS;
// clang-format off
// This tutorial will render to a single render target
PSOCreateInfo.GraphicsPipeline.NumRenderTargets = 1;
// Set render target format which is the format of the swap chain's color buffer
PSOCreateInfo.GraphicsPipeline.RTVFormats[0] = m_pSwapChain->GetDesc().ColorBufferFormat;
// Set depth buffer format which is the format of the swap chain's back buffer
PSOCreateInfo.GraphicsPipeline.DSVFormat = m_pSwapChain->GetDesc().DepthBufferFormat;
// Primitive topology defines what kind of primitives will be rendered by this pipeline state
PSOCreateInfo.GraphicsPipeline.PrimitiveTopology = PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
// Cull back faces
PSOCreateInfo.GraphicsPipeline.RasterizerDesc.CullMode = CULL_MODE_BACK;
// Enable depth testing
PSOCreateInfo.GraphicsPipeline.DepthStencilDesc.DepthEnable = True;
// clang-format on
ShaderCreateInfo ShaderCI;
// Tell the system that the shader source code is in HLSL.
// For OpenGL, the engine will convert this into GLSL under the hood.
ShaderCI.SourceLanguage = SHADER_SOURCE_LANGUAGE_HLSL;
// OpenGL backend requires emulated combined HLSL texture samplers (g_Texture + g_Texture_sampler combination)
ShaderCI.Desc.UseCombinedTextureSamplers = true;
// Pack matrices in row-major order
ShaderCI.CompileFlags = SHADER_COMPILE_FLAG_PACK_MATRIX_ROW_MAJOR;
// Presentation engine always expects input in gamma space. Normally, pixel shader output is
// converted from linear to gamma space by the GPU. However, some platforms (e.g. Android in GLES mode,
// or Emscripten in WebGL mode) do not support gamma-correction. In this case the application
// has to do the conversion manually.
ShaderMacro Macros[] = {{"CONVERT_PS_OUTPUT_TO_GAMMA", m_ConvertPSOutputToGamma ? "1" : "0"}};
ShaderCI.Macros = {Macros, _countof(Macros)};
// Create a shader source stream factory to load shaders from files.
RefCntAutoPtr<IShaderSourceInputStreamFactory> pShaderSourceFactory;
m_pEngineFactory->CreateDefaultShaderSourceStreamFactory(nullptr, &pShaderSourceFactory);
ShaderCI.pShaderSourceStreamFactory = pShaderSourceFactory;
// Create a vertex shader
RefCntAutoPtr<IShader> pVS;
{
ShaderCI.Desc.ShaderType = SHADER_TYPE_VERTEX;
ShaderCI.EntryPoint = "main";
ShaderCI.Desc.Name = "Cube VS";
ShaderCI.FilePath = "cube.vsh";
m_pDevice->CreateShader(ShaderCI, &pVS);
// Create dynamic uniform buffer that will store our transformation matrix
// Dynamic buffers can be frequently updated by the CPU
CreateUniformBuffer(m_pDevice, sizeof(float4x4), "VS constants CB", &m_VSConstants);
}
// Create a pixel shader
RefCntAutoPtr<IShader> pPS;
{
ShaderCI.Desc.ShaderType = SHADER_TYPE_PIXEL;
ShaderCI.EntryPoint = "main";
ShaderCI.Desc.Name = "Cube PS";
ShaderCI.FilePath = "cube.psh";
m_pDevice->CreateShader(ShaderCI, &pPS);
}
// clang-format off
// Define vertex shader input layout
LayoutElement LayoutElems[] =
{
// Attribute 0 - vertex position
LayoutElement{0, 0, 3, VT_FLOAT32, False},
// Attribute 1 - texture coordinates
LayoutElement{1, 0, 2, VT_FLOAT32, False}
};
// clang-format on
PSOCreateInfo.pVS = pVS;
PSOCreateInfo.pPS = pPS;
PSOCreateInfo.GraphicsPipeline.InputLayout.LayoutElements = LayoutElems;
PSOCreateInfo.GraphicsPipeline.InputLayout.NumElements = _countof(LayoutElems);
// Define variable type that will be used by default
PSOCreateInfo.PSODesc.ResourceLayout.DefaultVariableType = SHADER_RESOURCE_VARIABLE_TYPE_STATIC;
// clang-format off
// Shader variables should typically be mutable, which means they are expected
// to change on a per-instance basis
ShaderResourceVariableDesc Vars[] =
{
{SHADER_TYPE_PIXEL, "g_Texture", SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE}
};
// clang-format on
PSOCreateInfo.PSODesc.ResourceLayout.Variables = Vars;
PSOCreateInfo.PSODesc.ResourceLayout.NumVariables = _countof(Vars);
// clang-format off
// Define immutable sampler for g_Texture. Immutable samplers should be used whenever possible
SamplerDesc SamLinearClampDesc
{
FILTER_TYPE_LINEAR, FILTER_TYPE_LINEAR, FILTER_TYPE_LINEAR,
TEXTURE_ADDRESS_CLAMP, TEXTURE_ADDRESS_CLAMP, TEXTURE_ADDRESS_CLAMP
};
ImmutableSamplerDesc ImtblSamplers[] =
{
{SHADER_TYPE_PIXEL, "g_Texture", SamLinearClampDesc}
};
// clang-format on
PSOCreateInfo.PSODesc.ResourceLayout.ImmutableSamplers = ImtblSamplers;
PSOCreateInfo.PSODesc.ResourceLayout.NumImmutableSamplers = _countof(ImtblSamplers);
m_pDevice->CreateGraphicsPipelineState(PSOCreateInfo, &m_pPSO);
// Since we did not explicitly specify the type for 'Constants' variable, default
// type (SHADER_RESOURCE_VARIABLE_TYPE_STATIC) will be used. Static variables
// never change and are bound directly through the pipeline state object.
m_pPSO->GetStaticVariableByName(SHADER_TYPE_VERTEX, "Constants")->Set(m_VSConstants);
// Since we are using mutable variable, we must create a shader resource binding object
// http://diligentgraphics.com/2016/03/23/resource-binding-model-in-diligent-engine-2-0/
m_pPSO->CreateShaderResourceBinding(&m_SRB, true);
}
void Tutorial03_Texturing::CreateVertexBuffer()
{
// Layout of this structure matches the one we defined in the pipeline state
struct Vertex
{
float3 pos;
float2 uv;
};
// Cube vertices
// (-1,+1,+1)________________(+1,+1,+1)
// /| /|
// / | / |
// / | / |
// / | / |
//(-1,-1,+1) /____|__________/(+1,-1,+1)
// | |__________|____|
// | /(-1,+1,-1) | /(+1,+1,-1)
// | / | /
// | / | /
// |/ | /
// /_______________|/
// (-1,-1,-1) (+1,-1,-1)
//
// This time we have to duplicate verices because texture coordinates cannot
// be shared
constexpr Vertex CubeVerts[] =
{
{float3{-1, -1, -1}, float2{0, 1}},
{float3{-1, +1, -1}, float2{0, 0}},
{float3{+1, +1, -1}, float2{1, 0}},
{float3{+1, -1, -1}, float2{1, 1}},
{float3{-1, -1, -1}, float2{0, 1}},
{float3{-1, -1, +1}, float2{0, 0}},
{float3{+1, -1, +1}, float2{1, 0}},
{float3{+1, -1, -1}, float2{1, 1}},
{float3{+1, -1, -1}, float2{0, 1}},
{float3{+1, -1, +1}, float2{1, 1}},
{float3{+1, +1, +1}, float2{1, 0}},
{float3{+1, +1, -1}, float2{0, 0}},
{float3{+1, +1, -1}, float2{0, 1}},
{float3{+1, +1, +1}, float2{0, 0}},
{float3{-1, +1, +1}, float2{1, 0}},
{float3{-1, +1, -1}, float2{1, 1}},
{float3{-1, +1, -1}, float2{1, 0}},
{float3{-1, +1, +1}, float2{0, 0}},
{float3{-1, -1, +1}, float2{0, 1}},
{float3{-1, -1, -1}, float2{1, 1}},
{float3{-1, -1, +1}, float2{1, 1}},
{float3{+1, -1, +1}, float2{0, 1}},
{float3{+1, +1, +1}, float2{0, 0}},
{float3{-1, +1, +1}, float2{1, 0}},
};
BufferDesc VertBuffDesc;
VertBuffDesc.Name = "Cube vertex buffer";
VertBuffDesc.Usage = USAGE_IMMUTABLE;
VertBuffDesc.BindFlags = BIND_VERTEX_BUFFER;
VertBuffDesc.Size = sizeof(CubeVerts);
BufferData VBData;
VBData.pData = CubeVerts;
VBData.DataSize = sizeof(CubeVerts);
m_pDevice->CreateBuffer(VertBuffDesc, &VBData, &m_CubeVertexBuffer);
}
void Tutorial03_Texturing::CreateIndexBuffer()
{
// clang-format off
constexpr Uint32 Indices[] =
{
2,0,1, 2,3,0,
4,6,5, 4,7,6,
8,10,9, 8,11,10,
12,14,13, 12,15,14,
16,18,17, 16,19,18,
20,21,22, 20,22,23
};
// clang-format on
BufferDesc IndBuffDesc;
IndBuffDesc.Name = "Cube index buffer";
IndBuffDesc.Usage = USAGE_IMMUTABLE;
IndBuffDesc.BindFlags = BIND_INDEX_BUFFER;
IndBuffDesc.Size = sizeof(Indices);
BufferData IBData;
IBData.pData = Indices;
IBData.DataSize = sizeof(Indices);
m_pDevice->CreateBuffer(IndBuffDesc, &IBData, &m_CubeIndexBuffer);
}
void Tutorial03_Texturing::LoadTexture()
{
TextureLoadInfo loadInfo;
loadInfo.IsSRGB = true;
RefCntAutoPtr<ITexture> Tex;
CreateTextureFromFile("DGLogo.png", loadInfo, m_pDevice, &Tex);
// Get shader resource view from the texture
m_TextureSRV = Tex->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE);
// Set texture SRV in the SRB
m_SRB->GetVariableByName(SHADER_TYPE_PIXEL, "g_Texture")->Set(m_TextureSRV);
}
void Tutorial03_Texturing::Initialize(const SampleInitInfo& InitInfo)
{
SampleBase::Initialize(InitInfo);
CreatePipelineState();
CreateVertexBuffer();
CreateIndexBuffer();
LoadTexture();
}
// Render a frame
void Tutorial03_Texturing::Render()
{
ITextureView* pRTV = m_pSwapChain->GetCurrentBackBufferRTV();
ITextureView* pDSV = m_pSwapChain->GetDepthBufferDSV();
// Clear the back buffer
float4 ClearColor = {0.350f, 0.350f, 0.350f, 1.0f};
if (m_ConvertPSOutputToGamma)
{
// If manual gamma correction is required, we need to clear the render target with sRGB color
ClearColor = LinearToSRGB(ClearColor);
}
m_pImmediateContext->ClearRenderTarget(pRTV, ClearColor.Data(), RESOURCE_STATE_TRANSITION_MODE_TRANSITION);
m_pImmediateContext->ClearDepthStencil(pDSV, CLEAR_DEPTH_FLAG, 1.f, 0, RESOURCE_STATE_TRANSITION_MODE_TRANSITION);
{
// Map the buffer and write current world-view-projection matrix
MapHelper<float4x4> CBConstants(m_pImmediateContext, m_VSConstants, MAP_WRITE, MAP_FLAG_DISCARD);
*CBConstants = m_WorldViewProjMatrix;
}
// Bind vertex and index buffers
const Uint64 offset = 0;
IBuffer* pBuffs[] = {m_CubeVertexBuffer};
m_pImmediateContext->SetVertexBuffers(0, 1, pBuffs, &offset, RESOURCE_STATE_TRANSITION_MODE_TRANSITION, SET_VERTEX_BUFFERS_FLAG_RESET);
m_pImmediateContext->SetIndexBuffer(m_CubeIndexBuffer, 0, RESOURCE_STATE_TRANSITION_MODE_TRANSITION);
// Set the pipeline state
m_pImmediateContext->SetPipelineState(m_pPSO);
// Commit shader resources. RESOURCE_STATE_TRANSITION_MODE_TRANSITION mode
// makes sure that resources are transitioned to required states.
m_pImmediateContext->CommitShaderResources(m_SRB, RESOURCE_STATE_TRANSITION_MODE_TRANSITION);
DrawIndexedAttribs DrawAttrs; // This is an indexed draw call
DrawAttrs.IndexType = VT_UINT32; // Index type
DrawAttrs.NumIndices = 36;
// Verify the state of vertex and index buffers
DrawAttrs.Flags = DRAW_FLAG_VERIFY_ALL;
m_pImmediateContext->DrawIndexed(DrawAttrs);
}
void Tutorial03_Texturing::Update(double CurrTime, double ElapsedTime, bool DoUpdateUI)
{
SampleBase::Update(CurrTime, ElapsedTime, DoUpdateUI);
// Apply rotation
float4x4 CubeModelTransform = float4x4::RotationY(static_cast<float>(CurrTime) * 1.0f) * float4x4::RotationX(-PI_F * 0.1f);
// Camera is at (0, 0, -5) looking along the Z axis
float4x4 View = float4x4::Translation(0.f, 0.0f, 5.0f);
// Get pretransform matrix that rotates the scene according the surface orientation
float4x4 SrfPreTransform = GetSurfacePretransformMatrix(float3{0, 0, 1});
// Get projection matrix adjusted to the current screen orientation
float4x4 Proj = GetAdjustedProjectionMatrix(PI_F / 4.0f, 0.1f, 100.f);
// Compute world-view-projection matrix
m_WorldViewProjMatrix = CubeModelTransform * View * SrfPreTransform * Proj;
}
} // namespace Diligent