I have a code where I want to draw a bowl and two cones at a time.
But, it is showing only those cones, not showing the ball.
#include <GL/glut.h>
#include <stdlib.h>
#include <Math.h> // Needed for sin, cos
#define PI 3.14159265f
GLfloat ballRadius = 0.5f; // Radius of the bouncing ball
GLfloat ballX = 0.0f; // Ball's center (x, y) position
GLfloat ballY = 0.0f;
GLfloat ballXMax, ballXMin, ballYMax, ballYMin; // Ball's center (x, y) bounds
GLfloat xSpeed = 0.02f; // Ball's speed in x and y directions
GLfloat ySpeed = 0.007f;
int refreshMillis = 30; // Refresh period in milliseconds
static void resize(int width, int height)
{
const float ar = (float) width / (float) height;
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-ar, ar, -1.0, 1.0, 2.0, 100.0);
}
static void display(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// This is ball's code that is not being drawn.
***glTranslatef(ballX, ballY, 0.0f); // Translate to (xPos, yPos)
// Use triangular segments to form a circle
glBegin(GL_TRIANGLE_FAN);
glColor3f(1.0f, 0.0f, 0.0f); // Blue
glVertex2f(0.0f, 0.0f); // Center of circle
int numSegments = 100;
GLfloat angle;
for (int i = 0; i <= numSegments; i++) { // Last vertex same as first vertex
angle = i * 2.0f * PI / numSegments; // 360 deg for all segments
glVertex2f(cos(angle) * ballRadius, sin(angle) * ballRadius);
}
glEnd();***
//End of ball code
glColor3d(0,1,0);
glPushMatrix();
glTranslated(-1.0,0.5,-6);
glRotated(65, -1.0, 0.0, 0.0);
glutSolidCone(1, 2, 70, 50);
glPopMatrix();
glPushMatrix();
glTranslated(0.0,-1.5,-6);
glRotated(65, -1.0, 3.0, 0.0);
glutWireCone(1,2, 16, 16);
glPopMatrix();
glutSwapBuffers();
}
/* Program entry point */
int main(int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitWindowSize(740,580);
glutInitWindowPosition(10,10);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("Programming Techniques - 3D Cones");
glutReshapeFunc(resize);
glutDisplayFunc(display);
glClearColor(1,1,1,1);
glutMainLoop();
return EXIT_SUCCESS;
}
The reason you don't see the circle is that it's clipped against the near plane. With glFrustum(-ar, ar, -1.0, 1.0, 2.0, 100.0); you specify that the near plane is at z = -2, and the far plane at z = -100. Anything outside these values are clipped. But by using glVertex2, your z values for the circle vertices are 0, so all of them are clipped. You can fix it by calling glTranslatef(ballX, ballY, -10.0f); instead.
A couple more pointers:
Always reset the matrix mode to GL_MODELVIEW (e.g. in your resize() function). You don't have to, but it's a good convention.
Always glPush/PopMatrix() before modifying the matrix stack (e.g. when translating the circle).
glColor3f(1.0f, 0.0f, 0.0f); // Blue? ;)
Related
I have a 2D transformation problem in OpenGL. My program draws two letters on screen and, by pressing assigned keys, letters have to move up (GLUT_KEY_UP) down (GLUT_KEY_DOWN) left (GLUT_KEY_LEFT) right (GLUT_KEY_RIGHT) and rotate CW (GLUT_KEY_HOME) and CCW (GLUT_KEY_END). (On keys GLUT_KEY_PAGE_UP and GLUT_KEY_PAGE_DOWN both letters rotate around their own centers simultaniously in oposite directions, pressing e.g. GLUT_KEY_UP after GLUT_KEY_PAGE_UP moves both letters in a correct direction).
I can't make the letters do the correct movement (up, down, left or right) after the objects had been rotated with GLUT_KEY_HOME or GLUT_KEY_END:
case GLUT_KEY_HOME: //rotate clockwise around the center of the model
glMatrixMode(GL_MODELVIEW);
setRotationMatrix(-angle, modelSizeX, modelSizeY);
glMultMatrixf(rotationMatrix); // multiply current Modelview Matrix by rotate-and-translate matrix
display();
break;
Function that 'sets' the rotation matrix inserts angle and rotation point into Identity matrix [4x4]:
void setRotationMatrix(float theta, float x0, float y0)
{
theta = theta * (2 * acos(0.0)) / 180; // convert theta from degrees to radian
rotationMatrix[0] = cos(theta);
rotationMatrix[1] = sin(theta);
rotationMatrix[4] = -sin(theta);
rotationMatrix[5] = cos(theta);
rotationMatrix[12] = ((x0 * 0.5f) * (1 - cos(theta)) + (y0 * 0.5f) * sin(theta));
rotationMatrix[13] = ((y0 * 0.5f) * (1 - cos(theta)) - (x0 * 0.5f) * sin(theta));
}
After the objects have been rotated, if I press KEY_UP, they move not 'up' (in normal direction against x axis ) but in the direction normal to the horizontal plane of the object after rotation (slightly sideways).
case GLUT_KEY_UP:
glMatrixMode(GL_MODELVIEW);
glTranslated(0, delta, 0);
display();
break;
how do I make it move straightly to the 'north', meaning, not the 'north' of the object but the 'north' of my coordinate system?
#include <Windows.h>
#include <GL/glut.h>
#include <vector>
#include <fstream>
#include <cmath>
using namespace std;
#define EscKey 27
#define PlusKey 43
#define MinusKey 45
struct Point
{
int x, y;
};
double pi = 2 * acos(0.0);
void reshape(int w, int h);
void display();
void drawInitials();
void processNormalKeys(unsigned char key, int x, int y);
void processSpecialKeys(int key, int x, int y);
void setRotationMatrix(float theta, float x0, float y0);
void readFromFile();
void lineto(Point p);
void moveto(Point p);
void drawM();
void drawJ();
vector <Point> point;
vector <int> code;
Point currentPoint;
int modelSizeX = 202; int modelSizeY = 89;
int letterMSizeX = 107; int letterJSizeX = 78;
int delta = 5; // movement size
float zoomRate = 0.1; // scale-and-translate rate: 0.1 = resize by 10%
float angle = 1, rotaterR = 1 * pi / 180, rotater, angleCount = 0.0; // saved rotation angle
GLfloat modelviewStateMatrix[16];
int windowSizeX, windowSizeY;
boolean separate = false;
float rotationMatrix[16] = { 1.0f, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f };
float plusKeyMatrix[16] = { 1.0f + zoomRate, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f + zoomRate, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
-(modelSizeX * zoomRate * 0.5f), -(modelSizeY * zoomRate * 0.5f), 0.0f, 1.0f };
float minusKeyMatrix[16] = { 1.0f - zoomRate, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f - zoomRate, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
modelSizeX * zoomRate * 0.5f, modelSizeY * zoomRate * 0.5f, 0.0f, 1.0f };
void readFromFile()
{
fstream f("initials_points_2.txt", ios::in);
int pointNumber;
Point p;
f >> pointNumber;
for (int i = 0; i < pointNumber;i++)
{
f >> p.x >> p.y;
point.push_back(p);
}
int movesNumber, m;
f >> movesNumber;
for (int i = 0; i < movesNumber; i++)
{
f >> m; code.push_back(m);
}
f.close();
}
void moveto(Point p)
{
currentPoint.x = p.x; currentPoint.y = p.y;
}
void lineto(Point p)
{
glBegin(GL_LINES);
glVertex2i(currentPoint.x, currentPoint.y);
glVertex2i(p.x, p.y);
glEnd();
currentPoint.x = p.x; currentPoint.y = p.y;
}
void setRotationMatrix(float theta, float x0, float y0)
{
theta = theta * (2 * acos(0.0)) / 180; // convert theta from degrees to radian
rotationMatrix[0] = cos(theta);
rotationMatrix[1] = sin(theta);
rotationMatrix[4] = -sin(theta);
rotationMatrix[5] = cos(theta);
rotationMatrix[12] = ((x0 * 0.5f) * (1 - cos(theta)) + (y0 * 0.5f) * sin(theta));
rotationMatrix[13] = ((y0 * 0.5f) * (1 - cos(theta)) - (x0 * 0.5f) * sin(theta));
}
void drawM()
{
int i = 1;
moveto(point[0]);
while (code[i] > 0 && i < code.size())
{
lineto(point[code[i] - 1]);
i++;
}
glBegin(GL_LINES);
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(letterMSizeX, 0.0, 0.0);
glVertex3f(letterMSizeX, 0.0, 0.0);
glVertex3f(letterMSizeX, modelSizeY, 0.0);
glVertex3f(letterMSizeX, modelSizeY, 0.0);
glVertex3f(0.0, modelSizeY, 0.0);
glVertex3f(0.0, modelSizeY, 0.0);
glVertex3f(0.0, 0.0, 0.0);
glEnd();
glColor3f(0.0, 1.0, 0.0);
glBegin(GL_LINES);
glVertex2i(0, 0); glVertex2i(letterMSizeX, modelSizeY);
glVertex2i(letterMSizeX, 0); glVertex2i(0, modelSizeY);
glEnd();
}
void drawJ()
{
glColor3f(1.0, 0.0, 0.0);
int i = 14;
moveto(point[-1 * (code[i]) - 1]);
i++;
while (i < code.size())
{
lineto(point[code[i] - 1]);
i++;
}
glBegin(GL_LINES);
glVertex3f((modelSizeX - letterJSizeX), 0.0, 0.0);
glVertex3f((modelSizeX - letterJSizeX), modelSizeY, 0.0);
glVertex3f((modelSizeX - letterJSizeX), modelSizeY, 0.0);
glVertex3f(modelSizeX, modelSizeY, 0.0);
glVertex3f(modelSizeX, modelSizeY, 0.0);
glVertex3f(modelSizeX, 0.0, 0.0);
glVertex3f(modelSizeX, 0.0, 0.0);
glVertex3f((modelSizeX - letterJSizeX), 0.0, 0.0);
glEnd();
glColor3f(0.0, 1.0, 0.0);
glBegin(GL_LINES);
glVertex2i(letterMSizeX + 17, 0); glVertex2i(modelSizeX, modelSizeY);
glVertex2i(letterMSizeX + 17, modelSizeY); glVertex2i(modelSizeX, 0);
glEnd();
}
void drawInitials()
{
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
setRotationMatrix(-rotater, letterMSizeX, modelSizeY);
glMultMatrixf(rotationMatrix); // multiply current Modelview Matrix by rotate-and-translate matrix
drawM();
glTranslatef(-letterMSizeX * 0.5, -modelSizeY * 0.5, 0);
glPopMatrix();
glPushMatrix();
glTranslatef((modelSizeX - letterJSizeX), 0, 0);
setRotationMatrix(rotater, letterJSizeX, modelSizeY);
glMultMatrixf(rotationMatrix); // multiply current Modelview Matrix by rotate-and-translate matrix
glTranslatef(-(modelSizeX - letterJSizeX), 0, 0);
drawJ();
glPopMatrix();
}
void processNormalKeys(unsigned char key, int x, int y)
{
switch (key)
{
case EscKey:
exit(0);
break;
case PlusKey: // "zoom in"
glMatrixMode(GL_MODELVIEW);
glMultMatrixf(plusKeyMatrix); // multiply current Modelview Matrix by scale-and-translate matrix
display();
break;
case MinusKey: // "zoom out"
glMatrixMode(GL_MODELVIEW);
glMultMatrixf(minusKeyMatrix); // multiply current Modelview Matrix by scale-and-translate matrix
display();
break;
}
}
void processSpecialKeys(int key, int x, int y) {
switch (key) {
case GLUT_KEY_UP:
glMatrixMode(GL_MODELVIEW);
glTranslated(0, delta, 0);
display();
break;
case GLUT_KEY_DOWN:
glMatrixMode(GL_MODELVIEW);
glTranslated(0, -delta, 0);
display();
break;
case GLUT_KEY_LEFT:
glMatrixMode(GL_MODELVIEW);
glTranslated(-delta, 0, 0);
display();
break;
case GLUT_KEY_RIGHT:
glMatrixMode(GL_MODELVIEW);
glTranslated(delta, 0, 0);
display();
break;
case GLUT_KEY_HOME: //rotate clockwise around the center of the model
glMatrixMode(GL_MODELVIEW);
setRotationMatrix(-angle, modelSizeX, modelSizeY);
glMultMatrixf(rotationMatrix); // multiply current Modelview Matrix by rotate-and-translate matrix
display();
break;
case GLUT_KEY_END: //rotate counterclockwise around the center of the model
glMatrixMode(GL_MODELVIEW);
setRotationMatrix(angle, modelSizeX, modelSizeY);
glMultMatrixf(rotationMatrix); // multiply current Modelview Matrix by rotate-and-translate matrix
display();
break;
case GLUT_KEY_PAGE_UP:
rotater -= rotaterR;
if (rotater <= -2 * pi)
rotater += 2 * pi;
display();
break;
case GLUT_KEY_PAGE_DOWN:
rotater += rotaterR;
if (rotater >= 2 * pi)
rotater -= 2 * pi;
display();
break;
}
}
int main(int argc, char* argv[])
{
currentPoint.x = 0; currentPoint.y = 0;
readFromFile();
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(800, 600);
glutInitWindowPosition(100, 150);
glutCreateWindow("OpenGL lab");
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutKeyboardFunc(processNormalKeys);
glutSpecialFunc(processSpecialKeys);
glutMainLoop();
return 0;
}
void reshape(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
windowSizeX = w;
windowSizeY = h;
gluOrtho2D(-modelSizeX, modelSizeX * 2, -modelSizeY, modelSizeY * 2); // World size
}
void display()
{
glClearColor(1, 1, 1, 0);
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glColor3f(0.0, 0.0, 1.0);
glBegin(GL_LINES);
glVertex2i(-windowSizeX, 0); glVertex2i(windowSizeX, 0);
glVertex2i(0, -windowSizeY); glVertex2i(0, windowSizeY);
glEnd();
glPopMatrix();
glColor3d(1, 0, 0);
drawInitials();
glPointSize(5);
glBegin(GL_POINTS);
glVertex3f(modelSizeX * 0.5, modelSizeY * 0.5, 0.0);
glVertex3f(letterMSizeX * 0.5, modelSizeY * 0.5, 0.0);
glVertex3f(letterJSizeX * 0.5 + letterMSizeX + 17, modelSizeY * 0.5, 0.0);
glEnd();
glFlush();
}
vertices file: initials_points_2.txt
I was trying to:
encapsulate _HOME/_END rotation with glPushMatrix()/glPopMatrix()
revert the rotation after the drawal of the object by multiplying MODELVIEW matrix with (-angle, same point)
was trying to drop glMultMatrix() and use glTranslate(), glRotate()
none of them had worked as I intended
Consider the following steps:
At first, rotate the object on the object coordinate system.
Next, place the object into the space (coordinate system) that you are considering the directions {up, down, left, and right} in.
i.e. for first rotation, the center must be the value in the object coordinate system. For example, object coordinate system is often defined as the origin equals to the center of object. In this case, rotation center is (0,0,0).
glPushMatrix();
//2nd step : Place the object
glTranslatef( ... );
//1st step : rotate the object
glRotatef( ... );
//object draw code
//(all vertex value is in the object coordinate system)
glPopMatrix();
I found out what I was doing wrong: buttons GLUT_KEY_HOME/GLUT_KEY_END should be performing rotations similar to those of GLUT_KEY_PAGE_UP/GLUT_KEY_PAGE_DOWN:
increase current rotation angle for the whole model (new variable to save rotation angle around the middle of the model);
call display method();
Then, inside display() method:
push current matrix into stack;
rotate model by the angle;
another push matrix into stack
rotate letters by the rotater variable changed in PAGE_UP/PAGE_DOWN
draw letters
pop matrix
pop matrix;
Code on keys:
case GLUT_KEY_HOME: //rotate clockwise around the center of the model
glMatrixMode(GL_MODELVIEW);
angle -= rotationRate;
if (angle <= -2 * pi)
angle += 2 * pi;
display();
break;
case GLUT_KEY_END: //rotate counterclockwise around the center of the model
glMatrixMode(GL_MODELVIEW);
angle += rotationRate;
if (angle >= 2 * pi)
angle -= 2 * pi;
display();
break;
edited drawInitials() method (called from display() method):
void drawInitials()
{
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
setRotationMatrix(angle, modelSizeX, modelSizeY); //set rotation matrix to rotate around the center of the model by current angle
glMultMatrixf(rotationMatrix); // multiply current Modelview Matrix by rotate-and-translate matrix
glPushMatrix();
setRotationMatrix(-rotater, letterMSizeX, modelSizeY); //set to rotate around the center of the letter M by current rotater Clockwise
glMultMatrixf(rotationMatrix); // multiply current Modelview Matrix by rotate-and-translate matrix
drawM();
glPopMatrix();
glPushMatrix();
glTranslatef((modelSizeX - letterJSizeX), 0, 0); // move OX axis by the size of letter M + space between the letters
setRotationMatrix(rotater, letterJSizeX, modelSizeY);//set to rotate around the center of the letter J by current rotater Counter Clockwise
glMultMatrixf(rotationMatrix); // multiply current Modelview Matrix by rotate-and-translate matrix
glTranslatef(-(modelSizeX - letterJSizeX), 0, 0); // return OX axis to its previous place
drawJ();
glPopMatrix();
glPopMatrix();
}
In setRotationMatrix() remove conversion into radian;
Add new variable rotationRate to use it as an incriment for both rotations:
float angle;
// saved rotation angle around center of the model (radian)
float rotater;
// rotater - saved rotation angle around center of the letter (radian)
float rotationRate = 1 * pi / 180; // rotation rate (radian), ex rotaterR
I would like to be able to click on a point on the surface of a sphere in OpenGL. Here's what I have so far:
#include <iostream>
#include <stdlib.h>
#include "GL/freeglut.h"
#include "glm/glm.hpp"
#include "quaternion.h"
const GLsizei WINDOW_WIDTH = 640;
const GLsizei WINDOW_HEIGHT = 640;
int mouse_x = 0;
int mouse_y = 0;
float zoom = 1.0f;
float zoom_sensitivity = 0.1f;
const float zoom_max = 1.5f;
const float zoom_min = 0.1f;
bool clicked = false;
glm::vec3 pointClick;
glm::vec3 GetOGLPos(int x, int y);
void display(void) {
// Clear display port
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
// Reset camera
gluLookAt(
0.0, 0.0, 2.0,
0.0, 0.0, 0.0,
0.0, 1.0, 0.0
);
// Zoom
glScalef(zoom, zoom, zoom);
// Render sphere
glPushMatrix();
glTranslatef(0, 0, 0);
glColor3f(1, 0, 0);
glutSolidSphere(1, 64, 64);
glPopMatrix();
// Render point
if (clicked == true) {
glPushMatrix();
glColor3f(0, 1, 0);
glPointSize(0.5f);
glBegin(GL_POINTS);
glVertex3f(pointClick.x, pointClick.y, pointClick.z);
printf("%f, %f, %f\n", pointClick.x, pointClick.y, pointClick.z);
glEnd();
glPopMatrix();
}
// Swap buffers
glutSwapBuffers();
}
void reshape(GLsizei width, GLsizei height) {
if (height == 0) {
height = 1;
}
float ratio = 1.0 * width / height;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glViewport(0, 0, width, height);
gluPerspective(45, ratio, 1, 100);
glMatrixMode(GL_MODELVIEW);
}
// Handles mouse input for camera rotation.
void motion(int x, int y) {
pointClick = GetOGLPos(x, y);
clicked = true;
glutPostRedisplay();
}
// Handles scroll input for zoom.
void mouseWheel(int button, int state, int x, int y) {
if (state == 1) {
zoom = zoom + zoom_sensitivity >= zoom_max ? zoom_max : zoom + zoom_sensitivity;
}
else if (state == -1) {
zoom = zoom - zoom_sensitivity <= zoom_min ? zoom_min : zoom - zoom_sensitivity;
}
glutPostRedisplay();
}
int main(int argc, char** argv) {
// Initialize glut.
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DOUBLE);
glutInitWindowPosition(
(glutGet(GLUT_SCREEN_WIDTH) - WINDOW_WIDTH) / 2,
(glutGet(GLUT_SCREEN_HEIGHT) - WINDOW_HEIGHT) / 2
);
glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);
glutCreateWindow("Window");
// Register callbacks.
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMotionFunc(motion);
glutMouseWheelFunc(mouseWheel);
// Start glut.
glutMainLoop();
return 0;
}
// Get position of click in 3-d space
glm::vec3 GetOGLPos(int x, int y)
{
GLint viewport[4];
GLdouble modelview[16];
GLdouble projection[16];
GLfloat winX, winY, winZ;
GLdouble posX, posY, posZ;
glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
glGetDoublev(GL_PROJECTION_MATRIX, projection);
glGetIntegerv(GL_VIEWPORT, viewport);
winX = (float)x;
winY = (float)viewport[3] - (float)y;
glReadPixels(x, int(winY), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ);
gluUnProject(winX, winY, winZ, modelview, projection, viewport, &posX, &posY, &posZ);
return glm::vec3(posX, posY, posZ);
}
This is the visual output:
This renders a point on the screen, but it's not "on" the sphere. I'm wondering how to put the point on the surface of the sphere so, if I were to rotate and zoom the camera, the point would stay in the same place. How do I "project" the point on the surface of the sphere?
You first want to convert the cursor to a ray in the world, and then perform a ray-sphere intersection test to figure out where the ray intersects the sphere. You can read this article regarding how to convert the cursor to a ray in the world: http://antongerdelan.net/opengl/raycasting.html.
In OpenGL's fixed pipeline, by default, specifying vertex coordinates using glVertex3f is equivalent to specifying a location between -1.0 and +1.0 in screen space. Therefore, given a set of 4 perfectly adjacent screen-space vertices using GL_TRIANGLE_STRIP (or even GL_QUADS), and unless your window is already perfectly square, you will always render a rectangle instead of a perfect square...
Knowing the width, height and aspect ratio of a window, is there some way to correct this?
I have tried multiplying the vertex coordinates by the aspect ratio, which unfortunately seemed to achieve the same visual effect.
Here's the full source code I'm currently using:
#include "main.h"
#pragma comment(lib, "glut32.lib")
int g_width = 800;
int g_height = 600;
int g_aspectRatio = double(g_width) / double(g_height);
bool g_bInitialized = false;
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
glutInitWindowPosition(0, 0);
glutInitWindowSize(g_width, g_height);
glutCreateWindow("OpenGL Test App");
glutDisplayFunc(onRender);
glutReshapeFunc(onSize);
glutIdleFunc(onRender);
glutMainLoop();
return 0;
}
void onInit()
{
glFrontFace(GL_CW);
}
void onRender()
{
if(!g_bInitialized)
onInit();
static float angle = 0.0f;
const float p = 0.5f * g_aspectRatio;
glLoadIdentity();
gluLookAt(
0.0f, 0.0f, 10.0f,
0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f
);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glScalef(1, -1, 1); // Flip the Y-axis
glRotatef(angle, 0.0f, 1.0f, 0.0f);
glBegin(GL_TRIANGLE_STRIP);
{
glColor4f(1.0, 0.0, 0.0, 1.0); // Red
glVertex3f(-p, -p, 0.0); // Top-Left
glColor4f(0.0, 1.0, 0.0, 1.0); // Green
glVertex3f(p, -p, 0.0); // Top-Right
glColor4f(0.0, 0.0, 1.0, 1.0); // Blue
glVertex3f(-p, p, 0.0); // Bottom-Left
glColor4f(1.0, 1.0, 0.0, 1.0); // Yellow
glVertex3f(p, p, 0.0); // Bottom-Left
}
glEnd();
angle += 0.6f;
glutSwapBuffers();
}
void onSize(int w, int h)
{
g_width = max(w, 1);
g_height = max(h, 1);
g_aspectRatio = double(g_width) / double(g_height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glViewport(0, 0, w, h);
gluPerspective(45, g_aspectRatio, 1, 1000);
glMatrixMode(GL_MODELVIEW);
}
EDIT:
This has been solved... In the above code, I had defined g_aspectRatio as an int instead of a floating-point value. Therefore, it's value was always 1...
In my (old) experience, that's just why you have an aspect ratio argument to gluPerspective().
The manual page says:
In general, the aspect ratio in gluPerspective should match
the aspect ratio of the associated viewport. For example, aspect = 2.0
means the viewer's angle of view is twice as wide in x as it is in y.
If the viewport is twice as wide as it is tall, it displays the image
without distortion.
Check your g_aspectRatio value.
by default, specifying vertex coordinates using glVertex3f is equivalent to specifying a location between -1.0 and +1.0 in screen space
Wrong. Coordinates passed to OpenGL through glVertex or a glVertexPointer vertex array are in model space. The transformation to screen space happens by transforming into view space by the modelview matrix and from view space to clip space by the projection matrix. Then clipping is applied and the perspective divide applied to reach normalized coordinate space.
Hence the value range for glVertex can be whatever you like it to be. By applying the right projection matrix you get your view space to be in [-aspect; aspect]×[-1, 1] if you like that.
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-aspect, aspect, -1, 1, -1, 1);
I have this little program that is supposed to rotate a square in 2D. When I give it fixed vertexes, it works fine. But when I try to put it in motion, the square just starts to flash and blink and not really resemble a square at all. Everything looks good to me, so I must be missing something. Can anyone see it?
#include <stdio.h>
#include <math.h>
#include <glut/glut.h>
#define DEG_TO_RAD 0.017453
GLsizei ww, wh;
GLfloat theta;
void display()
{
//clear window
glClear(GL_COLOR_BUFFER_BIT);
//draw unit square polygon
glBegin(GL_POLYGON);
glVertex2f(sin(DEG_TO_RAD*theta), cos(DEG_TO_RAD*theta));
glVertex2f(-sin(DEG_TO_RAD*theta), cos(DEG_TO_RAD*theta));
glVertex2f(-sin(DEG_TO_RAD*theta), -cos(DEG_TO_RAD*theta));
glVertex2f(sin(DEG_TO_RAD*theta), -cos(DEG_TO_RAD*theta));
// glVertex2f(-0.5, -0.5);
// glVertex2f(-0.5, 0.5);
// glVertex2f(0.5, 0.5);
// glVertex2f(0.5, -0.5);
glEnd();
//flush gl buffers
glFlush();
}
void init() {
//set color to black
glClearColor(0.0, 0.0, 0.0, 0.0);
//set fill color to white
glColor3f(1.0, 1.0, 1.0);
//set up standard orthogonal view with clipping
//box as cube of side2 centered at origin
//this is default view and these statements could be removed
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-1.0, 1.0, -1.0, 1.0);
}
void myreshape(GLsizei w, GLsizei h) {
//adjust clipping window
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if (w<=h)
gluOrtho2D(-2.0, 2.0, -2.0 * (GLfloat) h / (GLfloat) w, 2.0 * (GLfloat) h / (GLfloat) w);
else
gluOrtho2D(-2.0 * (GLfloat) w / (GLfloat) h, 2.0 * (GLfloat) w / (GLfloat) h, -2.0, 2.0);
glMatrixMode(GL_MODELVIEW);
//adjust viewport
glViewport(0, 0, w, h);
//set global size for use by drawing routine
ww = w;
wh = h;
}
void myidle() {
theta += 2.0;
if (theta > 360.0) theta -= 360.0;
glutPostRedisplay();
}
int main(int argc, char** argv)
{
theta = 0.0;
// initialize mode and open a window in upper-left corner of screen
// window title is name of program (arg[0])
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(500, 500);//Set the window size
glutInitWindowPosition(0, 0);
glutCreateWindow("rotating square");
glutDisplayFunc(display);
init();
glutReshapeFunc(myreshape);
glutIdleFunc(myidle);
glutMainLoop();
return 0;
}
Your vertex definitions just don't produce a square. Try the following:
glVertex2f(cos(DEG_TO_RAD*(theta + 135)), sin(DEG_TO_RAD*(theta + 135)));
glVertex2f(cos(DEG_TO_RAD*(theta + 45 )), sin(DEG_TO_RAD*(theta + 45 )));
glVertex2f(cos(DEG_TO_RAD*(theta - 45 )), sin(DEG_TO_RAD*(theta - 45 )));
glVertex2f(cos(DEG_TO_RAD*(theta - 135)), sin(DEG_TO_RAD*(theta - 135)));
The comment from Andon below your question is right. You should create the geometry (the vertices) only once and then rotate them by setting the matrix to ModelView and rotate with glRotatef(...). Recreating geometries on each render cycle is a wrong aproach.
While pressing the down key, I expect the teapot to be drawn away as farther, yet it remains the same size. Why?
Note: this is a homework thing, I'm not allowed to use glTranslate.
#include <stdlib.h>
#include <stdio.h>
#include <GL/glut.h>
#include <GL/gl.h>
void display(void);
class Camera {
public: float eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ;
float aimX, aimY, aimZ;
Camera () {
eyeX = 0.0f ;
eyeY = 0.0f;
eyeZ = 0.5f ;
centerX = 0.0f;
centerY = 0.0f;
centerZ = 0.0f;
upX = 0.0f;
upY = 1.0f;
upZ = 0.0f;
}
void move_camera(double speed) {
aimX = centerX - eyeX;
aimY = centerY - eyeY;
aimZ = centerZ - eyeZ;
eyeX += aimX * speed;
eyeY += aimY * speed;
eyeZ += aimZ * speed;
centerX += aimX *speed;
centerY += aimY *speed;
centerZ += aimZ *speed;
}
};
Camera camera;
void init(void){
glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void specialKeys(int key, int x, int y){
if (key==GLUT_KEY_UP){
camera.move_camera(0.03f);
display();
}
if (key==GLUT_KEY_DOWN){
camera.move_camera(-0.03f);
display();
}
}
void reshape(int w, int h){
glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f, (float)w/(float)h, 0.0f, 200.0f); // fov, aspect ratio, ncp, fcp
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
//gluLookAt(camera.eyeX, camera.eyeY, camera.eyeZ, // eye
// camera.centerX, camera.centerY, camera.centerZ, // center
// camera.upX, camera.upY, camera.upZ // up
//
//);
}
void display(void){
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(camera.eyeX, camera.eyeY, camera.eyeZ, // eye
camera.centerX, camera.centerY, camera.centerZ, // center
camera.upX, camera.upY, camera.upZ // up
);
//glTranslatef(0.0,0.0,1.0f);
glutWireTeapot(0.5f);
glutSwapBuffers();
glFlush();
}
int main (int argc, char *argv[]){
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
//glutCreateWindow(argv[0]);
glutInitWindowPosition(500,200);
glutInitWindowSize(800,600);
glutCreateWindow("fgh");
init();
glutDisplayFunc(display);
glutSpecialFunc(specialKeys);
glutIdleFunc(display);
glutMainLoop();
return 0;
}
Your projection matrix is damaged.
gluPerspective(45.0f, (float)w/(float)h, 0.0f, 200.0f); // fov, aspect ratio, ncp, fcp
The third argument is the distance of the near clipping plane. It cannot be equal to 0 as that would imply that you need an inifinite-precision depth buffer. Make it 0.1 or 0.01.
I was missing the call to glutReshapeFunc(reshape);. That's it.