I am unable to understand why I am not getting any output for the given program. This problem has been occurring to me for my last 2 openGL programs, the previous one being DDA algorithm, again in which I didnt get any output. Is there a problem with the algorithm, or in my understanding how openGL works internally ?
#include <iostream>
#include <GL/glut.h>
using namespace std;
float X1 = 0, X2 = 100, Y1 = 0, Y2 = 400, X11, Y11, X22, Y22, slope, dely, delx, c, intercept, pi;
float absl(float x) {
if (x >= 0) return x;
return -1*x;
}
void drawScene() {
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, 500, 0, 500);
glClearColor(1.0, 1.0, 1.0, 0);
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 0.0, 0.0);
//start bresenham algo
glBegin(GL_POINTS);
glVertex2f(X1, Y1);
while(X1 <= X2) {
X1++;
if(pi < 0) {
glVertex2f(X1, Y1);
}
else {
Y1++;
glVertex2f(X1, Y1);
}
float flag = (pi >= 0);
pi = pi + 2*dely - 2*delx*flag;
}
glEnd();
//end DDA algo
glFlush();
}
int main(int argc, char **argv) {
//cin >> X1 >> Y1 >> X2 >> Y2;
// dely = Y2 - Y1;
// delx = X2 - X1;
// pi = 2*dely - delx;
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(500, 500);
glutInitWindowPosition(0,0);
glutCreateWindow("DDA");
glutDisplayFunc(drawScene);
glutMainLoop();
return 0;
}
gluOrtho2D defines a 2D orthographic projection matrix. But it also multiplies the current matrix on the matrix stack with the orthographic projection matrix and replaces the current matrix with the product.
Note, in OpenGL fixed function pipeline all matrix operations work like this (except glPushMatrix, glPopMatrix, glLoadMatrix and glLoadIdentity).
This means you have to replace the current matrix with the identity matrix (glLoadIdentity), befor you apply the orthographic projection matrix:
glLoadIdentity();
gluOrtho2D(0, 500, 0, 500);
Or you do gluOrtho2D only one time before you start the main loop in the main function:
gluOrtho2D(0, 500, 0, 500);
glutMainLoop();
Since the display function is called (drawScene) continuously, you should use local control varibales and not modify X1 and Y1:
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, 500, 0, 500);
glClearColor(0.0, 0.0, 0.0, 0);
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 0.0, 0.0);
//start bresenham algo
int x = X1, y = Y1;
glBegin(GL_LINES);
glVertex2f(100, 400);
glVertex2f(400, 100);
glEnd();
glBegin(GL_POINTS);
glVertex2f(x, Y1);
while(x <= X2) {
x ++;
if(pi < 0) {
glVertex2f(x, y);
}
else {
y ++
glVertex2f(x, y);
}
}
int flag = (pi >= 0);
pi = pi + 2*dely - 2*delx*flag;
glEnd();
Related
I've got a taks from university and have to make a small example of solar system, the objects have to rotate etc. The problem is that when I do not call GluLookAt() everything looks fine, but I would like to change the view and when I call the function, there occurs that one orbit renders completely strangely.
I do not know if problem is with wrong creation of the first orbit, or with the proper values in gluLookAt parameters. Can anyone help?
Here's how it looks without calling gluLookAt():
Here's how it looks after gluLookAt():
Here's the code:
#include "stdafx.h"
#include <GL\glut.h>
#include <math.h>
GLfloat yRotated=1;
GLfloat movement = 0;
void drawCircle(float r) { // radius
glBegin(GL_LINE_LOOP);
for (int i = 0; i <= 300; i++) {
double angle = 2 * 3.14 * i / 300;
double x = r*cos(angle);
double y = r*sin(angle);
glVertex3d(x, y, -5.5);
}
glEnd();
}
void display(void) {
glMatrixMode(GL_MODELVIEW);
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
//gluLookAt(5, 5, 5, 0, 0, -8, 0, 1, 0); // 3rd coordinate - depth
float radius1 = 6;
float radius2 = 1;
//first orbit
glColor3f(1, 1, 1);
glPushMatrix();
glTranslatef(0, 0, -5.5);
drawCircle(radius1);
glPopMatrix();
//second orbit with rotation
glPushMatrix();
glRotatef(yRotated, 0, 0, 1);
glPushMatrix();
glTranslatef(radius1 / 2, 0, 0);
drawCircle(radius2);
glPopMatrix();
glPopMatrix();
//first czajnik
glColor3f(0.8, 0.2, 0.1);
glPushMatrix();
glTranslatef(0.0, 0.0, -5.5);
// glScalef(1.0, 1.0, 1.0);
glRotatef(yRotated, 0, 0, 1);
glRotatef(90, 1, 0, 0);
glutSolidSphere(1,20,20);
//second czajnik
glPushMatrix();
glColor3f(0, 0, 1);
glTranslatef(radius1/2, 0, 0);
glRotatef(yRotated, 0, 1, 0);
glutSolidSphere(0.5, 20, 20);
//third czajnik
glPushMatrix();
glTranslatef(radius2, 0, 0);
glColor3f(1, 1, 0);
glRotatef(yRotated, 0, 1, 0);
glutSolidSphere(0.2, 20, 20);
glPopMatrix();
//second czajnik pop
glPopMatrix();
//first czajnik pop
glPopMatrix();
glFlush();
}
void idle() {
yRotated += 0.1;
Sleep(2);
display();
}
void myReshape(int w, int h) {
if (w == 0 || h == 0) return;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(70.0, (GLdouble)w / (GLdouble)h, 0.5, 20.0);
glViewport(0, 0, w, h);
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(900, 600);
glutCreateWindow("Solar system");
//window with a title
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glClearColor(0, 0, 0, 1.0);
glutDisplayFunc(display);
glutReshapeFunc(myReshape);
glutIdleFunc(idle);
glutMainLoop();
return 0;
}
Some of your objects are at different z values, e.g. 1st orbit at -5.5, second at 0, because you "popped" the matrix.
In general, do not do so many push\pops nested into each other, matrix stack isn't made of rubber.
There is more efficient circle drawing procedure than to calculate sine and cosine for each step, e.g. to get advantage of circle being a figure of rotation:
inline void circle(F32 r, U32 quality)
{
if (r < F_ALMOST_ZERO) return;
F32 th = M_PI /(quality-1);
F32 s = sinf(th);
F32 c = cosf(th);
F32 t;
F32 x = r;
F32 y = 0;
::glBegin (GL_LINE_LOOP);
for(U32 i = 0; i < quality; i++)
{
glVertex2f(x, y);
t = x;
x = c*x + s*y;
y = -s*t + c*y;
}
::glEnd();
}
it can be optimized further by using symmetry, but this one is the basis.
I don't know if I did something wrong in my functions (maybe wrong parameters to glOrtho) and so the result is just wrong or if it's all normal as it would be.
In particular I have this situation:
I would like to have the green rect and all its inner content to take all the space of the window and not just a part of it (if you notice there are some empty spaces all around the main content: "the green rect").
Here there are my main functions:
#define HEXAGONAL_SHRINK 0.8655f
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(640, 480);
glutInitWindowPosition(100, 100);
glutCreateWindow(argv[0]);
glClearColor (0.0, 0.0, 0.0, 0.0);
glShadeModel (GL_FLAT);
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMouseFunc(mouse);
glutMainLoop();
return 0;
}
void reshape(int w, int h)
{
GLfloat aspect, dim;
glViewport (0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if (s3hex->rows > s3hex->columns)
dim = s3hex->rows * 0.5f;
else
dim = s3hex->columns * 0.5f;
aspect = (GLfloat)w / (GLfloat)h;
if (w <= h)
glOrtho (-dim, dim, -dim/aspect, dim/aspect, 1.0, -1.0);
else
glOrtho (-dim*aspect, dim*aspect, -dim, dim, 1.0, -1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void display(void)
{
CALint i, j;
CALreal z, h, color;
glClear(GL_COLOR_BUFFER_BIT);
glPushMatrix();
glTranslatef(-(s3hex->columns*HEXAGONAL_SHRINK)/2.0f, s3hex->rows/2.0f, 0);
glScalef(HEXAGONAL_SHRINK, -1, 1);
for (i=0; i<s3hex->rows; i++)
for (j=0; j<s3hex->columns; j++)
{
z = calGet2Dr(s3hex,Q.z,i,j);
h = calGet2Dr(s3hex,Q.h,i,j);
if (h > 0)
{
color = (h - h_min) / (h_Max - h_min);
glColor3d(1,color,0);
glRecti(j, i, j+1, i+1);
}
else
if (z > 0)
{
color = (z - z_min) / (z_Max - z_min);
glColor3d(color,color,color);
glRecti(j, i, j+1, i+1);
}
}
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glColor3d(0,1,0);
glRectd(0,0,s3hex->columns, s3hex->rows);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glPopMatrix();
glutSwapBuffers();
}
P.S: If you need to know what's s3hex is, then you can see it as a normal matrix in which every cell contains a set of substates. Then in according to the value of these substates I set the colors for the rendering in the display func.
Everything seems normal to me.
Nothing guaranties that s3hex->columns and s3hex->rows will match your viewport size.
What you can do is to scale up the modelview to make the drawing fill your viewport.
Something along the lines of:
glScalef(viewportWidth / s3hex->columns, viewportHeight / s3hex->rows, 1);
Don't do this if s3hex->columns or s3hex->rows is zero.
I am working on an nbody simulator and I want to display it with OpenGL. I want to always be looking at the centre of mass reference frame. I have the following code. I calculate the COM and I set the center coordinate in the gluLookAt function to be the center of mass. I then subtract the "zoom" from the z coordinate to get the eye position. By logic this should ensure that I am always looking at whatever value the center of mass is. The only issue is that I marked where the center of mass should be on the screen with a red dot and it is moving. Shouldn't it never move if I am always looking at it from the same relative position? Here is my code. Focus on the display function since I assume that is where the error will be. I had similar code working in another project and I can't really find any differences.
#include "Universe.cuh"
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "timer.hpp"
#include <GL/glut.h>
Universe u;
float* vbuf;
double angle = 0.0, zoom = 1000;
void display()
{
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
float3 c = u.getCenterOfMass();
gluLookAt(c.x, c.y, c.z - zoom, c.x, c.y, c.z, 0, 1, 0);
glScalef(0.1, 0.1, 0.1);
glRotated(angle, 1, 0, 0);
glColor4f(1, 1, 1, 0.25);
glBegin(GL_POINTS);
{
glColor3f(1.0, 0.0, 0.0);
glVertex3d(c.x, c.y, c.z);
}
glEnd();
glutSwapBuffers();
}
void reshape(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60, (double)w / (double)h, 1.0, zoom * 1e9);
glMatrixMode(GL_MODELVIEW);
}
void copy_to_vbuf()
{
for(int i = 0; i < u.size(); i++)
{
vbuf[3 * i + 0] = u.getObjects()[i].p.x;
vbuf[3 * i + 1] = u.getObjects()[i].p.y;
vbuf[3 * i + 2] = u.getObjects()[i].p.z;
}
}
void keyboard(unsigned char c, int x, int y)
{
if(c == 'w')
angle += 1;
else if(c == 's')
angle -= 1;
else if(c == '=')
zoom /= 1.2;
else if(c == '-')
zoom *= 1.2;
glutPostRedisplay();
}
void idle()
{
u.timeStep();
copy_to_vbuf();
glutPostRedisplay();
}
int main(int argc, char** argv)
{
cudaSetDevice(0);
srand(time(0));
u.getConfiguration().max_velocity = 10;
u.getConfiguration().softening_factor = 0.01;
u.getConfiguration().threshold_angle = 35;
u.getConfiguration().time_step = 0.1;
const int N = 5;
vbuf = new float[3 * N];
for(int i = 0; i < N; i++)
{
Object o;
o.m = rand() % 100 + 1;
o.p.x = 500.0 * rand() / RAND_MAX - 250.0;
o.p.y = 500.0 * rand() / RAND_MAX - 250.0;
o.p.z = 500.0 * rand() / RAND_MAX - 250.0;
u.addObject(o);
}
copy_to_vbuf();
glutInit(&argc, argv);
glutInitDisplayMode(GL_DOUBLE);
glutInitWindowSize(1000, 1000);
glutCreateWindow("N-Body");
glutReshapeFunc(reshape);
glutDisplayFunc(display);
glutIdleFunc(idle);
glutKeyboardFunc(keyboard);
glEnable(GL_POINT_SMOOTH);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glPointSize(1.0);
glutMainLoop();
return 0;
}
Two points regarding:
glScalef(0.1, 0.1, 0.1);
glRotated(angle, 1, 0, 0);
Since your axis is not centered on the 'COM', when you apply rotation the COM point will not stay in place and logically would move around the screen.
AFIK the normal order is scale,rotate,translate for transformations. This will apply the rotation and then scale.
EDIT:
To expand on that: Currently you take an arbitrary point rotate it, scale it and then focus on the point where it used to be. If you want to rotate your model (e.g. point marking the 'COM') around itself, it needs to be centered at (0,0,0).
this is my cube. Once created, it has a random x position on either -2, -1, 0, 1, or 2.
void cube(void)
{
srand (time(0));
int cube_posX;
int lowv = -2;
int highv = 2;
cube_posX = rand() % (highv - lowv + 1) + lowv;
glTranslatef(cube_posX, 0.0, cube_angle);
glRotatef(cube_angle, 90.0, 0.0, 1.0);
glutSolidCube(0.25);
}
and this is how I move the cube slowly forward
void MOVE_CUBE(int value)
{
cube_posZ = cube_posZ - 0.01;
glutPostRedisplay();
glutTimerFunc(25, MOVE_CUBE, 0);
}
and finally putting them in display:
void init(void)
{
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
}
float cam_eyeX = 0.0, cam_eyeY = 1.5, cam_eyeZ = 5.0;
float cam_centerX = 0.0, cam_centerY = 0.0, cam_centerZ = 0.0;
void display(void)
{
glClearColor(1.0,1.0,1.0,1.0); //to add background color (white)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
gluLookAt(cam_eyeX, cam_eyeY, cam_eyeZ, cam_centerX, cam_centerY, cam_centerZ, 0.0, 1.0, 0.0); //camera! (cam position X, cam position Y, cam position Z, cam target X, cam target Y, cam target Z, up position X, up position Y, up position Z)
cube();
glutSwapBuffers();
angle += 0.05; //to affect the glRotate function
glFlush();
}
void reshape(int w, int h)
{
glViewport (0, 0, (GLsizei)w, (GLsizei)h);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
gluPerspective (60, (GLfloat)w / (GLfloat)h, 1.0, 100.0);
glMatrixMode (GL_MODELVIEW);
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH); // Set up display buffer
glutInitWindowSize(750, 500); //window's size
glutInitWindowPosition(100, 100); //window's position
glutCreateWindow("Hendra Ganteng!"); //window's title
init();
glutDisplayFunc(display);
glutIdleFunc (display);
glutReshapeFunc(reshape);
glutKeyboardFunc(keyboard_Handler);
MOVE_CUBE(0);
glutMainLoop();
return 0;
}
But when I see it in action, the cube moves forward flawlessly, but keeps changing x position onto those 5 possibilities (-2,-1,0,1,2) every 0.5 to 1 second. If I disable the srand(time(0)), the cube changes its x position rapidly. I just want to make it stay in 1 x position so then I can call more cubes in different x position. Could someone please kindly what's wrong in my code?
How is that behaviour not expected? You are generating a random X position every time you display your cube. If you re-seed the random number generator using the time, then it will be start a different sequence whenever the time changes (once per second).
Instead, you should pre-generate your cube(s). How about this:
// Global cube data
struct Cube {
int x;
double angle;
};
vector<Cube> cubes;
const int num_cubes = 1;
// Example initialisation...
void InitCubes()
{
cubes.reserve(num_cubes);
for( int i = 0; i < num_cubes; i++ )
{
Cube cube;
cube.x = rand() % (highv - lowv + 1) + lowv;
cube.angle = 0.0;
cubes.push_back(cube);
}
}
Now the update/display cycles simply need to modify the angle, but not the x-position.
void UpdateCube( Cube & cube )
{
cube.angle += 0.05;
}
void DisplayCube( Cube & cube )
{
glTranslatef((double)cube.x, 0.0, cube.angle);
glRotatef(cube.angle, 90.0, 0.0, 1.0);
glutSolidCube(0.25);
}
In your main function, call InitCubes() during startup.
In your display function, do this:
void display(void)
{
glClearColor(1.0,1.0,1.0,1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
gluLookAt(cam_eyeX, cam_eyeY, cam_eyeZ, cam_centerX, cam_centerY, cam_centerZ, 0.0, 1.0, 0.0);
// Display cubes
for( int i = 0; i < cubes.size(); i++ ) DisplayCube( cubes[i] );
glutSwapBuffers();
glFlush();
// Update cubes for next render cycle.
for( int i = 0; i < cubes.size(); i++ ) UpdateCube( cubes[i] );
}
The issue is that the further the mouse click is from the top left origin (0,0) the greater the height inaccuracy when the vertex is plotted. Any ideas?
int WindowWidth = 19;
int WindowHeight = 13;
int mouseClickCount = 0;
int rectPlotted;
GLint x1;
GLint y1;
GLint x2;
GLint y2;
//Declare our functions with prototypes:
void display(void);
void init (void);
void processNormalKeys(unsigned char key, int x, int y);
void on_vertex_selected(GLint x, GLint y);
void on_mouse_event(int button, int state, int x, int y);
/////////////////////////////////// MAIN ////////////////////////////////
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
//start calculation of max window size available at 19:13 aspect ratio
int screenWidth = glutGet(GLUT_SCREEN_WIDTH);
int screenHeight = glutGet(GLUT_SCREEN_HEIGHT);
screenWidth = screenWidth/WindowWidth;
WindowWidth = WindowWidth*screenWidth;
screenHeight = screenHeight/WindowHeight;
WindowHeight = screenHeight*WindowHeight;
//end calculation
glutInitWindowSize (WindowWidth, WindowHeight);
glutInitWindowPosition (0, 0);
glutCreateWindow ("Plot a rectangle!");
glutDisplayFunc(display);
glutKeyboardFunc(processNormalKeys);
glutMouseFunc(on_mouse_event);
init();
glutMainLoop();
return 0;
}
/////////////////////////////////////////////////////////////////////////
void display(void)
{
glClear (GL_COLOR_BUFFER_BIT); //clear all pixels
glFlush();
}
void init (void)
{
/* select clearing (background) color */
glClearColor (1.0, 1.0, 1.0, 0.0);
/* initialize viewing values */
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, WindowWidth, 0, WindowHeight, -1.0, 1.0);
}
void processNormalKeys(unsigned char key, int x, int y) {
if (key == 27) //esc
exit(0);
//Allows color change of most recently plotted rectangle
if (key == 98){ //b
glColor3f(0.0, 0.0, 1.0);
glBegin(GL_QUADS);
glVertex2i(x1, y1);
glVertex2i(x1, y2);
glVertex2i(x2, y2);
glVertex2i(x2, y1);
glEnd();
glFlush();
}
if (key == 114){ //r
glColor3f(1.0, 0.0, 0.0);
glBegin(GL_QUADS);
glVertex2i(x1, y1);
glVertex2i(x1, y2);
glVertex2i(x2, y2);
glVertex2i(x2, y1);
glEnd();
glFlush();
}
if (key == 103){ //g
glColor3f(0.0, 1.0, 0.0);
glBegin(GL_QUADS);
glVertex2i(x1, y1);
glVertex2i(x1, y2);
glVertex2i(x2, y2);
glVertex2i(x2, y1);
glEnd();
glFlush();
}
}
void on_vertex_selected(GLint x, GLint y){
if(mouseClickCount == 0){
x1 = x;
y1 = y;
glColor3f(0.0, 0.0, 0.0);
glEnable(GL_POINT_SMOOTH);
glPointSize(5.0);
glBegin(GL_POINTS);
glVertex2i(x1, y1);
glEnd();
glFlush();
}
else{
x2 = x;
y2 = y;
glBegin(GL_POINTS);
glColor3f(1.0, 1.0, 1.0);
glVertex2i(x1,y1); //"clears" previous point to make way for the rectangle
glEnd();
glColor3f(0.0, 0.0, 0.0);
glBegin(GL_QUADS);
glVertex2i(x1, y1);
glVertex2i(x1, y2);
glVertex2i(x2, y2);
glVertex2i(x2, y1);
glEnd();
glFlush();
}
}
void on_mouse_event(int button, int state, int x, int y){
if(button==GLUT_LEFT_BUTTON && state ==GLUT_DOWN && mouseClickCount == 0){
//y = y+20; //adjusts for VM mouse tracking error
on_vertex_selected(x, WindowHeight - y);
rectPlotted = 0;
}
if(button==GLUT_LEFT_BUTTON && state ==GLUT_UP && mouseClickCount == 0){
if(rectPlotted == 1){
return;
}
else{
mouseClickCount++;
}
}
if(button==GLUT_LEFT_BUTTON && state ==GLUT_DOWN && mouseClickCount == 1){
//y = y+20; //adjusts for VM mouse tracking error
on_vertex_selected(x, WindowHeight - y);
mouseClickCount = 0;
rectPlotted = 1;
}
}
Your glOrtho() call is almost certainly wrong. You pass the window size, not the window client area size. The difference is the size of the borders and the height of the caption.
Be aware that your actual window size will most probably be slightly different than what you asked at init time.
Simply said, implement a glutReshapeFunc()
I was compiling and running my code within Parallels VM v.6. This was the issue leading to inaccurate mouse coordinates being returned. I compiled and ran the exact same code on OS X without problem.