OpenGlController.cpp 11.8 KB
Newer Older
1
2
#include "OpenGLController.h"
#include "callback.h"
Anakin's avatar
Anakin committed
3
4
#include "shader.hpp"
#include "Texture.h"
Anakin's avatar
Anakin committed
5
6
7
8
#include <Windows.h>
#include <string>
#include <glm\gtc\matrix_transform.hpp>

Anakin's avatar
Anakin committed
9

Anakin's avatar
Anakin committed
10
11
#define VERTEX_SHADER "Shader/TextureShader.vert"
#define FRAGMENT_SHADER "Shader/TextureShader.frag"
12
13
14
15

/////////////////////////////////////////////////////////////////////////
// public constructor/destructor

Anakin's avatar
Anakin committed
16
OpenGLController* OpenGLController::getInstance(int oglMajor, int oglMinor)
17
{
Anakin's avatar
Anakin committed
18
	static OpenGLController *instace = new OpenGLController(oglMajor, oglMinor);
Anakin's avatar
Anakin committed
19
20
21
22
23
	return instace;
}

OpenGLController::~OpenGLController()
{
Anakin's avatar
Anakin committed
24
25
26
27
	glDeleteBuffers(1, &gluiVertexBufferID);
	glDeleteVertexArrays(1, &gluiVertexArrayID);
	glDeleteProgram(gluiShaderPrgmID);

Anakin's avatar
Anakin committed
28
29
	glDeleteTextures(1, &gluiSamplerID);
	glfwTerminate();
Anakin's avatar
Anakin committed
30

Anakin's avatar
Anakin committed
31
	deleteVectors();
32
33
}

Anakin's avatar
Anakin committed
34
35
36
37

/////////////////////////////////////////////////////////////////////////
// private constructor

Anakin's avatar
Anakin committed
38
OpenGLController::OpenGLController(int oglMajor, int oglMinor)
39
{
40
	// adjust ogl version optional
41
42
	iOglMajorVersion = oglMajor;
	iOglMinorVersion = oglMinor;
Anakin's avatar
Anakin committed
43
44

	// run OGL
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
	processInit();
}

/////////////////////////////////////////////////////////////////////////
// private functions

void OpenGLController::processInit()
{
	startGLFW();
	createWindow();
	startGLEW();
	setCallbackFunctions();
	
	// set background color
	glClearColor(0.5000f, 0.8000f, 1.0000f, 0.0000f);

	// enable z-order
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LESS);

	// draw vertics only from one side
	glEnable(GL_CULL_FACE);
Anakin's avatar
Anakin committed
67
68
69
70
71
72

	// generate stuff
	glGenVertexArrays(1, &gluiVertexArrayID);
	glBindVertexArray(gluiVertexArrayID);

	glGenBuffers(1, &gluiVertexBufferID);
73
74
75
76
77
78
79

	// open attribute position
	glBindBuffer(GL_ARRAY_BUFFER, gluiVertexBufferID);
	glVertexAttribPointer(VERTEX_INDEX_XYZ, VERTEX_COMPONENTS_XYZ, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)VERTEX_OFFSET_XYZ);
	glVertexAttribPointer(VERTEX_INDEX_UV, VERTEX_COMPONENTS_UV, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)VERTEX_OFFSET_UV);
	glBindBuffer(GL_ARRAY_BUFFER, 0);

Anakin's avatar
Anakin committed
80
	// enable position, UV and mvp
81
82
	glEnableVertexAttribArray(0);
	glEnableVertexAttribArray(1);
Anakin's avatar
Anakin committed
83
84
85
86
87
88
89
90
91
92
93
94

	// get the painter ready
	try
	{
		gluiShaderPrgmID = LoadShaders(VERTEX_SHADER, FRAGMENT_SHADER);
	}
	catch (std::invalid_argument e)
	{
		MessageBox(NULL, e.what(), "MeshViewer 2.0 Error", MB_OK | MB_ICONERROR);
		exit(1);
	}

95
	// get some shader IDs
Anakin's avatar
Anakin committed
96
97
	gluiMatrixID = glGetUniformLocation(gluiShaderPrgmID, "MVP");
	gluiSamplerID = glGetUniformLocation(gluiShaderPrgmID, "textureSampler");
98
99
100
101

	// generate texture
	glGenTextures(1, &gluiTextureID);
	glBindTexture(GL_TEXTURE_2D, gluiTextureID);
Anakin's avatar
Anakin committed
102
103
104
105
106
107

	// set some texture parameters
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
108
109
}

Anakin's avatar
Anakin committed
110
111
void OpenGLController::deleteVectors()
{
112
	if (vModels != NULL)
Anakin's avatar
Anakin committed
113
	{
114
		while (!vModels->empty())
Anakin's avatar
Anakin committed
115
		{
116
117
			Modl* cursor = vModels->back();
			vModels->pop_back();
118

119
			while (!cursor->segmLst.empty())
120
			{
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
				Segment* segmCuror = cursor->segmLst.back();
				cursor->segmLst.pop_back();

				delete segmCuror->uv;
				delete segmCuror->vertex;

				while (!segmCuror->meshIndices.empty())
				{
					std::vector<std::uint32_t>* meshCursor = segmCuror->meshIndices.back();
					meshCursor->clear();
					segmCuror->meshIndices.pop_back();
					delete meshCursor;
				}

				delete segmCuror;
136
137
			}

138
			delete cursor;
Anakin's avatar
Anakin committed
139
		}
140
		delete vModels;
Anakin's avatar
Anakin committed
141
142
143
144
145
146
	}

	while (!vTextures.empty())
	{
		textureData* cursor = vTextures.back();
		vTextures.pop_back();
147
		cursor->data->clear();
Anakin's avatar
Anakin committed
148
149
150
151
152
		delete cursor->data;
		delete cursor;
	}
}

153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
void OpenGLController::startGLFW()
{
	if (!glfwInit())
	{
		MessageBox(NULL, "Failed to initialize GLFW", "MeshViewer 2.0 Error", MB_OK | MB_ICONERROR);
		exit(0);
	}

	glfwWindowHint(GLFW_SAMPLES, iAntiAliasingLevel);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, iOglMajorVersion);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, iOglMinorVersion);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
}

void OpenGLController::createWindow()
{
	pWindow = glfwCreateWindow(iWidth, iHeight, sWindowName.c_str(), NULL, NULL);

	if (pWindow == NULL)
	{
		std::string message = "Your GPU does not support OpenGL ";
174
		message += std::to_string(iOglMajorVersion);
175
		message += ".";
176
177
		message += std::to_string(iOglMinorVersion);
		message += "\nTry to use an other version";
178
179
180
181
182
183
184
185
186
187
188

		MessageBox(NULL, message.c_str(), "MeshViewer 2.0 Error", MB_OK | MB_ICONERROR);

		glfwTerminate();
		exit(0);
	}

	glfwSetWindowUserPointer(pWindow, this);
	glfwMakeContextCurrent(pWindow);
}

Anakin's avatar
Anakin committed
189
190
191
192
193
194
195
196
197
198
199
200
void OpenGLController::startGLEW()
{
	glewExperimental = true;

	if (glewInit() != GLEW_OK)
	{
		MessageBox(NULL, "Failed to initialize GLEW", "MeshViewer 2.0 Error", MB_OK | MB_ICONERROR);
		glfwTerminate();
		exit(0);
	}
}

201
202
203
204
205
206
207
void OpenGLController::setCallbackFunctions()
{
	glfwSetMouseButtonCallback(pWindow, mouseButton);
	glfwSetCursorPosCallback(pWindow, mouseMove);
	glfwSetWindowSizeCallback(pWindow, windowResize);
	glfwSetScrollCallback(pWindow, mouseWheel);
	glfwSetKeyCallback(pWindow, keyPress);
Anakin's avatar
Anakin committed
208
	glfwSetDropCallback(pWindow, dragNdrop);
209
210
}

Anakin's avatar
Anakin committed
211
212
213
214
glm::mat4 OpenGLController::getModelMatrix(unsigned int index)
{
	glm::mat4 tempParentMatrix = glm::mat4(1.0f);

215
	for (unsigned int loop = 0; loop < vModels->size(); loop++)
Anakin's avatar
Anakin committed
216
	{
217
		if (!strcmp(vModels->at(index)->parent.c_str(), vModels->at(loop)->name.c_str()))
Anakin's avatar
Anakin committed
218
219
220
221
222
223
		{
			tempParentMatrix = getModelMatrix(loop);
			break;
		}
	}

224
	return tempParentMatrix * vModels->at(index)->m4x4Translation;
Anakin's avatar
Anakin committed
225
226
}

Anakin's avatar
Anakin committed
227
glm::mat4 OpenGLController::getMVPMatrix(unsigned int index)
228
{
Anakin's avatar
Anakin committed
229
230
231
232
233
	// Projection
	glm::mat4 m4x4Projection = glm::perspective(fFOV, float(iWidth) / float(iHeight), fMinView, fMaxView);
	
	// View
	glm::mat4 m4x4View = glm::lookAt(
Anakin's avatar
Anakin committed
234
235
236
237
		glm::vec3(dTranslationX, dTranslationY, dTranslationZ),
		glm::vec3(dTranslationX, dTranslationY, dTranslationZ - 1),
		glm::vec3(0, 1, 0)
	);
Anakin's avatar
Anakin committed
238

Anakin's avatar
Anakin committed
239
240
241
242
243
244
245
	// User controlled rotation
	glm::mat4 m4x4ModelRot = glm::mat4(1.0f);
	m4x4ModelRot = glm::rotate(m4x4ModelRot, fRotationX, glm::vec3(1, 0, 0));
	m4x4ModelRot = glm::rotate(m4x4ModelRot, fRotationY, glm::vec3(0, 1, 0));
	m4x4ModelRot = glm::rotate(m4x4ModelRot, fRotationZ, glm::vec3(0, 0, 1));

	// Return MVP
Anakin's avatar
Anakin committed
246
	return m4x4Projection * m4x4View * m4x4ModelRot * getModelMatrix(index);
247
248
}

Anakin's avatar
Anakin committed
249
250
251
252

/////////////////////////////////////////////////////////////////////////
// public getter

253
254
255
256
257
258
259
260
261
262
263
GLFWwindow * OpenGLController::getWindow() const
{
	return pWindow;
}


/////////////////////////////////////////////////////////////////////////
// public functions

void OpenGLController::resize(int width, int height)
{
Anakin's avatar
Anakin committed
264
265
	iWidth = width;
	iHeight = height;
266
267
268
269
}

void OpenGLController::addRotX(float value)
{
Anakin's avatar
Anakin committed
270
	fRotationX += value;
271
272
273
274
}

void OpenGLController::addRotY(float value)
{
Anakin's avatar
Anakin committed
275
	fRotationY += value;
276
277
278
279
}

void OpenGLController::addTransX(double value)
{
Anakin's avatar
Anakin committed
280
	dTranslationX += value;
281
282
283
284
}

void OpenGLController::addTransY(double value)
{
Anakin's avatar
Anakin committed
285
	dTranslationY += value;
286
287
288
289
}

void OpenGLController::addTransZ(double value)
{
Anakin's avatar
Anakin committed
290
	dTranslationZ += value;
291
292
}

Anakin's avatar
Anakin committed
293
294
295
296
297
298
299
300
301
302
void OpenGLController::resetView()
{
	dTranslationX = 0;
	dTranslationY = 0;
	dTranslationZ = 5;
	fRotationX = 0;
	fRotationY = 0;
	fRotationZ = 0;
}

303
304
305
306
307
308
void OpenGLController::updateScene()
{
	// get new matrices
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	// use shader prgm
Anakin's avatar
Anakin committed
309
	glUseProgram(gluiShaderPrgmID);
310
311
312

	// bind texture in texture unit 0
	glActiveTexture(GL_TEXTURE0);
Anakin's avatar
Anakin committed
313
	glBindTexture(GL_TEXTURE_2D, gluiTextureID);
314
315
316
	// tell sampler to use texture unit 0
	glUniform1i(gluiSamplerID, 0);

Anakin's avatar
Anakin committed
317
318
	int instanceOffset(0);

319
	for (unsigned int modelIndex = 0; modelIndex < vModels->size(); modelIndex++)
Anakin's avatar
Anakin committed
320
	{
321
		// skip null, bones, shadowMesh, hidden things (don't increase textrue index!!)
322
323
324
325
		if (vModels->at(modelIndex)->type == null ||
			vModels->at(modelIndex)->type == bone ||
			vModels->at(modelIndex)->type == shadowMesh ||
			vModels->at(modelIndex)->renderFlags == 1)
326
327
			continue;

328
		for (auto& segIt : vModels->at(modelIndex)->segmLst)
Anakin's avatar
Anakin committed
329
330
		{
			// give texture to the shader
Anakin's avatar
Anakin committed
331
			std::uint32_t tempTexIndex = segIt->textureIndex >= vTextures.size() ? vTextures.size() - 1 : segIt->textureIndex;
332

Anakin's avatar
Anakin committed
333
334
335
			glTexImage2D(
				GL_TEXTURE_2D,
				0,
Anakin's avatar
Anakin committed
336
337
338
				vTextures[tempTexIndex]->alpha ? GL_RGBA : GL_RGB,
				vTextures[tempTexIndex]->width,
				vTextures[tempTexIndex]->height,
Anakin's avatar
Anakin committed
339
				0,
Anakin's avatar
Anakin committed
340
				vTextures[tempTexIndex]->alpha ? GL_BGRA : GL_BGR,
Anakin's avatar
Anakin committed
341
				GL_UNSIGNED_BYTE,
Anakin's avatar
Anakin committed
342
				vTextures[tempTexIndex]->data->data()
Anakin's avatar
Anakin committed
343
344
345
346
347
348
349
			);

			glGenerateMipmap(GL_TEXTURE_2D);

			// give the MVP to the shader
			glUniformMatrix4fv(gluiMatrixID, 1, GL_FALSE, &getMVPMatrix(modelIndex)[0][0]);

Anakin's avatar
Anakin committed
350
351
352
353
354
355
356
			// calculate the number of vertex
			unsigned int vertexCount(0);
			for (auto& it : segIt->meshIndices)
				vertexCount += (it->size() - 2) * 3;


			glDrawArrays(GL_TRIANGLES, instanceOffset, vertexCount);
Anakin's avatar
Anakin committed
357

Anakin's avatar
Anakin committed
358
			// increase the offset
Anakin's avatar
Anakin committed
359
			instanceOffset += vertexCount;
Anakin's avatar
Anakin committed
360
		}
Anakin's avatar
Anakin committed
361
	}
362

Anakin's avatar
Anakin committed
363
364
365
366
367
368
	glfwSwapBuffers(pWindow);
	glfwPollEvents();
}

void OpenGLController::loadMsh(const char * path)
{
Anakin's avatar
Anakin committed
369
370
371
	// clean up old stuff first
	deleteVectors();

Anakin's avatar
Anakin committed
372
373
	std::vector<std::string> tempTexList;

374
	// get all models
375
376
377
	try
	{
		Object obj(path);
Anakin's avatar
Anakin committed
378
		vModels = obj.getModels();
Anakin's avatar
Anakin committed
379
		tempTexList = obj.getTextureList();
380
381
382
383
	}
	catch (std::invalid_argument e)
	{
		MessageBox(NULL, e.what(), "MeshViewer 2.0 Error", MB_OK | MB_ICONERROR);
Anakin's avatar
Anakin committed
384
		return; exit(1);
385
386
	}

387
	// collect vertex data of all models
388
	std::vector<Vertex> tempBufferData;
389

390
	for (auto& modIt : *vModels)		// for every model chunk
391
	{
Anakin's avatar
Anakin committed
392
		for (auto& segIt : modIt->segmLst)		// for every cluster
393
		{
Anakin's avatar
Anakin committed
394
			for (auto& mshIt : segIt->meshIndices)		// for every polygon
395
			{
Anakin's avatar
Anakin committed
396
				if (mshIt->size() >= 3)		// multipoly
397
				{
Anakin's avatar
Anakin committed
398
					// for every triangle of the multi polygon
Anakin's avatar
Anakin committed
399
					for (unsigned int tri = 0; tri < mshIt->size() - 2; tri++)
Anakin's avatar
Anakin committed
400
401
402
403
404
405
406
					{
						// for every edge of the triangle
						for (int triEdge = 0; triEdge < 3; triEdge++)
						{
							Vertex tempVertex;
							// every edge has 3 coordinates
							for (int j = 0; j < 3; j++)
Anakin's avatar
Anakin committed
407
408
								tempVertex.position[j] = (GLfloat)segIt->vertex[(*mshIt)[tri + triEdge - ((tri % 2) * (triEdge - 1) * 2)] * 3 + j];

Anakin's avatar
Anakin committed
409
410
411
412
413
414
415
416
417
							// and 2 UV
							if (segIt->uv == NULL)
							{
								tempVertex.uv[0] = 1.0;
								tempVertex.uv[1] = 1.0;
							}
							else
							{
								for (int j = 0; j < 2; j++)
Anakin's avatar
Anakin committed
418
									tempVertex.uv[j] = (GLfloat)segIt->uv[(*mshIt)[tri + triEdge - ((tri % 2) * (triEdge - 1) * 2)] * 2 + j];
Anakin's avatar
Anakin committed
419
420
421
422
							}
							tempBufferData.push_back(tempVertex);
						}
					}
423
				}
Anakin's avatar
Anakin committed
424
				else	// this shouldn't happen (polygon with less then 3 vertex)
425
426
427
428
429
430
431
				{
					deleteVectors();
					MessageBox(NULL, "You have polygons with less then 3 vertices!", "MeshViewer 2.0 Error", MB_OK | MB_ICONERROR);
					return;
				}
			}
		}
Anakin's avatar
Anakin committed
432
433
	}

434
	// fill the buffer
435
	glBindBuffer(GL_ARRAY_BUFFER, gluiVertexBufferID);
Anakin's avatar
Anakin committed
436
437
	glBufferData(
		GL_ARRAY_BUFFER,
438
		sizeof(Vertex) * tempBufferData.size(),
439
		tempBufferData.data(),
Anakin's avatar
Anakin committed
440
441
		GL_STATIC_DRAW
	);
Anakin's avatar
Anakin committed
442
	glBindBuffer(GL_ARRAY_BUFFER, 0);
Anakin's avatar
Anakin committed
443

444

Anakin's avatar
Anakin committed
445
446
	// get textures path
	std::string tempPath = path;
447

Anakin's avatar
Anakin committed
448
449
	while (tempPath.back() != '/' && tempPath.back() != '\\')
		tempPath.pop_back();
450

Anakin's avatar
Anakin committed
451
452
453
454
	// load all textures;
	for (auto& texIt : tempTexList)
	{
		textureData* tempData = new textureData;
455

Anakin's avatar
Anakin committed
456
457
458
		try
		{
			TextureTGA tempTex(std::string(tempPath + texIt).c_str());
459

Anakin's avatar
Anakin committed
460
461
462
			tempData->alpha = tempTex.hasAlpha();
			tempData->width = tempTex.getWidth();
			tempData->height = tempTex.getHeight();
463
			tempData->data = tempTex.getData();
Anakin's avatar
Anakin committed
464
		}
Anakin's avatar
Anakin committed
465
466
467
468
469
470
471
472
473
		catch (std::invalid_argument e)
		{
			tempData->alpha = true;
			tempData->width = 1;
			tempData->height = 1;
			tempData->data = new std::vector<std::uint8_t>({ 0, 0, 255, 255 });
		}

		vTextures.push_back(tempData);
474
	}
Anakin's avatar
Anakin committed
475
476
477
478
479
480
481
482
483
484

	// add a solid default color at the end (maybe there is an invalid index later)
	textureData* tempData = new textureData;
	tempData->alpha = true;
	tempData->width = 1;
	tempData->height = 1;
	tempData->data = new std::vector<std::uint8_t>({ 0, 0, 255, 255 });
	vTextures.push_back(tempData);

	tempTexList.clear();
485
}