OpenGL renderer with ImGui and SDL2 - c++

I'm trying to use all 3 libraries or whatnot but i'm quite confused by the sample code and I can't quite follow the documentation. This is the code and ill explain my confusions below:
#include <iostream>
#include <string>
#include <SDL2/SDL.h>
#include <GL/glew.h>
#include <imgui/imgui.h>
#include <imgui/imgui_stdlib.h>
#include <imgui/imgui_impl_sdl.h>
#include <imgui/imgui_impl_opengl3.h>
// Main code
int main(int argc, char* argv[])
{
if (SDL_Init(SDL_INIT_VIDEO) != 0)
{
std::cout << SDL_GetError() << std::endl;
return -1;
}
// GL 3.0 + GLSL 130
const char* glsl_version = "#version 130";
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, 0);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
// Create window with graphics context
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI);
SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+OpenGL3 example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags);
SDL_GLContext gl_context = SDL_GL_CreateContext(window);
SDL_GL_MakeCurrent(window, gl_context);
SDL_GL_SetSwapInterval(0); // Disable vsync
if (glewInit() != GLEW_OK) {
std::cout << "Error initializing glew\n";
}
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
//io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
// Setup Dear ImGui style
ImGui::StyleColorsDark();
//ImGui::StyleColorsClassic();
// Setup Platform/Renderer backends
ImGui_ImplSDL2_InitForOpenGL(window, gl_context);
ImGui_ImplOpenGL3_Init(glsl_version);
ImFont* font = io.Fonts->AddFontFromFileTTF("C:\\Windows\\Fonts\\Arial.ttf", 30.0f);
ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
// Main loop
bool running = false;
SDL_Event event;
while (!running)
{
while (SDL_PollEvent(&event))
{
ImGui_ImplSDL2_ProcessEvent(&event);
if (event.type == SDL_QUIT)
running = true;
if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_CLOSE && event.window.windowID == SDL_GetWindowID(window))
running = true;
}
// Start the Dear ImGui frame
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplSDL2_NewFrame(window);
ImGui::NewFrame();
{
static std::string buf = "";
ImGui::PushFont(font);
ImGui::Begin("Window");
ImGui::InputText("Hello", &buf);
//std::cout << io.Fonts->Fonts.size() << std::endl;
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
ImGui::End();
ImGui::PopFont();
}
// Rendering
glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y);
glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w);
glClear(GL_COLOR_BUFFER_BIT);
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
SDL_GL_SwapWindow(window);
}
// Cleanup
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplSDL2_Shutdown();
ImGui::DestroyContext();
SDL_GL_DeleteContext(gl_context);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
There are a few confusions I have here, starting with there being no SDL_Renderer anywhere within the code. I notice that the display draw color is handled by OpenGL, but the rendering is called via glClear(GL_COLOR_BUFFER_BIT); (I THINK). I'm unsure, though, how I could actually then call any SDL2 functions such as SDL_RenderFillRect() with no SDL_Renderer ? My best hint is this line:
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
SDL_GL_SwapWindow(window);
where its SDL_GL_SwapWindow() but this I believe just also renders for the OpenGL? I'm not really sure what line out of all the rending actually does what. I mean I would have thought ImGui::Render() would render all ImGui things, but then theres an ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); and then I'm not sure how the SDL_GL_SwapWindow ties in since i've already called glClear(). Additionally, why is there a function called ImGui::EndFrame() but not called in the sample code at the end of a frame and then there is ImGui::NewFrame() for each loop and same for ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplSDL2_NewFrame(window); Can someone please explain some of these things its very confusing.

SDL_Renderer is something you need if you want to use the SDL API for drawing tasks, but it is not required if you just create the OpenGL context with SDL and do all the drawing directly with OpenGL.
but the rendering is called via glClear(GL_COLOR_BUFFER_BIT);
No, glClearclearse part of the current render buffer, in this case, the color (What is the purpose of GL_COLOR_BUFFER_BIT and GL_DEPTH_BUFFER_BIT?
)
SDL_GL_SwapWindow(window); brings the contents of the current render buffer (the rendering) to the window SDL_GL_SwapWindow
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); invokes he drawing of the ImGUI components.

Related

imGUI + VTK using the VS2019, it doesn't appear on the screen

I made sample code using the imGUI & VTK in visual studio 2019.
refference sites : https://github.com/trlsmax/imgui-vtk & https://github.com/ocornut/imgui
VTK version : 9.2(latest version)
I'm doing with VTK viewer in imGUI. But, I faced on the problems as below.
======
code
#pragma once
////#include <vtkAutoInit.h>
////
////#define vtkRederingCore_AUTOINIT 3(vtkRenderingOpenGL2, vtkInteractionStyle, vtkRenderingFreeType)
////#define vtkRenderingContext2D_AUTOINIT 1(vtkRenderingContextOpenGL2)
#include <vtkAutoInit.h>
#define vtkRenderingCore_AUTOINIT 3(vtkRenderingOpenGL2,vtkInteractionStyle, vtkRenderingFreeType)
#define vtkRenderingContext2D_AUTOINIT 1(vtkRenderingContextOpenGL2)
#include <vtkActor.h>
#include <vtkCylinderSource.h>
#include <vtkSmartPointer.h>
#include <vtkContourFilter.h>
#include <vtkMath.h>
#include <vtkNamedColors.h>
#include <vtkPointData.h>
#include <vtkPolyDataMapper.h>
#include <vtkProperty.h>
#include <vtkShortArray.h>
#include <vtkStructuredPoints.h>
static vtkSmartPointer<vtkActor> SetupDemoCylinder()
{
auto colors = vtkSmartPointer<vtkNamedColors>::New();
// Set the background color.
std::array<unsigned char, 4> bkg{ {26, 51, 102, 255} };
colors->SetColor("BkgColor", bkg.data());
// This creates a polygonal cylinder model with eight circumferential facets
// (i.e, in practice an octagonal prism).
auto cylinder = vtkSmartPointer<vtkCylinderSource>::New();
cylinder->SetResolution(8);
// The mapper is responsible for pushing the geometry into the graphics
// library. It may also do color mapping, if scalars or other attributes are
// defined.
auto cylinderMapper = vtkSmartPointer<vtkPolyDataMapper>::New();
cylinderMapper->SetInputConnection(cylinder->GetOutputPort());
// The actor is a grouping mechanism: besides the geometry (mapper), it
// also has a property, transformation matrix, and/or texture map.
// Here we set its color and rotate it around the X and Y axes.
auto cylinderActor = vtkSmartPointer<vtkActor>::New();
cylinderActor->SetMapper(cylinderMapper);
cylinderActor->GetProperty()->SetColor(colors->GetColor4d("Tomato").GetData());
cylinderActor->RotateX(30.0);
cylinderActor->RotateY(-45.0);
return cylinderActor;
}
main.cpp
auto actor = SetupDemoCylinder();
// Setup window
glfwSetErrorCallback(glfw_error_callback);
if (!glfwInit()) {
return 1;
}
// Use GL 3.2 (All Platforms)
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
// Decide GLSL version
#ifdef __APPLE__
// GLSL 150
const char* glsl_version = "#version 150";
#else
// GLSL 130
const char* glsl_version = "#version 130";
#endif
// Create window with graphics context
GLFWwindow* window = glfwCreateWindow(1280, 720, "Dear ImGui VTKViewer Example", NULL, NULL);
if (window == NULL) {
return 1;
}
glfwMakeContextCurrent(window);
glfwSwapInterval(1); // Enable vsync
// Initialize OpenGL loader
if (gl3wInit() != 0) {
fprintf(stderr, "Failed to initialize OpenGL loader!\n");
return 1;
}
// Setup Dear ImGui context
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking
io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows'
// Setup Dear ImGui style
ImGui::StyleColorsDark();
// Setup Platform/Renderer backends
ImGui_ImplGlfw_InitForOpenGL(window, true);
ImGui_ImplOpenGL3_Init(glsl_version);
// Initialize VtkViewer objects
VtkViewer vtkViewer1;
vtkViewer1.addActor(actor);
VtkViewer vtkViewer2;
vtkViewer2.addActor(actor);
vtkViewer2.getRenderer()->SetBackground(0, 0, 0); // Black background
// Our state
bool show_demo_window = true;
bool show_another_window = false;
bool vtk_2_open = true;
ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
// Main loop
while (!glfwWindowShouldClose(window))
{
// 4. Show a simple VtkViewer Instance (Always Open)
ImGui::SetNextWindowSize(ImVec2(360, 240), ImGuiCond_FirstUseEver);
ImGui::Begin("Vtk Viewer 1", nullptr, VtkViewer::NoScrollFlags());
vtkViewer1.render(); // default render size = ImGui::GetContentRegionAvail()
ImGui::End();
// 5. Show a more complex VtkViewer Instance (Closable, Widgets in Window)
ImGui::SetNextWindowSize(ImVec2(720, 480), ImGuiCond_FirstUseEver);
if (vtk_2_open) {
ImGui::Begin("Vtk Viewer 2", &vtk_2_open, VtkViewer::NoScrollFlags());
// Other widgets can be placed in the same window as the VTKViewer
// However, since the VTKViewer is rendered to size ImGui::GetContentRegionAvail(),
// it is best to put all widgets first (i.e., render the VTKViewer last).
// If you want the VTKViewer to be at the top of a window, you can manually calculate
// and define its size, accounting for the space taken up by other widgets
auto renderer = vtkViewer2.getRenderer();
if (ImGui::Button("VTK Background: Black")) {
renderer->SetBackground(0, 0, 0);
}
ImGui::SameLine();
if (ImGui::Button("VTK Background: Red")) {
renderer->SetBackground(1, 0, 0);
}
ImGui::SameLine();
if (ImGui::Button("VTK Background: Green")) {
renderer->SetBackground(0, 1, 0);
}
ImGui::SameLine();
if (ImGui::Button("VTK Background: Blue")) {
renderer->SetBackground(0, 0, 1);
}
static float vtk2BkgAlpha = 0.2f;
ImGui::SliderFloat("Background Alpha", &vtk2BkgAlpha, 0.0f, 1.0f);
renderer->SetBackgroundAlpha(vtk2BkgAlpha);
vtkViewer2.render();
ImGui::End();
}
ImGui::Render();
int display_w, display_h;
glfwGetFramebufferSize(window, &display_w, &display_h);
glViewport(0, 0, display_w, display_h);
glClear(GL_COLOR_BUFFER_BIT);
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
// Update and Render additional Platform Windows
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
{
GLFWwindow* backup_current_context = glfwGetCurrentContext();
ImGui::UpdatePlatformWindows();
ImGui::RenderPlatformWindowsDefault();
glfwMakeContextCurrent(backup_current_context);
}
glfwSwapBuffers(window);
}
======
I attaced the code
enter image description here
I want to solve the ploblem.

How to avoid high GPU usage when calling SDL_GL_SwapWindow when using an OpenGL context?

I'm getting a strange behaviour where the GPU usage gets very high and sometimes just stays below 2%.
Right now I'm using an OpenGL context to make draw calls, you can see the code I'm using to reproduce this bug right here:
#include <GL/glew.h>
#include <SDL2/SDL.h>
#include <string>
static const int DEFAULT_WINDOW_WIDTH = 1280;
static const int DEFAULT_WINDOW_HEIGHT = 720;
int main() {
SDL_Init(SDL_INIT_VIDEO);
#ifdef __APPLE__
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS,
SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
#endif
SDL_SetHint(SDL_HINT_RENDER_DRIVER, "opengl");
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_Window *window =
SDL_CreateWindow(nullptr, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
DEFAULT_WINDOW_WIDTH, DEFAULT_WINDOW_HEIGHT,
SDL_WINDOW_OPENGL | SDL_WINDOW_ALLOW_HIGHDPI);
SDL_GLContext glcontext = SDL_GL_CreateContext(window);
glewExperimental = GL_TRUE;
glewInit();
SDL_GL_MakeCurrent(window, glcontext);
SDL_GL_SetSwapInterval(1);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
SDL_Event event;
bool quit = false;
while (!quit) {
while (SDL_PollEvent(&event)) {
quit = SDL_QUIT == event.type;
}
SDL_GL_SwapWindow(window);
}
SDL_GL_DeleteContext(glcontext);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
I isolated this down to just the SDL_GL_SwapWindow call, if you look at the screenshot you can see it's taking 26% of GPU usage just on its own. This is random, if I wait a couple of hours and come back de GPU usage will be around 2%.
I closed all other applications and processes to check this is not happening when other apps are open.
I tried switching GLEW and SDL for GLAD and GLFW and I still get the same result. All this is in macos catalina 10.15.7
Is this normal?

glew causes screen to flicker between red and black. glad works

I'm doing my programming on MacOS 10.14.3 that has support for OpenGL 4.1.
I'm using glfw for the ui and glew for the extensions detection.
this is the my code so far:
#include <iostream>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
const GLint WIDTH = 800, HEIGHT = 600;
int main() {
if (!glfwInit()) {
std::cout << "GLFW initialisation Failed";
glfwTerminate();
return 1;
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR,4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR,1);
// Core profile = No Backwards Compatibility
glfwWindowHint(GLFW_OPENGL_PROFILE,GLFW_OPENGL_CORE_PROFILE);
// Allow forward compatibility
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT,GL_TRUE);
GLFWwindow *mainWindow = glfwCreateWindow(WIDTH, HEIGHT, "Test Window", nullptr, nullptr);
if (!mainWindow) {
std::cout << "GLFW window creation Failed!";
glfwTerminate();
return 1;
}
// get buffer size information
int bufferWidth, bufferHeight;
glfwGetFramebufferSize(mainWindow,&bufferWidth,&bufferHeight);
// Set context for GLEW to use
glfwMakeContextCurrent(mainWindow);
// Allow modern extension features
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK) {
std::cout << "GLEW initialisation Failed!";
glfwDestroyWindow(mainWindow);
glfwTerminate();
return 1;
}
// Setup viewport size
glViewport(0,0,bufferWidth,bufferHeight);
while(!glfwWindowShouldClose(mainWindow)) {
// Get + handle user input events
glfwPollEvents();
// Clear window
glClearColor(1.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glfwSwapBuffers(mainWindow);
}
return 0;
}
this should be a basic started for an opengl application. it should init glfw and glew and paint the screen in red, and on top of that I can add my opengl drawing/rendering functions.
when I execute it instead of seeing a window with a red background color, the background color flickers between red and black.
any ideas why?
update
it appears that the screen flickers between black and red even if I choose a different color with glClearColor.
starting to think maybe glew isn't working properly.. i'll move back to glad and seee if there is any difference.
update 2
replaced glew with glad by removed glew code, generating glad code using the web interface, then included glad.h and added glad.c to compilation, and initialised glad with:
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
ok now that works properly... but I want to use glew... what may be the problem that's causing this ?

OpenGL cannot draw with glVertexAttrib in core profile

I want to use OpenGL 3.1.
I'm using a Macbook Pro with 2 graphic cards: NVIDIA GeForce GT 650M 1024 MB, and Intel HD Graphics 4000 1536 MB. They both support up to OpenGL 4.1.
Previously i was able to draw a triangle however, my program was using version 2.1. Therefore I added: SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);. However, now the triangle is no longer drawn.
#include <string>
#include <iostream>
#include <SDL2/SDL.h>
#define GL3_PROTOTYPES 1
#include "../include/GL3/gl3.h"
int main(int argc, const char *argv[]) {
// Initialize the SDL
if(SDL_Init(SDL_INIT_VIDEO) < 0) {
std::cout << "Failed to initialize the SDL: " << SDL_GetError() << std::endl;
SDL_Quit();
return -1;
}
// Configure the SDL to use OpenGL 3.1
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 1);
// ======= HERE =======
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
// ====================
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
SDL_Window* window = SDL_CreateWindow("Triangle Test", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);
if (window == 0) {
std::cout << "Error when creating the window: " << SDL_GetError() << std::endl;
SDL_Quit();
return -1;
}
// Create the OpenGL context
SDL_GLContext contextOpenGL = SDL_GL_CreateContext(window);
// Initialization may fail
if (contextOpenGL == 0) {
std::cout << SDL_GetError() << std::endl;
SDL_DestroyWindow(window);
SDL_Quit();
return -1;
}
SDL_Event events;
bool end = false;
// Define the vertices of our triangle
static const GLfloat vertices[] = {0.0, 1.0, // left point
-0.5, 0.0, // right point
0.5, 0.0}; // upper point
const int TRIANGLE_IDX = 0;
while(!end) {
SDL_WaitEvent(&events);
if(events.window.event == SDL_WINDOWEVENT_CLOSE) {
end = true;
}
// Clear the screen
glClear(GL_COLOR_BUFFER_BIT);
// Send vertices to OpenGL
glVertexAttribPointer(TRIANGLE_IDX, 2, GL_FLOAT, GL_FALSE, 0, vertices);
// Activate our vertex array
glEnableVertexAttribArray(TRIANGLE_IDX);
// Draw the points passed previously
glDrawArrays(GL_TRIANGLES, 0, 3);
glDisableVertexAttribArray(TRIANGLE_IDX);
// Refresh the screen
SDL_GL_SwapWindow(window);
}
return 0;
}
I tried to first use glGenBuffers, glBindBuffer and glBufferData but i could not manage to make it work.
The Fixed Function Pipeline has been removed from core OpenGL 3.1 and above.
You will have to use shaders instead. This site has a nice example of how to use them.

Using SDL and openGL drawing primitives does not work

I tried to do some basic stuff like a gameloop and drawing with OpenGL by following a tutorial. In that tutorial SDL 1.2 is used but I am using 2.0 so I had to replace some old functions with the new versions.
Unfortunately the lines I want to draw don't show up.
I already tried playing with the numbers so that the line is not outside the window but it did not work.
#include "SDL.h"
#include "SDL_opengl.h"
#include <iostream>
int main(int argc, char* args[])
{
//initialize SDL
SDL_Init(SDL_INIT_EVERYTHING);
//Set openGL memory usage
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_BUFFER_SIZE, 32);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_Window *window;
window=SDL_CreateWindow("MyWindow",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
600,400,
SDL_WINDOW_OPENGL);
SDL_Renderer *renderer;
renderer = SDL_CreateRenderer(window,-1,SDL_RENDERER_ACCELERATED);
SDL_SetRenderDrawColor(renderer,255,255,255,255);//RGB/ALPHA
glShadeModel(GL_SMOOTH);
//2D rendering
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
//Disable depth checking
glDisable(GL_DEPTH_TEST);
std::cout<<"OpenGL is running\n";
std::cout<<"Main loop has started\n";
//Handle GameLoop
bool isRunning=true;
//Handel events
SDL_Event event;
//main gameloop
while(isRunning)
{
//Events
while(SDL_PollEvent(&event))
{
if(event.type==SDL_QUIT)
isRunning=false;
//if esc button is released
if(event.type==SDL_KEYUP&&event.key.keysym.sym==SDLK_ESCAPE)
isRunning=false;
if(event.type==SDL_KEYUP&&event.key.keysym.sym==SDLK_r)
SDL_SetRenderDrawColor(renderer,255,0,0,255);
//Logic for certain events
}
//Logic
//Rendering
SDL_RenderClear(renderer);
SDL_RenderPresent(renderer);
glPushMatrix();
glOrtho(0,600,400,0,-1,1); //Set matrix
glBegin(GL_LINES);//start drawing
glColor4ub(255,0,0,255);
glVertex2i(0,0);
glVertex2i(600,400);
glEnd();// end drawing
glPopMatrix();
SDL_GL_SwapWindow(window);
}
SDL_Quit();
return 0;
}
Don't mix SDL_Renderer code and OpenGL. There's no provision (yet, maybe ever) in SDL2 for resetting Renderer GL state (if it's using the GL backend) that you trample with raw GL code.
First, don't mix OpenGL and the SDL_Renderer stuff. Then you actually need to create an OpenGL context for your window before rendering can work. Use this after your SDL_CreateWindow call:
SDL_GLContext glcontext = SDL_GL_CreateContext(window);
At the end you need to free the context:
SDL_GL_DeleteContext(glcontext);