forked from LukasBanana/LLGL
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExample.cpp
More file actions
385 lines (324 loc) · 14.9 KB
/
Example.cpp
File metadata and controls
385 lines (324 loc) · 14.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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
/*
* Example.cpp (Example_ShadowMapping)
*
* This file is part of the "LLGL" project (Copyright (c) 2015-2019 by Lukas Hermanns)
* See "LICENSE.txt" for license information.
*/
#include <ExampleBase.h>
class Example_ShadowMapping : public ExampleBase
{
LLGL::Shader* vsShadowMap = nullptr;
LLGL::Shader* vsScene = nullptr;
LLGL::Shader* fsScene = nullptr;
LLGL::PipelineLayout* pipelineLayoutShadowMap = nullptr;
LLGL::PipelineLayout* pipelineLayoutScene = nullptr;
LLGL::PipelineState* pipelineShadowMap = {};
LLGL::PipelineState* pipelineScene = {};
LLGL::ResourceHeap* resourceHeapShadowMap = {};
LLGL::ResourceHeap* resourceHeapScene = {};
LLGL::Buffer* vertexBuffer = nullptr;
LLGL::Buffer* constantBuffer = nullptr;
LLGL::Texture* shadowMap = nullptr;
LLGL::Sampler* shadowMapSampler = nullptr;
const LLGL::Extent2D shadowMapResolution = { 256, 256 };
LLGL::RenderTarget* shadowMapRenderTarget = nullptr;
std::vector<TriangleMesh> meshes;
Gs::Vector3f boxPosition = { 0, 0, 0 };
float viewDistanceToBox = 1.25f;
Gs::Vector2f viewRotation;
float spotLightAngle = 35.0f;
Gs::Vector3f lightOffset = { 0, 1.5f, 0 };
struct Settings
{
Gs::Matrix4f wMatrix;
Gs::Matrix4f vpMatrix;
Gs::Matrix4f vpShadowMatrix;
Gs::Vector3f lightDir = Gs::Vector3f(-0.25f, -1.0f, 0.5f).Normalized();
float _pad1;
LLGL::ColorRGBAf diffuse = { 1.0f, 1.0f, 1.0f, 1.0f };
}
settings;
public:
Example_ShadowMapping() :
ExampleBase { L"LLGL Example: ShadowMapping" }
{
// Create all graphics objects
CreateShadowMap();
auto vertexFormat = CreateBuffers();
LoadShaders(vertexFormat);
CreatePipelineLayouts();
CreatePipelines();
CreateResourceHeaps();
// Label objects for debugging
swapChain->SetName("BackBuffer");
vertexBuffer->SetName("Buffer.Vertices");
constantBuffer->SetName("Buffer.Constants");
vsShadowMap->SetName("ShadowMap.VertexShader");
vsScene->SetName("Scene.VertexShader");
fsScene->SetName("Scene.FragmentShader");
shadowMap->SetName("ShadowMap.Texture");
shadowMapRenderTarget->SetName("ShadowMap.RenderTarget");
#if 0
// Show some information
std::cout << "press LEFT MOUSE BUTTON and move the mouse on the X-axis to rotate the OUTER cube" << std::endl;
std::cout << "press RIGHT MOUSE BUTTON and move the mouse on the X-axis to rotate the INNER cube" << std::endl;
std::cout << "press RETURN KEY to save the render target texture to a PNG file" << std::endl;
#endif
}
private:
LLGL::VertexFormat CreateBuffers()
{
// Specify vertex format
LLGL::VertexFormat vertexFormat;
vertexFormat.AppendAttribute({ "position", LLGL::Format::RGB32Float });
vertexFormat.AppendAttribute({ "normal", LLGL::Format::RGB32Float });
vertexFormat.SetStride(sizeof(TexturedVertex));
// Load 3D models
std::vector<TexturedVertex> vertices;
meshes.push_back(LoadObjModel(vertices, "../../Media/Models/SimpleRoom.obj"));
meshes.push_back(LoadObjModel(vertices, "../../Media/Models/WiredBox.obj"));
meshes[1].color = { 0.4f, 0.5f, 1.0f };
// Create vertex, index, and constant buffer
vertexBuffer = CreateVertexBuffer(vertices, vertexFormat);
constantBuffer = CreateConstantBuffer(settings);
return vertexFormat;
}
void LoadShaders(const LLGL::VertexFormat& vertexFormat)
{
// Load shader program
if (Supported(LLGL::ShadingLanguage::GLSL))
{
vsShadowMap = LoadShaderAndPatchClippingOrigin({ LLGL::ShaderType::Vertex, "ShadowMap.vert" }, { vertexFormat });
vsScene = LoadShader({ LLGL::ShaderType::Vertex, "Scene.vert" }, { vertexFormat });
fsScene = LoadShader({ LLGL::ShaderType::Fragment, "Scene.frag" });
}
else if (Supported(LLGL::ShadingLanguage::SPIRV))
{
vsShadowMap = LoadShader({ LLGL::ShaderType::Vertex, "ShadowMap.450core.vert.spv" }, { vertexFormat });
vsScene = LoadShader({ LLGL::ShaderType::Vertex, "Scene.450core.vert.spv" }, { vertexFormat });
fsScene = LoadShader({ LLGL::ShaderType::Fragment, "Scene.450core.frag.spv" });
}
else if (Supported(LLGL::ShadingLanguage::HLSL))
{
vsShadowMap = LoadShader({ LLGL::ShaderType::Vertex, "Example.hlsl", "VShadowMap", "vs_5_0" }, { vertexFormat });
vsScene = LoadShader({ LLGL::ShaderType::Vertex, "Example.hlsl", "VScene", "vs_5_0" }, { vertexFormat });
fsScene = LoadShader({ LLGL::ShaderType::Fragment, "Example.hlsl", "PScene", "ps_5_0" });
}
else if (Supported(LLGL::ShadingLanguage::Metal))
{
vsShadowMap = LoadShader({ LLGL::ShaderType::Vertex, "Example.metal", "VShadowMap", "1.1" }, { vertexFormat });
vsScene = LoadShader({ LLGL::ShaderType::Vertex, "Example.metal", "VScene", "1.1" }, { vertexFormat });
fsScene = LoadShader({ LLGL::ShaderType::Fragment, "Example.metal", "PScene", "1.1" });
}
else
throw std::runtime_error("shaders not supported for active renderer");
}
void CreateShadowMap()
{
// Create texture
LLGL::TextureDescriptor textureDesc;
{
textureDesc.type = LLGL::TextureType::Texture2D;
textureDesc.bindFlags = LLGL::BindFlags::DepthStencilAttachment | LLGL::BindFlags::Sampled;
textureDesc.format = LLGL::Format::D32Float;
textureDesc.extent.width = shadowMapResolution.width;
textureDesc.extent.height = shadowMapResolution.height;
textureDesc.extent.depth = 1;
}
shadowMap = renderer->CreateTexture(textureDesc);
// Create render target
LLGL::RenderTargetDescriptor renderTargetDesc;
{
renderTargetDesc.resolution = shadowMapResolution;
renderTargetDesc.attachments =
{
LLGL::AttachmentDescriptor { LLGL::AttachmentType::Depth, shadowMap }
};
}
shadowMapRenderTarget = renderer->CreateRenderTarget(renderTargetDesc);
// Create texture sampler
LLGL::SamplerDescriptor samplerDesc;
{
samplerDesc.addressModeU = LLGL::SamplerAddressMode::Border;
samplerDesc.addressModeV = LLGL::SamplerAddressMode::Border;
samplerDesc.addressModeW = LLGL::SamplerAddressMode::Border;
samplerDesc.borderColor = { 1.0f, 1.0f, 1.0f, 1.0f };
samplerDesc.compareEnabled = true;
samplerDesc.mipMapping = false;
}
shadowMapSampler = renderer->CreateSampler(samplerDesc);
}
void CreatePipelineLayouts()
{
// Create pipeline layouts for shadow-map and scene rendering
if (IsOpenGL())
{
pipelineLayoutShadowMap = renderer->CreatePipelineLayout(
LLGL::PipelineLayoutDesc("cbuffer(0):vert")
);
pipelineLayoutScene = renderer->CreatePipelineLayout(
LLGL::PipelineLayoutDesc("cbuffer(0):frag:vert, texture(0):frag, sampler(0):frag")
);
}
else
{
pipelineLayoutShadowMap = renderer->CreatePipelineLayout(
LLGL::PipelineLayoutDesc("cbuffer(1):vert")
);
pipelineLayoutScene = renderer->CreatePipelineLayout(
LLGL::PipelineLayoutDesc("cbuffer(1):frag:vert, texture(2):frag, sampler(3):frag")
);
}
}
void CreatePipelines()
{
// Create graphics pipeline for shadow-map rendering
{
LLGL::GraphicsPipelineDescriptor pipelineDesc;
{
pipelineDesc.vertexShader = vsShadowMap;
pipelineDesc.renderPass = shadowMapRenderTarget->GetRenderPass();
pipelineDesc.pipelineLayout = pipelineLayoutShadowMap;
pipelineDesc.depth.testEnabled = true;
pipelineDesc.depth.writeEnabled = true;
pipelineDesc.rasterizer.cullMode = LLGL::CullMode::Back;
pipelineDesc.rasterizer.depthBias.constantFactor = 4.0f;
pipelineDesc.rasterizer.depthBias.slopeFactor = 4.0f;
pipelineDesc.blend.targets[0].colorMask = { false, false, false, false };
pipelineDesc.viewports = { shadowMapResolution };
}
pipelineShadowMap = renderer->CreatePipelineState(pipelineDesc);
}
// Create graphics pipeline for scene rendering
{
LLGL::GraphicsPipelineDescriptor pipelineDesc;
{
pipelineDesc.vertexShader = vsScene;
pipelineDesc.fragmentShader = fsScene;
pipelineDesc.renderPass = swapChain->GetRenderPass();
pipelineDesc.pipelineLayout = pipelineLayoutScene;
pipelineDesc.depth.testEnabled = true;
pipelineDesc.depth.writeEnabled = true;
pipelineDesc.rasterizer.cullMode = LLGL::CullMode::Back;
pipelineDesc.rasterizer.multiSampleEnabled = (GetSampleCount() > 1);
}
pipelineScene = renderer->CreatePipelineState(pipelineDesc);
}
}
void CreateResourceHeaps()
{
// Create resource heap for shadow-map rendering
LLGL::ResourceHeapDescriptor resourceHeapDesc;
{
resourceHeapDesc.pipelineLayout = pipelineLayoutShadowMap;
resourceHeapDesc.resourceViews = { constantBuffer };
}
resourceHeapShadowMap = renderer->CreateResourceHeap(resourceHeapDesc);
// Create resource heap for scene rendering
{
resourceHeapDesc.pipelineLayout = pipelineLayoutScene;
resourceHeapDesc.resourceViews = { constantBuffer, shadowMap, shadowMapSampler };
}
resourceHeapScene = renderer->CreateResourceHeap(resourceHeapDesc);
}
void UpdateScene()
{
// Update animation
static float animation;
if (input.KeyPressed(LLGL::Key::LButton))
{
auto motion = input.GetMouseMotion();
viewRotation.x += static_cast<float>(motion.y) * 0.25f;
viewRotation.x = Gs::Clamp(viewRotation.x, -90.0f, 0.0f);
viewRotation.y += static_cast<float>(motion.x) * 0.25f;
}
if (input.KeyPressed(LLGL::Key::RButton))
{
auto motion = input.GetMouseMotion();
animation += static_cast<float>(motion.x) * 0.25f;
}
// Update model transform
meshes[1].transform.LoadIdentity();
Gs::Translate(meshes[1].transform, boxPosition);
Gs::RotateFree(meshes[1].transform, Gs::Vector3f(1.0f).Normalized(), Gs::Deg2Rad(animation));
Gs::Scale(meshes[1].transform, Gs::Vector3f(0.15f));
// Update view transformation
settings.vpMatrix.LoadIdentity();
Gs::Translate(settings.vpMatrix, boxPosition);
Gs::RotateFree(settings.vpMatrix, { 0, 1, 0 }, Gs::Deg2Rad(viewRotation.y));
Gs::RotateFree(settings.vpMatrix, { 1, 0, 0 }, Gs::Deg2Rad(viewRotation.x));
Gs::Translate(settings.vpMatrix, { 0, 0, -viewDistanceToBox });
settings.vpMatrix.MakeInverse();
settings.vpMatrix = projection * settings.vpMatrix;
// Update light transformation
auto lightProjection = PerspectiveProjection(1.0f, 0.1f, 100.0f, Gs::Deg2Rad(spotLightAngle));
settings.vpShadowMatrix.LoadIdentity();
Gs::Translate(settings.vpShadowMatrix, boxPosition + lightOffset);
Gs::RotateFree(settings.vpShadowMatrix, { 1, 0, 0 }, Gs::Deg2Rad(-90.0f));
settings.vpShadowMatrix.MakeInverse();
settings.vpShadowMatrix = lightProjection * settings.vpShadowMatrix;
}
void RenderMesh(const TriangleMesh& mesh)
{
settings.wMatrix = mesh.transform;
settings.diffuse = mesh.color;
commands->UpdateBuffer(*constantBuffer, 0, &settings, sizeof(settings));
commands->Draw(mesh.numVertices, mesh.firstVertex);
}
void RenderAllMeshes()
{
for (const auto& mesh : meshes)
RenderMesh(mesh);
}
void RenderShadowMap()
{
// Render scene into shadow-map texture
commands->BeginRenderPass(*shadowMapRenderTarget);
{
commands->Clear(LLGL::ClearFlags::Depth);
commands->SetPipelineState(*pipelineShadowMap);
commands->SetResourceHeap(*resourceHeapShadowMap);
RenderAllMeshes();
}
commands->EndRenderPass();
// Update MIP-maps of shadow-map texture
//commands->GenerateMips(*shadowMap);
}
void RenderScene()
{
// Render scene onto screen
commands->BeginRenderPass(*swapChain);
{
commands->Clear(LLGL::ClearFlags::ColorDepth, { backgroundColor });
commands->SetViewport(swapChain->GetResolution());
commands->SetPipelineState(*pipelineScene);
commands->SetResourceHeap(*resourceHeapScene);
RenderAllMeshes();
}
commands->EndRenderPass();
}
void OnDrawFrame() override
{
// Update scene by user input
UpdateScene();
commands->Begin();
{
// Bind common input assembly
commands->SetVertexBuffer(*vertexBuffer);
// Unbind shadow texture before rendering into it
commands->ResetResourceSlots(LLGL::ResourceType::Texture, 2, 1, LLGL::BindFlags::Sampled, LLGL::StageFlags::FragmentStage);
// Draw scene into shadow-map, then draw scene onto screen
commands->PushDebugGroup("Shadow Map Pass");
RenderShadowMap();
commands->PopDebugGroup();
commands->PushDebugGroup("Scene Pass");
RenderScene();
commands->PopDebugGroup();
}
commands->End();
commandQueue->Submit(*commands);
// Present result on the screen
swapChain->Present();
}
};
LLGL_IMPLEMENT_EXAMPLE(Example_ShadowMapping);