i want to draw a polygon in openGL Glut with mouse interaction, every left click that will be made will be a vertex and a line will be drawn between every vertex. when the right mouse will be clicked the polygon will close drawing a line from the last to the first vertex. I have come up with this but it doesnt seem to work.
void draw_polygon(int button, int state, int x, int y) {
bool right_pushed = 0;
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_POINTS);
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) {
p1.x = x;
p1.y = 480 - y;
//if right is clicked draw a line to here
first.x = x;
first.y = 480 - y;
}
while (right_pushed == false) {
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) {
p2.x = x;
p2.y = 480 - y;
}
GLfloat dx = p2.x - p1.x;
GLfloat dy = p2.y - p1.y;
GLfloat x1 = p1.x;
GLfloat y1 = p1.y;
GLfloat step = 0;
if (abs(dx) > abs(dy)) {
step = abs(dx);
}
else {
step = abs(dy);
}
GLfloat xInc = dx / step;
GLfloat yInc = dy / step;
for (float i = 1; i <= step; i++) {
glVertex2i(x1, y1);
x1 += xInc;
y1 += yInc;
}
p1.x = p2.x;
p1.y = 480 - y;
if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) {
right_pushed = 1;
p2.x = first.x;
p2.y = first.y;
dx = p2.x - p1.x;
dy = p2.y - p1.y;
x1 = p1.x;
y1 = p1.y;
step = 0;
if (abs(dx) > abs(dy)) {
step = abs(dx);
}
else {
step = abs(dy);
}
xInc = dx / step;
yInc = dy / step;
for (float i = 1; i <= step; i++) {
glVertex2i(x1, y1);
x1 += xInc;
y1 += yInc;
}
}
}
glEnd();
glFlush();
}
int main(int argc, char **argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowPosition(200, 200);
glutInitWindowSize(640, 480);
glutCreateWindow("windows");
glutDisplayFunc(display);
glutMouseFunc(draw_polygon);//
init();
glutMainLoop();
return 0;
}
i am also trying to find out how to add a functionallity that when i select from a menu i could go from creating this polygon to editing it in a way that i could select a vertex , move it arround, and the shape changes accordingly.
glBegin / glEnd / glVertex ...
. – Jedthus