// OpenGL_DrawingLine.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <GL/glut.h>
int psize = 1; //Menentukan besar pixel
int icoord = 0; //Menentukan apakah titik awal icoord = 0 atau titik akhir icoord = 1
int wh = 400; //Tinggi layar window
int ww = 400; //Lebar layar window
struct Line
{
int x[2]; //Titik x1 dan x2
int y[2]; //Titik y1 dan y2
}line;
void renderScene()
{
glClear(GL_COLOR_BUFFER_BIT);
glFlush();
}
void myMouseClick(int button, int state, int x, int y)
{
glColor3f(1.0,1.0,1.0);
if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)//jika mouse klik kiri
{
line.x[icoord] = x/psize;//tentukan x1 dan x2 untuk garis
line.y[icoord] = (wh-y)/psize;//tentukan y1 dan y2 untuk garis
if (icoord == 0)//titik awal
{
icoord++;
}
else
{
glBegin(GL_LINES);//hubungkan titik awal dan titik akhir
glVertex2i(line.x[0],line.y[0]);
glVertex2i(line.x[1],line.y[1]);
glEnd();
glFlush();
icoord = 0; //set index untuk x dan y menjadi 0 lagi
}
}
}
void reshape(int neww, int newh)
{
ww = neww;
wh = newh;
glViewport(0,0,ww,wh);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.,(GLdouble)ww/psize,0.,(GLdouble)wh/psize); /* ensure aspect ratio */
//glutOrtho2D(left,right,bottom,top)
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void myMotion(int x,int y)
{
//catch mouse position and draw line while mouse left button is click and hold (drag)
line.x[icoord] = x/psize;
line.y[icoord] = (wh-y)/psize;
if (icoord == 0)//titik awal
{
icoord++;
}
else
{
glBegin(GL_LINES);
glVertex2i(line.x[0],line.y[0]);
glVertex2i(line.x[1],line.y[1]);
glEnd();
glFlush();
icoord = 0;
}
}
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(400, 400);
glutCreateWindow("Drawing Line");
glutDisplayFunc(renderScene);
glutMouseFunc(myMouseClick);
glutMotionFunc(myMotion);
glutReshapeFunc(reshape);
glutMainLoop();
return 0;
}