CSCI441 OpenGL Library 5.13.0
CS@Mines CSCI441 Computer Graphics Course Library
Loading...
Searching...
No Matches
OpenGLEngine.hpp
Go to the documentation of this file.
1
12#ifndef CSCI441_OPENGL_ENGINE_HPP
13#define CSCI441_OPENGL_ENGINE_HPP
14
15#include "OpenGLUtils.hpp"
16
17#ifdef CSCI441_USE_GLEW
18 #include <GL/glew.h>
19#else
20 #include <glad/gl.h>
21#endif
22
23#include <GLFW/glfw3.h>
24
25#include <cstdio>
26#include <cstring>
27#include <set>
28#include <string>
29
30namespace CSCI441 {
31
40 public:
44 OpenGLEngine(const OpenGLEngine&) = delete;
49
53 OpenGLEngine(OpenGLEngine&&) noexcept;
58 OpenGLEngine& operator=(OpenGLEngine&&) noexcept;
59
64 virtual ~OpenGLEngine();
65
73 virtual void initialize();
77 virtual void run() = 0;
85 virtual void shutdown();
86
91 [[maybe_unused]] virtual void turnDebuggingOn() noexcept final { DEBUG = true; }
96 virtual void turnDebuggingOff() noexcept final { DEBUG = false; }
100 [[maybe_unused]] [[nodiscard]] virtual bool isDebuggingEnabled() const noexcept final { return DEBUG; }
101
107 [[maybe_unused]] [[nodiscard]] virtual bool isExtensionEnabled(const std::string EXT) const noexcept final { return _extensions.find(EXT) != _extensions.end(); }
108
117 virtual void setCurrentWindowSize(const int WINDOW_WIDTH, const int WINDOW_HEIGHT) final { mWindowWidth = WINDOW_WIDTH; mWindowHeight = WINDOW_HEIGHT; }
121 [[maybe_unused]] [[nodiscard]] virtual int getWindowHeight() const noexcept final { return mWindowHeight; }
125 [[maybe_unused]] [[nodiscard]] virtual int getWindowWidth() const noexcept final { return mWindowWidth; }
129 [[maybe_unused]] [[nodiscard]] virtual GLFWwindow* getWindow() const noexcept final { return mpWindow; }
130
134 [[maybe_unused]] virtual void setWindowShouldClose() final { glfwSetWindowShouldClose(mpWindow, GLFW_TRUE); }
135
139 [[nodiscard]] virtual unsigned short getError() noexcept final {
140 const unsigned short storedErrorCode = mErrorCode; // store current error code
141 mErrorCode = OPENGL_ENGINE_ERROR_NO_ERROR; // reset error code
142 return storedErrorCode; // return previously stored error code
143 }
144
148 static constexpr unsigned short OPENGL_ENGINE_ERROR_NO_ERROR = 0;
152 static constexpr unsigned short OPENGL_ENGINE_ERROR_GLFW_INIT = 1;
156 static constexpr unsigned short OPENGL_ENGINE_ERROR_GLFW_WINDOW = 2;
160 static constexpr unsigned short OPENGL_ENGINE_ERROR_GLEW_INIT = 3;
164 static constexpr unsigned short OPENGL_ENGINE_ERROR_GLAD_INIT = 4;
168 static constexpr unsigned short OPENGL_ENGINE_ERROR_UNKNOWN = 5;
169 // note to developers: if more error codes are added, need to update LAST accordingly or
170 // update UNKNOWN to the last value and shift
175 static constexpr unsigned short OPENGL_ENGINE_ERROR_LAST = OPENGL_ENGINE_ERROR_UNKNOWN;
179 [[maybe_unused]] static constexpr unsigned short OPENGL_ENGINE_ERROR_SIZE = OPENGL_ENGINE_ERROR_LAST + 1;
180
181 protected:
193 OpenGLEngine(int OPENGL_MAJOR_VERSION, int OPENGL_MINOR_VERSION, int WINDOW_WIDTH, int WINDOW_HEIGHT, const char* WINDOW_TITLE, bool WINDOW_RESIZABLE = GLFW_FALSE);
194
199 bool DEBUG;
200
204 unsigned int mErrorCode;
205
238 GLFWwindow* mpWindow;
239
246 static void mErrorCallback(const int error, const char* DESCRIPTION) { fprintf(stderr, "[ERROR]: %d\n\t%s\n", error, DESCRIPTION ); }
247
251 static void APIENTRY mDebugMessageCallback(const GLenum source, const GLenum type, const GLuint id, const GLenum severity, const GLsizei length, const GLchar* message, const void* userParam) {
252 fprintf( stdout, "[VERBOSE]: Debug Message (%d): source = %s, type = %s, severity = %s, message = %s\n",
253 id,
254 CSCI441::OpenGLUtils::debugSourceToString(source),
255 CSCI441::OpenGLUtils::debugTypeToString(type),
256 CSCI441::OpenGLUtils::debugSeverityToString(severity),
257 message
258 );
259 }
260
268 static void mWindowResizeCallback(GLFWwindow* pWindow, int width, int height);
269
289 virtual void mSetupGLFW();
296 virtual void mSetupOpenGL() = 0;
303 virtual void mSetupShaders() {};
309 virtual void mSetupBuffers() {};
315 virtual void mSetupTextures() {}
321 virtual void mSetupScene() {};
322
327 virtual void mCleanupScene() {};
332 virtual void mCleanupTextures() {}
337 virtual void mCleanupBuffers() {};
342 virtual void mCleanupShaders() {};
347 virtual void mCleanupOpenGL() {};
354 virtual void mCleanupGLFW();
355
356 virtual void mReloadShaders() final;
357
358 private:
359 void _setupGLFunctions(); // initialize OpenGL functions
360 void _cleanupGLFunctions() {} // nothing to be done at this time
361
362 void _cleanupSelf(); // delete internal memory
363 void _moveFromSource(OpenGLEngine&);// move members from another instance
364
365 bool _isInitialized; // makes initialization a singleton process
366 bool _isCleanedUp; // makes cleanup a singleton process
367
368 std::set< std::string > _extensions;// set of all available OpenGL extensions
369 };
370}
371
373 const int OPENGL_MAJOR_VERSION,
374 const int OPENGL_MINOR_VERSION,
375 const int WINDOW_WIDTH,
376 const int WINDOW_HEIGHT,
377 const char* WINDOW_TITLE,
378 const bool WINDOW_RESIZABLE
379) : DEBUG(true),
380 mErrorCode(OPENGL_ENGINE_ERROR_NO_ERROR),
381 mOpenGLMajorVersion(OPENGL_MAJOR_VERSION),
382 mOpenGLMinorVersion(OPENGL_MINOR_VERSION),
383 mWindowWidth(WINDOW_WIDTH),
384 mWindowHeight(WINDOW_HEIGHT),
385 mWindowResizable(WINDOW_RESIZABLE),
386 mWindowTitle(nullptr),
387 mpWindow(nullptr),
388 _isInitialized(false),
389 _isCleanedUp(false)
390{
391 mWindowTitle = new char[ strlen(WINDOW_TITLE) ];
392 strcpy(mWindowTitle, WINDOW_TITLE);
393}
394
397) noexcept :
398 DEBUG(true),
399 mErrorCode(OPENGL_ENGINE_ERROR_NO_ERROR),
400 mOpenGLMajorVersion(0),
401 mOpenGLMinorVersion(0),
402 mWindowWidth(0),
403 mWindowHeight(0),
404 mWindowResizable(false),
405 mWindowTitle(nullptr),
406 mpWindow(nullptr),
407 _isInitialized(false),
408 _isCleanedUp(false)
409{
410 _moveFromSource(src);
411}
412
414 if (this != &src) {
415 _cleanupSelf();
416 _moveFromSource(src);
417 }
418 return *this;
419}
420
421
423 _cleanupSelf();
424}
425
426inline void CSCI441::OpenGLEngine::_cleanupSelf() {
427 delete[] mWindowTitle;
428 mWindowTitle = nullptr;
429}
430
431inline void CSCI441::OpenGLEngine::_moveFromSource(OpenGLEngine& src) {
432 DEBUG = src.DEBUG;
433 src.DEBUG = false;
434
435 mErrorCode = src.mErrorCode;
436 src.mErrorCode = OPENGL_ENGINE_ERROR_NO_ERROR;
437
438 mOpenGLMajorVersion = src.mOpenGLMajorVersion;
439 src.mOpenGLMajorVersion = 0;
440
441 mOpenGLMinorVersion = src.mOpenGLMinorVersion;
442 src.mOpenGLMinorVersion = 0;
443
444 mWindowWidth = src.mWindowWidth;
445 src.mWindowWidth = 0;
446
447 mWindowHeight = src.mWindowHeight;
448 src.mWindowHeight = 0;
449
450 mWindowResizable = src.mWindowResizable;
451 src.mWindowResizable = false;
452
453 mWindowTitle = src.mWindowTitle;
454 src.mWindowTitle = nullptr;
455
456 mpWindow = src.mpWindow;
457 src.mpWindow = nullptr;
458
459 _isInitialized = src._isInitialized;
460 src._isInitialized = false;
461
462 _isCleanedUp = src._isCleanedUp;
463 src._isCleanedUp = false;
464
465 _extensions = std::move(src._extensions);
466}
467
469 if( !_isInitialized ) {
470 mSetupGLFW(); // initialize GLFW and set up a window
471 _setupGLFunctions(); // create OpenGL function pointers
472 mSetupOpenGL(); // create the OpenGL context
473
474 // get OpenGL context information
475 if( DEBUG ) {
476 // if wanting debug information with Version 4.3 or higher
477 if( mOpenGLMajorVersion > 4 || (mOpenGLMajorVersion == 4 && mOpenGLMinorVersion >= 3) ) {
478 // check if debug context was created
479 int flags; glGetIntegerv(GL_CONTEXT_FLAGS, &flags);
480 if (flags & GL_CONTEXT_FLAG_DEBUG_BIT) {
481 // register callback to synchronously print any debug messages without having to call glGetError()
482 glEnable(GL_DEBUG_OUTPUT);
483 glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
484 glDebugMessageCallback(mDebugMessageCallback, nullptr);
485 glDebugMessageControl( GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_TRUE );
486 }
487 }
488
489 CSCI441::OpenGLUtils::printOpenGLInfo();
490 }
491
492 mSetupShaders(); // transfer, compile, link shaders on GPU
493 mSetupBuffers(); // register Buffers on GPU
494 mSetupTextures(); // register Textures on GPU
495 mSetupScene(); // setup any scene specific information
496
497 _isInitialized = true;
498 _isCleanedUp = false;
499 if (DEBUG) fprintf(stdout, "\n[INFO]: Setup complete\n");
500 }
501}
502
504 // set what function to use when registering errors
505 // this is the ONLY GLFW function that can be called BEFORE GLFW is initialized
506 // all other GLFW calls must be performed after GLFW has been initialized
507 glfwSetErrorCallback(mErrorCallback);
508
509 // initialize GLFW
510 if( !glfwInit() ) {
511 fprintf( stderr, "[ERROR]: Could not initialize GLFW\n" );
512 mErrorCode = OPENGL_ENGINE_ERROR_GLFW_INIT;
513 } else {
514 if(DEBUG) fprintf( stdout, "[INFO]: GLFW %d.%d.%d initialized\n", GLFW_VERSION_MAJOR, GLFW_VERSION_MINOR, GLFW_VERSION_REVISION );
515
516 glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, mOpenGLMajorVersion ); // request OpenGL vX.
517 glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, mOpenGLMinorVersion ); // request OpenGL v .X
518 glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE ); // request forward compatible OpenGL context
519 glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE ); // request OpenGL Core Profile context
520 glfwWindowHint(GLFW_DOUBLEBUFFER, GLFW_TRUE ); // request double buffering
521 glfwWindowHint(GLFW_RESIZABLE, mWindowResizable ); // set if our window should be able to be resized
522
523 // if wanting debug information with Version 4.3 or higher
524 if( DEBUG
525 && (mOpenGLMajorVersion > 4 || (mOpenGLMajorVersion == 4 && mOpenGLMinorVersion >= 3)) ) {
526 glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, true); // request a debug context
527 }
528
529 // create a window for a given size, with a given title
530 mpWindow = glfwCreateWindow(mWindowWidth, mWindowHeight, mWindowTitle, nullptr, nullptr );
531 if( !mpWindow ) { // if the window could not be created, NULL is returned
532 fprintf( stderr, "[ERROR]: GLFW Window could not be created\n" );
533 glfwTerminate();
534 mErrorCode = OPENGL_ENGINE_ERROR_GLFW_WINDOW;
535 } else {
536 if(DEBUG) fprintf( stdout, "[INFO]: GLFW Window created\n" );
537 glfwMakeContextCurrent(mpWindow); // make the created window the current window
538 glfwSwapInterval(1); // update our screen after at least 1 screen refresh
539 glfwSetInputMode(mpWindow, GLFW_LOCK_KEY_MODS, GLFW_TRUE); // track state of Caps Lock and Num Lock keys
540 glfwSetWindowUserPointer(mpWindow, (void*)this);
541 glfwSetWindowSizeCallback(mpWindow, mWindowResizeCallback);
542 }
543 }
544}
545
546inline void CSCI441::OpenGLEngine::_setupGLFunctions() {
547
548#ifdef CSCI441_USE_GLEW
549 glewExperimental = GL_TRUE;
550 const GLenum glewResult = glewInit(); // initialize GLEW
551
552 // check for an error
553 if( glewResult != GLEW_OK ) {
554 fprintf( stderr, "[ERROR]: Error initializing GLEW\n");
555 fprintf( stderr, "[ERROR]: %s\n", reinterpret_cast<const char *>(glewGetErrorString(glewResult)) );
556 mErrorCode = OPENGL_ENGINE_ERROR_GLEW_INIT;
557 } else {
558 if(DEBUG) {
559 fprintf(stdout, "\n[INFO]: GLEW initialized\n");
560 fprintf(stdout, "[INFO]: Using GLEW %s\n", reinterpret_cast<const char *>(glewGetString(GLEW_VERSION)));
561 }
562 }
563#else
564 int version = gladLoadGL(glfwGetProcAddress);
565 if(version == 0) {
566 fprintf(stderr, "Failed to initialize GLAD\n" );
567 mErrorCode = OPENGL_ENGINE_ERROR_GLAD_INIT;
568 } else {
569 if(DEBUG) {
570 // Successfully loaded OpenGL
571 fprintf(stdout, "\n[INFO]: GLAD initialized\n");
572 fprintf(stdout, "[INFO]: Loaded OpenGL %d.%d\n", GLAD_VERSION_MAJOR(version), GLAD_VERSION_MINOR(version));
573 }
574 }
575#endif
576
577 if(mErrorCode == OPENGL_ENGINE_ERROR_NO_ERROR) {
578 GLint numExtensions = 0;
579 glGetIntegerv(GL_NUM_EXTENSIONS, &numExtensions);
580 for (int i = 0; i < numExtensions; i++) {
581 _extensions.insert(reinterpret_cast<const char *>(glGetStringi(GL_EXTENSIONS, i)) );
582 }
583 }
584}
585
587 if(DEBUG) fprintf( stdout, "[INFO]: ...closing window...\n" );
588 glfwDestroyWindow(mpWindow ); // close our window
589 mpWindow = nullptr;
590 if(DEBUG) fprintf( stdout, "[INFO]: ...closing GLFW.....\n" );
591 glfwTerminate();
592}
593
595 if( !_isCleanedUp ) {
596 if (DEBUG) fprintf(stdout, "\n[INFO]: Shutting down.......\n");
597 mCleanupShaders(); // delete shaders from GPU
598 mCleanupBuffers(); // delete VAOs/VBOs from GPU
599 mCleanupTextures(); // delete textures from GPU
600 mCleanupScene(); // delete scene info from CPU
601 mCleanupOpenGL(); // cleanup anything OpenGL related
602 _cleanupGLFunctions(); // cleanup anything function pointer related
603 mCleanupGLFW(); // shut down GLFW to clean up our context
604 if (DEBUG) fprintf(stdout, "[INFO]: ..shut down complete!\n");
605 _isCleanedUp = true;
606 _isInitialized = false;
607 }
608}
609
610inline void CSCI441::OpenGLEngine::mWindowResizeCallback(GLFWwindow* pWindow, const int width, const int height) {
611 const auto pEngine = static_cast<OpenGLEngine *>(glfwGetWindowUserPointer(pWindow));
612 pEngine->setCurrentWindowSize(width, height);
613}
614
615inline void CSCI441::OpenGLEngine::mReloadShaders() {
616 if (DEBUG) fprintf(stdout, "\n[INFO]: Removing old shaders...\n");
617 mCleanupShaders();
618 if (DEBUG) fprintf(stdout, "\n[INFO]: Reloading shaders...\n");
619 mSetupShaders();
620 if (DEBUG) fprintf(stdout, "\n[INFO]: Shaders reloaded\n");
621}
622
623#endif //CSCI441_OPENGL_ENGINE_HPP
Helper functions to work with OpenGL 3.0+.
Abstract Class to run an OpenGL application. The following methods must be overridden:
Definition: OpenGLEngine.hpp:39
virtual void mSetupOpenGL()=0
override to enable specific OpenGL features
virtual bool isExtensionEnabled(const std::string EXT) const noexcept final
Returns if OpenGL extension exists.
Definition: OpenGLEngine.hpp:107
bool DEBUG
if information should be printed to console while running
Definition: OpenGLEngine.hpp:199
OpenGLEngine & operator=(const OpenGLEngine &)=delete
do not allow engines to be copied
int mOpenGLMinorVersion
the minor version of the requested OpenGL context
Definition: OpenGLEngine.hpp:215
int mOpenGLMajorVersion
the major version of the requested OpenGL context
Definition: OpenGLEngine.hpp:210
static constexpr unsigned short OPENGL_ENGINE_ERROR_NO_ERROR
no error is present, everything is currently working
Definition: OpenGLEngine.hpp:148
virtual void setCurrentWindowSize(const int WINDOW_WIDTH, const int WINDOW_HEIGHT) final
Set the new window size.
Definition: OpenGLEngine.hpp:117
virtual void initialize()
Initialize everything needed for OpenGL Rendering. This includes in order: GLFW, function pointers,...
Definition: OpenGLEngine.hpp:468
virtual void shutdown()
Cleanup everything needed for OpenGL Rendering. This includes freeing memory for data used in: any Sc...
Definition: OpenGLEngine.hpp:594
virtual unsigned short getError() noexcept final
Return current value of error code and clear the error code back to no error.
Definition: OpenGLEngine.hpp:139
virtual void mSetupTextures()
override to register any textures with the GPU
Definition: OpenGLEngine.hpp:315
virtual int getWindowHeight() const noexcept final
Return the height of the window.
Definition: OpenGLEngine.hpp:121
virtual bool isDebuggingEnabled() const noexcept final
Returns if logging is enabled.
Definition: OpenGLEngine.hpp:100
static void mWindowResizeCallback(GLFWwindow *pWindow, int width, int height)
Definition: OpenGLEngine.hpp:610
static constexpr unsigned short OPENGL_ENGINE_ERROR_GLAD_INIT
an error occurred while initializing GLAD
Definition: OpenGLEngine.hpp:164
virtual void mCleanupBuffers()
override to cleanup any buffer objects from the GPU
Definition: OpenGLEngine.hpp:337
virtual void mCleanupScene()
override to cleanup any scene specific information
Definition: OpenGLEngine.hpp:327
virtual void mCleanupShaders()
override to cleanup any shaders from the GPU
Definition: OpenGLEngine.hpp:342
virtual void mCleanupTextures()
override to cleanup any textures from the GPU
Definition: OpenGLEngine.hpp:332
bool mWindowResizable
if the GLFW window can be resized while open
Definition: OpenGLEngine.hpp:230
OpenGLEngine(const OpenGLEngine &)=delete
do not allow engines to be copied
virtual void turnDebuggingOn() noexcept final
Enable logging to command line.
Definition: OpenGLEngine.hpp:91
static constexpr unsigned short OPENGL_ENGINE_ERROR_GLEW_INIT
an error occurred while initializing GLEW
Definition: OpenGLEngine.hpp:160
static constexpr unsigned short OPENGL_ENGINE_ERROR_GLFW_WINDOW
an error occurred while creating the GLFW window
Definition: OpenGLEngine.hpp:156
static void mErrorCallback(const int error, const char *DESCRIPTION)
We will register this function as GLFW's error callback. When an error within OpenGL occurs,...
Definition: OpenGLEngine.hpp:246
static constexpr unsigned short OPENGL_ENGINE_ERROR_LAST
stores the error code number of the last possible error, this corresponds to the max error code value...
Definition: OpenGLEngine.hpp:175
unsigned int mErrorCode
tracks the current status of the OpenGL engine via error codes
Definition: OpenGLEngine.hpp:204
virtual void run()=0
Initiate the draw loop.
static void APIENTRY mDebugMessageCallback(const GLenum source, const GLenum type, const GLuint id, const GLenum severity, const GLsizei length, const GLchar *message, const void *userParam)
callback called whenever a debug message is signaled
Definition: OpenGLEngine.hpp:251
char * mWindowTitle
the title of the GLFW window
Definition: OpenGLEngine.hpp:234
int mWindowHeight
the window height of the requested GLFW window
Definition: OpenGLEngine.hpp:225
virtual void setWindowShouldClose() final
Tell our engine's window to close.
Definition: OpenGLEngine.hpp:134
static constexpr unsigned short OPENGL_ENGINE_ERROR_SIZE
stores the number of unique error codes that can be generated
Definition: OpenGLEngine.hpp:179
virtual void mSetupShaders()
override to register any shaders with the GPU
Definition: OpenGLEngine.hpp:303
GLFWwindow * mpWindow
pointer to the GLFW window object
Definition: OpenGLEngine.hpp:238
virtual void turnDebuggingOff() noexcept final
Disable logging to command line.
Definition: OpenGLEngine.hpp:96
virtual int getWindowWidth() const noexcept final
Return the width of the window.
Definition: OpenGLEngine.hpp:125
virtual void mSetupBuffers()
override to register any buffer objects with the GPU
Definition: OpenGLEngine.hpp:309
virtual ~OpenGLEngine()
cleans up our OpenGL Engine by destroying the OpenGL context, GLFW window, and cleaning up all GPU re...
Definition: OpenGLEngine.hpp:422
virtual void mCleanupGLFW()
Destroys the associated GLFW window and terminates the GLFW instance.
Definition: OpenGLEngine.hpp:586
int mWindowWidth
the window width of the requested GLFW window
Definition: OpenGLEngine.hpp:220
virtual void mCleanupOpenGL()
override to cleanup any specific OpenGL features
Definition: OpenGLEngine.hpp:347
static constexpr unsigned short OPENGL_ENGINE_ERROR_GLFW_INIT
an error occurred while initializing GLFW
Definition: OpenGLEngine.hpp:152
virtual void mSetupGLFW()
Used to setup everything GLFW related. This includes the OpenGL context and our window....
Definition: OpenGLEngine.hpp:503
virtual void mSetupScene()
override to setup any scene specific information
Definition: OpenGLEngine.hpp:321
static constexpr unsigned short OPENGL_ENGINE_ERROR_UNKNOWN
a new error that does not correspond to a predefined scenario has occurred
Definition: OpenGLEngine.hpp:168
virtual GLFWwindow * getWindow() const noexcept final
Return the window object.
Definition: OpenGLEngine.hpp:129
CSCI441 Helper Functions for OpenGL.
Definition: ArcballCam.hpp:17