-
Notifications
You must be signed in to change notification settings - Fork 4
/
Renderer.cpp
388 lines (346 loc) · 8.96 KB
/
Renderer.cpp
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
383
384
385
386
387
388
// Ahmed S. Tolba 2015-2018
#include "Renderer.h"
#include "Texture.h"
#include "Mesh.h"
#include <algorithm>
#include "Shader.h"
#include "VertexArray.h"
#include "SpriteComponent.h"
#include "MeshComponent.h"
#include "UIScreen.h"
#include "Game.h"
#include <GL/glew.h>
#include "SkeletalMeshComponent.h"
Renderer::Renderer(Game* game)
:mGame(game)
,mSpriteShader(nullptr)
,mMeshShader(nullptr)
,mSkinnedShader(nullptr)
{
}
Renderer::~Renderer()
{
}
bool Renderer::Initialize(float screenWidth, float screenHeight)
{
mScreenWidth = screenWidth;
mScreenHeight = screenHeight;
// Set OpenGL attributes
// Use the core OpenGL profile
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
// Specify version 3.3
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
// Request a color buffer with 8-bits per RGBA channel
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
// Enable double buffering
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
// Force OpenGL to use hardware acceleration
SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1);
mWindow = SDL_CreateWindow("Ahmed Tolba 3D Game Engine Crossplatform", 100, 100,
static_cast<int>(mScreenWidth), static_cast<int>(mScreenHeight), SDL_WINDOW_OPENGL);
if (!mWindow)
{
SDL_Log("Failed to create window: %s", SDL_GetError());
return false;
}
// Create an OpenGL context
mContext = SDL_GL_CreateContext(mWindow);
// Initialize GLEW
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK)
{
SDL_Log("Failed to initialize GLEW.");
return false;
}
// On some platforms, GLEW will emit a benign error code,
// so clear it
glGetError();
// Make sure we can create/compile shaders
if (!LoadShaders())
{
SDL_Log("Failed to load shaders.");
return false;
}
// Create quad for drawing sprites
CreateSpriteVerts();
return true;
}
void Renderer::Shutdown()
{
delete mSpriteVerts;
mSpriteShader->Unload();
delete mSpriteShader;
mMeshShader->Unload();
delete mMeshShader;
SDL_GL_DeleteContext(mContext);
SDL_DestroyWindow(mWindow);
}
void Renderer::UnloadData()
{
// Destroy textures
for (auto i : mTextures)
{
i.second->Unload();
delete i.second;
}
mTextures.clear();
// Destroy meshes
for (auto i : mMeshes)
{
i.second->Unload();
delete i.second;
}
mMeshes.clear();
}
void Renderer::Draw()
{
// Set the clear color to light grey
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
// Clear the color buffer
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Draw mesh components
// Enable depth buffering/disable alpha blend
glEnable(GL_DEPTH_TEST);
glDisable(GL_BLEND);
// Set the mesh shader active
mMeshShader->SetActive();
// Update view-projection matrix
mMeshShader->SetMatrixUniform("uViewProj", mView * mProjection);
// Update lighting uniforms
SetLightUniforms(mMeshShader);
for (auto mc : mMeshComps)
{
if (mc->GetVisible())
{
mc->Draw(mMeshShader);
}
}
// Draw any skinned meshes now
mSkinnedShader->SetActive();
// Update view-projection matrix
mSkinnedShader->SetMatrixUniform("uViewProj", mView * mProjection);
// Update lighting uniforms
SetLightUniforms(mSkinnedShader);
for (auto sk : mSkeletalMeshes)
{
if (sk->GetVisible())
{
sk->Draw(mSkinnedShader);
}
}
// Draw all sprite components
// Disable depth buffering
glDisable(GL_DEPTH_TEST);
// Enable alpha blending on the color buffer
glEnable(GL_BLEND);
glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD);
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO);
// Set shader/vao as active
mSpriteShader->SetActive();
mSpriteVerts->SetActive();
for (auto sprite : mSprites)
{
if (sprite->GetVisible())
{
sprite->Draw(mSpriteShader);
}
}
// Draw any UI screens
for (auto ui : mGame->GetUIStack())
{
ui->Draw(mSpriteShader);
}
// Swap the buffers
SDL_GL_SwapWindow(mWindow);
}
void Renderer::AddSprite(SpriteComponent* sprite)
{
// Find the insertion point in the sorted vector
// (The first element with a higher draw order than me)
int myDrawOrder = sprite->GetDrawOrder();
auto iter = mSprites.begin();
for (;
iter != mSprites.end();
++iter)
{
if (myDrawOrder < (*iter)->GetDrawOrder())
{
break;
}
}
// Inserts element before position of iterator
mSprites.insert(iter, sprite);
}
void Renderer::RemoveSprite(SpriteComponent* sprite)
{
auto iter = std::find(mSprites.begin(), mSprites.end(), sprite);
mSprites.erase(iter);
}
void Renderer::AddMeshComp(MeshComponent* mesh)
{
if (mesh->GetIsSkeletal())
{
SkeletalMeshComponent* sk = static_cast<SkeletalMeshComponent*>(mesh);
mSkeletalMeshes.emplace_back(sk);
}
else
{
mMeshComps.emplace_back(mesh);
}
}
void Renderer::RemoveMeshComp(MeshComponent* mesh)
{
if (mesh->GetIsSkeletal())
{
SkeletalMeshComponent* sk = static_cast<SkeletalMeshComponent*>(mesh);
auto iter = std::find(mSkeletalMeshes.begin(), mSkeletalMeshes.end(), sk);
mSkeletalMeshes.erase(iter);
}
else
{
auto iter = std::find(mMeshComps.begin(), mMeshComps.end(), mesh);
mMeshComps.erase(iter);
}
}
Texture* Renderer::GetTexture(const std::string& fileName)
{
Texture* tex = nullptr;
auto iter = mTextures.find(fileName);
if (iter != mTextures.end())
{
tex = iter->second;
}
else
{
tex = new Texture();
if (tex->Load(fileName))
{
mTextures.emplace(fileName, tex);
}
else
{
delete tex;
tex = nullptr;
}
}
return tex;
}
Mesh* Renderer::GetMesh(const std::string & fileName)
{
Mesh* m = nullptr;
auto iter = mMeshes.find(fileName);
if (iter != mMeshes.end())
{
m = iter->second;
}
else
{
m = new Mesh();
if (m->Load(fileName, this))
{
mMeshes.emplace(fileName, m);
}
else
{
delete m;
m = nullptr;
}
}
return m;
}
bool Renderer::LoadShaders()
{
// Create sprite shader
mSpriteShader = new Shader();
if (!mSpriteShader->Load("Shaders/Sprite.vert", "Shaders/Sprite.frag"))
{
return false;
}
mSpriteShader->SetActive();
// Set the view-projection matrix
Matrix4 viewProj = Matrix4::CreateSimpleViewProj(mScreenWidth, mScreenHeight);
mSpriteShader->SetMatrixUniform("uViewProj", viewProj);
// Create basic mesh shader
mMeshShader = new Shader();
if (!mMeshShader->Load("Shaders/Phong.vert", "Shaders/Phong.frag"))
{
return false;
}
mMeshShader->SetActive();
// Set the view-projection matrix
mView = Matrix4::CreateLookAt(Vector3::Zero, Vector3::UnitX, Vector3::UnitZ);
mProjection = Matrix4::CreatePerspectiveFOV(Math::ToRadians(70.0f),
mScreenWidth, mScreenHeight, 10.0f, 10000.0f);
mMeshShader->SetMatrixUniform("uViewProj", mView * mProjection);
// Create skinned shader
mSkinnedShader = new Shader();
if (!mSkinnedShader->Load("Shaders/Skinned.vert", "Shaders/Phong.frag"))
{
return false;
}
mSkinnedShader->SetActive();
// Set the view-projection matrix
mView = Matrix4::CreateLookAt(Vector3::Zero, Vector3::UnitX, Vector3::UnitZ);
mProjection = Matrix4::CreatePerspectiveFOV(Math::ToRadians(70.0f),
mScreenWidth, mScreenHeight, 10.0f, 10000.0f);
mSkinnedShader->SetMatrixUniform("uViewProj", mView * mProjection);
return true;
}
void Renderer::CreateSpriteVerts()
{
float vertices[] = {
-0.5f, 0.5f, 0.f, 0.f, 0.f, 0.0f, 0.f, 0.f, // top left
0.5f, 0.5f, 0.f, 0.f, 0.f, 0.0f, 1.f, 0.f, // top right
0.5f,-0.5f, 0.f, 0.f, 0.f, 0.0f, 1.f, 1.f, // bottom right
-0.5f,-0.5f, 0.f, 0.f, 0.f, 0.0f, 0.f, 1.f // bottom left
};
unsigned int indices[] = {
0, 1, 2,
2, 3, 0
};
mSpriteVerts = new VertexArray(vertices, 4, VertexArray::PosNormTex, indices, 6);
}
void Renderer::SetLightUniforms(Shader* shader)
{
// Camera position is from inverted view
Matrix4 invView = mView;
invView.Invert();
shader->SetVectorUniform("uCameraPos", invView.GetTranslation());
// Ambient light
shader->SetVectorUniform("uAmbientLight", mAmbientLight);
// Directional light
shader->SetVectorUniform("uDirLight.mDirection",
mDirLight.mDirection);
shader->SetVectorUniform("uDirLight.mDiffuseColor",
mDirLight.mDiffuseColor);
shader->SetVectorUniform("uDirLight.mSpecColor",
mDirLight.mSpecColor);
}
Vector3 Renderer::Unproject(const Vector3& screenPoint) const
{
// Convert screenPoint to device coordinates (between -1 and +1)
Vector3 deviceCoord = screenPoint;
deviceCoord.x /= (mScreenWidth) * 0.5f;
deviceCoord.y /= (mScreenHeight) * 0.5f;
// Transform vector by unprojection matrix
Matrix4 unprojection = mView * mProjection;
unprojection.Invert();
return Vector3::TransformWithPerspDiv(deviceCoord, unprojection);
}
void Renderer::GetScreenDirection(Vector3& outStart, Vector3& outDir) const
{
// Get start point (in center of screen on near plane)
Vector3 screenPoint(0.0f, 0.0f, 0.0f);
outStart = Unproject(screenPoint);
// Get end point (in center of screen, between near and far)
screenPoint.z = 0.9f;
Vector3 end = Unproject(screenPoint);
// Get direction vector
outDir = end - outStart;
outDir.Normalize();
}