Check out the below mentioned steps:
#include <iostream>
- Here, we'll include the GLEW and SFML libraries in our project:
#include <GL/glew.h> #include <SFML/Window.hpp> const GLint WIDTH = 800, HEIGHT = 600;
In the preceding lines of code, we've defined the GLint
constant. The reason we're creating constant global variables is so that we can easily use these wherever we need them in the code, whether that's for initially creating the window or for manipulating some sort of shape.
- Next, let's define our entry point:
int main( ) { sf::ContextSettings settings; settings.depthBits = 24; settings.stencilBits = 8;
In the preceding lines of code, we've defined some settings for our application and rendering window:
settings.majorVersion = 3; settings.minorVersion = 3; settings.attributeFlags = sf::ContextSettings::Core;
Here, the majorVersion
and minorVersion
that we defined in the preceding lines of code are for setting the version of OpenGL. Here, we set the version as 3.3 by setting the minorVersion
and the majorVersion
to 3. If you wish to set up for any other version, you'll have to make changes accordingly. ThemajorVersion
is to the left of the decimal point and theminorVersion
is to the right of the decimal point. Then, we defined that we're using core modern OpenGL by settingContextSettings
toCore
.
- Next, you want to define
sf::Window
. Here, we're going to putsf::VideoMode
, and we're going to putWIDTH
,HEIGHT
, and32
for the pixel depth. Then, we'll addOpenGL SFML
as the title of our window. And then, we addsf::Style::Titlebar
andsf::Style::Close
to have a title bar and a close button for our window:
sf::Window window( sf::VideoMode( WIDTH, HEIGHT, 32 ), "OpenGL SFML", sf::Style::Titlebar | sf::Style::Close, settings );
- Now, we'll try to initialize GLEW by setting it to
TRUE
and if it's unsuccessful, then we'll display aFailed to initialize GLEW
message to the developer. And then, we're going to doreturn EXIT_FAILURE
because it has failed:
glewExperimental = GL_TRUE; if ( GLEW_OK != glewInit( ) ) { std::cout << "Failed to initialize GLEW" << std::endl; return EXIT_FAILURE; } bool running = true;
- Next, we are going to create a
while
loop and define certain conditions in it:
while ( running ) { sf::Event windowEvent; while ( window.pollEvent( windowEvent ) ) { switch ( windowEvent.type ) { case sf::Event::Closed: running = false; break; } }
In the preceding while
loop, we are stating that if the window is closed, we are going to stop running our application and break out of our loop.
glClearColor( 0.2f, 0.3f, 0.3f, 1.0f ); glClear( GL_COLOR_BUFFER_BIT ); // draw OpenGL window.display( ); } window.close( ); return EXIT_SUCCESS; } }
Let's run our code and check whether there are any errors. If no errors pop up, we'll get a rendering window as output, similar to what we have witnessed in the previous sections.