Selasa, 04 Desember 2012

Cara Membuat 2 Garis dengan Titik Potong



#include <windows.h>
#include <gl/GL.h>
#include <gl/glut.h>
#include <stdio.h>

// pendefinisian variabel
int g=0,j=0,a,b,c,d,e,f,;
static float m1,c1,x;
static float m2,c2,y;

static float ax,cx;
static float ay,cy;
static float bx,dx;
static float by,dy;

void drawLine(int x,int y);
void myInit(void)
{
glClearColor(1.0,1.0,1.0,0.0);
glColor3f(0.0, 0.0, 0.0);
glPointSize(8.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 640.0, 0.0, 480.0);
}

void grad()
{
//mencetak gradien warna background
glBegin(GL_QUADS);
glColor3f(1.0, 1.0, 0.0);
glVertex2i(0, 0);
glColor3f(0.0, 1.0, 1.0);
glVertex2i(640, 0);
glColor3f(0.0, 1.0, 0.0);
glVertex2i(640, 480);
glColor3f(1.0, 0.0, 0.0);
glVertex2i(0, 480);
glEnd();
}
//rumus
void potong()
{
glColor3f(0,0,0);
glBegin(GL_LINES);
glVertex2f(ax,ay);
glVertex2f(bx,by);
glVertex2f(cx,cy);
glVertex2f(dx,dy);
glEnd();
glutSwapBuffers();
   //persamaan 1
m1=((by-ay)/(bx-ax));
c1=ay-(m1*ax);
    ////persamaan 2
m2=((dy-cy)/(dx-cx));
c2=cy-(m2*cx);
  //rumus utama
x=((c2-c1)/(m1-m2));
y=(m1*x)+c1;
a=x;
b=y;

glBegin(GL_POINTS);
glColor3f(1.0, 1.0, 0.0);
glVertex2i(a,b);
glEnd();
glutSwapBuffers();

}

void drawDot()
{
glBegin(GL_POINTS);
glColor3f(1.0, .0, 0.0);
glVertex2i(a, b);
glEnd();
glutSwapBuffers();
}
void drawLine(int x,int y)
{
grad();
if(g==1) {

ax=x;
ay=480-y;
bx=c;
by=d;
glClear(GL_COLOR_BUFFER_BIT);
grad();
glBegin(GL_LINE_STRIP);
glColor3f(0.0, 0.0, 0.0);
glVertex2i(c, d);
glVertex2i(x, 480-y);
glEnd();
glutSwapBuffers();
}

if(g>=2) {
dx=x;
dy=480-y;
cx=d;
cy=e;
potong();
drawDot();   
glBegin(GL_LINE_STRIP);
glColor3f(0.0, 1.0, 0.0);
glVertex2i(d, e);
glVertex2i(x, 480-y);
glEnd();
glFlush();
}
}

void mouse(int button, int state, int x, int y)
{
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
{
grad();
d=x;
e=480-y;
g+=1;
if(g==1)
{
c=x;
d=480-y;
}
if(g==2) {
g=0;
}
}
if (button == GLUT_LEFT_BUTTON && state == GLUT_UP)
{
g+=1;
grad();
}
else if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN)
exit(-1);
}

void myDisplay(void)
{
glClear(GL_COLOR_BUFFER_BIT);
grad();
glutSwapBuffers();
}

main(int argc, char**argv)
{
glutInit(&argc,argv);// inisialisasi toolkit
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);// set modus display
glutInitWindowSize(640,480);// set ukuran window
glutInitWindowPosition(100,150);// set posisi window di layar
glutCreateWindow("titikpotong_672011094");// buka screen window
glutDisplayFunc(myDisplay);// registrasi fungsi menggambar
glutMotionFunc(drawLine);//memanggil fungsi garis
glutMouseFunc(mouse);//memanggil fungsi mouse

myInit();
glutMainLoop();// berulang terus-menerus
}



silahkan download projectnya disini


Tidak ada komentar:

Posting Komentar