Draw 2D and 3D in the same OpenGL window - c

I'm creating a 3D game with OpenGL and I would like to make a toolbar in the top of the window. For that, I tried to use SDL to draw the buttons and OpenGL to draw the actual game. Here is the relevant part of my code:
void openMainWindow(){
SDL_Surface *screen;
SDL_Event event;
SDL_Rect position;
SDL_Init(SDL_INIT_VIDEO);
putenv("SDL_VIDEO_CENTERED=center");
SDL_WM_SetCaption("Example",NULL);
SDL_WM_SetIcon(IMG_Load("icon.png"),NULL);
screen = SDL_SetVideoMode(832,487,32,SDL_HWSURFACE | SDL_OPENGL);
glLoadIdentity();
gluPerspective(70,(double)832/487,1,1000);
//Some things to initialize the window
int continue = 1;
while(continue){
SDL_PollEvent(&event);
switch(event.type){
//Events
}
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBegin(GL_QUADS);
//Draw a square
glEnd();
//Draw more things the same way
glFlush();
SDL_GL_SwapBuffers();
SDL_Surface *button1 = SDL_CreateRGBSurface(SDL_HWSURFACE,50,50,32,0,0,0,0);
SDL_FillRect(button1,NULL,SDL_MapRGB(screen->format,50,50,50);
position.x = 8;
position.y = 8;
SDL_BlitSurface(button1,NULL,screen,&position);
SDL_Flip(screen);
}
SDL_Quit();
}
The problem with this is that when this function is called, the process ends and returns 3 (which means that there is an error). So I tried to draw the buttons with OpenGL like this:
void openMainWindow(){
//Everything before the while loop is the same as in the other code
int continue = 1;
while(continue){
SDL_PollEvent(&event);
switch(event.type){
//Events
}
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBegin(GL_QUADS);
//Draw a square
glEnd();
//Draw more things the same way
glDisable(GL_DEPTH_TEST);
glLoadIdentity();
glBegin(GL_QUADS); //Draw the button
glColor3ub(50,50,50);
glVertex2d(-0.5,-0.5);
glVertex2d(-0.5,0.5);
glVertex2d(0.5,0.5);
glVertex2d(0.5,-0.5);
glEnd();
glEnable(GL_DEPTH_TEST);
glFlush();
SDL_GL_SwapBuffers();
}
SDL_Quit();
}
I know that the second code should center the button in the window, but I use this code just to test if it works (and it doesn't, that's why I'm posting this question).
With the second code, the 3D things appear in the window as they should, but I can't see any button. How do I put 2D buttons in a 3D OpenGL window?

The second code works by adding the following right before drawing the 2D button:
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glDisable(GL_DEPTH_TEST);
glLoadIdentity();
and the following code right after drawing the 2D button:
glEnable(GL_DEPTH_TEST);
gluPerspective(70,(double)640/480,0.5,INFINITE); //These parameters have to be the same as the ones used for gluPerspective when initializing the 3D
gluLookAt(0,0,3,1,0,3,0,0,0.01); //Where you want to position the camera and where you want to look at
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
Here is the complete code that works:
void openMainWindow(){
//Everything before the while loop is the same as in the other code
int continue = 1;
while(continue){
SDL_PollEvent(&event);
switch(event.type){
//Events
}
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBegin(GL_QUADS);
//Draw a square
glEnd();
//Draw more things the same way
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glDisable(GL_DEPTH_TEST);
glLoadIdentity();
glBegin(GL_QUADS); //Draw the button
glColor3ub(50,50,50);
glVertex2d(-0.5,-0.5);
glVertex2d(-0.5,0.5);
glVertex2d(0.5,0.5);
glVertex2d(0.5,-0.5);
glEnd();
glEnable(GL_DEPTH_TEST);
gluPerspective(70,(double)640/480,0.5,INFINITE); //These parameters have to be the same as the ones used for gluPerspective when initializing the 3D
gluLookAt(0,0,3,1,0,3,0,0,0.01); //Where you want to position the camera and where you want to look at
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glFlush();
SDL_GL_SwapBuffers();
}
SDL_Quit();
}

Related

can't draw object in openGL

I've drawn a square in opengl in 1st window , and when I try to draw some object on second screen .I am getting a blank screen.
here is my code.
#include <GL/glut.h>
void display() {
glClearColor(1.0f, 0.0f, 0.0f, 1.0f); // Set background color to black and opaque
//glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer (background)
// Draw a Red 1x1 Square centered at origin
glBegin(GL_QUADS); // Each set of 4 vertices form a quad
glColor3f(0.0f, 1.0f, 0.0f); // Red
glVertex2f(-0.5f, -0.5f); // x, y
glVertex2f( 0.5f, -0.5f);
glVertex2f( 0.5f, 0.5f);
glVertex2f(-0.5f, 0.5f);
glEnd();
glFlush(); // Render now
}
void displayc2()
{
glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer (background)
glClearColor(1.0f, 0.0f, 0.0f, 1.0f); // Set background color to black and opaque
glBegin(GL_QUADS); // Each set of 4 vertices form a quad
glColor3f(0.0f, 1.0f, 0.0f); // green
glVertex2f(-0.5f, -0.5f); // x, y
glVertex2f( 0.5f, -0.5f);
glVertex2f( 0.5f, 0.5f);
glVertex2f(-0.5f, 0.5f);
glEnd();
}
void keycb(unsigned char key,int x , int y)
{
int win2;
if(key=='a') exit(0);
else if(key == 'b')
{
win2 = glutCreateWindow("window 2");
glutInitWindowSize(450, 450); // Set the window's initial width & height
glutInitWindowPosition(50, 50);
glutDisplayFunc(displayc2);
glutMainLoop(); // Enter the event-processing loop
}
}
int main(int argc, char** argv) {
int win1;
glutInit(&argc, argv); // Initialize GLUT
win1 = glutCreateWindow("OpenGL Setup Test"); // Create a window with the given title
glutInitWindowSize(450, 450); // Set the window's initial width & height
glutInitWindowPosition(50, 50); // Position the window's initial top-left corner
glutDisplayFunc(display); // Register display callback handler for window re-paint
glutKeyboardFunc(keycb);
glutMainLoop(); // Enter the event-processing loop
return 0;
}
What I am trying to do is , when I press the character 'b' on my keyboard , it should display a second screen . The first screen and the object are coming successfully But,here I am getting the second screen but i am not getting the object in the second screen.the second screen is blank in this case. tell me whats wrong in this code or is there any other way to acheive this ?
I am doing opengl in ubuntu 18.04 using C programming.
Some remarks to make your problem work:
before using glutDisplayFunc, you must select the window. If you have only one window, the question does not ask, but if you have two, you must call glutSetWindow(...) before.
note too that glutInitWindow... function work for the next window to be created.
glutMainLoop should be called once.
And finally, do not forget to call glFlush() at the end of display functions:
#include <GL/glut.h>
int win1, win2;
void display()
{
glClearColor(1.0f, 0.0f, 0.0f, 1.0f); // Set background color to black and opaque
glBegin(GL_QUADS); // Each set of 4 vertices form a quad
glColor3f(1.0f, 0.0f, 0.0f); // Red
glVertex2f(-0.5f, -0.5f); // x, y
glVertex2f(0.5f, -0.5f);
glVertex2f(0.5f, 0.5f);
glVertex2f(-0.5f, 0.5f);
glEnd();
glFlush(); // Render now
}
void displayc2()
{
glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer (background)
glClearColor(1.0f, 0.0f, 0.0f, 1.0f); // Set background color to black and opaque
glBegin(GL_QUADS); // Each set of 4 vertices form a quad
glColor3f(0.0f, 1.0f, 0.0f); // green
glVertex2f(-0.5f, -0.5f); // x, y
glVertex2f(0.5f, -0.5f);
glVertex2f(0.5f, 0.5f);
glVertex2f(-0.5f, 0.5f);
glEnd();
glFlush(); // Render now
}
void keycb(unsigned char key, int x, int y)
{
if (key == 'a')
exit(0);
else if (key == 'b'&&win2==0) {
glutInitWindowSize(450, 450);
glutInitWindowPosition(250, 250);
win2 = glutCreateWindow("window 2");
// Select the window for glutDisplayFunc
glutSetWindow(win2);
glutDisplayFunc(displayc2);
}
}
int main(int argc, char **argv)
{
glutInit(&argc, argv); // Initialize GLUT
glutInitWindowSize(450, 450); // Set the window's initial width & height
glutInitWindowPosition(50, 50); // Position the window's initial top-left corner
win1 = glutCreateWindow("OpenGL Setup Test"); // Create a window with the given title
glutDisplayFunc(display); // Register display callback handler for window re-paint
glutKeyboardFunc(keycb);
glutMainLoop(); // Enter the event-processing loop
return 0;
}

Where is my display function being called in GLUT?

I do not understand how this main function works. I have a display function, which uses glDrawArrays, but I do not see it being called. I only see it being used as a parameter for glutDisplayFunction.
Here is my main:
int main(int argc, char** argv){
// Set up the window
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);
glutInitWindowSize(800, 600);
glutCreateWindow("Hello Triangle");
// Tell glut where the display function is
glutDisplayFunc(display);
// A call to glewInit() must be done after glut is initialized!
GLenum res = glewInit();
// Check for any errors
if (res != GLEW_OK) {
fprintf(stderr, "Error: '%s'\n", glewGetErrorString(res));
return 1;
}
// Set up your objects and shaders
init();
// Begin infinite event loop
glutMainLoop();
return 0;
}
The problem is, I need to create two different triangles, on the same window, using seperate VAOs and VBOs. I've created the seperate VAO and VBO for my second triangle. However, I do not see how I am meant to generate and link my buffers, draw my arrays, switch to my second buffer, and draw those arrays, when I do not even know when my display function is being called.
My display function looks like this:
void display(){
glClear(GL_COLOR_BUFFER_BIT);
// NB: Make the call to draw the geometry in the currently activated vertex buffer. This is where the GPU starts to work!
glDrawArrays(GL_TRIANGLES, 0, 3);
glutSwapBuffers();
}
All operations could be done in separate function named asyouwant called from main
example:
#include <GL/glut.h>
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE);
glutInitWindowSize(300, 300);
glutInitWindowPosition(100, 100);
glutCreateWindow("Hello world :D");
glutDisplayFunc(displayMe); // = > draw in displayme function
glutMainLoop();
return 0;
}
void displayMe(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_POLYGON);
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(0.5, 0.0, 0.0);
glVertex3f(0.5, 0.5, 0.0);
glVertex3f(0.0, 0.5, 0.0);
glEnd();
// a second geoform
glBegin(GL_POLYGON);
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(-0.5, 0.0, 0.0);
glVertex3f(-0.5, -0.5, 0.0);
glVertex3f(0.0, -0.5, 0.0);
glEnd();
glFlush();
}
As complement: for VAO and buffer
1- Init (declare VAO , declare buffer of vertices, ...)
GLuint VaoID;
glGenVertexArrays(1, &VaoID);
glBindVertexArray(VaoID);
// An array of 3 vectors which represents 3 vertices
static const GLfloat g_vertex_buffer_data[] = {
-1.0f, -1.0f, 0.0f,
1.0f, -1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
};
Once time only
// This will identify our vertex buffer
GLuint vertexbuffer;
// Generate 1 buffer, put the resulting identifier in vertexbuffer
glGenBuffers(1, &vertexbuffer);
// The following commands will talk about our 'vertexbuffer' buffer
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
// Give our vertices to OpenGL.
glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);
2- Use it (bind and draw in display fucntion)
// 1st attribute buffer : vertices
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glVertexAttribPointer(
0, // attribute 0. No particular reason for 0, but must match the layout in the shader.
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
// Draw the triangle !
glDrawArrays(GL_TRIANGLES, 0, 3); // Starting from vertex 0; 3 vertices total -> 1 triangle
glDisableVertexAttribArray(0);

When I display image, I can't use colors anymore openGL

When I open and display an image in openGL, all colors on screen (except image's) suddenly turn into black and I can't use another color to draw anymore.
It's my colorful button on screen
void drawButton(int x1,int y1,int x2,int y2,int r,int g,int b)
{
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glColor3f(r,g,b);
glBegin(GL_QUADS);
glVertex2f(x1,y1);
glVertex2f(x2,y1);
glVertex2f(x2,y2);
glVertex2f(x1,y2);
glEnd();
glFlush();
glutSwapBuffers();
}
And here's display image function
void display_image(char* file_name)
{
GLuint texture_id=loadIm(file_name);
glClear(GL_COLOR_BUFFER_BIT);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture_id);
glLoadIdentity();
glColor3f(1, 1, 1);
glFrontFace(GL_CCW);
glCullFace(GL_FRONT);
glBindTexture(GL_TEXTURE_2D, texture_id);
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glBegin(GL_QUADS);
glTexCoord2f(0,1); glVertex2f(0, 0.0);
glTexCoord2f(0,0); glVertex2f(0, wh);
glTexCoord2f(1,0); glVertex2f(ww,wh);
glTexCoord2f(1,1); glVertex2f(ww, 0.0);
glEnd();
glFlush();
glutSwapBuffers();
drawArea();
}
EDIT: glDisable(GL_TEXTURE_2D)
OpenGL is a state machine. This means when one enables GL_TEXTURE_2D to draw with textures, this has to be disabled afterwards to render with colors only. Calling glDisable(GL_TEXTURE_2D); before starting to render the colored polygon should fix the problem.

glClear: RAM usage slighty increasing

Following is my little opengl program, just drawing a triangle. There is an glitch, the RAM is slightly increasing by about 10K per second the moment i add the glClear() function. Why is that so?
int screenwidth=537, screenheight=716;
GLFWwindow* window;
if (!glfwInit()) return -1;
window = glfwCreateWindow(screenwidth, screenheight, "Test", NULL, NULL);
if(!window){glfwTerminate(); return -1;}
glfwMakeContextCurrent(window);
//Setting up the OpenGL Context
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, screenwidth, screenheight, 0, 0, 1);
glDisable(GL_DEPTH_TEST);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glClearColor(1,0.9176f,0.1259f,1);
//The rendering loop
while (!glfwWindowShouldClose(window)){
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0f, 1.0f, 1.0f);
glBegin(GL_TRIANGLES);
glVertex2f(0, 0);
glVertex2f(.5f, .5f);
glVertex2f(0, .5f);
glEnd();
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS){
glfwSetWindowShouldClose(window, GL_TRUE);
}
glfwSwapBuffers(window);
glfwPollEvents();
}
Example: https://www.youtube.com/watch?v=MOxyaxuTsyI

Regarding glutReshapeFunc()

I have small code drawing a square initially but when I maximize the window it changes to rectangle. I know this has do with aspect ratio and when I add glutReshapeFunc(Reshape); call it works perfectly, I mean after maximizing the window, it remains square only. ReshapFunc is called every time display is modified and before the first display as well.
I am not getting just by adding reshapefunc, how it maintains aspect ratio. Please help me understanding this. I am copying my code here:
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.5, 0.5, 1.0);
glBegin(GL_POLYGON);
glVertex2f(-0.5, -0.5);
glVertex2f(0.5, -0.5);
glVertex2f(0.5, 0.5);
glVertex2f(-0.5, 0.5);
glEnd();
glutSwapBuffers();
glFlush();
}
void Reshape(int w, int h) {
glutPostRedisplay();
}
void init()
{
glClearColor(1.0, 0.0, 1.0, 0.0);
glColor3f(1.0, 1.0, 1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-1.0, 1.0, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
glutInitWindowSize(500, 500);
glutInitWindowPosition(200, 200);
glutCreateWindow("basics");
glutDisplayFunc(display);
// If I comment this, it will become rectangle.
glutReshapeFunc(Reshape);
init();
glutMainLoop();
}
Your problem is related to the use of gluOrtho2D (...). If you want to preserve aspect ratio, your projection matrix needs to be defined based on the dimensions of your window.
I suggest you do this in your reshape function:
GLdouble aspect = (GLdouble)w / (GLdouble)h;
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
gluOrtho2D (-1.0 * aspect, 1.0 * aspect, -1.0, 1.0);
glMatrixMode (GL_MODELVIEW);
glViewport (0, 0, w, h);

Resources