I have a problem, i'm using glut (the openGL utility toolkit). I'm making a subwindow in a mainwindow. The mainwindow displays a simple figure and the subwindow displays the figure from another view. The figure rotates so the mainwindow and the subwindow should always be redisplayed.
But only one of the two displays the rotating figure. So when I start the program the figure in the mainwindow rotates but in the subwindow it don't rotate, it just stands still.
When I move my mouse in the subwindow and press any key the roles changes so the figure rotates in the subwindow and stands still in the mainwindow.
How can I let them both display simultaneous. I followed the tutorial from Lighthouse, but it didn't give me an answer.
Do I have to do something with my viewport?
* GLUT Shapes Demo
*
* Written by Nigel Stewart November 2003
*
* This program is test harness for the sphere, cone
* and torus shapes in GLUT.
*
* Spinning wireframe and smooth shaded shapes are
* displayed until the ESC or q key is pressed. The
* number of geometry stacks and slices can be adjusted
* using the + and - keys.
*/
#include <windows.h>
#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include <math.h>
#include <stdlib.h>
static int slices = 16;
static int stacks = 16;
int m=0;
int mainWindow,SubWindow, SubWindow2;
/* GLUT callback Handlers */
static void resize(int width, int height)
{
const float ar = (float) width / (float) height;
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-10,10,-10,10,-10,10);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity() ;
}
static void key(unsigned char key, int x, int y)
{
switch (key)
{
case 27 :
case 'q':
exit(0);
break;
case '+':
slices++;
stacks++;
break;
case '-':
if (slices>3 && stacks>3)
{
slices--;
stacks--;
}
break;
}
//glutPostRedisplay();
}
void keyp(int key, int xx, int yy) {
glutSetWindow(mainWindow);
glutPostRedisplay();
}
void displaysub()
{const double t = glutGet(GLUT_ELAPSED_TIME) / 1000.0;
const double a = t*90.0;
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
glClearColor(20,1,1,1);
glLoadIdentity();
glOrtho(-5,5,-5,5,-5,5);
glColor3f(0,0,0);
glRotated(a,0,0,10);
glPushMatrix();
glTranslated(0,0,0);
glutSolidSphere(2,10,10);
glPopMatrix();
glutSwapBuffers();
}
void display()
{const double t = glutGet(GLUT_ELAPSED_TIME) / 1000.0;
const double a = t*90.0;
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
glClearColor(3,0,0,1);
glLoadIdentity();
glOrtho(-10,10,-10,10,-10,10);
glRotated(a,10,10,0);
displaysub();
}
static void idle(void)
{
glutPostRedisplay();
}
/* Program entry point */
void init()
{
glClearColor(3,0,0,1);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
// register callbacks
glutIgnoreKeyRepeat(1);
glutKeyboardFunc(key);
glutSpecialFunc(keyp);
}
int main(int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitWindowSize(640,480);
glutInitWindowPosition(10,10);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
mainWindow = glutCreateWindow("GLUT Shapes");
glutSetWindow(mainWindow);
glClearColor(3,0,0,1);
glutDisplayFunc(display);
init();
SubWindow = glutCreateSubWindow(mainWindow,0,0,50,50);
glutSetWindow(SubWindow);
glClearColor(3,0,0,1);
glutDisplayFunc(displaysub);
init();
glutIdleFunc(idle);
glutMainLoop();
return 1;
}
The documentation on glutPostRedisplay specifies that only the display func of the current window will be called. In this case there are two windows. I am not an expert using glut but I would suggest two changes
Remove displaysub() from the display() function and rewrite idle()
static void idle()
{
int currentWindow = glutGetWindow();
glutSetWindw(mainWindow);
glutPostRedisplay();
glutSetWindw(subWindow);
glutPostRedisplay();
glutSetWindow(currentWindow);
}
glutPostRedisplay just marks the window for update in the main loop, which I guess is the one with mouse focus. By doing a post for each window independent of the current window all windows will receive their respective display calls
Related
how do I get my C++ glut project to have smooth input?
the only way I could get input was with a slight delay, which is annoying. I am new to C++ glut so pls help me.
#include <windows.h>
#include <GL/glut.h>
#include <GL/glu.h>
#include <stdio.h>
#include <iostream>
GLboolean upPressed = false;
using namespace std;
void display();
void reshape(int,int);
void timer(int);
void keyboard_callback(int, int, int);
void SpecialKeysUp(int, int, int);
void update();
void init()
{
glClearColor(0.0, 0.0, 0.0, 0.0);
}
int main(int argc, char**argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
glutInitWindowPosition(200, 100);
glutInitWindowSize(500, 500);
glutCreateWindow("window");
glutSpecialFunc(keyboard_callback);
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutTimerFunc(0,timer,0);
glutSpecialUpFunc(SpecialKeysUp);
glutIdleFunc(update);
init();
glutMainLoop();
}
// sy is the first squares y position. no x value needed since the x value is static.
// also note that the "s" in sy stands for square, squarey_position
float x_position = 0.0;
float sy_position = -4.0;
int state = 1;
char input;
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
glBegin(GL_QUADS);
glColor3f(1.0,0.0,0.0);
glVertex2f(x_position,1.0);
glVertex2f(x_position,-1.0);
glVertex2f(x_position+2.0,-1.0);
glVertex2f(x_position+2.0,1.0);
glColor3f(1.0,0.0,0.0);
glVertex2f(-8.0,sy_position);
glVertex2f(-9.0,sy_position);
glVertex2f(-9.0,sy_position+8.0);
glVertex2f(-8.0,sy_position+8.0);
glEnd();
glutSwapBuffers();
}
void reshape(int w,int h)
{
glViewport(0,0,(GLsizei)w,(GLsizei)h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-10, 10, -10, 10);
glMatrixMode(GL_MODELVIEW);
}
void timer(int)
{
glutPostRedisplay();
glutTimerFunc(1000/60,timer,0);
switch(state)
{
case 1:
if(x_position<8)
x_position+=0.15;
else
state = -1;
break;
case -1:
if(x_position>-10)
x_position-=0.15;
else
state=1;
break;
}
}
void keyboard_callback(int key, int, int)
{
if(GLUT_KEY_UP == key)
upPressed = true;
}
void SpecialKeysUp(int key, int, int)
{
if(GLUT_KEY_UP == key)
upPressed = false;
}
void update()
{
// glutPostRedisplay();
// glutTimerFunc(1000/60,update,0);
if(upPressed)
sy_position+=0.15;
}
It is a ping pong game and currently the ball is working fine, however I am trying to get smooth input for the rectangle but the only way I could was with input delay.
I am new to glut C++ so pls help me
Actually I figured out how to do it. The glutTimerFunc updates and resets every 1000/60 milliseconds so valuing a bool at "true" whilst the up key is pressed(with GLUT_KEY_UP) and then valuing a bool at "false" when the key is not pressed(with the SpecialUpFunc) makes for smoother input since the update function resets must faster than just holding the key down.
I've checked every other related question on this site but none of the solutions have worked for me. I'm simply trying to follow my rectangle, which moves left and right with key presses in OpenGL. Here's my very simple program:
/*Begin useful backend functions/vars*/
/*************************************/
//Window size and refresh rate (60 fps)
int width = 500;
int height = 500;
int interval = 1000 / 60;
//Used to draw rectangles
void drawRect(float x, float y, float width, float height) {
glBegin(GL_QUADS);
glVertex2f(x, y);
glVertex2f(x + width, y);
glVertex2f(x + width, y + height);
glVertex2f(x, y + height);
glEnd();
}
/***********************************/
/*End useful backend functions/vars*/
/*Game vars*/
/***********/
//keycodes
#define keyA 0x41
#define keyD 0x44
//player
int playerWidth = 30;
int playerHeight = 50;
int playerSpeed = 3;
//player starting position
float playerX = width / 2;
float playerY = 25.0f;
/***************/
/*End game vars*/
/*Game specific functions*/
/*************************/
void keyboard() {
//Move player (and camera) on key presses
if (GetAsyncKeyState(keyA)) {
playerX -= playerSpeed;
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(-playerSpeed,0,0);
}
if (GetAsyncKeyState(keyD)) {
playerX += playerSpeed;
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(playerSpeed, 0, 0);
}
}
/********************/
/*End game functions*/
/*Draw and update for window*/
/****************************/
void draw() {
//Initialliy clear
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
//Draw player
drawRect(playerX, playerY, playerWidth, playerHeight);
//Swap buffers to end
glutSwapBuffers();
}
void update(int value) {
// input handling
keyboard();
// Call update() again in 'interval' milliseconds
glutTimerFunc(interval, update, 0);
// Redisplay frame
glutPostRedisplay();
}
/*****************/
/*End draw/update*/
/*Main function*/
/***************/
int main(int argc, char** argv) {
// initialize opengl (via glut)
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(width, height);
glutCreateWindow("My Game");
// Register callback functions
glutDisplayFunc(draw);
glutTimerFunc(interval, update, 0);
// setup scene to be 2d
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, width, 0, height);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
//set draw color to white
glColor3f(1.0f, 1.0f, 1.0f);
//start the whole thing
glutMainLoop();
return 0;
}
/*************/
/*End of main*/
The keyboard movement works perfectly, however:
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(-playerSpeed,0,0);
inside my keyboard() function, does nothing. And if I try it with GL_PROJECTION, it turns my screen black.
First of all note, that drawing by glBegin/glEnd sequences and the fixed function matrix stack is deprecated since decades. See Fixed Function Pipeline and Legacy OpenGL.
Simplify things.
Add a the keyboard events for key up and down (glutKeyboardFunc / glutKeyboardUpFunc). This functions only modifies the speed of the player. The speed is set when a button is pressed and is set 0, when a button is release:
int playerSpeed = 0;
void keyboardDown(unsigned char key, int x, int y)
{
if (key == 'a')
playerSpeed -= 3;
else if (key == 'd')
playerSpeed = 3;
}
void keyboardUp( unsigned char key, int x, int y )
{
playerSpeed = 0;
}
The timer event just modifies the position of the player:
void update(int value)
{
playerX += playerSpeed;
glutTimerFunc(interval, update, 0);
glutPostRedisplay();
}
In draw the model matrix is set and the rectangle is drawn:
void draw()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(playerX, playerY, 0);
//Draw player
drawRect(0, 0, playerWidth, playerHeight);
//Swap buffers to end
glutSwapBuffers();
}
Set the callback functions in main:
int main(int argc, char** argv)
{
// ...
glutDisplayFunc(draw);
glutTimerFunc(interval, update, 0);
glutKeyboardFunc( keyboardDown );
glutKeyboardUpFunc( keyboardUp );
// ...
}
I'm trying to use GLUT and OpenGL to draw a triangle that will change its z-coordinates based off a user input. I can't get it working though; no compiler errors, but the triangle doesn't change when I press those keys. Does anyone know why?
/////////////////////////////
/////OPENGL ASSIGNMENT 1/////
/////////////////////////////
#include <iostream>
#include <stdlib.h> //Needed for "exit" function
#include <GL/glut.h>
using namespace std;
/////GLOBAL VARIABLES/////
float zCoord = -10.0;
////Function Declarations/////
void initRendering();
void windowResize(int width, int height);
void keyBoardEvents(unsigned char key, int x, int y); ///this is the function that will use user input
void drawing(); /// Note: this is the function we will use to draw shapes using opengl functions
////Function Definitions/////
void initRendering()
{
glEnable(GL_DEPTH_TEST);
}
void windowResize(int width, int height)
{
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0, (double) width/ (double) height, 1.0, 200.0); ////Note: 45.0 is the camera angle, w/h is the aspect ratio///
}
void keyBoardEvents(unsigned char key, int x, int y)
{
switch (key)
{
case 27: exit(0);
break;
case 'w': zCoord = zCoord + 5.0f;
break;
case 's': zCoord = zCoord - 5.0f;
break;
case 'r': zCoord = -5.0f;
break;
}
if (zCoord < -30.0) ////// here we ensure -5.0 > zCoord > -30.0
{
zCoord = 30.0;
}
else if (zCoord > -5.0)
{
zCoord = -5.0;
}
}
void drawing()
{
//Standard OpenGL at the beginning of each drawing() function:
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
///Specifically to this one, drawing the rectangle:
glBegin(GL_TRIANGLES); ////here we say start grouping the next 3 statements as 3 vertices of a triangle
glVertex3f(-0.5f, 0.5f, (float)zCoord);
glVertex3f(-1.0f, 1.5f, (float)zCoord);
glVertex3f(-1.5f, 0.5f, (float)zCoord);
glEnd;
glutSwapBuffers();
}
int main(int argc, char** argv) ////here we are passing some initial arguments to main, that the user does not have to input
{
glutInit(&argc, argv);
glutInitDisplayMode( GLUT_DEPTH | GLUT_RGB | GLUT_DOUBLE ); ///initiates things like depth (DEPTH) and color (RGB)/////
glutInitWindowSize(400, 400); /////the initial window size
glutCreateWindow("MentorAssignment_1"); /////here we using an OpenGL function to make a window of title MentorAssignment_1
initRendering();
//////HANDLER FUNCTIONS///// ////These are functions that call other functions, like keyBoardEvents and drawing, every time glutMainLoop() runs
glutKeyboardFunc(keyBoardEvents);
glutDisplayFunc(drawing);
glutReshapeFunc(windowResize);
glutMainLoop(); ///The openGL function that ensures main runs infinitely! (until escape is pressed)
return 0;
}
You're missing parentheses after glEnd, which means you're not calling the function, just taking its address. Issuing a buffer swap after a glBegin() can likely put OpenGL in error state and cause it to ignore all further rendering commands. The net effect would be the triangle seems not to move, simply because it's no longer redrawn.
You need to call glutPostRedisplay() at the end of your keyBoardEvents function to indicate to GLUT that the frame should be redrawn.
I am fairly new to using GLUT, and I have been attempting to compile a program (which I found here, first response) that uses the mouse to draw a rectangle by recording the starting and ending points of a click-and-drag.
As a clean copy/paste, it will compile but not draw anything. It just displays a white screen, even after changing the background color to black (in the setup() function). I've read several sources to verify that this program doesn't miss anything in its draw and reshape functions, and it's all there.
I create a window, set the viewport to the window dimensions, and then use the gluOrtho2D function to set the mapping (since the window and viewport are the same dimensions, I set the mapping to the window dimensions). The mouse callback records where I left-click, and where I release left-click, then calls the glutPostRedisplay() function to redraw the window with the new coordinates. After a bit of debugging, I discovered the coordinates are recorded and saved appropriately, and are measured in pixels (x and y are integers between 0 and window dimension), so I should be able to draw a rectangle from one vertex to the other vertex using the coordinates. But, like I said, it only displays a white screen.
So, is there something wrong with the way I am drawing the rectangle? Am I mapping the window incorrectly? I am seriously lost, and any feedback would be greatly appreciated.
EDIT2: I changed the glutInitDisplayMode from GLUT_SINGLE to GLUT_DOUBLE, and that fixed the whole non-interactive white screen thing. Now it will draw a rectangle with the mouse with a flipped y-coordinate (which I fixed), and it works great now. Thank you very much for the suggestion.
Here is my program (EDIT1: added comments):
#include <cstdlib>
#include <GL/glut.h>
using namespace std;
GLsizei width, height;
struct Position
{
Position() : x(0), y(0) {}
float x;
float y;
};
Position start; // Records left-click location
Position finish; // Records left-click release location
void display()
{
glClear(GL_COLOR_BUFFER_BIT); // clear window
glColor3ub(rand()%256, rand()%256, rand()%256); // generates random color
glBegin(GL_QUADS);
glVertex2f(start.x,start.y);
glVertex2f(finish.x,start.y);
glVertex2f(finish.x,finish.y);
glVertex2f(start.x,finish.y);
glEnd();
glutSwapBuffers(); // display newly drawn image in window
}
void reshape( int w, int h )
{
glViewport( 0, 0, (GLsizei)w, (GLsizei)h ); // set to size of window
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluOrtho2D( 0.0, (float)w, 0.0, (float)h );
width = w; // records width globally
height = h; // records height globally
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void mouse(int button, int state, int x, int y)
{
switch(button)
{
case GLUT_LEFT_BUTTON:
if(state==GLUT_DOWN)
{
start.x = x; //x1
start.y = y; //y1
}
if(state==GLUT_UP)
{
finish.x = x; //x2
finish.y = y; //y2
}
break;
glutPostRedisplay();
}
}
void motion( int x, int y )
{
finish.x = x;
finish.y = y;
glutPostRedisplay();
}
void setup()
{
glClearColor(0.0, 0.0, 0.0, 1.0); // *should* display black background
}
int main(int argc, char** argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);
glutInitWindowSize(640,480);
glutInitWindowPosition(100,100);
glutCreateWindow("");
setup();
// initializing callbacks
glutReshapeFunc(reshape);
glutDisplayFunc(display);
glutMouseFunc(mouse);
glutMotionFunc(motion);
glutMainLoop();
return 0;
}
As my comment suggested:
change:
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
to:
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);
I'm new to OpenGL and I'm trying to paint a stickman and then move it using the arrow-keys from the keyboard.
My idea was to use global variables for the stickman and to change them when a certain key is pressed. Afterwards the draw-function (myDisplay()) is called again.
Unfortunately i always get the following error-message:
"Error 10 error C2371: 'myDisplay' : redefinition; different basic types "
When I replace the myDisplay()-call in the keyboard-function with glutPostRedisplay() as suggested in some tutorials I read the error message disapears and the build is successful. But the stickman doesn't move when pressing the keys.
Here's my code:
#include <GL/glut.h>
GLint x; GLint y; GLint d; //parameters for the stickman
void myKeyboard(unsigned char key, int mx, int my) {
int x1 = mx;
int y1 = 480 - my;
switch(key){
case GLUT_KEY_LEFT :
x = x-50;
myDisplay();
break;
case 'E' :
exit(-1);
break;
default:
break;
}
}
void stickman () {
glBegin(GL_LINES); //body
glVertex2i(x, y);
glVertex2i(x, y-2*d);
glVertex2i(x-d, y-d);
glVertex2i(x+d, y-d);
glVertex2i(x, y-2*d);
glVertex2i(x-d, y-3*d);
glVertex2i(x, y-2*d);
glVertex2i(x+d, y-3*d);
glEnd();
glBegin(GL_LINE_LOOP); //head
glVertex2i(x,y);
glVertex2i(x+0.5*d, y);
glVertex2i(x+0.5*d, y+0.5*d);
glVertex2i(x-0.5*d, y+0.5*d);
glVertex2i(x-0.5*d, y);
glEnd();
}
void myDisplay() {
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0, 0.0, 0.0);
stickman();
glFlush();
}
void myInit() {
glClearColor(1.0, 1.0, 1.0, 1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 640.0, 0.0, 480.0);
}
void main(int argc, char** argv) {
x = 320;
y = 350;
d = 100;
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(640, 480);
glutInitWindowPosition(200, 50);
glutCreateWindow("Stickman");
glutDisplayFunc(myDisplay);
glutKeyboardFunc(myKeyboard);
glutPostRedisplay();
myInit();
glutMainLoop();
}
As I found out (GLUT Keyboard Tutorial) the problem wasn't the repaint of the picture, but rather that the left arrow key wasn't recognized.
I needed to write another keyboard-function for my special keys such as the arrow keys.
Now my code looks like this and it works:
void processNormalKeys (unsigned char key, int mx, int my) {
if (key == 'E')
exit(-1);
}
void processSpecialKeys (int key, int mx, int my) {
switch(key){
case GLUT_KEY_LEFT :
x = x-5;
glutPostRedisplay();
break;
case GLUT_KEY_RIGHT :
x = x+5;
glutPostRedisplay();
break;
case GLUT_KEY_UP :
y = y+5;
glutPostRedisplay();
break;
case GLUT_KEY_DOWN :
y = y-5;
glutPostRedisplay();
break;
default:
break;
}
}
I also had to adjust the main function:
glutKeyboardFunc(processNormalKeys);
glutSpecialFunc(processSpecialKeys);
But thanks for your help anyways!
glutPostRedisplay() is used to tell mark that the current window needs to be redisplayed as said in the documentation. That means that you need to call this function at the end of your myKeyboard function.
I will also recommend you to use double or tripple buffer to avoid undesired results. For double buffer you need to change glutInitDisplayMode( GLUT_SINGLE | GLUT_RGB ); with glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGB ); and then at the end of your display function you need to add glutSwapBuffers();. You can find more info here http://www.swiftless.com/tutorials/opengl/smooth_rotation.html.